@kinti/a11y-toolkit 5.22.0 → 5.22.2

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 (39) hide show
  1. package/a11y_toolkit/__init__.py +5 -0
  2. package/a11y_toolkit/a11y.py +115 -0
  3. package/a11y_toolkit/a11yact.py +167 -0
  4. package/a11y_toolkit/a11yaudit.py +1951 -0
  5. package/a11y_toolkit/a11ybadge.py +102 -0
  6. package/a11y_toolkit/a11ybudget.py +122 -0
  7. package/a11y_toolkit/a11ycrit.py +1017 -0
  8. package/a11y_toolkit/a11ydiff.py +192 -0
  9. package/a11y_toolkit/a11ydisprove.py +175 -0
  10. package/a11y_toolkit/a11ydocx.py +132 -0
  11. package/a11y_toolkit/a11ydom.py +1831 -0
  12. package/a11y_toolkit/a11yevidence.py +272 -0
  13. package/a11y_toolkit/a11yfix.py +330 -0
  14. package/a11y_toolkit/a11yi18n.py +100 -0
  15. package/a11y_toolkit/a11yinit.py +113 -0
  16. package/a11y_toolkit/a11yjourney.py +284 -0
  17. package/a11y_toolkit/a11yledger.py +210 -0
  18. package/a11y_toolkit/a11ymutants.py +406 -0
  19. package/a11y_toolkit/a11yopenacr.py +207 -0
  20. package/a11y_toolkit/a11ypdf.py +273 -0
  21. package/a11y_toolkit/a11yroute.py +378 -0
  22. package/a11y_toolkit/a11ysarif.py +139 -0
  23. package/a11y_toolkit/a11yscroll.py +212 -0
  24. package/a11y_toolkit/a11ystatement.py +158 -0
  25. package/a11y_toolkit/a11yvalidate.py +127 -0
  26. package/a11y_toolkit/a11yvpat.py +238 -0
  27. package/a11y_toolkit/a11yvtt.py +136 -0
  28. package/a11y_toolkit/a11ywcag3.py +262 -0
  29. package/a11y_toolkit/arialive.js +107 -0
  30. package/a11y_toolkit/arialive_js.py +113 -0
  31. package/a11y_toolkit/contrast.py +536 -0
  32. package/a11y_toolkit/locales/_template.json +468 -0
  33. package/a11y_toolkit/locales/en.json +525 -0
  34. package/a11y_toolkit/locales/es.json +525 -0
  35. package/a11y_toolkit/server.py +1529 -0
  36. package/bin/a11y-toolkit-mcp.cjs +2 -2
  37. package/bin/a11y-toolkit.cjs +2 -2
  38. package/lib/runner.cjs +30 -22
  39. package/package.json +2 -1
@@ -0,0 +1,1951 @@
1
+ #!/usr/bin/env python3
2
+ """Express WCAG 2.2 audit over HTML (heuristics, zero dependencies).
3
+
4
+ a11y_audit_url / audit_html check automatic signals mapped to concrete WCAG
5
+ 2.2 criteria. Every finding carries concrete remediation.
6
+
7
+ Criteria covered (static): 1.1.1, 1.2.2, 1.3.1, 1.4.4, 2.1.1, 2.2.1, 2.4.1,
8
+ 2.4.2, 2.4.3, 3.1.1, 3.2.5, 3.3.2, 4.1.2 (+ 1.3.5, 1.4.2, 2.4.4 and ARIA
9
+ value validation since v3.1+).
10
+
11
+ Automation covers ~one third of WCAG: manual review remains irreplaceable.
12
+ This tool is a filter, not a verdict.
13
+
14
+ CLI:
15
+ a11yaudit.py --url https://example.com [--lang es]
16
+ a11yaudit.py --file page.html
17
+ """
18
+
19
+ import argparse
20
+ import json
21
+ import os
22
+ import re
23
+ import sys
24
+ import urllib.request
25
+ from html.parser import HTMLParser
26
+ from . import a11yi18n
27
+
28
+ MAX_HTML = 3_000_000
29
+
30
+ # Campos de formulario que necesitan etiqueta visible o nombre accesible
31
+ _FIELDS = {'text', 'email', 'tel', 'url', 'search', 'password', 'number',
32
+ 'date', 'time', 'datetime-local', 'month', 'week', 'checkbox',
33
+ 'radio', 'file', 'range', 'color'}
34
+ _CONTROLS = ('a', 'button', 'summary')
35
+
36
+ # elementos vacíos: sin endtag en HTML — no empujan pila de visibilidad ni profundidad
37
+ _VOID = {'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link',
38
+ 'meta', 'param', 'source', 'track', 'wbr'}
39
+
40
+ # roles que convierten cualquier elemento en campo etiquetable (e086e5)
41
+ _ROLE_FIELDS = {'textbox', 'searchbox', 'spinbutton', 'combobox', 'listbox',
42
+ 'checkbox', 'radio', 'switch', 'search'}
43
+
44
+ # Subetiquetas BCP-47 principales habituales (validación blanda)
45
+ _LANG_CODES = set('''af am ar az be bg bn bs ca cs cy da de el en es et eu fa fi fr ga gl
46
+ gu he hi hr hu hy id is it ja ka kk km kn ko ky lo lt lv mk ml mn mr ms my ne nl or pa
47
+ pl ps pt ro ru rw si sk sl sq sr sv sw ta te tg th ti tk tr uk ur uz vi zh'''.split())
48
+
49
+ _REGIONS = set('''af ax al dz as ad ao ai aq ag ar am aw au at az bs bh bd bb by be bz
50
+ bm bt bo bq ba bw bv io br io bn bg bf bi cv kh cm ca ky cf td cl cn cx cc co km cg cd
51
+ ck cr ci hr cu cw cy cz dj dk dm do ec eg sv gq er ee et fk fo fj fi fr gf pf tf ga gm
52
+ ge de gh gi gr gl gd gp gu gt gn gw gy ht hm hn hk hu is in id ir iq ie im il it jm je
53
+ jo kz ke ki kp kr kw kg la lv lb ls lr ly li lt lu mo mg mw my mv ml mt mh mq mr mu yt
54
+ mx fm md mc mn me ms ma mz mm na nr np nl nc nz ni ne ng nu nf mp no om pk pw ps pa pg
55
+ py pe ph pn pl pr qa re ro ru rw bl sh kn lc mf pm vc ws sm st sa sn rs sc sl sx sb so
56
+ za gs ss es lk sd sr sj sz se ch sy tw tj tz th tl tg tk to tt tn tr tm tc tv ug ua ae
57
+ gb us um uy uz vu ve vn vg vi wf eh ye zm zw'''.split())
58
+
59
+ # Roles ARIA concretos (WAI-ARIA 1.2); doc- se admite como prefijo de DPUB
60
+ _ROLES_ARIA = set('''alert alertdialog application article banner button caption cell
61
+ checkbox code columnheader combobox complementary contentinfo definition deletion dialog
62
+ directory document emphasis feed figure form generic grid gridcell group heading img image
63
+ input insertion link list listbox listitem log main mark marquee math menu menubar menuitem
64
+ menuitemcheckbox menuitemradio meter navigation none note option paragraph presentation
65
+ progressbar radio radiogroup region row rowgroup rowheader scrollbar search searchbox
66
+ section sectionhead select separator slider spinbutton status strong subscript superscript
67
+ switch tab table tablist tabpanel term textbox time timer toolbar tooltip tree treegrid
68
+ searchfield comment suggestion blockquote
69
+ treeitem'''.split())
70
+
71
+ # Texto de enlace sin propósito (2.4.4), es + en
72
+ _GENERIC_TEXT = {'more', 'read more', 'learn more', 'click here', 'here', 'this',
73
+ 'this link', 'link', 'details', 'view', 'see more', 'continue',
74
+ 'más', 'leer más', 'saber más', 'pincha aquí', 'aquí', 'ver más',
75
+ 'seguir leyendo', 'detalle', 'detalles', 'enlace', 'continuar', 'ver'}
76
+
77
+ # 1.3.3: instructions that rely on position/shape alone (es + en, review-only)
78
+ _SENSORIAL = re.compile(
79
+ r'(?:el|la|los|las)?\s*(?:bot[oó]n|enlace|icono)\s+(?:de|a|hacia)\s+(?:la\s+)?'
80
+ r'(?:derecha|izquierda|arriba|abajo)|(?:pulsa|haz clic en)\s+(?:el|la)\s+'
81
+ r'(?:redondo|verde|cuadrado)|(?:the\s+)?(?:button|link|icon)\s+(?:on|to)\s+(?:the\s+)?'
82
+ r'(?:right|left|top|bottom)|(?:click|press)\s+(?:the\s+)?(?:round|green|square)', re.I)
83
+
84
+ # detección extendida de autocomplete (1.3.5)
85
+
86
+
87
+ # Campos que con frecuencia recogen datos personales (1.3.5)
88
+ _PERSONAL_DATA = re.compile(
89
+ r'(^|[\W_])(name|nombre|email|correo|phone|telefono|tel|address|direccion|postal|zip|'
90
+ r'city|ciudad|country|pais|organi[sz]ation|company|empresa|street|user|usuario)([\W_]|$)', re.I)
91
+
92
+ # Tokens autofill válidos (HTML §7.5 — subconjunto práctico del estándar;
93
+ # one-time-code incluido: los campos OTP lo exigen y los lectores lo usan)
94
+ _AUTOFILL_TOKENS = {
95
+ 'name', 'honorific-prefix', 'given-name', 'additional-name', 'family-name',
96
+ 'nickname', 'username', 'new-password', 'current-password', 'one-time-code',
97
+ 'organization', 'street-address', 'address-line1', 'address-line2',
98
+ 'address-line3', 'address-level4', 'address-level3', 'address-level2',
99
+ 'address-level1', 'country', 'country-name', 'postal-code', 'cc-name',
100
+ 'cc-given-name', 'cc-family-name', 'cc-number', 'cc-exp', 'cc-exp-month',
101
+ 'cc-exp-year', 'cc-csc', 'cc-type', 'transaction-currency',
102
+ 'transaction-amount', 'language', 'bday', 'bday-day', 'bday-month',
103
+ 'bday-year', 'sex', 'url', 'photo',
104
+ 'tel', 'tel-country-code', 'tel-national', 'tel-area-code', 'tel-local',
105
+ 'email', 'impp',
106
+ # esquemas de contacto (WHATWG §7.5: «work email», «mobile tel»…)
107
+ 'home', 'work', 'mobile', 'fax', 'pager',
108
+ # nombres de campo que faltaban
109
+ 'cc-additional-name', 'tel-extension', 'webauthn',
110
+ }
111
+ # sección-*: comodín del estándar (section-main, section-top…)
112
+ _SECTION = __import__('re').compile(r'^section-[a-z0-9-]+$')
113
+
114
+ # gramática de modificadores (WHATWG §7.5): el modificador exige un campo
115
+ # de su familia detrás — "work email" ✓, "work photo" ✗, "shipping" solo ✗
116
+ _MOD_CONTACT = {'home', 'work', 'mobile', 'fax', 'pager'}
117
+ _MOD_ADDRESS = {'shipping', 'billing'}
118
+ # el modificador de contacto solo vale pegado a estos campos (ABNF 73f2c2)
119
+ _FIELDS_AFTER_CONTACT = {'email', 'impp', 'tel', 'tel-country-code', 'tel-national',
120
+ 'tel-area-code', 'tel-local', 'tel-extension'}
121
+ _FIELDS_AFTER_CONTACTMOD = {'username', 'email', 'impp', 'tel', 'tel-country-code',
122
+ 'tel-national', 'tel-area-code', 'tel-local', 'tel-extension',
123
+ 'nickname', 'honorific-prefix', 'given-name', 'additional-name',
124
+ 'family-name', 'new-password', 'current-password', 'one-time-code'}
125
+ _FIELDS_AFTER_ADDRMOD = {'street-address', 'address-line1', 'address-line2', 'address-line3',
126
+ 'address-level1', 'address-level2', 'address-level3', 'address-level4',
127
+ 'country', 'country-name', 'postal-code'}
128
+ _AUTOFILL_FIELDS = _AUTOFILL_TOKENS - _MOD_CONTACT - _MOD_ADDRESS
129
+
130
+ # Validación de VALORES aria-* (estilo axe aria-valid-attr-value)
131
+ _ARIA_BOOL = {'aria-hidden', 'aria-expanded', 'aria-selected', 'aria-pressed',
132
+ 'aria-checked', 'aria-disabled', 'aria-required', 'aria-readonly',
133
+ 'aria-multiline', 'aria-multiselectable', 'aria-modal', 'aria-grabbed'}
134
+ _ARIA_INT = {'aria-level', 'aria-posinset', 'aria-setsize', 'aria-colcount',
135
+ 'aria-rowcount', 'aria-colindex', 'aria-rowindex', 'aria-colspan',
136
+ 'aria-rowspan'}
137
+ _ARIA_NUM = {'aria-valuenow', 'aria-valuemin', 'aria-valuemax'}
138
+ _ARIA_TOKENS = {
139
+ 'aria-sort': {'ascending', 'descending', 'none', 'other'},
140
+ 'aria-current': {'page', 'step', 'location', 'date', 'time', 'true', 'false', ''},
141
+ 'aria-autocomplete': {'inline', 'list', 'both', 'none', ''},
142
+ 'aria-live': {'off', 'polite', 'assertive'},
143
+ 'aria-orientation': {'horizontal', 'vertical', 'undefined'},
144
+ 'aria-relevant': {'additions', 'removals', 'text', 'all'}, # lista: se valida token a token
145
+ }
146
+ _ARIA_IDREFS = {'aria-labelledby', 'aria-describedby', 'aria-controls', 'aria-errormessage'}
147
+ # atributos cuyo tipo tristate aún incluye 'undefined' en ARIA (casos 6a7281)
148
+ _ARIA_BOOL_UNDEFINED = {'aria-expanded', 'aria-selected', 'aria-grabbed'}
149
+
150
+ CRIT = {
151
+ 'es': {
152
+ '1.1.1': '1.1.1 Contenido no textual',
153
+ '1.2.2': '1.2.2 Subtítulos (pregrabado)',
154
+ '1.3.1': '1.3.1 Información y relaciones',
155
+ '1.4.4': '1.4.4 Cambio de tamaño del texto',
156
+ '2.1.1': '2.1.1 Teclado',
157
+ '2.2.1': '2.2.1 Tiempo ajustable',
158
+ '2.4.1': '2.4.1 Evitación de bloques',
159
+ '2.4.2': '2.4.2 Página con título',
160
+ '2.4.3': '2.4.3 Orden del foco',
161
+ '3.1.1': '3.1.1 Idioma de la página',
162
+ '3.2.5': '3.2.5 Cambio a petición',
163
+ '3.3.2': '3.3.2 Etiquetas o instrucciones',
164
+ '1.3.5': '1.3.5 Identificar el propósito de la entrada',
165
+ '2.5.2': '2.5.2 Cancelación del puntero',
166
+ '2.5.3': '2.5.3 Etiqueta en el nombre',
167
+ '3.1.2': '3.1.2 Idioma de las partes',
168
+ '3.3.8': '3.3.8 Autenticación accesible',
169
+ '3.3.1': '3.3.1 Identificación de errores',
170
+ '3.3.4': '3.3.4 Prevención de errores (legal, financiero)',
171
+ '2.4.6': '2.4.6 Encabezados y etiquetas (calidad)',
172
+ '2.1.4': '2.1.4 Atajos de carácter único',
173
+ '2.5.7': '2.5.7 Movimientos de arrastre',
174
+ '3.2.1': '3.2.1 Al recibir foco',
175
+ '3.2.2': '3.2.2 Al recibir entrada',
176
+ '4.1.3': '4.1.3 Mensajes de estado',
177
+ '3.2.6': '3.2.6 Ayuda coherente',
178
+ '1.4.5': '1.4.5 Imágenes de texto',
179
+ '1.4.11': '1.4.11 Contraste no textual',
180
+ '1.4.13': '1.4.13 Contenido al pasar el foco o el puntero',
181
+ '3.3.3': '3.3.3 Sugerencia ante errores',
182
+ '1.4.2': '1.4.2 Control del audio',
183
+ '1.4.3': '1.4.3 Contraste (mínimo)',
184
+ '2.4.4': '2.4.4 Propósito de los enlaces (en contexto)',
185
+ '4.1.2': '4.1.2 Nombre, función, valor',
186
+
187
+ # criterios evaluados por el modo renderizado (a11ydom) — explícitos
188
+ # aquí para que el catálogo sea completo sin depender de import colateral
189
+ '2.4.7': '2.4.7 Foco visible',
190
+ '2.2.2': '2.2.2 Poner en pausa, detener, ocultar',
191
+ '2.5.1': '2.5.1 Gestos de puntero',
192
+ '2.5.4': '2.5.4 Activación por movimiento',
193
+ '1.4.1': '1.4.1 Uso del color',
194
+ '1.3.2': '1.3.2 Secuencia significativa',
195
+ '1.3.3': '1.3.3 Características sensoriales',
196
+ '1.3.4': '1.3.4 Orientación',
197
+ '1.2.3': '1.2.3 Audiodescripción o alternativa media',
198
+ '1.2.5': '1.2.5 Audiodescripción (pregrabado)',
199
+ '3.2.3': '3.2.3 Navegación coherente',
200
+ '3.2.4': '3.2.4 Identificación coherente',
201
+ '2.4.5': '2.4.5 Múltiples vías',
202
+ '2.5.8': '2.5.8 Tamaño del objetivo (mínimo)',
203
+ '1.4.10': '1.4.10 Reflujo',
204
+ '2.1.2': '2.1.2 Sin trampa de teclado',
205
+ '2.4.11': '2.4.11 Foco no ocultado (mínimo)',
206
+ },
207
+ 'en': {
208
+ '1.1.1': '1.1.1 Non-text Content',
209
+ '1.2.2': '1.2.2 Captions (Prerecorded)',
210
+ '1.3.1': '1.3.1 Info and Relationships',
211
+ '1.4.4': '1.4.4 Resize Text',
212
+ '2.1.1': '2.1.1 Keyboard',
213
+ '2.2.1': '2.2.1 Timing Adjustable',
214
+ '2.4.1': '2.4.1 Bypass Blocks',
215
+ '2.4.2': '2.4.2 Page Titled',
216
+ '2.4.3': '2.4.3 Focus Order',
217
+ '3.1.1': '3.1.1 Language of Page',
218
+ '3.2.5': '3.2.5 Change on Request',
219
+ '3.3.2': '3.3.2 Labels or Instructions',
220
+ '1.3.5': '1.3.5 Identify Input Purpose',
221
+ '2.5.2': '2.5.2 Pointer Cancellation',
222
+ '2.5.3': '2.5.3 Label in Name',
223
+ '3.1.2': '3.1.2 Language of Parts',
224
+ '3.3.8': '3.3.8 Accessible Authentication',
225
+ '3.3.1': '3.3.1 Error Identification',
226
+ '3.3.4': '3.3.4 Error Prevention (Legal, Financial)',
227
+ '2.4.6': '2.4.6 Headings and Labels (quality)',
228
+ '2.1.4': '2.1.4 Character Key Shortcuts',
229
+ '2.5.7': '2.5.7 Dragging Movements',
230
+ '3.2.1': '3.2.1 On Focus',
231
+ '3.2.2': '3.2.2 On Input',
232
+ '4.1.3': '4.1.3 Status Messages',
233
+ '3.2.6': '3.2.6 Consistent Help',
234
+ '1.4.5': '1.4.5 Images of Text',
235
+ '1.4.11': '1.4.11 Non-text Contrast',
236
+ '1.4.13': '1.4.13 Content on Hover or Focus',
237
+ '3.3.3': '3.3.3 Error Suggestion',
238
+ '1.4.2': '1.4.2 Audio Control',
239
+ '1.4.3': '1.4.3 Contrast (Minimum)',
240
+ '2.4.4': '2.4.4 Link Purpose (In Context)',
241
+ '4.1.2': '4.1.2 Name, Role, Value',
242
+
243
+ '2.4.7': '2.4.7 Focus Visible',
244
+ '2.2.2': '2.2.2 Pause, Stop, Hide',
245
+ '2.5.1': '2.5.1 Pointer Gestures',
246
+ '2.5.4': '2.5.4 Motion Actuation',
247
+ '1.4.1': '1.4.1 Use of Color',
248
+ '1.3.2': '1.3.2 Meaningful Sequence',
249
+ '1.3.3': '1.3.3 Sensory Characteristics',
250
+ '1.3.4': '1.3.4 Orientation',
251
+ '1.2.3': '1.2.3 Audio Description or Media Alternative',
252
+ '1.2.5': '1.2.5 Audio Description (Prerecorded)',
253
+ '3.2.3': '3.2.3 Consistent Navigation',
254
+ '3.2.4': '3.2.4 Consistent Identification',
255
+ '2.4.5': '2.4.5 Multiple Ways',
256
+ '2.5.8': '2.5.8 Target Size (Minimum)',
257
+ '1.4.10': '1.4.10 Reflow',
258
+ '2.1.2': '2.1.2 No Keyboard Trap',
259
+ '2.4.11': '2.4.11 Focus Not Obscured (Minimum)',
260
+ },
261
+ }
262
+
263
+ T = a11yi18n.pair('audit') # locales/<lang>.json — community-editable
264
+
265
+ # Aviso de ventana nueva: texto que lo indica o icono con nombre
266
+ _BLANK_HINT = re.compile(r'nueva|nuevo|ventana|pesta|tab\b|window|external|externo|exterior', re.I)
267
+
268
+ # Widgets de accesibilidad de terceros ("overlays"): detección por dominio del
269
+ # script cargado. NO es un fallo WCAG (ningún criterio dice "no uses overlays";
270
+ # la posición pública es comunitaria: overlayfactsheet.com) — se reporta como
271
+ # dato del informe para la diligencia de compra. Detección ≠ juicio: la página
272
+ # puede seguir teniendo fallos reales, y esto no toca score ni findings.
273
+ _OVERLAY_WIDGETS = (
274
+ ('accessiBe', ('accessibe.com', 'acsbapp.com')),
275
+ ('UserWay', ('userway.org',)),
276
+ ('AudioEye', ('audioeye.com',)),
277
+ ('EqualWeb', ('equalweb.com',)),
278
+ ("FACIL'ITI", ('facil-iti.com', 'facil-iti.org')),
279
+ )
280
+
281
+
282
+ def _t(lang, key, n=None):
283
+ """Message by key; `{"one","other"}` entries resolve via the locale's
284
+ CLDR plural rule when the caller passes the count."""
285
+ value = T.get(lang, T['en']).get(key, key)
286
+ return a11yi18n.plural_entry(value, lang, n) if n is not None else value
287
+
288
+
289
+ def _crit(lang, code):
290
+ return CRIT.get(lang, CRIT['es'])[code]
291
+
292
+
293
+ class _Auditor(HTMLParser):
294
+ def __init__(self):
295
+ super().__init__(convert_charrefs=True)
296
+ self.imgs_no_alt = []
297
+ self.controls_by_kind = {} # tag → lista de atributos de controles sin nombre
298
+ self.fields_no_label = []
299
+ self.iframes_no_title = []
300
+ self.lang = None
301
+ self.lang_region_invalid = None
302
+ self.title = ''
303
+ self._in_title = False
304
+ self._in_script = False
305
+ self._script_srcs = [] # src de cada <script>: huella de overlays de terceros
306
+ self._in_style = False
307
+ self.headings = [] # (nivel, texto)
308
+ self._heading_level = None
309
+ self._heading_text = []
310
+ self._visible_text = []
311
+ self._heading_text = []
312
+ self.positive_tabindices = []
313
+ self.viewport = None
314
+ self.elements = 0
315
+ # Pila de controles interactivos (a/button/summary) para recoger su
316
+ # texto interno, que es la fuente más habitual de nombre accesible.
317
+ self._ctrl = []
318
+ self._label_depth = 0
319
+ self._labels_stack = [] # un booleano por <label> abierto: ¿contiene campo?
320
+ self._labels_for = {} # id → nº de <label for> que lo apuntan
321
+ self.orphan_labels = 0
322
+ # Nuevas señales
323
+ self.aria_hidden_focusable = [] # tag de interactivos con aria-hidden
324
+ self.stray_clicks = [] # tags no interactivos con onclick
325
+ self.meta_refresh = None
326
+ self.meta_refreshes = [] # todos los meta refresh: gana el 1º parseable (spec HTML)
327
+ self.saw_html = False
328
+ self.saw_body = False
329
+ self.root_tag = None
330
+ self._in_head = False
331
+ self._in_template = 0
332
+ self._title_buf = []
333
+ self._titles_in_order = []
334
+ # accname (ola de precisión ACT): visibilidad HEREDADA (aria-hidden con
335
+ # re-activación por false, attr hidden, display:none/visibility:hidden)
336
+ # y registro id→texto para resolver aria-labelledby a un salto — los ids
337
+ # referenciados pueden declararse DESPUÉS del elemento, así que la
338
+ # decisión de nombre se toma post-parse, no en streaming
339
+ self._hidden_stack = [(False, False)] # (hidden_cualquiera, hidden_aria)
340
+ self._css_hidden_stack = [False] # hidden por hidden/display:none/visibility:hidden
341
+ self._ah_true_stack = [] # un bool por elemento abierto: ¿él mismo aria-hidden=true?
342
+ self._ah_true_depth = 0 # ancestros abiertos con aria-hidden=true (6cfa84)
343
+ self._id_texts = {}
344
+ self._id_text_parts = {}
345
+ self._open_ids = []
346
+ self._depth = 0
347
+ self._scripts_text = '' # contenido de <script>: ids de centinelos de foco
348
+ self._styles_text = '' # contenido de <style>: clases ocultas y fuentes-icono
349
+ self._styles_cached_src = None
350
+ self._style_rules = []
351
+ self._icon_links = []
352
+ self._ahf_deferred = [] # (tag, id) off-screen: decidir post-parse con los scripts completos
353
+ self._el_stack = [] # (tag, attrs, [texto directo]) — texto propio del elemento
354
+ self._role_field_ids = set() # ids de campos por rol: su texto directo es su nombre
355
+ self._field_buffers = {} # id → texto directo (rescatado al cerrar)
356
+ self._role_field_text = [] # (attrs, texto directo) de campos por rol, con o sin id
357
+ self._nav_ids = set() # ids de <nav>: bloque repetido abatible por botón (3e12e1)
358
+ self._toggle_onclicks = []
359
+ # candidatos en cruto para las decisiones de nombre post-parse
360
+ self.imgs_all = [] # (attrs, hidden)
361
+ self.inputs_image = [] # (attrs, hidden)
362
+ self.iframes_all = [] # (attrs, hidden)
363
+ self.controls_raw = [] # (kind, attrs, texto, [nombres imgs internas], hidden)
364
+ self.headings_raw = [] # (nivel, attrs, texto, hidden)
365
+ self.fields_raw = [] # (tag, kind, attrs, dentro_de_label, hidden)
366
+ self._heading_attrs = {}
367
+ self.videos = 0
368
+ self.videos_with_captions = 0
369
+ self._in_video = False
370
+ self.tables = 0
371
+ self.tables_with_th = 0
372
+ self._in_table = False
373
+ self._th_in_table = False
374
+ self.blank_no_warning = 0
375
+ self.blank_total = 0
376
+ self.hay_main = False
377
+ self.hay_skip = False
378
+ self.h1s = 0
379
+ self.empty_h = 0
380
+ self.ids = {}
381
+ self.input_img_no_alt = 0
382
+ # v3.1: validez ARIA, autocomplete, enlaces, landmarks, accesskey, autoplay
383
+ self.aria_refs = [] # (attr, id) referenciados por aria-labelledby/describedby
384
+ self.aria_values = [] # valores aria-* inválidos
385
+ self.unknown_roles = []
386
+ self.roles_without_state = [] # widgets con role que exige aria-valuenow
387
+ self.landmarks = {} # tipo → [con_etiqueta, total]
388
+ self.accesskeys = {} # accesskey → tag
389
+ self.missing_autocomplete = []
390
+ self.autocomplete_invalid = []
391
+ self.links = {} # nombre normalizado → set de hrefs
392
+ self.generics = 0
393
+ self.labels_for_dups = {} # id → n labels (los >1, varios)
394
+ self.media_autoplay = 0
395
+ self._list_depth = 0
396
+ self._li_depth = 0
397
+ self._bad_list = 0
398
+ self.label_no_name = [] # (texto visible, aria-label) 2.5.3
399
+ self.lang_parts_invalid = [] # lang inválidos en elementos no-html
400
+ self.down_events = [] # onmousedown/ontouchstart/onpointerdown
401
+ self.captchas = [] # detección 3.3.8
402
+ self.mobiles = [] # marquee/blink/inline infinite animation (2.2.2)
403
+ self.nav_hrefs = set() # hrefs inside <nav> (site-level 3.2.3 signature)
404
+ self.help_hrefs = set() # help/contact links (site-level 3.2.6 signature)
405
+ self.images_of_text = []
406
+ self.vague_headings = []
407
+ self.char_shortcuts = []
408
+ self.drag_handlers = []
409
+ self.status_regions = 0
410
+ self.placeholder_only = [] # 3.3.2: placeholder sin label (decisión post-parse)
411
+ self._placeholder_candidates = []
412
+ self.required_no_indication = [] # 3.3.2: required sin * ni "obligatorio"
413
+ self.missing_fieldsets = 0 # 1.3.1: radio/check groups sin fieldset
414
+ self._radio_group = {}
415
+ self._radio_in_fieldset = {} # name → count (para detectar grupos)
416
+ self.vague_labels = [] # 2.4.6: label quality
417
+ self.financial_no_confirm = 0 # 3.3.4: financial form no confirm
418
+ self._financial_form = False
419
+ self._confirm_form = False # 1.4.5 suspicion: img inside heading or very long alt
420
+ self._in_nav = 0
421
+ self._in_fieldset = False
422
+ self.has_search = False
423
+ self.has_sitemap = False
424
+ self.gestures = [] # touchmove/drag handlers (2.5.1)
425
+ self.motions = [] # deviceorientation/devicemotion (2.5.4)
426
+ self.orientation_locks = [] # screen.orientation.lock / orientation MQ (1.3.4)
427
+ self.videos_descriptions = 0 # videos WITH descriptions track
428
+ self.sensory = [] # sensory-only instruction patterns (1.3.3)
429
+ self._skip_labels_pend = [] # labels declarados antes que su campo
430
+
431
+ def _close_control(self, tag):
432
+ if not self._ctrl:
433
+ return
434
+ c = self._ctrl[-1]
435
+ if c['tag'] != tag:
436
+ return
437
+ self._ctrl.pop()
438
+ a = c['attrs']
439
+ text = ' '.join(c['text']).strip()
440
+ # decisión de nombre POST-parse: los ids de un aria-labelledby pueden
441
+ # declararse después del control; se registra todo en crudo
442
+ self.controls_raw.append((c.get('kind') or tag, a, text, c.get('img_attrs', []),
443
+ c.get('hidden', False)))
444
+ # 2.5.3 label in name — algoritmo de WCAG Understanding 2.5.3: sin el
445
+ # contenido entre paréntesis, minúsculas, sin puntuación, y la
446
+ # etiqueta visible contenida POR PALABRAS en el nombre («just ice» ≠
447
+ # «justice»; «Discover It» falla contra «Discover Italy»). Una
448
+ # etiqueta visible de un solo carácter/símbolo (X, emoji) es texto no
449
+ # verbal: exenta. La etiqueta es la que se VEE (la oculta por CSS no)
450
+ # concatenación DOM fiel: sin espacios artificiales — los del DOM ya
451
+ # vienen en los propios nodos de texto (2ee8b8: «W C A G» ≠ «ACT»)
452
+ _vis = ''.join(c.get('text_visible', [])).strip()
453
+ _al = (a.get('aria-label') or '').strip()
454
+ # página con fuente-icono declarada (Material Icons, Font Awesome…):
455
+ # el «texto» de un botón puede ser un glifo no verbal — exento
456
+ _icon_font = bool(re.search(
457
+ r"font-family\s*:[^;}]*?(Material[+ ]Icons|Font Awesome|glyphicon|icomoon|feather)"
458
+ r"|@font-face[^}]*?(Material[+ ]Icons|Font Awesome|glyphicon|icomoon|feather)",
459
+ self._styles_text, re.I)) or bool(re.search(
460
+ r'fonts\.googleapis\.com/icon|/material-icons|font-?awesome|/icomoon',
461
+ ' '.join(getattr(self, '_icon_links', [])), re.I))
462
+ if not (tag == 'button' and _icon_font) and _vis and _al:
463
+ def _lin_words(txt):
464
+ txt = re.sub(r'\([^)]*\)', ' ', txt)
465
+ # la puntuación se ELIMINA sin partir palabras («11×3=33» →
466
+ # «1133»: una sola palabra) — algoritmo 2.5.3
467
+ return [w for w in re.sub(r'[^\w\s]|_', '', txt.lower()).split() if w]
468
+ _vp, _ap2 = _lin_words(_vis), _lin_words(_al)
469
+ _mismatch = False
470
+ if _vp and _ap2:
471
+ if len(_vp) == 1 and len(_vp[0]) <= 2 and _vp[0].isalpha():
472
+ _mismatch = False # letra-símbolo única (X): texto no verbal
473
+ else:
474
+ # RODAJA CONTIGUA EXACTA: «discover it» no cabe en
475
+ # «discover italy» (it ≠ italy); «download specification»
476
+ # no cabe en «download the specification»; «you how are»
477
+ # no en «how are you» aunque estén todas las palabras
478
+ _mismatch = not any(_ap2[i:i + len(_vp)] == _vp
479
+ for i in range(len(_ap2) - len(_vp) + 1))
480
+ if _mismatch:
481
+ self.label_no_name.append((_vis[:40], _al[:60]))
482
+ if tag == 'a':
483
+ if (a.get('target') or '').lower() == '_blank':
484
+ self.blank_total += 1
485
+ if not _BLANK_HINT.search(text) and not _BLANK_HINT.search(a.get('aria-label') or '') \
486
+ and not _BLANK_HINT.search(a.get('title') or ''):
487
+ self.blank_no_warning += 1
488
+ elif (a.get('href') or '').strip().startswith('#') and len((a.get('href') or '').strip()) > 1 and text:
489
+ self.hay_skip = True # ancla interna con fragmento y texto: candidato a skip link
490
+ name = (text or a.get('aria-label') or a.get('title') or '').strip()
491
+ href = (a.get('href') or '').strip()
492
+ if name and href:
493
+ entry_key = ' '.join(name.lower().split())[:60]
494
+ self.links.setdefault(entry_key, set()).add(href)
495
+ if entry_key in _GENERIC_TEXT:
496
+ self.generics += 1
497
+
498
+ def _field_note(self):
499
+ """El elemento que acaba de abrirse es un campo: marca su <label> ancestro."""
500
+ if self._labels_stack:
501
+ self._labels_stack[-1] = True
502
+
503
+ def handle_starttag(self, tag, attrs):
504
+ a = dict(attrs)
505
+ self.elements += 1
506
+ if a.get('id'):
507
+ self.ids[a['id']] = self.ids.get(a['id'], 0) + 1
508
+ if self.root_tag is None:
509
+ self.root_tag = tag
510
+ # visibilidad heredada para accname y enfocabilidad: aria-hidden se
511
+ # hereda y aria-hidden="false" RE-ACTIVA el subárbol; hidden y
512
+ # display:none/visibility:hidden ocultan sin re-activación
513
+ _style = (a.get('style') or '').replace(' ', '').lower()
514
+ _inh, _inh_aria = self._hidden_stack[-1]
515
+ _ah_val = (a.get('aria-hidden') or '').strip().lower()
516
+ _hidden_aria = _inh_aria
517
+ if _ah_val == 'true':
518
+ _hidden_aria = True
519
+ elif _ah_val == 'false':
520
+ _hidden_aria = False
521
+ _hidden = _inh or 'hidden' in a or 'display:none' in _style \
522
+ or 'visibility:hidden' in _style or _hidden_aria
523
+ if tag not in _VOID:
524
+ self._depth += 1
525
+ self._hidden_stack.append((_hidden, _hidden_aria))
526
+ self._css_hidden_stack.append('hidden' in a or 'display:none' in _style
527
+ or 'visibility:hidden' in _style
528
+ or self._css_hidden_stack[-1])
529
+ self._ah_true_stack.append(_ah_val == 'true')
530
+ if _ah_val == 'true':
531
+ self._ah_true_depth += 1
532
+ if a.get('id'):
533
+ self._open_ids.append((a['id'], self._depth))
534
+ self._el_stack.append((tag, a, []))
535
+ if tag == 'nav' and a.get('id'):
536
+ self._nav_ids.add(a['id'])
537
+ if a.get('onclick'):
538
+ self._toggle_onclicks.append(a['onclick'])
539
+ if tag == 'head':
540
+ self._in_head = True
541
+ elif tag == 'template':
542
+ self._in_template += 1
543
+ elif tag == 'html':
544
+ self.saw_html = True
545
+ self.lang = (a.get('lang') or '').strip()
546
+ parts = self.lang.split('-')
547
+ if len(parts) == 2 and parts[1] and parts[1].isalpha() \
548
+ and parts[1].lower() not in _REGIONS:
549
+ self.lang_region_invalid = self.lang
550
+ elif tag == 'body':
551
+ self.saw_body = True
552
+ elif tag == 'title' and not self._in_template:
553
+ # TODOS los <title> se acumulan en orden de documento: decide el
554
+ # PRIMERO (modelo de ACT 2779a5: head vacío + body con texto falla;
555
+ # title solo en body pasa; los de <template> son inertes)
556
+ self._in_title = True
557
+ elif tag == 'script':
558
+ self._in_script = True
559
+ if a.get('src'):
560
+ self._script_srcs.append(a['src'])
561
+ elif tag == 'style':
562
+ self._in_style = True
563
+ elif tag == 'link':
564
+ if (a.get('rel') or '').lower() == 'stylesheet' and a.get('href'):
565
+ self._icon_links.append(a['href'])
566
+ elif tag == 'meta':
567
+ if a.get('name', '').lower() == 'viewport':
568
+ self.viewport = a.get('content', '')
569
+ elif (a.get('http-equiv') or '').lower() == 'refresh':
570
+ self.meta_refresh = a.get('content', '')
571
+ self.meta_refreshes.append(a.get('content', ''))
572
+ elif tag == 'img':
573
+ # la decisión de nombre es POST-parse (nombre accesible = alt u
574
+ # otras fuentes; presentación/none y hiddens quedan fuera)
575
+ self.imgs_all.append((a, _hidden))
576
+ alt = (a.get('alt') or '').strip()
577
+ if self._ctrl:
578
+ # la imagen interna aporta SU nombre completo al control
579
+ # (alt, aria-label, title, labelledby — resuelto post-parse)
580
+ self._ctrl[-1]['img_attrs'].append(a)
581
+ if alt and not _hidden:
582
+ # el alt SE LEE: cuenta como texto bajo el lang de su
583
+ # contexto (de46e4 — una img con alt es contenido textual)
584
+ self._effective_lang_check()
585
+ if self._heading_level is not None and not _hidden \
586
+ and (a.get('role') or '').strip().lower() not in ('presentation', 'none'):
587
+ # nombre de la imagen (alt u otras fuentes) alimenta al
588
+ # encabezado — salvo presentación/none u oculta (ffd0e9)
589
+ _nom_img = alt or (a.get('aria-label') or '').strip() \
590
+ or (a.get('title') or '').strip()
591
+ if _nom_img:
592
+ self._heading_text.append(_nom_img)
593
+ self.images_of_text.append('imagen dentro de encabezado')
594
+ elif len(alt) > 120:
595
+ self.images_of_text.append(f'alt de {len(alt)} caracteres')
596
+ elif tag == 'iframe':
597
+ self.iframes_all.append((a, _hidden))
598
+ elif tag == 'nav':
599
+ self._in_nav += 1
600
+ elif tag in _CONTROLS:
601
+ # Enlace no interactivo (ancla pura sin href): no se audita.
602
+ if tag == 'a' and not (a.get('href') or '').strip():
603
+ pass
604
+ else:
605
+ self._ctrl.append({'tag': tag, 'attrs': a, 'text': [], 'text_visible': [],
606
+ 'inner_img': False,
607
+ 'img_attrs': [], 'hidden': _hidden})
608
+ href = (a.get('href') or '').strip()
609
+ if self._in_nav and href and not href.startswith('#'):
610
+ self.nav_hrefs.add(href.split('#')[0].rstrip('/'))
611
+ if href and re.search(r'help|contact|support|ayuda|contacto|soporte|asistencia',
612
+ href, re.I):
613
+ self.help_hrefs.add(href.split('#')[0].rstrip('/'))
614
+ if href and re.search(r'sitemap|site-map|mapa-del-sitio|mapa_web|mapaweb', href, re.I):
615
+ self.has_sitemap = True
616
+ elif tag == 'input':
617
+ self._field_note()
618
+ kind = (a.get('type') or 'text').lower()
619
+ if kind == 'image':
620
+ self.inputs_image.append((a, _hidden))
621
+ elif kind in ('submit', 'button', 'reset'):
622
+ # decisión de nombre post-parse: los input botones tienen valor
623
+ # por defecto del navegador ("Submit"/"Reset") — nunca sin nombre
624
+ self.controls_raw.append((f'input:{kind}', a, '', [], _hidden))
625
+ if kind == 'search' or re.search(r'search|busqueda|b[uú]squeda', (a.get('name') or '') + (a.get('id') or ''), re.I):
626
+ self.has_search = True
627
+ if kind in _FIELDS:
628
+ self.fields_raw.append((tag, kind, a, self._label_depth > 0, _hidden))
629
+ if 'autocomplete' not in a and kind != 'search' and (
630
+ kind in ('email', 'tel')
631
+ or _PERSONAL_DATA.search((a.get('name') or '') + ' ' + (a.get('id') or ''))):
632
+ self.missing_autocomplete.append(f'input type={kind} name={a.get("name") or "?"}'[:44])
633
+ if tag == 'input' and 'autocomplete' in a and 'disabled' not in a \
634
+ and (a.get('aria-disabled') or '').strip().lower() != 'true' and not _hidden:
635
+ # ABNF exacta de la regla ACT 73f2c2 (HTML autofill): [section-*]?
636
+ # [shipping|billing]? [home|work|mobile|fax|pager — solo si el
637
+ # siguiente es email/impp/tel/tel-*]? campo [webauthn]? — los
638
+ # campos disabled u hiddens quedan fuera (aplicabilidad)
639
+ _toks = (a['autocomplete'] or '').split()
640
+ _mal = None
641
+ if not (_toks == ['on'] or _toks == ['off']):
642
+ _i = 0
643
+ if _toks and _SECTION.match(_toks[0]):
644
+ _i = 1
645
+ if len(_toks) > _i and _toks[_i] in _MOD_ADDRESS:
646
+ _i += 1
647
+ if len(_toks) > _i and _toks[_i] in _MOD_CONTACT:
648
+ if len(_toks) > _i + 1 and _toks[_i + 1].split(':')[-1] in _FIELDS_AFTER_CONTACT:
649
+ _i += 1
650
+ else:
651
+ _mal = _toks[_i] # «work photo»: contacto exige su campo pegado
652
+ if _mal is None:
653
+ _remainder = _toks[_i:]
654
+ if not _remainder or _remainder[0].split(':')[-1] not in _AUTOFILL_FIELDS:
655
+ _mal = _remainder[0] if _remainder else (_toks or [None])[0]
656
+ elif len(_remainder) == 2 and _remainder[1] != 'webauthn':
657
+ _mal = _remainder[1]
658
+ elif len(_remainder) > 2:
659
+ _mal = _remainder[1]
660
+ if _mal:
661
+ self.autocomplete_invalid.append(
662
+ f'{_mal} (input name={a.get("name") or "?"})'[:60])
663
+ elif tag in ('select', 'textarea'):
664
+ self._field_note()
665
+ self.fields_raw.append((tag, tag, a, self._label_depth > 0, _hidden))
666
+ elif tag == 'label':
667
+ self._label_depth += 1
668
+ self._label_text_current = []
669
+ self._labels_stack.append(False)
670
+ if a.get('for'):
671
+ self._labels_for[a['for']] = self._labels_for.get(a['for'], 0) + 1
672
+ if self._labels_for[a['for']] > 1:
673
+ self.labels_for_dups[a['for']] = self._labels_for[a['for']]
674
+ self._labels_stack[-1] = True
675
+ elif tag == 'marquee':
676
+ self.mobiles.append('<marquee>')
677
+ elif tag == 'blink':
678
+ self.mobiles.append('<blink>')
679
+ elif tag == 'track':
680
+ kind = (a.get('kind') or '').lower()
681
+ if kind == 'descriptions':
682
+ self.videos_descriptions += 1
683
+ elif kind in ('captions', 'subtitles'):
684
+ self.videos_with_captions += 1
685
+ elif tag in ('video', 'audio'):
686
+ if tag == 'video':
687
+ self.videos += 1
688
+ self._in_video = True
689
+ if 'autoplay' in a:
690
+ self.media_autoplay += 1
691
+ elif tag in ('ul', 'ol'):
692
+ self._list_depth += 1
693
+ elif tag == 'li':
694
+ self._li_depth += 1
695
+ elif tag == 'table':
696
+ self.tables += 1
697
+ self._in_table = True
698
+ self._th_in_table = False
699
+ elif tag == 'th':
700
+ self._th_in_table = True
701
+ elif tag == 'main' or (a.get('role') or '').lower() == 'main':
702
+ self.hay_main = True
703
+ elif tag not in _CONTROLS + ('input', 'select', 'textarea', 'label', 'option',
704
+ 'video', 'audio', 'details', 'summary'):
705
+ _role_v = a.get('role', '').strip().lower()
706
+ if _role_v in _ROLE_FIELDS and _role_v not in ('none', 'presentation'):
707
+ if a.get('id'):
708
+ self._role_field_ids.add(a['id'])
709
+ # campos por rol (textbox, searchbox…): mismos requisitos de
710
+ # nombre — pero un <label> envolvente NO los etiqueta: el
711
+ # label solo asocia con elementos LABELABLE (input, select,
712
+ # textarea…), un div con role no lo es (e086e5)
713
+ self._field_note()
714
+ self.fields_raw.append((tag, 'role:' + _role_v, a, False, _hidden))
715
+ elif _role_v in ('button', 'link'):
716
+ # controles por rol: también necesitan nombre (97a4e1) — entran
717
+ # en la pila de controles para recoger su texto interno
718
+ self._ctrl.append({'tag': tag, 'attrs': a, 'text': [], 'text_visible': [],
719
+ 'inner_img': False,
720
+ 'img_attrs': [], 'hidden': _hidden, 'depth': self._depth,
721
+ 'kind': 'role:' + _role_v})
722
+ elif _role_v == 'img' and tag != 'img':
723
+ # div[role=img] con imagen de fondo: también necesita nombre (23a2a8)
724
+ self.imgs_all.append((a, _hidden))
725
+ if a.get('onclick') and not a.get('role') and 'tabindex' not in a:
726
+ self.stray_clicks.append(tag)
727
+ # v3.9: 2.5.2 sospecha de activación en down-event
728
+ for _de in ('onmousedown', 'ontouchstart', 'onpointerdown'):
729
+ if a.get(_de):
730
+ self.down_events.append(f'{tag}[{_de}]')
731
+ break
732
+ # v3.12: 2.2.2 inline looping animation
733
+ style = a.get('style') or ''
734
+ if 'animation' in style and 'infinite' in style:
735
+ self.mobiles.append(f'{tag}[style animation…infinite]')
736
+ # v3.12: 2.5.1 gesture without click alternative (attribute-level hint)
737
+ if a.get('ontouchmove') or a.get('ondrag'):
738
+ if not (a.get('onclick') or tag in ('input', 'button', 'a')):
739
+ self.gestures.append(f'{tag}[{list(a)[0] if a else ""}]')
740
+ # forms: placeholder-only, required sin indicio, financial
741
+ if tag == 'form':
742
+ self._financial_form = False
743
+ self._confirm_form = False
744
+ action = (a.get('action') or '').lower()
745
+ if re.search(r'pay|purchase|checkout|buy|order|contract|legal|billing',
746
+ action, re.I):
747
+ self._financial_form = True
748
+ if tag in ('input', 'textarea') and a.get('placeholder') \
749
+ and not (a.get('aria-label') or a.get('aria-labelledby')):
750
+ # candidato a placeholder-only: se confirma POST-parse (un
751
+ # <label for> con su id le da nombre real y lo retira)
752
+ self._placeholder_candidates.append((tag, a, self._label_depth > 0, _hidden))
753
+ if a.get('required') is not None or 'required' in a or a.get('aria-required') == 'true':
754
+ ph = (a.get('placeholder') or '').lower()
755
+ title_ = (a.get('title') or '').lower()
756
+ if not re.search(r'\*|requerid|obligator|required|necesari|precisa', ph + title_):
757
+ self.required_no_indication.append(
758
+ f'{tag}[name={a.get("name","?")}]')
759
+ if tag == 'input' and a.get('type') == 'radio':
760
+ nm = a.get('name') or '(no name)'
761
+ self._radio_group[nm] = self._radio_group.get(nm, 0) + 1
762
+ self._radio_in_fieldset[nm] = self._in_fieldset
763
+ if tag == 'fieldset':
764
+ self._in_fieldset = True
765
+ if tag in ('button', 'input'):
766
+ val = (a.get('value') or a.get('data-action') or '').lower()
767
+ if re.search(r'confirm|verificar|review|revisar|accept|aceptar', val):
768
+ self._confirm_form = True
769
+ # checkbox de términos
770
+ if tag == 'input' and a.get('type') == 'checkbox':
771
+ nm = (a.get('name') or '').lower()
772
+ if re.search(r'terms|accept|agree|terminos|aceptar|legal|privacy', nm):
773
+ self._confirm_form = True
774
+ if a.get('draggable') and (a.get('draggable') or '').lower() != 'false':
775
+ if not a.get('onclick') and tag not in ('input', 'button'):
776
+ self.drag_handlers.append(f'{tag}[draggable]')
777
+ if a.get('aria-live') or (a.get('role') or '').lower() in ('status', 'alert', 'log'):
778
+ self.status_regions += 1
779
+ if a.get('accesskey') and len((a.get('accesskey') or '').strip()) == 1:
780
+ self.char_shortcuts.append(f'{tag}[accesskey]')
781
+ # v3.12: 2.5.4 motion actuation handlers
782
+ for _ma in ('ondeviceorientation', 'ondevicemotion'):
783
+ if a.get(_ma):
784
+ self.motions.append(f'{tag}[{_ma}]')
785
+ # v3.12: 1.3.4 orientation lock hints (attribute/inline level)
786
+ if tag == 'meta' and 'orientation' in (a.get('content') or '').lower() \
787
+ and 'lock' in (a.get('content') or '').lower():
788
+ self.orientation_locks.append('meta orientation lock')
789
+ # v3.9: 3.3.8 captcha
790
+ for _v in (a.get('src') or '', a.get('href') or '', a.get('id') or ''):
791
+ if re.search(r'recaptcha|hcaptcha|turnstile|captcha', _v, re.I):
792
+ self.captchas.append(f'{tag} {_v[:50]}')
793
+ break
794
+ if (a.get('name') or '').lower().find('captcha') >= 0:
795
+ self.captchas.append(f'input name={a["name"][:30]}')
796
+ # v3.1/v3.3: validez ARIA (atributos, referencias y VALORES)
797
+ for _ar in _ARIA_IDREFS:
798
+ if a.get(_ar):
799
+ for _ref in a[_ar].split():
800
+ self.aria_refs.append((_ar, _ref))
801
+ for _ar, _val in a.items():
802
+ if not _ar.startswith('aria-'):
803
+ continue
804
+ _val = (_val or '').strip().lower()
805
+ if not _val:
806
+ continue # atributo sin valor: nada que validar (6a7281)
807
+ if _ar in _ARIA_BOOL and _val not in ('true', 'false') \
808
+ and not (_val == 'mixed' and _ar in ('aria-pressed', 'aria-checked')) \
809
+ and not (_val == 'undefined' and _ar in _ARIA_BOOL_UNDEFINED):
810
+ self.aria_values.append({'attr': _ar, 'val': _val, 'type': 'bool'})
811
+ elif _ar in _ARIA_INT and not _val.isdigit():
812
+ self.aria_values.append({'attr': _ar, 'val': _val, 'type': 'int'})
813
+ elif _ar in _ARIA_NUM:
814
+ try:
815
+ float(_val)
816
+ except ValueError:
817
+ self.aria_values.append({'attr': _ar, 'val': _val, 'type': 'num'})
818
+ elif _ar == 'aria-relevant':
819
+ # es una LISTA: cada token debe ser válido; una lista entera
820
+ # válida nunca llega al caso genérico
821
+ if any(_tk not in _ARIA_TOKENS['aria-relevant'] for _tk in _val.split()):
822
+ self.aria_values.append({'attr': _ar, 'val': _val, 'type': 'tokens',
823
+ 'valid_tokens': '/'.join(sorted(_ARIA_TOKENS['aria-relevant']))})
824
+ elif _ar in _ARIA_TOKENS and _val not in _ARIA_TOKENS[_ar]:
825
+ self.aria_values.append({'attr': _ar, 'val': _val,
826
+ 'type': 'tokens',
827
+ 'valid_tokens': '/'.join(sorted(v for v in _ARIA_TOKENS[_ar] if v))})
828
+ if a.get('role'):
829
+ # role admite LISTA de tokens separados por espacios (con
830
+ # fallback): TODOS deben ser roles válidos, no solo el primero
831
+ for role in a['role'].strip().lower().split():
832
+ if role not in _ROLES_ARIA and not role.startswith('doc-'):
833
+ self.unknown_roles.append(role)
834
+ if any(r in ('slider', 'spinbutton') for r in a['role'].strip().lower().split()) \
835
+ and 'aria-valuenow' not in a:
836
+ self.roles_without_state.append(f'{tag}[role={a["role"].split()[0]}]')
837
+ landmark_role = a.get('role', '').lower() if a.get('role') in (
838
+ 'banner', 'contentinfo', 'navigation', 'complementary', 'main', 'form', 'search', 'region') else None
839
+ lm = tag if tag in ('header', 'footer', 'nav', 'aside', 'main', 'search') else landmark_role
840
+ if lm and not (a.get('aria-label') or a.get('aria-labelledby')):
841
+ t = self.landmarks.setdefault(lm, [0, 0])
842
+ t[0] += 1
843
+ t[1] += 1
844
+ elif lm:
845
+ self.landmarks.setdefault(lm, [0, 0])[1] += 1
846
+ if a.get('accesskey'):
847
+ k = a['accesskey'].strip().lower()
848
+ self.accesskeys[k] = self.accesskeys.get(k, 0) + 1
849
+ if self._list_depth > 0 and self._li_depth == 0 \
850
+ and tag not in ('li', 'script', 'template', 'ul', 'ol'):
851
+ self._bad_list += 1
852
+ # 4.1.2/2.1.2: enfocable dentro de un subárbol aria-hidden=true — el
853
+ # aria-hidden=false anidado NO exime (ACT 6cfa84). No es enfocable:
854
+ # hidden por CSS/hidden (fuera de la navegación por tab), tabindex=-1
855
+ # explícito, o disabled (aria-disabled NO desactiva).
856
+ _ti_raw = (a.get('tabindex') or '').strip()
857
+ _ti_num = None
858
+ if _ti_raw and (_ti_raw.isdigit() or _ti_raw[1:].isdigit()):
859
+ _ti_num = int(_ti_raw)
860
+ _css_hidden = 'hidden' in a or 'display:none' in _style or 'visibility:hidden' in _style \
861
+ or self._css_hidden_stack[-1]
862
+ _native = (tag in ('button', 'summary', 'select', 'textarea', 'iframe')
863
+ or (tag in ('a', 'area') and (a.get('href') or '').strip())
864
+ or (tag == 'input' and (a.get('type') or 'text').lower() != 'hidden')
865
+ or (tag in ('video', 'audio') and 'controls' in a))
866
+ _enfocable = ((_native and 'disabled' not in a)
867
+ or (_ti_num is not None and _ti_num >= 0))
868
+ if _ti_num == -1 or _css_hidden:
869
+ _enfocable = False
870
+ # centinela de foco off-screen (patrón modal): un link fuera de vista
871
+ # cuyo id aparece en los scripts (el wiring de focus) NO cuenta — la
872
+ # regla lo define así (mueve el foco al recibirlo). El <script> suele
873
+ # llegar DESPUÉS del link: la decisión se difiere a post-parse
874
+ if (_hidden_aria or self._ah_true_depth > 0) and _enfocable:
875
+ if re.search(r'(top|left)\s*:\s*-\d{3,}', a.get('style') or '', re.I):
876
+ self._ahf_deferred.append((tag, a.get('id')))
877
+ else:
878
+ self.aria_hidden_focusable.append(tag)
879
+ if tag == 'area' and (a.get('href') or '').strip():
880
+ # <area> es void: sin pila de control — se registra directo (el
881
+ # nombre le llega del alt)
882
+ self.controls_raw.append(('area', a, '', [], _hidden))
883
+ if tag in ('h1', 'h2', 'h3', 'h4', 'h5', 'h6'):
884
+ self._heading_level = int(tag[1])
885
+ self._heading_text = []
886
+ self._heading_attrs = a
887
+ self._heading_hidden = _hidden
888
+ self._heading_tag = tag
889
+ elif a.get('role', '').lower() == 'heading' and 'aria-level' in a:
890
+ # role=heading cuenta como encabezado para el nombre (ffd0e9)
891
+ self._heading_level = int(a['aria-level'] or 1)
892
+ self._heading_text = []
893
+ self._heading_attrs = a
894
+ self._heading_hidden = _hidden
895
+ self._heading_tag = tag
896
+ ti = a.get('tabindex')
897
+ if ti and ti.isdigit() and int(ti) > 0:
898
+ self.positive_tabindices.append((tag, int(ti)))
899
+
900
+ def handle_endtag(self, tag):
901
+ if tag not in _VOID:
902
+ self._depth = max(0, self._depth - 1)
903
+ if self._el_stack:
904
+ _etag, _eattrs, _ebuf = self._el_stack.pop()
905
+ if _eattrs.get('id') and _eattrs['id'] in self._role_field_ids:
906
+ self._field_buffers[_eattrs['id']] = _ebuf
907
+ elif (_eattrs.get('role') or '').strip().lower() in _ROLE_FIELDS:
908
+ self._role_field_text.append((_eattrs, ' '.join(_ebuf).strip()))
909
+ if len(self._hidden_stack) > 1:
910
+ self._hidden_stack.pop()
911
+ self._css_hidden_stack.pop()
912
+ if self._ah_true_stack:
913
+ if self._ah_true_stack.pop():
914
+ self._ah_true_depth = max(0, self._ah_true_depth - 1)
915
+ self._open_ids = [(i, d) for (i, d) in self._open_ids if d <= self._depth]
916
+ # controles cierran con SU etiqueta Y a SU profundidad — un <div>
917
+ # anidado dentro de un div[role=button] no cierra el control (React)
918
+ if self._ctrl and self._ctrl[-1]['tag'] == tag \
919
+ and self._depth == self._ctrl[-1].get('depth', 0) - 1:
920
+ self._close_control(tag)
921
+ if tag == 'head':
922
+ self._in_head = False
923
+ elif tag == 'template':
924
+ self._in_template = max(0, self._in_template - 1)
925
+ if tag == 'title':
926
+ self._in_title = False
927
+ self._titles_in_order.append(' '.join(self._title_buf))
928
+ self._title_buf = []
929
+ elif tag == 'script':
930
+ self._in_script = False
931
+ elif tag == 'style':
932
+ self._in_style = False
933
+ elif tag == 'label':
934
+ self._label_depth = max(0, self._label_depth - 1)
935
+ if hasattr(self, '_label_text_current'):
936
+ txt = ' '.join(self._label_text_current).strip()
937
+ lowered = txt.lower()
938
+ if txt and (len(txt) < 2 or re.fullmatch(
939
+ r'(campo|field|input|texto|text|dato|value|entrada|box|caja)[\s\d]*', lowered)):
940
+ self.vague_labels.append(f'"{txt[:30]}"')
941
+ if self._labels_stack and not self._labels_stack.pop():
942
+ self.orphan_labels += 1
943
+ elif tag == 'fieldset':
944
+ self._in_fieldset = False
945
+ elif tag == 'form':
946
+ if self._financial_form and not self._confirm_form:
947
+ self.financial_no_confirm += 1
948
+ elif tag == 'nav':
949
+ self._in_nav = max(0, self._in_nav - 1)
950
+ elif tag == 'li':
951
+ self._li_depth = max(0, self._li_depth - 1)
952
+ elif tag in ('ul', 'ol'):
953
+ self._list_depth = max(0, self._list_depth - 1)
954
+ elif tag in _CONTROLS:
955
+ self._close_control(tag)
956
+ elif tag == 'video':
957
+ self._in_video = False
958
+ elif tag == 'table':
959
+ if self._in_table:
960
+ if not self._th_in_table:
961
+ pass # se contabiliza abajo
962
+ else:
963
+ self.tables_with_th += 1
964
+ self._in_table = False
965
+ elif tag == 'th':
966
+ pass
967
+ elif self._heading_level and tag == getattr(self, '_heading_tag', None):
968
+ # el veredicto de nombre vacío es POST-parse (labelledby resuelto,
969
+ # aria-label tras strip, nombres de imgs internas)
970
+ self.headings_raw.append((self._heading_level, dict(self._heading_attrs or {}),
971
+ ' '.join(self._heading_text).strip(),
972
+ getattr(self, '_heading_hidden', False)))
973
+ self._heading_level = None
974
+
975
+ _RE_CHAR_KEY = re.compile(r'key(?:Code)?\s*===?\s*["\']([a-zA-Z0-9])["\']', re.S)
976
+
977
+ def handle_script_wait(self, data):
978
+ self._scripts_text += ' ' + data
979
+ for m in self._RE_CHAR_KEY.finditer(data):
980
+ if len(self.char_shortcuts) < 5:
981
+ self.char_shortcuts.append(f"key === '{m.group(1)}'")
982
+ if re.search(r'addEventListener\s*\(\s*["\'](?:dragstart|dragover|drop)["\']', data, re.I):
983
+ self.drag_handlers.append('drag listener in script')
984
+ # v3.12: signals that only appear in script bodies
985
+ if 'screen.orientation.lock' in data:
986
+ self.orientation_locks.append('screen.orientation.lock()')
987
+ for _ma in ("addEventListener('deviceorientation'",
988
+ 'addEventListener("deviceorientation"',
989
+ "addEventListener('devicemotion'", 'addEventListener("devicemotion"'):
990
+ if _ma in data:
991
+ self.motions.append(_ma.split('(')[1].strip('\'"'))
992
+
993
+ def handle_style_wait(self, data):
994
+ self._styles_text += ' ' + data
995
+
996
+ def _effective_lang_check(self):
997
+ """El texto recién encontrado hereda el lang del ancestro (o propio)
998
+ más cercano CON lang; si ese lang es inválido, el texto se lee mal.
999
+ Un lang VACÍO no declara idioma: no acusa (de46e4)."""
1000
+ for _k in range(len(self._el_stack) - 1, -1, -1):
1001
+ _lang_v = self._el_stack[_k][1].get('lang')
1002
+ if _lang_v is None:
1003
+ continue
1004
+ _lang_eff = _lang_v.strip()
1005
+ _tag_eff = self._el_stack[_k][0]
1006
+ if _tag_eff == 'html' or _lang_v == '':
1007
+ return # "" no declara idioma; html es 3.1.1, no 3.1.2
1008
+ _prim = _lang_eff.lower().split('-')[0]
1009
+ if _prim not in _LANG_CODES:
1010
+ _mark = f'{_tag_eff} lang="{_lang_eff}"'
1011
+ if _mark not in self.lang_parts_invalid:
1012
+ self.lang_parts_invalid.append(_mark)
1013
+ return
1014
+
1015
+ _RE_RULE = re.compile(r'\.([\w-]+)\s*\{([^}]*)\}')
1016
+ _RE_HIDDEN_STYLE = re.compile(r'clip-path|display\s*:\s*none|visibility\s*:\s*hidden'
1017
+ r'|height\s*:\s*1px|width\s*:\s*1px|opacity\s*:\s*0')
1018
+
1019
+ def _hidden_class_style(self):
1020
+ """¿Algún ancestro abierto del control tiene una clase que el
1021
+ <style> de la página declara como oculta (clip-path, position
1022
+ absolute + 1px, display none, visibility hidden)? Las reglas se
1023
+ cachean: reparsear TODO el css por nodo de texto era cuadrático."""
1024
+ if self._styles_text is not self._styles_cached_src:
1025
+ self._styles_cached_src = self._styles_text
1026
+ self._style_rules = self._RE_RULE.findall(self._styles_text)
1027
+ _open_classes = [c.get('attrs', {}).get('class') for c in self._ctrl]
1028
+ if self._el_stack:
1029
+ _open_classes.append(self._el_stack[-1][1].get('class'))
1030
+ for _cls in filter(None, _open_classes):
1031
+ for _nom in _cls.split():
1032
+ for _selector, _body in self._style_rules:
1033
+ if _nom == _selector and self._RE_HIDDEN_STYLE.search(_body):
1034
+ return True
1035
+ return False
1036
+
1037
+ def handle_data(self, data):
1038
+ in_code = getattr(self, '_in_script', False) or getattr(self, '_in_style', False)
1039
+ if not in_code and not self._in_template:
1040
+ # registro para resolver aria-labelledby a un salto: todo texto
1041
+ # dentro de un elemento con id alimenta su entrada (los ids dentro
1042
+ # de <template> no existen en el DOM)
1043
+ for _id, _d in self._open_ids:
1044
+ # lista por id + join único post-parse: la concatenación por
1045
+ # nodo era cuadrática en páginas con wrappers id grandes
1046
+ self._id_text_parts.setdefault(_id, []).append(data)
1047
+ if data.strip() and not in_code and not self._in_title:
1048
+ self._visible_text.append(data) # prosa visible: ni JS, ni CSS, ni título
1049
+ if self._in_title:
1050
+ self._title_buf.append(data)
1051
+ elif getattr(self, '_in_script', False):
1052
+ self.handle_script_wait(data)
1053
+ elif getattr(self, '_in_style', False):
1054
+ self.handle_style_wait(data)
1055
+ else:
1056
+ # Un texto puede pertenecer a la vez a un enlace dentro de un
1057
+ # encabezado (<h2><a>Guías</a></h2>): alimenta a ambos. El texto
1058
+ # dentro de un subárbol aria-hidden NO es nombre de nada (accname).
1059
+ _hidden_ah = self._hidden_stack[-1][1]
1060
+ if self._el_stack:
1061
+ self._el_stack[-1][2].append(data)
1062
+ if data.strip() and not self._css_hidden_stack[-1] \
1063
+ and not self._hidden_class_style():
1064
+ self._effective_lang_check()
1065
+ if self._label_depth > 0 and hasattr(self, '_label_text_current'):
1066
+ self._label_text_current.append(data)
1067
+ if self._ctrl and not _hidden_ah:
1068
+ self._ctrl[-1]['text'].append(data)
1069
+ if self._ctrl and not self._css_hidden_stack[-1] \
1070
+ and not self._hidden_class_style():
1071
+ # el texto VISIBLE es el renderizado: aria-hidden se ve,
1072
+ # display:none / .visually-hidden (por <style>) no
1073
+ self._ctrl[-1]['text_visible'].append(data)
1074
+ if self._heading_level is not None and not _hidden_ah:
1075
+ self._heading_text.append(data)
1076
+ m = _SENSORIAL.search(data)
1077
+ if m and len(self.sensory) < 6:
1078
+ self.sensory.append(m.group(0).strip()[:60])
1079
+
1080
+
1081
+
1082
+ # Señales renombradas en 5.11.0 (superficie pública 100% inglesa).
1083
+ # Los informes y ledgers guardados antes del rename siguen siendo válidos:
1084
+ # toda ingesta pasa por normalize_signal().
1085
+ SIGNAL_ALIASES = {
1086
+ 'imgs_alt': 'img_no_alt',
1087
+ 'descarga_error': 'fetch_error',
1088
+ 'lang_partes': 'element_lang_invalid',
1089
+ 'lang_region_invalida': 'lang_region_invalid',
1090
+ 'docx_falsos_encabezados': 'docx_fake_headings',
1091
+ 'docx_sin_idioma': 'docx_no_lang',
1092
+ 'docx_sin_tabla_header': 'docx_table_no_header',
1093
+ }
1094
+
1095
+
1096
+ def normalize_signal(signal):
1097
+ """Nombre canónico de una señal (acepta las formas españolas previas a 5.11.0)."""
1098
+ return SIGNAL_ALIASES.get(signal, signal)
1099
+
1100
+
1101
+ def normalize_report(report):
1102
+ """Informe con señales normalizadas (no muta el original)."""
1103
+ if not isinstance(report, dict):
1104
+ return report
1105
+ findings = report.get('findings')
1106
+ if not findings:
1107
+ return report
1108
+ out = dict(report)
1109
+ out['findings'] = [dict(h, signal=normalize_signal(h.get('signal', '')))
1110
+ for h in findings]
1111
+ return out
1112
+
1113
+
1114
+ def compute_score(findings):
1115
+ """Puntuación 0-100: penalización ponderada por hallazgo (alta 12, media 6, baja 2)."""
1116
+ weights = {'high': 12, 'medium': 6, 'low': 2}
1117
+ penal = sum(weights[h['severity']] for h in findings)
1118
+ return max(0, 100 - penal)
1119
+
1120
+
1121
+ _VOCAL = re.compile(r'[aeiouyáéíóúàèìòùäëïöü]+', re.I)
1122
+
1123
+
1124
+ def _syllables(word):
1125
+ """Heurística de sílabas por grupos vocálicos (suficiente para índices)."""
1126
+ return max(1, len(_VOCAL.findall(word)))
1127
+
1128
+
1129
+ def _reading_level(text, lang='en'):
1130
+ """Flesch Reading Ease (en) / Fernández-Huerta (es) — 3.1.5 cognitivo.
1131
+
1132
+ Informativo (AAA): se reporta, no penaliza el score. 100 = muy fácil;
1133
+ <50 = difícil (nivel universitario)."""
1134
+ clean = re.sub(r'<[^>]+>', ' ', text)
1135
+ words = re.findall(r"[\wáéíóúñü'-]{2,}", clean, re.UNICODE)
1136
+ phrases = [f for f in re.split(r'[.!?;:]+', clean) if f.strip()]
1137
+ if len(words) < 40 or not phrases:
1138
+ return None # muestra insuficiente: no inventar un índice
1139
+ sil = sum(_syllables(w) for w in words)
1140
+ ppf = len(words) / len(phrases) # palabras por frase
1141
+ spf = sil / len(words) * 100 # sílabas por 100 palabras
1142
+ if lang == 'es':
1143
+ # Fernández-Huerta: L = 206.84 − 0.60·P − 1.02·F
1144
+ # (P = sílabas por 100 palabras, F = palabras por frase)
1145
+ index = 206.84 - 0.60 * spf - 1.02 * ppf
1146
+ scale = ('muy fácil', 'fácil', 'estándar', 'difícil', 'muy difícil')
1147
+ else:
1148
+ index = 206.835 - 1.015 * ppf - 84.6 * (sil / len(words))
1149
+ scale = ('very easy', 'easy', 'standard', 'difficult', 'very difficult')
1150
+ index = round(max(0, min(100, index)), 1)
1151
+ level = scale[0] if index >= 90 else scale[1] if index >= 70 else \
1152
+ scale[2] if index >= 50 else scale[3] if index >= 30 else scale[4]
1153
+ return {'index': index, 'level': level, 'scale': 'fernandez-huerta' if lang == 'es' else 'flesch-reading-ease',
1154
+ 'words': len(words), 'sentences': len(phrases),
1155
+ 'note': 'informational (3.1.5 is level AAA): reported, never scored'}
1156
+
1157
+
1158
+ def _not_measured(lang='en'):
1159
+ """Criterios que el pase estático NO mide: renderizado obligatorio.
1160
+
1161
+ Honradez del informe: un 100 estático nunca debe leerse como
1162
+ "contraste bien" (la limitación que la crítica externa destapó:
1163
+ .btn-primary{background:var(--x)} es invisible para el HTML puro)."""
1164
+ from .a11ycrit import RENDERED_ONLY, _C
1165
+ reason_txt = (T.get(lang, T['es'])).get('rendered_reason') or T['es']['rendered_reason']
1166
+ return [{
1167
+ 'criterion': f"{c} {_C[c][1]['en'][0]}",
1168
+ 'reason': reason_txt,
1169
+ } for c in sorted(RENDERED_ONLY)]
1170
+
1171
+
1172
+ def audit_html(html_text, url='(html)', lang='en'):
1173
+ """Analiza una cadena HTML y devuelve el informe de hallazgos (es/en)."""
1174
+ p = _Auditor()
1175
+ try:
1176
+ p.feed(html_text[:MAX_HTML])
1177
+ p.close()
1178
+ except Exception as e: # noqa: BLE001
1179
+ return {'error': f'unparseable HTML: {e}'}
1180
+
1181
+ # 1.3.1: grupos de radio (name compartido, ≥2) sin fieldset
1182
+ for nm, count in p._radio_group.items():
1183
+ if count >= 2 and not p._radio_in_fieldset.get(nm, False):
1184
+ p.missing_fieldsets += 1
1185
+
1186
+ # id→texto resuelto de una vez (partes acumuladas en streaming)
1187
+ for _id, _parts in p._id_text_parts.items():
1188
+ p._id_texts[_id] = ' '.join(_parts).strip()
1189
+
1190
+ # centinela off-screen: decidir con los scripts YA completos (el <script>
1191
+ # llega después del link en el documento) — sin id o sin wiring = fallo
1192
+ for _tag, _tid in p._ahf_deferred:
1193
+ if not _tid or _tid not in p._scripts_text:
1194
+ p.aria_hidden_focusable.append(_tag)
1195
+
1196
+ # ── decisiones de nombre POST-parse ─────────────────────────────────────
1197
+ # Los ids de un aria-labelledby pueden declararse DESPUÉS del elemento que
1198
+ # lo referencia: la resolución se hace con el registro completo id→texto.
1199
+ # Nombre accesible práctico (orden accname): aria-label (no vacío tras
1200
+ # strip) → aria-labelledby resuelto → texto/alt → title.
1201
+ def _name_sources(a):
1202
+ lb = ' '.join((p._id_texts.get(i, '') or '').strip()
1203
+ for i in (a.get('aria-labelledby') or '').split()).strip()
1204
+ return lb, (a.get('aria-label') or '').strip(), (a.get('title') or '').strip()
1205
+
1206
+ for a, hidden in p.imgs_all:
1207
+ # presentación/none = decorativo declarado; hidden (aria-hidden, hidden,
1208
+ # display:none) queda fuera de 23a2a8; alt="" exacto = decorativo.
1209
+ # PERO un img presentacional ENFOCABLE (tabindex ≥ 0) sigue necesitando
1210
+ # nombre: sigue en la navegación por tab (ACT 23a2a8)
1211
+ _ti = (a.get('tabindex') or '').strip()
1212
+ _enfocable_img = _ti.isdigit() and int(_ti) >= 0
1213
+ if hidden or ((a.get('role') or '').strip().lower() in ('presentation', 'none')
1214
+ and not _enfocable_img):
1215
+ continue
1216
+ if 'alt' in a and (a['alt'] or '').strip():
1217
+ continue
1218
+ if 'alt' in a and (a['alt'] or '') == '':
1219
+ continue
1220
+ lb, al, ti = _name_sources(a)
1221
+ if not (al or lb or ti):
1222
+ p.imgs_no_alt.append((a.get('src') or a.get('aria-label') or '(role=img)')[:100])
1223
+ for a, hidden in p.inputs_image:
1224
+ if hidden:
1225
+ continue
1226
+ lb, al, ti = _name_sources(a)
1227
+ if not ((a.get('alt') or '').strip() or al or lb or ti):
1228
+ p.input_img_no_alt += 1
1229
+ for a, hidden in p.iframes_all:
1230
+ # tabindex=-1 saca el iframe del orden de tab: la regla lo excluye;
1231
+ # role=none/presentation le quita la semántica de iframe (ACT cae760)
1232
+ if hidden or (a.get('tabindex') or '').strip() == '-1' \
1233
+ or (a.get('role') or '').strip().lower() in ('none', 'presentation'):
1234
+ continue
1235
+ lb, al, ti = _name_sources(a)
1236
+ if not ((a.get('title') or '').strip() or al or lb):
1237
+ p.iframes_no_title.append((a.get('src') or '')[:100])
1238
+ for kind, a, text, img_attrs, hidden in p.controls_raw:
1239
+ # input submit/reset/button llevan valor por defecto del navegador;
1240
+ # disabled/hidden quedan fuera. El value de un <button> NO es su
1241
+ # nombre (solo lo es en inputs) ni role=none exime (ACT 97a4e1)
1242
+ if hidden or 'disabled' in a or kind.startswith('input:'):
1243
+ continue
1244
+ lb, al, ti = _name_sources(a)
1245
+ _img_names = []
1246
+ for ia in img_attrs:
1247
+ ilb, ial, iti = _name_sources(ia)
1248
+ _img_names.append((ia.get('alt') or '').strip() or ial or ilb or iti)
1249
+ if not (text.strip() or al or lb or ti
1250
+ or ' '.join(x for x in _img_names if x).strip()
1251
+ or (a.get('alt') or '').strip()):
1252
+ p.controls_by_kind.setdefault(kind, []).append(a)
1253
+ for level, a, text, hidden in p.headings_raw:
1254
+ if hidden:
1255
+ continue
1256
+ lb, al, _ti = _name_sources(a)
1257
+ heading_name = text.strip() or al or lb
1258
+ if not heading_name:
1259
+ p.empty_h += 1
1260
+ else:
1261
+ p.headings.append((level, heading_name[:80]))
1262
+ if level == 1:
1263
+ p.h1s += 1
1264
+ lowered = heading_name.lower().strip()
1265
+ if len(heading_name) < 4 or len(heading_name) > 120:
1266
+ p.vague_headings.append(f'h{level} "{heading_name[:40]}"')
1267
+ elif re.fullmatch(r'(secci[oó]n|section|chapter|cap[ií]tulo|m[aá]s|more|info|informaci[oó]n|information|details|detalle|click|ver|see|leer|read|continue|seguir)[\s\d.]*', lowered):
1268
+ p.vague_headings.append(f'h{level} "{heading_name[:40]}"')
1269
+ elif re.fullmatch(r'[\d.\s]+', lowered):
1270
+ p.vague_headings.append(f'h{level} "{heading_name[:40]}"')
1271
+ # texto directo de campos por rol (name-from-content): buffer salvado al
1272
+ # cerrar el elemento, recuperado por id
1273
+ _direct_text = {}
1274
+ for _tid, _buf in p._field_buffers.items():
1275
+ _direct_text[_tid] = ' '.join(_buf).strip()
1276
+ for tag, kind, a, en_label, hidden in p.fields_raw:
1277
+ if hidden or (a.get('role') or '').strip().lower() in ('none', 'presentation'):
1278
+ continue
1279
+ lb, al, ti = _name_sources(a)
1280
+ _is_labelable = tag in ('input', 'select', 'textarea', 'meter', 'progress', 'output')
1281
+ # name-from-content SOLO aplica a los roles que toman nombre del
1282
+ # contenido (checkbox, radio, switch, option…): un textbox NO — su
1283
+ # contenido no es su etiqueta (e086e5)
1284
+ _NAME_FROM_CONTENT = {'checkbox', 'radio', 'switch', 'option', 'menuitem',
1285
+ 'menuitemcheckbox', 'menuitemradio', 'tab', 'treeitem'}
1286
+ _content_name = ''
1287
+ if kind.startswith('role:') and kind.split(':', 1)[1] in _NAME_FROM_CONTENT:
1288
+ _content_name = _direct_text.get(a.get('id'), '') or next(
1289
+ (_txt for _fa, _txt in p._role_field_text
1290
+ if _fa.get('role') == a.get('role') and not a.get('id') and not _fa.get('id')),
1291
+ '')
1292
+ _placeholder = (a.get('placeholder') or '').strip() if tag != 'select' else ''
1293
+ _has_real_name = bool(al or lb or ti
1294
+ or (en_label and _is_labelable)
1295
+ or (_is_labelable and a.get('id') and a['id'] in p._labels_for)
1296
+ or _content_name)
1297
+ if not (_has_real_name or _placeholder):
1298
+ p.fields_no_label.append((kind or tag, (a.get('name') or '')[:60], a.get('id')))
1299
+ for tag, a, en_label, hidden in p._placeholder_candidates:
1300
+ # placeholder como ÚNICO nombre: revisión 3.3.2 (el accname del
1301
+ # navegador lo cuenta, pero como etiqueta es débil — se declara)
1302
+ if hidden:
1303
+ continue
1304
+ lb, al, ti = _name_sources(a)
1305
+ if not (lb or al or ti or en_label
1306
+ or (a.get('id') and a['id'] in p._labels_for)):
1307
+ p.placeholder_only.append(f'{tag}[placeholder="{(a.get("placeholder") or "")[:30]}"]')
1308
+
1309
+ findings = []
1310
+
1311
+ def add(severity, code, key_msg, **fmt):
1312
+ h = {'severity': severity, 'criterion': _crit(lang, code), 'signal': key_msg,
1313
+ 'issue': _t(lang, key_msg, n=fmt.get('n')).format(**fmt)}
1314
+ h['remediation'] = _t(lang, key_msg + '_rem').format(**fmt)
1315
+ findings.append(h)
1316
+
1317
+ def add_ej(severity, code, key_msg, examples, **fmt):
1318
+ add(severity, code, key_msg, **fmt)
1319
+ findings[-1]['examples'] = examples[:5]
1320
+
1321
+ if p.imgs_no_alt:
1322
+ add_ej('high', '1.1.1', 'img_no_alt', p.imgs_no_alt, n=len(p.imgs_no_alt))
1323
+ if p.input_img_no_alt:
1324
+ add('high', '1.1.1', 'input_img_alt', n=p.input_img_no_alt)
1325
+ for tag, controls in p.controls_by_kind.items():
1326
+ add('high', '4.1.2', 'ctrl_name', n=len(controls), tag=tag)
1327
+ if p.aria_hidden_focusable:
1328
+ add('high', '4.1.2', 'aria_hidden_focusable',
1329
+ n=len(p.aria_hidden_focusable), tag=p.aria_hidden_focusable[0])
1330
+ if p.fields_no_label:
1331
+ add_ej('high', '3.3.2', 'field_label',
1332
+ [f'{t} name={n or "(no name)"}' for t, n, _i in p.fields_no_label],
1333
+ n=len(p.fields_no_label))
1334
+ if p.stray_clicks:
1335
+ add('high', '2.1.1', 'click_nonfocusable',
1336
+ n=len(p.stray_clicks), tag=p.stray_clicks[0])
1337
+ if p.orphan_labels:
1338
+ add('low', '3.3.2', 'label_orphan', n=p.orphan_labels)
1339
+ if p._bad_list:
1340
+ add('medium', '1.3.1', 'list_structure', n=p._bad_list)
1341
+ if p.root_tag in ('svg', 'math'):
1342
+ # documento no-HTML (svg/math como raíz): las señales de página
1343
+ # (idioma, título, bypass, encabezados) no aplican (ACT b5c3f8/3e12e1)
1344
+ pass
1345
+ elif not p.lang:
1346
+ add('medium', '3.1.1', 'lang_missing')
1347
+ elif p.lang.lower().split('-')[0] not in _LANG_CODES:
1348
+ add('medium', '3.1.1', 'lang_invalid', lang=p.lang)
1349
+ elif p.lang_region_invalid:
1350
+ add('low', '3.1.1', 'lang_region_invalid', l=p.lang_region_invalid)
1351
+ # el PRIMER <title> del documento decide (modelo ACT 2779a5)
1352
+ p.title = p._titles_in_order[0] if p._titles_in_order else ''
1353
+ t_clean = (p.title or '').strip().lower()
1354
+ if not t_clean:
1355
+ add('medium', '2.4.2', 'title_missing')
1356
+ elif t_clean in ('untitled', 'documento', 'documento sin título', 'sin título',
1357
+ 'home', 'inicio', 'page 1', 'new page', 'página 1',
1358
+ 'untitled document', 'sin nombre', 'document'):
1359
+ add('low', '2.4.2', 'title_generic', t=t_clean)
1360
+ if p.iframes_no_title:
1361
+ add_ej('medium', '4.1.2', 'iframe_title', p.iframes_no_title, n=len(p.iframes_no_title))
1362
+ if p.videos and p.videos_with_captions < p.videos:
1363
+ add('medium', '1.2.2', 'video_captions', n=p.videos - p.videos_with_captions)
1364
+ if p.viewport:
1365
+ # valores inválidos también blocksn (ACT b4f0c3): user-scalable ha de
1366
+ # ser yes/true o numérico ≥ 1; maximum-scale numérico — si no parsea,
1367
+ # el zoom queda sin garantía y se acusa
1368
+ m_us = re.search(r'user-scalable\s*=\s*([\w.-]+)', p.viewport, re.I)
1369
+ if m_us:
1370
+ v = m_us.group(1).lower()
1371
+ try:
1372
+ allows = float(v) >= 1
1373
+ except ValueError:
1374
+ allows = v in ('yes', 'true')
1375
+ if not allows:
1376
+ add('high', '1.4.4', 'zoom_no')
1377
+ m_ms = re.search(r'maximum-scale\s*=\s*([\w.-]+)', p.viewport, re.I)
1378
+ if m_ms:
1379
+ _v_ms = m_ms.group(1)
1380
+ try:
1381
+ blocks = 0 <= float(_v_ms) < 2 # negativo: ignorado por el parser
1382
+ except ValueError:
1383
+ # basura blocks (ACT), salvo las palabras clave del viewport
1384
+ blocks = _v_ms.lower() not in ('device-width', 'device-height',
1385
+ 'initial-scale', 'width', 'height')
1386
+ if blocks:
1387
+ add('medium', '1.4.4', 'zoom_max', v=_v_ms)
1388
+ # meta refresh (2.2.1/ACT bc659a): gana el PRIMER meta que parsea según
1389
+ # los pasos del HTML (dígitos + ; o , o fin — un «0: url» con dos puntos
1390
+ # NO parsea y se salta); 0 segundos = redirección inmediata y > 72000
1391
+ # (20 h) quedan EXENTOS
1392
+ _mr = None
1393
+ for _content in p.meta_refreshes or ([p.meta_refresh] if p.meta_refresh else []):
1394
+ _m = re.match(r'\s*(\d+)\s*(?:[;,]|$)', _content or '')
1395
+ if _m:
1396
+ _mr = int(_m.group(1))
1397
+ break
1398
+ if _mr is not None and 0 < _mr <= 72000:
1399
+ add('medium', '2.2.1', 'meta_refresh', v=_mr)
1400
+ if p.positive_tabindices:
1401
+ add_ej('medium', '2.4.3', 'tabindex_pos',
1402
+ [f'{t}[tabindex={i}]' for t, i in p.positive_tabindices],
1403
+ n=len(p.positive_tabindices))
1404
+ # un toggle cuenta como mecanismo de abatido SOLO si la función que
1405
+ # invoca colapsa de verdad (su cuerpo, en el script de la página, toca
1406
+ # `display`): mover off-screen o aria-hidden no colapsa el bloque (3e12e1)
1407
+ _nav_collapsible = False
1408
+ for _oc in p._toggle_onclicks:
1409
+ for _nid in p._nav_ids:
1410
+ if _nid not in _oc:
1411
+ continue
1412
+ _m = re.match(r'\s*(\w+)\s*\(', _oc)
1413
+ if not _m:
1414
+ continue
1415
+ if _nav_collapsible:
1416
+ break
1417
+ _fn = re.search(r'function\s+' + _m.group(1) + r'\s*\([^)]*\)\s*\{(.{0,180})',
1418
+ p._scripts_text, re.S)
1419
+ if _fn:
1420
+ _nav_collapsible = 'display' in _fn.group(1)
1421
+ else:
1422
+ # función en JS externo (no descargable): el NOMBRE decide —
1423
+ # hide/collapse/display colapsan; visibility/aria no (3e12e1)
1424
+ _nom = _m.group(1).lower()
1425
+ _nav_collapsible = not re.search(r'visib|aria', _nom) \
1426
+ and bool(re.search(r'hide|hidden|collapse|display', _nom))
1427
+ if p.root_tag not in ('svg', 'math') and not (p.hay_main or p.hay_skip or _nav_collapsible):
1428
+ add('medium', '2.4.1', 'no_bypass')
1429
+
1430
+ levels = [n for n, _ in p.headings]
1431
+ if levels:
1432
+ if p.h1s == 0:
1433
+ add('medium', '1.3.1', 'no_h1')
1434
+ elif p.h1s > 1:
1435
+ add('low', '1.3.1', 'multi_h1', n=p.h1s)
1436
+ prev = 0
1437
+ jumps = []
1438
+ for n in levels:
1439
+ if prev and n > prev + 1:
1440
+ jumps.append(f'h{prev}→h{n}')
1441
+ prev = n
1442
+ if jumps:
1443
+ add('low', '1.3.1', 'heading_skips', skips=', '.join(jumps[:5]))
1444
+ elif p.root_tag not in ('svg', 'math'):
1445
+ add('medium', '1.3.1', 'no_headings')
1446
+ if p.empty_h:
1447
+ add('low', '1.3.1', 'empty_heading', n=p.empty_h)
1448
+ if p.tables and p.tables_with_th < p.tables:
1449
+ add('medium', '1.3.1', 'table_no_th', n=p.tables - p.tables_with_th)
1450
+ if p.blank_no_warning:
1451
+ add('low', '3.2.5', 'blank_no_warning', n=p.blank_no_warning)
1452
+ dups = sum(1 for _c, k in p.ids.items() if k > 1)
1453
+ if dups:
1454
+ add('low', '4.1.2', 'dup_ids', n=dups)
1455
+
1456
+ # --- v3.1: validez ARIA, autocomplete, enlaces, landmarks, accesskey ---
1457
+ broken_refs = [f'{attr}="#{ref}"' for attr, ref in p.aria_refs if ref not in p.ids]
1458
+ if broken_refs:
1459
+ add_ej('high', '4.1.2', 'aria_ref_missing', broken_refs, n=len(broken_refs),
1460
+ example=broken_refs[0])
1461
+ if p.aria_values:
1462
+ _labels = {'es': {'bool': 'true/false', 'int': 'entero', 'num': 'número', 'tokens': 'valores'},
1463
+ 'en': {'bool': 'true/false', 'int': 'integer', 'num': 'number', 'tokens': 'one of'}}
1464
+ axes = [f"{v['attr']}=\"{v['val']}\" ({v['valid_tokens'] if v['type'] == 'tokens' else _labels[lang][v['type']]})"
1465
+ for v in p.aria_values]
1466
+ add_ej('medium', '4.1.2', 'aria_value_invalid', axes,
1467
+ n=len(p.aria_values), example=', '.join(axes[:4]))
1468
+ if p.unknown_roles:
1469
+ add_ej('medium', '4.1.2', 'role_unknown',
1470
+ sorted(set(p.unknown_roles)), n=len(p.unknown_roles),
1471
+ example=', '.join(f'"{r}"' for r in sorted(set(p.unknown_roles))[:4]))
1472
+ if p.roles_without_state:
1473
+ add_ej('medium', '4.1.2', 'role_required_attr', p.roles_without_state,
1474
+ n=len(p.roles_without_state), example=', '.join(p.roles_without_state[:4]))
1475
+ if p.missing_autocomplete:
1476
+ add_ej('medium', '1.3.5', 'autocomplete', p.missing_autocomplete,
1477
+ n=len(p.missing_autocomplete), example=', '.join(p.missing_autocomplete[:4]))
1478
+ if p.autocomplete_invalid:
1479
+ add_ej('medium', '1.3.5', 'autocomplete_invalid', p.autocomplete_invalid,
1480
+ n=len(p.autocomplete_invalid), example=', '.join(p.autocomplete_invalid[:4]))
1481
+ if p.media_autoplay:
1482
+ add('medium', '1.4.2', 'video_autoplay', n=p.media_autoplay)
1483
+ if p.label_no_name:
1484
+ _ln = p.label_no_name[0]
1485
+ add_ej('medium', '2.5.3', 'label_in_name',
1486
+ [f'«{t}» vs aria-label «{al}»' for t, al in p.label_no_name],
1487
+ n=len(p.label_no_name), example=f'{_ln[0]} ≠ {_ln[1]}')
1488
+ if p.lang_parts_invalid:
1489
+ add_ej('medium', '3.1.2', 'element_lang_invalid', p.lang_parts_invalid,
1490
+ n=len(p.lang_parts_invalid), example=', '.join(p.lang_parts_invalid[:4]))
1491
+ if p.down_events:
1492
+ add_ej('medium', '2.5.2', 'down_event', p.down_events,
1493
+ n=len(p.down_events), example=', '.join(p.down_events[:4]))
1494
+ # forms deep-dive
1495
+ if p.placeholder_only:
1496
+ add_ej('high', '3.3.2', 'placeholder_only', p.placeholder_only,
1497
+ n=len(p.placeholder_only), example=', '.join(p.placeholder_only[:3]))
1498
+ if p.required_no_indication:
1499
+ add_ej('low', '3.3.2', 'required_no_indication', p.required_no_indication,
1500
+ n=len(p.required_no_indication), example=', '.join(p.required_no_indication[:3]))
1501
+ if p.missing_fieldsets:
1502
+ add('medium', '1.3.1', 'fieldset_missing', n=p.missing_fieldsets)
1503
+ if p.vague_labels:
1504
+ add_ej('low', '2.4.6', 'label_vague', p.vague_labels,
1505
+ n=len(p.vague_labels), example=', '.join(p.vague_labels[:3]))
1506
+ if p.financial_no_confirm:
1507
+ add('medium', '3.3.4', 'financial_no_confirm', n=p.financial_no_confirm)
1508
+ if p.vague_headings:
1509
+ add_ej('low', '2.4.6', 'heading_quality', p.vague_headings,
1510
+ n=len(p.vague_headings), example=', '.join(p.vague_headings[:3]))
1511
+ if p.char_shortcuts:
1512
+ add_ej('low', '2.1.4', 'char_shortcut', p.char_shortcuts,
1513
+ n=len(p.char_shortcuts), example=', '.join(p.char_shortcuts[:3]))
1514
+ if p.drag_handlers:
1515
+ add_ej('low', '2.5.7', 'drag_no_alt', p.drag_handlers,
1516
+ n=len(p.drag_handlers), example=', '.join(p.drag_handlers[:3]))
1517
+ # 4.1.3: solo si hay evidencia de dinamismo (scripts con eventos, forms, fetch/XHR)
1518
+ dynamic = bool(p.stray_clicks or p._scripts_text.strip() or p.char_shortcuts or p.drag_handlers or p.fields_no_label)
1519
+ if dynamic and p.status_regions == 0:
1520
+ add('medium', '4.1.3', 'no_status_regions')
1521
+ if p.images_of_text:
1522
+ add_ej('low', '1.4.5', 'images_of_text', p.images_of_text,
1523
+ n=len(p.images_of_text), ej2='')
1524
+ if p.captchas:
1525
+ add_ej('medium', '3.3.8', 'captcha', p.captchas,
1526
+ n=len(p.captchas), example=', '.join(p.captchas[:2]))
1527
+ # v3.12: partial signals on previously manual-only criteria
1528
+ if p.mobiles:
1529
+ add_ej('low', '2.2.2', 'motion_moving', p.mobiles,
1530
+ n=len(p.mobiles), example=', '.join(p.mobiles[:3]))
1531
+ if p.gestures:
1532
+ add_ej('low', '2.5.1', 'gesture_no_click', p.gestures,
1533
+ n=len(p.gestures), example=', '.join(p.gestures[:3]))
1534
+ if p.motions:
1535
+ add_ej('low', '2.5.4', 'motion_actuation', p.motions,
1536
+ n=len(p.motions), example=', '.join(p.motions[:3]))
1537
+ if p.orientation_locks:
1538
+ add_ej('low', '1.3.4', 'orientation_lock', p.orientation_locks,
1539
+ n=len(p.orientation_locks), example=', '.join(p.orientation_locks[:2]))
1540
+ if p.videos and p.videos_descriptions < p.videos:
1541
+ add('low', '1.2.3', 'audio_desc_missing', n=p.videos - p.videos_descriptions)
1542
+ if p.sensory:
1543
+ add('low', '1.3.3', 'sensory_text', example='; '.join(p.sensory[:2])[:70])
1544
+ lm_dups = [f'{lm} ×{t[1]}' for lm, t in p.landmarks.items()
1545
+ if t[1] > 1 and t[0] == t[1]]
1546
+ if lm_dups:
1547
+ add('low', '1.3.1', 'landmark_dup', n=len(lm_dups), example=', '.join(lm_dups[:4]))
1548
+ if p.generics >= 2: # un enlace genérico único suele desambiguarse por contexto
1549
+ gen = [f'«{k}»' for k in p.links if k in _GENERIC_TEXT][:4]
1550
+ add('low', '2.4.4', 'generic_link', n=p.generics, example=', '.join(gen))
1551
+ same = sum(1 for _k, hrefs in p.links.items() if len(hrefs) > 1)
1552
+ if same:
1553
+ add('low', '2.4.4', 'same_name_links', n=same)
1554
+ ak_dups = [f'"{k}" ×{v}' for k, v in p.accesskeys.items() if v > 1]
1555
+ if ak_dups:
1556
+ add('low', '2.1.1', 'accesskey_dup', n=len(ak_dups), example=', '.join(ak_dups[:4]))
1557
+ if p.labels_for_dups:
1558
+ add('low', '3.3.2', 'multi_label', n=len(p.labels_for_dups))
1559
+
1560
+ severity_order = {'high': 0, 'medium': 1, 'low': 2}
1561
+ findings.sort(key=lambda h: severity_order[h['severity']])
1562
+ summary = {s: sum(1 for h in findings if h['severity'] == s)
1563
+ for s in ('high', 'medium', 'low')}
1564
+ page_lang = (p.lang or '').split('-')[0].lower() if getattr(p, 'lang', None) else ''
1565
+ reading = _reading_level(' '.join(p._visible_text),
1566
+ page_lang if page_lang in ('es', 'en') else lang)
1567
+
1568
+ res = {
1569
+ 'mode': 'static',
1570
+ 'url': url,
1571
+ 'reading_level': reading,
1572
+ 'score': compute_score(findings),
1573
+ 'score_note': _t(lang, 'score_note'),
1574
+ 'not_measured': _not_measured(lang),
1575
+ 'elements_scanned': p.elements,
1576
+ 'summary': summary,
1577
+ 'findings': findings,
1578
+ 'limits': _t(lang, 'limits'),
1579
+ }
1580
+ # overlays detectados: dato del informe (diligencia de compra), nunca un
1581
+ # hallazgo — no hay criterio WCAG que anclar y el score no se toca
1582
+ overlays, _seen = [], set()
1583
+ for _src in p._script_srcs:
1584
+ _low = _src.lower()
1585
+ for _vendor, _pats in _OVERLAY_WIDGETS:
1586
+ if _vendor not in _seen and any(_p in _low for _p in _pats):
1587
+ _seen.add(_vendor)
1588
+ overlays.append({'vendor': _vendor, 'evidence': _src[:180]})
1589
+ if overlays:
1590
+ res['overlay_widgets'] = overlays
1591
+ res['overlay_widgets_note'] = _t(lang, 'overlay_widgets_note')
1592
+ return res
1593
+
1594
+
1595
+ # ── redirect policy hook ───────────────────────────────────────────────────
1596
+ # urlopen follows 3xx (up to 10 hops) to ANY host without asking: every hop
1597
+ # is a NEW destination nobody validated. Callers that audit untrusted URLs
1598
+ # can inject a per-hop validator here (returns False → the redirect is not
1599
+ # followed). Without injection, behavior is unchanged.
1600
+ validate_redirect = None # callable(url) -> bool
1601
+
1602
+
1603
+ class _CheckedRedirect(urllib.request.HTTPRedirectHandler):
1604
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
1605
+ if validate_redirect is not None and not validate_redirect(newurl):
1606
+ raise ValueError(f'redirect to a disallowed destination: {newurl[:96]}')
1607
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
1608
+
1609
+
1610
+ _OPENER = urllib.request.build_opener(_CheckedRedirect)
1611
+
1612
+
1613
+ def _fetch(url, timeout=30, truncate_at=None, accept_ct=()):
1614
+ scheme = url.split(':', 1)[0].lower() if ':' in url else ''
1615
+ if scheme not in ('http', 'https'):
1616
+ # política única para TODAS las rutas de descarga (audit_url la
1617
+ # comprobaba; audit_site y el crawl pasaban por aquí sin frontera)
1618
+ return {'error': f'scheme not allowed: {scheme or url[:24]!r} (http/https only)'}
1619
+ req = urllib.request.Request(url, headers={
1620
+ 'User-Agent': 'Mozilla/5.0 (compatible; a11y-toolkit/3.2; WCAG audit)',
1621
+ 'Accept': 'text/html,application/xhtml+xml',
1622
+ 'Accept-Encoding': 'gzip',
1623
+ })
1624
+ with _OPENER.open(req, timeout=timeout) as r:
1625
+ ceiling = truncate_at or MAX_HTML
1626
+ # TOTAL-CLOCK reading: the socket timeout is per-operation and a server
1627
+ # dribbling one byte per operation reset it forever. Read in chunks
1628
+ # with a global deadline: what arrived is enough to audit (partial).
1629
+ import time
1630
+ read_deadline = time.monotonic() + max(timeout, 5)
1631
+ try:
1632
+ r.fp.raw._sock.settimeout(min(timeout, 5))
1633
+ except (AttributeError, OSError):
1634
+ pass
1635
+ data = b''
1636
+ while len(data) < ceiling + 1:
1637
+ if time.monotonic() >= read_deadline:
1638
+ break # partial: what arrived suffices to audit
1639
+ chunk = r.read(min(65536, ceiling + 1 - len(data)))
1640
+ if not chunk:
1641
+ break
1642
+ data += chunk
1643
+ if len(data) > ceiling and truncate_at is None:
1644
+ raise ValueError(f'HTML > {MAX_HTML // 1000000} MB, demasiado grande')
1645
+ if (r.headers.get('Content-Encoding') or '').lower() == 'gzip' or data[:2] == b'\x1f\x8b':
1646
+ import zlib
1647
+ d = zlib.decompressobj(16 + zlib.MAX_WBITS)
1648
+ data = d.decompress(data, ceiling) # techo duro también al descomprimir
1649
+ if d.unconsumed_tail:
1650
+ data = data[:ceiling] # bomba gzip: truncado, no OOM
1651
+ ctype = (r.headers.get('Content-Type') or '').lower()
1652
+ base = ctype.split(';')[0].strip()
1653
+ extra_ok = any(base == p or base.startswith(p + '/') for p in accept_ct)
1654
+ if ctype and not extra_ok and 'html' not in ctype and 'xml' not in ctype and base:
1655
+ raise ValueError(f'la URL no devuelve HTML (Content-Type: {base})')
1656
+ # the HEADER charset wins over body sniffing (HTTP has priority over
1657
+ # <meta>): a server declaring iso-8859-1 without a meta tag otherwise
1658
+ # produces U+FFFD inside findings
1659
+ charset = None
1660
+ m_ct = re.search(r'charset=["\']?([\w-]+)', (r.headers.get('Content-Type') or '').lower(), re.I)
1661
+ if m_ct:
1662
+ charset = m_ct.group(1)
1663
+ if not charset:
1664
+ m = re.search(rb'charset=["\']?([\w-]+)', data[:2048])
1665
+ if m:
1666
+ charset = m.group(1).decode('ascii', 'ignore')
1667
+ try:
1668
+ return data.decode(charset or 'utf-8', 'replace')
1669
+ except LookupError:
1670
+ return data.decode('utf-8', 'replace')
1671
+
1672
+
1673
+ _T_SCHEME = {
1674
+ 'es': 'solo se auditan URLs http/https; para HTML local usa --file / el argumento html',
1675
+ 'en': 'only http/https URLs can be audited; for local HTML use --file / the html argument',
1676
+ }
1677
+
1678
+
1679
+ def audit_url(url, timeout=30, lang='en'):
1680
+ if url.split(':')[0].lower() not in ('http', 'https'):
1681
+ return {'error': _T_SCHEME.get(lang, _T_SCHEME['es'])}
1682
+ try:
1683
+ html_text = _fetch(url, timeout=timeout)
1684
+ except ValueError as e:
1685
+ return {'error': str(e)}
1686
+ except Exception as e: # noqa: BLE001
1687
+ return {'error': _t(lang, 'fetch_error').format(e=e)}
1688
+ return audit_html(html_text, url, lang=lang)
1689
+
1690
+
1691
+ _LOC = re.compile(r'<loc>\s*([^<\s]+)\s*</loc>', re.I)
1692
+ _SITEMAP_MAX = 200
1693
+
1694
+
1695
+ def _urls_sitemap(url, timeout=30):
1696
+ """Same-domain page URLs from /sitemap.xml (and nested sitemap indexes,
1697
+ one level). Zero dependencies, bounded."""
1698
+ from urllib.parse import urlsplit, urljoin
1699
+ host = urlsplit(url).netloc
1700
+ seen, pages = set(), []
1701
+ queue = [urljoin(url, '/sitemap.xml')]
1702
+ while queue and len(pages) < _SITEMAP_MAX:
1703
+ sm = queue.pop(0)
1704
+ if sm in seen:
1705
+ continue
1706
+ seen.add(sm)
1707
+ try:
1708
+ data = _fetch(sm, timeout=timeout, truncate_at=2_000_000)
1709
+ except Exception: # noqa: BLE001
1710
+ continue
1711
+ if not data.lstrip().startswith('<'):
1712
+ continue
1713
+ for loc in _LOC.findall(data)[:_SITEMAP_MAX]:
1714
+ parts = urlsplit(loc)
1715
+ if parts.scheme not in ('http', 'https') or parts.netloc != host:
1716
+ continue
1717
+ clean = loc.split('#')[0].rstrip('/')
1718
+ if clean.endswith('.xml'): # nested sitemap
1719
+ if len(queue) < 8:
1720
+ queue.append(clean)
1721
+ continue
1722
+ if _DO_NOT_TRACK.search(parts.path):
1723
+ continue
1724
+ if clean not in pages:
1725
+ pages.append(clean)
1726
+ return pages
1727
+
1728
+
1729
+ _HREF = re.compile(r'<a\s[^>]*?href=["\']([^"\']+)["\']', re.I)
1730
+ _DO_NOT_TRACK = re.compile(r'\.(pdf|jpg|jpeg|png|gif|webp|svg|zip|mp3|mp4|docx?|xlsx?|pptx?|xml|json|rss)(\?|$)', re.I)
1731
+
1732
+
1733
+ def _internal_links(html_text, base_url, origin):
1734
+ from urllib.parse import urljoin, urlsplit
1735
+ host = urlsplit(origin).netloc
1736
+ out = []
1737
+ for href in _HREF.findall(html_text):
1738
+ if href.startswith(('#', 'mailto:', 'tel:', 'javascript:')):
1739
+ continue
1740
+ absolute = urljoin(base_url, href.strip()).split('#')[0].rstrip('/')
1741
+ parts = urlsplit(absolute)
1742
+ if parts.scheme not in ('http', 'https') or parts.netloc != host:
1743
+ continue
1744
+ if _DO_NOT_TRACK.search(parts.path):
1745
+ continue
1746
+ out.append(absolute)
1747
+ return out
1748
+
1749
+
1750
+ def evaluate_site(parsers, lang='en'):
1751
+ """Site-level criteria over the crawled parsers: 3.2.3/3.2.4 consistency,
1752
+ 2.4.5 multiple ways. Pure function so tests need no network."""
1753
+ out = []
1754
+ if len(parsers) >= 3:
1755
+ signatures = [frozenset(p.nav_hrefs) for p in parsers if p.nav_hrefs]
1756
+ if len(signatures) >= 3 and len(set(signatures)) > 1:
1757
+ out.append({'severity': 'medium', 'criterion': _crit(lang, '3.2.3'),
1758
+ 'signal': 'nav_inconsistent',
1759
+ 'issue': _t(lang, 'nav_inconsistent').format(
1760
+ example=f'{len(set(signatures))} distintas en {len(signatures)} páginas'),
1761
+ 'remediation': _t(lang, 'nav_inconsistent_rem')})
1762
+ # 3.2.6 Consistent Help (A, new in 2.2): help links stable across pages
1763
+ signatures_help = [frozenset(p.help_hrefs) for p in parsers if p.help_hrefs]
1764
+ if len(signatures_help) >= 2 and len(parsers) >= 3 and len(set(signatures_help)) > 1:
1765
+ out.append({'severity': 'medium', 'criterion': _crit(lang, '3.2.6'),
1766
+ 'signal': 'help_inconsistent',
1767
+ 'issue': _t(lang, 'help_inconsistent').format(
1768
+ example=f'{len(set(signatures_help))} variantes en {len(signatures_help)} páginas'),
1769
+ 'remediation': _t(lang, 'help_inconsistent_rem')})
1770
+ if parsers and not any(p.has_search or p.has_sitemap for p in parsers):
1771
+ out.append({'severity': 'medium', 'criterion': _crit(lang, '2.4.5'),
1772
+ 'signal': 'no_multiple_ways',
1773
+ 'issue': _t(lang, 'no_multiple_ways'),
1774
+ 'remediation': _t(lang, 'no_multiple_ways_rem')})
1775
+ return out
1776
+
1777
+
1778
+ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
1779
+ budget=None):
1780
+ """Audita la URL y hasta max_pages-1 páginas más del mismo dominio
1781
+ (descubrimiento por enlaces). Igual de cero-dependencias que el resto."""
1782
+ max_pages = max(1, min(20, int(max_pages)))
1783
+ import time
1784
+ deadline = (time.monotonic() + budget) if budget else None
1785
+ try:
1786
+ html_text = _fetch(url, timeout=timeout)
1787
+ except ValueError as e:
1788
+ return {'error': str(e)}
1789
+ except Exception as e: # noqa: BLE001
1790
+ return {'error': _t(lang, 'fetch_error').format(e=e)}
1791
+ p0 = _Auditor()
1792
+ p0.feed(html_text[:MAX_HTML]); p0.close()
1793
+ reports = [audit_html(html_text, url, lang=lang)]
1794
+ parsers = [p0]
1795
+ seen = {url.split('#')[0].rstrip('/')}
1796
+ # discovery: sitemap first (WCAG-EM's own enumeration), links as fallback
1797
+ urls_sm = _urls_sitemap(url, timeout=timeout) if from_sitemap else []
1798
+ queue = urls_sm or _internal_links(html_text, url, url)
1799
+ while queue and len(reports) < max_pages:
1800
+ if deadline is not None and time.monotonic() >= deadline:
1801
+ break # budget exhausted: partial, not eternal
1802
+ next = queue.pop(0)
1803
+ if next in seen:
1804
+ continue
1805
+ seen.add(next)
1806
+ try:
1807
+ html_pg = _fetch(next, timeout=timeout)
1808
+ except Exception: # noqa: BLE001
1809
+ continue
1810
+ reports.append(audit_html(html_pg, next, lang=lang))
1811
+ pg = _Auditor()
1812
+ pg.feed(html_pg[:MAX_HTML]); pg.close()
1813
+ parsers.append(pg)
1814
+ if len(reports) < max_pages and not from_sitemap:
1815
+ for new in _internal_links(html_pg, next, url):
1816
+ if new not in seen:
1817
+ queue.append(new)
1818
+ site_findings = evaluate_site(parsers, lang=lang)
1819
+ for h in site_findings:
1820
+ for inf in reports[:1]:
1821
+ inf.setdefault('findings', []).append(h)
1822
+ inf['score'] = compute_score(inf['findings'])
1823
+ scores = [pg['score'] for pg in reports if 'score' in pg]
1824
+ findings_by_signal = {}
1825
+ for pg in reports:
1826
+ for h in pg.get('findings', []):
1827
+ findings_by_signal[h['signal']] = findings_by_signal.get(h['signal'], 0) + 1
1828
+ return {
1829
+ 'url': url,
1830
+ 'mode': 'site',
1831
+ 'budget_exhausted': bool(deadline is not None and time.monotonic() >= deadline),
1832
+ 'not_measured': _not_measured(lang),
1833
+ 'discovery': 'sitemap' if urls_sm else 'links',
1834
+ 'pages': len(reports),
1835
+ 'mean_score': round(sum(scores) / len(scores)) if scores else None,
1836
+ 'worst_score': min(scores) if scores else None,
1837
+ 'recurring_signals': sorted(findings_by_signal, key=findings_by_signal.get, reverse=True)[:8],
1838
+ 'reports': reports,
1839
+ 'limits': _t(lang, 'limits'),
1840
+ }
1841
+
1842
+
1843
+ # extensiones que no son HTML auditable pero sí "web tocado" — se listan, no se audita
1844
+ _WEB_TOUCHED = {'.css', '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte', '.astro',
1845
+ '.php', '.erb', '.twig', '.liquid', '.hbs', '.ejs', '.md', '.svg'}
1846
+ _AUDITABLE = {'.html', '.htm'}
1847
+
1848
+
1849
+ def audit_changed(base='HEAD', lang='en', cwd='.'):
1850
+ """Audit ONLY what changed since `base` — the CI gate.
1851
+
1852
+ HEAD (default) covers staged+unstaged work; a ref like origin/main covers
1853
+ a branch (three-dot diff). HTML files are audited; other web-touched files
1854
+ are listed as not auditable (the honest boundary: without the build there
1855
+ is no HTML to audit). Deleted files are skipped.
1856
+ """
1857
+ import subprocess
1858
+ spec = ['git', 'diff', '--name-only', '--diff-filter=d',
1859
+ base if base == 'HEAD' else f'{base}...HEAD']
1860
+ try:
1861
+ out = subprocess.run(spec, cwd=cwd, capture_output=True, text=True, timeout=30)
1862
+ except FileNotFoundError:
1863
+ return {'error': 'git not available'}
1864
+ if out.returncode != 0:
1865
+ return {'error': f'git diff failed: {out.stderr.strip()[:200]}'}
1866
+ changed = [f for f in out.stdout.splitlines() if f.strip()]
1867
+ # los NUEVOS sin trackear no salen en git diff — entran también:
1868
+ # una página recién creada no puede escaparse del gate local
1869
+ untracked = subprocess.run(['git', 'ls-files', '--others', '--exclude-standard'],
1870
+ cwd=cwd, capture_output=True, text=True, timeout=30)
1871
+ if untracked.returncode == 0:
1872
+ changed += [f for f in untracked.stdout.splitlines() if f.strip() and f not in changed]
1873
+ auditables, web_touched = [], []
1874
+ for f in changed:
1875
+ ext = os.path.splitext(f)[1].lower()
1876
+ if ext in _AUDITABLE:
1877
+ auditables.append(f)
1878
+ elif ext in _WEB_TOUCHED:
1879
+ web_touched.append(f)
1880
+
1881
+ reports = []
1882
+ for f in auditables:
1883
+ filepath = os.path.join(cwd, f)
1884
+ if not os.path.exists(filepath):
1885
+ continue # renombrado/eliminado entre el diff y ahora
1886
+ with open(filepath, encoding='utf-8', errors='replace') as fh:
1887
+ reports.append(audit_html(fh.read(), f, lang=lang))
1888
+
1889
+ findings = [h for r in reports for h in r.get('findings', [])]
1890
+ scores = [r['score'] for r in reports if r.get('score') is not None]
1891
+ blocking = sum(1 for h in findings if h['severity'] in ('high', 'medium'))
1892
+ return {
1893
+ 'mode': 'changed', 'base': base, 'lang': lang,
1894
+ 'files': {'changed': len(changed), 'audited': len(reports),
1895
+ 'web_touched_not_auditable': sorted(web_touched)},
1896
+ 'reports': reports,
1897
+ 'score': round(sum(scores) / len(scores)) if scores else None,
1898
+ 'worst_score': min(scores) if scores else None,
1899
+ 'summary': {sev: sum(1 for h in findings if h['severity'] == sev)
1900
+ for sev in ('high', 'medium', 'low')},
1901
+ 'blocking': blocking,
1902
+ 'note': ('exit code 2 = high/medium findings in changed files (CI gate; '
1903
+ 'untracked new files included); web-touched non-HTML files are '
1904
+ 'listed, not audited — audit the built/deployed output for those.'
1905
+ if lang == 'en' else
1906
+ 'código de salida 2 = hallazgos high/medium en lo tocado (gate CI; '
1907
+ 'los nuevos sin trackear también entran); los ficheros web no-HTML '
1908
+ 'se listan sin auditar — audita la salida compilada/desplegada '
1909
+ 'para esos.'),
1910
+ }
1911
+
1912
+
1913
+ def main(argv):
1914
+ ap = argparse.ArgumentParser(description=__doc__)
1915
+ g = ap.add_mutually_exclusive_group(required=True)
1916
+ g.add_argument('--url')
1917
+ g.add_argument('--file')
1918
+ g.add_argument('--changed', action='store_true',
1919
+ help='audit ONLY files changed since --base (default HEAD) — CI gate')
1920
+ ap.add_argument('--base', default='HEAD',
1921
+ help='git ref for --changed (default HEAD; e.g. origin/main)')
1922
+ ap.add_argument('--lang', default='en', choices=['en', 'es'])
1923
+ ap.add_argument('--pages', type=int, default=1,
1924
+ help='crawl ligero mismo dominio (1 = solo la página)')
1925
+ ap.add_argument('--no-sitemap', action='store_true',
1926
+ help='descubre por enlaces, sin leer el sitemap')
1927
+ a = ap.parse_args(argv)
1928
+ if a.changed:
1929
+ res = audit_changed(base=a.base, lang=a.lang)
1930
+ if 'error' in res:
1931
+ print(json.dumps(res))
1932
+ return 1
1933
+ print(json.dumps(res, ensure_ascii=False, indent=1))
1934
+ return 2 if res.get('blocking') else 0
1935
+ if a.url:
1936
+ try:
1937
+ res = (audit_site(a.url, max_pages=a.pages, lang=a.lang,
1938
+ from_sitemap=not a.no_sitemap)
1939
+ if a.pages > 1 else audit_url(a.url, lang=a.lang))
1940
+ except Exception as e: # noqa: BLE001
1941
+ print(json.dumps({'error': f'no se pudo descargar: {e}'}))
1942
+ return 1
1943
+ else:
1944
+ with open(a.file, encoding='utf-8', errors='replace') as f:
1945
+ res = audit_html(f.read(), a.file, lang=a.lang)
1946
+ print(json.dumps(res, ensure_ascii=False, indent=1))
1947
+ return 0
1948
+
1949
+
1950
+ if __name__ == '__main__':
1951
+ sys.exit(main(sys.argv[1:]))