@kinti/a11y-toolkit 5.26.0 → 5.27.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.
Files changed (44) hide show
  1. package/README.md +1 -1
  2. package/a11y_toolkit/a11y.py +27 -4
  3. package/a11y_toolkit/a11yact.py +9 -1
  4. package/a11y_toolkit/a11yannotate.py +185 -0
  5. package/a11y_toolkit/a11yaudit.py +853 -193
  6. package/a11y_toolkit/a11ybadge.py +24 -17
  7. package/a11y_toolkit/a11ybudget.py +145 -1
  8. package/a11y_toolkit/a11ycorpus.py +58 -24
  9. package/a11y_toolkit/a11ycrit.py +110 -53
  10. package/a11y_toolkit/a11ydiff.py +104 -34
  11. package/a11y_toolkit/a11ydisprove.py +15 -8
  12. package/a11y_toolkit/a11ydocx.py +8 -6
  13. package/a11y_toolkit/a11ydom.py +425 -95
  14. package/a11y_toolkit/a11yen301549.py +53 -1
  15. package/a11y_toolkit/a11yengines.py +157 -0
  16. package/a11y_toolkit/a11yevidence.py +81 -33
  17. package/a11y_toolkit/a11yfix.py +131 -52
  18. package/a11y_toolkit/a11yinit.py +30 -5
  19. package/a11y_toolkit/a11yjourney.py +110 -4
  20. package/a11y_toolkit/a11yledger.py +119 -12
  21. package/a11y_toolkit/a11ylocate.py +247 -0
  22. package/a11y_toolkit/a11yopenacr.py +10 -3
  23. package/a11y_toolkit/a11ypatches.py +154 -0
  24. package/a11y_toolkit/a11ypatterns.py +344 -0
  25. package/a11y_toolkit/a11ypdf.py +109 -53
  26. package/a11y_toolkit/a11yrgaa.py +60 -0
  27. package/a11y_toolkit/a11yroute.py +34 -12
  28. package/a11y_toolkit/a11ysarif.py +45 -18
  29. package/a11y_toolkit/a11yscope.py +67 -15
  30. package/a11y_toolkit/a11yscroll.py +7 -5
  31. package/a11y_toolkit/a11ystatement.py +30 -6
  32. package/a11y_toolkit/a11ytrace.py +293 -0
  33. package/a11y_toolkit/a11yvalidate.py +21 -15
  34. package/a11y_toolkit/a11yvpat.py +34 -7
  35. package/a11y_toolkit/a11yvtt.py +22 -6
  36. package/a11y_toolkit/a11ywiz.py +121 -0
  37. package/a11y_toolkit/contrast.py +62 -24
  38. package/a11y_toolkit/locales/en.json +177 -20
  39. package/a11y_toolkit/locales/es.json +178 -21
  40. package/a11y_toolkit/rgaa.json +2661 -0
  41. package/a11y_toolkit/server.py +149 -50
  42. package/package.json +2 -2
  43. package/a11y_toolkit/a11yplan.py +0 -214
  44. package/a11y_toolkit/a11ywcagem.py +0 -237
@@ -22,6 +22,27 @@ import sys
22
22
  from .a11yaudit import CRIT, T, compute_score
23
23
  from .contrast import parse_color, decode_png, sample_rgb, hexs, luminance, ratio
24
24
 
25
+ # textos de las funciones renderizadas que NO viven en locales (errores de
26
+ # carga y limits): bilingües aquí, igual que el catálogo (invariante es/en)
27
+ _LOAD_ERR = {'es': 'no se pudo cargar: {e}',
28
+ 'en': 'could not load: {e}'}
29
+ _LIMITS_HCM = {
30
+ 'es': ('Heurística de revisión (1.4.3/1.4.11 en HCM): los fills '
31
+ 'coloreados hardcoded en SVG suelen caer al heredado con '
32
+ 'forced-colors. La comprobación definitiva es visual con '
33
+ 'Windows High Contrast — esto la prepara, no la sustituye.'),
34
+ 'en': ('Review heuristic (1.4.3/1.4.11 under HCM): hardcoded SVG fills '
35
+ 'usually fall back to inherited under forced-colors. The definitive '
36
+ 'check is visual on Windows High Contrast — this prepares it, '
37
+ 'it does not replace it.'),
38
+ }
39
+ _LIMITS_MOTION = {
40
+ 'es': ('Mide CSS animations y video[autoplay]. No cubre animaciones '
41
+ 'JS/WebGL ni parallax por scroll — revisión manual.'),
42
+ 'en': ('Measures CSS animations and video[autoplay]. Does not cover '
43
+ 'JS/WebGL animations or scroll parallax — manual review.'),
44
+ }
45
+
25
46
  from . import a11yi18n
26
47
  # browser pool: Chromium reutilizable entre llamadas consecutivas
27
48
  _POOL = {'playwright': None, 'browser': None, 'type': None}
@@ -71,7 +92,7 @@ def _detect_browser(pw, preferred=None):
71
92
  def _get_browser(pw, headless=True, preferred=None):
72
93
  """Devuelve un browser del pool (o crea uno si no existe)."""
73
94
  if _POOL['browser'] is not None and _POOL['browser'].is_connected() and \
74
- _POOL['type'] == (preferred or 'auto'):
95
+ (preferred in (None, 'auto') or _POOL['type'] == preferred):
75
96
  return _POOL['browser']
76
97
  _close_pool()
77
98
  br, kind = _detect_browser(pw, preferred)
@@ -104,10 +125,51 @@ def _t(lang, key, n=None):
104
125
 
105
126
 
106
127
  # ------------------------------------------------------------------- JS -----
128
+ # Accessible-name computation, spliced into _JS below. Module-level so the
129
+ # accname PRECEDENCE is pinnable by test_dom as a plain string (no browser
130
+ # needed): labelledby (multi-id list, texts joined in order) > aria-label >
131
+ # implicit <label> > content > title. Static string — no page data ever lands
132
+ # here.
133
+ _JS_NAMEOF = r'''
134
+ const nameOf = el => {
135
+ let n = '';
136
+ // 1. aria-labelledby: a whitespace-SEPARATED id list — resolve each id
137
+ // within the root (shadow roots carry getElementById too), join the
138
+ // name texts in ORDER, skip missing ids (accname step 2B)
139
+ if (el.getAttribute('aria-labelledby')) {
140
+ const root = el.getRootNode();
141
+ const byId = id => (root.getElementById ? root.getElementById(id)
142
+ : root.querySelector('#' + CSS.escape(id)));
143
+ const parts = [];
144
+ for (const id of el.getAttribute('aria-labelledby').trim().split(/\s+/)) {
145
+ const ref = byId(id);
146
+ if (ref) parts.push((ref.innerText || '').trim());
147
+ }
148
+ n = parts.join(' ').trim();
149
+ }
150
+ // 2. aria-label
151
+ if (!n) n = (el.getAttribute('aria-label') || '').trim();
152
+ // 3. implicit <label>
153
+ if (!n && el.labels && el.labels[0]) n = el.labels[0].innerText.trim();
154
+ // 4. content: input value/image alt, element text, descendant img alt
155
+ if (!n && el.tagName === 'INPUT' && ['submit', 'button', 'reset'].includes(el.type)) n = el.value || '';
156
+ if (!n && el.tagName === 'INPUT' && el.type === 'image') n = el.alt || '';
157
+ if (!n && ['A', 'BUTTON', 'SUMMARY'].includes(el.tagName)) {
158
+ n = (el.innerText || '').trim();
159
+ // accname: a descendant image's alt contributes to the link's name
160
+ if (!n) { const im = el.querySelector('img[alt]'); if (im) n = (im.getAttribute('alt') || '').trim(); }
161
+ }
162
+ if (!n && el.tagName === 'IMG') n = el.getAttribute('alt') || '';
163
+ // 5. title — the LAST resort in the accname order
164
+ if (!n) n = (el.getAttribute('title') || '').trim();
165
+ return n.trim();
166
+ };
167
+ '''
168
+
107
169
  _JS = r'''(maxEj) => {
108
170
  const INTER = 'a[href], button, input, select, textarea, summary, [role="button"], [role="link"], [tabindex]';
109
171
  const out = { contrast: {}, contrastReview: 0, contrastZones: [], targets: [], unnamed: [], fields: [],
110
- imgs: [], iframes: [], headings: [], tabindex: [], ariaHidden: [],
172
+ imgs: [], canvasNoName: [], chartsNoEquiv: [], iframes: [], headings: [], tabindex: [], ariaHidden: [],
111
173
  blank: 0, videos: 0, videoSubs: 0, tables: 0, tableTh: 0,
112
174
  focus: [], focusFail: [], focusContrast: [], focusObscured: [], marks: 0,
113
175
  ids: {}, lang: null, title: '', viewport: null, refresh: null,
@@ -423,26 +485,7 @@ _JS = r'''(maxEj) => {
423
485
  }
424
486
 
425
487
  // ---- nombres accesibles renderizados ----
426
- const nameOf = el => {
427
- let n = (el.getAttribute('aria-label') || '').trim();
428
- if (!n && el.labels && el.labels[0]) n = el.labels[0].innerText.trim();
429
- if (!n && el.getAttribute('aria-labelledby')) {
430
- const root = el.getRootNode();
431
- const ref = root.getElementById ? root.getElementById(el.getAttribute('aria-labelledby'))
432
- : root.querySelector('#' + CSS.escape(el.getAttribute('aria-labelledby')));
433
- if (ref) n = (ref.innerText || '').trim();
434
- }
435
- if (!n) n = (el.getAttribute('title') || '').trim();
436
- if (!n && el.tagName === 'INPUT' && ['submit', 'button', 'reset'].includes(el.type)) n = el.value || '';
437
- if (!n && el.tagName === 'INPUT' && el.type === 'image') n = el.alt || '';
438
- if (!n && ['A', 'BUTTON', 'SUMMARY'].includes(el.tagName)) {
439
- n = (el.innerText || '').trim();
440
- // accname: a descendant image's alt contributes to the link's name
441
- if (!n) { const im = el.querySelector('img[alt]'); if (im) n = (im.getAttribute('alt') || '').trim(); }
442
- }
443
- if (!n && el.tagName === 'IMG') n = el.getAttribute('alt') || '';
444
- return n.trim();
445
- };
488
+ /*__NAMEOF__*/
446
489
  for (const el of deepQ('a[href], button, summary, [role="button"], [role="link"]')) {
447
490
  if (!vis(el) || el.closest('[aria-hidden="true"]')) continue;
448
491
  if (!nameOf(el) && out.unnamed.length < 30) out.unnamed.push(path(el));
@@ -456,6 +499,43 @@ _JS = r'''(maxEj) => {
456
499
  if (!vis(el)) continue;
457
500
  if (!el.hasAttribute('alt') && out.imgs.length < 30) out.imgs.push(el.getAttribute('src') || '');
458
501
  }
502
+ // canvas: el pase rendered es el JUEZ del nombre computado (el estático es
503
+ // filtro — la capa suele inyectarse por JS al renderizar el gráfico)
504
+ for (const el of deepQ('canvas')) {
505
+ if (!vis(el)) continue;
506
+ const _role = (el.getAttribute('role') || '').toLowerCase();
507
+ if (_role === 'presentation' || _role === 'none') continue;
508
+ if (el.closest('[aria-hidden="true"]')) continue;
509
+ const _fallback = (el.textContent || '').trim();
510
+ if (!nameOf(el) && !_fallback && out.canvasNoName.length < 20)
511
+ out.canvasNoName.push(path(el));
512
+ }
513
+ // charts CON nombre: ¿hay equivalente de datos visible para la máquina?
514
+ // (aria-details / aria-describedby resolubles, o una tabla en el entorno).
515
+ // Hallazgo de REVISIÓN (low): si los datos viven en prosa cercana, pasa.
516
+ const _chartName = el => (el.getAttribute('aria-label') || '').trim()
517
+ || (el.getAttribute('title') || '').trim()
518
+ || [...el.querySelectorAll('title')].map(t => t.textContent.trim())[0]
519
+ || ((el.getAttribute('aria-labelledby') || '').split(/\s+/)
520
+ .filter(Boolean).some(id => document.getElementById(id)) ? 'named' : '');
521
+ for (const el of deepQ('canvas, svg[role="img"]')) {
522
+ if (!vis(el)) continue;
523
+ if (el.closest('[aria-hidden="true"]')) continue;
524
+ const _r = (el.getAttribute('role') || '').toLowerCase();
525
+ if (el.tagName.toLowerCase() === 'svg' && _r !== 'img') continue;
526
+ if (!_chartName(el)) continue; // sin nombre: ya lo acusan las señales de nombre
527
+ let _equiv = [...(el.getAttribute('aria-details') || '').split(/\s+/),
528
+ ...(el.getAttribute('aria-describedby') || '').split(/\s+/)]
529
+ .filter(Boolean).some(id => document.getElementById(id));
530
+ if (!_equiv) {
531
+ // solo el entorno SEMÁNTICO (figure/section/celda/lista) cuenta como
532
+ // "cerca" — el parent genérico contaminaría (la tabla de OTRO chart
533
+ // en el mismo main haría pasar a todos)
534
+ const _scope = el.closest('figure, section, td, li');
535
+ _equiv = !!(_scope && _scope.querySelector('table'));
536
+ }
537
+ if (!_equiv && out.chartsNoEquiv.length < 15) out.chartsNoEquiv.push(path(el));
538
+ }
459
539
  for (const el of deepQ('iframe')) {
460
540
  if (!((el.getAttribute('title') || '').trim() || (el.getAttribute('aria-label') || '').trim())
461
541
  && out.iframes.length < 20) out.iframes.push(el.getAttribute('src') || '');
@@ -564,7 +644,8 @@ _JS = r'''(maxEj) => {
564
644
  if (prevFocus && prevFocus.blur) { try { prevFocus.focus(); } catch (e) {} }
565
645
 
566
646
  return out;
567
- }'''
647
+ }''' # /*__NAMEOF__*/ is spliced in below — keep nameOf in _JS_NAMEOF only
648
+ _JS = _JS.replace('/*__NAMEOF__*/', _JS_NAMEOF.strip('\n'))
568
649
 
569
650
 
570
651
  def _add(findings, lang, severity, code, key, examples=None, **fmt):
@@ -668,6 +749,12 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
668
749
  if data.get('imgs'):
669
750
  _add(findings, lang, 'high', '1.1.1', 'img_no_alt',
670
751
  examples=data['imgs'], n=len(data['imgs']))
752
+ if data.get('canvasNoName'):
753
+ _add(findings, lang, 'high', '1.1.1', 'canvas_no_accessible_layer',
754
+ examples=data['canvasNoName'], n=len(data['canvasNoName']))
755
+ if data.get('chartsNoEquiv'):
756
+ _add(findings, lang, 'low', '1.1.1', 'chart_no_data_equivalent',
757
+ examples=data['chartsNoEquiv'], n=len(data['chartsNoEquiv']))
671
758
  if data.get('ariaHidden'):
672
759
  _add(findings, lang, 'high', '4.1.2', 'aria_hidden_focusable',
673
760
  n=len(data['ariaHidden']), tag='control')
@@ -685,7 +772,7 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
685
772
  if re.search(r'user-scalable\s*=\s*(no|0)', vp, re.I):
686
773
  _add(findings, lang, 'high', '1.4.4', 'zoom_no')
687
774
  elif (m := re.search(r'maximum-scale\s*=\s*([\d.]+)', vp, re.I)) and float(m.group(1)) < 2:
688
- _add(findings, lang, 'medium', '1.4.4', 'zoom_max', v=m.group(1))
775
+ _add(findings, lang, 'high', '1.4.4', 'zoom_max', v=m.group(1))
689
776
  if data.get('refresh'):
690
777
  m = re.match(r'\s*(\d+)', str(data['refresh']))
691
778
  segs = int(m.group(1)) if m else 0
@@ -694,14 +781,14 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
694
781
  _add(findings, lang, 'medium', '2.4.3', 'tabindex_pos',
695
782
  examples=data['tabindex'], n=len(data['tabindex']))
696
783
  if not (data.get('main') or data.get('skip')):
697
- _add(findings, lang, 'medium', '2.4.1', 'no_bypass')
784
+ _add(findings, lang, 'low', '2.4.1', 'no_bypass')
698
785
 
699
786
  levels = [h['lvl'] for h in (data.get('headings') or []) if h['text']]
700
787
  h1s = sum(1 for h in data.get('headings') or [] if h['lvl'] == 1 and h['text'])
701
788
  empties = sum(1 for h in data.get('headings') or [] if not h['text'])
702
789
  if levels:
703
790
  if h1s == 0:
704
- _add(findings, lang, 'medium', '1.3.1', 'no_h1')
791
+ _add(findings, lang, 'low', '1.3.1', 'no_h1')
705
792
  elif h1s > 1:
706
793
  _add(findings, lang, 'low', '1.3.1', 'multi_h1', n=h1s)
707
794
  prev, jumps = 0, []
@@ -713,7 +800,7 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
713
800
  _add(findings, lang, 'low', '1.3.1', 'heading_skips',
714
801
  skips=', '.join(jumps[:5]))
715
802
  else:
716
- _add(findings, lang, 'medium', '1.3.1', 'no_headings')
803
+ _add(findings, lang, 'low', '1.3.1', 'no_headings')
717
804
  if empties:
718
805
  _add(findings, lang, 'low', '1.3.1', 'empty_heading', n=empties)
719
806
  tables, con_th = data.get('tables', 0), data.get('tableTh', 0)
@@ -811,7 +898,7 @@ _JS_FORM_STATE = r'''(pre) => {
811
898
  suggested: 0, native: 0 };
812
899
  for (const el of f.querySelectorAll(FIELDS_JS)) {
813
900
  if (el.disabled) continue;
814
- info.campos++;
901
+ info.fields++;
815
902
  const key = (el.name || el.id || el.type) + '@' + (f.id || f.action || '');
816
903
  const shot_before = pre[key] || {};
817
904
  let identified = false, sugerido = false;
@@ -851,13 +938,13 @@ _JS_FORM_STATE = r'''(pre) => {
851
938
  return out;
852
939
  }'''
853
940
 
854
- def audit_forms(url, timeout=45, lang='en', auth_state=None):
941
+ def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
855
942
  """3.3.1 Error Identification / 3.3.3 Error Suggestion — the guided flow:
856
943
  fill every validatable field with INVALID data, really submit, then judge
857
944
  how errors are identified and announced in the post-submit DOM."""
858
945
  from playwright.sync_api import sync_playwright
859
946
  with sync_playwright() as p:
860
- nav = p.chromium.launch()
947
+ nav = _get_browser(p, preferred=browser)
861
948
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
862
949
  page = ctx.new_page() if auth_state else nav.new_page()
863
950
  try:
@@ -882,7 +969,7 @@ def audit_forms(url, timeout=45, lang='en', auth_state=None):
882
969
  'remediation': _t(lang, key + '_rem').format(**fmt)})
883
970
 
884
971
  if navigated:
885
- add('low', '3.3.1', 'form_navigated', example=page.url if False else 'submit')
972
+ add('low', '3.3.1', 'form_navigated', example='submit')
886
973
  elif touched and state is not None:
887
974
  unidentified = [f['form'] for f in state['forms']
888
975
  if f['fields'] and f['identified'] == 0 and f['native'] == 0
@@ -916,56 +1003,64 @@ def sr_transcript(url, timeout=45, lang='en', auth_state=None, browser='auto'):
916
1003
  structure; this function returns it as prose an agent can READ and
917
1004
  understand from a blind user's perspective.
918
1005
  """
1006
+ # J4 (ronda 4): el driver de playwright NUNCA se paraba — una fuga
1007
+ # de proceso por llamada en un servidor MCP de larga vida
919
1008
  from playwright.sync_api import sync_playwright
920
1009
  pw = sync_playwright().start()
921
- nav = _get_browser(pw, preferred=browser)
922
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
923
- page = ctx.new_page() if auth_state else nav.new_page()
924
- try:
925
- page.goto(url, wait_until='load', timeout=timeout * 1000)
926
- page.wait_for_timeout(400)
927
- except Exception as e:
928
- ctx.close()
929
- _close_pool()
930
- return {'error': str(e)[:100]}
931
-
932
- try:
933
- tree = page.locator('body').aria_snapshot()
934
- except Exception:
935
- tree = None
936
1010
  try:
937
- ctx.close()
938
- except Exception:
939
- pass
1011
+ nav = _get_browser(pw, preferred=browser)
1012
+ ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1013
+ page = ctx.new_page() if auth_state else nav.new_page()
1014
+ try:
1015
+ page.goto(url, wait_until='load', timeout=timeout * 1000)
1016
+ page.wait_for_timeout(400)
1017
+ except Exception as e:
1018
+ ctx.close()
1019
+ _close_pool()
1020
+ return {'error': str(e)[:100]}
940
1021
 
941
- if not tree:
942
- return {'url': url, 'mode': 'sr-transcript',
943
- 'error': 'accessibility tree not available (Playwright >= 1.49 required)'}
1022
+ try:
1023
+ tree = page.locator('body').aria_snapshot()
1024
+ except Exception:
1025
+ tree = None
1026
+ try:
1027
+ ctx.close()
1028
+ except Exception:
1029
+ pass
944
1030
 
945
- # parse the YAML-like snapshot into linearized announcements
946
- import re
947
- announcements = []
948
- for line in tree.split('\n'):
949
- stripped = line.strip()
950
- if not stripped.startswith('- '):
951
- continue
952
- # quitar el guion inicial; el resto es el anuncio
953
- announcement = stripped[2:].rstrip(':')
954
- if announcement:
955
- announcements.append(announcement)
1031
+ if not tree:
1032
+ return {'url': url, 'mode': 'sr-transcript',
1033
+ 'error': 'accessibility tree not available (Playwright >= 1.49 required)'}
956
1034
 
957
- return {
958
- 'url': url,
959
- 'mode': 'sr-transcript',
960
- 'announcements': announcements[:200], # cap
961
- 'total': len(announcements),
962
- 'arbol_raw': tree[:5000] if len(tree) > 5000 else tree,
963
- 'note': ('Linearized announcement order — what a screen reader user hears. '
964
- 'Roles and names as computed by the browser. Use this to understand '
965
- 'the page from a blind user\'s perspective.'),
966
- }
1035
+ # parse the YAML-like snapshot into linearized announcements
1036
+ import re
1037
+ announcements = []
1038
+ for line in tree.split('\n'):
1039
+ stripped = line.strip()
1040
+ if not stripped.startswith('- '):
1041
+ continue
1042
+ # quitar el guion inicial; el resto es el anuncio
1043
+ announcement = stripped[2:].rstrip(':')
1044
+ if announcement:
1045
+ announcements.append(announcement)
1046
+
1047
+ return {
1048
+ 'url': url,
1049
+ 'mode': 'sr-transcript',
1050
+ 'announcements': announcements[:200], # cap
1051
+ 'total': len(announcements),
1052
+ 'arbol_raw': tree[:5000] if len(tree) > 5000 else tree,
1053
+ 'note': ('Linearized announcement order — what a screen reader user hears. '
1054
+ 'Roles and names as computed by the browser. Use this to understand '
1055
+ 'the page from a blind user\'s perspective.'),
1056
+ }
967
1057
 
968
1058
 
1059
+ finally:
1060
+ try:
1061
+ pw.stop()
1062
+ except Exception: # noqa: BLE001
1063
+ pass
969
1064
  _JS_HOVER_TEST = r'''() => {
970
1065
  // find elements that show tooltips/overlays on hover
971
1066
  const candidates = [];
@@ -984,11 +1079,11 @@ _JS_HOVER_TEST = r'''() => {
984
1079
  return candidates;
985
1080
  }'''
986
1081
 
987
- def audit_hover(url, timeout=45, lang='en', auth_state=None):
1082
+ def audit_hover(url, timeout=45, lang='en', auth_state=None, browser='auto'):
988
1083
  """1.4.13 Content on Hover or Focus: do tooltips dismiss on Escape?"""
989
1084
  from playwright.sync_api import sync_playwright
990
1085
  with sync_playwright() as p:
991
- nav = p.chromium.launch()
1086
+ nav = _get_browser(p, preferred=browser)
992
1087
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
993
1088
  page = ctx.new_page() if auth_state else nav.new_page()
994
1089
  try:
@@ -1167,14 +1262,14 @@ def audit_reflow(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1167
1262
  el layout)."""
1168
1263
  from playwright.sync_api import sync_playwright
1169
1264
  with sync_playwright() as p:
1170
- nav = p.chromium.launch()
1265
+ nav = _get_browser(p, preferred=browser)
1171
1266
  page = nav.new_page(viewport={'width': 1280, 'height': 800})
1172
1267
  try:
1173
1268
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1174
1269
  page.wait_for_timeout(300)
1175
1270
  except Exception as e: # noqa: BLE001
1176
1271
  nav.close()
1177
- return {'error': f'no se pudo cargar: {e}'}
1272
+ return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1178
1273
 
1179
1274
  page.set_viewport_size({'width': 320, 'height': 800})
1180
1275
  page.wait_for_timeout(500)
@@ -1240,7 +1335,7 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1240
1335
  """
1241
1336
  from playwright.sync_api import sync_playwright
1242
1337
  with sync_playwright() as p:
1243
- nav = p.chromium.launch()
1338
+ nav = _get_browser(p, preferred=browser)
1244
1339
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1245
1340
  page = ctx.new_page() if auth_state else nav.new_page()
1246
1341
  try:
@@ -1248,7 +1343,7 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1248
1343
  page.wait_for_timeout(400)
1249
1344
  except Exception as e: # noqa: BLE001
1250
1345
  nav.close()
1251
- return {'error': f'no se pudo cargar: {e}'}
1346
+ return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1252
1347
 
1253
1348
  page.evaluate("document.querySelectorAll('[data-a11ystop]').forEach(e => {"
1254
1349
  " e.removeAttribute('data-a11ystop'); e.removeAttribute('data-a11yruta'); })")
@@ -1521,7 +1616,7 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
1521
1616
  from .a11yaudit import _t as _t_audit, CRIT, compute_score
1522
1617
 
1523
1618
  with sync_playwright() as p:
1524
- nav = p.chromium.launch()
1619
+ nav = _get_browser(p, preferred=browser)
1525
1620
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1526
1621
  page = ctx.new_page() if auth_state else nav.new_page()
1527
1622
  try:
@@ -1553,10 +1648,7 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
1553
1648
  'findings': findings,
1554
1649
  'summary': {s2: sum(1 for h in findings if h['severity'] == s2)
1555
1650
  for s2 in ('high', 'medium', 'low')},
1556
- 'limits': ('Heurística de revisión (1.4.3/1.4.11 en HCM): los fills '
1557
- 'coloreados hardcoded en SVG suelen caer al heredado con '
1558
- 'forced-colors. La comprobación definitiva es visual con '
1559
- 'Windows High Contrast — esto la prepara, no la sustituye.'),
1651
+ 'limits': _LIMITS_HCM.get(lang, _LIMITS_HCM['en']),
1560
1652
  }
1561
1653
 
1562
1654
 
@@ -1590,7 +1682,7 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
1590
1682
  from .a11yaudit import _t as _t_audit, CRIT, compute_score
1591
1683
 
1592
1684
  with sync_playwright() as p:
1593
- nav = p.chromium.launch()
1685
+ nav = _get_browser(p, preferred=browser)
1594
1686
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1595
1687
  page = ctx.new_page() if auth_state else nav.new_page()
1596
1688
  try:
@@ -1625,8 +1717,7 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
1625
1717
  'findings': findings,
1626
1718
  'summary': {s2: sum(1 for h in findings if h['severity'] == s2)
1627
1719
  for s2 in ('high', 'medium', 'low')},
1628
- 'limits': ('Mide CSS animations y video[autoplay]. No cubre '
1629
- 'animaciones JS/WebGL ni parallax por scroll — revisión manual.'),
1720
+ 'limits': _LIMITS_MOTION.get(lang, _LIMITS_MOTION['en']),
1630
1721
  }
1631
1722
 
1632
1723
 
@@ -1639,7 +1730,7 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
1639
1730
  iniciada) para auditar detrás de login."""
1640
1731
  from playwright.sync_api import sync_playwright
1641
1732
  with sync_playwright() as p:
1642
- nav = p.chromium.launch()
1733
+ nav = _get_browser(p, preferred=browser)
1643
1734
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1644
1735
  page = ctx.new_page() if auth_state else nav.new_page()
1645
1736
  if color_scheme in ('dark', 'light'):
@@ -1652,7 +1743,7 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
1652
1743
  except Exception as e: # noqa: BLE001
1653
1744
  if not page.content() or page.url in ('about:blank', ''):
1654
1745
  nav.close()
1655
- return {'error': f'no se pudo cargar: {e}'}
1746
+ return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1656
1747
  try:
1657
1748
  data = page.evaluate(_JS, MAX_EXAMPLES)
1658
1749
  # 1.4.12: inject the WCAG spacing overrides, count clipped texts
@@ -1720,7 +1811,7 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
1720
1811
  from .contrast import T as _TC
1721
1812
  t9 = _TC.get(lang, _TC['es'])
1722
1813
  with sync_playwright() as p:
1723
- nav = p.chromium.launch()
1814
+ nav = _get_browser(p, preferred=browser)
1724
1815
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1725
1816
  page = ctx.new_page() if auth_state else nav.new_page()
1726
1817
  try:
@@ -1770,23 +1861,243 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
1770
1861
  pass
1771
1862
 
1772
1863
 
1864
+ # --- contrast walk: perceptual pass over EVERY rendered text element --------
1865
+
1866
+ _JS_WALK = r'''(maxEls) => {
1867
+ const visible = el => !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
1868
+ const directText = el => [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim());
1869
+ const parseC = s => { const m = String(s).match(/rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\)/);
1870
+ return m ? {r:+m[1], g:+m[2], b:+m[3], a: m[4] === undefined ? 1 : +m[4]} : null; };
1871
+ const effBg = el => {
1872
+ const layers = [];
1873
+ let image = null, n = el;
1874
+ while (n && n.nodeType === 1) {
1875
+ const cs = getComputedStyle(n);
1876
+ if (!image && cs.backgroundImage && cs.backgroundImage !== 'none') image = cs.backgroundImage;
1877
+ const c = parseC(cs.backgroundColor);
1878
+ if (c) { layers.push(c); if (c.a >= 1) break; }
1879
+ n = n.parentElement;
1880
+ }
1881
+ let r = 255, g = 255, b = 255;
1882
+ for (let i = layers.length - 1; i >= 0; i--) {
1883
+ const L = layers[i];
1884
+ r = L.r * L.a + r * (1 - L.a); g = L.g * L.a + g * (1 - L.a); b = L.b * L.a + b * (1 - L.a);
1885
+ }
1886
+ return {r: Math.round(r), g: Math.round(g), b: Math.round(b), image};
1887
+ };
1888
+ const path = el => {
1889
+ const parts = [];
1890
+ let n = el, depth = 0;
1891
+ while (n && n.nodeType === 1 && depth < 5) {
1892
+ if (n.id) { parts.unshift('#' + (window.CSS && CSS.escape ? CSS.escape(n.id) : n.id)); break; }
1893
+ const parent = n.parentElement;
1894
+ if (!parent) { parts.unshift(n.tagName.toLowerCase()); break; }
1895
+ const same = [...parent.children].filter(c => c.tagName === n.tagName);
1896
+ let s = n.tagName.toLowerCase();
1897
+ if (same.length > 1) s += ':nth-of-type(' + (same.indexOf(n) + 1) + ')';
1898
+ parts.unshift(s);
1899
+ n = parent; depth++;
1900
+ }
1901
+ return parts.join(' > ') || 'body';
1902
+ };
1903
+ const out = [];
1904
+ for (const el of document.querySelectorAll('body *')) {
1905
+ if (out.length >= maxEls) break;
1906
+ if (!visible(el) || !directText(el)) continue;
1907
+ const cs = getComputedStyle(el);
1908
+ const color = parseC(cs.color);
1909
+ if (!color) continue;
1910
+ if (color.a < 1) { out.push({skip: 'translucent', path: path(el)}); continue; }
1911
+ const fs = parseFloat(cs.fontSize) || 16;
1912
+ const fw = parseInt(cs.fontWeight) || 400;
1913
+ const bg = effBg(el);
1914
+ out.push({path: path(el), tag: el.tagName.toLowerCase(),
1915
+ text: (el.innerText || '').replace(/\s+/g, ' ').trim().slice(0, 60),
1916
+ color, bg: {r: bg.r, g: bg.g, b: bg.b, a: 1},
1917
+ bg_image: bg.image ? bg.image.slice(0, 100) : null,
1918
+ font_px: Math.round(fs * 10) / 10, bold: fw >= 700});
1919
+ }
1920
+ return out;
1921
+ }'''
1922
+
1923
+
1924
+ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
1925
+ lang='en', timeout=45, auth_state=None, browser='auto'):
1926
+ """Contraste PERCIBIDO de cada text_ renderizado de la página (1.4.3).
1927
+
1928
+ La capa informe de la familia de contraste: donde audit_dom audita y
1929
+ contrast-dom mide UN elemento contra lo que sea que tenga detrás, el walk
1930
+ recorre TODOS los text_ visibles y emite la tabla por elemento que consume
1931
+ un equipo de design system: ratio real, umbral (4.5 normal / 3.0 large por
1932
+ font-size/weight computados), verdict_ y sugerencia de color. Los fondos
1933
+ con imagen/gradiente se miden por PIXELES (peor caso, misma mecánica que
1934
+ contrast-dom) hasta max_sample; el resto queda honestamente sin medir.
1935
+ Con dark=True repite el pase bajo prefers-color-scheme: dark y añade el
1936
+ delta (nuevos fallos / resueltos) — la condición de display que el CSS
1937
+ declarado no ve.
1938
+
1939
+ Filtro honesto, no veredicto: text_ en shadow DOM, canvas, vídeo y
1940
+ pseudo-elementos no se captura; lo no medido se declara, jamás inventado.
1941
+ """
1942
+ from playwright.sync_api import sync_playwright
1943
+ from .contrast import ratio as _ratio, suggest as _suggest, parse_color
1944
+
1945
+ def _verdicts(entries):
1946
+ for e in entries:
1947
+ if e['ratio'] is not None:
1948
+ e['verdict'] = 'pass' if e['ratio'] >= e['threshold'] else 'fail'
1949
+
1950
+ def _pass(page):
1951
+ raw = page.evaluate(_JS_WALK, max_walk)
1952
+ entries, shot_jobs, skipped = [], [], 0
1953
+ for row in raw:
1954
+ if row.get('skip') == 'translucent':
1955
+ skipped += 1
1956
+ continue
1957
+ fg = {k: row['color'][k] for k in ('r', 'g', 'b')}
1958
+ bg = {k: row['bg'][k] for k in ('r', 'g', 'b')}
1959
+ large = row['font_px'] >= 24 or (row['font_px'] >= 18.66 and row['bold'])
1960
+ thr = 3.0 if large else 4.5
1961
+ entry = {'path': row['path'], 'tag': row['tag'], 'text': row['text'],
1962
+ 'font_px': row['font_px'], 'bold': row['bold'],
1963
+ 'large_text': large, 'threshold': thr,
1964
+ 'color': hexs(fg), 'bg': hexs(bg),
1965
+ 'bg_image': row['bg_image'], 'pixel_sampled': False,
1966
+ 'ratio': None, 'verdict': 'unmeasured'}
1967
+ if row['bg_image']:
1968
+ shot_jobs.append((entry, fg))
1969
+ else:
1970
+ entry['ratio'] = round(_ratio(fg, bg), 2)
1971
+ entries.append(entry)
1972
+ sampled = 0
1973
+ for entry, fg in shot_jobs:
1974
+ if sampled >= max_sample:
1975
+ continue # stays unmeasured — honest cap, never invented
1976
+ try:
1977
+ loc = page.locator(entry['path']).first
1978
+ box = loc.bounding_box()
1979
+ if not box or box['width'] < 3 or box['height'] < 3:
1980
+ continue
1981
+ m = _samples_background(loc, box, fg)
1982
+ if m:
1983
+ entry['ratio'] = m['worst_ratio']
1984
+ entry['median_ratio'] = m['median_ratio']
1985
+ entry['pixel_sampled'] = True
1986
+ sampled += 1
1987
+ except Exception: # noqa: BLE001 — one dead locator must not kill the walk
1988
+ continue
1989
+ _verdicts(entries)
1990
+ return entries, skipped
1991
+
1992
+ def _summarize(entries, skipped):
1993
+ fails = [e for e in entries if e['verdict'] == 'fail']
1994
+ worst = min((e for e in entries if e['ratio'] is not None),
1995
+ key=lambda e: e['ratio'], default=None)
1996
+ return {'pass': sum(1 for e in entries if e['verdict'] == 'pass'),
1997
+ 'fail': len(fails),
1998
+ 'unmeasured': sum(1 for e in entries if e['verdict'] == 'unmeasured'),
1999
+ 'fails_4_5_normal_text': sum(1 for e in fails if e['threshold'] >= 4.5),
2000
+ 'fails_3_0_large_text': sum(1 for e in fails if e['threshold'] < 4.5),
2001
+ 'translucent_text_skipped': skipped,
2002
+ 'pixel_sampled': sum(1 for e in entries if e['pixel_sampled']),
2003
+ 'worst_ratio': worst['ratio'] if worst else None,
2004
+ 'worst_element': worst['path'] if worst else None}
2005
+
2006
+ with sync_playwright() as p:
2007
+ def _run(scheme):
2008
+ nav = _get_browser(p, preferred=browser)
2009
+ ctx = (nav.new_context(storage_state=auth_state, color_scheme=scheme)
2010
+ if auth_state else nav.new_context(color_scheme=scheme))
2011
+ page = ctx.new_page()
2012
+ try:
2013
+ page.goto(url, wait_until='load', timeout=timeout * 1000)
2014
+ page.wait_for_timeout(300)
2015
+ return _pass(page)
2016
+ finally:
2017
+ try:
2018
+ ctx.close()
2019
+ nav.close()
2020
+ except Exception: # noqa: BLE001
2021
+ pass
2022
+
2023
+ entries, skipped = _run('light')
2024
+ report = {'mode': 'contrast-walk', 'url': url, 'scheme': 'light',
2025
+ 'checked': len(entries),
2026
+ 'elements': entries,
2027
+ 'summary': _summarize(entries, skipped)}
2028
+
2029
+ # suggestions for the worst flat-background fails (pixel zones have no
2030
+ # single background to suggest against — honest skip)
2031
+ fails = sorted((e for e in entries if e['verdict'] == 'fail' and not e['bg_image']),
2032
+ key=lambda e: e['ratio'])
2033
+ for e in fails[:8]:
2034
+ s = _suggest(parse_color(e['color']), parse_color(e['bg']),
2035
+ target=e['threshold'], lang=lang)
2036
+ if s:
2037
+ e['suggestion'] = s
2038
+
2039
+ if dark:
2040
+ entries_d, skipped_d = _run('dark')
2041
+ report['dark'] = {'scheme': 'dark', 'checked': len(entries_d),
2042
+ 'elements': entries_d,
2043
+ 'summary': _summarize(entries_d, skipped_d)}
2044
+ light_fails = {e['path'] for e in entries if e['verdict'] == 'fail'}
2045
+ dark_fails = {e['path'] for e in entries_d if e['verdict'] == 'fail'}
2046
+ report['dark_delta'] = {
2047
+ 'new_fails': sorted(dark_fails - light_fails)[:20],
2048
+ 'resolved': sorted(light_fails - dark_fails)[:20],
2049
+ 'note': ('a site that ignores prefers-color-scheme shows a zero '
2050
+ 'delta: same colors in both passes')}
2051
+
2052
+ report['limits'] = (
2053
+ 'Computed ratios cover effective background-color with alpha '
2054
+ 'compositing; text over images/gradients is pixel-sampled '
2055
+ '(worst-case) up to the cap, the rest is declared unmeasured. Text '
2056
+ 'in shadow DOM, canvas, video and pseudo-elements is not captured. '
2057
+ 'A fail is a filter finding (1.4.3), not a verdict — judge the '
2058
+ 'zone with contrast-dom.'
2059
+ if lang == 'en' else
2060
+ 'Los ratios computados cubren background-color efectivo con '
2061
+ 'composición alfa; el text_ sobre imágenes/gradientes se muestrea '
2062
+ 'por píxeles (peor caso) hasta el tope y el resto se declara sin '
2063
+ 'medir. El text_ en shadow DOM, canvas, vídeo y pseudo-elementos '
2064
+ 'no se captura. Un fallo es un hallazgo de filtro (1.4.3), no un '
2065
+ 'veredicto — juzga la zona con contrast-dom.')
2066
+ return report
2067
+
2068
+
1773
2069
  def contrast_dom_main(argv):
1774
- ap = argparse.ArgumentParser(description='Real text-over-anything contrast: screenshot + pixel sampling (auto-region)')
2070
+ ap = argparse.ArgumentParser(description='Real text-over-anything contrast: screenshot + pixel sampling (auto-region); --walk = perceptual pass over every text element')
1775
2071
  ap.add_argument('url')
1776
- ap.add_argument('--selector', required=True, help='CSS selector of the text element')
2072
+ ap.add_argument('--selector', help='CSS selector of the text element (required without --walk)')
2073
+ ap.add_argument('--walk', action='store_true',
2074
+ help='perceptual pass over every rendered text element (per-element table + suggestions)')
2075
+ ap.add_argument('--max-walk', type=int, default=400, help='max elements collected per pass (default 400)')
2076
+ ap.add_argument('--max-sample', type=int, default=24, help='max image/gradient backgrounds pixel-sampled (default 24)')
2077
+ ap.add_argument('--dark', action='store_true', help='add a second pass under prefers-color-scheme: dark + delta')
1777
2078
  ap.add_argument('--text', help='text color (default: computed from the element)')
1778
2079
  ap.add_argument('--sample', type=int, default=4)
1779
2080
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
1780
2081
  ap.add_argument('--timeout', type=int, default=45)
1781
2082
  a = ap.parse_args(argv)
1782
2083
  try:
1783
- res = contrast_dom(a.url, a.selector, text_color=a.text, sample=a.sample,
1784
- lang=a.lang, timeout=a.timeout)
2084
+ if a.walk:
2085
+ if not a.selector:
2086
+ res = contrast_walk(a.url, max_walk=a.max_walk, max_sample=a.max_sample,
2087
+ dark=a.dark, lang=a.lang, timeout=a.timeout)
2088
+ else:
2089
+ res = {'error': '--walk covers the whole page: drop --selector'}
2090
+ else:
2091
+ if not a.selector:
2092
+ res = {'error': 'need --selector ".hero h1" (or --walk for the whole page)'}
2093
+ else:
2094
+ res = contrast_dom(a.url, a.selector, text_color=a.text, sample=a.sample,
2095
+ lang=a.lang, timeout=a.timeout)
1785
2096
  except ImportError:
1786
2097
  print(json.dumps({'error': 'Playwright not installed'}))
1787
2098
  return 1
1788
2099
  print(json.dumps(res, ensure_ascii=False, indent=1))
1789
- return 0
2100
+ return 1 if isinstance(res, dict) and 'error' in res else 0
1790
2101
 
1791
2102
 
1792
2103
  def main(argv):
@@ -1852,5 +2163,24 @@ def kbd_main(argv):
1852
2163
  return 0
1853
2164
 
1854
2165
 
2166
+ def hover_main(argv):
2167
+ # the same audit the MCP tool a11y_hover runs (audit_hover, verbatim) —
2168
+ # 1.4.13 Content on Hover or Focus: do tooltips dismiss on Escape?
2169
+ ap = argparse.ArgumentParser(description='Tooltip dismissibility (1.4.13): hover + Escape, real browser')
2170
+ ap.add_argument('url')
2171
+ ap.add_argument('--lang', default='en', choices=['en', 'es'])
2172
+ ap.add_argument('--timeout', type=int, default=45)
2173
+ ap.add_argument('--auth-state', dest='auth_state',
2174
+ help='Path to a Playwright storage_state JSON to audit behind login')
2175
+ a = ap.parse_args(argv)
2176
+ try:
2177
+ res = audit_hover(a.url, timeout=a.timeout, lang=a.lang, auth_state=a.auth_state)
2178
+ except ImportError:
2179
+ print(json.dumps({'error': 'Playwright not installed'}))
2180
+ return 1
2181
+ print(json.dumps(res, ensure_ascii=False, indent=1))
2182
+ return 0
2183
+
2184
+
1855
2185
  if __name__ == '__main__':
1856
2186
  sys.exit(main(sys.argv[1:]))