@kinti/a11y-toolkit 5.30.0 → 5.32.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.
@@ -63,6 +63,76 @@ def path_segment(tag, nth):
63
63
  pueden romper la identidad)."""
64
64
  return f'{tag}:nth-of-type({nth})'
65
65
 
66
+
67
+ class _ElementPaths:
68
+ """Store one segment and parent index per distinct route."""
69
+
70
+ def __init__(self, implicit_tbody=True):
71
+ self.stack = []
72
+ self._implicit_tbody = implicit_tbody
73
+ self._nodes = [None]
74
+ self._node_ids = {}
75
+
76
+ def _child(self, tag):
77
+ if self.stack:
78
+ _, parent, siblings = self.stack[-1]
79
+ nth = siblings[tag] = siblings.get(tag, 0) + 1
80
+ else:
81
+ parent, nth = 0, 1
82
+ key = (parent, path_segment(tag, nth))
83
+ index = self._node_ids.get(key)
84
+ if index is None:
85
+ index = self._node_ids[key] = len(self._nodes)
86
+ self._nodes.append(key)
87
+ return index
88
+
89
+ def start(self, tag):
90
+ # Browsers insert a tbody for a row directly inside a table.
91
+ if self._implicit_tbody and tag == 'tr' and self.stack and self.stack[-1][0] == 'table':
92
+ self.stack.append(('tbody', self._child('tbody'), {}))
93
+ index = self._child(tag)
94
+ if tag not in VOID_TAGS:
95
+ self.stack.append((tag, index, {}))
96
+ return index
97
+
98
+ def end(self, tag):
99
+ if tag in VOID_TAGS:
100
+ return
101
+ for index in range(len(self.stack) - 1, -1, -1):
102
+ if self.stack[index][0] == tag:
103
+ del self.stack[index:]
104
+ break
105
+
106
+ def format(self, index):
107
+ segments = []
108
+ while index:
109
+ index, segment = self._nodes[index]
110
+ segments.append(segment)
111
+ return '>'.join(reversed(segments))
112
+
113
+ def lookup(self, path):
114
+ index = 0
115
+ for segment in path.split('>'):
116
+ index = self._node_ids.get((index, segment))
117
+ if index is None:
118
+ break
119
+ return index
120
+
121
+
122
+ class _Table:
123
+ def __init__(self, attrs, counted):
124
+ self.attrs = attrs
125
+ self.counted = counted
126
+ border = (attrs.get('border') or '0').strip()
127
+ bordered = counted and border.isdecimal() and any(int(digit) for digit in border)
128
+ self.suspect_layout = not bordered and bool(
129
+ {'cellpadding', 'cellspacing', 'width', 'border'} & attrs.keys())
130
+ self.data = bordered or 'summary' in attrs
131
+ self.has_th = False
132
+ self.header_ids = set()
133
+ self.references = []
134
+
135
+
66
136
  # roles que convierten cualquier elemento en campo etiquetable (e086e5).
67
137
  # OJO: 'search' NO está — es un LANDMARK (WAI-ARIA 1.2), no un widget: un
68
138
  # <form role="search"> sin aria-label es un landmark sin etiqueta, no un
@@ -385,8 +455,8 @@ class _Auditor(HTMLParser):
385
455
  # CSS (tag:nth-of-type(n) desde la raíz). id(attrs) es estable dentro
386
456
  # del parseo (cada attrs es un dict nuevo) → los recolectores pueden
387
457
  # resolver la ruta de LO QUE COGIERON sin cambiar sus tuplas.
388
- self._path_stack = [] # [(tag, path, {tag: nth})] del elemento abierto
389
- self._elem_paths = {} # id(attrs) → ruta del elemento
458
+ self._paths = _ElementPaths()
459
+ self._elem_paths = {} # id(attrs) → índice de ruta
390
460
  super().__init__(convert_charrefs=True)
391
461
  self.imgs_no_alt = []
392
462
  self.alt_quality_bad = [] # (razón, alt, attrs) — emitida en findings
@@ -495,9 +565,7 @@ class _Auditor(HTMLParser):
495
565
  self.media_autoplay_elems = []
496
566
  self.tables = 0
497
567
  self.tables_with_th = 0
498
- self._in_table = False
499
- self._th_in_table = False
500
- self._table_stack = [] # (th_había, attrs) por <table> abierta
568
+ self._table_stack = []
501
569
  self.tables_no_th_elems = []
502
570
  self.blank_no_warning = 0
503
571
  self.blank_total = 0
@@ -521,6 +589,14 @@ class _Auditor(HTMLParser):
521
589
  self.autocomplete_mismatch = []
522
590
  self.heading_role_removed = [] # h1-h6 con rol que sustituye al de heading
523
591
  self.text_spacing_important = [] # 1.4.12: spacing !important inline (ACT 24afc2/78fd32/9e45ec)
592
+ self.a_no_href = [] # 2.1.1: <a> sin href usado como control (batida B1-a)
593
+ self.nested_main = [] # 1.3.1: main anidado en seccionante (B1-b)
594
+ self.fake_lists = [] # 1.3.1: lista falsa con viñetas y <br> (B1-c)
595
+ self.alert_polite = [] # 4.1.2: role=alert gritando en aria-live=polite (B1-d)
596
+ self.headers_bad = [] # 1.3.1: headers= apuntando fuera de tabla o a no-th (ACT d0f69e/a25f45)
597
+ self.lang_xml_mismatch = [] # 3.1.2: lang y xml:lang discrepando (ACT 5b7ae0)
598
+ self._p_bullets = None # contador de viñetas del <p> abierto
599
+ self._p_brs = 0
524
600
  self.links = {} # nombre normalizado → set de hrefs
525
601
  self.links_elems = {} # entry_key → primeros elems (marcas 2.4.4)
526
602
  self.generics = 0
@@ -680,29 +756,7 @@ class _Auditor(HTMLParser):
680
756
  or (_ti_mark.isdecimal() and int(_ti_mark) >= 0):
681
757
  for _sp in self._stray_pend:
682
758
  _sp[3] = True
683
- # ruta determinista del elemento (kernel de anotación): nth-of-type
684
- # SIEMPRE (los id duplicados no pueden romper la ruta) y los void no
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']), {}))
696
- if self._path_stack:
697
- _parent = self._path_stack[-1]
698
- _parent[2][tag] = _parent[2].get(tag, 0) + 1
699
- _seg = path_segment(tag, _parent[2][tag])
700
- _path = _parent[1] + '>' + _seg
701
- else:
702
- _path = path_segment(tag, 1)
703
- self._elem_paths[id(a)] = _path
704
- if tag not in VOID_TAGS:
705
- self._path_stack.append((tag, _path, {}))
759
+ self._elem_paths[id(a)] = self._paths.start(tag)
706
760
  # rasgos estructurales para el scope de aplicabilidad (a11yscope):
707
761
  # evidencia POSITIVA — cero <video> habilita proponer 1.2.x como no
708
762
  # aplicable; la ausencia de señal jamás cuenta como ausencia de
@@ -873,12 +927,15 @@ class _Auditor(HTMLParser):
873
927
  self.help_hrefs.add(href.split('#')[0].rstrip('/'))
874
928
  if href and re.search(r'sitemap|site-map|mapa-del-sitio|mapa_web|mapaweb', href, re.I):
875
929
  self.has_sitemap = True
876
- # 2.4.5 vía adicional (4ª pasada): un índice/TOC o bloque de
877
- # relacionados SON formas de encontrar páginas
878
- if href and re.search(
879
- r'(?:^|[/\-_!.])(?:index|indice|indice-de-contenidos|contents|toc|related|relacionados|ver-tambien|see-also)(?:$|[/\-_!.])',
880
- href.split('#')[0].rstrip('/'), re.I):
881
- self.has_index = True
930
+ # 2.4.5 vía adicional (4ª pasada, afinada 7ª): un índice/TOC
931
+ # o bloque de relacionados SON formas de encontrar páginas —
932
+ # por SUBCADENA en el último segmento: los límites de palabra
933
+ # con puntuación dejaban fuera /blog/index.php, /articulos-relacionados
934
+ if href:
935
+ _seg = href.split('#')[0].rstrip('/').split('/')[-1].lower()
936
+ 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',
937
+ _seg):
938
+ self.has_index = True
882
939
  elif tag == 'input':
883
940
  self._field_note()
884
941
  kind = (a.get('type') or 'text').lower()
@@ -999,37 +1056,31 @@ class _Auditor(HTMLParser):
999
1056
  self._list_depth += 1
1000
1057
  elif tag == 'li':
1001
1058
  self._li_depth += 1
1002
- elif tag == 'table':
1003
- # role=presentation/none la declara de MAQUETACIÓN: no se exige th
1004
- # (el mail HTML y las grids legacy viven aquí) — y el contenido de
1005
- # <template> es inerte
1006
- if (a.get('role') or '').strip().lower() in ('presentation', 'none') \
1007
- or self._in_template:
1008
- pass
1009
- else:
1010
- self.tables += 1
1011
- self._in_table = True
1012
- # sospecha de maquetación (attrs presentacionales de la era
1013
- # <table width=… cellpadding=0 border=0>): sin th NI marcadores
1014
- # de datos no se exige th (FP clásico años-90). OJO border:
1015
- # el spec dice que border≠0 declara tabla de DATOS — solo el
1016
- # «0» (o sin valor, que es 0) es maquetación
1017
- _bv = (a.get('border') or '0').strip()
1018
- _border_data = _bv.isdecimal() and int(_bv) > 0
1019
- _suspect = (bool({'cellpadding', 'cellspacing', 'width'} & set(a))
1020
- or ('border' in a and not _border_data)) and not _border_data
1021
- _data = 'summary' in a or _border_data
1022
- # pila por tabla anidada, CON IDENTIDAD: una </table> de una
1023
- # tabla presentation/none (no apilada) jamás popea la entrada
1024
- # de la tabla externa que la envuelve
1025
- self._table_stack.append([self._th_in_table, a, _suspect, _data])
1026
- self._th_in_table = False
1027
- elif tag == 'th':
1028
- self._th_in_table = True
1029
- elif tag == 'caption' and self._table_stack:
1030
- self._table_stack[-1][3] = True # marcador de tabla de DATOS
1031
- elif tag == 'td' and self._table_stack and ('scope' in a or 'headers' in a):
1032
- self._table_stack[-1][3] = True # asociaciones explícitas = datos
1059
+ if tag == 'br' and self._p_bullets is not None and not self._in_template:
1060
+ self._p_brs += 1
1061
+ if tag == 'p' and not self._in_template:
1062
+ self._p_bullets = 0
1063
+ self._p_brs = 0
1064
+ if tag == 'table':
1065
+ counted = not self._in_template and (
1066
+ (a.get('role') or '').strip().lower() not in ('presentation', 'none'))
1067
+ self._table_stack.append(_Table(a, counted))
1068
+ self.tables += int(counted)
1069
+ elif tag in ('th', 'td', 'caption') and self._table_stack and not self._in_template:
1070
+ table = self._table_stack[-1]
1071
+ if table.counted:
1072
+ if tag == 'caption':
1073
+ table.data = True
1074
+ else:
1075
+ table.has_th |= tag == 'th'
1076
+ if tag == 'td' and ('scope' in a or 'headers' in a):
1077
+ table.data = True
1078
+ cell_id = a.get('id')
1079
+ role = (a.get('role') or '').strip().lower()
1080
+ if cell_id and (tag == 'th' or role in ('columnheader', 'rowheader')):
1081
+ table.header_ids.add(cell_id)
1082
+ if (a.get('headers') or '').strip(' \t\n\f\r'):
1083
+ table.references.append(a)
1033
1084
  elif tag == 'main' or (a.get('role') or '').lower() == 'main':
1034
1085
  self.hay_main = True
1035
1086
  if a.get('id'):
@@ -1281,16 +1332,33 @@ class _Auditor(HTMLParser):
1281
1332
  # <area> es void: sin pila de control — se registra directo (el
1282
1333
  # nombre le llega del alt)
1283
1334
  self.controls_raw.append(('area', a, '', [], _hidden))
1335
+ if tag == 'main' and not self._in_template:
1336
+ # B1-b (batida 18-nov): main es top-level por definición — anidado
1337
+ # en section/aside/nav/article/main/header/footer no es ni landmark
1338
+ # válido ni estructura honesta (1.3.1)
1339
+ # [-1] es el PROPIO main (ya apilado cuando corre este chequeo):
1340
+ # el ancestro a mirar empieza uno antes
1341
+ for index in range(len(self._paths.stack) - 2, -1, -1):
1342
+ _utag = self._paths.stack[index][0]
1343
+ if _utag in ('section', 'aside', 'nav', 'article', 'main',
1344
+ 'header', 'footer'):
1345
+ if len(self.nested_main) < 8:
1346
+ self.nested_main.append(f'<{_utag}> … <main>')
1347
+ break
1348
+ if _utag == 'body':
1349
+ break
1284
1350
  if tag in ('h1', 'h2', 'h3', 'h4', 'h5', 'h6'):
1285
1351
  # role=none/presentation APAGA la semántica del encabezado; un
1286
1352
  # aria-level válido la SOBRESCRIBE (accname: h3[aria-level=4] ES 4)
1287
1353
  _hrole = (a.get('role') or '').strip().lower()
1288
1354
  if _hrole in ('none', 'presentation') or self._in_template:
1289
1355
  pass
1290
- elif _hrole and _hrole != 'heading':
1291
- # CUALQUIER otro rol explícito SUSTITUYE al de heading (la
1292
- # primera regla de ARIA): h2 role=button desaparece de la
1293
- # navegación por encabezados del AT — se registra (1.3.1)
1356
+ elif _hrole and _hrole != 'heading' and _hrole in _ROLES_ARIA:
1357
+ # un rol VALIDO distinto de heading SUSTITUYE al de heading
1358
+ # (la primera regla de ARIA): h2 role=button desaparece de la
1359
+ # navegación por encabezados del AT — se registra (1.3.1).
1360
+ # (7a pasada) un rol DESCONOCIDO (role="bogus heading") el
1361
+ # navegador lo IGNORA y el h2 SIGUE siendo heading: sin aviso
1294
1362
  if not _hidden and len(self.heading_role_removed) < 12:
1295
1363
  _nm = (a.get('aria-label') or '').strip()[:24]
1296
1364
  self.heading_role_removed.append(
@@ -1302,7 +1370,6 @@ class _Auditor(HTMLParser):
1302
1370
  self._heading_level = int(_alv.group())
1303
1371
  self._heading_text = []
1304
1372
  self._heading_attrs = a
1305
- self._heading_route = self._elem_paths.get(id(a))
1306
1373
  self._heading_hidden = _hidden
1307
1374
  self._heading_tag = tag
1308
1375
  elif (a.get('role') or '').lower() == 'heading' and not self._in_template:
@@ -1313,27 +1380,44 @@ class _Auditor(HTMLParser):
1313
1380
  self._heading_level = int(_alv.group()) if _alv else 2
1314
1381
  self._heading_text = []
1315
1382
  self._heading_attrs = a
1316
- self._heading_route = self._elem_paths.get(id(a))
1317
1383
  self._heading_hidden = _hidden
1318
1384
  self._heading_tag = tag
1385
+ # ── batida 18-nov, día 2 ──
1386
+ if not self._in_template:
1387
+ # B1-a: <a> SIN href con vida de control (2.1.1): tabindex>=0,
1388
+ # onclick o rol interactivo. Sin href NO es enlace: el AT no lo
1389
+ # anuncia como tal aunque sea enfocable y le echen un click.
1390
+ # Exento: tabindex=-1 (ancla objetivo legítima) y <a> puro con id
1391
+ # (ancla con nombre de toda la vida).
1392
+ if tag == 'a' and not (a.get('href') or '').strip():
1393
+ _anchor_role = (a.get('role') or '').strip().lower()
1394
+ _viva = ((a.get('onclick') or '')
1395
+ or _anchor_role in ('button', 'link', 'tab', 'menuitem')
1396
+ or (a.get('tabindex') or '').strip() not in ('', '-1'))
1397
+ if _viva and len(self.a_no_href) < 12:
1398
+ _tx = ' '.join(self._ctrl[-1]['text']).strip()[:20] if self._ctrl else ''
1399
+ self.a_no_href.append('<a>' + (f' "{_tx}"' if _tx else ''))
1400
+ # B1-d: role=alert ES assertive en sí mismo (ARIA): un aria-live
1401
+ # polite encima lo contradice (4.1.2, estado que no es el que dice)
1402
+ _role_low = (a.get('role') or '').strip().lower()
1403
+ _live = (a.get('aria-live') or '').strip().lower()
1404
+ if _role_low == 'alert' and _live == 'polite' and len(self.alert_polite) < 8:
1405
+ self.alert_polite.append('role="alert" + aria-live="polite"')
1406
+ if _lang_v := (a.get('lang') or '').strip():
1407
+ _xml = (a.get('{http://www.w3.org/XML/1998/namespace}lang')
1408
+ or a.get('xml:lang') or '').strip()
1409
+ if _xml and _lang_v.lower() != _xml.lower() and len(self.lang_xml_mismatch) < 8:
1410
+ self.lang_xml_mismatch.append(f'{tag} lang="{_lang_v}" xml:lang="{_xml}"')
1411
+
1319
1412
  ti = a.get('tabindex')
1320
1413
  if ti and ti.isdecimal() and int(ti) > 0 and not self._in_template:
1321
1414
  self.positive_tabindices.append((tag, int(ti)))
1322
1415
  self.positive_tabindex_elems.append(a)
1323
1416
 
1324
1417
  def handle_endtag(self, tag):
1325
- # pila de rutas del kernel: pop normal si casa; si hay anidamiento
1326
- # malformado, se descarta hasta el que casa; suelto, se ignora
1327
- if self._path_stack:
1328
- if self._path_stack[-1][0] == tag:
1329
- self._path_stack.pop()
1330
- else:
1331
- for _i in range(len(self._path_stack) - 1, -1, -1):
1332
- if self._path_stack[_i][0] == tag:
1333
- del self._path_stack[_i:]
1334
- break
1418
+ self._paths.end(tag)
1335
1419
  if tag not in _VOID:
1336
- # LAS PILAS SE SINCRONIZAN como _path_stack: buscar el frame que
1420
+ # LAS PILAS SE SINCRONIZAN con las rutas: buscar el frame que
1337
1421
  # casa y descartar hasta él (un </span> suelto ya no arrastra el
1338
1422
  # elemento abierto de verdad — el texto no se malatribuye)
1339
1423
  _idx = None
@@ -1349,12 +1433,12 @@ class _Auditor(HTMLParser):
1349
1433
  self._close_control(tag)
1350
1434
  return
1351
1435
  _nframes = len(self._el_stack) - _idx
1352
- _closed_attrs = None # attrs del frame que CASA (el último popeado)
1353
1436
  for _ in range(_nframes):
1354
1437
  if not self._el_stack:
1355
1438
  break
1356
1439
  _etag, _eattrs, _ebuf = self._el_stack.pop()
1357
- _closed_attrs = _eattrs
1440
+ if _etag == 'table':
1441
+ self._finish_table(self._table_stack.pop())
1358
1442
  if _etag == 'canvas':
1359
1443
  self.canvases.append((_eattrs, ' '.join(_ebuf).strip(),
1360
1444
  self.canvas_hidden.pop(id(_eattrs), False)))
@@ -1457,6 +1541,16 @@ class _Auditor(HTMLParser):
1457
1541
  self._form_auth = False
1458
1542
  elif tag == 'nav':
1459
1543
  self._in_nav = max(0, self._in_nav - 1)
1544
+ elif tag == 'p':
1545
+ # B1-c: lista falsa = ≥2 viñetas tipográficas + separadores <br>
1546
+ # en un párrafo fuera de listas reales (batida 18-nov, htmhell 30)
1547
+ if self._p_bullets is not None and self._p_bullets >= 2 \
1548
+ and self._p_brs >= 1 and self._list_depth == 0 \
1549
+ and len(self.fake_lists) < 8:
1550
+ self.fake_lists.append(f'<p> • × {self._p_bullets}, '
1551
+ f'<br> × {self._p_brs}')
1552
+ self._p_bullets = None
1553
+ self._p_brs = 0
1460
1554
  elif tag == 'li':
1461
1555
  self._li_depth = max(0, self._li_depth - 1)
1462
1556
  elif tag in ('ul', 'ol'):
@@ -1471,34 +1565,48 @@ class _Auditor(HTMLParser):
1471
1565
  self.videos_no_caps_elems.append(_vattrs)
1472
1566
  if not _vdesc:
1473
1567
  self.videos_no_desc_elems.append(_vattrs)
1474
- elif tag == 'table':
1475
- if self._table_stack and _closed_attrs is not None:
1476
- _th_saved, _tattrs, _suspect, _data = self._table_stack[-1]
1477
- # IDENTIDAD: solo decide la entrada cuya tabla se CIERRA (el
1478
- # </table> de una presentation/template NUNCA apilada resbala
1479
- # sin tocar la pila — antes popeaba la entrada de la externa)
1480
- if _closed_attrs is _tattrs:
1481
- self._table_stack.pop()
1482
- if self._th_in_table:
1483
- self.tables_with_th += 1
1484
- elif _data or not _suspect:
1485
- self.tables_no_th_elems.append(_tattrs)
1486
- else:
1487
- # maquetación por heurística: fuera del cómputo
1488
- self.tables -= 1
1489
- self._th_in_table = _th_saved
1490
- self._in_table = bool(self._table_stack)
1491
- elif tag == 'th':
1492
- pass
1493
1568
  elif self._heading_level and tag == getattr(self, '_heading_tag', None):
1494
1569
  # el veredicto de nombre vacío es POST-parse (labelledby resuelto,
1495
1570
  # aria-label tras strip, nombres de imgs internas)
1496
- self.headings_raw.append((self._heading_level, dict(self._heading_attrs or {}),
1571
+ self.headings_raw.append((self._heading_level, self._heading_attrs,
1497
1572
  ' '.join(self._heading_text).strip(),
1498
- getattr(self, '_heading_hidden', False),
1499
- getattr(self, '_heading_route', None)))
1573
+ getattr(self, '_heading_hidden', False)))
1500
1574
  self._heading_level = None
1501
1575
 
1576
+ def _finish_table(self, table):
1577
+ if not table.counted:
1578
+ return
1579
+ if table.has_th:
1580
+ self.tables_with_th += 1
1581
+ elif table.data or not table.suspect_layout:
1582
+ self.tables_no_th_elems.append(table.attrs)
1583
+ else:
1584
+ self.tables -= 1
1585
+ for cell in table.references:
1586
+ for token in re.split(r'[ \t\n\f\r]+', cell['headers'].strip(' \t\n\f\r')):
1587
+ if token not in table.header_ids or token == cell.get('id'):
1588
+ self.headers_bad.append((token, cell))
1589
+ break
1590
+
1591
+ def close(self):
1592
+ super().close()
1593
+ while self._table_stack:
1594
+ self._finish_table(self._table_stack.pop())
1595
+
1596
+ def _finding_paths(self, elements):
1597
+ paths = []
1598
+ for attrs in elements:
1599
+ path = self.element_path(attrs)
1600
+ if path:
1601
+ paths.append(path)
1602
+ if len(paths) == 5:
1603
+ break
1604
+ return paths
1605
+
1606
+ def element_path(self, attrs):
1607
+ index = self._elem_paths.get(id(attrs))
1608
+ return self._paths.format(index) if index is not None else None
1609
+
1502
1610
  _RE_CHAR_KEY = re.compile(r'key(?:Code)?\s*===?\s*["\']([a-zA-Z0-9])["\']', re.S)
1503
1611
 
1504
1612
  def handle_script_wait(self, data):
@@ -1633,6 +1741,11 @@ class _Auditor(HTMLParser):
1633
1741
  m = _SENSORIAL.search(re.sub(r'«[^»]*»|“[^”]*”|"[^"]*"', ' ', data))
1634
1742
  if m and len(self.sensory) < 6:
1635
1743
  self.sensory.append(m.group(0).strip()[:60])
1744
+ # B1-c: viñetas tipográficas en prosa = lista falsa (umbral ≥2;
1745
+ # un solo guion de cita o de lista de definición NO es lista)
1746
+ if self._p_bullets is not None:
1747
+ self._p_bullets += len(re.findall(
1748
+ r'(?:^|\s)[•‣▪●◦∙]\s*\S', data))
1636
1749
 
1637
1750
 
1638
1751
 
@@ -1892,7 +2005,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
1892
2005
  or ' '.join(x for x in _img_names if x).strip()
1893
2006
  or (a.get('alt') or '').strip()):
1894
2007
  p.controls_by_kind.setdefault(kind, []).append(a)
1895
- for level, a, text, hidden, _hroute in p.headings_raw:
2008
+ for level, a, text, hidden in p.headings_raw:
1896
2009
  if hidden:
1897
2010
  continue
1898
2011
  lb, al, _ti = _name_sources(a)
@@ -1975,52 +2088,43 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
1975
2088
  findings[-1]['examples'] = examples[:5]
1976
2089
 
1977
2090
  if p.alt_quality_bad:
1978
- _p_q = [p._elem_paths[id(_a)] for _r, _alt, _a in p.alt_quality_bad
1979
- if id(_a) in p._elem_paths][:5]
2091
+ _p_q = p._finding_paths(a for _, _, a in p.alt_quality_bad)
1980
2092
  add_ej('medium', '1.1.1', 'alt_quality',
1981
2093
  [_alt[:40] for _r, _alt, _a in p.alt_quality_bad],
1982
2094
  n=len(p.alt_quality_bad), paths=_p_q)
1983
2095
  if p.imgs_no_alt:
1984
- _p_img = [p._elem_paths[id(_a)] for _a in p.imgs_no_alt_elems
1985
- if id(_a) in p._elem_paths][:5]
2096
+ _p_img = p._finding_paths(p.imgs_no_alt_elems)
1986
2097
  add_ej('high', '1.1.1', 'img_no_alt', p.imgs_no_alt,
1987
2098
  n=len(p.imgs_no_alt), paths=_p_img)
1988
2099
  if p.input_img_no_alt:
1989
2100
  add('high', '1.1.1', 'input_img_alt', n=p.input_img_no_alt)
1990
2101
  if p.canvas_no_layer:
1991
- _p_canvas = [p._elem_paths[id(_a)] for _a in p.canvas_no_layer_elems
1992
- if id(_a) in p._elem_paths][:5]
2102
+ _p_canvas = p._finding_paths(p.canvas_no_layer_elems)
1993
2103
  add_ej('medium', '1.1.1', 'canvas_no_accessible_layer', p.canvas_no_layer,
1994
2104
  n=len(p.canvas_no_layer), paths=_p_canvas)
1995
2105
  for tag, controls in p.controls_by_kind.items():
1996
2106
  add('high', '4.1.2', 'ctrl_name', n=len(controls), tag=tag,
1997
- paths=[p._elem_paths[id(_a)] for _a in controls
1998
- if id(_a) in p._elem_paths][:5])
2107
+ paths=p._finding_paths(controls))
1999
2108
  if p.aria_hidden_focusable:
2000
2109
  add('high', '4.1.2', 'aria_hidden_focusable',
2001
2110
  n=len(p.aria_hidden_focusable), tag=p.aria_hidden_focusable[0],
2002
- paths=[p._elem_paths[id(_a)] for _a in p.aria_hidden_focusable_elems
2003
- if id(_a) in p._elem_paths][:5])
2111
+ paths=p._finding_paths(p.aria_hidden_focusable_elems))
2004
2112
  if p.fields_no_label:
2005
2113
  add_ej('high', '3.3.2', 'field_label',
2006
2114
  [f'{t} name={n or "(no name)"}' for t, n, _i in p.fields_no_label],
2007
2115
  n=len(p.fields_no_label),
2008
- paths=[p._elem_paths[id(_a)] for _a in p.fields_no_label_elems
2009
- if id(_a) in p._elem_paths][:5])
2116
+ paths=p._finding_paths(p.fields_no_label_elems))
2010
2117
  if p.stray_clicks:
2011
2118
  add('high', '2.1.1', 'click_nonfocusable',
2012
2119
  n=len(p.stray_clicks), tag=p.stray_clicks[0],
2013
- paths=[p._elem_paths[id(_a)] for _a in p.stray_click_elems
2014
- if id(_a) in p._elem_paths][:5])
2120
+ paths=p._finding_paths(p.stray_click_elems))
2015
2121
  if p.role_no_tabindex:
2016
2122
  add_ej('low', '2.1.1', 'role_no_tabindex', p.role_no_tabindex,
2017
2123
  n=len(p.role_no_tabindex), example=', '.join(p.role_no_tabindex[:3]),
2018
- paths=[p._elem_paths[id(_a)] for _a in p.role_no_tabindex_elems
2019
- if id(_a) in p._elem_paths][:5])
2124
+ paths=p._finding_paths(p.role_no_tabindex_elems))
2020
2125
  if p.orphan_labels:
2021
2126
  add('low', '3.3.2', 'label_orphan', n=p.orphan_labels,
2022
- paths=[p._elem_paths[id(_a)] for _a in p.orphan_label_elems
2023
- if id(_a) in p._elem_paths][:5])
2127
+ paths=p._finding_paths(p.orphan_label_elems))
2024
2128
  if p._bad_list:
2025
2129
  add('medium', '1.3.1', 'list_structure', n=p._bad_list)
2026
2130
  if p.root_tag in ('svg', 'math'):
@@ -2046,12 +2150,10 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2046
2150
  if p.iframes_no_title:
2047
2151
  add_ej('medium', '4.1.2', 'iframe_title', p.iframes_no_title,
2048
2152
  n=len(p.iframes_no_title),
2049
- paths=[p._elem_paths[id(_a)] for _a in p.iframes_no_title_elems
2050
- if id(_a) in p._elem_paths][:5])
2153
+ paths=p._finding_paths(p.iframes_no_title_elems))
2051
2154
  if p.videos and p.videos_no_caps_elems:
2052
2155
  add('medium', '1.2.2', 'video_captions', n=len(p.videos_no_caps_elems),
2053
- paths=[p._elem_paths[id(_a)] for _a in p.videos_no_caps_elems
2054
- if id(_a) in p._elem_paths][:5])
2156
+ paths=p._finding_paths(p.videos_no_caps_elems))
2055
2157
  if p.viewport:
2056
2158
  # valores inválidos también blocksn (ACT b4f0c3): user-scalable ha de
2057
2159
  # ser yes/true o numérico ≥ 1; maximum-scale numérico — si no parsea,
@@ -2065,8 +2167,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2065
2167
  allows = v in ('yes', 'true')
2066
2168
  if not allows:
2067
2169
  add('high', '1.4.4', 'zoom_no',
2068
- paths=([p._elem_paths[id(p._viewport_elem)]]
2069
- if p._viewport_elem and id(p._viewport_elem) in p._elem_paths else None))
2170
+ paths=p._finding_paths([p._viewport_elem]))
2070
2171
  m_ms = re.search(r'maximum-scale\s*=\s*([\w.-]+)', p.viewport, re.I)
2071
2172
  if m_ms:
2072
2173
  _v_ms = m_ms.group(1)
@@ -2080,8 +2181,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2080
2181
  # mismo daño que user-scalable=no (bloquea el zoom del usuario):
2081
2182
  # misma severidad — ACT b4f0c3 no las distingue
2082
2183
  add('high', '1.4.4', 'zoom_max', v=_v_ms,
2083
- paths=([p._elem_paths[id(p._viewport_elem)]]
2084
- if p._viewport_elem and id(p._viewport_elem) in p._elem_paths else None))
2184
+ paths=p._finding_paths([p._viewport_elem]))
2085
2185
  # meta refresh (2.2.1/ACT bc659a): gana el PRIMER meta que parsea según
2086
2186
  # los pasos del HTML (dígitos + ; o , o fin — un «0: url» con dos puntos
2087
2187
  # NO parsea y se salta); 0 segundos = redirección inmediata y > 72000
@@ -2097,14 +2197,12 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2097
2197
  break
2098
2198
  if _mr is not None and 0 < _mr <= 72000:
2099
2199
  add('medium', '2.2.1', 'meta_refresh', v=_mr,
2100
- paths=([p._elem_paths[id(_mr_elem)]]
2101
- if _mr_elem and id(_mr_elem) in p._elem_paths else None))
2200
+ paths=p._finding_paths([_mr_elem]))
2102
2201
  if p.positive_tabindices:
2103
2202
  add_ej('medium', '2.4.3', 'tabindex_pos',
2104
2203
  [f'{t}[tabindex={i}]' for t, i in p.positive_tabindices],
2105
2204
  n=len(p.positive_tabindices),
2106
- paths=[p._elem_paths[id(_a)] for _a in p.positive_tabindex_elems
2107
- if id(_a) in p._elem_paths][:5])
2205
+ paths=p._finding_paths(p.positive_tabindex_elems))
2108
2206
  # un toggle cuenta como mecanismo de abatido SOLO si la función que
2109
2207
  # invoca colapsa de verdad (su cuerpo, en el script de la página, toca
2110
2208
  # `display`): mover off-screen o aria-hidden no colapsa el bloque (3e12e1)
@@ -2156,17 +2254,36 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2156
2254
  if p.heading_role_removed:
2157
2255
  add_ej('medium', '1.3.1', 'heading_role_removed', p.heading_role_removed,
2158
2256
  n=len(p.heading_role_removed), example=', '.join(p.heading_role_removed[:4]))
2257
+ if p.nested_main:
2258
+ add_ej('medium', '1.3.1', 'nested_main', p.nested_main,
2259
+ n=len(p.nested_main), example=', '.join(p.nested_main[:4]))
2260
+ if p.fake_lists:
2261
+ add_ej('low', '1.3.1', 'fake_list', p.fake_lists,
2262
+ n=len(p.fake_lists), example=', '.join(p.fake_lists[:3]))
2263
+ if p.a_no_href:
2264
+ add_ej('medium', '2.1.1', 'a_no_href', p.a_no_href,
2265
+ n=len(p.a_no_href), example=', '.join(p.a_no_href[:4]))
2266
+ if p.alert_polite:
2267
+ add_ej('low', '4.1.2', 'alert_polite', p.alert_polite,
2268
+ n=len(p.alert_polite), example=', '.join(p.alert_polite[:3]))
2269
+ if p.lang_xml_mismatch:
2270
+ add_ej('low', '3.1.2', 'lang_xml_mismatch', p.lang_xml_mismatch,
2271
+ n=len(p.lang_xml_mismatch), example=', '.join(p.lang_xml_mismatch[:4]))
2272
+ if p.headers_bad:
2273
+ examples = [f'headers="{token[:20]}"' for token, _ in p.headers_bad[:5]]
2274
+ add_ej('medium', '1.3.1', 'headers_attr_bad', examples,
2275
+ n=len(p.headers_bad), example=', '.join(examples[:4]),
2276
+ paths=p._finding_paths(cell for _, cell in p.headers_bad))
2277
+
2159
2278
  if p.text_spacing_important:
2160
2279
  add_ej('medium', '1.4.12', 'text_spacing_important', p.text_spacing_important,
2161
2280
  n=len(p.text_spacing_important), example=', '.join(p.text_spacing_important[:4]))
2162
2281
  if p.tables and p.tables_with_th < p.tables:
2163
2282
  add('medium', '1.3.1', 'table_no_th', n=p.tables - p.tables_with_th,
2164
- paths=[p._elem_paths[id(_a)] for _a in p.tables_no_th_elems
2165
- if id(_a) in p._elem_paths][:5])
2283
+ paths=p._finding_paths(p.tables_no_th_elems))
2166
2284
  if p.blank_no_warning:
2167
2285
  add('low', '3.2.5', 'blank_no_warning', n=p.blank_no_warning,
2168
- paths=[p._elem_paths[id(_a)] for _a in p.blank_no_warning_elems
2169
- if id(_a) in p._elem_paths][:5])
2286
+ paths=p._finding_paths(p.blank_no_warning_elems))
2170
2287
  dups = sum(1 for _c, k in p.ids.items() if k > 1)
2171
2288
  if dups:
2172
2289
  add_ej('low', '4.1.2', 'dup_ids',
@@ -2195,8 +2312,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2195
2312
  if p.missing_autocomplete:
2196
2313
  add_ej('medium', '1.3.5', 'autocomplete', p.missing_autocomplete,
2197
2314
  n=len(p.missing_autocomplete), example=', '.join(p.missing_autocomplete[:4]),
2198
- paths=[p._elem_paths[id(_a)] for _a in p.autocomplete_elems
2199
- if id(_a) in p._elem_paths][:5])
2315
+ paths=p._finding_paths(p.autocomplete_elems))
2200
2316
  if p.autocomplete_invalid:
2201
2317
  add_ej('medium', '1.3.5', 'autocomplete_invalid', p.autocomplete_invalid,
2202
2318
  n=len(p.autocomplete_invalid), example=', '.join(p.autocomplete_invalid[:4]))
@@ -2205,8 +2321,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2205
2321
  n=len(p.autocomplete_mismatch), example=', '.join(p.autocomplete_mismatch[:4]))
2206
2322
  if p.media_autoplay:
2207
2323
  add('medium', '1.4.2', 'video_autoplay', n=p.media_autoplay,
2208
- paths=[p._elem_paths[id(_a)] for _a in p.media_autoplay_elems
2209
- if id(_a) in p._elem_paths][:5])
2324
+ paths=p._finding_paths(p.media_autoplay_elems))
2210
2325
  # 2.5.3, veredicto POST-parse (4ª pasada): el nombre EFECTIVO por
2211
2326
  # precedencia accname — labelledby (ids resueltos, unidos en orden) GANA
2212
2327
  # a aria-label. El nombre del propio contenido cumple trivialmente.
@@ -2242,8 +2357,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2242
2357
  add_ej('medium', '2.5.3', 'label_in_name',
2243
2358
  [f'«{t}» vs name «{al}»' for t, al in p.label_no_name],
2244
2359
  n=len(p.label_no_name), example=f'{_ln[0]} ≠ {_ln[1]}',
2245
- paths=[p._elem_paths[id(_a)] for _a in p.label_no_name_elems
2246
- if id(_a) in p._elem_paths][:5])
2360
+ paths=p._finding_paths(p.label_no_name_elems))
2247
2361
  if p.lang_parts_invalid:
2248
2362
  add_ej('medium', '3.1.2', 'element_lang_invalid', p.lang_parts_invalid,
2249
2363
  n=len(p.lang_parts_invalid), example=', '.join(p.lang_parts_invalid[:4]))
@@ -2254,8 +2368,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2254
2368
  if p.placeholder_only:
2255
2369
  add_ej('high', '3.3.2', 'placeholder_only', p.placeholder_only,
2256
2370
  n=len(p.placeholder_only), example=', '.join(p.placeholder_only[:3]),
2257
- paths=[p._elem_paths[id(_a)] for _a in p.placeholder_only_elems
2258
- if id(_a) in p._elem_paths][:5])
2371
+ paths=p._finding_paths(p.placeholder_only_elems))
2259
2372
  if p.required_no_indication:
2260
2373
  add_ej('low', '3.3.2', 'required_no_indication', p.required_no_indication,
2261
2374
  n=len(p.required_no_indication), example=', '.join(p.required_no_indication[:3]))
@@ -2298,8 +2411,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2298
2411
  if p.focus_blur:
2299
2412
  add_ej('high', '2.1.1', 'onfocus_blur', p.focus_blur,
2300
2413
  n=len(p.focus_blur),
2301
- paths=[p._elem_paths[id(_a)] for _a in p.focus_blur_elems
2302
- if id(_a) in p._elem_paths][:5])
2414
+ paths=p._finding_paths(p.focus_blur_elems))
2303
2415
  if p.motions:
2304
2416
  add_ej('low', '2.5.4', 'motion_actuation', p.motions,
2305
2417
  n=len(p.motions), example=', '.join(p.motions[:3]))
@@ -2308,8 +2420,7 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2308
2420
  n=len(p.orientation_locks), example=', '.join(p.orientation_locks[:2]))
2309
2421
  if p.videos and p.videos_no_desc_elems:
2310
2422
  add('low', '1.2.3', 'audio_desc_missing', n=len(p.videos_no_desc_elems),
2311
- paths=[p._elem_paths[id(_a)] for _a in p.videos_no_desc_elems
2312
- if id(_a) in p._elem_paths][:5])
2423
+ paths=p._finding_paths(p.videos_no_desc_elems))
2313
2424
  if p.sensory:
2314
2425
  add('low', '1.3.3', 'sensory_text', example='; '.join(p.sensory[:2])[:70])
2315
2426
  lm_dups = [f'{lm} ×{t[1]}' for lm, t in p.landmarks.items()
@@ -2319,15 +2430,13 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2319
2430
  if p.generics >= 2: # un enlace genérico único suele desambiguarse por contexto
2320
2431
  gen = [f'«{k}»' for k in p.links if k in _GENERIC_TEXT][:4]
2321
2432
  add('low', '2.4.4', 'generic_link', n=p.generics, example=', '.join(gen),
2322
- paths=[p._elem_paths[id(_a)] for _a in p.generic_link_elems
2323
- if id(_a) in p._elem_paths][:5])
2433
+ paths=p._finding_paths(p.generic_link_elems))
2324
2434
  same = sum(1 for _k, hrefs in p.links.items() if len(hrefs) > 1)
2325
2435
  if same:
2326
2436
  _same_elems = [p.links_elems.get(_k, [None])[0]
2327
2437
  for _k, _hs in p.links.items() if len(_hs) > 1]
2328
2438
  add('low', '2.4.4', 'same_name_links', n=same,
2329
- paths=[p._elem_paths[id(_a)] for _a in _same_elems
2330
- if _a is not None and id(_a) in p._elem_paths][:5])
2439
+ paths=p._finding_paths(_same_elems))
2331
2440
  ak_dups = [f'"{k}" ×{v}' for k, v in p.accesskeys.items() if v > 1]
2332
2441
  if ak_dups:
2333
2442
  add('low', '2.1.1', 'accesskey_dup', n=len(ak_dups), example=', '.join(ak_dups[:4]))
@@ -2675,14 +2784,19 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
2675
2784
  max_pages = max(1, min(20, int(max_pages)))
2676
2785
  import time
2677
2786
  deadline = (time.monotonic() + budget) if budget else None
2787
+ # (7ª pasada) la PRIMERA página también contra su URL FINAL: /deep2 que
2788
+ # redirige a /deep reportaba bajo /deep2 y sus enlaces relativos se
2789
+ # resolvían contra la ruta PEDIDA — el camino equivocado
2790
+ _m0 = {}
2678
2791
  try:
2679
- html_text = _fetch(url, timeout=timeout)
2792
+ html_text = _fetch(url, timeout=timeout, _meta=_m0)
2680
2793
  except _FetchError as e:
2681
2794
  return {'error': _t(lang, e.key).format(**e.fmt)}
2682
2795
  except ValueError as e:
2683
2796
  return {'error': str(e)}
2684
2797
  except Exception as e: # noqa: BLE001
2685
2798
  return {'error': _t(lang, 'fetch_error').format(e=e)}
2799
+ entry_final = ((_m0.get('final_url') or url).split('#')[0]).rstrip('/')
2686
2800
  # el parser jamás tira el crawl entero: una página hostil → informe de
2687
2801
  # error de ESA página y se sigue con la cola
2688
2802
  def _parse_page(html_txt, page_url):
@@ -2693,15 +2807,15 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
2693
2807
  except Exception as e: # noqa: BLE001
2694
2808
  return pg, {'url': page_url, 'error': _t(lang, 'err_unparseable').format(e=str(e)[:120])}
2695
2809
  return pg, None
2696
- p0, p0_err = _parse_page(html_text, url)
2810
+ p0, p0_err = _parse_page(html_text, entry_final)
2697
2811
  if p0_err:
2698
2812
  return p0_err
2699
- reports = [audit_html(html_text, url, lang=lang)]
2813
+ reports = [audit_html(html_text, entry_final, lang=lang)]
2700
2814
  parsers = [p0]
2701
- seen = {url.split('#')[0].rstrip('/')}
2702
- # discovery: sitemap first (WCAG-EM's own enumeration), links as fallback
2815
+ seen = {url.split('#')[0].rstrip('/'), entry_final}
2816
+ # discovery: sitemap first (WCAG-EM's enumeration), links as fallback
2703
2817
  urls_sm = _urls_sitemap(url, timeout=timeout) if from_sitemap else []
2704
- queue = urls_sm or _internal_links(html_text, url, url)
2818
+ queue = urls_sm or _internal_links(html_text, entry_final, url)
2705
2819
  while queue and len(reports) < max_pages:
2706
2820
  if deadline is not None and time.monotonic() >= deadline:
2707
2821
  break # budget exhausted: partial, not eternal