impeccable 3.2.0 → 3.3.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.
@@ -123,6 +123,7 @@ const ANTIPATTERNS = [
123
123
  {
124
124
  id: 'overused-font',
125
125
  category: 'slop',
126
+ scopes: ['type'],
126
127
  name: 'Overused font',
127
128
  description:
128
129
  'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
@@ -132,15 +133,17 @@ const ANTIPATTERNS = [
132
133
  {
133
134
  id: 'single-font',
134
135
  category: 'slop',
135
- name: 'Single font for everything',
136
+ scopes: ['type'],
137
+ name: 'Single font without hierarchy',
136
138
  description:
137
- 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
139
+ 'Only one font family is used for the entire page. A single family can work when weight and size contrast carry the hierarchy; otherwise pair a distinctive display font with a refined body font.',
138
140
  skillSection: 'Typography',
139
141
  skillGuideline: 'only one font family for the entire page',
140
142
  },
141
143
  {
142
144
  id: 'flat-type-hierarchy',
143
145
  category: 'slop',
146
+ scopes: ['type'],
144
147
  name: 'Flat type hierarchy',
145
148
  description:
146
149
  'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
@@ -177,6 +180,7 @@ const ANTIPATTERNS = [
177
180
  {
178
181
  id: 'nested-cards',
179
182
  category: 'slop',
183
+ scopes: ['layout'],
180
184
  name: 'Nested cards',
181
185
  description:
182
186
  'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
@@ -186,6 +190,7 @@ const ANTIPATTERNS = [
186
190
  {
187
191
  id: 'monotonous-spacing',
188
192
  category: 'slop',
193
+ scopes: ['layout'],
189
194
  name: 'Monotonous spacing',
190
195
  description:
191
196
  'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
@@ -201,18 +206,64 @@ const ANTIPATTERNS = [
201
206
  skillSection: 'Motion',
202
207
  skillGuideline: 'bounce or elastic easing',
203
208
  },
209
+ {
210
+ id: 'pulsing-dot',
211
+ category: 'slop',
212
+ name: 'Pulsing status dot',
213
+ description:
214
+ 'Small pulsing status dots simulate liveness decoratively. Reserve pulse animation for indicators tied to genuinely live, changing data; a static indicator with clear labeling is honest and calmer.',
215
+ skillSection: 'Motion',
216
+ skillGuideline: 'decorative pulsing status dot',
217
+ },
218
+ {
219
+ id: 'blinking-cursor',
220
+ category: 'slop',
221
+ severity: 'advisory',
222
+ name: 'Decorative blinking cursor',
223
+ description:
224
+ 'A blinking text cursor animated into a hero or landing section simulates typing where no input exists. It borrows the dev-tool aesthetic as decoration. Real editable fields draw their own caret; anywhere else, let the composition hold attention without a fake prompt.',
225
+ skillSection: 'Motion',
226
+ },
227
+ {
228
+ id: 'shape-assembled-illustration',
229
+ category: 'slop',
230
+ severity: 'advisory',
231
+ name: 'Shape-assembled illustration',
232
+ description:
233
+ 'A large inline SVG that builds a pictorial scene from a pile of primitive shapes reads as placeholder clip art, not illustration. Icons, logos, and data graphics are fine at their scale; a hero-sized visual deserves real artwork, a photograph, or a deliberately drawn graphic.',
234
+ skillSection: 'Imagery',
235
+ },
204
236
  {
205
237
  id: 'dark-glow',
206
238
  category: 'slop',
207
- name: 'Dark mode with glowing accents',
239
+ name: 'Glowing shadow accents',
240
+ description:
241
+ 'Colored glow shadows — a zero-offset chromatic halo (box- or text-shadow) on any background, or any colored blurred shadow on a dark background — are the default "cool" look of AI-generated UIs. Use neutral elevation shadows and subtle, purposeful lighting instead.',
242
+ skillSection: 'Color & Contrast',
243
+ skillGuideline: 'dark mode with glowing accents',
244
+ },
245
+ {
246
+ id: 'radial-halo',
247
+ category: 'slop',
248
+ name: 'Radial-gradient background halo',
208
249
  description:
209
- 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
250
+ 'A chromatic radial-gradient wash — saturated at the center, fading to transparent — used as a decorative background glow on a dark page. Same tell as glowing shadows, drawn with a gradient instead of a shadow. Ground the surface with a solid or subtly shifted background instead.',
210
251
  skillSection: 'Color & Contrast',
211
252
  skillGuideline: 'dark mode with glowing accents',
212
253
  },
254
+ {
255
+ id: 'marquee',
256
+ category: 'slop',
257
+ name: 'Auto-scrolling marquee',
258
+ description:
259
+ 'Continuously auto-scrolling content demands attention it has not earned and hides half its content at any moment. Reserve motion for content that changes; let readers move at their own pace.',
260
+ skillSection: 'Motion',
261
+ skillGuideline: 'auto-scrolling marquee',
262
+ },
213
263
  {
214
264
  id: 'icon-tile-stack',
215
265
  category: 'slop',
266
+ scopes: ['layout'],
216
267
  name: 'Icon tile stacked above heading',
217
268
  description:
218
269
  'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
@@ -222,6 +273,7 @@ const ANTIPATTERNS = [
222
273
  {
223
274
  id: 'italic-serif-display',
224
275
  category: 'slop',
276
+ scopes: ['type'],
225
277
  name: 'Italic serif display headline',
226
278
  description:
227
279
  'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
@@ -231,6 +283,7 @@ const ANTIPATTERNS = [
231
283
  {
232
284
  id: 'hero-eyebrow-chip',
233
285
  category: 'slop',
286
+ scopes: ['type'],
234
287
  name: 'Hero eyebrow / pill chip',
235
288
  description:
236
289
  'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
@@ -240,6 +293,7 @@ const ANTIPATTERNS = [
240
293
  {
241
294
  id: 'repeated-section-kickers',
242
295
  category: 'slop',
296
+ scopes: ['type'],
243
297
  severity: 'advisory',
244
298
  name: 'Repeated section kicker labels',
245
299
  description:
@@ -248,12 +302,13 @@ const ANTIPATTERNS = [
248
302
  skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
249
303
  },
250
304
  {
251
- id: 'numbered-section-markers',
305
+ id: 'numbered-section-labels',
252
306
  category: 'slop',
307
+ scopes: ['type'],
253
308
  severity: 'advisory',
254
- name: 'Numbered section markers (01 / 02 / 03)',
309
+ name: 'Tiny numbered section labels',
255
310
  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.',
311
+ 'Small numeric index labels riding next to section headings, repeated section after section, are AI editorial scaffolding — a page numbering its own chapters instead of earning structure. Let hierarchy, content, and rhythm carry the sequence.',
257
312
  skillSection: 'Layout & Space',
258
313
  skillGuideline: 'numbered section markers',
259
314
  },
@@ -287,6 +342,7 @@ const ANTIPATTERNS = [
287
342
  {
288
343
  id: 'oversized-h1',
289
344
  category: 'slop',
345
+ scopes: ['type'],
290
346
  name: 'Oversized hero headline',
291
347
  description:
292
348
  '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.',
@@ -296,6 +352,7 @@ const ANTIPATTERNS = [
296
352
  {
297
353
  id: 'extreme-negative-tracking',
298
354
  category: 'slop',
355
+ scopes: ['type'],
299
356
  name: 'Crushed letter spacing',
300
357
  description:
301
358
  'Letter-spacing pulled tighter than the point where characters keep their own shapes costs legibility. Tighten display type optically, not destructively.',
@@ -313,6 +370,49 @@ const ANTIPATTERNS = [
313
370
  },
314
371
 
315
372
  // ── Quality: general design and accessibility issues ──
373
+ {
374
+ id: 'script-error',
375
+ category: 'quality',
376
+ severity: 'error',
377
+ name: 'Uncaught script error on load',
378
+ description:
379
+ 'A script threw an uncaught exception or failed to parse while the page loaded. Broken JavaScript silently kills reveals, interactions, and dynamic content, and can leave most of a page invisible. Fix the error before judging anything else.',
380
+ },
381
+ {
382
+ id: 'content-hidden-at-rest',
383
+ category: 'quality',
384
+ severity: 'error',
385
+ scopes: ['layout'],
386
+ name: 'Content invisible at rest',
387
+ description:
388
+ 'A large share of the page text sits at opacity 0 or visibility hidden even after every reveal handler had a chance to run. This is the failed-reveal signature: the content shipped but never becomes visible. Make content visible by default and let JavaScript enhance its entrance instead of gating its existence.',
389
+ },
390
+ {
391
+ id: 'edge-flush-cards',
392
+ category: 'quality',
393
+ scopes: ['layout'],
394
+ name: 'Cards flush against the scroller edge',
395
+ description:
396
+ 'Cards inside a horizontal scroller or tab panel sit flush against the container edge at rest while keeping a gutter on the other side, so their edges and rounded corners get cut off. Usually the panel is sized wider than its clip box. Keep a consistent inset on both sides.',
397
+ },
398
+ {
399
+ id: 'text-occlusion',
400
+ category: 'quality',
401
+ scopes: ['layout'],
402
+ name: 'Text occluded by an overlapping element',
403
+ description:
404
+ 'Text is painted under an opaque element or a second text run, so part of it cannot be read. A decorative box, a stacked layer, or an inline element with leaked padding lands on the words instead of beside them. Give overlapping layers room, or move the text out from under the layer above it.',
405
+ skillSection: 'Layout & Space',
406
+ },
407
+ {
408
+ id: 'first-viewport-column-overflow',
409
+ category: 'quality',
410
+ scopes: ['layout'],
411
+ name: 'One column stretches the first viewport',
412
+ description:
413
+ 'A multi-column opening section lets one column run far past the fold while its sibling fits in a single viewport, so the short column floats in dead space and the fold falls deep inside one section. Balance the columns, cap the tall one, or let the long content flow below the opening row.',
414
+ skillSection: 'Layout & Space',
415
+ },
316
416
  {
317
417
  id: 'gray-on-color',
318
418
  category: 'quality',
@@ -341,6 +441,7 @@ const ANTIPATTERNS = [
341
441
  {
342
442
  id: 'line-length',
343
443
  category: 'quality',
444
+ scopes: ['type', 'layout'],
344
445
  name: 'Line length too long',
345
446
  description:
346
447
  'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
@@ -350,6 +451,7 @@ const ANTIPATTERNS = [
350
451
  {
351
452
  id: 'cramped-padding',
352
453
  category: 'quality',
454
+ scopes: ['layout'],
353
455
  name: 'Cramped padding',
354
456
  description:
355
457
  '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.',
@@ -359,6 +461,7 @@ const ANTIPATTERNS = [
359
461
  {
360
462
  id: 'body-text-viewport-edge',
361
463
  category: 'quality',
464
+ scopes: ['layout'],
362
465
  name: 'Body text touching viewport edge',
363
466
  description:
364
467
  'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
@@ -366,6 +469,7 @@ const ANTIPATTERNS = [
366
469
  {
367
470
  id: 'tight-leading',
368
471
  category: 'quality',
472
+ scopes: ['type'],
369
473
  name: 'Tight line height',
370
474
  description:
371
475
  'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
@@ -373,13 +477,24 @@ const ANTIPATTERNS = [
373
477
  {
374
478
  id: 'skipped-heading',
375
479
  category: 'quality',
480
+ scopes: ['type'],
376
481
  name: 'Skipped heading level',
377
482
  description:
378
483
  'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
379
484
  },
485
+ {
486
+ id: 'heading-rhythm',
487
+ category: 'quality',
488
+ scopes: ['layout', 'type'],
489
+ name: 'Heading crowded against the previous block',
490
+ description:
491
+ 'A heading binds to the content it introduces, so the rendered space above it should exceed the space below it. When headings across a page sit as close or closer to the block above than to their own content, every section reads as if it captions the previous one. Open up the space above each heading.',
492
+ skillSection: 'Layout & Space',
493
+ },
380
494
  {
381
495
  id: 'justified-text',
382
496
  category: 'quality',
497
+ scopes: ['type'],
383
498
  name: 'Justified text',
384
499
  description:
385
500
  'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
@@ -387,6 +502,7 @@ const ANTIPATTERNS = [
387
502
  {
388
503
  id: 'tiny-text',
389
504
  category: 'quality',
505
+ scopes: ['type'],
390
506
  name: 'Tiny body text',
391
507
  description:
392
508
  'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
@@ -394,6 +510,7 @@ const ANTIPATTERNS = [
394
510
  {
395
511
  id: 'all-caps-body',
396
512
  category: 'quality',
513
+ scopes: ['type'],
397
514
  name: 'All-caps body text',
398
515
  description:
399
516
  'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
@@ -403,6 +520,7 @@ const ANTIPATTERNS = [
403
520
  {
404
521
  id: 'wide-tracking',
405
522
  category: 'quality',
523
+ scopes: ['type'],
406
524
  name: 'Wide letter spacing on body text',
407
525
  description:
408
526
  'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
@@ -410,15 +528,24 @@ const ANTIPATTERNS = [
410
528
  {
411
529
  id: 'text-overflow',
412
530
  category: 'quality',
531
+ scopes: ['layout'],
413
532
  name: 'Content overflowing its container',
414
533
  description:
415
534
  '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
535
  skillSection: 'Layout & Space',
417
536
  skillGuideline: 'content wider than its container',
418
537
  },
538
+ {
539
+ id: 'repeated-container-text',
540
+ category: 'quality',
541
+ name: 'Same text repeated inside one container',
542
+ description:
543
+ 'The same literal text rendered three or more times in structurally different spots inside a single card or panel is redundant messaging — usually a status or label wired into every slot of a template. Say it once, in the slot where it matters most.',
544
+ },
419
545
  {
420
546
  id: 'clipped-overflow-container',
421
547
  category: 'quality',
548
+ scopes: ['layout'],
422
549
  name: 'Positioned child clipped by overflow container',
423
550
  description:
424
551
  '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.',
@@ -428,6 +555,7 @@ const ANTIPATTERNS = [
428
555
  {
429
556
  id: 'design-system-font',
430
557
  category: 'quality',
558
+ scopes: ['type'],
431
559
  name: 'Font outside DESIGN.md',
432
560
  description:
433
561
  'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
@@ -454,13 +582,23 @@ const ANTIPATTERNS = [
454
582
  skillSection: 'Visual Details',
455
583
  skillGuideline: 'border radius outside the project design system',
456
584
  },
585
+ {
586
+ id: 'design-system-font-size',
587
+ category: 'quality',
588
+ severity: 'advisory',
589
+ scopes: ['type'],
590
+ name: 'Font size outside DESIGN.md',
591
+ description:
592
+ 'A literal font-size is off the type ramp documented in DESIGN.md typography. Use a documented size step or update the design system if the new step is intentional.',
593
+ skillSection: 'Typography',
594
+ skillGuideline: 'font size outside the project design system',
595
+ },
457
596
 
458
- // ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
597
+ // ── Common generated-UI tells ───────────────────────────────────────────
459
598
  {
460
599
  id: 'gpt-thin-border-wide-shadow',
461
600
  category: 'slop',
462
601
  severity: 'advisory',
463
- gated: 'gpt',
464
602
  name: 'Hairline border with wide shadow',
465
603
  description:
466
604
  '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.',
@@ -471,7 +609,6 @@ const ANTIPATTERNS = [
471
609
  id: 'repeating-stripes-gradient',
472
610
  category: 'slop',
473
611
  severity: 'advisory',
474
- gated: 'gpt',
475
612
  name: 'Repeating-gradient stripes',
476
613
  description:
477
614
  'Repeating-gradient stripes used as surface decoration are a recurring generated-UI signature. Reach for a deliberate texture or leave the surface plain.',
@@ -482,10 +619,9 @@ const ANTIPATTERNS = [
482
619
  id: 'codex-grid-background',
483
620
  category: 'slop',
484
621
  severity: 'advisory',
485
- gated: 'gpt',
486
622
  name: 'Decorative grid-line background',
487
623
  description:
488
- 'A two-axis grid drawn with hairline linear-gradient layers ("1px, transparent 1px" on both axes) is a recurring generated-UI signature. Reserve grid overlays for actual canvas, map, blueprint, or measurement surfaces; elsewhere use product structure or a plain surface.',
624
+ 'A decorative grid or line-field background drawn with hairline linear-gradient layers tiled by a fixed pixel cell is a recurring generated-UI signature. Reserve grid overlays for actual canvas, map, blueprint, or measurement surfaces; elsewhere use product structure or a plain surface.',
489
625
  skillSection: 'Visual Details',
490
626
  skillGuideline: 'two-axis grid-line gradient background',
491
627
  },
@@ -493,7 +629,6 @@ const ANTIPATTERNS = [
493
629
  id: 'theater-slop-phrase',
494
630
  category: 'slop',
495
631
  severity: 'advisory',
496
- gated: 'gpt',
497
632
  name: 'Theater framing copy',
498
633
  description:
499
634
  'Dismissing something as "theater" is a recurring generated-copy tic. Say plainly what the thing does or does not do.',
@@ -504,7 +639,6 @@ const ANTIPATTERNS = [
504
639
  id: 'image-hover-transform',
505
640
  category: 'slop',
506
641
  severity: 'advisory',
507
- gated: 'gemini',
508
642
  name: 'Image hover transform',
509
643
  description:
510
644
  'Scaling or rotating an image on hover is a recurring generated-UI signature. Let imagery sit still, or use a subtler, purposeful interaction.',
@@ -628,13 +762,50 @@ function colorToHex(c) {
628
762
  return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
629
763
  }
630
764
 
765
+ // --- cli/engine/shared/fonts.mjs ---
766
+ const GOOGLE_FONTS_URL_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
767
+
768
+ function normalizeGoogleFontFamilyParam(value) {
769
+ return String(value || '')
770
+ .split('|')
771
+ .map(part => part.split(':')[0].trim().toLowerCase())
772
+ .filter(Boolean);
773
+ }
774
+
775
+ function extractGoogleFontFamilies(text) {
776
+ const families = [];
777
+ if (!text) return families;
778
+
779
+ GOOGLE_FONTS_URL_RE.lastIndex = 0;
780
+ let urlMatch;
781
+ while ((urlMatch = GOOGLE_FONTS_URL_RE.exec(text)) !== null) {
782
+ const url = urlMatch[0];
783
+ const queryStart = url.indexOf('?');
784
+ if (queryStart === -1) continue;
785
+
786
+ const params = new URLSearchParams(url.slice(queryStart + 1).replace(/&amp;/g, '&'));
787
+ for (const value of params.getAll('family')) {
788
+ families.push(...normalizeGoogleFontFamilyParam(value));
789
+ }
790
+ }
791
+
792
+ return families;
793
+ }
794
+
631
795
  // --- cli/engine/rules/checks.mjs ---
632
796
  const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
633
797
 
634
798
  // ─── Section 3: Pure Detection ──────────────────────────────────────────────
635
799
 
636
- function checkBorders(tag, widths, colors, radius) {
637
- if (BORDER_SAFE_TAGS.has(tag)) return [];
800
+ function checkBorders(tag, widths, colors, radius, opts = {}) {
801
+ // Badge-shaped <span>s (own visible background) are a real stripe target
802
+ // for the top/bottom variant — the inline-tag exemption exists to quiet
803
+ // text-level borders, not chips. They skip the left/right arms below.
804
+ const spanBadge = tag === 'span' && !!opts.badgeLike;
805
+ if (BORDER_SAFE_TAGS.has(tag) && !spanBadge) return [];
806
+ // A live status/alert region wears a colored single-edge border as a
807
+ // severity accent (toast, snackbar, callout), not as the side-tab tell.
808
+ if (opts.statusContext) return [];
638
809
  const findings = [];
639
810
  const sides = ['Top', 'Right', 'Bottom', 'Left'];
640
811
 
@@ -650,10 +821,20 @@ function checkBorders(tag, widths, colors, radius) {
650
821
  const isSide = side === 'Left' || side === 'Right';
651
822
 
652
823
  if (isSide) {
824
+ if (spanBadge) continue;
653
825
  if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
654
826
  else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
655
827
  } else {
656
828
  if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
829
+ // Horizontal variant of the side-tab stripe: a thick chromatic accent
830
+ // riding the top or bottom edge of a card/badge/container. Same
831
+ // dominant-edge + chroma gates as left/right, 3-12px band. Selected-
832
+ // tab underlines are exempt via opts.tabContext (adapters look for
833
+ // tablist/nav/tab ancestors and aria-selected); links, buttons,
834
+ // table cells, and <hr> never reach here (BORDER_SAFE_TAGS).
835
+ else if (!opts.tabContext && w >= 3 && w <= 12) {
836
+ findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
837
+ }
657
838
  }
658
839
  }
659
840
 
@@ -675,16 +856,26 @@ function isEmojiOnlyText(text) {
675
856
  function checkColors(opts) {
676
857
  const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
677
858
  if (SAFE_TAGS.has(tag)) {
678
- // Exception for <a> and <button> elements styled as buttons. SAFE_TAGS
679
- // exists to suppress contrast noise on inline links and unstyled controls,
680
- // where the element has no own background and the contrast against the
681
- // ancestor surface is already the intended visual. When the element has
682
- // its own opaque background and direct text, it is a styled button — and
683
- // contrast on its own surface is a real, frequent bug worth flagging.
684
- const isStyledButton = (tag === 'a' || tag === 'button')
685
- && hasDirectText
686
- && bgColor && bgColor.a > 0.5;
687
- if (!isStyledButton) return [];
859
+ // Exception for elements styled as controls or chips. SAFE_TAGS exists to
860
+ // suppress contrast noise on inline links and unstyled spans, where the
861
+ // element has no own background and the contrast against the ancestor
862
+ // surface is already the intended visual. When the element paints its own
863
+ // opaque background under direct text, it is a styled button, chip, or
864
+ // badge regardless of tag, and contrast on its own surface is a real,
865
+ // frequent bug worth flagging. (The shipped miss: a <span> severity chip
866
+ // whose white text lost a specificity fight and rendered muted-on-red at
867
+ // 1.2:1; the old a/button-only exception never looked at it.) The 9px
868
+ // font floor keeps sub-text decorations out.
869
+ const isStyledControl = hasDirectText
870
+ && ((bgColor && bgColor.a > 0.5)
871
+ // A gradient painted on the element itself is an own surface the
872
+ // same way a solid background is. Without this branch a nav CTA
873
+ // built as `<a>` with `background: linear-gradient(…)` and a text
874
+ // color that fails against every stop sails through on the
875
+ // SAFE_TAGS suppression (the shipped escape).
876
+ || (bgImage && /gradient/i.test(bgImage)))
877
+ && fontSize >= 9;
878
+ if (!isStyledControl) return [];
688
879
  }
689
880
  const findings = [];
690
881
 
@@ -721,7 +912,11 @@ function checkColors(opts) {
721
912
  // like `text-paper/60` on `bg-ink` sections are the FP pattern.
722
913
  const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
723
914
  if (!isAlphaFallbackFP) {
724
- findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
915
+ // Near-threshold ratios (e.g. 4.497) would round to the threshold
916
+ // itself at one decimal and read as "4.5 needs 4.5" — show two
917
+ // decimals there so the finding stays legible.
918
+ const ratioLabel = ratio.toFixed(1) === threshold.toFixed(1) ? ratio.toFixed(2) : ratio.toFixed(1);
919
+ findings.push({ id: 'low-contrast', snippet: `${ratioLabel}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
725
920
  }
726
921
  }
727
922
  }
@@ -767,6 +962,27 @@ function checkColors(opts) {
767
962
  return findings;
768
963
  }
769
964
 
965
+ // WCAG contrast for the :hover state of an element whose hover rules change
966
+ // its text color and/or background. The classic miss: a nav CTA whose
967
+ // author-intended hover pair passes AA, but a broader selector (e.g.
968
+ // `.nav-links a:hover`) wins the specificity fight and swaps in a color
969
+ // that fails. Only fires on elements that present as styled controls —
970
+ // direct text plus an opaque-ish own background in either state — so plain
971
+ // inline links keep the same suppression they get in checkColors.
972
+ function checkHoverContrast(opts) {
973
+ const { tag, textColor, bg, ownBgAlpha, fontSize, fontWeight, hasDirectText, isEmojiOnly } = opts;
974
+ if (!hasDirectText || isEmojiOnly || !textColor || !bg) return [];
975
+ if (SAFE_TAGS.has(tag) && !(ownBgAlpha != null && ownBgAlpha > 0.5)) return [];
976
+ const ratio = contrastRatio(textColor, bg);
977
+ const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
978
+ const threshold = isLargeText ? 3.0 : 4.5;
979
+ if (ratio >= threshold) return [];
980
+ return [{
981
+ id: 'low-contrast',
982
+ snippet: `:hover state ${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bg)}`,
983
+ }];
984
+ }
985
+
770
986
  function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
771
987
  if (!hasShadow && !hasBorder) return false;
772
988
  return hasRadius || hasBg;
@@ -912,26 +1128,57 @@ function isAccentColor(cssColor) {
912
1128
  return false;
913
1129
  }
914
1130
 
1131
+ function resolveHeroHeadingSizePx(value) {
1132
+ const input = String(value || '').trim().toLowerCase();
1133
+ if (!input) return 0;
1134
+
1135
+ const simpleLengthPx = (token) => {
1136
+ const match = /^(-?\d*\.?\d+)\s*(px|rem|em|%)?$/.exec(String(token || '').trim());
1137
+ if (!match) return null;
1138
+ const amount = Number(match[1]);
1139
+ if (!Number.isFinite(amount)) return null;
1140
+ if (match[2] === 'rem' || match[2] === 'em') return amount * 16;
1141
+ if (match[2] === '%') return amount * 0.16;
1142
+ return amount;
1143
+ };
1144
+
1145
+ const direct = simpleLengthPx(input);
1146
+ if (direct !== null) return direct;
1147
+
1148
+ // Static CSS engines cannot resolve viewport units, but clamp's min/max
1149
+ // bounds still tell us whether the heading can ever reach hero scale.
1150
+ const clamp = /^clamp\((.*)\)$/.exec(input);
1151
+ if (clamp) {
1152
+ const parts = clamp[1].split(',');
1153
+ if (parts.length === 3) {
1154
+ const bounds = [simpleLengthPx(parts[0]), simpleLengthPx(parts[2])]
1155
+ .filter((candidate) => candidate !== null);
1156
+ if (bounds.length > 0) return Math.max(...bounds);
1157
+ }
1158
+ }
1159
+
1160
+ return 0;
1161
+ }
1162
+
915
1163
  // Sibling-relationship rule. Anchor on a hero-scale h1, look at the
916
1164
  // previousElementSibling, and gate on EITHER the classic tracked-
917
1165
  // uppercase eyebrow OR the modern accent-colored bold eyebrow.
918
1166
  function checkHeroEyebrow(opts) {
919
1167
  const {
920
1168
  headingTag, headingText, headingFontSize,
1169
+ headingInApplicationContext,
921
1170
  siblingTag, siblingText, siblingTextTransform,
922
1171
  siblingFontSize, siblingLetterSpacing,
923
1172
  siblingFontWeight, siblingColor,
1173
+ siblingHasAccentDashPseudo,
924
1174
  } = opts;
925
1175
  if (headingTag !== 'h1') return [];
926
- // We previously gated on headingFontSize >= 48 to anchor "hero scale".
927
- // But modern hero h1s use clamp() / vw / var(--text-*), none of which
928
- // jsdom can resolve — the computed value comes back as "2em" or
929
- // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
930
- // on virtually every Tailwind v4 / framework build. The other gates
931
- // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
932
- // tracked-caps) are tight enough to avoid false positives on non-
933
- // hero h1s — a tiny tan label directly above any h1 is the
934
- // antipattern regardless of how big the h1 ends up.
1176
+ // This is specifically a marketing-hero cliché, not a ban on compact
1177
+ // context labels in product UI (for example, a station name inside a tab
1178
+ // panel). Browser-computed sizes are reliable; the static adapter also
1179
+ // resolves ordinary px/rem/em and clamp() bounds before reaching here.
1180
+ if (headingInApplicationContext) return [];
1181
+ if (!(headingFontSize >= 48)) return [];
935
1182
  if (!siblingTag) return [];
936
1183
  // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
937
1184
  // headings) — never an eyebrow.
@@ -952,11 +1199,16 @@ function checkHeroEyebrow(opts) {
952
1199
  const weight = Number(siblingFontWeight) || 400;
953
1200
  const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
954
1201
 
955
- if (!isClassicTracked && !isAccentBold) return [];
1202
+ // Branch C: dash-prefix eyebrow — sentence case, low tracking, regular
1203
+ // weight, but announced by a short chromatic ::before/::after bar
1204
+ // (the kicker dash). Same label-above-headline pattern, third styling.
1205
+ const isDashPrefixed = !!siblingHasAccentDashPseudo;
1206
+
1207
+ if (!isClassicTracked && !isAccentBold && !isDashPrefixed) return [];
956
1208
 
957
1209
  const headingTextSnippet = (headingText || '').trim().slice(0, 60);
958
1210
  const eyebrowSnippet = text.slice(0, 40);
959
- const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
1211
+ const style = isClassicTracked ? 'tracked-caps' : isAccentBold ? 'accent-bold' : 'dash-prefix';
960
1212
  return [{
961
1213
  id: 'hero-eyebrow-chip',
962
1214
  snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
@@ -1017,38 +1269,872 @@ function checkMotion(opts) {
1017
1269
  return findings;
1018
1270
  }
1019
1271
 
1272
+ // Locate the color token in a single shadow layer. Returns
1273
+ // { color, start, end } where color is the parsed {r,g,b,a} (null when the
1274
+ // token exists but can't be parsed — e.g. an unresolved var() or an exotic
1275
+ // color space), or null when no color token is present at all. Handles both
1276
+ // serialization orders: computed style puts the color first
1277
+ // ("rgb(…) 0px 0px 20px"), authored CSS usually puts it last
1278
+ // ("0 0 20px #3b82f6").
1279
+ function findShadowColor(layer) {
1280
+ const fn = layer.match(/(?:rgba?|hsla?|hwb|oklch|oklab|lch|lab|color)\([^)]*\)/i);
1281
+ if (fn) return { color: parseAnyColor(fn[0]), start: fn.index, end: fn.index + fn[0].length };
1282
+ const hex = layer.match(/#[0-9a-fA-F]{3,8}\b/);
1283
+ if (hex) return { color: parseAnyColor(hex[0]), start: hex.index, end: hex.index + hex[0].length };
1284
+ const wordRe = /[a-zA-Z][a-zA-Z]*/g;
1285
+ let m;
1286
+ while ((m = wordRe.exec(layer)) !== null) {
1287
+ const named = CSS_NAMED_COLORS[m[0].toLowerCase()];
1288
+ if (named) return { color: { ...named, a: 1 }, start: m.index, end: m.index + m[0].length };
1289
+ }
1290
+ return null;
1291
+ }
1292
+
1293
+ // Extract the length values of a shadow layer in declaration order, with the
1294
+ // color token removed so its components aren't misread as lengths. Handles
1295
+ // computed-style px values AND authored unitless zeros ("0 0 20px"); rem/em
1296
+ // approximate at 16px. Result order is offset-x, offset-y, blur, [spread].
1297
+ function extractShadowLengths(layer, colorStart, colorEnd) {
1298
+ const stripped = colorStart != null
1299
+ ? layer.slice(0, colorStart) + ' ' + layer.slice(colorEnd)
1300
+ : layer;
1301
+ const vals = [];
1302
+ const re = /(-?\d*\.?\d+)(px|rem|em)?/g;
1303
+ let m;
1304
+ while ((m = re.exec(stripped)) !== null) {
1305
+ let v = parseFloat(m[1]);
1306
+ if (m[2] === 'rem' || m[2] === 'em') v *= 16;
1307
+ vals.push(v);
1308
+ }
1309
+ return vals;
1310
+ }
1311
+
1020
1312
  function checkGlow(opts) {
1021
- const { boxShadow, effectiveBg } = opts;
1022
- if (!boxShadow || boxShadow === 'none') return [];
1023
- if (!effectiveBg) return [];
1313
+ const { boxShadow, textShadow, effectiveBg } = opts;
1314
+ const onDarkBg = effectiveBg ? relativeLuminance(effectiveBg) < 0.1 : false;
1315
+
1316
+ // Scan one shadow list. Two glow tells, in any color format:
1317
+ // 1. Zero-offset chromatic halo (0 0 Npx <color>) — slop on ANY
1318
+ // background; the light radiates evenly outward, which is never how
1319
+ // real elevation shadows behave. Achromatic zero-offset shadows stay
1320
+ // legal (soft ambient elevation), as do focus rings (blur 0).
1321
+ // 2. Any chromatic shadow with real blur on a dark background — the
1322
+ // classic dark-mode glow accent.
1323
+ const scan = (value, prop) => {
1324
+ if (!value || value === 'none') return null;
1325
+ // Split multiple shadows (commas not inside parentheses)
1326
+ for (const layer of value.split(/,(?![^(]*\))/)) {
1327
+ const colorInfo = findShadowColor(layer);
1328
+ // No color token, or one we can't resolve (unresolved var(), exotic
1329
+ // color space): don't guess — skip rather than false-positive.
1330
+ if (!colorInfo || !colorInfo.color) continue;
1331
+ const color = colorInfo.color;
1332
+ if (!hasChroma(color, 30)) continue;
1333
+ const vals = extractShadowLengths(layer, colorInfo.start, colorInfo.end);
1334
+ // Third value is blur (offset-x, offset-y, blur, [spread])
1335
+ if (vals.length < 3 || vals[2] <= 4) continue;
1336
+ if (vals[0] === 0 && vals[1] === 0) {
1337
+ return { id: 'dark-glow', snippet: `Zero-offset ${prop} glow (${colorToHex(color)})` };
1338
+ }
1339
+ if (onDarkBg) {
1340
+ return { id: 'dark-glow', snippet: `Colored ${prop} glow (${colorToHex(color)}) on dark background` };
1341
+ }
1342
+ }
1343
+ return null;
1344
+ };
1345
+
1346
+ const found = scan(boxShadow, 'box-shadow') || scan(textShadow, 'text-shadow');
1347
+ return found ? [found] : [];
1348
+ }
1024
1349
 
1025
- // Only flag on dark backgrounds (luminance < 0.1)
1026
- const bgLum = relativeLuminance(effectiveBg);
1027
- if (bgLum >= 0.1) return [];
1350
+ // Collect CSS custom property declarations from raw stylesheet/HTML text.
1351
+ // First declaration wins (:root declarations usually come first); good
1352
+ // enough for the single-level var() resolution the text engines need.
1353
+ function collectCssCustomProps(content) {
1354
+ const map = new Map();
1355
+ const re = /(--[\w-]+)\s*:\s*([^;{}]+)/g;
1356
+ let m;
1357
+ while ((m = re.exec(content)) !== null) {
1358
+ if (!map.has(m[1])) map.set(m[1], m[2].trim());
1359
+ }
1360
+ return map;
1361
+ }
1028
1362
 
1029
- // Split multiple shadows (commas not inside parentheses)
1030
- const parts = boxShadow.split(/,(?![^(]*\))/);
1031
- for (const shadow of parts) {
1032
- const colorMatch = shadow.match(/rgba?\([^)]+\)/);
1033
- if (!colorMatch) continue;
1034
- const color = parseRgb(colorMatch[0]);
1035
- if (!color || !hasChroma(color, 30)) continue;
1363
+ // Text-level glow scan shared by the regex engine and the page-level HTML
1364
+ // pattern pass. Resolves single-level var() refs against custom properties
1365
+ // collected from the same text, then applies the same two glow tells as
1366
+ // checkGlow: zero-offset chromatic halo (any background) and chromatic
1367
+ // blurred shadow when the page has a dark background. Returns
1368
+ // [{ index, snippet }] — index is the offset of the shadow declaration.
1369
+ // Dark-page heuristic for raw CSS/HTML text: dark hex/rgb literals, Tailwind
1370
+ // dark bg utilities, or a ROOT-scoped (body/html/:root or <body style>)
1371
+ // background that resolves — via var() — to a dark color. The var/modern-
1372
+ // color extension is deliberately root-scoped: a light page with one dark
1373
+ // accent chip must not turn every tinted drop shadow into a "dark page"
1374
+ // signal. Shared by the glow and radial-halo text scanners.
1375
+ function cssTextHasDarkRootBg(content, customProps) {
1376
+ const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/i;
1377
+ const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
1378
+ if (darkBgRe.test(content) || twDarkBg.test(content)) return true;
1379
+ const rootScopes = [];
1380
+ const blockRe = /(?:^|[}\s,;>])(?:body|html|:root)\s*(?:,[^{]*)?\{([^}]*)\}/gi;
1381
+ let sm;
1382
+ while ((sm = blockRe.exec(content)) !== null) rootScopes.push(sm[1]);
1383
+ const inlineBody = content.match(/<body[^>]*\bstyle\s*=\s*"([^"]*)"/i);
1384
+ if (inlineBody) rootScopes.push(inlineBody[1]);
1385
+ for (const scope of rootScopes) {
1386
+ const bgRe = /background(?:-color)?\s*:\s*([^;{}]+)/gi;
1387
+ let bm;
1388
+ while ((bm = bgRe.exec(scope)) !== null) {
1389
+ const c = parseAnyColor(resolveVarRefs(bm[1].trim(), customProps));
1390
+ if (c && (c.a ?? 1) > 0.5 && relativeLuminance(c) < 0.1) return true;
1391
+ }
1392
+ }
1393
+ return false;
1394
+ }
1036
1395
 
1037
- // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
1038
- const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
1039
- const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
1040
- const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
1041
- .map(m => parseFloat(m[1]));
1396
+ function scanCssTextForGlow(content) {
1397
+ const customProps = collectCssCustomProps(content);
1398
+ const hasDarkBg = cssTextHasDarkRootBg(content, customProps);
1042
1399
 
1043
- // Third value is blur (offset-x, offset-y, blur, [spread])
1044
- if (pxVals.length >= 3 && pxVals[2] > 4) {
1045
- return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
1400
+ const results = [];
1401
+ const shadowRe = /\b(box-shadow|text-shadow)\s*:\s*([^;{}]+)/gi;
1402
+ let m;
1403
+ while ((m = shadowRe.exec(content)) !== null) {
1404
+ const prop = m[1].toLowerCase();
1405
+ const value = resolveVarRefs(m[2].trim(), customProps);
1406
+ for (const layer of value.split(/,(?![^(]*\))/)) {
1407
+ const colorInfo = findShadowColor(layer);
1408
+ if (!colorInfo || !colorInfo.color || !hasChroma(colorInfo.color, 30)) continue;
1409
+ const vals = extractShadowLengths(layer, colorInfo.start, colorInfo.end);
1410
+ if (vals.length < 3 || vals[2] <= 4) continue;
1411
+ const zeroOffset = vals[0] === 0 && vals[1] === 0;
1412
+ if (!zeroOffset && !hasDarkBg) continue;
1413
+ results.push({
1414
+ index: m.index,
1415
+ snippet: zeroOffset
1416
+ ? `Zero-offset ${prop} glow (${colorToHex(colorInfo.color)})`
1417
+ : `Colored ${prop} glow (${colorToHex(colorInfo.color)}) on dark page`,
1418
+ });
1419
+ break; // one finding per declaration
1046
1420
  }
1047
1421
  }
1422
+ return results;
1423
+ }
1048
1424
 
1425
+ // Decorative grid or line-field backgrounds drawn with hairline
1426
+ // linear-gradient layers tiled by a fixed pixel cell. Shared by the HTML
1427
+ // pattern pass and the regex source engine so standalone CSS, component
1428
+ // styles, and inline styles receive the same coverage. Both signals must
1429
+ // co-occur in one declaration block; unrelated rules must not add up across
1430
+ // the file. Returns [{ index, snippet }], capped at one finding per source to
1431
+ // match the page-level HTML check's existing behavior.
1432
+ function scanCssTextForGridBackground(content) {
1433
+ const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
1434
+ const invertedHairlineRe = /transparent\s+calc\(100%\s*-\s*\d{1,3}px\)/gi;
1435
+ const sizeDeclPxRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
1436
+ const sizeDeclPxPairRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\s+\d{1,3}px/i;
1437
+ const shorthandPxAnyRe = /\/\s*\d{1,3}px\b/;
1438
+ const shorthandPxPairRe = /\/\s*\d{1,3}px\s+\d{1,3}px/;
1439
+ const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
1440
+ const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
1441
+ let blk;
1442
+ while ((blk = blockRe.exec(content)) !== null) {
1443
+ const block = blk[1] || blk[2] || blk[3] || '';
1444
+ let hairlineCount = 0;
1445
+ let bgJoined = '';
1446
+ let bm;
1447
+ bgDeclRe.lastIndex = 0;
1448
+ while ((bm = bgDeclRe.exec(block)) !== null) {
1449
+ hairlineCount += (bm[1].match(hairlineRe) || []).length;
1450
+ hairlineCount += (bm[1].match(invertedHairlineRe) || []).length;
1451
+ bgJoined += `${bm[1]};`;
1452
+ }
1453
+ if (hairlineCount === 0) continue;
1454
+ const hasPxCell = sizeDeclPxRe.test(block) || shorthandPxAnyRe.test(bgJoined);
1455
+ const hasPxPairCell = sizeDeclPxPairRe.test(block) || shorthandPxPairRe.test(bgJoined);
1456
+ if ((hairlineCount >= 2 && hasPxCell) || hasPxPairCell) {
1457
+ return [{
1458
+ index: blk.index,
1459
+ snippet: hairlineCount >= 2
1460
+ ? 'two-axis grid-line gradient background'
1461
+ : 'px-tiled hairline line-field background',
1462
+ }];
1463
+ }
1464
+ }
1049
1465
  return [];
1050
1466
  }
1051
1467
 
1468
+ // Decorative chromatic halo drawn as a radial-gradient background on a dark
1469
+ // page: a saturated center stop dissolving to transparent. The gradient
1470
+ // sibling of the dark-glow shadow tell. Mechanical gates, in order:
1471
+ // * page has a dark root background (shared heuristic with the glow scan)
1472
+ // * declaration has no url() layer (photographic imagery is exempt)
1473
+ // * the gradient's first color stop is chromatic (RGB spread >= 24) and
1474
+ // visible (alpha >= 0.7 — deliberately translucent light-scene washes
1475
+ // composite with content instead of painting a flat halo, and stay legal)
1476
+ // * the gradient's last stop is transparent / near-zero alpha
1477
+ // * no small pixel-sized stop positions (<= 24px = dot/texture patterns)
1478
+ // * not a repeating-* gradient
1479
+ // Achromatic vignettes fail the chroma gate; panel sheens that fade to an
1480
+ // opaque surface color fail the transparent-end gate.
1481
+ function scanCssTextForRadialHalo(content) {
1482
+ const customProps = collectCssCustomProps(content);
1483
+ if (!cssTextHasDarkRootBg(content, customProps)) return [];
1484
+
1485
+ const findings = [];
1486
+ const seen = new Set();
1487
+ const declRe = /background(?:-image)?\s*:\s*([^;{}]+)/gi;
1488
+ let m;
1489
+ while ((m = declRe.exec(content)) !== null) {
1490
+ const value = resolveVarRefs(m[1].trim(), customProps);
1491
+ if (/url\s*\(/i.test(value)) continue;
1492
+
1493
+ const gradRe = /(repeating-)?radial-gradient\(/gi;
1494
+ let g;
1495
+ while ((g = gradRe.exec(value)) !== null) {
1496
+ if (g[1]) continue; // repeating-* = pattern, not halo
1497
+ // Balanced-paren capture of the gradient arguments.
1498
+ let depth = 0, end = -1;
1499
+ const open = value.indexOf('(', g.index);
1500
+ for (let i = open; i < value.length; i++) {
1501
+ if (value[i] === '(') depth++;
1502
+ else if (value[i] === ')') { depth--; if (depth === 0) { end = i; break; } }
1503
+ }
1504
+ if (end < 0) break;
1505
+ const args = splitTopLevelCommas(value.slice(open + 1, end));
1506
+ if (args.length < 2) continue;
1507
+
1508
+ // Optional prelude (shape / size / `at <pos>`) carries no color.
1509
+ const colorTokenRe = /(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb|color-mix)\([^)]*(?:\([^)]*\))?[^)]*\)|#[0-9a-f]{3,8}\b|\btransparent\b/i;
1510
+ const stops = args.filter(a => colorTokenRe.test(a));
1511
+ if (stops.length < 2) continue;
1512
+
1513
+ // Dot/texture exemption: px-sized stop positions mean a repeating
1514
+ // background-size pattern, not a page-scale halo.
1515
+ const pxStop = stops.some(s => {
1516
+ const pm = s.match(/(-?[\d.]+)px\b/);
1517
+ return pm && Math.abs(parseFloat(pm[1])) <= 24;
1518
+ });
1519
+ if (pxStop) continue;
1520
+
1521
+ const first = stops[0].match(colorTokenRe);
1522
+ const last = stops[stops.length - 1].match(colorTokenRe);
1523
+ if (!first || !last) continue;
1524
+
1525
+ const lastColor = /^transparent$/i.test(last[0]) ? { r: 0, g: 0, b: 0, a: 0 } : parseAnyColor(last[0]);
1526
+ if (!lastColor || (lastColor.a ?? 1) > 0.05) continue;
1527
+
1528
+ const firstColor = /^transparent$/i.test(first[0]) ? null : parseAnyColor(first[0]);
1529
+ if (!firstColor) continue;
1530
+ if ((firstColor.a ?? 1) < 0.7) continue;
1531
+ const spread = Math.max(firstColor.r, firstColor.g, firstColor.b) - Math.min(firstColor.r, firstColor.g, firstColor.b);
1532
+ if (spread < 24) continue;
1533
+
1534
+ const snippet = `radial-gradient halo (${colorToHex(firstColor)} → transparent) on dark page`;
1535
+ if (seen.has(snippet)) continue;
1536
+ seen.add(snippet);
1537
+ findings.push({ index: m.index, snippet });
1538
+ }
1539
+ }
1540
+ return findings;
1541
+ }
1542
+
1543
+ // ---------------------------------------------------------------------------
1544
+ // Text-level CSS rule-block scanners (pseudo-element stripes, pulsing dots)
1545
+ // ---------------------------------------------------------------------------
1546
+
1547
+ // Iterate `selector { declarations }` pairs in raw CSS/HTML text. The block
1548
+ // body excludes braces, so nested structures (@media, @keyframes) naturally
1549
+ // yield their innermost rules with the innermost selector text. Callers
1550
+ // create the regex locally — a shared /g instance is not re-entrant.
1551
+ const CSS_RULE_BLOCK_SOURCE = String.raw`([^{};]+)\{([^{}]*)\}`;
1552
+
1553
+ // Parse a declaration block into a prop → value map (last declaration wins,
1554
+ // approximating the cascade inside one block). Values keep their raw text
1555
+ // with any !important suffix stripped.
1556
+ function parseCssDeclBlock(block) {
1557
+ const decls = new Map();
1558
+ for (const part of String(block || '').split(';')) {
1559
+ const idx = part.indexOf(':');
1560
+ if (idx <= 0) continue;
1561
+ const prop = part.slice(0, idx).trim().toLowerCase();
1562
+ const value = part.slice(idx + 1).replace(/\s*!important\s*$/i, '').trim();
1563
+ if (prop && value) decls.set(prop, value);
1564
+ }
1565
+ return decls;
1566
+ }
1567
+
1568
+ function cssLengthToPx(value) {
1569
+ const m = String(value || '').trim().match(/^(-?[\d.]+)(px|rem|em)$/i);
1570
+ if (!m) return null;
1571
+ const n = parseFloat(m[1]);
1572
+ return m[2].toLowerCase() === 'px' ? n : n * 16;
1573
+ }
1574
+
1575
+ function isZeroOffset(value) {
1576
+ return value != null && /^-?0(?:px|%|rem|em)?$/.test(String(value).trim());
1577
+ }
1578
+
1579
+ // Side-tab variant: the accent stripe drawn as an absolutely-positioned
1580
+ // ::before/::after pseudo-element (narrow colored box hugging a vertical
1581
+ // edge) instead of a border-left/right. The element-level border checks
1582
+ // never see it — pseudo-elements aren't part of the DOM the cascade walks —
1583
+ // so this scans stylesheet text directly, mirroring the border rule's
1584
+ // gates: >= 3px thick, chromatic fill, full height against a side edge.
1585
+ function scanCssTextForPseudoStripe(content) {
1586
+ const customProps = collectCssCustomProps(content);
1587
+ const findings = [];
1588
+ const seen = new Set();
1589
+ const ruleRe = new RegExp(CSS_RULE_BLOCK_SOURCE, 'g');
1590
+ let m;
1591
+ while ((m = ruleRe.exec(content)) !== null) {
1592
+ const selector = m[1].trim();
1593
+ if (!/::?(?:before|after)\b/i.test(selector)) continue;
1594
+ // Keep the border rule's prose exemptions (blockquote bars etc.).
1595
+ if (/\b(?:blockquote|pre|code|nav|hr)\b/i.test(selector)) continue;
1596
+ const decls = parseCssDeclBlock(m[2]);
1597
+ const position = decls.get('position');
1598
+ if (position !== 'absolute' && position !== 'fixed') continue;
1599
+
1600
+ const widthPx = cssLengthToPx(resolveVarRefs(
1601
+ decls.get('width') || decls.get('inline-size') || '', customProps));
1602
+ const heightPx = cssLengthToPx(resolveVarRefs(
1603
+ decls.get('height') || decls.get('block-size') || '', customProps));
1604
+ const verticalCandidate = widthPx != null && widthPx >= 3 && widthPx <= 12;
1605
+ // Horizontal variant (top/bottom stripe) carries extra exemptions:
1606
+ // link/button underline affordances, selected-state indicators
1607
+ // (aria-selected="true", aria-current, active/current/selected class
1608
+ // hints), and state-conditional (:hover/:focus/...) affordances are
1609
+ // not stripes. Tab-strip membership alone ([role=tab], .tabs, bare
1610
+ // [aria-selected]) is NOT exempt — a stripe on every tab in the
1611
+ // group is decoration; only the selected item's underline stays.
1612
+ const horizontalCandidate = heightPx != null && heightPx >= 3 && heightPx <= 12
1613
+ && !/(?:^|[\s>+~,(])(?:a|button|summary|tr|td|th|table|li)(?![\w-])/i.test(selector)
1614
+ && !/\[aria-selected\s*[*^$|~]?=\s*["']?true/i.test(selector)
1615
+ && !/\[aria-current(?!\s*[*^$|~]?=\s*["']?false)/i.test(selector)
1616
+ && !/(?:^|[\s._[-])(?:active|current|selected|btn[\w-]*|button[\w-]*|link[\w-]*)(?![\w])/i.test(selector)
1617
+ && !/:(?:hover|focus|focus-visible|focus-within|active|checked)\b/i.test(selector);
1618
+ if (!verticalCandidate && !horizontalCandidate) continue;
1619
+
1620
+ // Resolve edge offsets, letting an `inset` shorthand fill the gaps.
1621
+ const offsets = {
1622
+ top: decls.get('top'), right: decls.get('right'),
1623
+ bottom: decls.get('bottom'), left: decls.get('left'),
1624
+ };
1625
+ const inset = decls.get('inset');
1626
+ if (inset) {
1627
+ const p = inset.split(/\s+/);
1628
+ const [t, r, b, l] =
1629
+ p.length === 1 ? [p[0], p[0], p[0], p[0]]
1630
+ : p.length === 2 ? [p[0], p[1], p[0], p[1]]
1631
+ : p.length === 3 ? [p[0], p[1], p[2], p[1]]
1632
+ : p;
1633
+ if (offsets.top == null) offsets.top = t;
1634
+ if (offsets.right == null) offsets.right = r;
1635
+ if (offsets.bottom == null) offsets.bottom = b;
1636
+ if (offsets.left == null) offsets.left = l;
1637
+ }
1638
+ if (offsets.left == null) offsets.left = decls.get('inset-inline-start');
1639
+ if (offsets.right == null) offsets.right = decls.get('inset-inline-end');
1640
+
1641
+ const heightValue = String(resolveVarRefs(
1642
+ decls.get('height') || decls.get('block-size') || '', customProps)).trim();
1643
+ const widthValue = String(resolveVarRefs(
1644
+ decls.get('width') || decls.get('inline-size') || '', customProps)).trim();
1645
+
1646
+ let edge = null;
1647
+ let thicknessPx = null;
1648
+ if (verticalCandidate) {
1649
+ // Full-height stripes hug both corners; the "floating" variant backs
1650
+ // off each end by a small inset (top/bottom a few px) so the bar
1651
+ // clears the card's corners. Both read as the same side-tab accent —
1652
+ // corner treatment is styling, not a different pattern.
1653
+ const topPx = cssLengthToPx(resolveVarRefs(String(offsets.top ?? ''), customProps));
1654
+ const bottomPx = cssLengthToPx(resolveVarRefs(String(offsets.bottom ?? ''), customProps));
1655
+ const fullHeight = (isZeroOffset(offsets.top) && isZeroOffset(offsets.bottom))
1656
+ || /^100(?:\.0*)?%$/.test(heightValue)
1657
+ || (topPx != null && bottomPx != null
1658
+ && topPx >= 0 && topPx <= 20 && bottomPx >= 0 && bottomPx <= 20);
1659
+ if (fullHeight) {
1660
+ edge = isZeroOffset(offsets.left) ? 'left'
1661
+ : isZeroOffset(offsets.right) ? 'right' : null;
1662
+ thicknessPx = widthPx;
1663
+ }
1664
+ }
1665
+ if (!edge && horizontalCandidate) {
1666
+ const fullWidth = (isZeroOffset(offsets.left) && isZeroOffset(offsets.right))
1667
+ || /^100(?:\.0*)?%$/.test(widthValue);
1668
+ if (fullWidth) {
1669
+ edge = isZeroOffset(offsets.top) ? 'top'
1670
+ : isZeroOffset(offsets.bottom) ? 'bottom' : null;
1671
+ thicknessPx = heightPx;
1672
+ }
1673
+ }
1674
+ if (!edge) continue;
1675
+
1676
+ // Chromatic fill only — a neutral hairline divider is not an accent
1677
+ // stripe. Unresolvable colors err toward detection, matching the
1678
+ // border rule's unknown-format default.
1679
+ const bg = String(resolveVarRefs(
1680
+ decls.get('background-color') || decls.get('background') || '', customProps)).trim();
1681
+ if (!bg || /^(?:none|transparent|inherit|initial|unset|currentcolor)$/i.test(bg)) continue;
1682
+ const colorToken = bg.match(/(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb)\([^)]*\)|#[0-9a-f]{3,8}\b/i);
1683
+ const parsed = parseAnyColor(colorToken ? colorToken[0] : bg);
1684
+ if (parsed) {
1685
+ if ((parsed.a ?? 1) < 0.1) continue;
1686
+ const spread = Math.max(parsed.r, parsed.g, parsed.b) - Math.min(parsed.r, parsed.g, parsed.b);
1687
+ if (spread < 30) continue;
1688
+ } else if (/^(?:white|black|gray|grey|silver)$/i.test(bg)) {
1689
+ continue;
1690
+ }
1691
+
1692
+ if (seen.has(selector)) continue;
1693
+ seen.add(selector);
1694
+ findings.push({
1695
+ id: 'side-tab',
1696
+ snippet: `${selector} — absolute ${thicknessPx}px pseudo-element stripe (${edge}: 0)`,
1697
+ });
1698
+ }
1699
+ return findings;
1700
+ }
1701
+
1702
+ // Side-tab stripe drawn as a single-edge inset box-shadow
1703
+ // (x or y offset 3-12px, other axis 0, no blur/spread, chromatic color):
1704
+ // paints a bar along one edge with no border property involved, so the
1705
+ // element-level border checks never see it. Selection-state indicators
1706
+ // are exempt — an inset stripe on [aria-current] / .active / [role=tab]
1707
+ // marks the selected item; the same stripe unconditionally on every item
1708
+ // is decoration and flags.
1709
+ function scanCssTextForInsetStripe(content) {
1710
+ const customProps = collectCssCustomProps(content);
1711
+ const findings = [];
1712
+ const seen = new Set();
1713
+ const ruleRe = new RegExp(CSS_RULE_BLOCK_SOURCE, 'g');
1714
+ let m;
1715
+ while ((m = ruleRe.exec(content)) !== null) {
1716
+ const selector = m[1].trim();
1717
+ // Selection-state contexts: current-item markers and interaction
1718
+ // states. Tab-strip membership alone ([role=tab], .tabs, bare
1719
+ // [aria-selected]) is NOT exempt — a stripe on every tab in the
1720
+ // group is decoration; only the selected item's indicator stays.
1721
+ if (/:(?:hover|focus|focus-visible|focus-within|active|checked|target)\b/i.test(selector)) continue;
1722
+ if (/\[aria-selected\s*[*^$|~]?=\s*["']?true/i.test(selector)) continue;
1723
+ if (/\[aria-current(?!\s*[*^$|~]?=\s*["']?false)/i.test(selector)) continue;
1724
+ if (/(?:^|[\s._[-])(?:active|current|selected)(?![\w])/i.test(selector)) continue;
1725
+ // Structural tags where a single-edge inset shadow is depth/quoting,
1726
+ // not an accent stripe.
1727
+ if (/(?:^|[\s>+~,(])(?:button|hr|tr|td|th|table|blockquote|pre|code)(?![\w-])/i.test(selector)) continue;
1728
+
1729
+ const decls = parseCssDeclBlock(m[2]);
1730
+ const shadow = decls.get('box-shadow');
1731
+ if (!shadow || !/\binset\b/i.test(shadow)) continue;
1732
+ // Narrow fixed-width elements (logo marks, icon glyphs) use inset
1733
+ // fills as artwork, not edge stripes. Stripe targets — cards, badges,
1734
+ // menu items — are wider or leave width to layout.
1735
+ const declaredWidth = cssLengthToPx(resolveVarRefs(decls.get('width') || decls.get('inline-size') || '', customProps));
1736
+ if (declaredWidth != null && declaredWidth <= 40) continue;
1737
+ const value = resolveVarRefs(shadow, customProps);
1738
+ for (const layer of value.split(/,(?![^(]*\))/)) {
1739
+ if (!/\binset\b/i.test(layer)) continue;
1740
+ const colorInfo = findShadowColor(layer);
1741
+ // Unresolvable colors (currentColor, external vars): don't guess.
1742
+ if (!colorInfo || !colorInfo.color) continue;
1743
+ const c = colorInfo.color;
1744
+ if ((c.a ?? 1) < 0.1) continue;
1745
+ const chroma = Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b);
1746
+ if (chroma < 30) continue;
1747
+ const vals = extractShadowLengths(layer, colorInfo.start, colorInfo.end);
1748
+ const x = vals[0] || 0, y = vals[1] || 0, blur = vals[2] || 0, sp = vals[3] || 0;
1749
+ if (blur !== 0 || sp !== 0) continue;
1750
+ const ax = Math.abs(x), ay = Math.abs(y);
1751
+ const isStripe = (ax >= 3 && ax <= 12 && ay === 0) || (ay >= 3 && ay <= 12 && ax === 0);
1752
+ if (!isStripe) continue;
1753
+ if (seen.has(selector)) break;
1754
+ seen.add(selector);
1755
+ const edge = ay === 0 ? (x > 0 ? 'left' : 'right') : (y > 0 ? 'top' : 'bottom');
1756
+ findings.push({
1757
+ id: 'side-tab',
1758
+ snippet: `${selector} — inset box-shadow ${ay === 0 ? ax : ay}px stripe (${edge})`,
1759
+ });
1760
+ break;
1761
+ }
1762
+ }
1763
+ return findings;
1764
+ }
1765
+
1766
+ // Collect @keyframes names whose body travels horizontally — the marquee
1767
+ // loop. X travel is measured across every translateX/translate/translate3d
1768
+ // X component in the body: a centered element animating something else
1769
+ // keeps a constant -50% X (zero travel) and never qualifies, while a
1770
+ // ticker moves from its resting position to a large offset. Keyframes
1771
+ // with a single X sample that also vary scale/opacity read as pulses or
1772
+ // breathes, not marquees.
1773
+ function collectMarqueeKeyframes(content) {
1774
+ const names = new Set();
1775
+ const re = /@(?:-webkit-)?keyframes\s+([\w-]+)\s*\{/g;
1776
+ let m;
1777
+ while ((m = re.exec(content)) !== null) {
1778
+ let depth = 1;
1779
+ let i = re.lastIndex;
1780
+ while (i < content.length && depth > 0) {
1781
+ const ch = content.charCodeAt(i);
1782
+ if (ch === 0x7b /* { */) depth++;
1783
+ else if (ch === 0x7d /* } */) depth--;
1784
+ i++;
1785
+ }
1786
+ const body = content.slice(re.lastIndex, Math.max(re.lastIndex, i - 1));
1787
+ re.lastIndex = i;
1788
+
1789
+ // Only percentage travel qualifies: a content marquee translates by a
1790
+ // fraction of its own (unknown) track width, so generated tickers use
1791
+ // -50% / -100%. Pixel-travel loops are bespoke product animations —
1792
+ // sweeping playheads, progress indicators — not marquees.
1793
+ const pct = [];
1794
+ const xRe = /\btranslate(?:X|3d)?\(\s*(-?[\d.]+)%/gi;
1795
+ let xm;
1796
+ while ((xm = xRe.exec(body)) !== null) pct.push(parseFloat(xm[1]));
1797
+ if (pct.length === 0) continue;
1798
+ if (pct.length === 1 && /\bscale\(|\bopacity\s*:/i.test(body)) continue;
1799
+ // Implicit start: a lone declared X animates from the element's
1800
+ // resting position, so its magnitude is the travel.
1801
+ const travelPct = pct.length > 1 ? Math.max(...pct) - Math.min(...pct) : Math.abs(pct[0]);
1802
+ if (travelPct >= 20) names.add(m[1]);
1803
+ }
1804
+ return names;
1805
+ }
1806
+
1807
+ // Auto-scrolling marquee: a <marquee> element, or an infinite animation
1808
+ // bound to a keyframe loop that travels a large horizontal distance.
1809
+ // Rotation/opacity animations never qualify (no X travel); JS-driven
1810
+ // carousels with user controls have no infinite CSS X-loop to match.
1811
+ function scanCssTextForMarquee(content) {
1812
+ const findings = [];
1813
+ if (/<marquee\b/i.test(content)) {
1814
+ findings.push({ id: 'marquee', snippet: '<marquee> element' });
1815
+ }
1816
+ const marqueeKeyframes = collectMarqueeKeyframes(content);
1817
+ if (marqueeKeyframes.size === 0) return findings;
1818
+ const seen = new Set();
1819
+ const ruleRe = new RegExp(CSS_RULE_BLOCK_SOURCE, 'g');
1820
+ let m;
1821
+ while ((m = ruleRe.exec(content)) !== null) {
1822
+ const selector = m[1].trim();
1823
+ const decls = parseCssDeclBlock(m[2]);
1824
+ for (const name of infiniteAnimationNames(decls)) {
1825
+ if (!marqueeKeyframes.has(name)) continue;
1826
+ const key = `${selector} ${name}`;
1827
+ if (seen.has(key)) continue;
1828
+ seen.add(key);
1829
+ findings.push({ id: 'marquee', snippet: `${selector} — infinite horizontal loop animation "${name}"` });
1830
+ }
1831
+ }
1832
+ return findings;
1833
+ }
1834
+
1835
+ // Collect @keyframes names and whether each one reads as a "pulse" —
1836
+ // i.e. it varies opacity, scale, or box-shadow. Rotation-only keyframes
1837
+ // (spinners) are explicitly not pulses.
1838
+ function collectPulseKeyframes(content) {
1839
+ const map = new Map();
1840
+ const re = /@(?:-webkit-)?keyframes\s+([\w-]+)\s*\{/g;
1841
+ let m;
1842
+ while ((m = re.exec(content)) !== null) {
1843
+ let depth = 1;
1844
+ let i = re.lastIndex;
1845
+ while (i < content.length && depth > 0) {
1846
+ const ch = content.charCodeAt(i);
1847
+ if (ch === 0x7b /* { */) depth++;
1848
+ else if (ch === 0x7d /* } */) depth--;
1849
+ i++;
1850
+ }
1851
+ const body = content.slice(re.lastIndex, Math.max(re.lastIndex, i - 1));
1852
+ const pulses = /\bopacity\s*:/i.test(body)
1853
+ || /\bbox-shadow\s*:/i.test(body)
1854
+ || /\btransform\s*:[^;{}]*\bscale/i.test(body);
1855
+ if (!map.has(m[1]) || pulses) map.set(m[1], pulses);
1856
+ re.lastIndex = i;
1857
+ }
1858
+ return map;
1859
+ }
1860
+
1861
+ const ANIMATION_VALUE_KEYWORDS = new Set([
1862
+ 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'linear',
1863
+ 'infinite', 'alternate', 'alternate-reverse', 'normal', 'reverse',
1864
+ 'none', 'forwards', 'backwards', 'both', 'running', 'paused',
1865
+ 'step-start', 'step-end', 'inherit', 'initial', 'unset',
1866
+ ]);
1867
+
1868
+ // Extract animation names that run with iteration-count: infinite from a
1869
+ // declaration block (shorthand layers or animation-name + iteration-count).
1870
+ function infiniteAnimationNames(decls) {
1871
+ const out = [];
1872
+ const shorthand = decls.get('animation');
1873
+ if (shorthand) {
1874
+ for (const layer of shorthand.split(/,(?![^(]*\))/)) {
1875
+ if (!/\binfinite\b/i.test(layer)) continue;
1876
+ const name = layer.split(/\s+/).find(t =>
1877
+ /^[a-zA-Z_-][\w-]*$/.test(t) && !ANIMATION_VALUE_KEYWORDS.has(t.toLowerCase()));
1878
+ if (name) out.push(name);
1879
+ }
1880
+ }
1881
+ const nameDecl = decls.get('animation-name');
1882
+ if (nameDecl && /\binfinite\b/i.test(decls.get('animation-iteration-count') || '')) {
1883
+ for (const raw of nameDecl.split(',')) {
1884
+ const t = raw.trim();
1885
+ if (t && t.toLowerCase() !== 'none') out.push(t);
1886
+ }
1887
+ }
1888
+ return out;
1889
+ }
1890
+
1891
+ function isRoundDotRadius(radiusValue, w, h) {
1892
+ if (!radiusValue) return false;
1893
+ const first = String(radiusValue).trim().split(/\s+/)[0];
1894
+ const pct = first.match(/^([\d.]+)%$/);
1895
+ if (pct) return parseFloat(pct[1]) >= 40;
1896
+ const px = cssLengthToPx(first);
1897
+ if (px == null) return false;
1898
+ return px >= 999 || px >= 0.4 * Math.min(w, h);
1899
+ }
1900
+
1901
+ // Remove @media blocks whose condition is prefers-reduced-motion: reduce.
1902
+ // Those blocks describe the accessibility fallback, not the default
1903
+ // experience that ships — an `animation: none` reset inside one must not
1904
+ // mask the resting-state animation the page plays for everyone else.
1905
+ function stripReducedMotionBlocks(content) {
1906
+ const re = /@media[^{]*prefers-reduced-motion\s*:\s*reduce[^{]*\{/gi;
1907
+ let out = '';
1908
+ let last = 0;
1909
+ let m;
1910
+ while ((m = re.exec(content)) !== null) {
1911
+ let depth = 1;
1912
+ let i = re.lastIndex;
1913
+ while (i < content.length && depth > 0) {
1914
+ const ch = content.charCodeAt(i);
1915
+ if (ch === 0x7b /* { */) depth++;
1916
+ else if (ch === 0x7d /* } */) depth--;
1917
+ i++;
1918
+ }
1919
+ out += content.slice(last, m.index);
1920
+ last = i;
1921
+ re.lastIndex = i;
1922
+ }
1923
+ return out + content.slice(last);
1924
+ }
1925
+
1926
+ // Source-index ranges of <header> and <nav> landmark elements in an HTML
1927
+ // string. Lets string-level scans decide whether a matched element sits in
1928
+ // the page chrome (the hero/nav region) without needing a DOM.
1929
+ function landmarkSourceRanges(content) {
1930
+ const ranges = [];
1931
+ for (const tag of ['header', 'nav']) {
1932
+ const re = new RegExp(`<${tag}\\b|</${tag}\\s*>`, 'gi');
1933
+ const stack = [];
1934
+ let m;
1935
+ while ((m = re.exec(content)) !== null) {
1936
+ if (m[0].charAt(1) === '/') {
1937
+ const start = stack.pop();
1938
+ if (start != null) ranges.push([start, m.index]);
1939
+ } else {
1940
+ stack.push(m.index);
1941
+ }
1942
+ }
1943
+ }
1944
+ return ranges;
1945
+ }
1946
+
1947
+ function indexInSourceRanges(index, ranges) {
1948
+ return ranges.some(([start, end]) => index >= start && index < end);
1949
+ }
1950
+
1951
+ // Does any element targeted by the final compound of `selector` appear
1952
+ // inside a header/nav landmark range of the HTML source? Resolves the last
1953
+ // .class or #id token of the selector against class/id attributes; a
1954
+ // tag-only compound is never resolvable this way and returns false
1955
+ // (conservative: no promotion without placement evidence).
1956
+ function selectorHitsLandmark(content, selector, ranges) {
1957
+ if (!ranges || ranges.length === 0) return false;
1958
+ const last = selector.split(/[\s>+~]+/).filter(Boolean).pop() || '';
1959
+ const idMatch = last.match(/#([A-Za-z_][\w-]*)/);
1960
+ const classMatch = last.match(/\.([A-Za-z_][\w-]*)/);
1961
+ let attrRe = null;
1962
+ if (idMatch) {
1963
+ const id = idMatch[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1964
+ attrRe = new RegExp(`<[a-zA-Z][^>]*\\bid\\s*=\\s*["']${id}["']`, 'gi');
1965
+ } else if (classMatch) {
1966
+ const cls = classMatch[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1967
+ attrRe = new RegExp(`<[a-zA-Z][^>]*\\bclass\\s*=\\s*["'][^"']*(?<![\\w-])${cls}(?![\\w-])[^"']*["']`, 'gi');
1968
+ }
1969
+ if (!attrRe) return false;
1970
+ let m;
1971
+ while ((m = attrRe.exec(content)) !== null) {
1972
+ if (indexInSourceRanges(m.index, ranges)) return true;
1973
+ }
1974
+ return false;
1975
+ }
1976
+
1977
+ // Small circular indicator bound to an infinite pulse animation — the
1978
+ // decorative "live" dot. Gates: tiny (<= 16px square-ish), round
1979
+ // (border-radius >= 40% or pill values), and an infinite animation whose
1980
+ // keyframes vary opacity/scale/box-shadow (or a pulse/blink/ping name when
1981
+ // the keyframes aren't in the scanned text). Rotation-only animations
1982
+ // (spinners) never flag.
1983
+ //
1984
+ // Declarations for one selector are merged across rule blocks before the
1985
+ // predicate runs: size in the base rule plus the animation added in a
1986
+ // second block (or inside a matching @media block) is the construction
1987
+ // that ships. prefers-reduced-motion: reduce overrides are stripped first
1988
+ // so their animation resets don't mask the default experience. A dot whose
1989
+ // element sits inside a header/nav landmark is the hero liveness cliché
1990
+ // and is promoted to error severity; occurrences elsewhere keep the
1991
+ // registry default severity.
1992
+ function scanCssTextForPulsingDot(content) {
1993
+ const customProps = collectCssCustomProps(content);
1994
+ const keyframes = collectPulseKeyframes(content);
1995
+ const heroRanges = landmarkSourceRanges(content);
1996
+ const findings = [];
1997
+ const seen = new Set();
1998
+
1999
+ // Merge declarations per selector across rule blocks, approximating the
2000
+ // cascade: later declarations for the same property win. Comma lists are
2001
+ // split so `.a, .b { … }` contributes to both selectors. Comments are
2002
+ // stripped first so they neither pollute selector keys nor smuggle a
2003
+ // comma into the selector-list split.
2004
+ const scanText = stripReducedMotionBlocks(content).replace(/\/\*[\s\S]*?\*\//g, ' ');
2005
+ const merged = new Map();
2006
+ const ruleRe = new RegExp(CSS_RULE_BLOCK_SOURCE, 'g');
2007
+ let m;
2008
+ while ((m = ruleRe.exec(scanText)) !== null) {
2009
+ const decls = parseCssDeclBlock(m[2]);
2010
+ if (decls.size === 0) continue;
2011
+ for (const rawSelector of m[1].split(',')) {
2012
+ const selector = rawSelector.trim();
2013
+ if (!selector || selector.startsWith('@')) continue;
2014
+ let acc = merged.get(selector);
2015
+ if (!acc) {
2016
+ acc = new Map();
2017
+ merged.set(selector, acc);
2018
+ }
2019
+ for (const [prop, value] of decls) acc.set(prop, value);
2020
+ }
2021
+ }
2022
+
2023
+ for (const [selector, decls] of merged) {
2024
+ const names = infiniteAnimationNames(decls);
2025
+ if (names.length === 0) continue;
2026
+ const pulseName = names.find(n => {
2027
+ const known = keyframes.get(n);
2028
+ if (known != null) return known;
2029
+ return /pulse|blink|ping/i.test(n);
2030
+ });
2031
+ if (!pulseName) continue;
2032
+
2033
+ const w = cssLengthToPx(resolveVarRefs(
2034
+ decls.get('width') || decls.get('inline-size') || '', customProps));
2035
+ const h = cssLengthToPx(resolveVarRefs(
2036
+ decls.get('height') || decls.get('block-size') || '', customProps));
2037
+ if (w == null || h == null || w < 2 || h < 2 || w > 16 || h > 16) continue;
2038
+
2039
+ const radius = resolveVarRefs(decls.get('border-radius') || '', customProps);
2040
+ if (!isRoundDotRadius(radius, w, h)) continue;
2041
+
2042
+ if (seen.has(selector)) continue;
2043
+ seen.add(selector);
2044
+ const inLandmark = selectorHitsLandmark(content, selector, heroRanges);
2045
+ findings.push({
2046
+ id: 'pulsing-dot',
2047
+ snippet: `${selector} — ${w}x${h}px dot with infinite "${pulseName}" animation${inLandmark ? ' in header/nav' : ''}`,
2048
+ selector,
2049
+ ...(inLandmark ? { severity: 'error' } : {}),
2050
+ });
2051
+ }
2052
+
2053
+ // Tailwind utilities: animate-ping / animate-pulse on a tiny rounded-full
2054
+ // element declared entirely in the class attribute.
2055
+ const classRe = /class\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
2056
+ let cm;
2057
+ while ((cm = classRe.exec(content)) !== null) {
2058
+ const cls = cm[1] || cm[2] || '';
2059
+ const anim = cls.match(/\banimate-(ping|pulse)\b/);
2060
+ if (!anim) continue;
2061
+ if (!/\brounded-full\b/.test(cls)) continue;
2062
+ if (!/\b(?:w|h|size)-(?:1|1\.5|2|2\.5|3|3\.5|4)\b/.test(cls)) continue;
2063
+ const key = `tw:${cls}`;
2064
+ if (seen.has(key)) continue;
2065
+ seen.add(key);
2066
+ const inLandmark = indexInSourceRanges(cm.index, heroRanges);
2067
+ findings.push({
2068
+ id: 'pulsing-dot',
2069
+ snippet: `animate-${anim[1]} on tiny rounded-full element${inLandmark ? ' in header/nav' : ''}`,
2070
+ ...(inLandmark ? { severity: 'error' } : {}),
2071
+ });
2072
+ }
2073
+
2074
+ return findings;
2075
+ }
2076
+
2077
+ // Shape-assembled illustration: a large inline SVG composing a pictorial
2078
+ // scene from many primitive shapes (rect / circle / ellipse / polygon) in
2079
+ // several fill colors — the clip-art hero mascot. Gates keep the legitimate
2080
+ // SVG population out:
2081
+ // • icons and logos: intrinsic size gate (>= 200px on both axes, from
2082
+ // width/height attributes or the viewBox when no explicit size is set)
2083
+ // • charts / labeled diagrams: more than two <text>/<tspan> nodes exempts
2084
+ // the graphic (axis labels, callouts)
2085
+ // • line drawings / technical diagrams: primitive count < 8 or fewer
2086
+ // than 3 distinct fills never qualifies (stroke-only art has no fills)
2087
+ // • tiling background textures: any <pattern> definition exempts
2088
+ function scanHtmlForShapeAssembledIllustration(html) {
2089
+ const findings = [];
2090
+ const svgRe = /<svg\b[^>]*>[\s\S]*?<\/svg>/gi;
2091
+ let m;
2092
+ while ((m = svgRe.exec(html)) !== null) {
2093
+ const block = m[0];
2094
+ const openTag = (block.match(/^<svg\b[^>]*>/i) || [''])[0];
2095
+
2096
+ // Data-bearing or annotated graphics: axis labels and callout text
2097
+ // mark a chart or diagram, not a mascot.
2098
+ const textCount = (block.match(/<(?:text|tspan)\b/gi) || []).length;
2099
+ if (textCount > 2) continue;
2100
+ // Tiling texture definitions are decorative backgrounds, not scenes.
2101
+ if (/<pattern\b/i.test(block)) continue;
2102
+
2103
+ const primitives = (block.match(/<(?:rect|circle|ellipse|polygon)\b/gi) || []).length;
2104
+ if (primitives < 8) continue;
2105
+
2106
+ // Intrinsic size: explicit width/height attributes win; fall back to
2107
+ // the viewBox box. Percentage or missing sizes stay unresolvable on
2108
+ // that axis and the viewBox speaks for them.
2109
+ const attrDim = (name) => {
2110
+ // (?<![-\w]) keeps compound attributes like stroke-width from
2111
+ // masquerading as the svg's own width.
2112
+ const am = openTag.match(new RegExp(`(?<![-\\w])${name}\\s*=\\s*["']\\s*([\\d.]+)(?:px)?\\s*["']`, 'i'));
2113
+ return am ? parseFloat(am[1]) : null;
2114
+ };
2115
+ const vb = openTag.match(/\bviewBox\s*=\s*["']\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)\s*["']/i);
2116
+ const w = attrDim('width') ?? (vb ? parseFloat(vb[1]) : null);
2117
+ const h = attrDim('height') ?? (vb ? parseFloat(vb[2]) : null);
2118
+ if (w == null || h == null || w < 200 || h < 200) continue;
2119
+
2120
+ // Distinct fill paints (attributes and inline styles), excluding
2121
+ // non-paints. Multiple fills are what turn a shape pile into a scene.
2122
+ const fills = new Set();
2123
+ for (const fm of block.matchAll(/\bfill\s*[:=]\s*["']?\s*([^"';>}\s]+)/gi)) {
2124
+ const paint = fm[1].trim().toLowerCase();
2125
+ if (!paint || ['none', 'transparent', 'currentcolor', 'inherit'].includes(paint)) continue;
2126
+ fills.add(paint);
2127
+ }
2128
+ if (fills.size < 3) continue;
2129
+
2130
+ findings.push({
2131
+ id: 'shape-assembled-illustration',
2132
+ snippet: `inline <svg> scene: ${primitives} primitive shapes, ~${Math.round(w)}x${Math.round(h)}px, ${fills.size} fill colors`,
2133
+ });
2134
+ }
2135
+ return findings;
2136
+ }
2137
+
1052
2138
  /**
1053
2139
  * Regex-on-HTML checks shared between browser and Node page-level detection.
1054
2140
  * These don't need DOM access, just the raw HTML string.
@@ -1082,6 +2168,16 @@ function checkHtmlPatterns(html) {
1082
2168
  findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
1083
2169
  }
1084
2170
 
2171
+ // --- Borders ---
2172
+
2173
+ // Side-tab accent stripe drawn as an absolutely-positioned pseudo-element
2174
+ // (no border property involved, so the element-level border checks and
2175
+ // the border-left regexes never see it).
2176
+ findings.push(...scanCssTextForPseudoStripe(html));
2177
+
2178
+ // Side-tab accent stripe drawn as a single-edge inset box-shadow.
2179
+ findings.push(...scanCssTextForInsetStripe(html));
2180
+
1085
2181
  // --- Layout ---
1086
2182
 
1087
2183
  // Monotonous spacing
@@ -1157,33 +2253,34 @@ function checkHtmlPatterns(html) {
1157
2253
  }
1158
2254
  }
1159
2255
 
1160
- // --- Dark glow ---
2256
+ // Pulsing status dots (tiny circular elements on infinite pulse animations)
2257
+ findings.push(...scanCssTextForPulsingDot(html));
1161
2258
 
1162
- const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
1163
- const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
1164
- if (darkBgRe.test(html) || twDarkBg.test(html)) {
1165
- const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
1166
- let shm;
1167
- while ((shm = shadowRe.exec(html)) !== null) {
1168
- const val = shm[1];
1169
- const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
1170
- if (!colorMatch) continue;
1171
- const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
1172
- if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
1173
- const pxVals = [...val.matchAll(/(\d+)px|(?<![.\d])\b(0)\b(?![.\d])/g)].map(p => +(p[1] || p[2]));
1174
- if (pxVals.length >= 3 && pxVals[2] > 4) {
1175
- findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
1176
- break;
1177
- }
1178
- }
2259
+ // Shape-assembled illustrations (large pictorial SVGs built from primitives)
2260
+ findings.push(...scanHtmlForShapeAssembledIllustration(html));
2261
+
2262
+ // Auto-scrolling marquees (<marquee> or infinite horizontal loop animations)
2263
+ findings.push(...scanCssTextForMarquee(html));
2264
+
2265
+ // --- Dark glow / chromatic halo shadows ---
2266
+
2267
+ const glowHits = scanCssTextForGlow(html);
2268
+ if (glowHits.length > 0) {
2269
+ findings.push({ id: 'dark-glow', snippet: glowHits[0].snippet });
2270
+ }
2271
+
2272
+ // Radial-gradient background halo (gradient-drawn sibling of dark-glow)
2273
+ const haloHits = scanCssTextForRadialHalo(html);
2274
+ if (haloHits.length > 0) {
2275
+ findings.push({ id: 'radial-halo', snippet: haloHits[0].snippet });
1179
2276
  }
1180
2277
 
1181
- // --- Provider tells (gated): repeating-gradient stripes (GPT) ---
2278
+ // --- Generated-UI tells: repeating-gradient stripes ---
1182
2279
  if (/repeating-(?:linear|radial|conic)-gradient\s*\(/i.test(html)) {
1183
2280
  findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
1184
2281
  }
1185
2282
 
1186
- // --- Provider tells (gated): two-axis grid-line background (Codex/GPT) ---
2283
+ // --- Generated-UI tells: two-axis grid-line background ---
1187
2284
  // The Codex grid tell is two hairline `linear-gradient(... <color> 1px,
1188
2285
  // transparent 1px)` layers (one per axis) tiled by a repeating
1189
2286
  // `background-size` cell. Both signals must co-occur in the SAME style block
@@ -1196,30 +2293,12 @@ function checkHtmlPatterns(html) {
1196
2293
  // in for the second axis. Colors like `oklch(96% 0.012 82 / 0.055)` carry
1197
2294
  // nested parens, so match the hairline stop directly rather than parsing
1198
2295
  // whole gradient layers.
1199
- {
1200
- const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
1201
- const gridSizeRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
1202
- const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
1203
- const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
1204
- let blk;
1205
- while ((blk = blockRe.exec(html)) !== null) {
1206
- const block = blk[1] || blk[2] || blk[3] || '';
1207
- if (!gridSizeRe.test(block)) continue;
1208
- let hairlineCount = 0;
1209
- let bm;
1210
- bgDeclRe.lastIndex = 0;
1211
- while ((bm = bgDeclRe.exec(block)) !== null) {
1212
- const stops = bm[1].match(hairlineRe);
1213
- if (stops) hairlineCount += stops.length;
1214
- }
1215
- if (hairlineCount >= 2) {
1216
- findings.push({ id: 'codex-grid-background', snippet: 'two-axis grid-line gradient background' });
1217
- break;
1218
- }
1219
- }
2296
+ const gridHits = scanCssTextForGridBackground(html);
2297
+ if (gridHits.length > 0) {
2298
+ findings.push({ id: 'codex-grid-background', snippet: gridHits[0].snippet });
1220
2299
  }
1221
2300
 
1222
- // --- Provider tells (gated): "X theater" framing copy (GPT) ---
2301
+ // --- Generated-copy tells: "X theater" framing copy ---
1223
2302
  // Lives here (regex-on-HTML) rather than in the text-content analyzers so it
1224
2303
  // runs in the bundled browser path too, not just the CLI/static path.
1225
2304
  {
@@ -1231,7 +2310,7 @@ function checkHtmlPatterns(html) {
1231
2310
  if (tm) findings.push({ id: 'theater-slop-phrase', snippet: `"${tm[0].trim()}"` });
1232
2311
  }
1233
2312
 
1234
- // --- Provider tells (gated): image hover transform (Gemini) ---
2313
+ // --- Generated-UI tells: image hover transform ---
1235
2314
  // A CSS `img...:hover { transform: ... }` rule, or a Tailwind hover:scale /
1236
2315
  // hover:rotate / hover:translate utility on an <img>. Each distinct
1237
2316
  // mechanism is its own finding.
@@ -1260,7 +2339,11 @@ function checkHtmlPatterns(html) {
1260
2339
  // `background: #abc`. Real browsers always decompose, so the fallback is
1261
2340
  // a no-op there.
1262
2341
  function readOwnBackgroundColor(el, computedStyle) {
1263
- const bg = parseRgb(computedStyle.backgroundColor);
2342
+ // Real browsers keep wide-gamut/computed color functions (oklch(), oklab(),
2343
+ // color-mix() results) in getComputedStyle output, which plain parseRgb
2344
+ // misses — a flat oklch button background would silently skip every
2345
+ // contrast check without the parseAnyColor fallback.
2346
+ const bg = parseRgb(computedStyle.backgroundColor) || parseAnyColor(computedStyle.backgroundColor);
1264
2347
  if (DETECTOR_IS_BROWSER || (bg && bg.a >= 0.1)) return bg;
1265
2348
  const rawStyle = el.getAttribute?.('style') || '';
1266
2349
  const bgMatch = rawStyle.match(/background(?:-color)?\s*:\s*([^;]+)/i);
@@ -1282,6 +2365,18 @@ function readOwnBackgroundColor(el, computedStyle) {
1282
2365
 
1283
2366
  function resolveBackground(el, win, customPropMap) {
1284
2367
  let current = el;
2368
+ // Translucent layers (0.1 < a < 1) found on the way down to an opaque
2369
+ // base. A browser composites these over the base; the old behavior
2370
+ // either returned them as-if-opaque (browser mode) or skipped them
2371
+ // entirely (static mode), both of which misstate the effective surface
2372
+ // for contrast checks (e.g. `background: color-mix(in oklab, var(--hot)
2373
+ // 16%, transparent)` chips on dark pages).
2374
+ const overlays = [];
2375
+ const flatten = (base) => {
2376
+ let acc = base;
2377
+ for (let i = overlays.length - 1; i >= 0; i--) acc = compositeColorOver(overlays[i], acc);
2378
+ return acc;
2379
+ };
1285
2380
  while (current && current.nodeType === 1) {
1286
2381
  const style = DETECTOR_IS_BROWSER ? getComputedStyle(current) : win.getComputedStyle(current);
1287
2382
  const bgImage = style.backgroundImage || '';
@@ -1294,7 +2389,9 @@ function resolveBackground(el, win, customPropMap) {
1294
2389
  // decorative. The old behavior bailed on any gradient ancestor, which
1295
2390
  // caused massive false-positive contrast findings on grain-textured
1296
2391
  // body backgrounds.
1297
- let bg = parseRgb(style.backgroundColor);
2392
+ // Real browsers serialize wide-gamut computed values as oklab()/oklch()
2393
+ // (e.g. any color-mix() result), which plain parseRgb misses.
2394
+ let bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
1298
2395
  if (!DETECTOR_IS_BROWSER && (!bg || bg.a < 0.1)) {
1299
2396
  // jsdom returns literal "var(--X)" / "oklch(...)" strings. Resolve
1300
2397
  // through customPropMap so Tailwind v4 color tokens become RGB.
@@ -1314,7 +2411,8 @@ function resolveBackground(el, win, customPropMap) {
1314
2411
  }
1315
2412
 
1316
2413
  if (bg && bg.a > 0.1) {
1317
- if (DETECTOR_IS_BROWSER || bg.a >= 0.5) return bg;
2414
+ if (bg.a >= 0.99) return flatten(bg);
2415
+ overlays.push(bg);
1318
2416
  }
1319
2417
  // No solid bg-color at this level. If THIS level has a gradient/url
1320
2418
  // with no underlying solid color we can read:
@@ -1330,13 +2428,13 @@ function resolveBackground(el, win, customPropMap) {
1330
2428
  // bgs worth checking against).
1331
2429
  if (hasGradientOrUrl) {
1332
2430
  if (current.tagName === 'BODY' || current.tagName === 'HTML') {
1333
- return { r: 255, g: 255, b: 255, a: 1 };
2431
+ return flatten({ r: 255, g: 255, b: 255, a: 1 });
1334
2432
  }
1335
2433
  return null;
1336
2434
  }
1337
2435
  current = current.parentElement;
1338
2436
  }
1339
- return { r: 255, g: 255, b: 255 };
2437
+ return flatten({ r: 255, g: 255, b: 255, a: 1 });
1340
2438
  }
1341
2439
 
1342
2440
  // Walk parents looking for a gradient background and return its color stops.
@@ -1398,6 +2496,43 @@ function resolveBorderRadiusPx(el, style, widthPx, win) {
1398
2496
 
1399
2497
  // Browser adapters — call getComputedStyle/getBoundingClientRect on live DOM
1400
2498
 
2499
+ // Selected-state context for accent stripes. Only an actual selection
2500
+ // marker exempts the stripe as the standard active-item indicator:
2501
+ // aria-selected="true", aria-current (any non-false value), or an
2502
+ // active/current/selected class hint. Tab-strip MEMBERSHIP alone
2503
+ // ([role=tablist]/[role=tab]/.tabs ancestry, aria-selected="false")
2504
+ // deliberately does not — a chromatic stripe repeated on every tab in
2505
+ // the group, or on every menu item, is decoration, not state; the
2506
+ // selected item's own underline stays legal.
2507
+ function isTabContextElement(el) {
2508
+ if (!el) return false;
2509
+ try {
2510
+ if (el.closest?.('[aria-selected="true"], [aria-current]:not([aria-current="false"])')) return true;
2511
+ } catch { /* selector engine differences — fall through to class scan */ }
2512
+ let cur = el, depth = 0;
2513
+ while (cur && cur.nodeType === 1 && depth < 6) {
2514
+ const cls = String(cur.getAttribute?.('class') || cur.className || '');
2515
+ if (/(?:^|[\s_-])(?:active|current|selected)(?:$|[\s_-])/i.test(cls)) return true;
2516
+ cur = cur.parentElement;
2517
+ depth++;
2518
+ }
2519
+ return false;
2520
+ }
2521
+
2522
+ // Status-surface context for accent borders. On a live status/alert region
2523
+ // (role=status|alert|alertdialog|log, or aria-live=polite|assertive) a colored
2524
+ // single-edge border is the established severity-accent convention — a toast,
2525
+ // snackbar, or callout bar — not the decorative side-tab tell. The element
2526
+ // itself or a wrapping live region qualifies. This never fires from the
2527
+ // CSS-only / regex scanners, which have no role information.
2528
+ function isStatusContextElement(el) {
2529
+ if (!el) return false;
2530
+ try {
2531
+ if (el.closest?.('[role="status"], [role="alert"], [role="alertdialog"], [role="log"], [aria-live="polite"], [aria-live="assertive"]')) return true;
2532
+ } catch { /* selector engine differences — fall through */ }
2533
+ return false;
2534
+ }
2535
+
1401
2536
  function checkElementBordersDOM(el) {
1402
2537
  const tag = el.tagName.toLowerCase();
1403
2538
  if (BORDER_SAFE_TAGS.has(tag)) return [];
@@ -1410,7 +2545,105 @@ function checkElementBordersDOM(el) {
1410
2545
  widths[s] = parseFloat(style[`border${s}Width`]) || 0;
1411
2546
  colors[s] = style[`border${s}Color`] || '';
1412
2547
  }
1413
- return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0);
2548
+ const ownBg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
2549
+ return checkBorders(tag, widths, colors, parseFloat(style.borderRadius) || 0, {
2550
+ tabContext: isTabContextElement(el),
2551
+ statusContext: isStatusContextElement(el),
2552
+ badgeLike: !!(ownBg && (ownBg.a ?? 1) > 0.1),
2553
+ });
2554
+ }
2555
+
2556
+ // Browser-side twin of scanCssTextForPseudoStripe. The text scanner reads
2557
+ // stylesheet source, so a stripe whose color only exists at runtime (an
2558
+ // inline per-card custom property, a JS-assigned var) or whose geometry
2559
+ // resolves in layout never matches it. In a real browser the pseudo-element's
2560
+ // computed style carries the actual used color and px geometry — check those
2561
+ // directly. Gates mirror the text scanner: 3-12px thick, chromatic fill,
2562
+ // spanning (nearly) the full edge; corner rounding on the host card is
2563
+ // irrelevant. Exemptions stay narrow: structural/prose tags, real selection
2564
+ // markers (isTabContextElement), and button/link affordances for the
2565
+ // horizontal variant.
2566
+ function checkElementPseudoStripeDOM(el) {
2567
+ const tag = el.tagName.toLowerCase();
2568
+ if (BORDER_SAFE_TAGS.has(tag) || tag === 'summary') return [];
2569
+ if (el.closest?.('nav, blockquote, pre')) return [];
2570
+ if (!isRenderedForBrowserRule(el)) return [];
2571
+ const rect = el.getBoundingClientRect();
2572
+ if (rect.width < 40 || rect.height < 20) return [];
2573
+ if (isTabContextElement(el)) return [];
2574
+
2575
+ const findings = [];
2576
+ for (const which of ['::before', '::after']) {
2577
+ let ps;
2578
+ try { ps = getComputedStyle(el, which); } catch { continue; }
2579
+ if (!ps || ps.content === 'none' || ps.content === '') continue;
2580
+ if (ps.position !== 'absolute' && ps.position !== 'fixed') continue;
2581
+ if ((parseFloat(ps.opacity) || 0) <= 0.01 || ps.display === 'none') continue;
2582
+ const w = parseFloat(ps.width) || 0;
2583
+ const h = parseFloat(ps.height) || 0;
2584
+ if (!(w > 0 && h > 0)) continue;
2585
+
2586
+ // Used values: for absolutely-positioned boxes the browser resolves
2587
+ // both edge offsets after layout, so left/right (and top/bottom) are
2588
+ // real distances, never "auto".
2589
+ const left = parseFloat(ps.left);
2590
+ const right = parseFloat(ps.right);
2591
+ const top = parseFloat(ps.top);
2592
+ const bottom = parseFloat(ps.bottom);
2593
+ const hugs = (v) => Number.isFinite(v) && v >= -2 && v <= 2;
2594
+
2595
+ let edge = null;
2596
+ let thickness = null;
2597
+ // Vertical stripe: narrow box spanning (nearly) the full height of the
2598
+ // host, hugging its left or right edge. "Nearly" tolerates the floating
2599
+ // variant that backs off each end by a small inset.
2600
+ if (w >= 3 && w <= 12 && h >= rect.height - 44 && h >= rect.height * 0.5) {
2601
+ edge = hugs(left) ? 'left' : hugs(right) ? 'right' : null;
2602
+ thickness = w;
2603
+ }
2604
+ // Horizontal stripe riding the top or bottom edge. Button/link-styled
2605
+ // hosts keep their underline affordances.
2606
+ if (!edge && h >= 3 && h <= 12 && w >= rect.width - 44 && w >= rect.width * 0.5) {
2607
+ const cls = String(el.getAttribute?.('class') || el.className || '');
2608
+ if (!/(?:^|[\s_-])(?:btn|button|link)(?:$|[\s\w_-])/i.test(cls)) {
2609
+ edge = hugs(top) ? 'top' : hugs(bottom) ? 'bottom' : null;
2610
+ thickness = h;
2611
+ }
2612
+ }
2613
+ if (!edge) continue;
2614
+
2615
+ const bg = parseRgb(ps.backgroundColor) || parseAnyColor(ps.backgroundColor);
2616
+ if (!bg || (bg.a ?? 1) < 0.1) continue;
2617
+ if (Math.max(bg.r, bg.g, bg.b) - Math.min(bg.r, bg.g, bg.b) < 30) continue;
2618
+
2619
+ findings.push({
2620
+ id: 'side-tab',
2621
+ snippet: `${classSelector(el)}${which} — absolute ${thickness}px pseudo-element stripe (${edge})`,
2622
+ });
2623
+ }
2624
+ return findings;
2625
+ }
2626
+
2627
+ // Full-cover surface pseudo (browser): a ::before/::after positioned
2628
+ // absolute/fixed whose box covers (nearly) the whole host and carries an
2629
+ // opaque background. That pseudo is the element's visible surface even
2630
+ // though the element's own background-color reads transparent — the nav-CTA
2631
+ // construction that otherwise escapes every own-background contrast gate.
2632
+ function readPseudoSurfaceDOM(el, rect) {
2633
+ for (const which of ['::before', '::after']) {
2634
+ let ps;
2635
+ try { ps = getComputedStyle(el, which); } catch { continue; }
2636
+ if (!ps || ps.content === 'none' || ps.content === '') continue;
2637
+ if (ps.position !== 'absolute' && ps.position !== 'fixed') continue;
2638
+ if (ps.display === 'none' || (parseFloat(ps.opacity) || 1) < 0.9) continue;
2639
+ const w = parseFloat(ps.width) || 0;
2640
+ const h = parseFloat(ps.height) || 0;
2641
+ if (w < rect.width - 4 || h < rect.height - 4) continue;
2642
+ const bg = parseRgb(ps.backgroundColor) || parseAnyColor(ps.backgroundColor);
2643
+ if (!bg || (bg.a ?? 1) < 0.9) continue;
2644
+ return bg;
2645
+ }
2646
+ return null;
1414
2647
  }
1415
2648
 
1416
2649
  function checkElementColorsDOM(el) {
@@ -1423,11 +2656,24 @@ function checkElementColorsDOM(el) {
1423
2656
  const style = getComputedStyle(el);
1424
2657
  const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
1425
2658
  const hasDirectText = directText.trim().length > 0;
1426
- const effectiveBg = resolveBackground(el);
2659
+ let effectiveBg = resolveBackground(el);
2660
+ let ownBg = readOwnBackgroundColor(el, style);
2661
+ if (!ownBg || (ownBg.a ?? 1) <= 0.5) {
2662
+ const pseudoSurface = readPseudoSurfaceDOM(el, rect);
2663
+ if (pseudoSurface) {
2664
+ ownBg = pseudoSurface;
2665
+ effectiveBg = pseudoSurface;
2666
+ }
2667
+ }
1427
2668
  return checkColors({
1428
2669
  tag,
1429
- textColor: parseRgb(style.color),
1430
- bgColor: readOwnBackgroundColor(el, style),
2670
+ // Chrome serializes computed colors specified in modern spaces as
2671
+ // oklch()/oklab() strings; without the parseAnyColor fallback the text
2672
+ // color comes back null and the low-contrast / gray-on-color checks
2673
+ // silently never run (the shipped miss: a nav CTA whose text color was
2674
+ // an oklch token near its own oklch background).
2675
+ textColor: parseRgb(style.color) || parseAnyColor(style.color),
2676
+ bgColor: ownBg,
1431
2677
  effectiveBg,
1432
2678
  effectiveBgStops: effectiveBg ? null : resolveGradientStops(el),
1433
2679
  fontSize: parseFloat(style.fontSize) || 16,
@@ -1488,6 +2734,21 @@ function checkElementItalicSerifDOM(el) {
1488
2734
  });
1489
2735
  }
1490
2736
 
2737
+ function domAccentDashPseudo(el) {
2738
+ for (const which of ['::before', '::after']) {
2739
+ let ps;
2740
+ try { ps = getComputedStyle(el, which); } catch { continue; }
2741
+ if (!ps || ps.content === 'none' || ps.content === '') continue;
2742
+ const w = parseFloat(ps.width) || 0;
2743
+ const h = parseFloat(ps.height) || 0;
2744
+ if (!(w >= 8 && w <= 80 && h >= 1 && h <= 6)) continue;
2745
+ const bg = parseRgb(ps.backgroundColor) || parseAnyColor(ps.backgroundColor);
2746
+ if (!bg || (bg.a ?? 1) < 0.1) continue;
2747
+ if (Math.max(bg.r, bg.g, bg.b) - Math.min(bg.r, bg.g, bg.b) >= 30) return true;
2748
+ }
2749
+ return false;
2750
+ }
2751
+
1491
2752
  function checkElementHeroEyebrowDOM(el) {
1492
2753
  const tag = el.tagName.toLowerCase();
1493
2754
  if (tag !== 'h1') return [];
@@ -1499,6 +2760,7 @@ function checkElementHeroEyebrowDOM(el) {
1499
2760
  headingTag: tag,
1500
2761
  headingText: el.textContent || '',
1501
2762
  headingFontSize: parseFloat(headStyle.fontSize) || 0,
2763
+ headingInApplicationContext: !!el.closest('[role="tabpanel"], [role="dialog"], [role="application"], dialog'),
1502
2764
  siblingTag: sibling.tagName.toLowerCase(),
1503
2765
  siblingText: sibling.textContent || '',
1504
2766
  siblingTextTransform: sibStyle.textTransform || '',
@@ -1506,6 +2768,7 @@ function checkElementHeroEyebrowDOM(el) {
1506
2768
  siblingLetterSpacing: parseFloat(sibStyle.letterSpacing) || 0,
1507
2769
  siblingFontWeight: sibStyle.fontWeight || '',
1508
2770
  siblingColor: sibStyle.color || '',
2771
+ siblingHasAccentDashPseudo: domAccentDashPseudo(sibling),
1509
2772
  });
1510
2773
  }
1511
2774
 
@@ -1570,8 +2833,10 @@ function resolveVarRefs(raw, customPropMap, depth = 0) {
1570
2833
  // detector's contrast / color checks.
1571
2834
  function oklchToRgb(L, C, H) {
1572
2835
  const hRad = (H * Math.PI) / 180;
1573
- const a = C * Math.cos(hRad);
1574
- const b = C * Math.sin(hRad);
2836
+ return oklabToRgb(L, C * Math.cos(hRad), C * Math.sin(hRad));
2837
+ }
2838
+
2839
+ function oklabToRgb(L, a, b) {
1575
2840
  const l_ = L + 0.3963377774 * a + 0.2158037573 * b;
1576
2841
  const m_ = L - 0.1055613458 * a - 0.0638541728 * b;
1577
2842
  const s_ = L - 0.0894841775 * a - 1.2914855480 * b;
@@ -1591,13 +2856,178 @@ function oklchToRgb(L, C, H) {
1591
2856
  };
1592
2857
  }
1593
2858
 
1594
- // Extended color parser: rgb/rgba/hex/oklch. Returns null on no match.
1595
- // Use this when the input might be any CSS color form; use plain parseRgb
1596
- // when you only expect computed rgb() values from real browsers.
2859
+ function hslToRgb(h, s, l) {
2860
+ h = ((h % 360) + 360) % 360;
2861
+ const c = (1 - Math.abs(2 * l - 1)) * s;
2862
+ const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
2863
+ const m0 = l - c / 2;
2864
+ const [r, g, b] =
2865
+ h < 60 ? [c, x, 0] :
2866
+ h < 120 ? [x, c, 0] :
2867
+ h < 180 ? [0, c, x] :
2868
+ h < 240 ? [0, x, c] :
2869
+ h < 300 ? [x, 0, c] : [c, 0, x];
2870
+ return {
2871
+ r: Math.round((r + m0) * 255),
2872
+ g: Math.round((g + m0) * 255),
2873
+ b: Math.round((b + m0) * 255),
2874
+ a: 1,
2875
+ };
2876
+ }
2877
+
2878
+ function hwbToRgb(h, w, bl) {
2879
+ if (w + bl >= 1) {
2880
+ const g = Math.round((w / (w + bl)) * 255);
2881
+ return { r: g, g, b: g, a: 1 };
2882
+ }
2883
+ const base = hslToRgb(h, 1, 0.5);
2884
+ const mix = (c) => Math.round(((c / 255) * (1 - w - bl) + w) * 255);
2885
+ return { r: mix(base.r), g: mix(base.g), b: mix(base.b), a: 1 };
2886
+ }
2887
+
2888
+ // Common CSS named colors — the handful that actually show up in generated
2889
+ // UIs, not the full 148-name spec list. Includes the achromatic names so a
2890
+ // named gray parses (and correctly reads as no-chroma) instead of being
2891
+ // treated as an unknown color.
2892
+ const CSS_NAMED_COLORS = {
2893
+ black: { r: 0, g: 0, b: 0 },
2894
+ white: { r: 255, g: 255, b: 255 },
2895
+ gray: { r: 128, g: 128, b: 128 },
2896
+ grey: { r: 128, g: 128, b: 128 },
2897
+ silver: { r: 192, g: 192, b: 192 },
2898
+ dimgray: { r: 105, g: 105, b: 105 },
2899
+ darkgray: { r: 169, g: 169, b: 169 },
2900
+ lightgray: { r: 211, g: 211, b: 211 },
2901
+ gainsboro: { r: 220, g: 220, b: 220 },
2902
+ whitesmoke: { r: 245, g: 245, b: 245 },
2903
+ red: { r: 255, g: 0, b: 0 },
2904
+ crimson: { r: 220, g: 20, b: 60 },
2905
+ tomato: { r: 255, g: 99, b: 71 },
2906
+ coral: { r: 255, g: 127, b: 80 },
2907
+ salmon: { r: 250, g: 128, b: 114 },
2908
+ orange: { r: 255, g: 165, b: 0 },
2909
+ gold: { r: 255, g: 215, b: 0 },
2910
+ yellow: { r: 255, g: 255, b: 0 },
2911
+ olive: { r: 128, g: 128, b: 0 },
2912
+ lime: { r: 0, g: 255, b: 0 },
2913
+ green: { r: 0, g: 128, b: 0 },
2914
+ teal: { r: 0, g: 128, b: 128 },
2915
+ turquoise: { r: 64, g: 224, b: 208 },
2916
+ cyan: { r: 0, g: 255, b: 255 },
2917
+ aqua: { r: 0, g: 255, b: 255 },
2918
+ skyblue: { r: 135, g: 206, b: 235 },
2919
+ dodgerblue: { r: 30, g: 144, b: 255 },
2920
+ blue: { r: 0, g: 0, b: 255 },
2921
+ navy: { r: 0, g: 0, b: 128 },
2922
+ indigo: { r: 75, g: 0, b: 130 },
2923
+ rebeccapurple: { r: 102, g: 51, b: 153 },
2924
+ purple: { r: 128, g: 0, b: 128 },
2925
+ violet: { r: 238, g: 130, b: 238 },
2926
+ orchid: { r: 218, g: 112, b: 214 },
2927
+ magenta: { r: 255, g: 0, b: 255 },
2928
+ fuchsia: { r: 255, g: 0, b: 255 },
2929
+ hotpink: { r: 255, g: 105, b: 180 },
2930
+ pink: { r: 255, g: 192, b: 203 },
2931
+ maroon: { r: 128, g: 0, b: 0 },
2932
+ };
2933
+
2934
+ // Split a string on top-level commas (ignoring commas nested in parens).
2935
+ function splitTopLevelCommas(str) {
2936
+ const parts = [];
2937
+ let depth = 0, start = 0;
2938
+ for (let i = 0; i < str.length; i++) {
2939
+ const ch = str[i];
2940
+ if (ch === '(') depth++;
2941
+ else if (ch === ')') depth = Math.max(0, depth - 1);
2942
+ else if (ch === ',' && depth === 0) {
2943
+ parts.push(str.slice(start, i).trim());
2944
+ start = i + 1;
2945
+ }
2946
+ }
2947
+ const tail = str.slice(start).trim();
2948
+ if (tail) parts.push(tail);
2949
+ return parts;
2950
+ }
2951
+
2952
+ // Evaluate a CSS color-mix() expression to {r,g,b,a}. Returns null when
2953
+ // the expression can't be resolved (unresolved var(), unknown colors).
2954
+ //
2955
+ // Mixing is done with premultiplied alpha in sRGB regardless of the
2956
+ // declared interpolation space. That is exact for the dominant generated-UI
2957
+ // pattern — `color-mix(in oklab, <color> N%, transparent)` — where the
2958
+ // result is simply <color> at alpha N% in ANY rectangular space, and a
2959
+ // close-enough approximation for opaque-opaque mixes (the detector only
2960
+ // consumes these values for contrast/chroma thresholds, not for display).
2961
+ function parseColorMix(str) {
2962
+ const m = String(str).trim().match(/^color-mix\(/i);
2963
+ if (!m) return null;
2964
+ // Balanced-paren capture of the arguments.
2965
+ let depth = 0, end = -1;
2966
+ const open = str.indexOf('(');
2967
+ for (let i = open; i < str.length; i++) {
2968
+ if (str[i] === '(') depth++;
2969
+ else if (str[i] === ')') { depth--; if (depth === 0) { end = i; break; } }
2970
+ }
2971
+ if (end < 0) return null;
2972
+ const args = splitTopLevelCommas(str.slice(open + 1, end));
2973
+ if (args.length !== 3 || !/^in\s/i.test(args[0])) return null;
2974
+
2975
+ const parseComponent = (component) => {
2976
+ // Percentage may lead or trail the color per spec.
2977
+ let pct = null;
2978
+ let colorStr = component;
2979
+ const trail = component.match(/\s+([\d.]+)%$/);
2980
+ const lead = component.match(/^([\d.]+)%\s+/);
2981
+ if (trail) { pct = parseFloat(trail[1]); colorStr = component.slice(0, trail.index).trim(); }
2982
+ else if (lead) { pct = parseFloat(lead[1]); colorStr = component.slice(lead[0].length).trim(); }
2983
+ let color;
2984
+ if (/^transparent$/i.test(colorStr)) color = { r: 0, g: 0, b: 0, a: 0 };
2985
+ else color = parseAnyColor(colorStr);
2986
+ if (!color) return null;
2987
+ return { color, pct };
2988
+ };
2989
+
2990
+ const c1 = parseComponent(args[1]);
2991
+ const c2 = parseComponent(args[2]);
2992
+ if (!c1 || !c2) return null;
2993
+ let p1 = c1.pct, p2 = c2.pct;
2994
+ if (p1 == null && p2 == null) { p1 = 50; p2 = 50; }
2995
+ else if (p1 == null) p1 = 100 - p2;
2996
+ else if (p2 == null) p2 = 100 - p1;
2997
+ const sum = p1 + p2;
2998
+ if (sum <= 0) return null;
2999
+ // Per spec: weights normalize to sum; when sum < 100 the result alpha is
3000
+ // additionally scaled by sum/100.
3001
+ const w1 = p1 / sum, w2 = p2 / sum;
3002
+ const alphaScale = sum < 100 ? sum / 100 : 1;
3003
+ const a1 = c1.color.a ?? 1, a2 = c2.color.a ?? 1;
3004
+ const a = (a1 * w1 + a2 * w2) * alphaScale;
3005
+ if (a <= 0) return { r: 0, g: 0, b: 0, a: 0 };
3006
+ const mix = (ch) => Math.round((c1.color[ch] * a1 * w1 + c2.color[ch] * a2 * w2) / (a1 * w1 + a2 * w2));
3007
+ return { r: mix('r'), g: mix('g'), b: mix('b'), a: Math.min(1, a) };
3008
+ }
3009
+
3010
+ // Composite a translucent color over an opaque(ish) base (simple
3011
+ // source-over in sRGB). Returns an opaque {r,g,b,a:1}.
3012
+ function compositeColorOver(top, base) {
3013
+ const a = top.a ?? 1;
3014
+ return {
3015
+ r: Math.round(top.r * a + base.r * (1 - a)),
3016
+ g: Math.round(top.g * a + base.g * (1 - a)),
3017
+ b: Math.round(top.b * a + base.b * (1 - a)),
3018
+ a: 1,
3019
+ };
3020
+ }
3021
+
3022
+ // Extended color parser: rgb/rgba/hex/oklch/oklab/hsl/hwb/color-mix/common
3023
+ // named colors. Returns null on no match. Use this when the input might be
3024
+ // any CSS color form; use plain parseRgb when you only expect computed rgb()
3025
+ // values from real browsers.
1597
3026
  function parseAnyColor(s) {
1598
3027
  if (!s || typeof s !== 'string') return null;
1599
3028
  const str = s.trim();
1600
3029
  if (str === 'transparent' || str === 'currentcolor' || str === 'inherit') return null;
3030
+ if (/^color-mix\(/i.test(str)) return parseColorMix(str);
1601
3031
  let m;
1602
3032
  m = str.match(/rgba?\(\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)\s*,?\s*(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+))?\s*\)/);
1603
3033
  if (m) return { r: Math.round(+m[1]), g: Math.round(+m[2]), b: Math.round(+m[3]), a: m[4] !== undefined ? +m[4] : 1 };
@@ -1635,6 +3065,41 @@ function parseAnyColor(s) {
1635
3065
  }
1636
3066
  return rgb;
1637
3067
  }
3068
+ // OKLAB — a/b are signed axes; percentages map 100% → 0.4.
3069
+ m = str.match(/oklab\(\s*([\d.]+)(%?)\s+(-?[\d.]+)(%?)\s+(-?[\d.]+)(%?)(?:\s*\/\s*([\d.]+)(%)?)?\s*\)/i);
3070
+ if (m) {
3071
+ const L = m[2] === '%' ? parseFloat(m[1]) / 100 : parseFloat(m[1]);
3072
+ const a = m[4] === '%' ? parseFloat(m[3]) * 0.004 : parseFloat(m[3]);
3073
+ const b = m[6] === '%' ? parseFloat(m[5]) * 0.004 : parseFloat(m[5]);
3074
+ const rgb = oklabToRgb(L, a, b);
3075
+ if (m[7] !== undefined) {
3076
+ const alpha = parseFloat(m[7]);
3077
+ rgb.a = m[8] === '%' ? alpha / 100 : alpha;
3078
+ }
3079
+ return rgb;
3080
+ }
3081
+ // HSL/HSLA — comma or space syntax, optional deg on hue.
3082
+ m = str.match(/hsla?\(\s*(-?[\d.]+)(?:deg)?\s*[,\s]\s*([\d.]+)%\s*[,\s]\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+)(%)?)?\s*\)/i);
3083
+ if (m) {
3084
+ const rgb = hslToRgb(parseFloat(m[1]), parseFloat(m[2]) / 100, parseFloat(m[3]) / 100);
3085
+ if (m[4] !== undefined) {
3086
+ const alpha = parseFloat(m[4]);
3087
+ rgb.a = m[5] === '%' ? alpha / 100 : alpha;
3088
+ }
3089
+ return rgb;
3090
+ }
3091
+ // HWB — hue whiteness% blackness%.
3092
+ m = str.match(/hwb\(\s*(-?[\d.]+)(?:deg)?\s+([\d.]+)%\s+([\d.]+)%(?:\s*\/\s*([\d.]+)(%)?)?\s*\)/i);
3093
+ if (m) {
3094
+ const rgb = hwbToRgb(parseFloat(m[1]), parseFloat(m[2]) / 100, parseFloat(m[3]) / 100);
3095
+ if (m[4] !== undefined) {
3096
+ const alpha = parseFloat(m[4]);
3097
+ rgb.a = m[5] === '%' ? alpha / 100 : alpha;
3098
+ }
3099
+ return rgb;
3100
+ }
3101
+ const named = CSS_NAMED_COLORS[str.toLowerCase()];
3102
+ if (named) return { ...named, a: 1 };
1638
3103
  return null;
1639
3104
  }
1640
3105
 
@@ -1718,51 +3183,188 @@ function isRepeatedKickerCandidate(opts) {
1718
3183
  return true;
1719
3184
  }
1720
3185
 
1721
- function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
3186
+ function collectRepeatedSectionKickerCandidates(doc, getStyle, resolveLetterSpacing) {
3187
+ const candidates = [];
3188
+ for (const heading of doc.querySelectorAll('h2, h3, h4')) {
3189
+ if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
3190
+ const kicker = heading.previousElementSibling;
3191
+ if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
3192
+ if (isRepeatedKickerCardContext(heading, kicker)) continue;
3193
+
3194
+ const headingStyle = getStyle(heading);
3195
+ const kickerStyle = getStyle(kicker);
3196
+ const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
3197
+ const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
3198
+ const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
3199
+ const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
3200
+ const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
3201
+
3202
+ if (!isRepeatedKickerCandidate({
3203
+ headingTag: heading.tagName.toLowerCase(),
3204
+ headingText,
3205
+ headingFontSize,
3206
+ kickerTag: kicker.tagName.toLowerCase(),
3207
+ kickerText,
3208
+ kickerTextTransform: kickerStyle.textTransform || '',
3209
+ kickerFontSize,
3210
+ kickerLetterSpacing,
3211
+ })) {
3212
+ continue;
3213
+ }
3214
+
3215
+ candidates.push({
3216
+ headingTag: heading.tagName.toLowerCase(),
3217
+ headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
3218
+ kickerText: kickerText.slice(0, 40),
3219
+ });
3220
+ }
3221
+ return candidates;
3222
+ }
3223
+
3224
+ function checkRepeatedSectionKickersDOM() {
3225
+ const candidates = collectRepeatedSectionKickerCandidates(
3226
+ document,
3227
+ (el) => getComputedStyle(el),
3228
+ (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
3229
+ );
3230
+ return checkRepeatedSectionKickers({ candidates });
3231
+ }
3232
+
3233
+ // ── Numbered section labels ─────────────────────────────────────────────────
3234
+ // Sibling of the repeated-kicker rule: instead of a tracked uppercase word,
3235
+ // the section scaffold is a tiny numeric index riding beside each section
3236
+ // heading — bare and zero-padded, or an index joined to a short micro-label
3237
+ // by a separator glyph. The kicker rule deliberately excludes bare 1-2 digit
3238
+ // labels; this rule owns that shape.
3239
+
3240
+ const NUMBERED_LABEL_TAGS = new Set(['span', 'p', 'div', 'small', 'em', 'strong', 'b']);
3241
+
3242
+ // Returns { index, text } when the trimmed text reads as a section index
3243
+ // label, else null. Two accepted shapes: a zero-padded/two-digit bare index,
3244
+ // or a 1-2 digit index followed by a non-word separator and a short label.
3245
+ function parseNumberedLabelText(rawText) {
3246
+ const text = (rawText || '').replace(/\s+/g, ' ').trim();
3247
+ if (!text || text.length > 40) return null;
3248
+ let m = /^(\d{2})$/.exec(text);
3249
+ if (!m) m = /^(\d{1,2})\s*[^\w\s]\s*\S/.exec(text);
3250
+ if (!m) return null;
3251
+ const index = parseInt(m[1], 10);
3252
+ if (!Number.isFinite(index) || index > 40) return null;
3253
+ return { index, text };
3254
+ }
3255
+
3256
+ function isNumberedSectionLabelCandidate(opts) {
3257
+ const {
3258
+ headingTag, headingText, headingFontSize,
3259
+ labelTag, labelIndex, labelText,
3260
+ labelFontSize, labelLetterSpacing, labelFontWeight,
3261
+ labelFontFamily, labelTextTransform, labelColor,
3262
+ } = opts;
3263
+ if (!['h2', 'h3', 'h4'].includes(headingTag)) return false;
3264
+ if (!headingText || headingText.length < 3) return false;
3265
+ if (!labelTag || !NUMBERED_LABEL_TAGS.has(labelTag)) return false;
3266
+ if (labelIndex == null || !labelText) return false;
3267
+ // Tiny rendered size is the tell — a display-scale section number is a
3268
+ // different (deliberate) device and stays legal.
3269
+ if (!(labelFontSize > 0 && labelFontSize <= 13)) return false;
3270
+ // The heading must be visibly larger where we can resolve its size.
3271
+ // clamp()/var() sizes come back unparseable (0) in the static engine —
3272
+ // the remaining gates carry the check there.
3273
+ if (headingFontSize > 0 && headingFontSize < labelFontSize * 1.3) return false;
3274
+ // Deliberate micro-label styling separates the scaffold from incidental
3275
+ // small text: mono face, bold weight, tracking, uppercase, or accent color.
3276
+ const weight = Number(labelFontWeight) || 400;
3277
+ return /mono/i.test(labelFontFamily || '')
3278
+ || weight >= 600
3279
+ || (labelLetterSpacing || 0) >= 0.5
3280
+ || (labelTextTransform || '') === 'uppercase'
3281
+ || isAccentColor(labelColor || '');
3282
+ }
3283
+
3284
+ function collectNumberedSectionLabelCandidates(doc, getStyle, resolveLetterSpacing) {
1722
3285
  const candidates = [];
3286
+ const seenLabels = new Set();
1723
3287
  for (const heading of doc.querySelectorAll('h2, h3, h4')) {
1724
3288
  if (heading.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
1725
- const kicker = heading.previousElementSibling;
1726
- if (!kicker || kicker.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
1727
- if (isRepeatedKickerCardContext(heading, kicker)) continue;
3289
+ // The index sits either directly before the heading, or before the
3290
+ // wrapper the heading leads (label | <div><h2>…</h2>…</div>).
3291
+ let label = heading.previousElementSibling;
3292
+ if (!label) {
3293
+ const parent = heading.parentElement;
3294
+ const firstChild = parent?.children?.[0];
3295
+ if (firstChild === heading) label = parent.previousElementSibling;
3296
+ }
3297
+ if (!label || seenLabels.has(label)) continue;
3298
+ if (label.closest?.(REPEATED_KICKER_SKIP_SELECTOR)) continue;
3299
+ if (HEADING_TAGS.has(label.tagName.toLowerCase())) continue;
3300
+ if (isRepeatedKickerCardContext(heading, label)) continue;
3301
+
3302
+ const labelText = cleanInlineText(label) || (label.textContent || '').replace(/\s+/g, ' ').trim();
3303
+ const parsed = parseNumberedLabelText(labelText);
3304
+ if (!parsed) continue;
1728
3305
 
1729
3306
  const headingStyle = getStyle(heading);
1730
- const kickerStyle = getStyle(kicker);
3307
+ const labelStyle = getStyle(label);
1731
3308
  const headingText = (heading.textContent || '').replace(/\s+/g, ' ').trim();
1732
- const kickerText = cleanInlineText(kicker) || (kicker.textContent || '').replace(/\s+/g, ' ').trim();
1733
3309
  const headingFontSize = resolveLetterSpacing(headingStyle.fontSize || '', 16) || parseFloat(headingStyle.fontSize) || 0;
1734
- const kickerFontSize = resolveLetterSpacing(kickerStyle.fontSize || '', 16) || parseFloat(kickerStyle.fontSize) || 0;
1735
- const kickerLetterSpacing = resolveLetterSpacing(kickerStyle.letterSpacing || '', kickerFontSize);
3310
+ const labelFontSize = resolveLetterSpacing(labelStyle.fontSize || '', 16) || parseFloat(labelStyle.fontSize) || 0;
1736
3311
 
1737
- if (!isRepeatedKickerCandidate({
3312
+ if (!isNumberedSectionLabelCandidate({
1738
3313
  headingTag: heading.tagName.toLowerCase(),
1739
3314
  headingText,
1740
3315
  headingFontSize,
1741
- kickerTag: kicker.tagName.toLowerCase(),
1742
- kickerText,
1743
- kickerTextTransform: kickerStyle.textTransform || '',
1744
- kickerFontSize,
1745
- kickerLetterSpacing,
3316
+ labelTag: label.tagName.toLowerCase(),
3317
+ labelIndex: parsed.index,
3318
+ labelText: parsed.text,
3319
+ labelFontSize,
3320
+ labelLetterSpacing: resolveLetterSpacing(labelStyle.letterSpacing || '', labelFontSize),
3321
+ labelFontWeight: labelStyle.fontWeight || '',
3322
+ labelFontFamily: labelStyle.fontFamily || '',
3323
+ labelTextTransform: labelStyle.textTransform || '',
3324
+ labelColor: labelStyle.color || '',
1746
3325
  })) {
1747
3326
  continue;
1748
3327
  }
1749
3328
 
3329
+ seenLabels.add(label);
1750
3330
  candidates.push({
3331
+ index: parsed.index,
3332
+ labelText: parsed.text.slice(0, 24),
1751
3333
  headingTag: heading.tagName.toLowerCase(),
1752
3334
  headingText: headingText.replace(/^"|"$/g, '').slice(0, 60),
1753
- kickerText: kickerText.slice(0, 40),
1754
3335
  });
1755
3336
  }
1756
3337
  return candidates;
1757
3338
  }
1758
3339
 
1759
- function checkRepeatedSectionKickersDOM() {
1760
- const candidates = collectRepeatedSectionKickerCandidates(
3340
+ function checkNumberedSectionLabels(opts) {
3341
+ const { candidates, minCount = 2 } = opts;
3342
+ if (!Array.isArray(candidates) || candidates.length < minCount) return [];
3343
+ // A repeated identical number is some other device; the scaffold counts up.
3344
+ const distinctIndices = new Set(candidates.map(c => c.index));
3345
+ if (distinctIndices.size < 2) return [];
3346
+ return candidates.map(candidate => ({
3347
+ id: 'numbered-section-labels',
3348
+ snippet: `tiny numbered label "${candidate.labelText}" beside ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
3349
+ }));
3350
+ }
3351
+
3352
+ function checkNumberedSectionLabelsFromDoc(doc, win) {
3353
+ const candidates = collectNumberedSectionLabelCandidates(
3354
+ doc,
3355
+ (el) => win.getComputedStyle(el),
3356
+ (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
3357
+ );
3358
+ return checkNumberedSectionLabels({ candidates });
3359
+ }
3360
+
3361
+ function checkNumberedSectionLabelsDOM() {
3362
+ const candidates = collectNumberedSectionLabelCandidates(
1761
3363
  document,
1762
3364
  (el) => getComputedStyle(el),
1763
3365
  (value, fontSize) => resolveLengthPx(value, fontSize) || 0,
1764
3366
  );
1765
- return checkRepeatedSectionKickers({ candidates });
3367
+ return checkNumberedSectionLabels({ candidates });
1766
3368
  }
1767
3369
 
1768
3370
  function checkElementMotionDOM(el) {
@@ -1781,7 +3383,14 @@ function checkElementMotionDOM(el) {
1781
3383
  function checkElementGlowDOM(el) {
1782
3384
  const tag = el.tagName.toLowerCase();
1783
3385
  const style = getComputedStyle(el);
1784
- if (!style.boxShadow || style.boxShadow === 'none') return [];
3386
+ const boxShadow = style.boxShadow && style.boxShadow !== 'none' ? style.boxShadow : '';
3387
+ // text-shadow inherits: only check the element that introduces it, so one
3388
+ // declaration doesn't produce a finding on every descendant.
3389
+ let textShadow = style.textShadow && style.textShadow !== 'none' ? style.textShadow : '';
3390
+ if (textShadow && el.parentElement && getComputedStyle(el.parentElement).textShadow === textShadow) {
3391
+ textShadow = '';
3392
+ }
3393
+ if (!boxShadow && !textShadow) return [];
1785
3394
  // Use parent's background — glow radiates outward, so the surrounding context matters
1786
3395
  // If resolveBackground returns null (gradient), try to infer from the gradient colors
1787
3396
  let parentBg = el.parentElement ? resolveBackground(el.parentElement) : resolveBackground(el);
@@ -1804,7 +3413,7 @@ function checkElementGlowDOM(el) {
1804
3413
  cur = cur.parentElement;
1805
3414
  }
1806
3415
  }
1807
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg: parentBg });
3416
+ return checkGlow({ tag, boxShadow, textShadow, effectiveBg: parentBg });
1808
3417
  }
1809
3418
 
1810
3419
  function checkElementAIPaletteDOM(el) {
@@ -2361,7 +3970,7 @@ function checkElementQuality(el, style, tag, window) {
2361
3970
  return checkQuality({ el, tag, style, hasDirectText, textLen, fontSize, lineHeightPx, letterSpacingPx, rect: null, win: window });
2362
3971
  }
2363
3972
 
2364
- function checkElementBorders(tag, style, overrides, resolvedRadius) {
3973
+ function checkElementBorders(tag, style, overrides, resolvedRadius, el = null) {
2365
3974
  const sides = ['Top', 'Right', 'Bottom', 'Left'];
2366
3975
  const widths = {}, colors = {};
2367
3976
  for (const s of sides) {
@@ -2388,7 +3997,12 @@ function checkElementBorders(tag, style, overrides, resolvedRadius) {
2388
3997
  const radius = resolvedRadius != null
2389
3998
  ? resolvedRadius
2390
3999
  : (parseFloat(style.borderRadius) || 0);
2391
- return checkBorders(tag, widths, colors, radius);
4000
+ const ownBg = parseAnyColor(style.backgroundColor);
4001
+ return checkBorders(tag, widths, colors, radius, {
4002
+ tabContext: isTabContextElement(el),
4003
+ statusContext: isStatusContextElement(el),
4004
+ badgeLike: !!(ownBg && (ownBg.a ?? 1) > 0.1),
4005
+ });
2392
4006
  }
2393
4007
 
2394
4008
  function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInheritRule) {
@@ -2429,12 +4043,32 @@ function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInhe
2429
4043
  }
2430
4044
  }
2431
4045
 
4046
+ // Own background: resolve var()/oklch() tokens through the custom-property
4047
+ // map first (mirrors the textColor path above). Without this a chip whose
4048
+ // background is `var(--sev)` reads as no-own-bg in the static engine and
4049
+ // the styled-control contrast exception never engages.
4050
+ let ownBg = (customPropMap ? parseColorResolved(style.backgroundColor, customPropMap) : null)
4051
+ || readOwnBackgroundColor(el, style);
4052
+
4053
+ // Full-cover surface pseudo (static): the cascade pass marks elements
4054
+ // whose ::before/::after paints an opaque covering surface. When the
4055
+ // element itself has no usable own background, that pseudo is the real
4056
+ // surface for contrast purposes.
4057
+ let finalEffectiveBg = effectiveBg;
4058
+ if ((!ownBg || (ownBg.a ?? 1) <= 0.5) && typeof window.getPseudoSurface === 'function') {
4059
+ const pseudoSurface = window.getPseudoSurface(el);
4060
+ if (pseudoSurface) {
4061
+ ownBg = pseudoSurface;
4062
+ finalEffectiveBg = pseudoSurface;
4063
+ }
4064
+ }
4065
+
2432
4066
  return checkColors({
2433
4067
  tag,
2434
4068
  textColor,
2435
- bgColor: readOwnBackgroundColor(el, style),
2436
- effectiveBg,
2437
- effectiveBgStops: effectiveBg ? null : resolveGradientStops(el, window),
4069
+ bgColor: ownBg,
4070
+ effectiveBg: finalEffectiveBg,
4071
+ effectiveBgStops: finalEffectiveBg ? null : resolveGradientStops(el, window),
2438
4072
  fontSize: parseFloat(style.fontSize) || 16,
2439
4073
  fontWeight: parseInt(style.fontWeight) || 400,
2440
4074
  hasDirectText,
@@ -2445,6 +4079,50 @@ function checkElementColors(el, style, tag, window, customPropMap, hasAnchorInhe
2445
4079
  });
2446
4080
  }
2447
4081
 
4082
+ // Static-engine adapter for hover-state contrast. Relies on the static
4083
+ // cascade's hover pass (css-cascade.mjs) exposing a per-element hover style
4084
+ // via window.getHoverStyle — present only when a :hover rule changed the
4085
+ // element's color or background-color relative to its resting state.
4086
+ function checkElementHoverContrast(el, style, tag, window) {
4087
+ if (typeof window.getHoverStyle !== 'function') return [];
4088
+ const hover = window.getHoverStyle(el);
4089
+ if (!hover) return [];
4090
+
4091
+ const directText = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent).join('');
4092
+ if (directText.trim().length === 0) return [];
4093
+
4094
+ const textColor = parseAnyColor(hover.color);
4095
+ if (!textColor || (textColor.a != null && textColor.a < 1)) return [];
4096
+
4097
+ const restingOwnBg = parseAnyColor(style.backgroundColor);
4098
+ const hoverOwnBg = parseAnyColor(hover.backgroundColor);
4099
+ const ownBg = hoverOwnBg || restingOwnBg;
4100
+
4101
+ // Effective hover background: the element's own hover bg composited over
4102
+ // whatever sits underneath. Bail when the surface can't be resolved to a
4103
+ // solid color — gradient ancestors are handled (as at rest) by the
4104
+ // resting-state check, not duplicated here.
4105
+ let bg = null;
4106
+ if (ownBg && ownBg.a >= 0.99) {
4107
+ bg = ownBg;
4108
+ } else {
4109
+ const under = resolveBackground(el.parentElement || el, window, null);
4110
+ if (!under) return [];
4111
+ bg = ownBg && ownBg.a > 0.1 ? compositeColorOver(ownBg, under) : under;
4112
+ }
4113
+
4114
+ return checkHoverContrast({
4115
+ tag,
4116
+ textColor,
4117
+ bg,
4118
+ ownBgAlpha: ownBg ? ownBg.a ?? 1 : null,
4119
+ fontSize: parseFloat(style.fontSize) || 16,
4120
+ fontWeight: parseInt(style.fontWeight) || 400,
4121
+ hasDirectText: true,
4122
+ isEmojiOnly: isEmojiOnlyText(directText),
4123
+ });
4124
+ }
4125
+
2448
4126
  function checkElementIconTile(el, tag, window) {
2449
4127
  if (!HEADING_TAGS.has(tag)) return [];
2450
4128
  const sibling = el.previousElementSibling;
@@ -2513,7 +4191,8 @@ function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
2513
4191
  return checkHeroEyebrow({
2514
4192
  headingTag: tag,
2515
4193
  headingText: el.textContent || '',
2516
- headingFontSize: parseFloat(headingFontSizeRaw) || 0,
4194
+ headingFontSize: resolveHeroHeadingSizePx(headingFontSizeRaw),
4195
+ headingInApplicationContext: !!el.closest?.('[role="tabpanel"], [role="dialog"], [role="application"], dialog'),
2517
4196
  siblingTag: sibling.tagName.toLowerCase(),
2518
4197
  siblingText: sibling.textContent || '',
2519
4198
  siblingTextTransform: sibStyle.textTransform || '',
@@ -2521,6 +4200,11 @@ function checkElementHeroEyebrow(el, style, tag, window, customPropMap) {
2521
4200
  siblingLetterSpacing: resolveLengthPx(letterSpacingRaw, siblingFontSize) || 0,
2522
4201
  siblingFontWeight: fontWeightRaw || '',
2523
4202
  siblingColor: colorRaw || '',
4203
+ // Static cascade marks elements matched by a ::before/::after rule
4204
+ // whose geometry is a short chromatic dash (css-cascade.mjs).
4205
+ siblingHasAccentDashPseudo: typeof window.hasAccentDashPseudo === 'function'
4206
+ ? window.hasAccentDashPseudo(sibling)
4207
+ : false,
2524
4208
  });
2525
4209
  }
2526
4210
 
@@ -2544,8 +4228,10 @@ function checkElementMotion(tag, style) {
2544
4228
  }
2545
4229
 
2546
4230
  function checkElementGlow(tag, style, effectiveBg) {
2547
- if (!style.boxShadow || style.boxShadow === 'none') return [];
2548
- return checkGlow({ tag, boxShadow: style.boxShadow, effectiveBg });
4231
+ const boxShadow = style.boxShadow && style.boxShadow !== 'none' ? style.boxShadow : '';
4232
+ const textShadow = style.textShadow && style.textShadow !== 'none' ? style.textShadow : '';
4233
+ if (!boxShadow && !textShadow) return [];
4234
+ return checkGlow({ tag, boxShadow, textShadow, effectiveBg });
2549
4235
  }
2550
4236
 
2551
4237
  // ─── Section 6: Page-Level Checks ───────────────────────────────────────────
@@ -2655,6 +4341,157 @@ function checkLayout() {
2655
4341
  return findings;
2656
4342
  }
2657
4343
 
4344
+ // Heading rhythm (browser-only): a heading binds to the content it
4345
+ // introduces, so its rendered space above must exceed its space below.
4346
+ // Margins alone can't be trusted (collapsing, flex rows, section padding),
4347
+ // so this measures actual getBoundingClientRect gaps between the heading
4348
+ // and the nearest content genuinely above / below it. Fires only when two
4349
+ // or more headings violate the principle — a single occurrence is noise.
4350
+ function checkHeadingRhythmDOM() {
4351
+ const MIN_VIOLATIONS = 2;
4352
+ const CARD_EXEMPT_HEIGHT = 200;
4353
+ const MAX_BELOW_PX = 160; // beyond this the heading isn't binding to nearby content at all
4354
+ const MIN_DEFICIT_PX = 12;
4355
+
4356
+ function isVisibleFlow(el) {
4357
+ const style = getComputedStyle(el);
4358
+ if (style.display === 'none' || style.visibility === 'hidden') return false;
4359
+ if (parseFloat(style.opacity || '1') <= 0.05) return false;
4360
+ if (style.position === 'absolute' || style.position === 'fixed' || style.position === 'sticky') return false;
4361
+ const rect = el.getBoundingClientRect();
4362
+ return rect.width >= 1 && rect.height >= 1;
4363
+ }
4364
+
4365
+ // Edges only count when they share the heading's column — grid layouts
4366
+ // put content beside a heading, and a far-away element in another column
4367
+ // says nothing about the heading's vertical rhythm.
4368
+ function overlapsX(sr, rect) {
4369
+ return Math.min(sr.right, rect.right) - Math.max(sr.left, rect.left) >= 8;
4370
+ }
4371
+
4372
+ // Does this container draw its own top boundary (background, top border,
4373
+ // shadow)? Crossing out of such a container means the container edge is
4374
+ // the separator above the heading, not raw whitespace — exempt.
4375
+ function hasOwnTopBoundary(el) {
4376
+ const style = getComputedStyle(el);
4377
+ const bg = parseAnyColor(style.backgroundColor || '');
4378
+ if (bg && (bg.a ?? 1) > 0.05) return true;
4379
+ if ((parseFloat(style.borderTopWidth) || 0) > 0) return true;
4380
+ if (style.boxShadow && style.boxShadow !== 'none') return true;
4381
+ return false;
4382
+ }
4383
+
4384
+ // Eyebrows, kickers, and index labels sitting directly on top of a
4385
+ // heading belong to the heading's own cluster — space above is measured
4386
+ // from the top of the cluster, not from the label to the heading.
4387
+ function clusterTop(h, rect) {
4388
+ const headingFontSize = parseFloat(getComputedStyle(h).fontSize) || 16;
4389
+ let topEl = h;
4390
+ let top = rect.top;
4391
+ for (let i = 0; i < 3; i++) {
4392
+ const sib = topEl.previousElementSibling;
4393
+ if (!sib || !isVisibleFlow(sib)) break;
4394
+ const sr = sib.getBoundingClientRect();
4395
+ if (!overlapsX(sr, rect)) break;
4396
+ const gap = top - sr.bottom;
4397
+ if (gap < 0 || gap >= 28 || sr.height > 60) break;
4398
+ const text = (sib.textContent || '').trim();
4399
+ const sibFontSize = parseFloat(getComputedStyle(sib).fontSize) || 16;
4400
+ const labelLike = sibFontSize < headingFontSize * 0.75 || text.length <= 40;
4401
+ if (!labelLike || text.length > 80) break;
4402
+ topEl = sib;
4403
+ top = sr.top;
4404
+ }
4405
+ return { topEl, top };
4406
+ }
4407
+
4408
+ // Nearest content edge strictly above the heading cluster. Walks
4409
+ // previous siblings, then out through ancestors. Skips elements that
4410
+ // vertically overlap (flex-row companions, sticky rails) or sit in
4411
+ // another column. Returns null when nothing qualifies — first content
4412
+ // on the page, or the top of a visually bounded container.
4413
+ function edgeAbove(startEl, top, rect) {
4414
+ let node = startEl;
4415
+ while (node && node !== document.body) {
4416
+ let sib = node.previousElementSibling;
4417
+ while (sib) {
4418
+ if (isVisibleFlow(sib)) {
4419
+ const sr = sib.getBoundingClientRect();
4420
+ if (sr.bottom <= top + 2 && overlapsX(sr, rect)) return sr.bottom;
4421
+ }
4422
+ sib = sib.previousElementSibling;
4423
+ }
4424
+ const parent = node.parentElement;
4425
+ if (!parent || parent === document.body) return null;
4426
+ // Leaving a container upward: if it draws its own top edge, that
4427
+ // edge separates the heading from whatever sits above.
4428
+ if (hasOwnTopBoundary(parent)) return null;
4429
+ node = parent;
4430
+ }
4431
+ return null;
4432
+ }
4433
+
4434
+ // Nearest content edge strictly below the heading — the block the
4435
+ // heading introduces. Crosses wrappers freely (headings often share a
4436
+ // row wrapper with an eyebrow or index label).
4437
+ function edgeBelow(h, rect) {
4438
+ let node = h;
4439
+ while (node && node !== document.body) {
4440
+ let sib = node.nextElementSibling;
4441
+ while (sib) {
4442
+ if (isVisibleFlow(sib)) {
4443
+ const sr = sib.getBoundingClientRect();
4444
+ if (sr.top >= rect.bottom - 2 && overlapsX(sr, rect)) return sr.top;
4445
+ }
4446
+ sib = sib.nextElementSibling;
4447
+ }
4448
+ node = node.parentElement;
4449
+ }
4450
+ return null;
4451
+ }
4452
+
4453
+ function insideSmallCard(h) {
4454
+ let cur = h.parentElement;
4455
+ while (cur && cur !== document.body) {
4456
+ if (isCardLikeDOM(cur)) {
4457
+ const cr = cur.getBoundingClientRect();
4458
+ if (cr.height < CARD_EXEMPT_HEIGHT) return true;
4459
+ }
4460
+ cur = cur.parentElement;
4461
+ }
4462
+ return false;
4463
+ }
4464
+
4465
+ const candidates = [];
4466
+ for (const h of document.querySelectorAll('h2, h3, h4')) {
4467
+ if (!isVisibleFlow(h)) continue;
4468
+ const text = (h.textContent || '').trim().replace(/\s+/g, ' ');
4469
+ if (text.length < 3) continue;
4470
+ const rect = h.getBoundingClientRect();
4471
+ const belowTop = edgeBelow(h, rect);
4472
+ if (belowTop == null) continue; // heading introduces nothing measurable
4473
+ const { topEl, top } = clusterTop(h, rect);
4474
+ const aboveBottom = edgeAbove(topEl, top, rect);
4475
+ if (aboveBottom == null) continue; // first content, or bounded container
4476
+ if (insideSmallCard(h)) continue;
4477
+ const above = Math.max(0, top - aboveBottom);
4478
+ const below = Math.max(0, belowTop - rect.bottom);
4479
+ if (below < 6 || below > MAX_BELOW_PX) continue;
4480
+ // Violation: the space above clearly fails to exceed the space below.
4481
+ // Near-equal gaps are ambiguous rather than inverted, so they pass.
4482
+ if (above < below * 0.75 && below - above >= MIN_DEFICIT_PX) {
4483
+ candidates.push({ el: h, tag: h.tagName.toLowerCase(), text: text.slice(0, 60), above, below });
4484
+ }
4485
+ }
4486
+
4487
+ if (candidates.length < MIN_VIOLATIONS) return [];
4488
+ return candidates.map(c => ({
4489
+ type: 'heading-rhythm',
4490
+ detail: `${c.tag} "${c.text}" has ${Math.round(c.above)}px above vs ${Math.round(c.below)}px below — it reads as bound to the block above (${candidates.length} headings on page)`,
4491
+ el: c.el,
4492
+ }));
4493
+ }
4494
+
2658
4495
  // Node page-level checks — take document/window as parameters
2659
4496
 
2660
4497
  function checkPageTypography(doc, win) {
@@ -2682,14 +4519,9 @@ function checkPageTypography(doc, win) {
2682
4519
 
2683
4520
  // Check Google Fonts links in HTML
2684
4521
  const html = doc.documentElement?.outerHTML || '';
2685
- const gfRe = /fonts\.googleapis\.com\/css2?\?family=([^&"'\s]+)/gi;
2686
- let m;
2687
- while ((m = gfRe.exec(html)) !== null) {
2688
- const families = m[1].split('|').map(f => f.split(':')[0].replace(/\+/g, ' ').toLowerCase());
2689
- for (const f of families) {
2690
- fonts.add(f);
2691
- if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
2692
- }
4522
+ for (const f of extractGoogleFontFamilies(html)) {
4523
+ fonts.add(f);
4524
+ if (OVERUSED_FONTS.has(f)) overusedFound.add(f);
2693
4525
  }
2694
4526
 
2695
4527
  // Also parse raw HTML/style content for font-family (jsdom may not expose all via CSSOM)
@@ -2802,6 +4634,135 @@ function checkPageLayout(doc, win) {
2802
4634
  return findings;
2803
4635
  }
2804
4636
 
4637
+ // ── Repeated text inside one container ──────────────────────────────────────
4638
+ // The same literal string rendered 3+ times in structurally different spots
4639
+ // inside one bordered/elevated container — typically a status word wired
4640
+ // into every slot of a card template. Legitimate repetition is structural:
4641
+ // table columns, calendar grids, nav/menu lists, and templated sibling rows
4642
+ // all repeat text in *parallel* positions, so occurrences whose element
4643
+ // paths inside the container are identical (or live in dedicated repetition
4644
+ // structures) never count. Only 3+ occurrences at 3+ distinct structural
4645
+ // positions flag.
4646
+
4647
+ const REPEATED_TEXT_SKIP_SELECTOR = [
4648
+ 'table',
4649
+ 'select',
4650
+ 'datalist',
4651
+ 'nav',
4652
+ 'menu',
4653
+ '[role="navigation"]',
4654
+ '[role="menu"]',
4655
+ '[role="menubar"]',
4656
+ '[role="listbox"]',
4657
+ '[role="grid"]',
4658
+ '[role="tablist"]',
4659
+ '[role="radiogroup"]',
4660
+ '[aria-hidden="true"]',
4661
+ ].join(',');
4662
+
4663
+ const REPEATED_TEXT_CONTAINER_TAGS = new Set([
4664
+ 'div', 'section', 'article', 'aside', 'main', 'figure', 'form', 'fieldset', 'details', 'li',
4665
+ ]);
4666
+
4667
+ // A container worth attributing text to: visibly bounded (border on most
4668
+ // sides or an elevation shadow) and surface-like (radius or own background).
4669
+ function isRepeatedTextContainer(style) {
4670
+ if (!style) return false;
4671
+ const hasShadow = !!(style.boxShadow && style.boxShadow !== 'none' && style.boxShadow !== '');
4672
+ const borderSides = ['Top', 'Right', 'Bottom', 'Left']
4673
+ .filter(side => (parseFloat(style[`border${side}Width`]) || 0) >= 1).length;
4674
+ const hasBorder = borderSides >= 3;
4675
+ const hasRadius = (parseFloat(style.borderRadius) || 0) > 0;
4676
+ const bg = parseRgb(style.backgroundColor) || parseAnyColor(style.backgroundColor);
4677
+ const hasBg = !!(bg && (bg.a ?? 1) > 0.1);
4678
+ return isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg);
4679
+ }
4680
+
4681
+ function collectRepeatedContainerTextFindings(doc, getStyle, opts = {}) {
4682
+ const isVisible = opts.isVisible || (() => true);
4683
+ const findings = [];
4684
+
4685
+ const containers = [];
4686
+ const containerSet = new Set();
4687
+ for (const el of doc.querySelectorAll('*')) {
4688
+ if (!REPEATED_TEXT_CONTAINER_TAGS.has(el.tagName.toLowerCase())) continue;
4689
+ if (el.closest?.(REPEATED_TEXT_SKIP_SELECTOR)) continue;
4690
+ if (!isRepeatedTextContainer(getStyle(el))) continue;
4691
+ containers.push(el);
4692
+ containerSet.add(el);
4693
+ }
4694
+
4695
+ for (const container of containers) {
4696
+ if (!isVisible(container)) continue;
4697
+ const descendants = container.querySelectorAll('*');
4698
+ // Page-scale wrappers that merely happen to carry a background are not
4699
+ // the "one card" this rule reasons about.
4700
+ if (descendants.length > 250) continue;
4701
+
4702
+ const groups = new Map();
4703
+ for (const d of descendants) {
4704
+ // Attribute text to the innermost container only.
4705
+ let anc = d.parentElement;
4706
+ let ownedByInner = false;
4707
+ while (anc && anc !== container) {
4708
+ if (containerSet.has(anc)) { ownedByInner = true; break; }
4709
+ anc = anc.parentElement;
4710
+ }
4711
+ if (ownedByInner) continue;
4712
+ if (d.closest?.(REPEATED_TEXT_SKIP_SELECTOR)) continue;
4713
+ // Icon-font glyph names read as text but render as symbols.
4714
+ if (/icon|material-symbols|(?:^|\s)fa[srlbd]?(?:\s|-|$)/i.test(String(d.getAttribute?.('class') || ''))) continue;
4715
+ if (!isVisible(d)) continue;
4716
+
4717
+ const direct = [...d.childNodes]
4718
+ .filter(n => n.nodeType === 3)
4719
+ .map(n => n.textContent)
4720
+ .join(' ')
4721
+ .replace(/\s+/g, ' ')
4722
+ .trim();
4723
+ if (direct.length < 4 || direct.length > 48) continue;
4724
+ if (!/[a-zA-Z]/.test(direct)) continue;
4725
+
4726
+ // Structural signature: the element path from the occurrence up to
4727
+ // the container. Parallel/templated repetition shares one signature.
4728
+ const sig = [];
4729
+ for (let cur = d; cur && cur !== container; cur = cur.parentElement) {
4730
+ const cls = String(cur.getAttribute?.('class') || '')
4731
+ .trim().split(/\s+/).filter(Boolean).sort().join('.');
4732
+ sig.push(cur.tagName.toLowerCase() + (cls ? `.${cls}` : ''));
4733
+ }
4734
+ if (!groups.has(direct)) groups.set(direct, []);
4735
+ groups.get(direct).push(sig.join('>'));
4736
+ }
4737
+
4738
+ for (const [text, sigs] of groups) {
4739
+ if (sigs.length < 3) continue;
4740
+ if (new Set(sigs).size < 3) continue;
4741
+ findings.push({
4742
+ id: 'repeated-container-text',
4743
+ snippet: `"${text.slice(0, 40)}" rendered ${sigs.length}× in distinct spots inside ${classSelector(container)}`,
4744
+ });
4745
+ }
4746
+ }
4747
+ return findings;
4748
+ }
4749
+
4750
+ function checkRepeatedContainerTextFromDoc(doc, win) {
4751
+ return collectRepeatedContainerTextFindings(
4752
+ doc,
4753
+ (el) => win.getComputedStyle(el),
4754
+ { isVisible: (el) => String(win.getComputedStyle(el).display || '') !== 'none' },
4755
+ );
4756
+ }
4757
+
4758
+ function checkRepeatedContainerTextDOM() {
4759
+ return collectRepeatedContainerTextFindings(
4760
+ document,
4761
+ (el) => getComputedStyle(el),
4762
+ { isVisible: isRenderedForBrowserRule },
4763
+ );
4764
+ }
4765
+
2805
4766
  // ─── Cream / beige palette (the default "tasteful" AI surface) ────────────────
2806
4767
  // A warm, lightly-tinted off-white page background — light, with R≥G≥B and a
2807
4768
  // small warm tint (not white, not a strong color). The current reflex surface.
@@ -2915,7 +4876,7 @@ function checkElementOversizedH1DOM(el) {
2915
4876
  return checkOversizedH1({ tag, fontSize, headingText, rect, viewportWidth, viewportHeight });
2916
4877
  }
2917
4878
 
2918
- // ─── GPT tell: hairline border + wide diffuse shadow (gated --gpt) ────────────
4879
+ // ─── Generated-UI tell: hairline border + wide diffuse shadow ────────────────
2919
4880
  const CSS_COLOR_TOKEN_RE = /(?:rgba?|hsla?|oklch|oklab|lab|lch|color)\([^)]*\)|#[0-9a-fA-F]{3,8}\b|\b(?:black|white|transparent|currentcolor)\b/gi;
2920
4881
 
2921
4882
  function shadowLayerAlpha(layer) {
@@ -3240,9 +5201,645 @@ function checkElementTextOverflowDOM(el) {
3240
5201
  if (el.clientWidth > 0 && delta >= 16) {
3241
5202
  return [{ id: 'text-overflow', snippet: `${classSelector(el)} overflows its box by ${Math.round(delta)}px` }];
3242
5203
  }
5204
+
5205
+ // Inline text owners have no client geometry (clientWidth/scrollWidth are
5206
+ // both 0), so the scrollWidth path above never sees them. Their overflow
5207
+ // registers only on a block ancestor, and that ancestor has no direct text
5208
+ // so the ownership gate skips it. (The shipped miss: a nowrap inline
5209
+ // <span> spilling 45px past its fixed-width grid cell.) Measure the inline
5210
+ // box against the padding box of its nearest block container instead.
5211
+ if (el.clientWidth === 0 && rect && rect.width > 0) {
5212
+ let container = el.parentElement;
5213
+ while (container && container.clientWidth === 0) container = container.parentElement;
5214
+ if (!container) return [];
5215
+ // Transforms make rect comparisons lie; skip anything on that path.
5216
+ for (let p = el; p && p !== container.parentElement; p = p.parentElement) {
5217
+ const t = getComputedStyle(p).transform;
5218
+ if (t && t !== 'none') return [];
5219
+ }
5220
+ const cRect = container.getBoundingClientRect();
5221
+ const contentRight = cRect.left + container.clientLeft + container.clientWidth;
5222
+ const spill = rect.right - contentRight;
5223
+ if (spill >= 16) {
5224
+ return [{ id: 'text-overflow', snippet: `${classSelector(el)} overflows its container by ${Math.round(spill)}px` }];
5225
+ }
5226
+ }
3243
5227
  return [];
3244
5228
  }
3245
5229
 
5230
+ // ---------------------------------------------------------------------------
5231
+ // Blinking cursor (browser-only)
5232
+ // ---------------------------------------------------------------------------
5233
+
5234
+ // Block / underscore glyphs commonly used as a fake text cursor.
5235
+ const CURSOR_GLYPH_RE = /^[_|▀-▟■▮❙❚|]$/;
5236
+
5237
+ // How far down the page still counts as the first-viewport / hero region.
5238
+ // Hero compositions regularly run past a literal viewport height, so the
5239
+ // gate is a landing-region budget, not an exact fold line.
5240
+ const CURSOR_FIRST_VIEWPORT_PX = 1200;
5241
+
5242
+ // Do the named @keyframes only toggle visibility (opacity dropping to ~0 or
5243
+ // visibility:hidden), i.e. a blink rather than a fade/move/spin? Walks the
5244
+ // live CSSOM; cross-origin sheets are skipped.
5245
+ function keyframesToggleVisibilityDOM(name) {
5246
+ if (!name) return false;
5247
+ for (const sheet of document.styleSheets) {
5248
+ let rules;
5249
+ try { rules = sheet.cssRules || sheet.rules; } catch { continue; }
5250
+ if (!rules) continue;
5251
+ const stack = [...rules];
5252
+ while (stack.length) {
5253
+ const rule = stack.shift();
5254
+ if (rule.cssRules && rule.type !== 7) { stack.push(...rule.cssRules); continue; }
5255
+ if (rule.type !== 7 || rule.name !== name) continue; // 7 = KEYFRAMES_RULE
5256
+ let togglesOut = false;
5257
+ for (const frame of rule.cssRules || []) {
5258
+ const fs = frame.style;
5259
+ if (!fs) continue;
5260
+ for (let i = 0; i < fs.length; i++) {
5261
+ const prop = fs[i];
5262
+ if (prop === 'opacity') {
5263
+ if ((parseFloat(fs.getPropertyValue('opacity')) || 0) <= 0.15) togglesOut = true;
5264
+ } else if (prop === 'visibility') {
5265
+ if (/hidden/i.test(fs.getPropertyValue('visibility'))) togglesOut = true;
5266
+ } else if (prop !== 'animation-timing-function') {
5267
+ return false; // keyframes animate something else — not a blink
5268
+ }
5269
+ }
5270
+ }
5271
+ return togglesOut;
5272
+ }
5273
+ }
5274
+ return false;
5275
+ }
5276
+
5277
+ // Decorative blinking cursor: a small block / underscore element bound to an
5278
+ // infinite blink animation, sitting in the first-viewport region of a page.
5279
+ // Real editable surfaces (inputs, textareas, contenteditable, role=textbox)
5280
+ // draw their own caret and are exempt. Round pulsing dots stay with the
5281
+ // pulsing-dot rule.
5282
+ function checkElementBlinkingCursorDOM(el) {
5283
+ const tag = el.tagName.toLowerCase();
5284
+ if (['input', 'textarea', 'select', 'img', 'svg', 'script', 'style'].includes(tag)) return [];
5285
+ const style = getComputedStyle(el);
5286
+
5287
+ const iterations = (style.animationIterationCount || '').split(',').map(s => s.trim());
5288
+ if (!iterations.includes('infinite')) return [];
5289
+ const names = (style.animationName || '').split(',').map(s => s.trim()).filter(n => n && n !== 'none');
5290
+ if (names.length === 0) return [];
5291
+ const blinkName = names.find(n => /blink|caret|cursor/i.test(n))
5292
+ || names.find(n => keyframesToggleVisibilityDOM(n));
5293
+ if (!blinkName) return [];
5294
+
5295
+ // Real caret contexts are exempt.
5296
+ if (el.isContentEditable || el.closest('[contenteditable=""], [contenteditable="true"], [role="textbox"]')) return [];
5297
+
5298
+ const rect = el.getBoundingClientRect();
5299
+ if (rect.width <= 0 || rect.height <= 0) return [];
5300
+
5301
+ // First-viewport gate: the hero cliché, not a footer terminal.
5302
+ const pageTop = rect.top + (window.scrollY || 0);
5303
+ if (pageTop > CURSOR_FIRST_VIEWPORT_PX) return [];
5304
+
5305
+ // Cursor shape: a lone block/underscore glyph, or an empty solid
5306
+ // rectangle sized like a text caret (block or underscore form).
5307
+ const text = (el.textContent || '').trim();
5308
+ const glyphCursor = text.length === 1 && CURSOR_GLYPH_RE.test(text);
5309
+ let blockCursor = false;
5310
+ if (!glyphCursor) {
5311
+ if (text.length > 0 || el.childElementCount > 0) return [];
5312
+ const bg = parseAnyColor(style.backgroundColor || '');
5313
+ const filled = bg && (bg.a ?? 1) > 0.2;
5314
+ const hasBorderFill = ['Left', 'Right', 'Bottom'].some(
5315
+ side => (parseFloat(style[`border${side}Width`]) || 0) >= 1,
5316
+ );
5317
+ if (!filled && !hasBorderFill) return [];
5318
+ const vertical = rect.width >= 1 && rect.width <= 24 && rect.height >= 6 && rect.height <= 48 && rect.height >= rect.width;
5319
+ const underscore = rect.height >= 1 && rect.height <= 6 && rect.width >= 4 && rect.width <= 24;
5320
+ if (!vertical && !underscore) return [];
5321
+ // Round dots are the pulsing-dot rule's territory.
5322
+ const radiusPx = parseFloat(style.borderRadius) || 0;
5323
+ if (radiusPx >= 0.4 * Math.min(rect.width, rect.height)) return [];
5324
+ blockCursor = true;
5325
+ }
5326
+ if (!glyphCursor && !blockCursor) return [];
5327
+
5328
+ // Hero-region promotion: a fake caret blinking in the first ~900px or
5329
+ // inside the page chrome is the shipped hero cliché, not an incidental
5330
+ // flourish. Promote those from the registry's advisory to warning;
5331
+ // lower first-viewport occurrences keep the default severity.
5332
+ const inHeroRegion = pageTop <= 900
5333
+ || !!(el.closest && el.closest('header, nav, [role="banner"], [role="navigation"]'));
5334
+ return [{
5335
+ id: 'blinking-cursor',
5336
+ snippet: `${classSelector(el)} — ${Math.round(rect.width)}x${Math.round(rect.height)}px blinking cursor (animation "${blinkName}") in the first viewport`,
5337
+ ...(inHeroRegion ? { severity: 'warning' } : {}),
5338
+ }];
5339
+ }
5340
+
5341
+ // ---------------------------------------------------------------------------
5342
+ // Content invisible at rest (browser-only, driven by the URL engine)
5343
+ // ---------------------------------------------------------------------------
5344
+
5345
+ // Tags whose text never renders, or whose hidden state is legitimate UI
5346
+ // (templates, dialogs, native select options). Text inside them stays out of
5347
+ // both the numerator and the denominator.
5348
+ const HIDDEN_TEXT_EXCLUDE_TAGS = new Set([
5349
+ 'script', 'style', 'noscript', 'template', 'title', 'head', 'meta', 'link',
5350
+ 'option', 'optgroup', 'select', 'datalist', 'dialog',
5351
+ ]);
5352
+
5353
+ // Measure how many text characters currently render invisible (computed
5354
+ // opacity ~0 or visibility hidden anywhere on the ancestor chain) versus
5355
+ // visible. display:none / [hidden] / aria-hidden subtrees are legitimately
5356
+ // hidden UI (menus, tab panels, templates): they are excluded from the
5357
+ // denominator entirely rather than counted as invisible.
5358
+ function measureHiddenTextDOM() {
5359
+ const cache = new Map();
5360
+ function stateOf(el) {
5361
+ if (!el || el.nodeType !== 1 || el === document.documentElement) return 'visible';
5362
+ const cached = cache.get(el);
5363
+ if (cached) return cached;
5364
+ let state;
5365
+ const tag = el.tagName.toLowerCase();
5366
+ if (HIDDEN_TEXT_EXCLUDE_TAGS.has(tag)) {
5367
+ state = 'excluded';
5368
+ } else {
5369
+ const parentState = stateOf(el.parentElement);
5370
+ if (parentState === 'excluded') {
5371
+ state = 'excluded';
5372
+ } else {
5373
+ const style = getComputedStyle(el);
5374
+ if (style.display === 'none' || el.hidden || el.getAttribute('aria-hidden') === 'true'
5375
+ || String(style.contentVisibility || '').toLowerCase() === 'hidden') {
5376
+ state = 'excluded';
5377
+ } else if (parentState === 'invisible'
5378
+ || (parseFloat(style.opacity) || 0) <= 0.02
5379
+ || /^(hidden|collapse)$/.test(style.visibility)) {
5380
+ state = 'invisible';
5381
+ } else {
5382
+ state = 'visible';
5383
+ }
5384
+ }
5385
+ }
5386
+ cache.set(el, state);
5387
+ return state;
5388
+ }
5389
+
5390
+ let totalChars = 0;
5391
+ let hiddenChars = 0;
5392
+ const hiddenSamples = [];
5393
+ for (const el of document.querySelectorAll('body *')) {
5394
+ let len = 0;
5395
+ for (const node of el.childNodes) {
5396
+ if (node.nodeType === 3) len += node.textContent.replace(/\s+/g, ' ').trim().length;
5397
+ }
5398
+ if (!len) continue;
5399
+ const state = stateOf(el);
5400
+ if (state === 'excluded') continue;
5401
+ totalChars += len;
5402
+ if (state === 'invisible') {
5403
+ hiddenChars += len;
5404
+ if (hiddenSamples.length < 3) {
5405
+ const text = String(el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 40);
5406
+ if (text) hiddenSamples.push(text);
5407
+ }
5408
+ }
5409
+ }
5410
+ return { totalChars, hiddenChars, hiddenSamples };
5411
+ }
5412
+
5413
+ // Pure threshold check over a measureHiddenTextDOM() result. The URL engine
5414
+ // calls it AFTER a reveal sweep (scroll through the document so every
5415
+ // IntersectionObserver / scroll reveal had its chance to fire, then back to
5416
+ // the top): a healthy reveal-on-scroll page drops to ~0 invisible text after
5417
+ // the sweep, while a page whose reveal script died keeps most of its text at
5418
+ // opacity 0 forever. Fires only when the invisible share stays above 30%
5419
+ // with a real amount of text behind it.
5420
+ function checkContentHiddenAtRest({ totalChars = 0, hiddenChars = 0, hiddenSamples = [] } = {}) {
5421
+ if (totalChars < 200 || hiddenChars < 150) return [];
5422
+ const share = hiddenChars / totalChars;
5423
+ if (share <= 0.3) return [];
5424
+ const sample = hiddenSamples.length ? ` (e.g. "${hiddenSamples[0]}")` : '';
5425
+ return [{
5426
+ id: 'content-hidden-at-rest',
5427
+ snippet: `${Math.round(share * 100)}% of page text (${hiddenChars} of ${totalChars} chars) stays at opacity 0 / visibility hidden after reveal handlers ran${sample}`,
5428
+ }];
5429
+ }
5430
+
5431
+ // ---------------------------------------------------------------------------
5432
+ // Edge-flush cards in horizontal scrollers (browser-only)
5433
+ // ---------------------------------------------------------------------------
5434
+
5435
+ // A visually-defined card (own opaque background, or borders on 2+ sides)
5436
+ // inside a horizontal scroller, sitting flush against one edge of the
5437
+ // scroller's clip box at rest while keeping a clear gutter on the other
5438
+ // side. The canonical bug: the first snap panel is sized wider than the
5439
+ // scroller, so its cards end exactly at the clip edge with their rounded
5440
+ // corners cut, while every sibling panel keeps its inset. Cards that extend
5441
+ // far past the edge are deliberate peeks and stay exempt.
5442
+ function checkEdgeFlushCardsDOM() {
5443
+ const findings = [];
5444
+ const vh = window.innerHeight || 800;
5445
+ const isScroller = (s) => /(auto|scroll)/.test(s.overflowX || '') || /(auto|scroll)/.test(s.overflow || '');
5446
+
5447
+ for (const scroller of document.querySelectorAll('*')) {
5448
+ const style = getComputedStyle(scroller);
5449
+ if (!isScroller(style)) continue;
5450
+ if (scroller.scrollWidth <= scroller.clientWidth + 8) continue;
5451
+ // At rest only: a user-scrolled or snapped-forward scroller legitimately
5452
+ // shows cut cards at both edges.
5453
+ if (scroller.scrollLeft > 4) continue;
5454
+ const scRect = scroller.getBoundingClientRect();
5455
+ if (scRect.width < 120 || scRect.height < 60) continue;
5456
+ // Landing-region gate: the defect matters where the page opens.
5457
+ if (scRect.top + (window.scrollY || 0) > 2 * vh) continue;
5458
+ const contentLeft = scRect.left + scroller.clientLeft;
5459
+ const contentRight = contentLeft + scroller.clientWidth;
5460
+
5461
+ const flush = [];
5462
+ for (const card of scroller.querySelectorAll('*')) {
5463
+ if (!isRenderedForBrowserRule(card)) continue;
5464
+ // Attribute cards to their nearest scroller only (nested scrollers).
5465
+ let owner = card.parentElement;
5466
+ while (owner && owner !== scroller && !isScroller(getComputedStyle(owner))) owner = owner.parentElement;
5467
+ if (owner !== scroller) continue;
5468
+ const cs = getComputedStyle(card);
5469
+ const rect = card.getBoundingClientRect();
5470
+ if (rect.width < 80 || rect.height < 40) continue;
5471
+ const bg = parseAnyColor(cs.backgroundColor || '');
5472
+ const hasBg = !!(bg && (bg.a ?? 1) > 0.5);
5473
+ const borderSides = ['Top', 'Right', 'Bottom', 'Left']
5474
+ .filter(side => (parseFloat(cs[`border${side}Width`]) || 0) > 0).length;
5475
+ if (!hasBg && borderSides < 2) continue;
5476
+ const leftGutter = rect.left - contentLeft;
5477
+ const rightGap = contentRight - rect.right;
5478
+ // Flush right with a left gutter, or the mirror. The -24 floor keeps
5479
+ // deliberately peeking next-cards (cut mid-card) exempt.
5480
+ const flushRight = leftGutter >= 6 && rightGap < 8 && rightGap > -24;
5481
+ const flushLeft = rightGap >= 6 && leftGutter < 8 && leftGutter > -24;
5482
+ if (!flushRight && !flushLeft) continue;
5483
+ flush.push({ card, edge: flushRight ? 'right' : 'left', gap: Math.round(flushRight ? rightGap : leftGutter) });
5484
+ }
5485
+ if (flush.length === 0) continue;
5486
+ const worst = flush.reduce((a, b) => (b.gap < a.gap ? b : a));
5487
+ findings.push({
5488
+ el: scroller,
5489
+ type: 'edge-flush-cards',
5490
+ detail: `${flush.length} card${flush.length === 1 ? '' : 's'} flush against the ${worst.edge} edge of ${classSelector(scroller)} at rest (${worst.gap}px gap, e.g. ${classSelector(worst.card)})`,
5491
+ });
5492
+ }
5493
+ return findings;
5494
+ }
5495
+
5496
+ // ---------------------------------------------------------------------------
5497
+ // Text occlusion / element overlap (browser-only)
5498
+ // ---------------------------------------------------------------------------
5499
+
5500
+ // An opaque decorated box: a near-solid background fill or two-plus visible
5501
+ // borders make it hide whatever sits behind it. Gradient / image fills are
5502
+ // deliberately excluded — a scrim gradient over hero imagery is a contrast
5503
+ // layer, not an occluder, and belongs to the pixel low-contrast rule.
5504
+ function isOpaqueDecoratedBox(cs) {
5505
+ if (!cs) return false;
5506
+ const bg = parseAnyColor(cs.backgroundColor || '');
5507
+ if (bg && (bg.a ?? 1) > 0.6) return true;
5508
+ const borderSides = ['Top', 'Right', 'Bottom', 'Left'].filter((side) => {
5509
+ if ((parseFloat(cs[`border${side}Width`]) || 0) <= 0) return false;
5510
+ const bc = parseAnyColor(cs[`border${side}Color`] || '');
5511
+ return bc && (bc.a ?? 1) > 0.3;
5512
+ }).length;
5513
+ return borderSides >= 2;
5514
+ }
5515
+
5516
+ // Is this element lifted out of normal flow into a layer that can cover
5517
+ // siblings? Two normal-flow blocks stacked vertically cannot truly hide each
5518
+ // other's ink — an overlap between their rects is line-box bleed from tight
5519
+ // leading (a display headline reaching up over the line before it), not
5520
+ // occlusion. Only out-of-flow positioning (absolute / fixed / sticky) moves an
5521
+ // element off its own row onto the pixels of another; an in-place transform or
5522
+ // relative nudge on a display headline does not.
5523
+ function isLayeredElement(el) {
5524
+ for (let cur = el; cur && cur.nodeType === 1 && cur !== document.body; cur = cur.parentElement) {
5525
+ const pos = String(getComputedStyle(cur).position || 'static');
5526
+ if (pos === 'absolute' || pos === 'fixed' || pos === 'sticky') return true;
5527
+ }
5528
+ return false;
5529
+ }
5530
+
5531
+ function elementDirectText(el) {
5532
+ let t = '';
5533
+ for (const node of el.childNodes || []) {
5534
+ if (node.nodeType === 3) t += node.textContent;
5535
+ }
5536
+ return t.trim();
5537
+ }
5538
+
5539
+ // Rendered gate that, unlike isRenderedForBrowserRule, does NOT exempt
5540
+ // aria-hidden subtrees: a decorative aria-hidden box still paints on screen
5541
+ // and can still visually cover real text.
5542
+ function isPaintedForOcclusion(el) {
5543
+ for (let cur = el; cur && cur.nodeType === 1; cur = cur.parentElement) {
5544
+ const style = getComputedStyle(cur);
5545
+ const visibility = String(style.visibility || '').toLowerCase();
5546
+ if (style.display === 'none' || visibility === 'hidden' || visibility === 'collapse') return false;
5547
+ if ((parseFloat(style.opacity) || 0) <= 0.05) return false;
5548
+ if (String(style.contentVisibility || '').toLowerCase() === 'hidden') return false;
5549
+ }
5550
+ return true;
5551
+ }
5552
+
5553
+ // Detects text that is actually painted UNDER an opaque box or another text
5554
+ // run (the reader can't read it), plus two structural overlap tells the
5555
+ // elementFromPoint probe can't reach: a large headline whose edge tucks behind
5556
+ // an opaque card, and an inline element whose leaked padding-box (a common
5557
+ // class-name-collision bug) covers a sibling.
5558
+ //
5559
+ // The occlusion probe is viewport-bound: elementFromPoint only answers for the
5560
+ // scan's current viewport (scroll 0), so the ground-truth paths cover the
5561
+ // first-viewport composition where collisions matter most. The inline-leak
5562
+ // path is pure geometry and runs anywhere on the page.
5563
+ const OCCLUSION_TEXT_SKIP_TAGS = new Set(['script', 'style', 'noscript', 'template', 'title']);
5564
+
5565
+ function checkTextOcclusionDOM() {
5566
+ const findings = [];
5567
+ const seenVictims = new Set();
5568
+ const vw = window.innerWidth || 1280;
5569
+ const vh = window.innerHeight || 800;
5570
+
5571
+ const isFloated = (cs) => {
5572
+ const f = String(cs.cssFloat || cs.float || 'none').toLowerCase();
5573
+ return f === 'left' || f === 'right';
5574
+ };
5575
+ const isMarqueeish = (el, cs) => {
5576
+ if (el.tagName === 'MARQUEE') return true;
5577
+ const ident = `${el.getAttribute?.('class') || ''} ${el.getAttribute?.('id') || ''}`;
5578
+ if (/\b(marquee|ticker|scroller|carousel|conveyor)\b/i.test(ident)) return true;
5579
+ const anim = String(cs.animationName || '').toLowerCase();
5580
+ return /marquee|ticker|scroll/.test(anim);
5581
+ };
5582
+ // A fixed or sticky overlay (status bar, toolbar, sticky header) floats above
5583
+ // scrolling content by design — whatever sits under it at rest scrolls clear,
5584
+ // so it is not occluding the page.
5585
+ const isPinnedOverlay = (el) => {
5586
+ for (let cur = el; cur && cur.nodeType === 1 && cur !== document.body; cur = cur.parentElement) {
5587
+ const pos = String(getComputedStyle(cur).position || 'static');
5588
+ if (pos === 'fixed' || pos === 'sticky') return true;
5589
+ }
5590
+ return false;
5591
+ };
5592
+
5593
+ // Collect renderable text owners in / near the first viewport for the
5594
+ // elementFromPoint probe. SVG <text> counts too.
5595
+ const textEls = [];
5596
+ for (const el of document.querySelectorAll('body *')) {
5597
+ const tag = el.tagName.toLowerCase();
5598
+ if (OCCLUSION_TEXT_SKIP_TAGS.has(tag)) continue;
5599
+ const inSvg = !!el.closest('svg');
5600
+ if (inSvg && tag !== 'text') continue;
5601
+ const text = inSvg ? (el.textContent || '').trim() : elementDirectText(el);
5602
+ if (text.length < 2) continue;
5603
+ if (!isPaintedForOcclusion(el)) continue;
5604
+ let rect; try { rect = el.getBoundingClientRect(); } catch { continue; }
5605
+ if (rect.width < 6 || rect.height < 6) continue;
5606
+ // Viewport-bound probe: keep text whose box overlaps the live viewport.
5607
+ if (rect.bottom <= 0 || rect.top >= vh) continue;
5608
+ textEls.push({ el, rect, text, inSvg });
5609
+ }
5610
+
5611
+ for (const victim of textEls) {
5612
+ const { el, rect, text } = victim;
5613
+ if (seenVictims.has(el)) continue;
5614
+ const style = getComputedStyle(el);
5615
+ if (isScreenReaderOnlyTextStyle(style, { width: rect.width, height: rect.height, clientWidth: el.clientWidth, clientHeight: el.clientHeight })) continue;
5616
+
5617
+ const cols = Math.max(6, Math.min(30, Math.round(rect.width / 12)));
5618
+ const rows = Math.max(1, Math.min(4, Math.round(rect.height / 14)));
5619
+ let total = 0;
5620
+ let occluded = 0;
5621
+ let occluderEl = null;
5622
+ let occluderKind = '';
5623
+ for (let i = 0; i < cols; i++) {
5624
+ const x = rect.left + rect.width * ((i + 0.5) / cols);
5625
+ if (x < 1 || x > vw - 1) continue;
5626
+ for (let j = 0; j < rows; j++) {
5627
+ const y = rect.top + rect.height * ((j + 0.5) / rows);
5628
+ if (y < 1 || y > vh - 1) continue;
5629
+ total++;
5630
+ const top = document.elementFromPoint(x, y);
5631
+ if (!top) continue;
5632
+ // Text visible here: the probe returns the text itself, a descendant,
5633
+ // or one of its ancestors (the text's own container / background).
5634
+ if (top === el || el.contains(top) || top.contains(el)) continue;
5635
+ const topCs = getComputedStyle(top);
5636
+ if (isFloated(topCs) || isMarqueeish(top, topCs) || isPinnedOverlay(top)) continue;
5637
+ const topTag = top.tagName.toLowerCase();
5638
+ // Text sitting under a raw image/video is contrast territory (deduped
5639
+ // against the pixel low-contrast rule); leave those alone here.
5640
+ if (['img', 'video', 'canvas', 'picture'].includes(topTag)) continue;
5641
+ const topHasText = elementDirectText(top).length > 0 || !!top.closest('svg');
5642
+ if (isOpaqueDecoratedBox(topCs)) {
5643
+ occluded++;
5644
+ if (!occluderEl) { occluderEl = top; occluderKind = 'box'; }
5645
+ } else if (topHasText) {
5646
+ occluded++;
5647
+ if (!occluderEl) { occluderEl = top; occluderKind = 'text'; }
5648
+ }
5649
+ }
5650
+ }
5651
+ if (total === 0 || !occluderEl) continue;
5652
+ const occFrac = occluded / total;
5653
+ // A solid box's paint fills its rect, so box coverage is real at a lower
5654
+ // bar. Text coverage rides on elementFromPoint returning the occluder's box
5655
+ // (line box / container), which can exceed its actual glyph ink, so the
5656
+ // text bar is higher — partial overlaps below it are crowding, not burial.
5657
+ if (occFrac < (occluderKind === 'text' ? 0.45 : 0.3)) continue;
5658
+
5659
+ // (i) Substantial occlusion: a real slab of the text is behind something.
5660
+ if (occluderKind === 'text') {
5661
+ // Two SVG texts inside the same emblem (concentric arcs, monogram) are one
5662
+ // decorative unit, not a collision.
5663
+ const victimSvg = el.closest('svg');
5664
+ const occSvg = occluderEl.closest('svg');
5665
+ if (victimSvg && occSvg && victimSvg === occSvg) continue;
5666
+ // Both sides in plain flow: the overlap is line-box bleed from tight
5667
+ // leading (a big headline reaching up over its own eyebrow), not one text
5668
+ // run painted over another.
5669
+ if (!isLayeredElement(el) && !isLayeredElement(occluderEl)) continue;
5670
+ }
5671
+ seenVictims.add(el);
5672
+ findings.push({
5673
+ el,
5674
+ type: 'text-occlusion',
5675
+ detail: `${classSelector(el)} "${text.slice(0, 24)}" is ${Math.round(occFrac * 100)}% covered by ${occluderKind === 'text' ? 'overlapping text' : 'an opaque element'} (${classSelector(occluderEl)})`,
5676
+ });
5677
+ }
5678
+
5679
+ // (ii) Headline overhanging an opaque card: a display-scale line whose bulk
5680
+ // sits outside a bounded content card but whose edge clips into it. The text
5681
+ // may still paint on top and stay readable, but the two layers were dropped
5682
+ // on the same pixels — a placement collision, not a composition.
5683
+ const cards = [];
5684
+ for (const el of document.querySelectorAll('body *')) {
5685
+ if (el.closest('svg')) continue;
5686
+ if (!isPaintedForOcclusion(el)) continue;
5687
+ const cs = getComputedStyle(el);
5688
+ const bg = parseAnyColor(cs.backgroundColor || '');
5689
+ const bgImg = cs.backgroundImage || '';
5690
+ if (!bg || (bg.a ?? 1) <= 0.7) continue;
5691
+ if (bgImg && bgImg !== 'none' && /(gradient|url)\(/i.test(bgImg)) continue;
5692
+ const hasBorder = ['Top', 'Right', 'Bottom', 'Left'].some((s) => (parseFloat(cs[`border${s}Width`]) || 0) > 0);
5693
+ const hasShadow = cs.boxShadow && cs.boxShadow !== 'none';
5694
+ if (!hasBorder && !hasShadow) continue;
5695
+ if (isPinnedOverlay(el)) continue;
5696
+ let cr; try { cr = el.getBoundingClientRect(); } catch { continue; }
5697
+ if (cr.width < 100 || cr.width > 0.8 * vw || cr.height < 60) continue;
5698
+ cards.push({ el, rect: cr });
5699
+ }
5700
+ for (const victim of textEls) {
5701
+ const { el, rect, text } = victim;
5702
+ if (seenVictims.has(el)) continue;
5703
+ const style = getComputedStyle(el);
5704
+ if ((parseFloat(style.fontSize) || 16) < 40) continue;
5705
+ let lineHeight = parseFloat(style.lineHeight);
5706
+ if (!Number.isFinite(lineHeight)) lineHeight = (parseFloat(style.fontSize) || 16) * 1.2;
5707
+ const centerX = rect.left + rect.width / 2;
5708
+ for (const card of cards) {
5709
+ if (card.el === el || el.contains(card.el) || card.el.contains(el)) continue;
5710
+ const ix = Math.max(0, Math.min(rect.right, card.rect.right) - Math.max(rect.left, card.rect.left));
5711
+ const iy = Math.max(0, Math.min(rect.bottom, card.rect.bottom) - Math.max(rect.top, card.rect.top));
5712
+ if (ix < 8 || iy < 0.5 * lineHeight) continue;
5713
+ // The headline's bulk must sit outside the card — only its edge clips in.
5714
+ if (centerX >= card.rect.left && centerX <= card.rect.right) continue;
5715
+ if (ix > 0.5 * rect.width) continue;
5716
+ seenVictims.add(el);
5717
+ findings.push({
5718
+ el,
5719
+ type: 'text-occlusion',
5720
+ detail: `${classSelector(el)} "${text.slice(0, 24)}" overhangs ${classSelector(card.el)} by ${Math.round(ix)}px — the headline and the card collide`,
5721
+ });
5722
+ break;
5723
+ }
5724
+ }
5725
+
5726
+ // (iii) Inline padding leak: an inline element with an opaque background and
5727
+ // large vertical padding paints a filled block whose padding-box overflows
5728
+ // its line (inline padding reserves no vertical space), so the fill lands on
5729
+ // the content above and below instead of enclosing its own text. The
5730
+ // canonical bug is a class-name collision that hands a decorative marker a
5731
+ // payoff card's padding. The tell is a rendered height several times the line
5732
+ // height, which distinguishes the leak from a padded inline highlight.
5733
+ for (const el of document.querySelectorAll('body *')) {
5734
+ if (el.closest('svg')) continue;
5735
+ if (!isPaintedForOcclusion(el)) continue;
5736
+ const cs = getComputedStyle(el);
5737
+ if (cs.display !== 'inline') continue;
5738
+ const bg = parseAnyColor(cs.backgroundColor || '');
5739
+ if (!bg || (bg.a ?? 1) <= 0.6) continue;
5740
+ const padTop = parseFloat(cs.paddingTop) || 0;
5741
+ const padBottom = parseFloat(cs.paddingBottom) || 0;
5742
+ if (padTop + padBottom < 24) continue;
5743
+ let rect; try { rect = el.getBoundingClientRect(); } catch { continue; }
5744
+ if (rect.width < 12 || rect.height < 24) continue;
5745
+ const fontSize = parseFloat(cs.fontSize) || 16;
5746
+ let lineHeight = parseFloat(cs.lineHeight);
5747
+ if (!Number.isFinite(lineHeight)) lineHeight = fontSize * 1.4;
5748
+ // The padding box has to overflow the line by a clear margin — a padded
5749
+ // inline highlight sits at roughly one line height, the leak at several.
5750
+ if (rect.height < 2.2 * lineHeight) continue;
5751
+ if (seenVictims.has(el)) continue;
5752
+ // Name a neighbour the fill lands on, if one is nearby (paint state aside,
5753
+ // reveal-on-scroll siblings still occupy the space it covers).
5754
+ let overlaps = null;
5755
+ for (const other of el.parentElement ? el.parentElement.children : []) {
5756
+ if (other === el || el.contains(other) || other.contains(el)) continue;
5757
+ if (getComputedStyle(other).display === 'none') continue;
5758
+ const oRect = other.getBoundingClientRect();
5759
+ const ix = Math.max(0, Math.min(rect.right, oRect.right) - Math.max(rect.left, oRect.left));
5760
+ const iy = Math.max(0, Math.min(rect.bottom, oRect.bottom) - Math.max(rect.top, oRect.top));
5761
+ if (ix > 4 && iy > 4 && (other.textContent || '').trim().length > 0) { overlaps = other; break; }
5762
+ }
5763
+ seenVictims.add(el);
5764
+ findings.push({
5765
+ el,
5766
+ type: 'text-occlusion',
5767
+ detail: `${classSelector(el)} is an inline element whose opaque fill leaks ${Math.round(rect.height)}px past its line${overlaps ? ` onto ${classSelector(overlaps)}` : ''}`,
5768
+ });
5769
+ }
5770
+
5771
+ return findings;
5772
+ }
5773
+
5774
+ // ---------------------------------------------------------------------------
5775
+ // First-viewport column overflow — the stretched-hero signature (browser-only)
5776
+ // ---------------------------------------------------------------------------
5777
+
5778
+ // A multi-column composition that opens the page (grid/flex with two or more
5779
+ // side-by-side columns, each a real share of the width) where one column's
5780
+ // content runs far past the fold while its sibling fits inside a single
5781
+ // viewport. The row stretches to the tall column, so the short one floats in a
5782
+ // screen-and-a-half of dead space and the fold falls deep inside a single
5783
+ // section. Single-column pages and full-page heroes (no sibling column) are
5784
+ // exempt because there is no fitting sibling to contrast against.
5785
+ function checkFirstViewportColumnOverflowDOM() {
5786
+ const findings = [];
5787
+ const vw = window.innerWidth || 1280;
5788
+ const vh = window.innerHeight || 800;
5789
+ const isMultiCol = (s) => /(^|inline-)(grid|flex)$/.test(String(s.display || ''));
5790
+
5791
+ for (const el of document.querySelectorAll('body *')) {
5792
+ const style = getComputedStyle(el);
5793
+ if (!isMultiCol(style)) continue;
5794
+ let rect; try { rect = el.getBoundingClientRect(); } catch { continue; }
5795
+ if (rect.width < 0.5 * vw) continue;
5796
+ const pageTop = rect.top + (window.scrollY || 0);
5797
+ const pageBottom = pageTop + rect.height;
5798
+ // The fold must fall inside this container: it opens within the first
5799
+ // viewport and runs past it.
5800
+ if (pageTop >= vh * 0.9 || pageBottom <= vh) continue;
5801
+
5802
+ // Direct children that read as side-by-side columns: a real width share,
5803
+ // not full-bleed (stacked single column), sharing the container's top row.
5804
+ const cols = [];
5805
+ for (const child of el.children) {
5806
+ const cs = getComputedStyle(child);
5807
+ if (cs.display === 'none') continue;
5808
+ if (String(cs.position || '') === 'absolute' || String(cs.position || '') === 'fixed') continue;
5809
+ let cr; try { cr = child.getBoundingClientRect(); } catch { continue; }
5810
+ const wShare = cr.width / rect.width;
5811
+ if (wShare < 0.25 || wShare > 0.9) continue;
5812
+ if (cr.height < 40) continue;
5813
+ // Content extent: how far the child's own content actually reaches,
5814
+ // independent of a stretched row height.
5815
+ let contentBottom = cr.top;
5816
+ for (const d of child.querySelectorAll('*')) {
5817
+ const ds = getComputedStyle(d);
5818
+ if (ds.position === 'absolute' || ds.position === 'fixed') continue;
5819
+ if (ds.display === 'none' || ds.visibility === 'hidden') continue;
5820
+ let dr; try { dr = d.getBoundingClientRect(); } catch { continue; }
5821
+ if (dr.width > 0 && dr.height > 0) contentBottom = Math.max(contentBottom, dr.bottom);
5822
+ }
5823
+ cols.push({ child, top: cr.top, contentH: contentBottom - cr.top });
5824
+ }
5825
+ if (cols.length < 2) continue;
5826
+ // Side-by-side: the two candidate columns must share the top row.
5827
+ cols.sort((a, b) => b.contentH - a.contentH);
5828
+ const tall = cols[0];
5829
+ const shortest = cols[cols.length - 1];
5830
+ if (Math.abs(tall.top - shortest.top) > 0.25 * vh) continue;
5831
+ if (tall.contentH <= vh * 1.4) continue;
5832
+ if (shortest.contentH > vh) continue;
5833
+
5834
+ findings.push({
5835
+ el,
5836
+ type: 'first-viewport-column-overflow',
5837
+ detail: `${classSelector(el)} opens the page with one column running ${Math.round(tall.contentH / vh * 100)}% of the viewport tall while a sibling fits in ${Math.round(shortest.contentH / vh * 100)}% — the fold falls deep inside the section`,
5838
+ });
5839
+ }
5840
+ return findings;
5841
+ }
5842
+
3246
5843
  // --- cli/engine/browser/injected/index.mjs ---
3247
5844
  const IS_BROWSER = typeof window !== 'undefined';
3248
5845
 
@@ -4468,7 +7065,7 @@ if (IS_BROWSER) {
4468
7065
  return {
4469
7066
  type: f.type || f.id,
4470
7067
  category: ap ? ap.category : 'quality',
4471
- severity: ap?.severity || 'warning',
7068
+ severity: f.severity || ap?.severity || 'warning',
4472
7069
  detail: f.detail || f.snippet,
4473
7070
  ignoreValue: f.ignoreValue || f.value || '',
4474
7071
  name: ap ? ap.name : (f.type || f.id),
@@ -4704,10 +7301,7 @@ if (IS_BROWSER) {
4704
7301
  const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
4705
7302
  const designSystem = browserDesignSystemConfig();
4706
7303
  const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
4707
- // Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
4708
- // real browser env (detector page, live overlay, extension) running every
4709
- // check is free, so we always surface them; the gating is purely a CLI
4710
- // output concern, applied in the Node engines' detect* return paths.
7304
+ // All deterministic rules run in the browser and extension path.
4711
7305
 
4712
7306
  for (const el of document.querySelectorAll('*')) {
4713
7307
  // Skip impeccable's own elements and any descendants (overlays, labels, banner, nav buttons)
@@ -4723,6 +7317,7 @@ if (IS_BROWSER) {
4723
7317
 
4724
7318
  const findings = [
4725
7319
  ...checkElementBordersDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
7320
+ ...checkElementPseudoStripeDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4726
7321
  ...checkElementColorsDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4727
7322
  ...checkElementMotionDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4728
7323
  ...checkElementGlowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
@@ -4734,6 +7329,7 @@ if (IS_BROWSER) {
4734
7329
  ...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4735
7330
  ...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
4736
7331
  ...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
7332
+ ...checkElementBlinkingCursorDOM(el).map(f => ({ type: f.id, detail: f.snippet, ...(f.severity ? { severity: f.severity } : {}) })),
4737
7333
  ...checkElementDesignSystemDOM(el, designSystem, designSeen),
4738
7334
  ].filter(f => _ruleOk(f.type));
4739
7335
 
@@ -4772,12 +7368,55 @@ if (IS_BROWSER) {
4772
7368
  addBrowserFindings(groupMap, document.body, sectionKickerFindings);
4773
7369
  }
4774
7370
 
7371
+ const numberedLabelFindings = checkNumberedSectionLabelsDOM()
7372
+ .map(f => ({ type: f.id, detail: f.snippet }))
7373
+ .filter(f => _ruleOk(f.type));
7374
+ if (numberedLabelFindings.length > 0) {
7375
+ pageLevelFindings.push(...numberedLabelFindings);
7376
+ addBrowserFindings(groupMap, document.body, numberedLabelFindings);
7377
+ }
7378
+
7379
+ const repeatedTextFindings = checkRepeatedContainerTextDOM()
7380
+ .map(f => ({ type: f.id, detail: f.snippet }))
7381
+ .filter(f => _ruleOk(f.type));
7382
+ if (repeatedTextFindings.length > 0) {
7383
+ pageLevelFindings.push(...repeatedTextFindings);
7384
+ addBrowserFindings(groupMap, document.body, repeatedTextFindings);
7385
+ }
7386
+
4775
7387
  const layoutFindings = checkLayout().filter(f => _ruleOk(f.type));
4776
7388
  for (const f of layoutFindings) {
4777
7389
  const el = f.el || document.body;
4778
7390
  addBrowserFindings(groupMap, el, [{ type: f.type, detail: f.detail || f.snippet }]);
4779
7391
  }
4780
7392
 
7393
+ // Heading rhythm (browser-only: needs real layout for the gap math)
7394
+ const headingRhythmFindings = checkHeadingRhythmDOM().filter(f => _ruleOk(f.type));
7395
+ for (const f of headingRhythmFindings) {
7396
+ addBrowserFindings(groupMap, f.el || document.body, [{ type: f.type, detail: f.detail }]);
7397
+ }
7398
+
7399
+ // Edge-flush cards in horizontal scrollers (browser-only: needs real
7400
+ // layout for the scroller clip box vs card rect math)
7401
+ const edgeFlushFindings = checkEdgeFlushCardsDOM().filter(f => _ruleOk(f.type));
7402
+ for (const f of edgeFlushFindings) {
7403
+ addBrowserFindings(groupMap, f.el || document.body, [{ type: f.type, detail: f.detail }]);
7404
+ }
7405
+
7406
+ // Text occlusion / element overlap (browser-only: needs real layout +
7407
+ // elementFromPoint to confirm what actually paints on top)
7408
+ const occlusionFindings = checkTextOcclusionDOM().filter(f => _ruleOk(f.type));
7409
+ for (const f of occlusionFindings) {
7410
+ addBrowserFindings(groupMap, f.el || document.body, [{ type: f.type, detail: f.detail }]);
7411
+ }
7412
+
7413
+ // First-viewport column overflow — the stretched-hero signature
7414
+ // (browser-only: needs real layout for the content-extent math)
7415
+ const colOverflowFindings = checkFirstViewportColumnOverflowDOM().filter(f => _ruleOk(f.type));
7416
+ for (const f of colOverflowFindings) {
7417
+ addBrowserFindings(groupMap, f.el || document.body, [{ type: f.type, detail: f.detail }]);
7418
+ }
7419
+
4781
7420
  // Page-level quality checks (headings, etc.)
4782
7421
  const qualityFindings = checkPageQualityDOM().filter(f => _ruleOk(f.type));
4783
7422
  if (qualityFindings.length > 0) {
@@ -4803,7 +7442,25 @@ if (IS_BROWSER) {
4803
7442
  }
4804
7443
  const htmlPatternFindings = checkHtmlPatterns(docClone.outerHTML);
4805
7444
  if (htmlPatternFindings.length > 0) {
4806
- const mapped = htmlPatternFindings.map(f => ({ type: f.id, detail: f.snippet })).filter(f => _ruleOk(f.type));
7445
+ const mapped = htmlPatternFindings.map(f => {
7446
+ const item = { type: f.id, detail: f.snippet };
7447
+ if (f.severity) {
7448
+ item.severity = f.severity;
7449
+ } else if (f.id === 'pulsing-dot' && f.selector) {
7450
+ // The string scan promotes header/nav dots on its own; with a live
7451
+ // layout also promote dots resting in the first ~900px of the page
7452
+ // (the hero region), which the source scan cannot measure.
7453
+ try {
7454
+ const dotEl = document.querySelector(f.selector);
7455
+ if (dotEl) {
7456
+ const rect = dotEl.getBoundingClientRect();
7457
+ const pageTop = rect.top + (window.scrollY || 0);
7458
+ if (pageTop <= 900) item.severity = 'error';
7459
+ }
7460
+ } catch { /* unresolvable selector: keep registry severity */ }
7461
+ }
7462
+ return item;
7463
+ }).filter(f => _ruleOk(f.type));
4807
7464
  pageLevelFindings.push(...mapped);
4808
7465
  addBrowserFindings(groupMap, document.body, mapped);
4809
7466
  }
@@ -5177,6 +7834,9 @@ if (IS_BROWSER) {
5177
7834
  window.impeccableDetectAsync = detectAsync;
5178
7835
  window.impeccableScan = scan;
5179
7836
  window.impeccableScanAsync = scanAsync;
7837
+ // Raw measurement for the URL engine's content-hidden-at-rest pass: it
7838
+ // drives a reveal sweep from Node and thresholds the result itself.
7839
+ window.impeccableMeasureHiddenText = measureHiddenTextDOM;
5180
7840
  window.impeccableCollectVisualContrastCandidates = collectVisualContrastCandidates;
5181
7841
  window.impeccableAnalyzeVisualContrast = analyzeVisualContrast;
5182
7842
  window.impeccableGetLastVisualContrastAnalyses = () => lastVisualContrastAnalyses.slice();