@kinti/a11y-toolkit 5.29.0 → 5.31.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.
@@ -97,13 +97,22 @@ def act_ids(signal):
97
97
  def earl(report, url=None):
98
98
  """Informe de auditoría → EARL 1.0 JSON-LD (solo hallazgos con mapeo ACT)."""
99
99
  assertions = []
100
- # site crawls anidan en reports[]; entrada hostil (no-dict/no-list) → []
101
- _hls = report.get('findings') if isinstance(report, dict) else None
102
- if not isinstance(_hls, list) and isinstance(report, dict) and isinstance(report.get('reports'), list):
103
- _hls = [h for sub in report['reports']
104
- if isinstance(sub, dict) for h in sub.get('findings', [])
105
- if isinstance(h, dict)]
106
- for h in (_hls if isinstance(_hls, list) else []):
100
+ # site crawls anidan en reports[]: cada hallazgo pertenece a SU página —
101
+ # aplanar sin más atribuía el fallo de /gallery a la PORTADA (revisión
102
+ # externa, 3ª pasada). Se conserva el par (hallazgo, url de su página).
103
+ pares = []
104
+ if isinstance(report, dict):
105
+ _hls = report.get('findings')
106
+ # precedencia como a11yevidence: findings top-level NO VACÍOS son las
107
+ # copias re-verificadas; una lista vacía es «sin hallazgos propios» y
108
+ # los de las páginas anidadas siguen siendo del crawl
109
+ if isinstance(_hls, list) and _hls:
110
+ pares = [(h, url or report.get('url', '')) for h in _hls]
111
+ elif isinstance(report.get('reports'), list):
112
+ pares = [(h, (sub.get('url') or url or report.get('url', '')))
113
+ for sub in report['reports'] if isinstance(sub, dict)
114
+ for h in sub.get('findings', []) if isinstance(h, dict)]
115
+ for h, _subj in pares:
107
116
  if not isinstance(h, dict):
108
117
  continue
109
118
  if h.get('status') in _NOT_DEAD or h.get('disprover_status') in _NOT_DEAD:
@@ -116,7 +125,7 @@ def earl(report, url=None):
116
125
  assertions.append({
117
126
  '@type': 'earl:Assertion',
118
127
  'earl:subject': {'@type': 'earl:TestSubject',
119
- 'url': url or report.get('url', '')},
128
+ 'url': _subj},
120
129
  'earl:test': {'@type': 'earl:TestCase',
121
130
  'url': _ACT_URL.format(rid=rid),
122
131
  'title': name},
@@ -357,7 +357,7 @@ _SKIP_TEXT = re.compile(
357
357
  r'skip|jump to|saltar|ir al contenido|ir para o conte[uú]do|passer au contenu', re.I)
358
358
 
359
359
  # encabezados cortos legítimos (acrónimos y términos técnicos): «FAQ», «API»…
360
- _SHORT_HEADINGS = {'FAQ', 'API', 'CSS', 'APP', 'MAP', 'EN', 'DE', 'ES', 'PT', 'FR',
360
+ _SHORT_HEADINGS = {'FAQ', 'API', 'CSS', 'SVG', 'APP', 'MAP', 'EN', 'DE', 'ES', 'PT', 'FR',
361
361
  'IT', 'UI', 'UX', 'ID', 'TV', 'HR', 'PR', 'AI', 'PC', 'OK', '3D',
362
362
  'IOS', 'OS', 'GB', 'MB', 'KB', 'PDF', 'RSS', 'URL', 'WWW', 'XML',
363
363
  'HTTP', 'FAQS', 'BLOG', 'HOME', 'INICIO', 'NOTAS', 'AGENDA'}
@@ -483,6 +483,8 @@ class _Auditor(HTMLParser):
483
483
  self.controls_raw = [] # (kind, attrs, texto, [nombres imgs internas], hidden)
484
484
  self.headings_raw = [] # (nivel, attrs, texto, hidden)
485
485
  self.fields_raw = [] # (tag, kind, attrs, dentro_de_label, hidden)
486
+ self._fields_in_label = [] # campos que el <label> ABIERTO envuelve
487
+ self._wrap_label_text = {} # id(attrs del campo) → texto de su label envolvente
486
488
  self._heading_attrs = {}
487
489
  self.videos = 0
488
490
  self.videos_with_captions = 0
@@ -520,7 +522,10 @@ class _Auditor(HTMLParser):
520
522
  self.heading_role_removed = [] # h1-h6 con rol que sustituye al de heading
521
523
  self.text_spacing_important = [] # 1.4.12: spacing !important inline (ACT 24afc2/78fd32/9e45ec)
522
524
  self.links = {} # nombre normalizado → set de hrefs
525
+ self.links_elems = {} # entry_key → primeros elems (marcas 2.4.4)
523
526
  self.generics = 0
527
+ self.generic_link_elems = [] # marcas 2.4.4
528
+ self._label_elem_stack = [] # elem por <label> abierto (marcas 3.3.2)
524
529
  self.labels_for_dups = {} # id → n labels (los >1, varios)
525
530
  self._label_for_stack = [] # valor `for` de cada <label> abierto (None = envolvente)
526
531
  self._label_text_for = {} # id del for → texto del label (decisión post-parse)
@@ -528,7 +533,10 @@ class _Auditor(HTMLParser):
528
533
  self._list_depth = 0
529
534
  self._li_depth = 0
530
535
  self._bad_list = 0
531
- self.label_no_name = [] # (texto visible, aria-label) 2.5.3
536
+ self.label_no_name = [] # (texto visible, nombre efectivo) 2.5.3
537
+ self.label_no_name_elems = [] # marcas 2.5.3
538
+ self.label_in_name_raw = [] # (visible, aria-label, ids labelledby, attrs) — crudo, POST-parse decide
539
+ self.orphan_label_elems = [] # marcas 3.3.2
532
540
  self.lang_parts_invalid = [] # lang inválidos en elementos no-html
533
541
  self.down_events = [] # onmousedown/ontouchstart/onpointerdown
534
542
  self.captchas = [] # detección 3.3.8 — SOLO en contexto de autenticación
@@ -537,7 +545,7 @@ class _Auditor(HTMLParser):
537
545
  self._required_pend = [] # (tag, attrs) required: decide post-parse con el label
538
546
  self.mobiles = [] # marquee/blink/inline infinite animation (2.2.2)
539
547
  self._landmark_ids = set() # ids de landmarks: objetivos válidos de skip link
540
- self.nav_hrefs = set() # hrefs inside <nav> (site-level 3.2.3 signature)
548
+ self.nav_hrefs = [] # hrefs inside <nav> EN ORDEN (3.2.3 juzga el ORDEN relativo)
541
549
  self.help_hrefs = set() # help/contact links (site-level 3.2.6 signature)
542
550
  self.images_of_text = []
543
551
  self.vague_headings = []
@@ -560,6 +568,7 @@ class _Auditor(HTMLParser):
560
568
  self._group_role_depth = 0 # <div role=group/radiogroup> abierto (con nombre)
561
569
  self.has_search = False
562
570
  self.has_sitemap = False
571
+ self.has_index = False # índice/TOC/relacionados: vía 2.4.5 (4ª pasada)
563
572
  self.gestures = [] # touchmove/drag handlers (2.5.1)
564
573
  self.focus_blur = [] # onfocus="blur()": foco robado (2.1.1)
565
574
  self.focus_blur_elems = []
@@ -577,52 +586,29 @@ class _Auditor(HTMLParser):
577
586
  return
578
587
  self._ctrl.pop()
579
588
  a = c['attrs']
580
- text = ' '.join(c['text']).strip()
589
+ # nombre desde el texto VISIBLE (4ª pasada): el crudo incluía texto
590
+ # con display:none/visibility:hidden que accname excluye. .sr-only
591
+ # (clip) sigue contando: está en el árbol de accesibilidad; y el
592
+ # <title> de un svg interno entra por su canal (alternativo, no
593
+ # renderizado, PERO sí nombre)
594
+ text = ' '.join(x for x in (
595
+ ''.join(c.get('text_visible', [])).strip(),
596
+ ' '.join(c.get('text_alt', [])).strip()) if x)
581
597
  # decisión de nombre POST-parse: los ids de un aria-labelledby pueden
582
598
  # declararse después del control; se registra todo en crudo
583
599
  self.controls_raw.append((c.get('kind') or tag, a, text, c.get('img_attrs', []),
584
600
  c.get('hidden', False)))
585
- # 2.5.3 label in name — algoritmo de WCAG Understanding 2.5.3: sin el
586
- # contenido entre paréntesis, minúsculas, sin puntuación, y la
587
- # etiqueta visible contenida POR PALABRAS en el nombre («just ice» ≠
588
- # «justice»; «Discover It» falla contra «Discover Italy»). Una
589
- # etiqueta visible de un solo carácter/símbolo (X, emoji) es texto no
590
- # verbal: exenta. La etiqueta es la que se VEE (la oculta por CSS no)
591
- # concatenación DOM fiel: sin espacios artificiales — los del DOM ya
592
- # vienen en los propios nodos de texto (2ee8b8: «W C A G» ≠ «ACT»)
601
+ # 2.5.3 label in name — el VEREDICTO se decide POST-parse (los ids de
602
+ # aria-labelledby pueden declararse después del control). Aquí solo se
603
+ # registra lo crudo; el algoritmo vive abajo, sobre el nombre EFECTIVO
604
+ # por precedencia accname (revisión externa, 4ª pasada: comparar
605
+ # contra aria-label penalizaba controles nombrados por labelledby y
606
+ # aprobaba el caso inverso)
593
607
  _vis = ''.join(c.get('text_visible', [])).strip()
594
608
  _al = (a.get('aria-label') or '').strip()
595
- # página con fuente-icono declarada (Material Icons, Font Awesome…):
596
- # el «texto» de un botón puede ser un glifo no verbal — exento
597
- _icon_font = bool(re.search(
598
- r"font-family\s*:[^;}]*?(Material[+ ]Icons|Font Awesome|glyphicon|icomoon|feather)"
599
- r"|@font-face[^}]*?(Material[+ ]Icons|Font Awesome|glyphicon|icomoon|feather)",
600
- self._styles_text, re.I)) or bool(re.search(
601
- r'fonts\.googleapis\.com/icon|/material-icons|font-?awesome|/icomoon',
602
- ' '.join(getattr(self, '_icon_links', [])), re.I))
603
- # página con fuente-icono: el «texto» del control puede ser un glifo
604
- # no verbal (ligadura Material «shopping_cart») — exento en CUALQUIER
605
- # control (enlaces-icono incluidos), no solo <button>
606
- if not _icon_font and _vis and _al:
607
- def _lin_words(txt):
608
- txt = re.sub(r'\([^)]*\)', ' ', txt)
609
- # la puntuación se ELIMINA sin partir palabras («11×3=33» →
610
- # «1133»: una sola palabra) — algoritmo 2.5.3
611
- return [w for w in re.sub(r'[^\w\s]|_', '', txt.lower()).split() if w]
612
- _vp, _ap2 = _lin_words(_vis), _lin_words(_al)
613
- _mismatch = False
614
- if _vp and _ap2:
615
- if len(_vp) == 1 and len(_vp[0]) <= 2 and _vp[0].isalpha():
616
- _mismatch = False # letra-símbolo única (X): texto no verbal
617
- else:
618
- # RODAJA CONTIGUA EXACTA: «discover it» no cabe en
619
- # «discover italy» (it ≠ italy); «download specification»
620
- # no cabe en «download the specification»; «you how are»
621
- # no en «how are you» aunque estén todas las palabras
622
- _mismatch = not any(_ap2[i:i + len(_vp)] == _vp
623
- for i in range(len(_ap2) - len(_vp) + 1))
624
- if _mismatch:
625
- self.label_no_name.append((_vis[:40], _al[:60]))
609
+ _lb_ids = (a.get('aria-labelledby') or '').split()
610
+ if _vis and (_al or _lb_ids) and len(self.label_in_name_raw) < 30:
611
+ self.label_in_name_raw.append((_vis[:80], _al[:120], _lb_ids[:6], a))
626
612
  if tag == 'a' and not c.get('hidden'):
627
613
  if (a.get('target') or '').lower() == '_blank':
628
614
  self.blank_total += 1
@@ -645,8 +631,13 @@ class _Auditor(HTMLParser):
645
631
  if name and href:
646
632
  entry_key = ' '.join(name.lower().split())[:60]
647
633
  self.links.setdefault(entry_key, set()).add(href)
634
+ _le_list = self.links_elems.setdefault(entry_key, [])
635
+ if len(_le_list) < 5:
636
+ _le_list.append(a)
648
637
  if entry_key in _GENERIC_TEXT:
649
638
  self.generics += 1
639
+ if len(self.generic_link_elems) < 5:
640
+ self.generic_link_elems.append(a)
650
641
 
651
642
  def _field_note(self):
652
643
  """El elemento que acaba de abrirse es un campo: marca su <label> ancestro."""
@@ -692,6 +683,16 @@ class _Auditor(HTMLParser):
692
683
  # ruta determinista del elemento (kernel de anotación): nth-of-type
693
684
  # SIEMPRE (los id duplicados no pueden romper la ruta) y los void no
694
685
  # abren pila (no tienen handle_endtag)
686
+ # tbody IMPLÍCITO bajo <table>: el navegador normaliza <table><tr>
687
+ # insertando <tbody>; sin reflejarlo, las rutas nth-of-type que
688
+ # cruzan la mesa no resuelven en el DOM real (Chromium: table>tr
689
+ # casa CERO elementos — revisión externa 2026-11-22). Se abre igual
690
+ # que un tag normal y </table> lo cierra con el resto de la pila.
691
+ if tag == 'tr' and self._path_stack and self._path_stack[-1][0] == 'table':
692
+ _parent_tb = self._path_stack[-1]
693
+ _parent_tb[2]['tbody'] = _parent_tb[2].get('tbody', 0) + 1
694
+ self._path_stack.append(
695
+ ('tbody', _parent_tb[1] + '>' + path_segment('tbody', _parent_tb[2]['tbody']), {}))
695
696
  if self._path_stack:
696
697
  _parent = self._path_stack[-1]
697
698
  _parent[2][tag] = _parent[2].get(tag, 0) + 1
@@ -727,8 +728,10 @@ class _Auditor(HTMLParser):
727
728
  _hidden_aria = True
728
729
  elif _ah_val == 'false':
729
730
  _hidden_aria = False
731
+ # inert (4ª pasada): el subtroke queda no interactivo Y fuera del
732
+ # árbol de accesibilidad — un botón dentro de inert JAMÁS es enfocable
730
733
  _hidden = _inh or 'hidden' in a or 'display:none' in _style \
731
- or 'visibility:hidden' in _style or _hidden_aria
734
+ or 'visibility:hidden' in _style or _hidden_aria or 'inert' in a
732
735
  # <template> es contenido INERTE (spec HTML): no renderiza, no recibe
733
736
  # foco, sus ids no existen — se audita como oculto y los colectores
734
737
  # que no consultan _hidden llevan guardia explícita
@@ -862,12 +865,23 @@ class _Auditor(HTMLParser):
862
865
  'img_attrs': [], 'hidden': _hidden})
863
866
  href = (a.get('href') or '').strip()
864
867
  if self._in_nav and href and not href.startswith('#'):
865
- self.nav_hrefs.add(href.split('#')[0].rstrip('/'))
868
+ _nv = href.split('#')[0].rstrip('/')
869
+ if _nv not in self.nav_hrefs:
870
+ self.nav_hrefs.append(_nv)
866
871
  if href and re.search(r'help|contact|support|ayuda|contacto|soporte|asistencia',
867
872
  href, re.I):
868
873
  self.help_hrefs.add(href.split('#')[0].rstrip('/'))
869
874
  if href and re.search(r'sitemap|site-map|mapa-del-sitio|mapa_web|mapaweb', href, re.I):
870
875
  self.has_sitemap = True
876
+ # 2.4.5 vía adicional (4ª pasada, afinada 7ª): un índice/TOC
877
+ # o bloque de relacionados SON formas de encontrar páginas —
878
+ # por SUBCADENA en el último segmento: los límites de palabra
879
+ # con puntuación dejaban fuera /blog/index.php, /articulos-relacionados
880
+ if href:
881
+ _seg = href.split('#')[0].rstrip('/').split('/')[-1].lower()
882
+ if re.search(r'index|ind[ií]ce|contents|\btoc\b|related|relacionad|ver-tambien|see-also|sobre-este|more-like|similares|etiquetas|tags\b|categorias|categories|archivo|archive',
883
+ _seg):
884
+ self.has_index = True
871
885
  elif tag == 'input':
872
886
  self._field_note()
873
887
  kind = (a.get('type') or 'text').lower()
@@ -882,8 +896,19 @@ class _Auditor(HTMLParser):
882
896
  if kind == 'search' or re.search(r'search|busqueda|b[uú]squeda', (a.get('name') or '') + (a.get('id') or ''), re.I):
883
897
  self.has_search = True
884
898
  if kind in _FIELDS:
899
+ if self._wrap_labels(a):
900
+ self._fields_in_label.append(id(a))
885
901
  self.fields_raw.append((tag, kind, a, self._wrap_labels(a), _hidden))
886
- if 'autocomplete' not in a and kind != 'search' and (
902
+ # 1.3.5 aplicabilidad y cobertura por SEPARADO (4ª pasada):
903
+ # type=email asumía «dato de la persona usuaria» aunque fuera
904
+ # el correo del DESTINATARIO, y autocomplete=off daba la
905
+ # condición por cubierta — off/on no identifican propósito
906
+ _recipient = re.search(
907
+ r'(?<![a-z0-9])(to|recipient|destinatari[oa]s?|destino|friend|amigo)(?![a-z0-9])',
908
+ ((a.get('name') or '') + ' ' + (a.get('id') or '')), re.I)
909
+ _tok_ac = (a.get('autocomplete') or '').strip().lower()
910
+ _covered = bool(_tok_ac) and _tok_ac not in ('off', 'on')
911
+ if (not _covered) and kind != 'search' and not _recipient and (
887
912
  kind in ('email', 'tel')
888
913
  or _PERSONAL_DATA.search((a.get('name') or '') + ' ' + (a.get('id') or ''))):
889
914
  self.missing_autocomplete.append(f'input type={kind} name={a.get("name") or "?"}'[:44])
@@ -929,11 +954,15 @@ class _Auditor(HTMLParser):
929
954
  f'{_mal} (input name={a.get("name") or "?"})'[:60])
930
955
  elif tag in ('select', 'textarea'):
931
956
  self._field_note()
957
+ if self._wrap_labels(a):
958
+ self._fields_in_label.append(id(a))
932
959
  self.fields_raw.append((tag, tag, a, self._wrap_labels(a), _hidden))
933
960
  elif tag == 'label':
934
961
  self._label_depth += 1
935
962
  self._label_text_current = []
963
+ self._fields_in_label = [] # campos que ESTE label envuelve
936
964
  self._labels_stack.append(False)
965
+ self._label_elem_stack.append(a)
937
966
  self._label_for_stack.append(a.get('for') or None)
938
967
  if a.get('for'):
939
968
  self._labels_for[a['for']] = self._labels_for.get(a['for'], 0) + 1
@@ -1261,10 +1290,12 @@ class _Auditor(HTMLParser):
1261
1290
  _hrole = (a.get('role') or '').strip().lower()
1262
1291
  if _hrole in ('none', 'presentation') or self._in_template:
1263
1292
  pass
1264
- elif _hrole and _hrole != 'heading':
1265
- # CUALQUIER otro rol explícito SUSTITUYE al de heading (la
1266
- # primera regla de ARIA): h2 role=button desaparece de la
1267
- # navegación por encabezados del AT — se registra (1.3.1)
1293
+ elif _hrole and _hrole != 'heading' and _hrole in _ROLES_ARIA:
1294
+ # un rol VALIDO distinto de heading SUSTITUYE al de heading
1295
+ # (la primera regla de ARIA): h2 role=button desaparece de la
1296
+ # navegación por encabezados del AT — se registra (1.3.1).
1297
+ # (7a pasada) un rol DESCONOCIDO (role="bogus heading") el
1298
+ # navegador lo IGNORA y el h2 SIGUE siendo heading: sin aviso
1268
1299
  if not _hidden and len(self.heading_role_removed) < 12:
1269
1300
  _nm = (a.get('aria-label') or '').strip()[:24]
1270
1301
  self.heading_role_removed.append(
@@ -1371,8 +1402,11 @@ class _Auditor(HTMLParser):
1371
1402
  if _svgtxt:
1372
1403
  if self._ctrl:
1373
1404
  # nombre SÍ (accname from content); VISIBLE no — el
1374
- # <title> de svg es texto alternativo, no renderizado
1405
+ # <title> de svg es texto alternativo, no renderizado.
1406
+ # Canal aparte (4ª pasada): el nombre del control parte
1407
+ # del texto VISIBLE y el título-vía-svg entra aquí
1375
1408
  self._ctrl[-1]['text'].append(_svgtxt)
1409
+ self._ctrl[-1].setdefault('text_alt', []).append(_svgtxt)
1376
1410
  for _fr in reversed(self._el_stack):
1377
1411
  if _fr[0] == 'svg':
1378
1412
  self._svg_titles[id(_fr[1])] = _svgtxt
@@ -1402,8 +1436,18 @@ class _Auditor(HTMLParser):
1402
1436
  _lfor = self._label_for_stack.pop()
1403
1437
  if _lfor and txt:
1404
1438
  self._label_text_for[_lfor] = txt
1405
- if self._labels_stack and not self._labels_stack.pop():
1406
- self.orphan_labels += 1
1439
+ # texto del label ENVOLVENTE por campo (a11ylocate indexa el
1440
+ # campo por su nombre visible — la misma resolución del auditor)
1441
+ if txt:
1442
+ for _fa in getattr(self, '_fields_in_label', []):
1443
+ self._wrap_label_text[_fa] = txt
1444
+ if self._labels_stack:
1445
+ # pila paralela de elems: pop SIEMPRE (un pop por cierre)
1446
+ _le = self._label_elem_stack.pop() if self._label_elem_stack else None
1447
+ if not self._labels_stack.pop():
1448
+ self.orphan_labels += 1
1449
+ if _le is not None and len(self.orphan_label_elems) < 5:
1450
+ self.orphan_label_elems.append(_le)
1407
1451
  elif tag == 'fieldset':
1408
1452
  self._in_fieldset = False
1409
1453
  elif tag == 'form':
@@ -1588,7 +1632,10 @@ class _Auditor(HTMLParser):
1588
1632
  self._ctrl[-1]['text_visible'].append(data)
1589
1633
  if self._heading_level is not None and not _hidden_ah:
1590
1634
  self._heading_text.append(data)
1591
- m = _SENSORIAL.search(data)
1635
+ # las CITAS son menciones legítimas (un checklist que cita el
1636
+ # anti-patrón «el botón de la derecha» para enseñarlo no incumple:
1637
+ # espejo de _sin_citas del corrector de plantillas)
1638
+ m = _SENSORIAL.search(re.sub(r'«[^»]*»|“[^”]*”|"[^"]*"', ' ', data))
1592
1639
  if m and len(self.sensory) < 6:
1593
1640
  self.sensory.append(m.group(0).strip()[:60])
1594
1641
 
@@ -1894,9 +1941,14 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
1894
1941
  if _fa.get('role') == a.get('role') and not a.get('id') and not _fa.get('id')),
1895
1942
  '')
1896
1943
  _placeholder = (a.get('placeholder') or '').strip() if tag != 'select' else ''
1944
+ # el <label> SOLO cuenta con TEXTO (4ª pasada: un label VACÍO daba
1945
+ # nombre y Chromium exponía el campo sin nombre)
1946
+ _label_txt = (getattr(p, '_label_text_for', {}).get(a.get('id'), '')
1947
+ or getattr(p, '_wrap_label_text', {}).get(id(a), '')).strip()
1897
1948
  _has_real_name = bool(al or lb or ti
1898
- or (en_label and _is_labelable)
1899
- or (_is_labelable and a.get('id') and a['id'] in p._labels_for)
1949
+ or (en_label and _is_labelable and _label_txt)
1950
+ or (_is_labelable and a.get('id') and a['id'] in p._labels_for
1951
+ and getattr(p, '_label_text_for', {}).get(a.get('id'), '').strip())
1900
1952
  or _content_name)
1901
1953
  if not (_has_real_name or _placeholder):
1902
1954
  p.fields_no_label.append((kind or tag, (a.get('name') or '')[:60], a.get('id')))
@@ -1971,7 +2023,9 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
1971
2023
  paths=[p._elem_paths[id(_a)] for _a in p.role_no_tabindex_elems
1972
2024
  if id(_a) in p._elem_paths][:5])
1973
2025
  if p.orphan_labels:
1974
- add('low', '3.3.2', 'label_orphan', n=p.orphan_labels)
2026
+ add('low', '3.3.2', 'label_orphan', n=p.orphan_labels,
2027
+ paths=[p._elem_paths[id(_a)] for _a in p.orphan_label_elems
2028
+ if id(_a) in p._elem_paths][:5])
1975
2029
  if p._bad_list:
1976
2030
  add('medium', '1.3.1', 'list_structure', n=p._bad_list)
1977
2031
  if p.root_tag in ('svg', 'math'):
@@ -2158,11 +2212,43 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2158
2212
  add('medium', '1.4.2', 'video_autoplay', n=p.media_autoplay,
2159
2213
  paths=[p._elem_paths[id(_a)] for _a in p.media_autoplay_elems
2160
2214
  if id(_a) in p._elem_paths][:5])
2215
+ # 2.5.3, veredicto POST-parse (4ª pasada): el nombre EFECTIVO por
2216
+ # precedencia accname — labelledby (ids resueltos, unidos en orden) GANA
2217
+ # a aria-label. El nombre del propio contenido cumple trivialmente.
2218
+ def _lin_words(txt):
2219
+ txt = re.sub(r'\([^)]*\)', ' ', txt)
2220
+ return [w for w in re.sub(r'[^\w\s]|_', '', txt.lower()).split() if w]
2221
+ _icon_font = bool(re.search(
2222
+ r"font-family\s*:[^;}]*?(Material[+ ]Icons|Font Awesome|glyphicon|icomoon|feather)"
2223
+ r"|@font-face[^}]*?(Material[+ ]Icons|Font Awesome|glyphicon|icomoon|feather)",
2224
+ getattr(p, '_styles_text', ''), re.I)) or bool(re.search(
2225
+ r'fonts\.googleapis\.com/icon|/material-icons|font-?awesome|/icomoon',
2226
+ ' '.join(getattr(p, '_icon_links', [])), re.I))
2227
+ for _vis, _al, _lb_ids, _a in p.label_in_name_raw:
2228
+ _lb_txt = ' '.join((p._id_texts.get(i, '') or '').strip()
2229
+ for i in _lb_ids if (p._id_texts.get(i, '') or '').strip())
2230
+ _name_eff = _lb_txt or _al
2231
+ _vp, _np2 = _lin_words(_vis), _lin_words(_name_eff)
2232
+ if not (_vp and _np2):
2233
+ continue
2234
+ if len(_vp) == 1 and len(_vp[0]) <= 2 and _vp[0].isalpha():
2235
+ continue # letra-símbolo única (X, emoji): texto no verbal
2236
+ # fuente-icono: SOLO controles de token único (ligadura); un botón de
2237
+ # texto con dos palabras JAMÁS es un glifo (4ª pasada)
2238
+ if _icon_font and len(_vp) == 1:
2239
+ continue
2240
+ # RODAJA CONTIGUA EXACTA: «discover it» no cabe en «discover italy»
2241
+ if not any(_np2[i:i + len(_vp)] == _vp for i in range(len(_np2) - len(_vp) + 1)):
2242
+ p.label_no_name.append((_vis[:40], _name_eff[:60]))
2243
+ if len(p.label_no_name_elems) < 5:
2244
+ p.label_no_name_elems.append(_a)
2161
2245
  if p.label_no_name:
2162
2246
  _ln = p.label_no_name[0]
2163
2247
  add_ej('medium', '2.5.3', 'label_in_name',
2164
- [f'«{t}» vs aria-label «{al}»' for t, al in p.label_no_name],
2165
- n=len(p.label_no_name), example=f'{_ln[0]} ≠ {_ln[1]}')
2248
+ [f'«{t}» vs name «{al}»' for t, al in p.label_no_name],
2249
+ n=len(p.label_no_name), example=f'{_ln[0]} ≠ {_ln[1]}',
2250
+ paths=[p._elem_paths[id(_a)] for _a in p.label_no_name_elems
2251
+ if id(_a) in p._elem_paths][:5])
2166
2252
  if p.lang_parts_invalid:
2167
2253
  add_ej('medium', '3.1.2', 'element_lang_invalid', p.lang_parts_invalid,
2168
2254
  n=len(p.lang_parts_invalid), example=', '.join(p.lang_parts_invalid[:4]))
@@ -2237,10 +2323,16 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2237
2323
  add('low', '1.3.1', 'landmark_dup', n=len(lm_dups), example=', '.join(lm_dups[:4]))
2238
2324
  if p.generics >= 2: # un enlace genérico único suele desambiguarse por contexto
2239
2325
  gen = [f'«{k}»' for k in p.links if k in _GENERIC_TEXT][:4]
2240
- add('low', '2.4.4', 'generic_link', n=p.generics, example=', '.join(gen))
2326
+ add('low', '2.4.4', 'generic_link', n=p.generics, example=', '.join(gen),
2327
+ paths=[p._elem_paths[id(_a)] for _a in p.generic_link_elems
2328
+ if id(_a) in p._elem_paths][:5])
2241
2329
  same = sum(1 for _k, hrefs in p.links.items() if len(hrefs) > 1)
2242
2330
  if same:
2243
- add('low', '2.4.4', 'same_name_links', n=same)
2331
+ _same_elems = [p.links_elems.get(_k, [None])[0]
2332
+ for _k, _hs in p.links.items() if len(_hs) > 1]
2333
+ add('low', '2.4.4', 'same_name_links', n=same,
2334
+ paths=[p._elem_paths[id(_a)] for _a in _same_elems
2335
+ if _a is not None and id(_a) in p._elem_paths][:5])
2244
2336
  ak_dups = [f'"{k}" ×{v}' for k, v in p.accesskeys.items() if v > 1]
2245
2337
  if ak_dups:
2246
2338
  add('low', '2.1.1', 'accesskey_dup', n=len(ak_dups), example=', '.join(ak_dups[:4]))
@@ -2366,7 +2458,7 @@ class _CheckedRedirect(urllib.request.HTTPRedirectHandler):
2366
2458
  _OPENER = urllib.request.build_opener(_CheckedRedirect)
2367
2459
 
2368
2460
 
2369
- def _fetch(url, timeout=30, truncate_at=None, accept_ct=()):
2461
+ def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None):
2370
2462
  scheme = url.split(':', 1)[0].lower() if ':' in url else ''
2371
2463
  if scheme not in ('http', 'https'):
2372
2464
  # política única para TODAS las rutas de descarga (audit_url la
@@ -2378,6 +2470,11 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=()):
2378
2470
  'Accept-Encoding': 'gzip',
2379
2471
  })
2380
2472
  with _OPENER.open(req, timeout=timeout) as r:
2473
+ # verdad de navegación (4ª pasada): seguir una redirección en
2474
+ # silencio hacía puntuar 100 la pantalla de acceso BAJO la URL pedida
2475
+ if _meta is not None:
2476
+ _meta['final_url'] = r.geturl()
2477
+ _meta['status'] = getattr(r, 'status', None)
2381
2478
  ceiling = truncate_at or MAX_HTML
2382
2479
  # TOTAL-CLOCK reading: the socket timeout is per-operation and a server
2383
2480
  # dribbling one byte per operation reset it forever. Read in chunks
@@ -2435,15 +2532,29 @@ _T_SCHEME = {
2435
2532
  def audit_url(url, timeout=30, lang='en', standard=None, target=None):
2436
2533
  if url.split(':')[0].lower() not in ('http', 'https'):
2437
2534
  return {'error': _T_SCHEME.get(lang, _T_SCHEME['es'])}
2535
+ _meta = {}
2438
2536
  try:
2439
- html_text = _fetch(url, timeout=timeout)
2537
+ html_text = _fetch(url, timeout=timeout, _meta=_meta)
2440
2538
  except _FetchError as e:
2441
2539
  return {'error': _t(lang, e.key).format(**e.fmt)}
2442
2540
  except ValueError as e:
2443
2541
  return {'error': str(e)}
2444
2542
  except Exception as e: # noqa: BLE001
2445
2543
  return {'error': _t(lang, 'fetch_error').format(e=e)}
2446
- return audit_html(html_text, url, lang=lang, standard=standard, target=target)
2544
+ # verdad de navegación (4ª pasada): el informe lleva la URL FINAL (la
2545
+ # página que de verdad se miró), la PEDIDA y el estado HTTP
2546
+ final_url = _meta.get('final_url') or url
2547
+ res = audit_html(html_text, final_url.split('#')[0], lang=lang,
2548
+ standard=standard, target=target)
2549
+ if final_url.split('#')[0] != url.split('#')[0]:
2550
+ res['requested_url'] = url
2551
+ res['redirect_note'] = (
2552
+ 'la URL pedida redirigió: el informe es de la página FINAL'
2553
+ if lang == 'es' else
2554
+ 'the requested URL redirected: this report is for the FINAL page')
2555
+ if _meta.get('status'):
2556
+ res['http_status'] = _meta['status']
2557
+ return res
2447
2558
 
2448
2559
 
2449
2560
  _LOC = re.compile(r'<loc>\s*([^<\s]+)\s*</loc>', re.I)
@@ -2510,13 +2621,28 @@ def evaluate_site(parsers, lang='en'):
2510
2621
  2.4.5 multiple ways. Pure function so tests need no network."""
2511
2622
  out = []
2512
2623
  if len(parsers) >= 3:
2513
- signatures = [frozenset(p.nav_hrefs) for p in parsers if p.nav_hrefs]
2514
- if len(signatures) >= 3 and len(set(signatures)) > 1:
2515
- out.append({'severity': 'medium', 'criterion': _crit(lang, '3.2.3'),
2516
- 'signal': 'nav_inconsistent',
2517
- 'issue': _t(lang, 'nav_inconsistent').format(
2518
- example=f'{len(set(signatures))} distintas en {len(signatures)} páginas'),
2519
- 'remediation': _t(lang, 'nav_inconsistent_rem')})
2624
+ # 3.2.3 evalúa el ORDEN RELATIVO de la navegación repetida (4ª
2625
+ # pasada): comparar conjuntos dejaba pasar dos enlaces intercambiados
2626
+ # y disparaba ante un enlace contextual INSERTADO sin mover a los
2627
+ # demás. Se juzga la secuencia de los enlaces COMPARTIDOS por par
2628
+ seqs = [list(p.nav_hrefs) for p in parsers if p.nav_hrefs]
2629
+ if len(seqs) >= 3:
2630
+ reordered_pairs = 0
2631
+ for i in range(len(seqs)):
2632
+ for j in range(i + 1, len(seqs)):
2633
+ shared = set(seqs[i]) & set(seqs[j])
2634
+ if len(shared) < 2:
2635
+ continue
2636
+ order_a = [h for h in seqs[i] if h in shared]
2637
+ order_b = [h for h in seqs[j] if h in shared]
2638
+ if order_a != order_b:
2639
+ reordered_pairs += 1
2640
+ if reordered_pairs:
2641
+ out.append({'severity': 'medium', 'criterion': _crit(lang, '3.2.3'),
2642
+ 'signal': 'nav_inconsistent',
2643
+ 'issue': _t(lang, 'nav_inconsistent').format(
2644
+ example=f'{reordered_pairs} pares de páginas con orden distinto en {len(seqs)}'),
2645
+ 'remediation': _t(lang, 'nav_inconsistent_rem')})
2520
2646
  # 3.2.6 Consistent Help (A, new in 2.2): help links stable across pages
2521
2647
  signatures_help = [frozenset(p.help_hrefs) for p in parsers if p.help_hrefs]
2522
2648
  if len(signatures_help) >= 2 and len(parsers) >= 3 and len(set(signatures_help)) > 1:
@@ -2528,11 +2654,22 @@ def evaluate_site(parsers, lang='en'):
2528
2654
  # 2.4.5 exige múltiples formas de encontrar PÁGINAS: con una muestra de
2529
2655
  # una sola página no hay proceso multi-página que reclamarlo (FP en
2530
2656
  # sitios de una página — la excepción del propio criterio)
2531
- if len(parsers) >= 2 and not any(p.has_search or p.has_sitemap for p in parsers):
2532
- out.append({'severity': 'medium', 'criterion': _crit(lang, '2.4.5'),
2533
- 'signal': 'no_multiple_ways',
2534
- 'issue': _t(lang, 'no_multiple_ways'),
2535
- 'remediation': _t(lang, 'no_multiple_ways_rem')})
2657
+ # 2.4.5 (4ª pasada): un índice/TOC o enlaces relacionados SON vías; sin
2658
+ # buscador NI sitemap en una muestra pequeña, la evidencia es PARCIAL —
2659
+ # la reseña baja a low y lo declara
2660
+ _has_way = any(p.has_search or p.has_sitemap for p in parsers)
2661
+ _has_index_way = any(getattr(p, 'has_index', False) for p in parsers)
2662
+ if len(parsers) >= 2 and not _has_way and not _has_index_way:
2663
+ entry = {'criterion': _crit(lang, '2.4.5'),
2664
+ 'signal': 'no_multiple_ways',
2665
+ 'issue': _t(lang, 'no_multiple_ways'),
2666
+ 'remediation': _t(lang, 'no_multiple_ways_rem')}
2667
+ entry['severity'] = 'medium' if len(parsers) >= 4 else 'low'
2668
+ entry['issue'] = entry['issue'] + (
2669
+ ' (partial evidence: search and sitemap not found in a small sample)'
2670
+ if lang == 'en' else
2671
+ ' (evidencia parcial: ni buscador ni sitemap en una muestra pequeña)')
2672
+ out.append(entry)
2536
2673
  return out
2537
2674
 
2538
2675
 
@@ -2543,14 +2680,19 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
2543
2680
  max_pages = max(1, min(20, int(max_pages)))
2544
2681
  import time
2545
2682
  deadline = (time.monotonic() + budget) if budget else None
2683
+ # (7ª pasada) la PRIMERA página también contra su URL FINAL: /deep2 que
2684
+ # redirige a /deep reportaba bajo /deep2 y sus enlaces relativos se
2685
+ # resolvían contra la ruta PEDIDA — el camino equivocado
2686
+ _m0 = {}
2546
2687
  try:
2547
- html_text = _fetch(url, timeout=timeout)
2688
+ html_text = _fetch(url, timeout=timeout, _meta=_m0)
2548
2689
  except _FetchError as e:
2549
2690
  return {'error': _t(lang, e.key).format(**e.fmt)}
2550
2691
  except ValueError as e:
2551
2692
  return {'error': str(e)}
2552
2693
  except Exception as e: # noqa: BLE001
2553
2694
  return {'error': _t(lang, 'fetch_error').format(e=e)}
2695
+ entry_final = ((_m0.get('final_url') or url).split('#')[0]).rstrip('/')
2554
2696
  # el parser jamás tira el crawl entero: una página hostil → informe de
2555
2697
  # error de ESA página y se sigue con la cola
2556
2698
  def _parse_page(html_txt, page_url):
@@ -2561,15 +2703,15 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
2561
2703
  except Exception as e: # noqa: BLE001
2562
2704
  return pg, {'url': page_url, 'error': _t(lang, 'err_unparseable').format(e=str(e)[:120])}
2563
2705
  return pg, None
2564
- p0, p0_err = _parse_page(html_text, url)
2706
+ p0, p0_err = _parse_page(html_text, entry_final)
2565
2707
  if p0_err:
2566
2708
  return p0_err
2567
- reports = [audit_html(html_text, url, lang=lang)]
2709
+ reports = [audit_html(html_text, entry_final, lang=lang)]
2568
2710
  parsers = [p0]
2569
- seen = {url.split('#')[0].rstrip('/')}
2570
- # discovery: sitemap first (WCAG-EM's own enumeration), links as fallback
2711
+ seen = {url.split('#')[0].rstrip('/'), entry_final}
2712
+ # discovery: sitemap first (WCAG-EM's enumeration), links as fallback
2571
2713
  urls_sm = _urls_sitemap(url, timeout=timeout) if from_sitemap else []
2572
- queue = urls_sm or _internal_links(html_text, url, url)
2714
+ queue = urls_sm or _internal_links(html_text, entry_final, url)
2573
2715
  while queue and len(reports) < max_pages:
2574
2716
  if deadline is not None and time.monotonic() >= deadline:
2575
2717
  break # budget exhausted: partial, not eternal
@@ -2577,17 +2719,24 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
2577
2719
  if next in seen:
2578
2720
  continue
2579
2721
  seen.add(next)
2722
+ _m = {}
2580
2723
  try:
2581
- html_pg = _fetch(next, timeout=timeout)
2724
+ html_pg = _fetch(next, timeout=timeout, _meta=_m)
2582
2725
  except Exception: # noqa: BLE001
2583
2726
  continue
2584
- pg, pg_err = _parse_page(html_pg, next)
2727
+ # enlaces y reporte contra la URL FINAL (4ª pasada: tras una
2728
+ # redirección, resolver contra la PEDIDA visitaba rutas equivocadas)
2729
+ next_final = ((_m.get('final_url') or next).split('#')[0]).rstrip('/')
2730
+ if next_final != next and next_final in seen:
2731
+ continue # la redirección aterrizó en una ya auditada
2732
+ seen.add(next_final)
2733
+ pg, pg_err = _parse_page(html_pg, next_final)
2585
2734
  if pg_err is not None:
2586
2735
  continue # página rota: no cuenta, el crawl sigue
2587
- reports.append(audit_html(html_pg, next, lang=lang))
2736
+ reports.append(audit_html(html_pg, next_final, lang=lang))
2588
2737
  parsers.append(pg)
2589
2738
  if len(reports) < max_pages and not from_sitemap:
2590
- for new in _internal_links(html_pg, next, url):
2739
+ for new in _internal_links(html_pg, next_final, url):
2591
2740
  if new not in seen:
2592
2741
  queue.append(new)
2593
2742
  site_findings = evaluate_site(parsers, lang=lang)
@@ -2762,7 +2911,11 @@ def main(argv):
2762
2911
  # --standard nunca se descarte en silencio en NINGUNA ruta del CLI
2763
2912
  res = _apply_standard(res, a.standard, a.target, a.lang)
2764
2913
  print(json.dumps(res, ensure_ascii=False, indent=1))
2765
- return 0
2914
+ # fallo de ejecución (error en el informe) ≠ hallazgo de accesibilidad:
2915
+ # la revisión externa cazó audit --url devolviendo 1 pero --file (y los
2916
+ # mains de a11ydom) devolviendo 0 CON error — un verde falso para cualquier
2917
+ # script que encauce por el código de salida
2918
+ return 1 if isinstance(res, dict) and res.get('error') else 0
2766
2919
 
2767
2920
 
2768
2921
  if __name__ == '__main__':