@kinti/a11y-toolkit 5.26.0 → 5.28.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 (45) hide show
  1. package/README.md +1 -1
  2. package/a11y_toolkit/a11y.py +30 -4
  3. package/a11y_toolkit/a11yact.py +9 -1
  4. package/a11y_toolkit/a11yannotate.py +185 -0
  5. package/a11y_toolkit/a11yaudit.py +924 -196
  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 +114 -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 +567 -97
  14. package/a11y_toolkit/a11yen301549.py +53 -1
  15. package/a11y_toolkit/a11yengines.py +157 -0
  16. package/a11y_toolkit/a11yevidence.py +81 -33
  17. package/a11y_toolkit/a11yfix.py +131 -52
  18. package/a11y_toolkit/a11ygate.py +225 -0
  19. package/a11y_toolkit/a11yinit.py +73 -7
  20. package/a11y_toolkit/a11yjourney.py +110 -4
  21. package/a11y_toolkit/a11yledger.py +119 -12
  22. package/a11y_toolkit/a11ylocate.py +247 -0
  23. package/a11y_toolkit/a11yopenacr.py +10 -3
  24. package/a11y_toolkit/a11ypatches.py +154 -0
  25. package/a11y_toolkit/a11ypatterns.py +344 -0
  26. package/a11y_toolkit/a11ypdf.py +109 -53
  27. package/a11y_toolkit/a11yrgaa.py +60 -0
  28. package/a11y_toolkit/a11yroute.py +34 -12
  29. package/a11y_toolkit/a11ysarif.py +45 -18
  30. package/a11y_toolkit/a11yscope.py +67 -15
  31. package/a11y_toolkit/a11yscroll.py +7 -5
  32. package/a11y_toolkit/a11ystatement.py +30 -6
  33. package/a11y_toolkit/a11ytrace.py +293 -0
  34. package/a11y_toolkit/a11yvalidate.py +21 -15
  35. package/a11y_toolkit/a11yvpat.py +34 -7
  36. package/a11y_toolkit/a11yvtt.py +22 -6
  37. package/a11y_toolkit/a11ywiz.py +121 -0
  38. package/a11y_toolkit/contrast.py +62 -24
  39. package/a11y_toolkit/locales/en.json +185 -20
  40. package/a11y_toolkit/locales/es.json +186 -21
  41. package/a11y_toolkit/rgaa.json +2661 -0
  42. package/a11y_toolkit/server.py +157 -54
  43. package/package.json +2 -2
  44. package/a11y_toolkit/a11yplan.py +0 -214
  45. package/a11y_toolkit/a11ywcagem.py +0 -237
@@ -38,11 +38,20 @@ def _t(lang, key):
38
38
  return T.get(lang, T['en'])[key]
39
39
 
40
40
 
41
+ # Techos anti-bomba de descompresión: por stream y ACUMULADO entre streams
42
+ # (una bomba repartida en 100 streams de 20MB no descomprime 2GB; lo que
43
+ # llegó hasta el techo basta para auditar — doctrina de lectura parcial).
44
+ _STREAM_CAP = 20_000_000 # 20 MB por stream descomprimido
45
+ _STREAM_BUDGET = 120_000_000 # 120 MB en total entre todos los streams
46
+
47
+
41
48
  def _uncompressed_streams(data, limit=60):
42
49
  """Los streams FlateDecode, descomprimidos (zlib es stdlib) — ahí viven
43
50
  el XMP, el contenido y buena parte de la estructura."""
44
- out = []
51
+ out, total = [], 0
45
52
  for m in re.finditer(rb'stream\r?\n', data):
53
+ if total >= _STREAM_BUDGET:
54
+ break # techo acumulado: dejar de inflar, auditar lo que llegó
46
55
  start = m.end()
47
56
  end = data.find(b'endstream', start)
48
57
  if end == -1:
@@ -50,14 +59,92 @@ def _uncompressed_streams(data, limit=60):
50
59
  chunk = data[start:end].rstrip(b'\r\n')
51
60
  try:
52
61
  d = zlib.decompressobj()
53
- out.append(d.decompress(chunk, 20_000_000)) # bomba: techo por stream
62
+ dec = d.decompress(chunk, _STREAM_CAP) # bomba: techo por stream
54
63
  except Exception: # noqa: BLE001
55
64
  continue
65
+ out.append(dec)
66
+ total += len(dec)
56
67
  if len(out) >= limit:
57
68
  break
58
69
  return out
59
70
 
60
71
 
72
+ # ── 1.4.3 en PDF: contraste del texto contra el fondo efectivo ──
73
+ # Parseo de la secuencia de operadores: `rg`/`g`/`k` cambian el color de
74
+ # relleno (con el que se escribe texto), `re` declara un rectángulo —
75
+ # candidato a FONDO solo si un operador de pintado (f/F/B/B*/b) lo pinta
76
+ # después, con el relleno VIGENTE —, y `Tj`/`TJ` escriben texto (TJ también
77
+ # en forma de array: `[(H) -3 (ola)] TJ`). El fondo por defecto del PDF es
78
+ # blanco si nadie lo pinta: un rect oscuro pintado antes del texto cambia
79
+ # el fondo efectivo — no acusar blanco-sobre-oscuro como bajo (el mismo bug
80
+ # que CSS var() en HTML). Los operandos de `re` NUNCA se interpretan como
81
+ # color (bug histórico: `0 0 612 792 re` se leía como triple RGB).
82
+ _RE_STREAM_OPS = re.compile(
83
+ r'(?P<r>[\d.]+)\s+(?P<g>[\d.]+)\s+(?P<b>[\d.]+)\s+rg\b' # relleno RGB
84
+ r'|(?P<gray>[\d.]+)\s+g\b' # relleno gris
85
+ r'|(?P<k1>[\d.]+)\s+(?P<k2>[\d.]+)\s+(?P<k3>[\d.]+)\s+(?P<k4>[\d.]+)\s+k\b' # relleno CMYK
86
+ r'|(?P<x1>[\d.]+)\s+(?P<y1>[\d.]+)\s+(?P<w1>[\d.]+)\s+(?P<h1>[\d.]+)\s+re\b' # rectángulo
87
+ r'|(?P<paint>\b[fFBb]\*?(?![\w*]))' # pintado del path
88
+ r'|(?P<text>\((?:[^()\\]|\\.)*\)\s*(?:Tj|TJ)|\]\s*TJ)') # texto (cadena o array)
89
+
90
+
91
+ def _l(r, g, b):
92
+ def lin(v):
93
+ v /= 255.0
94
+ return v / 12.92 if v <= 0.03928 else ((v + 0.055) / 1.055) ** 2.4
95
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
96
+
97
+
98
+ def _ratio(f, b):
99
+ l1, l2 = max(f, b), min(f, b)
100
+ return (l1 + 0.05) / (l2 + 0.05)
101
+
102
+
103
+ def _stream_low_contrast(text):
104
+ """Un content stream (ya decodificado latin-1) → lista de ejemplos
105
+ 'color sobre fondo' por debajo de 4.5:1. Escaneo secuencial
106
+ determinista de los operadores de color/pintado/texto."""
107
+ hits = []
108
+ fill = (0, 0, 0) # relleno vigente: el color con el que se escribe
109
+ bg = (255, 255, 255) # fondo efectivo: blanco salvo rect pintado
110
+ rect_pending = False # un `re` declarado, esperando su operador de pintado
111
+ for m in _RE_STREAM_OPS.finditer(text):
112
+ if m.group('r') is not None: # rg — relleno RGB
113
+ try:
114
+ fill = tuple(max(0, min(255, round(float(x) * 255)))
115
+ for x in (m.group('r'), m.group('g'), m.group('b')))
116
+ except ValueError:
117
+ pass
118
+ elif m.group('gray') is not None: # g — relleno en escala de grises
119
+ try:
120
+ v = max(0, min(255, round(float(m.group('gray')) * 255)))
121
+ fill = (v, v, v)
122
+ except ValueError:
123
+ pass
124
+ elif m.group('k1') is not None: # k — relleno CMYK (aprox. naive)
125
+ try:
126
+ c_, mm_, y_, black = (max(0.0, min(1.0, float(x))) for x in
127
+ (m.group('k1'), m.group('k2'),
128
+ m.group('k3'), m.group('k4')))
129
+ fill = tuple(max(0, min(255, round(255 * (1 - x) * (1 - black))))
130
+ for x in (c_, mm_, y_))
131
+ except ValueError:
132
+ pass
133
+ elif m.group('x1') is not None: # re — rectángulo: solo candidato a fondo
134
+ rect_pending = True # sin pintado posterior no cambia nada
135
+ elif m.group('paint') is not None: # f/F/B/B*/b — pinta el path pendiente
136
+ if rect_pending:
137
+ bg = fill # pintado con el relleno VIGENTE: ese rect es el fondo
138
+ rect_pending = False
139
+ else: # Tj / TJ — texto con el relleno vigente
140
+ ratio_ = _ratio(_l(*fill), _l(*bg))
141
+ if ratio_ < 4.5:
142
+ hits.append(f'rgb({fill[0]},{fill[1]},{fill[2]})'
143
+ f' sobre rgb({bg[0]},{bg[1]},{bg[2]})'
144
+ f' \u2192 {ratio_:.2f}:1')
145
+ return hits
146
+
147
+
61
148
  def pdf_screen(path_or_bytes, lang='en'):
62
149
  """Cribado estructural de accesibilidad de un PDF (fichero local)."""
63
150
  if isinstance(path_or_bytes, (bytes, bytearray)):
@@ -75,19 +162,33 @@ def pdf_screen(path_or_bytes, lang='en'):
75
162
  return {'error': 'not a PDF (no %PDF- marker)'}
76
163
 
77
164
  streams = _uncompressed_streams(data)
78
- todo = data + b'\n'.join(streams[:40])
165
+ # `todo` respeta el MISMO presupuesto acumulado: ensamblar 40 streams de
166
+ # 20MB sería una segunda bomba
167
+ parts, total_todo = [data], len(data)
168
+ for s in streams[:40]:
169
+ if total_todo + len(s) > _STREAM_BUDGET:
170
+ break
171
+ parts += [b'\n', s]
172
+ total_todo += len(s) + 1
173
+ todo = b''.join(parts)
79
174
 
80
175
  def present(pat):
81
176
  return re.search(pat, todo) is not None
82
177
 
83
178
  encrypted = b'/Encrypt' in data # el trailer vive al FINAL del fichero
84
- tagged = present(rb'/StructTreeRoot\s+\d+\s+0\s+R') or present(rb'/StructTreeRoot')
179
+ # tagged: la forma canónica es la referencia del catálogo (/StructTreeRoot
180
+ # N 0 R). Una mención suelta (p. ej. dentro de un content stream) solo
181
+ # cuenta como estructura cuando el documento además declara /Marked true.
85
182
  marked = present(rb'/Marked\s+true')
183
+ tagged = present(rb'/StructTreeRoot\s+\d+\s+0\s+R') or \
184
+ (marked and present(rb'/StructTreeRoot'))
86
185
  lang_doc = re.search(rb'/Lang\s*\(([^)]{2,20})\)', todo)
87
186
  title_meta = re.search(rb'/Title\s*\(([^)]{1,300})\)', todo) or \
88
187
  re.search(rb'<dc:title>.{0,200}?<rdf:li[^>]*>([^<]{1,300})</rdf:li>', todo, re.S)
89
188
  n_pages = len(re.findall(rb'/Type\s*/Page[^s]', todo))
90
- n_alt = len(re.findall(rb'/Alt\s*\(', todo))
189
+ # /Alt acepta literal (/Alt (…)) y hex (/Alt <FEFF…>, la forma natural
190
+ # UTF-16BE para alt no latino) — misma paridad que /TU
191
+ n_alt = len(re.findall(rb'/Alt\s*[<(]', todo))
91
192
  n_actual = len(re.findall(rb'/ActualText', todo))
92
193
  n_imgs = len(re.findall(rb'/Subtype\s*/Image', todo))
93
194
  n_outline = len(re.findall(rb'/Outlines\s+\d+\s+0\s+R', todo))
@@ -100,56 +201,11 @@ def pdf_screen(path_or_bytes, lang='en'):
100
201
  findings = []
101
202
 
102
203
  # ── 1.4.3 en PDF: contraste del texto contra el fondo efectivo ──
103
- # Parseo de la secuencia: `rg` cambia el color de relleno de texto,
104
- # `re` + `f` pinta un rectángulo (fondo), `Tj`/`TJ` escriben texto.
105
- # El fondo por defecto del PDF es blanco si nadie lo pinta. Si un rect
106
- # oscuro precede al texto, el fondo efectivo es ese fill — no acusar
107
- # blanco-sobre-oscuro como bajo (el mismo bug que CSS var() en HTML).
108
- def _l(r, g, b):
109
- def lin(v):
110
- v /= 255.0
111
- return v / 12.92 if v <= 0.03928 else ((v + 0.055) / 1.055) ** 2.4
112
- return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
113
-
114
- def _ratio(f, b):
115
- l1, l2 = max(f, b), min(f, b)
116
- return (l1 + 0.05) / (l2 + 0.05)
117
-
118
- blanc = _l(255, 255, 255)
119
204
  low_hits = []
120
205
  for stream in streams:
121
- text = stream.decode('latin-1', 'replace')
122
- text_color = (0, 0, 0)
123
- bg_color = (255, 255, 255) # el PDF no pinta fondo por defecto
124
- painted_bg = False
125
- for m in re.finditer(
126
- r'([\d.]+)\s+([\d.]+)\s+([\d.]+)\s+(rg|re)\b'
127
- r'|\b(f)\b'
128
- r'|\((?:[^()\\]|\\.)*\)\s*(Tj|TJ)'
129
- , text):
130
- op = m.group(4) or m.group(5) or m.group(6)
131
- if op in ('rg', 're'):
132
- try:
133
- text_color = tuple(
134
- max(0, min(255, round(float(x) * 255)))
135
- for x in m.groups()[:3])
136
- except ValueError:
137
- pass
138
- if op == 're':
139
- # el rect se pinta con el fill actual: es el FONDO
140
- bg_color = text_color
141
- elif op == 'f':
142
- pass # el f pinta con el fill ya establecido (fondo ya guardado)
143
- else: # Tj / TJ
144
- lt = _l(*text_color)
145
- lb = _l(*bg_color)
146
- ratio = _ratio(lt, lb)
147
- if ratio < 4.5:
148
- ej = (f'rgb({text_color[0]},{text_color[1]},{text_color[2]})'
149
- f' sobre rgb({bg_color[0]},{bg_color[1]},{bg_color[2]})'
150
- f' \u2192 {ratio:.2f}:1')
151
- if ej not in [x.split(' \u2014 ')[0] for x in low_hits]:
152
- low_hits.append(ej)
206
+ for ej in _stream_low_contrast(stream.decode('latin-1', 'replace')):
207
+ if ej not in low_hits:
208
+ low_hits.append(ej)
153
209
  if len(low_hits) >= 4:
154
210
  break
155
211
  if low_hits:
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env python3
2
+ """RGAA 4.1 — the French legal standard as data.
3
+
4
+ Generated by scripts/rgaa_ingest.py from the OFFICIAL government JSON
5
+ (github.com/DISIC/accessibilite.numerique.gouv.fr — open data, 106/106
6
+ criteria with a mechanical bridge to WCAG SC). This module is the thin
7
+ loader + the lookup surfaces other modules use; never hand-edit the JSON.
8
+
9
+ The RGAA has its own numbering (1.1–13.12 across 13 topics) and NO A/AA
10
+ levels — every criterion is conformant / not conformant. Titles and tests
11
+ are French (the standard's language); the WCAG bridge lives in each
12
+ criterion's `wcag` list.
13
+ """
14
+
15
+ import json
16
+ import os
17
+
18
+ _HERE = os.path.dirname(os.path.abspath(__file__))
19
+
20
+ with open(os.path.join(_HERE, 'rgaa.json'), encoding='utf-8') as _f:
21
+ _DATA = json.load(_f)
22
+
23
+ STANDARD_NAME = 'RGAA 4.1 (France)'
24
+ VERSION = _DATA['version']
25
+ WCAG_BASE = _DATA['wcag_base']
26
+ SOURCE = _DATA['source']
27
+ TOPICS = [(t['number'], t['name']) for t in _DATA['topics']]
28
+ CRITERIA = _DATA['criteria'] # 106: {num, topic, number, title, tests, notes, wcag}
29
+
30
+ # índice inverso: WCAG SC code → [números RGAA] (el puente mecánico)
31
+ _BY_SC = {}
32
+ for _c in CRITERIA:
33
+ for _w in _c['wcag']:
34
+ _sc = _w.split(' ')[0]
35
+ _BY_SC.setdefault(_sc, []).append(_c['num'])
36
+
37
+
38
+ def rgaa_for_sc(sc_code):
39
+ """'1.1.1' → ['1.1', …]: los criterios RGAA que verifican ese SC.
40
+ Devuelve [] si ningún criterio RGAA lo referencia."""
41
+ return list(_BY_SC.get(sc_code, []))
42
+
43
+
44
+ def criterion(num):
45
+ """'1.1' → el criterio completo, o None."""
46
+ return next((c for c in CRITERIA if c['num'] == num), None)
47
+
48
+
49
+ def standard_block(lang='en'):
50
+ """Bloque 'standard' para informes audit --standard rgaa."""
51
+ names = {'en': 'RGAA 4.1 — the French web accessibility framework',
52
+ 'es': 'RGAA 4.1 — el marco francés de accesibilidad web'}
53
+ return {
54
+ 'name': names.get(lang) or names['en'],
55
+ 'version': VERSION,
56
+ 'topics': len(TOPICS),
57
+ 'criteria': len(CRITERIA),
58
+ 'wcag_base': WCAG_BASE,
59
+ 'source': SOURCE,
60
+ }
@@ -105,8 +105,12 @@ ROUTES = [
105
105
  'cli': 'a11ytoolkit kbd https://…',
106
106
  'prompts': []},
107
107
  {'id': 'statement',
108
+ # 'document' lives HERE, not in the pdf route: the English verb ("document
109
+ # the accessibility of my site") is a statement goal; pdf keywords stay
110
+ # unambiguous (pdf/docx/word/'documento')
108
111
  'patterns': ['statement', 'declaración', 'declaracion', 'eaa', 'ley',
109
- 'legal', 'rd 1112', 'acta', '11/2023', 'compliance doc'],
112
+ 'legal', 'rd 1112', 'acta', '11/2023', 'compliance doc',
113
+ 'document'],
110
114
  'tools': [
111
115
  ('a11y_audit_url', 'los hallazgos alimentan la lista de contenido no accesible',
112
116
  'findings feed the non-accessible content list'),
@@ -142,7 +146,7 @@ ROUTES = [
142
146
  'cli': 'a11ytoolkit vpat pack.json --product "Acme" -o vpat.html',
143
147
  'prompts': []},
144
148
  {'id': 'media',
145
- 'patterns': ['video', 'caption', 'subtítulo', 'subtitulo', 'subtitulo',
149
+ 'patterns': ['video', 'caption', 'subtítulo', 'subtitulo',
146
150
  'vtt', 'audio description', 'audiodescripción', 'podcast'],
147
151
  'tools': [
148
152
  ('a11y_vtt_check', 'el CONTENIDO de los subtítulos: cps, solapes, cobertura',
@@ -152,7 +156,7 @@ ROUTES = [
152
156
  ],
153
157
  'cli': None, 'prompts': []},
154
158
  {'id': 'pdf',
155
- 'patterns': ['pdf', 'documento', 'document', 'docx', 'word', 'informe pdf'],
159
+ 'patterns': ['pdf', 'documento', 'docx', 'word', 'informe pdf'],
156
160
  'tools': [
157
161
  ('a11y_audit_pdf', 'cribado estructural + formularios: lo que nadie automatiza',
158
162
  'structural screening + forms: what nobody automates'),
@@ -233,39 +237,55 @@ _NOTE = {
233
237
  # ── diagnóstico secuencial: la EVIDENCIA manda, la severidad solo desempata ──
234
238
  # Traducción cruzada del diagnóstico diferencial (medicina): primero la
235
239
  # constante vital barata —el pase estático— y sus síntomas deciden qué
236
- # examen reduce más la incertidumbre. No es una prioridad fija de criterios:
240
+ # examen reduce más la incertumbre. No es una prioridad fija de criterios:
237
241
  # una página sin formularios no necesita el examen de formularios por muy
238
242
  # grave que sea 3.3.1 sobre el papel. detect() devuelve None (síntoma
239
- # ausente) o la evidencia en una línea.
243
+ # ausente) o el dato crudo; la línea de evidencia se redacta por idioma
244
+ # con _DIAG_EV (antes llegaba siempre en inglés, también con lang='es').
240
245
  _DIAG = [
241
246
  {'id': 'forms', 'severity': 'high', 'tool': 'a11y_forms',
242
247
  # ojo: sin \b dentro de las llaves del f-string (barra invertida DENTRO
243
248
  # de llaves es SyntaxError antes de 3.12; el guardián de test_solido lo
244
249
  # vigila) — la detección con \b vive en el re.search de fuera
245
- 'detect': lambda h: (f'{len(re.findall(r"<(?:input|select|textarea)", h))} form fields'
250
+ 'detect': lambda h: (len(re.findall(r"<(?:input|select|textarea)", h))
246
251
  if re.search(r'<(?:input|select|textarea)\b', h) else None),
247
252
  'why': ('formularios presentes: rellenar inválido, enviar y juzgar el aviso de errores',
248
253
  'forms present: fill invalid data, submit, judge the error announcement')},
249
254
  {'id': 'menus', 'severity': 'high', 'tool': 'a11y_keyboard',
250
- 'detect': lambda h: ('menus or disclosure widgets'
255
+ 'detect': lambda h: (True
251
256
  if re.search(r'<(?:nav|details)\b|aria-expanded', h) else None),
252
257
  'why': ('menús o desplegables: la zona clásica de trampas de teclado',
253
258
  'menus or disclosure widgets: the classic keyboard-trap zone')},
254
259
  {'id': 'video', 'severity': 'medium', 'tool': 'a11y_vtt_check',
255
- 'detect': lambda h: (f'{h.count("<video")} <video>' if '<video' in h else None),
260
+ 'detect': lambda h: (h.count('<video') if '<video' in h else None),
256
261
  'why': ('vídeo presente: que existan subtítulos no basta — juzgar su CONTENIDO',
257
262
  'video present: captions existing is not enough — judge their CONTENT')},
258
263
  {'id': 'animation', 'severity': 'medium', 'tool': 'a11y_reduced_motion',
259
- 'detect': lambda h: ('animated content'
264
+ 'detect': lambda h: (True
260
265
  if re.search(r'animation|transition|<marquee', h) else None),
261
266
  'why': ('contenido animado: ¿respeta prefers-reduced-motion?',
262
267
  'animated content: does it honor prefers-reduced-motion?')},
263
268
  {'id': 'svg', 'severity': 'low', 'tool': 'a11y_forced_colors',
264
- 'detect': lambda h: (f'{h.count("<svg")} inline <svg>' if h.count('<svg') >= 2 else None),
269
+ 'detect': lambda h: (h.count('<svg') if h.count('<svg') >= 2 else None),
265
270
  'why': ('iconografía SVG en volumen: los fills fijos caen en forced-colors',
266
271
  'SVG iconography at volume: hardcoded fills fall in forced-colors')},
267
272
  ]
268
273
 
274
+ # evidencia por síntoma e idioma: {n} recibe el dato crudo de detect()
275
+ _DIAG_EV = {
276
+ 'forms': {'es': '{n} campos de formulario', 'en': '{n} form fields'},
277
+ 'menus': {'es': 'menús o desplegables', 'en': 'menus or disclosure widgets'},
278
+ 'video': {'es': '{n} <video>', 'en': '{n} <video>'},
279
+ 'animation': {'es': 'contenido animado', 'en': 'animated content'},
280
+ 'svg': {'es': '{n} <svg> inline', 'en': '{n} inline <svg>'},
281
+ }
282
+
283
+
284
+ def _evidence(sid, raw, lang):
285
+ """La línea de evidencia de un síntoma, en el idioma pedido."""
286
+ tpl = _DIAG_EV[sid]['es' if lang == 'es' else 'en']
287
+ return tpl.format(n=raw) if isinstance(raw, int) else tpl
288
+
269
289
  _RANK = {'high': 0, 'medium': 1, 'low': 2}
270
290
 
271
291
  _GUARANTEE = {
@@ -291,7 +311,8 @@ def diagnose(html_text, url='(html)', lang='en', goal=None):
291
311
  for d in _DIAG:
292
312
  ev = d['detect'](html_text)
293
313
  if ev:
294
- symptoms.append({'symptom': d['id'], 'evidence': ev})
314
+ symptoms.append({'symptom': d['id'],
315
+ 'evidence': _evidence(d['id'], ev, t)})
295
316
  hit.append(d)
296
317
  # sort estable: severidad como desempate, orden de tabla dentro de cada nivel
297
318
  hit.sort(key=lambda d: _RANK[d['severity']])
@@ -301,7 +322,8 @@ def diagnose(html_text, url='(html)', lang='en', goal=None):
301
322
  evidences = {d['id']: d['detect'](html_text) for d in _DIAG}
302
323
  for i, d in enumerate(hit, 2):
303
324
  steps.append({'step': i, 'tool': d['tool'], 'why': d['why'][idx],
304
- 'symptom': d['id'], 'evidence': evidences[d['id']]})
325
+ 'symptom': d['id'],
326
+ 'evidence': _evidence(d['id'], evidences[d['id']], t)})
305
327
  steps.append({'step': len(steps) + 1, 'tool': 'a11y_audit_dom',
306
328
  'why': ('profundizar lo que el estático no ve: contraste computado, 2.5.8, foco',
307
329
  'deepen what static cannot see: computed contrast, 2.5.8, focus')[idx]})
@@ -17,6 +17,7 @@ CLI:
17
17
  import argparse
18
18
  import json
19
19
 
20
+ from .a11yact import _NOT_DEAD
20
21
  from .a11yaudit import normalize_signal # noqa: E402 (compat 5.10)
21
22
  import sys
22
23
 
@@ -55,28 +56,48 @@ def _help_uri(criterion_text):
55
56
  return _BASE + slug if slug else 'https://www.w3.org/TR/WCAG22/'
56
57
 
57
58
 
58
- def from_report(report, driver_version='3.2.0', standard=None, target=None):
59
+ def from_report(report, driver_version=None, standard=None, target=None):
59
60
  """Informe(s) del auditor → dict SARIF 2.1.0.
60
61
 
61
62
  Acepta un informe individual (audit_html/audit_url) o uno 'site'
62
63
  (con la lista 'reports'). Con standard='en301549' cada regla gana
63
64
  properties/tags con su cláusula EN 301 549 V4.1.1 (9.x web por defecto,
64
65
  10.x documents, 11.x software) — filtrable en code scanning."""
66
+ if driver_version is None:
67
+ # versión del driver = fuente única (estaba congelada en '3.2.0' con el
68
+ # motor en 5.26: GitHub mostraba una versión muerta en code scanning)
69
+ from .server import VERSION as _V # lazy: server importa este módulo
70
+ driver_version = _V
65
71
  from . import a11yen301549 as _enstd
66
- pages = report.get('reports') if 'reports' in report else [report]
72
+ pages = report.get('reports') if isinstance(report.get('reports'), list) else [report]
67
73
  rules = {}
68
74
  results = []
75
+ skipped = 0 # hallazgos truncados/hostiles: se saltan, jamás un KeyError
69
76
  _tgt = target or _enstd.target_for_mode(report.get('mode', 'static'))
70
77
  for pg in pages:
78
+ if not isinstance(pg, dict):
79
+ skipped += 1
80
+ continue
71
81
  url = pg.get('url', '(html)')
72
- for h in pg.get('findings', []):
73
- code = h['criterion'].split(' ')[0]
82
+ for h in pg.get('findings', []) or []:
83
+ if not isinstance(h, dict):
84
+ skipped += 1
85
+ continue
86
+ if h.get('status') in _NOT_DEAD or h.get('disprover_status') in _NOT_DEAD:
87
+ # hallazgo muerto (disprover rejected / not-rechecked): no es
88
+ # evidencia y no navega a GitHub como alerta viva
89
+ continue
90
+ crit, issue = h.get('criterion'), h.get('issue')
91
+ if not isinstance(crit, str) or not isinstance(issue, str):
92
+ skipped += 1
93
+ continue # --from-audit hostil/truncado: degradar, no caer
94
+ code = crit.split(' ')[0]
74
95
  rule_id = f'WCAG-{code}-{normalize_signal(h.get("signal", ""))}'
75
96
  if rule_id not in rules:
76
97
  rule = {
77
98
  'id': rule_id,
78
- 'shortDescription': {'text': h['criterion']},
79
- 'helpUri': _help_uri(h['criterion']),
99
+ 'shortDescription': {'text': crit},
100
+ 'helpUri': _help_uri(crit),
80
101
  }
81
102
  # target explícito = mandato del usuario: recalcula SIEMPRE
82
103
  # (las cláusulas embebidas pueden ser de otro target); sin
@@ -90,12 +111,12 @@ def from_report(report, driver_version='3.2.0', standard=None, target=None):
90
111
  'tags': [f'en301549:{clause}', 'wcag22:' + code],
91
112
  }
92
113
  rules[rule_id] = rule
93
- message = h['issue']
114
+ message = issue
94
115
  if h.get('remediation'):
95
- message += ' — Fix: ' + h['remediation']
116
+ message += ' — Fix: ' + str(h['remediation'])
96
117
  results.append({
97
118
  'ruleId': rule_id,
98
- 'level': LEVEL.get(h['severity'], 'note'),
119
+ 'level': LEVEL.get(h.get('severity'), 'note'),
99
120
  'message': {'text': message},
100
121
  'locations': [{
101
122
  'physicalLocation': {
@@ -103,18 +124,22 @@ def from_report(report, driver_version='3.2.0', standard=None, target=None):
103
124
  },
104
125
  }],
105
126
  })
127
+ run = {
128
+ 'tool': {'driver': {
129
+ 'name': 'a11y-toolkit',
130
+ 'version': driver_version,
131
+ 'informationUri': 'https://github.com/kinti/a11y-toolkit',
132
+ 'rules': sorted(rules.values(), key=lambda r: r['id']),
133
+ }},
134
+ 'results': results,
135
+ }
136
+ if skipped:
137
+ # exportación degradada, no silenciada: lo saltado queda contado
138
+ run['properties'] = {'skippedFindings': skipped}
106
139
  return {
107
140
  '$schema': 'https://json.schemastore.org/sarif-2.1.0.json',
108
141
  'version': '2.1.0',
109
- 'runs': [{
110
- 'tool': {'driver': {
111
- 'name': 'a11y-toolkit',
112
- 'version': driver_version,
113
- 'informationUri': 'https://github.com/kinti/a11y-toolkit',
114
- 'rules': sorted(rules.values(), key=lambda r: r['id']),
115
- }},
116
- 'results': results,
117
- }],
142
+ 'runs': [run],
118
143
  }
119
144
 
120
145
 
@@ -152,6 +177,8 @@ def main(argv):
152
177
  summary = report.get('summary', {'high': 0, 'medium': 0, 'low': 0})
153
178
  print(json.dumps({'sarif': a.out,
154
179
  'results': len(sarif['runs'][0]['results']),
180
+ 'skipped': sarif['runs'][0].get('properties', {})
181
+ .get('skippedFindings', 0),
155
182
  'score': report.get('score'),
156
183
  'summary': summary}))
157
184
  return 0
@@ -32,7 +32,7 @@ import json
32
32
  import sys
33
33
  from datetime import datetime, timezone
34
34
 
35
- STANDARDS = ('wcag22', 'en301549')
35
+ STANDARDS = ('wcag22', 'en301549', 'rgaa') # 508 GSA tree: capa privada pro
36
36
  STATUS_ORDER = ('in-scope', 'proposed-excluded', 'excluded')
37
37
 
38
38
  # Criterios cuya aplicabilidad depende de un rasgo ESTRUCTURAL detectable:
@@ -100,7 +100,7 @@ def _forms_present(feats, findings_codes):
100
100
 
101
101
 
102
102
  def build_scope(reports, standard='wcag22', target='web', answers=None,
103
- lang='en'):
103
+ lang='en', targets=None):
104
104
  """Informes (lista de dicts) + respuestas humanas → alcance a11y-scope/1."""
105
105
  if standard not in STANDARDS:
106
106
  raise ValueError(f"standard must be one of {STANDARDS}, got {standard!r}")
@@ -109,6 +109,10 @@ def build_scope(reports, standard='wcag22', target='web', answers=None,
109
109
  from .a11ycrit import _C
110
110
  tx = pack(lang).get('scope', {}) or {}
111
111
 
112
+ if targets:
113
+ targets = [x for x in targets if x in ('web', 'documents', 'software')] or [target]
114
+ else:
115
+ targets = [target]
112
116
  reports = [r for r in reports if isinstance(r, dict)]
113
117
  findings_codes = set()
114
118
  for rep in reports:
@@ -136,7 +140,9 @@ def build_scope(reports, standard='wcag22', target='web', answers=None,
136
140
  name = (_C[code][1].get(lang) or _C[code][1]['en'])[0]
137
141
  row = {'criterion': f'{code} {name}', 'level': _C[code][0]}
138
142
  if standard == 'en301549':
139
- row['clause'] = enstd.clause_for(code, target)
143
+ row['clause'] = enstd.clause_for(code, targets[0])
144
+ if len(targets) > 1:
145
+ row['clauses'] = {tg: enstd.clause_for(code, tg) for tg in targets}
140
146
 
141
147
  ans = answers.get(code)
142
148
  if isinstance(ans, str): # abreviatura: "excluded"/"in-scope"
@@ -171,6 +177,32 @@ def build_scope(reports, standard='wcag22', target='web', answers=None,
171
177
  row['evidence'] = tx.get('evidence_forms_present')
172
178
  criteria.append(row)
173
179
 
180
+ if standard == 'rgaa':
181
+ from . import a11yrgaa
182
+ criteria = [{'criterion': c['num'] + ' ' + c['title'],
183
+ 'status': 'in-scope'} for c in a11yrgaa.CRITERIA]
184
+ # las respuestas humanas también aplican a RGAA (antes se descartaban:
185
+ # counters.excluded siempre 0). La máquina NUNCA propone en rgaa —
186
+ # solo una respuesta humana mueve filas. La clave puede venir como el
187
+ # num exacto ('1.1') o con cola de test ('1.1.1'): el num de la fila
188
+ # es el prefijo — el match con separador evita 1.1 vs 1.10.
189
+ for key, ans in answers.items():
190
+ if not isinstance(key, str):
191
+ continue
192
+ a = {'status': ans} if isinstance(ans, str) else (
193
+ ans if isinstance(ans, dict) else None)
194
+ if not a or a.get('status') not in STATUS_ORDER:
195
+ continue
196
+ for row in criteria:
197
+ num = row['criterion'].split(' ')[0]
198
+ if key == num or key.startswith(num + '.'):
199
+ row['status'] = a['status']
200
+ row['evidence_source'] = 'human'
201
+ if a.get('reason'):
202
+ row['reason'] = str(a['reason'])[:500]
203
+
204
+ std508_block = None # 508 GSA tree: moved to the private pro layer
205
+
174
206
  counters = {
175
207
  'criteria': len(criteria),
176
208
  'in_scope': sum(1 for r in criteria if r['status'] == 'in-scope'),
@@ -184,11 +216,14 @@ def build_scope(reports, standard='wcag22', target='web', answers=None,
184
216
  counters['en_clauses_applicable'] = counters['in_scope'] + counters['excluded']
185
217
 
186
218
  scope = {
219
+ 'section508': std508_block,
187
220
  'format': 'a11y-scope/1',
188
221
  'lang': lang,
189
222
  'generated': datetime.now(timezone.utc).isoformat(timespec='seconds'),
190
223
  'tool': 'a11y-toolkit (github.com/kinti/a11y-toolkit)',
191
- 'standard': enstd.STANDARD_NAME if standard == 'en301549' else 'WCAG 2.2 (A/AA)',
224
+ 'standard': (enstd.STANDARD_NAME if standard == 'en301549'
225
+ else a11yrgaa.STANDARD_NAME if standard == 'rgaa'
226
+ else 'WCAG 2.2 (A/AA)'),
192
227
  'target': target,
193
228
  'features_observed': feats if features_seen else None,
194
229
  'features_evidence': bool(features_seen),
@@ -201,16 +236,29 @@ def build_scope(reports, standard='wcag22', target='web', answers=None,
201
236
  if standard == 'en301549':
202
237
  fam_rows = []
203
238
  for fam in enstd.family_rows(lang):
204
- status = 'human-review'
205
- if fam['family'] in ('6', '7', '8') and target == 'web':
206
- # un producto web no lleva RTT/transmisión de vídeo/hardware:
207
- # propuesta de la MISMA lógica que usa el wizard oficial
208
- status = 'proposed-excluded'
209
- if fam['family'] == '12':
210
- status = 'in-scope'
211
- fam_rows.append({**fam, 'status': status,
212
- 'evaluated_by_toolkit': False})
239
+ def _status_for(tg):
240
+ if fam['family'] == '12':
241
+ return 'in-scope'
242
+ if fam['family'] in ('6', '7', '8') and tg == 'web':
243
+ # un producto web no lleva RTT/transmisión de vídeo/hardware:
244
+ # propuesta de la MISMA lógica que usa el wizard oficial
245
+ return 'proposed-excluded'
246
+ return 'human-review'
247
+ status = _status_for(targets[0])
248
+ row_f = {**fam, 'status': status,
249
+ 'evaluated_by_toolkit': False}
250
+ if len(targets) > 1:
251
+ row_f['status_per_target'] = {tg: _status_for(tg) for tg in targets}
252
+ fam_rows.append(row_f)
213
253
  scope['en301549_families'] = fam_rows
254
+ if 'software' in targets:
255
+ # cláusulas EN-only de la cláusula 11 (11.5-11.7): aplicabilidad
256
+ # honesta que este motor NO evalúa — revisión humana, jamás una
257
+ # propuesta (la forma del producto NO las decide, a diferencia de
258
+ # 6/7/8 en web) y jamás un claim de conformidad
259
+ scope['en301549_software_clauses'] = [
260
+ {**row, 'status': 'human-review', 'evaluated_by_toolkit': False}
261
+ for row in enstd.software_clause_rows(lang)]
214
262
  # el sello excluye el reloj: re-emitir el mismo alcance → mismo sha
215
263
  scope['sha256'] = _sha256({k: v for k, v in scope.items() if k != 'generated'})
216
264
  return scope
@@ -228,11 +276,15 @@ def main(argv):
228
276
  '{"1.2.4": {"status": "excluded", "reason": "…"}}')
229
277
  ap.add_argument('--lang', default='en', choices=('es', 'en'))
230
278
  ap.add_argument('-o', '--out', default='scope.json')
279
+ ap.add_argument('--targets', default=None,
280
+ help='comma-separated ICT targets for combined scope (e.g. web,documents)')
281
+ # (--solicitation se retiró: el generador de anexos vive en a11y-toolkit-pro)
231
282
  a = ap.parse_args(argv)
232
- reports = [json.load(open(f, encoding='utf-8')) for f in a.reports]
283
+ reports = [json.load(open(r, encoding='utf-8')) for r in a.reports]
233
284
  answers = json.load(open(a.answers, encoding='utf-8')) if a.answers else None
285
+ tgts = [t.strip() for t in a.targets.split(',')] if a.targets else None
234
286
  scope = build_scope(reports, standard=a.standard, target=a.target,
235
- answers=answers, lang=a.lang)
287
+ answers=answers, lang=a.lang, targets=tgts)
236
288
  with open(a.out, 'w', encoding='utf-8') as f:
237
289
  json.dump(scope, f, ensure_ascii=False, indent=1)
238
290
  print(json.dumps({'scope': a.out, 'sha256': scope['sha256'],