@kinti/a11y-toolkit 5.25.2 → 5.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +1 -1
  2. package/a11y_toolkit/a11y.py +31 -4
  3. package/a11y_toolkit/a11yact.py +9 -1
  4. package/a11y_toolkit/a11yannotate.py +185 -0
  5. package/a11y_toolkit/a11yaudit.py +903 -186
  6. package/a11y_toolkit/a11ybadge.py +24 -17
  7. package/a11y_toolkit/a11ybudget.py +145 -1
  8. package/a11y_toolkit/a11ycorpus.py +58 -24
  9. package/a11y_toolkit/a11ycrit.py +110 -53
  10. package/a11y_toolkit/a11ydiff.py +104 -34
  11. package/a11y_toolkit/a11ydisprove.py +15 -8
  12. package/a11y_toolkit/a11ydocx.py +8 -6
  13. package/a11y_toolkit/a11ydom.py +451 -96
  14. package/a11y_toolkit/a11yen301549.py +147 -0
  15. package/a11y_toolkit/a11yengines.py +157 -0
  16. package/a11y_toolkit/a11yevidence.py +182 -36
  17. package/a11y_toolkit/a11yfix.py +131 -52
  18. package/a11y_toolkit/a11yinit.py +30 -5
  19. package/a11y_toolkit/a11yjourney.py +110 -4
  20. package/a11y_toolkit/a11yledger.py +119 -12
  21. package/a11y_toolkit/a11ylocate.py +247 -0
  22. package/a11y_toolkit/a11yopenacr.py +28 -7
  23. package/a11y_toolkit/a11ypatches.py +154 -0
  24. package/a11y_toolkit/a11ypatterns.py +344 -0
  25. package/a11y_toolkit/a11ypdf.py +109 -53
  26. package/a11y_toolkit/a11yrgaa.py +60 -0
  27. package/a11y_toolkit/a11yroute.py +34 -12
  28. package/a11y_toolkit/a11ysarif.py +70 -21
  29. package/a11y_toolkit/a11yscope.py +296 -0
  30. package/a11y_toolkit/a11yscroll.py +7 -5
  31. package/a11y_toolkit/a11ystatement.py +30 -6
  32. package/a11y_toolkit/a11ytrace.py +293 -0
  33. package/a11y_toolkit/a11yvalidate.py +21 -15
  34. package/a11y_toolkit/a11yvpat.py +54 -11
  35. package/a11y_toolkit/a11yvtt.py +22 -6
  36. package/a11y_toolkit/a11ywiz.py +121 -0
  37. package/a11y_toolkit/contrast.py +62 -24
  38. package/a11y_toolkit/locales/en.json +222 -24
  39. package/a11y_toolkit/locales/es.json +223 -25
  40. package/a11y_toolkit/rgaa.json +2661 -0
  41. package/a11y_toolkit/server.py +247 -59
  42. package/package.json +2 -2
  43. package/a11y_toolkit/a11yplan.py +0 -214
  44. package/a11y_toolkit/a11ywcagem.py +0 -237
@@ -19,6 +19,10 @@ import sys
19
19
 
20
20
  # Enlace oficial Understanding WCAG 2.2 por criterio (w3.org, índice 2026-10).
21
21
  # Fuente: https://www.w3.org/WAI/WCAG22/Understanding/ — los 86 criterios.
22
+ # Success criteria introduced in WCAG 2.2 (for --new-in filters)
23
+ NEW_IN_22 = {'2.4.11', '2.4.12', '2.4.13', '2.5.7', '2.5.8',
24
+ '3.2.6', '3.3.7', '3.3.8', '3.3.9'}
25
+
22
26
  _UNDERSTANDING = {
23
27
  '1.1.1': 'non-text-content',
24
28
  '1.2.1': 'audio-only-and-video-only-prerecorded',
@@ -112,39 +116,39 @@ _UNDERSTANDING = {
112
116
  # code → (nivel, {es: (nombre, exige, fallos, prueba)}, {en: ...})
113
117
  _C = {
114
118
  '1.2.1': ('A', {
115
- 'es': ('Solo audio y solo vídeo (pregrabado)', 'El audio tiene transcripción; el vídeo sin audio, alternativa textual.', 'Podcasts without transcripts; silent demonstration videos without text description.', 'Manual: play the media and check an alternative exists.'),
119
+ 'es': ('Solo audio y solo vídeo (pregrabado)', 'El audio tiene transcripción; el vídeo sin audio, alternativa textual.', 'Podcasts sin transcripción; vídeos demostrativos sin sonido y sin descripción textual.', 'Manual: reproduce el medio y comprueba que existe una alternativa.'),
116
120
  'en': ('Audio-only and Video-only (Prerecorded)', 'Audio-only content has a transcript; video-only has a text or audio alternative.', 'Podcasts without transcripts; silent demonstration videos without text description.', 'Manual: play the media and check an alternative exists.'),
117
121
  }),
118
122
  '1.4.10': ('AA', {
119
- 'es': ('Reflujo', 'El contenido refluye a 320px CSS sin scroll bidimensional.', 'Fixed-width layouts that force horizontal scrolling on phones.', 'a11y_reflow (320px viewport, real overflow measurement + offenders).'),
123
+ 'es': ('Reflujo', 'El contenido refluye a 320px CSS sin scroll bidimensional.', 'Maquetas de ancho fijo que fuerzan scroll horizontal en móviles.', 'a11y_reflow (320px viewport, real overflow measurement + offenders).'),
120
124
  'en': ('Reflow', 'Content reflows to 320 CSS px without two-dimensional scroll.', 'Fixed-width layouts that force horizontal scrolling on phones.', 'a11y_reflow (320px viewport, real overflow measurement + offenders).'),
121
125
  }),
122
126
  '1.4.12': ('AA', {
123
- 'es': ('Espaciado de texto', 'Sin pérdida de contenido con los overrides de espaciado oficiales.', 'Cards with fixed heights that clip their text when spacing grows.', 'a11y_audit_dom (injects the official override set and counts clipped texts).'),
127
+ 'es': ('Espaciado de texto', 'Sin pérdida de contenido con los overrides de espaciado oficiales.', 'Tarjetas con altura fija que cortan su texto al crecer el espaciado.', 'a11y_audit_dom (inyecta el juego oficial de overrides y cuenta textos cortados).'),
124
128
  'en': ('Text Spacing', 'No loss of content when users apply the documented spacing overrides (line-height 1.5, letter-spacing 0.12em…)', 'Cards with fixed heights that clip their text when spacing grows.', 'a11y_audit_dom (injects the official override set and counts clipped texts).'),
125
129
  }),
126
130
  '1.4.13': ('AA', {
127
- 'es': ('Contenido al pasar el foco o el puntero', 'El contenido emergente se puede cerrar, alcanzar y persiste.', 'Tooltips that vanish when you move toward them; hovers you cannot dismiss with Esc.', 'Manual: hover/focus each trigger, try Esc, try moving to the tooltip.'),
131
+ 'es': ('Contenido al pasar el foco o el puntero', 'El contenido emergente se puede cerrar, alcanzar y persiste.', 'Tooltips que desaparecen al acercarte a ellos; hovers que no se pueden descartar con Esc.', 'Manual: hover/foco en cada disparador, prueba Esc, prueba moverte al tooltip.'),
128
132
  'en': ('Content on Hover or Focus', 'Hover/focus-triggered content is dismissible, hoverable and persistent.', 'Tooltips that vanish when you move toward them; hovers you cannot dismiss with Esc.', 'Manual: hover/focus each trigger, try Esc, try moving to the tooltip.'),
129
133
  }),
130
134
  '2.1.2': ('A', {
131
- 'es': ('Sin trampa de teclado', 'El foco siempre puede salir solo con teclado.', 'Modals whose focus cycles forever with no Escape release.', 'a11y_keyboard (real Tab walk, cycle detection, Escape-release test).'),
135
+ 'es': ('Sin trampa de teclado', 'El foco siempre puede salir solo con teclado.', 'Modales cuyo foco cicla para siempre sin salida con Escape.', 'a11y_keyboard (pase real de Tab, detección de ciclo, prueba de Escape).'),
132
136
  'en': ('No Keyboard Trap', 'Focus can always leave a component with the keyboard alone.', 'Modals whose focus cycles forever with no Escape release.', 'a11y_keyboard (real Tab walk, cycle detection, Escape-release test).'),
133
137
  }),
134
138
  '2.5.7': ('AA', {
135
- 'es': ('Movimientos de arrastre', 'Toda acción de arrastre tiene alternativa sin arrastre.', 'Sliders you can only drag; kanban cards you can only drag-and-drop.', 'Manual: try every action with click/tap only; a11y_audit_url flags drag-handler suspicion.'),
139
+ 'es': ('Movimientos de arrastre', 'Toda acción de arrastre tiene alternativa sin arrastre.', 'Sliders que solo se arrastran; tarjetas kanban que solo admiten arrastrar-y-soltar.', 'Manual: prueba cada acción solo con clic/toque; a11y_audit_url marca sospecha de handlers de arrastre.'),
136
140
  'en': ('Dragging Movements', 'Dragging operations have a non-dragging alternative.', 'Sliders you can only drag; kanban cards you can only drag-and-drop.', 'Manual: try every action with click/tap only; a11y_audit_url flags drag-handler suspicion.'),
137
141
  }),
138
142
  '1.4.5': ('AA', {
139
- 'es': ('Imágenes de texto', 'Salvo logotipos, el texto se presenta como texto real, no como imagen.', 'Headings or paragraphs rendered as PNG/JPG; banner text baked into hero images.', 'a11y_audit_url flags images inside headings and book-length alts (review signal); you judge whether each image of text is justified (logo exception).'),
143
+ 'es': ('Imágenes de texto', 'Salvo logotipos, el texto se presenta como texto real, no como imagen.', 'Encabezados o párrafos renderizados como PNG/JPG; texto de banner horneado en imágenes hero.', 'a11y_audit_url marca imágenes dentro de encabezados y alts kilométricos (señal de revisión); juzgas si cada imagen de texto está justificada (excepción logotipo).'),
140
144
  'en': ('Images of Text', 'Except for logotypes, text is presented as real text, not images of text.', 'Headings or paragraphs rendered as PNG/JPG; banner text baked into hero images.', 'a11y_audit_url flags images inside headings and book-length alts (review signal); you judge whether each image of text is justified (logo exception).'),
141
145
  }),
142
146
  '1.4.11': ('AA', {
143
- 'es': ('Contraste no textual', 'Componentes UI y objetos gráficos tienen al menos 3:1 contra colores adyacentes.', 'Icon buttons barely visible against their background; focus indicators too faint to see.', 'a11y_contrast_pair with target 3.0 for UI elements; the rendered audit checks focus-indicator contrast; you verify visually.'),
147
+ 'es': ('Contraste no textual', 'Componentes UI y objetos gráficos tienen al menos 3:1 contra colores adyacentes.', 'Botones-icono apenas visibles contra su fondo; indicadores de foco demasiado tenues.', 'a11y_contrast_pair con objetivo 3.0 para elementos UI; el pase renderizado comprueba el contraste del indicador de foco; verifícalo visualmente.'),
144
148
  'en': ('Non-text Contrast', 'UI components and graphical objects have at least 3:1 contrast against adjacent colors.', 'Icon buttons barely visible against their background; focus indicators too faint to see.', 'a11y_contrast_pair with target 3.0 for UI elements; the rendered audit checks focus-indicator contrast; you verify visually.'),
145
149
  }),
146
150
  '3.2.6': ('A', {
147
- 'es': ('Ayuda coherente — NUEVO en 2.2', 'Si hay ayuda en varias páginas, aparece en el mismo orden relativo.', 'A "Contact us" link in the header on some pages and the footer on others.', 'a11ytoolkit audit --pages N (site-level help-link drift detection across the crawl).'),
151
+ 'es': ('Ayuda coherente — NUEVO en 2.2', 'Si hay ayuda en varias páginas, aparece en el mismo orden relativo.', 'Un enlace «Contacto» en la cabecera en unas páginas y en el pie en otras.', 'a11ytoolkit audit --pages N (deriva de enlaces de ayuda a nivel de sitio durante el crawl).'),
148
152
  'en': ('Consistent Help — NEW in WCAG 2.2', 'If help is available on multiple pages, it appears in the same relative order.', 'A "Contact us" link in the header on some pages and the footer on others.', 'a11ytoolkit audit --pages N (site-level help-link drift detection across the crawl).'),
149
153
  }),
150
154
  '1.1.1': ('A', {
@@ -380,8 +384,8 @@ _C = {
380
384
  '2.2.2': ('A', {
381
385
  'es': ('Poner en pausa, detener, ocultar',
382
386
  'El contenido en movimiento >5s se puede pausar, detener u ocultar.',
383
- '<marquee>, looping CSS animations, auto-updating tickers with no pause control.',
384
- 'a11y_audit_url / a11y_audit_dom (detection); you verify a pause control actually exists and works.'),
387
+ '<marquee>, animaciones CSS en bucle, tickers de auto-actualización sin control de pausa.',
388
+ 'a11y_audit_url / a11y_audit_dom (detección); verificas que exista y funcione un control de pausa.'),
385
389
  'en': ('Pause, Stop, Hide',
386
390
  'Moving, blinking or auto-updating content that starts automatically and lasts >5s can be paused, stopped or hidden',
387
391
  '<marquee>, looping CSS animations, auto-updating tickers with no pause control.',
@@ -390,8 +394,8 @@ _C = {
390
394
  '2.5.1': ('A', {
391
395
  'es': ('Gestos de puntero',
392
396
  'Todo gesto complejo tiene alternativa de clic/toque simple.',
393
- 'Swipe carousels with no prev/next buttons; drag-to-reorder with no menu alternative.',
394
- 'a11y_audit_url (touch/drag handler suspicion); you test with single clicks only.'),
397
+ 'Carruseles por swipe sin botones anterior/siguiente; reordenar arrastrando sin alternativa de menú.',
398
+ 'a11y_audit_url (sospecha de handlers touch/drag); lo pruebas solo con clics simples.'),
395
399
  'en': ('Pointer Gestures',
396
400
  'Multipoint or path-based gestures have a single-pointer alternative (tap/click).',
397
401
  'Swipe carousels with no prev/next buttons; drag-to-reorder with no menu alternative.',
@@ -400,8 +404,8 @@ _C = {
400
404
  '2.5.4': ('A', {
401
405
  'es': ('Activación por movimiento',
402
406
  'Lo que activa el movimiento del dispositivo se activa también con UI y se puede desactivar.',
403
- 'Shake-to-undo, tilt-to-scroll with no button alternative.',
404
- 'a11y_audit_url (devicemotion/orientation handler suspicion); you verify the UI alternative actually works.'),
407
+ 'Sacudir-para-deshacer, inclinar-para-scroll sin alternativa de botón.',
408
+ 'a11y_audit_url (sospecha de handlers devicemotion/orientation); verificas que la alternativa UI funciona.'),
405
409
  'en': ('Motion Actuation',
406
410
  'Functions triggered by device motion can also be triggered by UI, and the motion trigger can be disabled.',
407
411
  'Shake-to-undo, tilt-to-scroll with no button alternative.',
@@ -410,8 +414,8 @@ _C = {
410
414
  '1.4.1': ('A', {
411
415
  'es': ('Uso del color',
412
416
  'El color nunca es el único medio visual de transmitir información.',
413
- 'Links inside prose distinguished only by a slightly different color; "fields in red are required" alone fails the criterion.',
414
- 'a11y_audit_dom (link-in-text-block color/underline check); you scan the page for color-only links by eye.'),
417
+ 'Enlaces dentro de prosa distinguidos solo por un color ligeramente distinto; «los campos en rojo son obligatorios» a solas falla el criterio.',
418
+ 'a11y_audit_dom (color/subrayado de enlace-en-texto); repasas a la vista los enlaces solo-color.'),
415
419
  'en': ('Use of Color',
416
420
  'Color is never the only visual means of conveying information.',
417
421
  'Links inside prose distinguished only by a slightly different color; "fields in red are required" alone fails the criterion.',
@@ -420,8 +424,8 @@ _C = {
420
424
  '1.3.2': ('A', {
421
425
  'es': ('Secuencia significativa',
422
426
  'El orden de lectura del código coincide con el visual.',
423
- 'CSS flex/grid order or absolute positioning that contradicts DOM order.',
424
- 'a11y_audit_dom (DOM-vs-visual inversion heuristic); you confirm with a Tab walk.'),
427
+ 'Orden flex/grid o posicionamiento absoluto que contradice el orden del DOM.',
428
+ 'a11y_audit_dom (heurística de inversión DOM-vs-visual); confirmas con un pase de Tab.'),
425
429
  'en': ('Meaningful Sequence',
426
430
  'The reading order in code matches the visual presentation order.',
427
431
  'CSS flex/grid order or absolute positioning that contradicts DOM order.',
@@ -430,8 +434,8 @@ _C = {
430
434
  '1.3.3': ('A', {
431
435
  'es': ('Características sensoriales',
432
436
  'Las instrucciones no dependen solo de forma/posición/tamaño.',
433
- '"Click the round button on the right"; "see the instructions above".',
434
- 'a11y_audit_url (text pattern review); you judge whether the reference is unambiguous.'),
437
+ '«Pulsa el botón redondo de la derecha»; «mira las instrucciones de arriba».',
438
+ 'a11y_audit_url (patrón textual de revisión); juzgas si la referencia es inequívoca.'),
435
439
  'en': ('Sensory Characteristics',
436
440
  'Instructions do not rely on shape, size, position or orientation alone.',
437
441
  '"Click the round button on the right"; "see the instructions above".',
@@ -441,7 +445,7 @@ _C = {
441
445
  'es': ('Orientación',
442
446
  'El contenido no se limita a una sola orientación salvo excepción.',
443
447
  'screen.orientation.lock() calls; orientation-forcing media queries.',
444
- 'a11y_audit_url (lock detection); you test portrait and landscape.'),
448
+ 'a11y_audit_url (detección de lock); pruebas vertical y horizontal.'),
445
449
  'en': ('Orientation',
446
450
  'Content does not restrict operation to a single orientation unless essential.',
447
451
  'screen.orientation.lock() calls; orientation-forcing media queries.',
@@ -450,8 +454,8 @@ _C = {
450
454
  '1.2.3': ('A', {
451
455
  'es': ('Audiodescripción o alternativa media',
452
456
  'El vídeo pregrabado tiene audiodescripción o alternativa.',
453
- 'Videos with essential visual information and no descriptions track.',
454
- 'a11y_audit_url (track absence); a human watching the video decides if description is needed.'),
457
+ 'Vídeos con información visual esencial y sin pista de descripciones.',
458
+ 'a11y_audit_url (ausencia de track); una persona viendo el vídeo decide si hace falta descripción.'),
455
459
  'en': ('Audio Description or Media Alternative',
456
460
  'Prerecorded video has audio description or a media alternative.',
457
461
  'Videos with essential visual information and no descriptions track.',
@@ -470,8 +474,8 @@ _C = {
470
474
  '3.2.3': ('AA', {
471
475
  'es': ('Navegación coherente',
472
476
  'La navegación repetida mantiene el mismo orden relativo en todas las páginas.',
473
- 'Menu items reordered or renamed between sections of the same site.',
474
- 'a11ytoolkit audit --pages N (site-level nav-signature comparison); you review the diff.'),
477
+ 'Ítems de menú reordenados o renombrados entre secciones del mismo sitio.',
478
+ 'a11ytoolkit audit --pages N (comparación de firma de navegación a nivel sitio); repasas el diff.'),
475
479
  'en': ('Consistent Navigation',
476
480
  'Repeated navigation appears in the same relative order across pages.',
477
481
  'Menu items reordered or renamed between sections of the same site.',
@@ -480,8 +484,8 @@ _C = {
480
484
  '3.2.4': ('AA', {
481
485
  'es': ('Identificación coherente',
482
486
  'Lo que funciona igual se identifica igual en todo el sitio.',
483
- 'A search icon labelled "Search" on one page and "Find" on another.',
484
- 'Site-level pass (same crawl); you compare accessible names across pages.'),
487
+ 'Un icono de búsqueda etiquetado «Buscar» en una página y «Find» en otra.',
488
+ 'Pase a nivel de sitio (mismo crawl); comparas nombres accesibles entre páginas.'),
485
489
  'en': ('Consistent Identification',
486
490
  'Components with the same functionality are identified consistently.',
487
491
  'A search icon labelled "Search" on one page and "Find" on another.',
@@ -490,8 +494,8 @@ _C = {
490
494
  '2.4.5': ('AA', {
491
495
  'es': ('Múltiples vías',
492
496
  'Hay al menos dos formas de encontrar cada página.',
493
- 'Sites where the only path to content is one deep menu.',
494
- 'a11ytoolkit audit --pages N (search input / sitemap link detection across the crawl).'),
497
+ 'Sitios donde el único camino al contenido es un menú profundo.',
498
+ 'a11ytoolkit audit --pages N (detección de buscador/sitemap a lo largo del crawl).'),
495
499
  'en': ('Multiple Ways',
496
500
  'At least two ways exist to find any page (nav + search/sitemap).',
497
501
  'Sites where the only path to content is one deep menu.',
@@ -500,8 +504,8 @@ _C = {
500
504
  '1.2.4': ('AA', {
501
505
  'es': ('Subtítulos (directo)',
502
506
  'El audio en directo tiene subtítulos sincronizados.',
503
- 'Live streams, webinars with no CART/captioning.',
504
- 'Manual: attend the live session and verify captions exist.'),
507
+ 'Directos, webinars sin CART/subtitulado.',
508
+ 'Manual: asiste a la sesión en vivo y verifica que hay subtítulos.'),
505
509
  'en': ('Captions (Live)',
506
510
  'Live audio content has synchronized captions.',
507
511
  'Live streams, webinars with no CART/captioning.',
@@ -511,7 +515,7 @@ _C = {
511
515
  'es': ('Atajos de carácter único',
512
516
  'Los atajos de una tecla se pueden desactivar o remapear.',
513
517
  'Pressing "s" anywhere triggers search while typing in a field.',
514
- 'Manual: type single letters with focus inside inputs and outside.'),
518
+ 'Manual: teclea letras sueltas con el foco dentro de inputs y fuera.'),
515
519
  'en': ('Character Key Shortcuts',
516
520
  'Single-character shortcuts can be turned off, remapped, or active only on focus.',
517
521
  'Pressing "s" anywhere triggers search while typing in a field.',
@@ -520,7 +524,7 @@ _C = {
520
524
  '2.3.1': ('A', {
521
525
  'es': ('Tres destellos o menos',
522
526
  'Nada parpadea más de 3 veces por segundo.',
523
- 'Videos, animations or GIFs with rapid strobe sections.',
527
+ 'Vídeos, animaciones o GIFs con secciones de destello rápido.',
524
528
  'Manual (frame-by-frame review); automated flash counting is not implemented anywhere honestly.'),
525
529
  'en': ('Three Flashes or Below Threshold',
526
530
  'Nothing flashes more than 3 times per second.',
@@ -530,7 +534,7 @@ _C = {
530
534
  '2.4.6': ('AA', {
531
535
  'es': ('Encabezados y etiquetas',
532
536
  'Encabezados y etiquetas describen su tema o propósito.',
533
- 'A heading that says "Section 2"; a form label that says "Field 1".',
537
+ 'Un encabezado que dice «Sección 2»; una etiqueta de formulario que dice «Campo 1».',
534
538
  'a11ytoolkit checks structure (empty/skips); descriptiveness is human/agent judgment.'),
535
539
  'en': ('Headings and Labels',
536
540
  'Headings and labels describe their topic or purpose.',
@@ -540,8 +544,8 @@ _C = {
540
544
  '3.2.1': ('A', {
541
545
  'es': ('Al recibir foco',
542
546
  'Recibir foco nunca cambia el contexto.',
543
- 'Focus moving to a menu item navigates immediately.',
544
- 'Manual: Tab through the page and watch for unexpected changes.'),
547
+ 'Que el foco caiga en un ítem de menú navegue de inmediato.',
548
+ 'Manual: recorre con Tab y vigila cambios inesperados.'),
545
549
  'en': ('On Focus',
546
550
  'Receiving focus never triggers a context change (navigation, form submission).',
547
551
  'Focus moving to a menu item navigates immediately.',
@@ -550,8 +554,8 @@ _C = {
550
554
  '3.2.2': ('A', {
551
555
  'es': ('Al recibir entrada',
552
556
  'Cambiar un ajuste nunca cambia el contexto automáticamente.',
553
- 'Selecting from a select navigates without a Submit.',
554
- 'Manual: interact with every control and watch for surprises.'),
557
+ 'Elegir en un select navega sin un botón Enviar.',
558
+ 'Manual: interactúa con cada control y vigila sorpresas.'),
555
559
  'en': ('On Input',
556
560
  'Changing a setting never changes context automatically.',
557
561
  'Selecting from a select navigates without a Submit.',
@@ -560,8 +564,8 @@ _C = {
560
564
  '3.3.1': ('A', {
561
565
  'es': ('Identificación de errores',
562
566
  'Los errores se identifican y describen en texto.',
563
- 'Forms that just border fields in red with no message.',
564
- 'Manual/agent: submit invalid data and check the announced error.'),
567
+ 'Formularios que solo ponen borde rojo sin ningún mensaje.',
568
+ 'Manual/agente: envía datos inválidos y comprueba el error anunciado.'),
565
569
  'en': ('Error Identification',
566
570
  'Input errors are identified in text, and described to the user.',
567
571
  'Forms that just border fields in red with no message.',
@@ -571,7 +575,7 @@ _C = {
571
575
  'es': ('Sugerencia ante errores',
572
576
  'Los mensajes de error sugieren la corrección cuando se conoce.',
573
577
  '"Invalid date" instead of "Use DD/MM/YYYY".',
574
- 'Manual/agent: trigger errors and read the messages.'),
578
+ 'Manual/agente: provoca errores y lee los mensajes.'),
575
579
  'en': ('Error Suggestion',
576
580
  'Error messages suggest a correction when known.',
577
581
  '"Invalid date" instead of "Use DD/MM/YYYY".',
@@ -580,8 +584,8 @@ _C = {
580
584
  '3.3.4': ('AA', {
581
585
  'es': ('Prevención de errores',
582
586
  'Envíos con consecuencias son reversibles, verificados o confirmados.',
583
- 'Purchase buttons with no review step.',
584
- 'Manual: walk the full transaction flow.'),
587
+ 'Botones de compra sin paso de revisión.',
588
+ 'Manual: recorre el flujo de transacción completo.'),
585
589
  'en': ('Error Prevention (Legal, Financial, Data)',
586
590
  'Submissions with legal/financial consequences are reversible, checked or confirmed.',
587
591
  'Purchase buttons with no review step.',
@@ -590,7 +594,7 @@ _C = {
590
594
  '3.3.7': ('A', {
591
595
  'es': ('Entrada redundante',
592
596
  'No se pide reescribir información ya dada.',
593
- 'Multi-step forms asking for the email again.',
597
+ 'Formularios multi-paso que piden el email otra vez.',
594
598
  'Manual/agent: walk multi-step flows.'),
595
599
  'en': ('Redundant Entry',
596
600
  'Information asked before is auto-filled or selectable, not retyped.',
@@ -600,8 +604,8 @@ _C = {
600
604
  '4.1.3': ('AA', {
601
605
  'es': ('Mensajes de estado',
602
606
  'Los mensajes de estado se anuncian sin mover el foco.',
603
- 'Toasts, "saved" confirmations with no aria-live.',
604
- 'a11y_aria_live_snippet (observe announcements); the scroll auditor checks feed loading announcements.'),
607
+ 'Toasts, confirmaciones de «guardado» sin aria-live.',
608
+ 'a11y_aria_live_snippet (observa anuncios); la auditoría de scroll comprueba los anuncios de carga del feed.'),
605
609
  'en': ('Status Messages',
606
610
  'Status messages are announced without moving focus.',
607
611
  'Toasts, "saved" confirmations with no aria-live.',
@@ -841,8 +845,11 @@ _SIGNAL_CRIT = {
841
845
  'autocomplete_invalid': '1.3.5',
842
846
  'blank_no_warning': '3.2.5',
843
847
  'captcha': '3.3.8',
848
+ 'canvas_no_accessible_layer': '1.1.1',
849
+ 'chart_no_data_equivalent': '1.1.1',
844
850
  'char_shortcut': '2.1.4',
845
851
  'click_nonfocusable': '2.1.1',
852
+ 'role_no_tabindex': '2.1.1',
846
853
  'color_only_link': '1.4.1',
847
854
  'contrast_fail': '1.4.3',
848
855
  'contrast_image_fail': '1.4.3',
@@ -878,6 +885,7 @@ _SIGNAL_CRIT = {
878
885
  'iframe_title': '4.1.2',
879
886
  'images_of_text': '1.4.5',
880
887
  'img_no_alt': '1.1.1',
888
+ 'alt_quality': '1.1.1',
881
889
  'input_img_alt': '1.1.1',
882
890
  'input_navigates': '3.2.2',
883
891
  'journey_dialog_trap': '2.1.2',
@@ -951,20 +959,33 @@ _SIGNAL_CRIT = {
951
959
  'zoom_no': '1.4.4'
952
960
  }
953
961
 
962
+ # Errores de lookup, bilingües (el repositorio exige es y en en el contenido;
963
+ # el español ya no puede colarse en una respuesta lang='en')
964
+ _CRIT_ERRORS = {
965
+ 'es': {'unknown_signal': 'señal desconocida: {signal}',
966
+ 'unknown_criterion': 'criterio desconocido: {code}',
967
+ 'hint': 'los ids de señal aparecen en cada hallazgo de auditoría'},
968
+ 'en': {'unknown_signal': 'unknown signal: {signal}',
969
+ 'unknown_criterion': 'unknown criterion: {code}',
970
+ 'hint': 'signal ids appear in every audit finding'},
971
+ }
972
+
973
+
954
974
  def criterion(code=None, lang='en', signal=None):
955
975
  from .a11yact import act_rules_for
976
+ _t = _CRIT_ERRORS['es' if lang == 'es' else 'en']
956
977
  if signal:
957
978
  from .a11yaudit import normalize_signal
958
979
  signal = normalize_signal(signal.strip())
959
980
  if signal in _SIGNAL_CRIT:
960
981
  code = _SIGNAL_CRIT[signal]
961
982
  else:
962
- return {'error': f'señal desconocida: {signal}',
983
+ return {'error': _t['unknown_signal'].format(signal=signal),
963
984
  'known_signals': len(_SIGNAL_CRIT),
964
- 'hint': 'signal ids appear in every audit finding'}
985
+ 'hint': _t['hint']}
965
986
  code = code.strip()
966
987
  if code not in _C:
967
- return {'error': f'criterio desconocido: {code}',
988
+ return {'error': _t['unknown_criterion'].format(code=code),
968
989
  'available': sorted(_C)}
969
990
  level, languages = _C[code]
970
991
  name, requires, failures, how_to_check = languages.get(lang) or languages['es']
@@ -1005,12 +1026,48 @@ def main(argv):
1005
1026
  ap.add_argument('--signal', help='engine signal id (e.g. kbd_trap) instead of a criterion code')
1006
1027
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
1007
1028
  ap.add_argument('--list', action='store_true')
1029
+ ap.add_argument('--level', choices=['A', 'AA', 'AAA'],
1030
+ help='--list: filter by conformance level')
1031
+ ap.add_argument('--new-in', dest='new_in', metavar='VERSION',
1032
+ help='--list: only criteria introduced in the given version (e.g. 2.2)')
1033
+ ap.add_argument('--signal-filter', dest='signal_filter', choices=['yes', 'no'],
1034
+ help='--list: only criteria with (yes) or without (no) an automated signal')
1035
+ ap.add_argument('--standard', choices=['en301549'],
1036
+ help='--list: add the EN 301 549 clause per row (with --target)')
1037
+ ap.add_argument('--target', choices=['web', 'documents', 'software'], default='web',
1038
+ help='--list: target for the EN clause (with --standard en301549)')
1039
+ ap.add_argument('--json', action='store_true', help='--list: machine-readable output')
1008
1040
  a = ap.parse_args(argv)
1009
1041
  if a.list or not (a.code or a.signal):
1010
- print(json.dumps({'available_criteria': sorted(_C)}, indent=1))
1042
+ # listing: --level/--new-in/--signal-filter narrow it, --standard +
1043
+ # --target add the EN clause column, --json is the (machine) shape the
1044
+ # rows already have — none of them needs another filter flag to apply
1045
+ from .a11yevidence import MANUAL_AA # lazy: avoids the import cycle
1046
+ no_signal = {m.split(' ')[0] for m in MANUAL_AA}
1047
+ rows = []
1048
+ for code, (level, loc) in sorted(_C.items()):
1049
+ if a.level and level != a.level:
1050
+ continue
1051
+ if a.new_in and code not in NEW_IN_22:
1052
+ continue
1053
+ if a.signal_filter == 'yes' and code in no_signal:
1054
+ continue
1055
+ if a.signal_filter == 'no' and code not in no_signal:
1056
+ continue
1057
+ row = {'code': code, 'level': level,
1058
+ 'name': (loc.get(a.lang) or loc['en'])[0],
1059
+ 'new_in_22': code in NEW_IN_22,
1060
+ 'signal': code not in no_signal}
1061
+ if a.standard:
1062
+ from .a11yen301549 import clause_for as _cf
1063
+ row['clause'] = _cf(code, a.target)
1064
+ rows.append(row)
1065
+ print(json.dumps({'count': len(rows), 'criteria': rows},
1066
+ ensure_ascii=False, indent=1))
1011
1067
  return 0
1012
- print(json.dumps(criterion(a.code, a.lang, signal=a.signal), ensure_ascii=False, indent=1))
1013
- return 0
1068
+ res = criterion(a.code, a.lang, signal=a.signal)
1069
+ print(json.dumps(res, ensure_ascii=False, indent=1))
1070
+ return 1 if 'error' in res else 0
1014
1071
 
1015
1072
 
1016
1073
  if __name__ == '__main__':
@@ -50,11 +50,87 @@ COLLECTOR = r'''() => {
50
50
  }'''
51
51
 
52
52
 
53
- def snapshot(url, output=None, auth_state=None):
54
- """Captura una URL. Con salida=None devuelve los datos sin escribir fichero."""
53
+ _LAUNCHERS = {
54
+ 'chromium': lambda p: p.chromium.launch(),
55
+ 'firefox': lambda p: p.firefox.launch(),
56
+ 'webkit': lambda p: p.webkit.launch(),
57
+ 'chrome': lambda p: p.chromium.launch(channel='chrome'),
58
+ 'msedge': lambda p: p.chromium.launch(channel='msedge'),
59
+ }
60
+
61
+
62
+ # firma estable del elemento enfocado — la MISMA doctrina de claves que el
63
+ # snapshot (#id o tag:nombre:href); compartida con a11ytrace
64
+ FOCUS_KEY_JS = r'''() => {
65
+ const el = document.activeElement;
66
+ if (!el || el === document.body) return null;
67
+ const link = el.closest('a[href]');
68
+ let name = el.getAttribute('aria-label') || (el.innerText || '')
69
+ .replace(/\s+/g,' ').trim() || el.getAttribute('title') ||
70
+ (el.tagName==='INPUT' && el.value) || '';
71
+ return el.id ? '#'+el.id : el.tagName.toLowerCase()+':'+name.slice(0,60).toLowerCase()+
72
+ (link ? ':'+link.getAttribute('href') : '');
73
+ }'''
74
+
75
+ # Pase de foco por IDENTIDAD de elemento, no por firma: dos enfocables
76
+ # distintos pueden compartir firma (dos botones-icono sin name, un Edit por
77
+ # fila) y la firma repetida truncaba el pase a la segunda aparición. El primer
78
+ # enfocable se marca con un data-attribute (token estático) y la vuelta se
79
+ # detecta cuando el ACTIVO es ese mismo elemento; la firma del primero queda
80
+ # como stop secundario de refuerzo y el cap de iteraciones como tercero.
81
+ _WALK_STAMP_JS = r'''() => {
82
+ const el = document.activeElement;
83
+ if (!el || el === document.body) return false;
84
+ try { el.dataset.__a11yWalk = '0'; } catch (e) {}
85
+ return true;
86
+ }'''
87
+
88
+ _WALK_IS_STAMPED_JS = r'''() => {
89
+ const el = document.activeElement;
90
+ return !!(el && el.dataset && el.dataset.__a11yWalk === '0');
91
+ }'''
92
+
93
+ _WALK_CLEAN_JS = r'''() => {
94
+ const el = document.querySelector('[data-__a11y-walk]');
95
+ if (el) el.removeAttribute('data-__a11y-walk');
96
+ }'''
97
+
98
+
99
+ def _walk_focus(page, cap):
100
+ """Tab walk → focus order (list of signatures). Stops on wrap by element
101
+ identity (the stamped first focusable), secondarily on the first
102
+ signature repeating, and on the iteration cap."""
103
+ order = []
104
+ page.keyboard.press('Tab')
105
+ if not page.evaluate(_WALK_STAMP_JS):
106
+ return order # nothing focusable (body stayed active)
107
+ first = page.evaluate(FOCUS_KEY_JS)
108
+ if first is None:
109
+ return order
110
+ order.append(first)
111
+ for _ in range(cap):
112
+ page.keyboard.press('Tab')
113
+ info = page.evaluate(FOCUS_KEY_JS)
114
+ if info is None:
115
+ break
116
+ if page.evaluate(_WALK_IS_STAMPED_JS) or info == first:
117
+ break # focus returned to the FIRST element itself: full circle
118
+ order.append(info)
119
+ try:
120
+ page.evaluate(_WALK_CLEAN_JS) # leave the page as we found it
121
+ except Exception: # noqa: BLE001 — best-effort cleanup
122
+ pass
123
+ return order
124
+
125
+
126
+ def snapshot(url, output=None, auth_state=None, engine='chromium'):
127
+ """Captura una URL. Con salida=None devuelve los datos sin escribir fichero.
128
+ engine: chromium (default), firefox, webkit, chrome, msedge — la misma
129
+ captura en otro motor es la materia prima de la matriz cross-engine."""
55
130
  from playwright.sync_api import sync_playwright
56
131
  with sync_playwright() as p:
57
- nav = p.chromium.launch()
132
+ launch = _LAUNCHERS.get(engine or 'chromium', _LAUNCHERS['chromium'])
133
+ nav = launch(p)
58
134
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
59
135
  page = ctx.new_page() if auth_state else nav.new_page()
60
136
  page.goto(url, wait_until='networkidle', timeout=45000)
@@ -70,45 +146,38 @@ def snapshot(url, output=None, auth_state=None):
70
146
  except Exception: # noqa: BLE001
71
147
  tree = None
72
148
 
73
- order = []
74
- page.keyboard.press('Tab')
75
- seen = set()
76
- for _ in range(len(elements) * 2 + 10):
77
- info = page.evaluate(r'''() => {
78
- const el = document.activeElement;
79
- if (!el || el === document.body) return null;
80
- const link = el.closest('a[href]');
81
- let name = el.getAttribute('aria-label') || (el.innerText || '')
82
- .replace(/\s+/g,' ').trim() || el.getAttribute('title') ||
83
- (el.tagName==='INPUT' && el.value) || '';
84
- return el.id ? '#'+el.id : el.tagName.toLowerCase()+':'+name.slice(0,60).toLowerCase()+
85
- (link ? ':'+link.getAttribute('href') : '');
86
- }''')
87
- if info is None:
88
- break
89
- entry_key = info + '@' + str(len(seen))
90
- if info in seen:
91
- break
92
- seen.add(info)
93
- order.append(info)
94
- page.keyboard.press('Tab')
149
+ order = _walk_focus(page, len(elements) * 2 + 10)
95
150
  nav.close()
96
151
 
97
152
  data = {'url': url, 'ts': datetime.now(timezone.utc).isoformat(),
98
153
  'elements': elements, 'focus_order': order}
99
154
  if tree is not None:
100
- data['arbol_accesible'] = tree
155
+ data['accessibility_tree'] = tree
101
156
  if output:
102
157
  with open(output, 'w', encoding='utf-8') as f:
103
158
  json.dump(data, f, ensure_ascii=False, indent=1)
104
159
  return data
105
160
 
106
161
 
107
- def diff(a, b):
162
+ _NOTE = {
163
+ 'es': ('Elementos sin id se casan por tag+nombre+href: renombrar produce '
164
+ 'eliminado+añadido, no un diff fino. Usa ids estables para trazabilidad.'),
165
+ 'en': ('Elements without ids are matched by tag+name+href: renaming shows as '
166
+ 'removed+added, not a fine-grained diff. Use stable ids for traceability.'),
167
+ }
168
+
169
+
170
+ def diff(a, b, lang='en'):
171
+ # multiset por firma: dos controles con el MISMO nombre (Edit por fila,
172
+ # botones-icono sin name) son dos elementos — un dict por clave los
173
+ # colapsaba y el diff decía «sin cambios» ante una duplicación
174
+ from collections import Counter
175
+ ca = Counter(x['key'] for x in a['elements'])
176
+ cb = Counter(x['key'] for x in b['elements'])
177
+ aniadidos = sorted((cb - ca).elements())
178
+ removed = sorted((ca - cb).elements())
108
179
  ea = {x['key']: x for x in a['elements']}
109
180
  eb = {x['key']: x for x in b['elements']}
110
- aniadidos = sorted(set(eb) - set(ea))
111
- removed = sorted(set(ea) - set(eb))
112
181
  renamed = []
113
182
  for k in set(ea) & set(eb):
114
183
  if ea[k]['name'] != eb[k]['name']:
@@ -126,8 +195,10 @@ def diff(a, b):
126
195
  # roles/nombres computados que la lista de interactivos no ve.
127
196
  tree_changed = None
128
197
  tree_diff = None
129
- if 'arbol_accesible' in a and 'arbol_accesible' in b:
130
- la, lb = a['arbol_accesible'].splitlines(), b['arbol_accesible'].splitlines()
198
+ _ta = a.get('accessibility_tree', a.get('arbol_accesible')) # clave vieja: compat
199
+ _tb = b.get('accessibility_tree', b.get('arbol_accesible'))
200
+ if _ta is not None and _tb is not None:
201
+ la, lb = _ta.splitlines(), _tb.splitlines()
131
202
  tree_changed = la != lb
132
203
  if tree_changed:
133
204
  tree_diff = [f'- {la[i]}' for i in range(min(len(la), len(lb)))
@@ -143,7 +214,7 @@ def diff(a, b):
143
214
  return {
144
215
  'ok': ok,
145
216
  'summary': {
146
- 'elements': {'before': len(ea), 'after': len(eb)},
217
+ 'elements': {'before': len(a['elements']), 'after': len(b['elements'])},
147
218
  'added': len(aniadidos), 'removed': len(removed),
148
219
  'renamed': len(renamed),
149
220
  'focus_order_changed': focus_changed or bool(focus_removed),
@@ -153,8 +224,7 @@ def diff(a, b):
153
224
  'removed': focus_removed, 'added': focus_added,
154
225
  'reordered': bool(focus_changed and not focus_removed and not focus_added)},
155
226
  'tree': {'changed': tree_changed, 'first_differences': tree_diff},
156
- 'note': ('Elementos sin id se casan por tag+nombre+href: renombrar produce '
157
- 'eliminado+añadido, no un diff fino. Usa ids estables para trazabilidad.'),
227
+ 'note': _NOTE.get(lang, _NOTE['en']),
158
228
  }
159
229
 
160
230