@kinti/a11y-toolkit 5.35.3 → 5.35.4
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.
- package/a11y_toolkit/a11y.py +1 -0
- package/a11y_toolkit/a11yaudit.py +59 -2
- package/a11y_toolkit/a11ybudget.py +114 -28
- package/a11y_toolkit/a11ydiff.py +6 -1
- package/a11y_toolkit/a11ydisprove.py +36 -8
- package/a11y_toolkit/a11ydocx.py +7 -1
- package/a11y_toolkit/a11ydom.py +175 -8
- package/a11y_toolkit/a11yfix.py +15 -3
- package/a11y_toolkit/a11ygate.py +71 -16
- package/a11y_toolkit/a11ypatches.py +8 -0
- package/a11y_toolkit/a11yscroll.py +4 -2
- package/a11y_toolkit/locales/en.json +1 -1
- package/a11y_toolkit/locales/es.json +2 -2
- package/a11y_toolkit/server.py +1 -1
- package/package.json +1 -1
package/a11y_toolkit/a11y.py
CHANGED
|
@@ -127,6 +127,7 @@ SUBCOMMANDS = {
|
|
|
127
127
|
'locate': (a11ylocate, None),
|
|
128
128
|
'patches': (a11ypatches, None),
|
|
129
129
|
'guard': (a11ygate, None),
|
|
130
|
+
'guard-hook': (a11ygate, 'hook_main'), # the command `init` installs
|
|
130
131
|
'engines': (a11yengines, None),
|
|
131
132
|
'trace': (a11ytrace, None),
|
|
132
133
|
'patterns': (a11ypatterns, None),
|
|
@@ -65,6 +65,35 @@ def path_segment(tag, nth):
|
|
|
65
65
|
return f'{tag}:nth-of-type({nth})'
|
|
66
66
|
|
|
67
67
|
|
|
68
|
+
_CSS_IDENT = re.compile(r'^[A-Za-z][A-Za-z0-9_-]*$')
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _css_string(value):
|
|
72
|
+
"""Valor entre comillas CSS (selector válido para cualquier atributo)."""
|
|
73
|
+
return '"' + value.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\a ') + '"'
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _stable_anchor(attrs):
|
|
77
|
+
"""Selector ESTABLE de un elemento cuando lo tiene — id, data-testid o un
|
|
78
|
+
nombre ARIA (aria-label / aria-labelledby) —; None si solo cabe
|
|
79
|
+
identificarlo por posición. No sustituye a `paths` (la ruta determinista
|
|
80
|
+
tag:nth-of-type que comparten annotate/locate): la acompaña para quien
|
|
81
|
+
necesite una identidad que sobreviva a insertar un hermano delante, como
|
|
82
|
+
el presupuesto (revisión 2026-11-25). Degradación honesta: sin atributo
|
|
83
|
+
estable no se inventa nada."""
|
|
84
|
+
value = (attrs.get('id') or '').strip()
|
|
85
|
+
if value:
|
|
86
|
+
return '#' + value if _CSS_IDENT.match(value) else '[id=' + _css_string(value) + ']'
|
|
87
|
+
value = (attrs.get('data-testid') or '').strip()
|
|
88
|
+
if value:
|
|
89
|
+
return '[data-testid=' + _css_string(value) + ']'
|
|
90
|
+
for name in ('aria-label', 'aria-labelledby'):
|
|
91
|
+
value = (attrs.get(name) or '').strip()
|
|
92
|
+
if value:
|
|
93
|
+
return '[' + name + '=' + _css_string(value) + ']'
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
|
|
68
97
|
class _ElementPaths:
|
|
69
98
|
"""Store one segment and parent index per distinct route."""
|
|
70
99
|
|
|
@@ -513,6 +542,7 @@ class _Auditor(HTMLParser):
|
|
|
513
542
|
# resolver la ruta de LO QUE COGIERON sin cambiar sus tuplas.
|
|
514
543
|
self._paths = _ElementPaths()
|
|
515
544
|
self._elem_paths = {} # id(attrs) → índice de ruta
|
|
545
|
+
self._path_anchors = {} # ruta posicional → selector estable (si lo tiene)
|
|
516
546
|
super().__init__(convert_charrefs=True)
|
|
517
547
|
self.imgs_no_alt = []
|
|
518
548
|
self.alt_quality_bad = [] # (razón, alt, attrs) — emitida en findings
|
|
@@ -841,6 +871,9 @@ class _Auditor(HTMLParser):
|
|
|
841
871
|
for _sp in self._stray_pend:
|
|
842
872
|
_sp[3] = True
|
|
843
873
|
self._elem_paths[id(a)] = self._paths.start(tag)
|
|
874
|
+
anchor = _stable_anchor(a)
|
|
875
|
+
if anchor:
|
|
876
|
+
self._path_anchors[self._paths.format(self._elem_paths[id(a)])] = anchor
|
|
844
877
|
# rasgos estructurales para el scope de aplicabilidad (a11yscope):
|
|
845
878
|
# evidencia POSITIVA — cero <video> habilita proponer 1.2.x como no
|
|
846
879
|
# aplicable; la ausencia de señal jamás cuenta como ausencia de
|
|
@@ -2327,6 +2360,11 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
|
|
|
2327
2360
|
paths = fmt.pop('paths', None)
|
|
2328
2361
|
if paths:
|
|
2329
2362
|
h['paths'] = paths[:5]
|
|
2363
|
+
anchors = [p._path_anchors.get(path) for path in h['paths']]
|
|
2364
|
+
if any(anchors):
|
|
2365
|
+
# alineada con `paths` (null = el elemento no tiene atributo
|
|
2366
|
+
# estable): identidad que sobrevive a insertar un hermano delante
|
|
2367
|
+
h['stable_paths'] = anchors
|
|
2330
2368
|
findings.append(h)
|
|
2331
2369
|
|
|
2332
2370
|
def add_ej(severity, code, key_msg, examples, **fmt):
|
|
@@ -2942,7 +2980,16 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None, *, requi
|
|
|
2942
2980
|
while len(data) < ceiling + 1:
|
|
2943
2981
|
if time.monotonic() >= read_deadline:
|
|
2944
2982
|
if complete:
|
|
2945
|
-
|
|
2983
|
+
# Cuerpo COMPLETO que tardó ≠ cuerpo truncado: si los bytes
|
|
2984
|
+
# recibidos cuadran con Content-Length (length llega a 0) o
|
|
2985
|
+
# el flujo terminó bien, se acepta; solo lo incompleto es error
|
|
2986
|
+
length = getattr(r, 'length', None)
|
|
2987
|
+
try:
|
|
2988
|
+
finished = length == 0 if length is not None else r.read(1) == b''
|
|
2989
|
+
except Exception: # noqa: BLE001 — estancado a medio cuerpo
|
|
2990
|
+
finished = False
|
|
2991
|
+
if not finished:
|
|
2992
|
+
raise _FetchError('err_incomplete_html')
|
|
2946
2993
|
break
|
|
2947
2994
|
chunk = r.read(min(65536, ceiling + 1 - len(data)))
|
|
2948
2995
|
if not chunk:
|
|
@@ -3181,10 +3228,19 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
|
|
|
3181
3228
|
# discovery: sitemap first (WCAG-EM's enumeration), links as fallback
|
|
3182
3229
|
urls_sm = _urls_sitemap(url, timeout=timeout) if from_sitemap else []
|
|
3183
3230
|
queue = urls_sm or _internal_links(html_text, entry_final, url)
|
|
3184
|
-
|
|
3231
|
+
# Las URLs FALLIDAS no gastan el presupuesto de páginas (con cupo de 5
|
|
3232
|
+
# solo se medían tres y se despreciaba una buena): el cupo lo consumen las
|
|
3233
|
+
# medidas. Para que un sitemap de enlaces muertos no corretee sin fin, los
|
|
3234
|
+
# fallos tienen su propio techo — y el informe lo dice
|
|
3235
|
+
failed_cap = 2 * max_pages
|
|
3236
|
+
failed_pages_capped = False
|
|
3237
|
+
while queue and len(reports) < max_pages:
|
|
3185
3238
|
if deadline is not None and time.monotonic() >= deadline:
|
|
3186
3239
|
budget_exhausted = True
|
|
3187
3240
|
break
|
|
3241
|
+
if len(page_errors) >= failed_cap:
|
|
3242
|
+
failed_pages_capped = True
|
|
3243
|
+
break
|
|
3188
3244
|
next = queue.pop(0)
|
|
3189
3245
|
if next in seen:
|
|
3190
3246
|
continue
|
|
@@ -3236,6 +3292,7 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
|
|
|
3236
3292
|
'mode': 'site',
|
|
3237
3293
|
'budget_exhausted': budget_exhausted,
|
|
3238
3294
|
'page_errors': page_errors,
|
|
3295
|
+
'failed_pages_capped': failed_pages_capped,
|
|
3239
3296
|
'not_measured': _not_measured(lang),
|
|
3240
3297
|
'discovery': 'sitemap' if urls_sm else 'links',
|
|
3241
3298
|
'pages': len(reports),
|
|
@@ -54,11 +54,21 @@ _CLI_MSG = {
|
|
|
54
54
|
'es': {'stdin_json': ('stdin no contiene un JSON de informe válido — '
|
|
55
55
|
'esperado: la salida de `a11ytoolkit audit` '
|
|
56
56
|
'(p. ej. {"url": …, "score": …, "findings": […]}) '
|
|
57
|
-
'por tubería, o usa --audit fichero.json')
|
|
57
|
+
'por tubería, o usa --audit fichero.json'),
|
|
58
|
+
'stdin_snapshot': ('stdin no contiene un JSON de snapshot válido — '
|
|
59
|
+
'esperado: la salida de `a11ytoolkit snapshot` '
|
|
60
|
+
'(p. ej. {"url": …, "elements": […]})'),
|
|
61
|
+
'file_json': ('no se pudo leer {role} {file}: {err} — se esperaba un '
|
|
62
|
+
'fichero JSON escrito por este toolkit')},
|
|
58
63
|
'en': {'stdin_json': ('stdin is not a valid audit-report JSON — expected: '
|
|
59
64
|
'the output of `a11ytoolkit audit` (e.g. {"url": …, '
|
|
60
65
|
'"score": …, "findings": […]}), or pass '
|
|
61
|
-
'--audit report.json instead')
|
|
66
|
+
'--audit report.json instead'),
|
|
67
|
+
'stdin_snapshot': ('stdin is not a valid snapshot JSON — expected: '
|
|
68
|
+
'the output of `a11ytoolkit snapshot` '
|
|
69
|
+
'(e.g. {"url": …, "elements": […]})'),
|
|
70
|
+
'file_json': ('could not read {role} {file}: {err} — expected a JSON '
|
|
71
|
+
'file written by this toolkit')},
|
|
62
72
|
}
|
|
63
73
|
|
|
64
74
|
|
|
@@ -79,17 +89,34 @@ def _page_index(pages):
|
|
|
79
89
|
url = page.get('url')
|
|
80
90
|
if not isinstance(url, str) or not url or url in result:
|
|
81
91
|
raise ValueError('every audited page must have a unique URL')
|
|
82
|
-
findings = {}
|
|
92
|
+
findings, sampled = {}, set()
|
|
83
93
|
for finding in _active_findings(page):
|
|
84
94
|
signal = normalize_signal(finding['signal'])
|
|
85
|
-
|
|
95
|
+
stored = finding.get('paths') if isinstance(finding.get('paths'), list) else []
|
|
96
|
+
stable = finding.get('stable_paths') if isinstance(finding.get('stable_paths'), list) else []
|
|
97
|
+
# `stable_paths` viaja alineada con `paths` (null sin atributo
|
|
98
|
+
# estable) y puede faltar entera: cada ruta conserva su posición
|
|
99
|
+
located = sorted(((path, stable[index] if index < len(stable) else None)
|
|
100
|
+
for index, path in enumerate(stored) if isinstance(path, str)),
|
|
101
|
+
key=lambda pair: (pair[0], pair[1] if isinstance(pair[1], str) else ''))
|
|
102
|
+
paths = [path for path, _ in located]
|
|
86
103
|
count = finding.get('count')
|
|
87
104
|
if type(count) is not int or count < 1:
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
105
|
+
examples = finding.get('examples')
|
|
106
|
+
# sin `count` las instancias se cuentan por sus ejemplos, que el
|
|
107
|
+
# motor RECORTA: es una muestra, y el veredicto lo dice
|
|
108
|
+
count = max(len(paths), len(examples) if isinstance(examples, list) else 0, 1)
|
|
109
|
+
if not paths:
|
|
110
|
+
sampled.add(signal)
|
|
111
|
+
entry = {'severity': finding['severity'], 'count': max(count, len(paths)),
|
|
112
|
+
'paths': paths}
|
|
113
|
+
anchors = {path: anchor for path, anchor in located
|
|
114
|
+
if isinstance(anchor, str) and anchor}
|
|
115
|
+
if anchors:
|
|
116
|
+
entry['anchors'] = anchors
|
|
117
|
+
findings[signal] = entry
|
|
91
118
|
result[url] = {'mode': page.get('mode', 'static'), 'conditions': audit_conditions(page),
|
|
92
|
-
'findings': findings}
|
|
119
|
+
'findings': findings, 'sampled': sorted(sampled)}
|
|
93
120
|
return result
|
|
94
121
|
|
|
95
122
|
|
|
@@ -113,18 +140,43 @@ def init(audit):
|
|
|
113
140
|
}
|
|
114
141
|
|
|
115
142
|
|
|
143
|
+
def _located(entry):
|
|
144
|
+
"""[(ruta posicional, selector estable o None)] — solo lo identificado."""
|
|
145
|
+
entry = entry or {}
|
|
146
|
+
anchors = entry.get('anchors') if isinstance(entry.get('anchors'), dict) else {}
|
|
147
|
+
return [(path, anchors.get(path)) for path in entry.get('paths', [])]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _unmatched_by_anchor(located, matched):
|
|
151
|
+
"""Rutas posicionales de las instancias que la identidad estable NO emparejó."""
|
|
152
|
+
used, out = Counter(), []
|
|
153
|
+
for path, anchor in located:
|
|
154
|
+
if anchor and used[anchor] < matched[anchor]:
|
|
155
|
+
used[anchor] += 1
|
|
156
|
+
continue
|
|
157
|
+
out.append(path)
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
|
|
116
161
|
def _instance_delta(before, after):
|
|
117
162
|
before_count = before['count'] if before else 0
|
|
118
163
|
after_count = after['count'] if after else 0
|
|
119
|
-
|
|
120
|
-
|
|
164
|
+
located_before, located_after = _located(before), _located(after)
|
|
165
|
+
# Identidad ESTABLE primero: un elemento con id, data-testid o nombre ARIA
|
|
166
|
+
# es el MISMO aunque insertar un hermano delante desplace su ruta
|
|
167
|
+
# posicional (revisión 2026-11-25). Lo demás se compara por ruta, como
|
|
168
|
+
# siempre — sin atributo estable no se inventa identidad.
|
|
169
|
+
matched = (Counter(anchor for _, anchor in located_before if anchor)
|
|
170
|
+
& Counter(anchor for _, anchor in located_after if anchor))
|
|
171
|
+
before_paths = _unmatched_by_anchor(located_before, matched)
|
|
172
|
+
after_paths = _unmatched_by_anchor(located_after, matched)
|
|
121
173
|
old, new = Counter(before_paths), Counter(after_paths)
|
|
122
|
-
before_missing = max(0, before_count - len(
|
|
123
|
-
after_missing = max(0, after_count - len(
|
|
174
|
+
before_missing = max(0, before_count - len(located_before))
|
|
175
|
+
after_missing = max(0, after_count - len(located_after))
|
|
124
176
|
added_paths = sum((new - old).values())
|
|
125
177
|
removed_paths = sum((old - new).values())
|
|
126
178
|
if not before_missing and not after_missing:
|
|
127
|
-
return added_paths, removed_paths, 'paths'
|
|
179
|
+
return added_paths, removed_paths, 'stable-paths' if matched else 'paths'
|
|
128
180
|
# A path observed on one side could be among the hidden paths on the other.
|
|
129
181
|
# Any excess over those hidden slots is still a demonstrated change.
|
|
130
182
|
added_by_count = max(0, after_count - before_count)
|
|
@@ -196,8 +248,14 @@ def compare(budget, audit, today=None):
|
|
|
196
248
|
blocking = set(budget.get('blocking', ['high', 'medium']))
|
|
197
249
|
max_new = int(budget.get('max_new', 0))
|
|
198
250
|
signals = {normalize_signal(h['signal']) for pg in pages for h in _active_findings(pg)}
|
|
251
|
+
sampled = set()
|
|
199
252
|
if budget.get('format') == BUDGET_FORMAT:
|
|
200
|
-
|
|
253
|
+
index = _page_index(pages)
|
|
254
|
+
# señales cuyas instancias solo se conocen por una MUESTRA de
|
|
255
|
+
# ejemplos (informe sin `count` ni rutas): no se puede demostrar
|
|
256
|
+
# crecimiento más allá de la muestra, y el veredicto lo dice
|
|
257
|
+
sampled = {signal for pg in index.values() for signal in pg['sampled']}
|
|
258
|
+
verdict = _compare_instances(budget, index, blocking)
|
|
201
259
|
else:
|
|
202
260
|
if any(p.get('mode') == 'rendered' for p in pages):
|
|
203
261
|
return {'error': 'a rendered audit needs a baseline with recorded capture conditions'}
|
|
@@ -222,9 +280,13 @@ def compare(budget, audit, today=None):
|
|
|
222
280
|
'resolved': len(verdict['resolved']),
|
|
223
281
|
},
|
|
224
282
|
'baseline_expired': expired,
|
|
283
|
+
'sampled_counts': sorted(sampled),
|
|
225
284
|
'note': ('ok=false: there are new blocking findings (or the baseline expired). '
|
|
226
285
|
'ok=true: nothing new vs the accepted baseline — fix baseline items '
|
|
227
|
-
'and re-run --init to lower it.'
|
|
286
|
+
'and re-run --init to lower it.'
|
|
287
|
+
+ (' sampled_counts: signals whose instances are known only through '
|
|
288
|
+
'a sample of examples — growth beyond that sample cannot be '
|
|
289
|
+
'demonstrated.' if sampled else '')),
|
|
228
290
|
}
|
|
229
291
|
|
|
230
292
|
|
|
@@ -319,12 +381,31 @@ def main(argv):
|
|
|
319
381
|
ap.add_argument('--snapshot', help='structural compare: today\'s snapshot JSON')
|
|
320
382
|
ap.add_argument('--url', help='auditar esta URL al vuelo')
|
|
321
383
|
a = ap.parse_args(argv)
|
|
384
|
+
def read_json(path, role):
|
|
385
|
+
"""JSON de un fichero de entrada, o None con el error de USO ya impreso
|
|
386
|
+
(JSON + exit 1): un fichero inexistente o corrupto no es un traceback."""
|
|
387
|
+
try:
|
|
388
|
+
with open(path, encoding='utf-8') as f:
|
|
389
|
+
return json.load(f)
|
|
390
|
+
except (OSError, ValueError) as err:
|
|
391
|
+
print(json.dumps({'error': _CLI_MSG['en']['file_json'].format(
|
|
392
|
+
role=role, file=path, err=str(err)[:160])}, ensure_ascii=False))
|
|
393
|
+
return None
|
|
394
|
+
|
|
322
395
|
if a.init_snapshot:
|
|
323
396
|
if a.init_snapshot == '-':
|
|
324
|
-
|
|
397
|
+
try:
|
|
398
|
+
snap = json.loads(sys.stdin.read())
|
|
399
|
+
except ValueError:
|
|
400
|
+
snap = None
|
|
401
|
+
if snap is None:
|
|
402
|
+
print(json.dumps({'error': _CLI_MSG['en']['stdin_snapshot']},
|
|
403
|
+
ensure_ascii=False))
|
|
404
|
+
return 1
|
|
325
405
|
else:
|
|
326
|
-
|
|
327
|
-
|
|
406
|
+
snap = read_json(a.init_snapshot, 'the snapshot')
|
|
407
|
+
if snap is None:
|
|
408
|
+
return 1
|
|
328
409
|
b = init_structural(snap)
|
|
329
410
|
if 'error' in b:
|
|
330
411
|
print(json.dumps(b, ensure_ascii=False))
|
|
@@ -334,8 +415,9 @@ def main(argv):
|
|
|
334
415
|
if a.init:
|
|
335
416
|
inform = None
|
|
336
417
|
if a.audit:
|
|
337
|
-
|
|
338
|
-
|
|
418
|
+
inform = read_json(a.audit, 'the audit report')
|
|
419
|
+
if inform is None:
|
|
420
|
+
return 1
|
|
339
421
|
elif not sys.stdin.isatty():
|
|
340
422
|
try:
|
|
341
423
|
inform = json.loads(sys.stdin.read())
|
|
@@ -352,10 +434,12 @@ def main(argv):
|
|
|
352
434
|
print(json.dumps(baseline, ensure_ascii=False, indent=1))
|
|
353
435
|
return 1 if 'error' in baseline else 0
|
|
354
436
|
if a.snapshot:
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
437
|
+
budget = read_json(a.budget, 'the budget')
|
|
438
|
+
if budget is None:
|
|
439
|
+
return 1
|
|
440
|
+
snap = read_json(a.snapshot, 'the snapshot')
|
|
441
|
+
if snap is None:
|
|
442
|
+
return 1
|
|
359
443
|
verdict = compare_structural(budget, snap)
|
|
360
444
|
if 'error' in verdict:
|
|
361
445
|
# presupuesto no-estructural / snapshot malformado: error de USO
|
|
@@ -367,11 +451,13 @@ def main(argv):
|
|
|
367
451
|
if not (a.audit or a.url):
|
|
368
452
|
print('need --audit report.json or --url https://…')
|
|
369
453
|
return 1
|
|
370
|
-
|
|
371
|
-
|
|
454
|
+
budget = read_json(a.budget, 'the budget')
|
|
455
|
+
if budget is None:
|
|
456
|
+
return 1
|
|
372
457
|
if a.audit:
|
|
373
|
-
|
|
374
|
-
|
|
458
|
+
report = read_json(a.audit, 'the audit report')
|
|
459
|
+
if report is None:
|
|
460
|
+
return 1
|
|
375
461
|
else:
|
|
376
462
|
from .a11yaudit import audit_url
|
|
377
463
|
report = audit_url(a.url)
|
package/a11y_toolkit/a11ydiff.py
CHANGED
|
@@ -137,7 +137,12 @@ def snapshot(url, output=None, auth_state=None, engine='chromium'):
|
|
|
137
137
|
engine: chromium (default), firefox, webkit, chrome, msedge — la misma
|
|
138
138
|
captura en otro motor es la materia prima de la matriz cross-engine."""
|
|
139
139
|
from playwright.sync_api import sync_playwright
|
|
140
|
-
|
|
140
|
+
# The browser pool leaves its own loop as this thread's «running loop»
|
|
141
|
+
# after a11y_audit_dom and friends; opened on top of it, this second sync
|
|
142
|
+
# session died with «Playwright Sync API inside the asyncio loop».
|
|
143
|
+
# Detach the pool loop first, re-attach it when this session is over.
|
|
144
|
+
from .a11ydom import _OwnSyncSession
|
|
145
|
+
with _OwnSyncSession(), sync_playwright() as p:
|
|
141
146
|
launch = _LAUNCHERS.get(engine or 'chromium', _LAUNCHERS['chromium'])
|
|
142
147
|
nav = launch(p)
|
|
143
148
|
ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
|
|
@@ -47,15 +47,30 @@ def _recheck(url, expected_url, timeout, lang, color_scheme=None, auth_state=Non
|
|
|
47
47
|
return fresh, None
|
|
48
48
|
|
|
49
49
|
|
|
50
|
+
def _text(value):
|
|
51
|
+
return value if isinstance(value, str) else ''
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _count(finding):
|
|
55
|
+
count = finding.get('count')
|
|
56
|
+
return count if type(count) is int and count > 0 else None
|
|
57
|
+
|
|
58
|
+
|
|
50
59
|
def _finding_key(finding):
|
|
51
|
-
|
|
52
|
-
|
|
60
|
+
# el informe es entrada externa: un `signal` o `criterion` numérico no
|
|
61
|
+
# puede tirar la reverificación (revisión 2026-11-25)
|
|
62
|
+
return (normalize_signal(_text(finding.get('signal'))),
|
|
63
|
+
_text(finding.get('criterion')).split(' ', 1)[0])
|
|
53
64
|
|
|
54
65
|
|
|
55
66
|
def _location_evidence(finding):
|
|
56
|
-
|
|
67
|
+
"""(rutas guardadas, cubren TODAS las instancias). Las rutas de un
|
|
68
|
+
hallazgo con más instancias que rutas son una MUESTRA, no el inventario."""
|
|
69
|
+
stored = finding.get('paths')
|
|
70
|
+
paths = tuple(sorted({path for path in (stored if isinstance(stored, (list, tuple)) else [])
|
|
71
|
+
if isinstance(path, str)}))
|
|
57
72
|
if paths:
|
|
58
|
-
count = finding
|
|
73
|
+
count = _count(finding)
|
|
59
74
|
return paths, count == len(paths) if count is not None else len(paths) < 5
|
|
60
75
|
return (), False
|
|
61
76
|
|
|
@@ -79,10 +94,12 @@ def _classify_findings(previous, current, lang):
|
|
|
79
94
|
if not candidates or (complete and all(known and not set(paths).intersection(new_paths)
|
|
80
95
|
for new_paths, known in locations)):
|
|
81
96
|
historical.append(dict(old, status='rejected', reject_reason=rejected))
|
|
82
|
-
elif len(candidates) == 1
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
97
|
+
elif len(candidates) == 1:
|
|
98
|
+
# una sola candidata de la misma señal, en la misma página, y sin
|
|
99
|
+
# prueba completa de que los elementos originales ya no fallan: el
|
|
100
|
+
# defecto se reproduce → confirmada. Antes, una MUESTRA de rutas (8
|
|
101
|
+
# instancias, 5 guardadas) no confirmaba nunca y quedaba
|
|
102
|
+
# `not-rechecked` sin haber mirado la evidencia (2026-11-25)
|
|
86
103
|
candidates[0]['status'] = 'confirmed'
|
|
87
104
|
else:
|
|
88
105
|
historical.append(dict(old, disprover_status='not-rechecked'))
|
|
@@ -104,11 +121,22 @@ def disprove(url, report=None, timeout=30, lang='en', auth_state=None):
|
|
|
104
121
|
report = audit_dom_url(url, timeout=timeout, lang=lang, auth_state=auth_state)
|
|
105
122
|
else:
|
|
106
123
|
report = audit_url(url, timeout=timeout, lang=lang)
|
|
124
|
+
if not isinstance(report, dict):
|
|
125
|
+
report = {'error': ('El informe no es un objeto JSON de informe de auditoría.'
|
|
126
|
+
if lang == 'es'
|
|
127
|
+
else 'The report is not an audit-report JSON object.')}
|
|
107
128
|
if report.get('error'):
|
|
108
129
|
return report
|
|
109
130
|
mode_name = report.get('mode', 'static')
|
|
110
131
|
expected_url = report.get('url') or url
|
|
111
132
|
findings = report.get('findings', [])
|
|
133
|
+
if not isinstance(findings, list) or any(not isinstance(h, dict) for h in findings):
|
|
134
|
+
# el informe es entrada externa (CLI --file / MCP): una lista de
|
|
135
|
+
# hallazgos que no lo es se dice, no se tronca
|
|
136
|
+
message = ('El informe trae una lista de hallazgos inválida: se esperaba una lista de objetos.'
|
|
137
|
+
if lang == 'es' else
|
|
138
|
+
'The report carries an invalid findings list: a list of objects was expected.')
|
|
139
|
+
return dict(report, error=message, disprover={'executed': False, 'reason': message})
|
|
112
140
|
|
|
113
141
|
if mode_name == 'site':
|
|
114
142
|
# site reports nest findings INSIDE each page: re-checking them against
|
package/a11y_toolkit/a11ydocx.py
CHANGED
|
@@ -104,7 +104,13 @@ def docx_screen(path, lang='en'):
|
|
|
104
104
|
try:
|
|
105
105
|
with zipfile.ZipFile(path) as archive:
|
|
106
106
|
return _screen_zip(archive, lang, path)
|
|
107
|
-
except
|
|
107
|
+
except Exception as error: # noqa: BLE001
|
|
108
|
+
# Un fichero corrupto falla de tantas maneras como decodificadores
|
|
109
|
+
# intervienen (zipfile.BadZipFile, zlib.error, EOFError, LZMAError,
|
|
110
|
+
# NotImplementedError por compresión desconocida, ET.ParseError,
|
|
111
|
+
# LookupError por codificación XML desconocida…): la lista cerrada
|
|
112
|
+
# dejaba 26 de 120 DOCX corruptos con traceback (revisión 2026-11-25).
|
|
113
|
+
# La promesa del cribado es JSON + exit 1 para CUALQUIER fichero.
|
|
108
114
|
message = 'No se pudo leer el DOCX' if lang == 'es' else 'Could not read DOCX'
|
|
109
115
|
return {'error': f'{message}: {error}', 'mode': 'docx', 'file': os.path.basename(path)}
|
|
110
116
|
|
package/a11y_toolkit/a11ydom.py
CHANGED
|
@@ -15,6 +15,7 @@ CLI:
|
|
|
15
15
|
"""
|
|
16
16
|
|
|
17
17
|
import argparse
|
|
18
|
+
import asyncio
|
|
18
19
|
import json
|
|
19
20
|
import re
|
|
20
21
|
import sys
|
|
@@ -40,6 +41,58 @@ class _NavigationHTTPError(RuntimeError):
|
|
|
40
41
|
return {'error': message, 'url': self.url, 'http_status': self.status}
|
|
41
42
|
|
|
42
43
|
|
|
44
|
+
class _NavigationLoadError(RuntimeError):
|
|
45
|
+
"""The page did not load at all (timeout, network failure). Reported with
|
|
46
|
+
the same clean contract as an HTTP error — never raised to the caller."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, url, reason):
|
|
49
|
+
super().__init__(reason)
|
|
50
|
+
self.url = url
|
|
51
|
+
self.reason = reason
|
|
52
|
+
|
|
53
|
+
def report(self, lang='en'):
|
|
54
|
+
return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=self.reason),
|
|
55
|
+
'url': self.url}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _first_line(error):
|
|
59
|
+
"""One-line cause of a Playwright error (its message carries a call log)."""
|
|
60
|
+
return str(error).strip().split('\n')[0] or type(error).__name__
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _is_playwright_timeout(error):
|
|
64
|
+
"""Playwright's TimeoutError without importing Playwright at module load
|
|
65
|
+
(the toolkit must stay importable without it)."""
|
|
66
|
+
try:
|
|
67
|
+
from playwright.sync_api import TimeoutError as _PwTimeout
|
|
68
|
+
except Exception: # noqa: BLE001
|
|
69
|
+
return False
|
|
70
|
+
return isinstance(error, _PwTimeout)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _rendered_despite_timeout(page, error):
|
|
74
|
+
"""True when `load` timed out but the document IS there: the navigation
|
|
75
|
+
committed (the page is no longer about:blank) and the parser finished
|
|
76
|
+
(readyState interactive/complete) — a hanging subresource, not a dead
|
|
77
|
+
page. False for any other failure and when the navigation never committed."""
|
|
78
|
+
if not _is_playwright_timeout(error):
|
|
79
|
+
return False
|
|
80
|
+
try:
|
|
81
|
+
if page.url in ('', 'about:blank'):
|
|
82
|
+
return False
|
|
83
|
+
return page.evaluate('document.readyState') in ('interactive', 'complete')
|
|
84
|
+
except Exception: # noqa: BLE001
|
|
85
|
+
return False
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
_SLOW_LOAD = {'es': ('el evento load no llegó en {t} s: se auditó el DOM ya '
|
|
89
|
+
'renderizado (readyState {rs}); lo que cargue después '
|
|
90
|
+
'no está evaluado'),
|
|
91
|
+
'en': ('the load event did not fire within {t} s: the rendered '
|
|
92
|
+
'DOM was audited (readyState {rs}); whatever loads '
|
|
93
|
+
'later is not evaluated')}
|
|
94
|
+
|
|
95
|
+
|
|
43
96
|
def _load_page(page, url, timeout, wait_until='load'):
|
|
44
97
|
response = page.goto(url, wait_until=wait_until, timeout=timeout)
|
|
45
98
|
if response is not None and response.status >= 400:
|
|
@@ -168,6 +221,58 @@ def _close_pool():
|
|
|
168
221
|
pw.stop()
|
|
169
222
|
except Exception: # noqa: BLE001
|
|
170
223
|
pass
|
|
224
|
+
# the driver is gone: its loop must not stay pinned to this thread as a
|
|
225
|
+
# «running» loop (a closed loop pinned here is the «Event loop is closed»
|
|
226
|
+
# poison of the old pool)
|
|
227
|
+
_loop = getattr(pw, '_loop', None)
|
|
228
|
+
if _loop is not None and asyncio._get_running_loop() is _loop:
|
|
229
|
+
asyncio._set_running_loop(None)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _pool_loop():
|
|
233
|
+
"""The asyncio loop the pool's Playwright driver runs on (None: no pool)."""
|
|
234
|
+
return getattr(_POOL['playwright'], '_loop', None)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _unpin_loop():
|
|
238
|
+
"""Detach the pool loop from THIS thread so a SECOND sync session can
|
|
239
|
+
start here (a11y_snapshot, a host's own Playwright).
|
|
240
|
+
|
|
241
|
+
Root cause closed (review 2026-11-25): Playwright's sync client ends every
|
|
242
|
+
call with asyncio._set_running_loop(loop) and the loop stays suspended
|
|
243
|
+
inside its dispatcher greenlet, so it still reports is_running() == True.
|
|
244
|
+
The next sync_playwright() in the same thread found that marker and died
|
|
245
|
+
with «It looks like you are using Playwright Sync API inside the asyncio
|
|
246
|
+
loop» (a11y_snapshot right after a11y_audit_dom). Only the pool's OWN
|
|
247
|
+
loop is detached: a real host loop running in the thread is never touched
|
|
248
|
+
(Playwright keeps its own error for that misuse). No pool loop
|
|
249
|
+
(A11Y_BROWSER_POOL=0, pool never started): no-op, as before."""
|
|
250
|
+
loop = _pool_loop()
|
|
251
|
+
if loop is not None and asyncio._get_running_loop() is loop:
|
|
252
|
+
asyncio._set_running_loop(None)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _pin_loop():
|
|
256
|
+
"""Re-attach the pool loop to THIS thread after the second session ended:
|
|
257
|
+
the pool is touched again as if nothing happened. The sync client needs
|
|
258
|
+
its loop marked as running to resume it («no running event loop»)."""
|
|
259
|
+
loop = _pool_loop()
|
|
260
|
+
if loop is not None and asyncio._get_running_loop() is None:
|
|
261
|
+
asyncio._set_running_loop(loop)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
class _OwnSyncSession:
|
|
265
|
+
"""`with` guard for a caller that opens its OWN sync Playwright session in
|
|
266
|
+
a thread where the pool may have run (a11y_snapshot): detaches the pool
|
|
267
|
+
loop first and re-attaches it once the second session is over, so the
|
|
268
|
+
thread is left exactly as the pool expects it."""
|
|
269
|
+
|
|
270
|
+
def __enter__(self):
|
|
271
|
+
_unpin_loop()
|
|
272
|
+
return self
|
|
273
|
+
|
|
274
|
+
def __exit__(self, *exc):
|
|
275
|
+
_pin_loop()
|
|
171
276
|
|
|
172
277
|
|
|
173
278
|
atexit.register(_close_pool)
|
|
@@ -253,6 +358,29 @@ def _t(lang, key, n=None):
|
|
|
253
358
|
# implicit <label> > content > title. Static string — no page data ever lands
|
|
254
359
|
# here.
|
|
255
360
|
_JS_NAMEOF = r'''
|
|
361
|
+
// Layout-free text. innerText only returns what is being PAINTED: the
|
|
362
|
+
// content of a closed <details> keeps its boxes in Chromium (so it passes
|
|
363
|
+
// the visibility filter) but is not painted, and every link of a closed
|
|
364
|
+
// menu came out as having NO accessible name. When innerText gives nothing
|
|
365
|
+
// the same text is read from the tree — when the user opens the disclosure
|
|
366
|
+
// that IS the name — while a really empty element keeps giving ''.
|
|
367
|
+
const textOf = el => {
|
|
368
|
+
const painted = (el.innerText || '').trim();
|
|
369
|
+
if (painted) return painted;
|
|
370
|
+
const parts = [];
|
|
371
|
+
const walk = node => {
|
|
372
|
+
for (const c of node.childNodes) {
|
|
373
|
+
if (c.nodeType === 3) { parts.push(c.nodeValue); continue; }
|
|
374
|
+
if (c.nodeType !== 1) continue;
|
|
375
|
+
if (['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE'].includes(c.tagName)) continue;
|
|
376
|
+
const s = getComputedStyle(c);
|
|
377
|
+
if (s.display === 'none' || s.visibility === 'hidden' || s.visibility === 'collapse') continue;
|
|
378
|
+
walk(c);
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
walk(el);
|
|
382
|
+
return parts.join(' ').replace(/\s+/g, ' ').trim();
|
|
383
|
+
};
|
|
256
384
|
const nameOf = el => {
|
|
257
385
|
let n = '';
|
|
258
386
|
// 1. aria-labelledby: a whitespace-SEPARATED id list — resolve each id
|
|
@@ -265,19 +393,19 @@ _JS_NAMEOF = r'''
|
|
|
265
393
|
const parts = [];
|
|
266
394
|
for (const id of el.getAttribute('aria-labelledby').trim().split(/\s+/)) {
|
|
267
395
|
const ref = byId(id);
|
|
268
|
-
if (ref) parts.push((ref
|
|
396
|
+
if (ref) parts.push(textOf(ref));
|
|
269
397
|
}
|
|
270
398
|
n = parts.join(' ').trim();
|
|
271
399
|
}
|
|
272
400
|
// 2. aria-label
|
|
273
401
|
if (!n) n = (el.getAttribute('aria-label') || '').trim();
|
|
274
402
|
// 3. implicit <label>
|
|
275
|
-
if (!n && el.labels && el.labels[0]) n = el.labels[0]
|
|
403
|
+
if (!n && el.labels && el.labels[0]) n = textOf(el.labels[0]);
|
|
276
404
|
// 4. content: input value/image alt, element text, descendant img alt
|
|
277
405
|
if (!n && el.tagName === 'INPUT' && ['submit', 'button', 'reset'].includes(el.type)) n = el.value || '';
|
|
278
406
|
if (!n && el.tagName === 'INPUT' && el.type === 'image') n = el.alt || '';
|
|
279
407
|
if (!n && ['A', 'BUTTON', 'SUMMARY'].includes(el.tagName)) {
|
|
280
|
-
n = (el
|
|
408
|
+
n = textOf(el);
|
|
281
409
|
// accname: a descendant image's alt contributes to the link's name
|
|
282
410
|
if (!n) { const im = el.querySelector('img[alt]'); if (im) n = (im.getAttribute('alt') || '').trim(); }
|
|
283
411
|
}
|
|
@@ -780,9 +908,26 @@ _JS = r'''(maxEj) => {
|
|
|
780
908
|
// ---- foco: indicador visible (heurístico) + contraste en estado focus ----
|
|
781
909
|
const hiddenEl = el => { const r = el.getBoundingClientRect();
|
|
782
910
|
return (r.width <= 2 && r.height <= 2); };
|
|
911
|
+
// Content that is NOT rendered although it keeps layout boxes: the content
|
|
912
|
+
// of a closed <details> (Chromium keeps real rects, so vis() lets it
|
|
913
|
+
// through) and anything under content-visibility:hidden. It cannot take
|
|
914
|
+
// focus now, and that is hidden content, not a failure — it turns into a
|
|
915
|
+
// real control when the user opens it. A closed <summary> IS rendered.
|
|
916
|
+
const hiddenContent = el => {
|
|
917
|
+
let inSummary = false;
|
|
918
|
+
for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
|
|
919
|
+
const tag = n.tagName;
|
|
920
|
+
if (tag === 'SUMMARY') inSummary = true;
|
|
921
|
+
else if (tag === 'DETAILS') {
|
|
922
|
+
if (!n.open && !inSummary) return true;
|
|
923
|
+
inSummary = false;
|
|
924
|
+
} else if (getComputedStyle(n).contentVisibility === 'hidden') return true;
|
|
925
|
+
}
|
|
926
|
+
return false;
|
|
927
|
+
};
|
|
783
928
|
const stops = deepQ(INTER)
|
|
784
|
-
.filter(el => vis(el) && !el
|
|
785
|
-
&& !hiddenEl(el)).slice(0, 40);
|
|
929
|
+
.filter(el => vis(el) && !hiddenContent(el) && !el.disabled
|
|
930
|
+
&& el.getAttribute('tabindex') !== '-1' && !hiddenEl(el)).slice(0, 40);
|
|
786
931
|
const activeEl = () => { let a = document.activeElement;
|
|
787
932
|
while (a && a.shadowRoot && a.shadowRoot.activeElement) a = a.shadowRoot.activeElement;
|
|
788
933
|
return a; };
|
|
@@ -853,6 +998,11 @@ def _add(findings, lang, severity, code, key, examples=None, **fmt):
|
|
|
853
998
|
'remediation': _t(lang, key + '_rem').format(**fmt)}
|
|
854
999
|
if examples:
|
|
855
1000
|
h['examples'] = examples[:MAX_EXAMPLES]
|
|
1001
|
+
# total instances: the examples are capped, the count is not — the
|
|
1002
|
+
# instance budget compares totals (8 vs 11 images), never the 6 shown.
|
|
1003
|
+
# Same line as add() in a11yaudit.py: no rendered report carried it.
|
|
1004
|
+
if type(fmt.get('n')) is int and fmt['n'] > 0:
|
|
1005
|
+
h['count'] = fmt['n']
|
|
856
1006
|
findings.append(h)
|
|
857
1007
|
|
|
858
1008
|
|
|
@@ -2175,6 +2325,7 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
|
|
|
2175
2325
|
page, close_page = _pooled_page(nav, auth_state)
|
|
2176
2326
|
_resp = None
|
|
2177
2327
|
page_url_final = None
|
|
2328
|
+
slow_load = None
|
|
2178
2329
|
try:
|
|
2179
2330
|
if color_scheme in ('dark', 'light'):
|
|
2180
2331
|
# contraste por esquema: los temas oscuros fallan donde el claro
|
|
@@ -2184,7 +2335,11 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
|
|
|
2184
2335
|
_resp = page.goto(url, wait_until='load', timeout=timeout * 1000)
|
|
2185
2336
|
page.wait_for_timeout(400)
|
|
2186
2337
|
except Exception as e: # noqa: BLE001
|
|
2187
|
-
|
|
2338
|
+
if not _rendered_despite_timeout(page, e):
|
|
2339
|
+
return _load_error(e, lang, _LOAD_ERR.get(lang, _LOAD_ERR['en']))
|
|
2340
|
+
# `load` timed out on a hanging subresource but the document is
|
|
2341
|
+
# parsed and rendered: audit it and leave the record below
|
|
2342
|
+
slow_load = page.evaluate('document.readyState')
|
|
2188
2343
|
data = page.evaluate(_JS, MAX_EXAMPLES)
|
|
2189
2344
|
# 1.4.12: inject the WCAG spacing overrides, count clipped texts
|
|
2190
2345
|
data['spacingClipped'] = page.evaluate(_JS_SPACING)
|
|
@@ -2237,6 +2392,13 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
|
|
|
2237
2392
|
report_out = audit_dom(data, final_url, lang=lang, color_scheme=color_scheme)
|
|
2238
2393
|
report_out['authenticated'] = bool(auth_state)
|
|
2239
2394
|
report_out['browser'] = browser_kind
|
|
2395
|
+
if slow_load:
|
|
2396
|
+
# the record for the layers above: evidence and before/after
|
|
2397
|
+
# comparisons already treat a non-empty page_errors as «not a
|
|
2398
|
+
# complete measurement» — this page was audited, but not wholly loaded
|
|
2399
|
+
report_out['page_errors'] = [{
|
|
2400
|
+
'url': final_url,
|
|
2401
|
+
'error': _SLOW_LOAD.get(lang, _SLOW_LOAD['en']).format(t=timeout, rs=slow_load)}]
|
|
2240
2402
|
try:
|
|
2241
2403
|
_st = _resp.status if _resp is not None else None
|
|
2242
2404
|
except Exception: # noqa: BLE001 — respuesta ya consumida
|
|
@@ -2495,6 +2657,11 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
|
|
|
2495
2657
|
page = ctx.new_page()
|
|
2496
2658
|
try:
|
|
2497
2659
|
_load_page(page, url, timeout * 1000)
|
|
2660
|
+
except _NavigationHTTPError:
|
|
2661
|
+
raise
|
|
2662
|
+
except Exception as error: # noqa: BLE001 — timeout/network: same clean contract as an HTTP error
|
|
2663
|
+
raise _NavigationLoadError(url, _first_line(error)) from error
|
|
2664
|
+
try:
|
|
2498
2665
|
page.wait_for_timeout(300)
|
|
2499
2666
|
return _pass(page)
|
|
2500
2667
|
finally:
|
|
@@ -2505,7 +2672,7 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
|
|
|
2505
2672
|
|
|
2506
2673
|
try:
|
|
2507
2674
|
entries, skipped, unparsed = _run('light')
|
|
2508
|
-
except _NavigationHTTPError as error:
|
|
2675
|
+
except (_NavigationHTTPError, _NavigationLoadError) as error:
|
|
2509
2676
|
return error.report(lang)
|
|
2510
2677
|
report = {'mode': 'contrast-walk', 'url': url, 'scheme': 'light',
|
|
2511
2678
|
'checked': len(entries),
|
|
@@ -2525,7 +2692,7 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
|
|
|
2525
2692
|
if dark:
|
|
2526
2693
|
try:
|
|
2527
2694
|
entries_d, skipped_d, _unp_d = _run('dark')
|
|
2528
|
-
except _NavigationHTTPError as error:
|
|
2695
|
+
except (_NavigationHTTPError, _NavigationLoadError) as error:
|
|
2529
2696
|
return error.report(lang)
|
|
2530
2697
|
report['dark'] = {'scheme': 'dark', 'checked': len(entries_d),
|
|
2531
2698
|
'elements': entries_d,
|
package/a11y_toolkit/a11yfix.py
CHANGED
|
@@ -381,7 +381,13 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
|
|
|
381
381
|
'remediation': h['remediation']})
|
|
382
382
|
|
|
383
383
|
fixed = _unmask(fixed)
|
|
384
|
-
|
|
384
|
+
result = {'fixed_html': fixed, 'applied': applied, 'not_applied': not_applied}
|
|
385
|
+
if report.get('error'):
|
|
386
|
+
# `not_applied` nace de esa auditoría: si el motor no pudo mirar el
|
|
387
|
+
# HTML (más de 3 MB, no parseable), una lista vacía leía como "nada
|
|
388
|
+
# pendiente" cuando es "no medido" — el error viaja (2026-11-25)
|
|
389
|
+
result['error'] = report['error']
|
|
390
|
+
return result
|
|
385
391
|
|
|
386
392
|
|
|
387
393
|
_DO_NOT_TOUCH = {
|
|
@@ -444,13 +450,19 @@ def main(argv):
|
|
|
444
450
|
with open(a.out, 'w', encoding='utf-8') as f:
|
|
445
451
|
f.write(res['fixed_html'])
|
|
446
452
|
print(json.dumps({'file': a.out, 'applied': res['applied'],
|
|
447
|
-
'not_applied': res['not_applied']
|
|
453
|
+
'not_applied': res['not_applied'],
|
|
454
|
+
**({'error': res['error']} if res.get('error') else {})},
|
|
455
|
+
ensure_ascii=False, indent=1))
|
|
448
456
|
# human-facing thank-you goes to stderr AFTER the JSON: piped stdout
|
|
449
457
|
# stays machine-parseable, and only a real fix (a file written) asks
|
|
450
458
|
_star_nudge_once()
|
|
451
459
|
else:
|
|
452
460
|
print(res['fixed_html'])
|
|
453
|
-
|
|
461
|
+
if res.get('error'):
|
|
462
|
+
print(json.dumps({'error': res['error']}, ensure_ascii=False), file=sys.stderr)
|
|
463
|
+
# los arreglos deterministas se aplicaron; el error dice que `not_applied`
|
|
464
|
+
# no pudo calcularse — estado de error visible, no un verde incompleto
|
|
465
|
+
return 1 if res.get('error') else 0
|
|
454
466
|
|
|
455
467
|
|
|
456
468
|
if __name__ == '__main__':
|
package/a11y_toolkit/a11ygate.py
CHANGED
|
@@ -12,20 +12,25 @@ second the failure would have been born.
|
|
|
12
12
|
|
|
13
13
|
Honesty, as everywhere: the gate audits what the engine sees (part of
|
|
14
14
|
WCAG) — a filter, not a conformance verdict, and it says so in every
|
|
15
|
-
refusal. A11Y_GATE=off disables it
|
|
16
|
-
|
|
15
|
+
refusal. A11Y_GATE=off disables it. Two failures, two answers: an
|
|
16
|
+
unreadable hook PAYLOAD fails open (there is nothing to judge), but an
|
|
17
|
+
engine ERROR on a real save fails CLOSED — decision `error`, never
|
|
18
|
+
`allow` (a page over 3 MB used to pass as verified with an image
|
|
19
|
+
without alt). A11Y_LANG=es answers in Spanish.
|
|
17
20
|
|
|
18
21
|
Output:
|
|
19
22
|
verdict(old, new, path) -> {decision, blocked[], warnings[], counts...}
|
|
23
|
+
or {decision: 'error', failed, error, note}
|
|
20
24
|
guard_hook(payload) -> (exit_code, stderr) # Claude Code protocol
|
|
21
25
|
|
|
22
26
|
CLI:
|
|
23
|
-
a11ytoolkit guard --file index.html #
|
|
27
|
+
a11ytoolkit guard --file index.html # 0 allow / 2 block / 1 error
|
|
24
28
|
a11ytoolkit guard --hook # stdin JSON -> exit protocol
|
|
25
29
|
"""
|
|
26
30
|
|
|
27
31
|
import argparse
|
|
28
32
|
import json
|
|
33
|
+
import os
|
|
29
34
|
import re
|
|
30
35
|
import subprocess
|
|
31
36
|
import sys
|
|
@@ -40,6 +45,23 @@ _SEV_ORDER = {'high': 0, 'medium': 1, 'low': 2}
|
|
|
40
45
|
_LIST_CAP = 6
|
|
41
46
|
_FOOT = ('the gate audits what the engine sees — a filter, not a '
|
|
42
47
|
'conformance verdict · disable: A11Y_GATE=off')
|
|
48
|
+
_FOOT_ES = ('el gate audita lo que el motor ve — un filtro, no un veredicto '
|
|
49
|
+
'de conformidad · desactivar: A11Y_GATE=off')
|
|
50
|
+
# el gate NO PUDO auditar: falla cerrado (jamás `allow`) y dice por qué
|
|
51
|
+
_ERROR_MSG = {
|
|
52
|
+
'en': {'note': ('the gate could not audit this save: nothing is verified. '
|
|
53
|
+
'Fix the cause below or bypass the gate for this save with '
|
|
54
|
+
'A11Y_GATE=off'),
|
|
55
|
+
'side': {'new': 'saved content', 'old': 'git HEAD version'}},
|
|
56
|
+
'es': {'note': ('el gate no pudo auditar este guardado: nada está verificado. '
|
|
57
|
+
'Corrige la causa de abajo o salta el gate para este guardado '
|
|
58
|
+
'con A11Y_GATE=off'),
|
|
59
|
+
'side': {'new': 'contenido guardado', 'old': 'versión de git HEAD'}},
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _lang(lang):
|
|
64
|
+
return lang if lang in _ERROR_MSG else 'en'
|
|
43
65
|
|
|
44
66
|
|
|
45
67
|
def is_user_facing(path):
|
|
@@ -71,20 +93,26 @@ def old_version(path, project='.'):
|
|
|
71
93
|
return ''
|
|
72
94
|
|
|
73
95
|
|
|
74
|
-
def verdict(old_content, new_content, path='(file)'):
|
|
96
|
+
def verdict(old_content, new_content, path='(file)', lang='en'):
|
|
75
97
|
"""Compare findings in OLD (git HEAD) vs NEW (the save in flight).
|
|
76
98
|
|
|
77
99
|
The engine aggregates findings by KIND (one 'img without alt' finding
|
|
78
100
|
covers N images), so the gate works on KINDS, like the budget module:
|
|
79
101
|
a NEW kind with high/medium severity refuses the save; new LOW kinds
|
|
80
102
|
and kinds already in HEAD are warnings. Returns {decision, blocked[],
|
|
81
|
-
warnings[], known, before, after, score}
|
|
82
|
-
|
|
83
|
-
|
|
103
|
+
warnings[], known, before, after, score}; if the engine cannot audit
|
|
104
|
+
either side: {decision: 'error', failed: 'new'|'old', error, note}."""
|
|
105
|
+
lang = _lang(lang)
|
|
106
|
+
old = audit_html(old_content or '', url=f'(old) {path}', lang=lang)
|
|
107
|
+
new = audit_html(new_content or '', url=f'(new) {path}', lang=lang)
|
|
84
108
|
if 'error' in old or 'error' in new:
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
109
|
+
# FALLA CERRADO: `allow` se lee como "verificado" y aquí no se miró
|
|
110
|
+
# nada (una página de más de 3 MB pasaba con una imagen sin alt)
|
|
111
|
+
side = 'new' if 'error' in new else 'old'
|
|
112
|
+
failed = new if side == 'new' else old
|
|
113
|
+
return {'decision': 'error', 'path': path, 'blocked': [], 'warnings': [],
|
|
114
|
+
'failed': side, 'error': failed['error'],
|
|
115
|
+
'note': _ERROR_MSG[lang]['note'], 'lang': lang}
|
|
88
116
|
|
|
89
117
|
before = _counts(old.get('findings', []))
|
|
90
118
|
after = _counts(new.get('findings', []))
|
|
@@ -169,11 +197,22 @@ def payload_to_write(payload):
|
|
|
169
197
|
return path, None
|
|
170
198
|
|
|
171
199
|
|
|
172
|
-
def
|
|
200
|
+
def _fmt_error(v):
|
|
201
|
+
lang = _lang(v.get('lang'))
|
|
202
|
+
side = _ERROR_MSG[lang]['side'].get(v.get('failed'), _ERROR_MSG[lang]['side']['new'])
|
|
203
|
+
return '\n'.join([f"[a11y gate] {v['note']}",
|
|
204
|
+
f" cause ({side}): {v.get('error', '')}",
|
|
205
|
+
_FOOT_ES if lang == 'es' else _FOOT])
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def guard_hook(payload_text, lang=None):
|
|
173
209
|
"""stdin JSON → (exit_code, stderr) under the Claude Code protocol:
|
|
174
210
|
exit 2 blocks the write and feeds stderr back to the model; exit 0
|
|
175
|
-
allows (stderr is a transcript note).
|
|
176
|
-
|
|
211
|
+
allows (stderr is a transcript note). An unreadable payload fails OPEN
|
|
212
|
+
(nothing to judge); a save the engine could not audit fails CLOSED."""
|
|
213
|
+
if (os.environ.get('A11Y_GATE') or '').strip().lower() == 'off':
|
|
214
|
+
return 0, ''
|
|
215
|
+
lang = _lang(lang or os.environ.get('A11Y_LANG'))
|
|
177
216
|
try:
|
|
178
217
|
payload = json.loads(payload_text or '')
|
|
179
218
|
except Exception: # noqa: BLE001
|
|
@@ -183,7 +222,9 @@ def guard_hook(payload_text):
|
|
|
183
222
|
return 0, ''
|
|
184
223
|
if not is_user_facing(path):
|
|
185
224
|
return 0, ''
|
|
186
|
-
v = verdict(old_version(path), content, path)
|
|
225
|
+
v = verdict(old_version(path), content, path, lang=lang)
|
|
226
|
+
if v['decision'] == 'error':
|
|
227
|
+
return 2, _fmt_error(v)
|
|
187
228
|
if v['decision'] == 'block':
|
|
188
229
|
return 2, _fmt_verdict(v)
|
|
189
230
|
if v.get('warnings'):
|
|
@@ -198,16 +239,24 @@ def main(argv):
|
|
|
198
239
|
ap.add_argument('--hook', action='store_true',
|
|
199
240
|
help='read the client hook JSON payload from stdin')
|
|
200
241
|
ap.add_argument('--file', help='audit this file directly')
|
|
242
|
+
ap.add_argument('--lang', default=os.environ.get('A11Y_LANG') or 'en',
|
|
243
|
+
help='message language: en (default) or es')
|
|
201
244
|
a = ap.parse_args(argv)
|
|
245
|
+
lang = _lang(a.lang.strip().lower() if isinstance(a.lang, str) else 'en')
|
|
202
246
|
if a.hook:
|
|
203
247
|
text = sys.stdin.read()
|
|
204
|
-
code, err = guard_hook(text)
|
|
248
|
+
code, err = guard_hook(text, lang=lang)
|
|
205
249
|
if err:
|
|
206
250
|
print(err, file=sys.stderr)
|
|
207
251
|
return code
|
|
208
252
|
if a.file:
|
|
209
253
|
content = open(a.file, encoding='utf-8', errors='replace').read()
|
|
210
|
-
v = verdict(old_version(a.file), content, a.file)
|
|
254
|
+
v = verdict(old_version(a.file), content, a.file, lang=lang)
|
|
255
|
+
if v['decision'] == 'error':
|
|
256
|
+
print(json.dumps({k: v[k] for k in ('decision', 'path', 'failed', 'error', 'note')},
|
|
257
|
+
ensure_ascii=False, indent=1))
|
|
258
|
+
print(_fmt_error(v), file=sys.stderr)
|
|
259
|
+
return 1
|
|
211
260
|
print(json.dumps({k: v[k] for k in ('decision', 'path', 'known',
|
|
212
261
|
'before', 'after', 'score')},
|
|
213
262
|
ensure_ascii=False, indent=1))
|
|
@@ -221,5 +270,11 @@ def main(argv):
|
|
|
221
270
|
return 2
|
|
222
271
|
|
|
223
272
|
|
|
273
|
+
def hook_main(argv):
|
|
274
|
+
"""`a11ytoolkit guard-hook`: the exact command `a11yinit.GATE_CMD` writes
|
|
275
|
+
into the client hook settings. Same protocol as `guard --hook`."""
|
|
276
|
+
return main(['--hook'] + list(argv))
|
|
277
|
+
|
|
278
|
+
|
|
224
279
|
if __name__ == '__main__':
|
|
225
280
|
sys.exit(main(sys.argv[1:]))
|
|
@@ -59,6 +59,10 @@ def build(html_text, lang=None, title=None, form_errors=True):
|
|
|
59
59
|
the fixed html. The record is a fact about this run, not a promise."""
|
|
60
60
|
from .server import VERSION # lazy: server importa este módulo arriba
|
|
61
61
|
res = _autofix(html_text, lang=lang, title=title, form_errors=form_errors)
|
|
62
|
+
if res.get('error'):
|
|
63
|
+
# `not_applied` del registro sellado nace de la auditoría que falló:
|
|
64
|
+
# sellar uno incompleto sería enunciar un hecho falso
|
|
65
|
+
return {'error': res['error']}
|
|
62
66
|
patch_set = {
|
|
63
67
|
'format': FORMAT,
|
|
64
68
|
'source_sha256': _sha(html_text),
|
|
@@ -135,6 +139,10 @@ def main(argv):
|
|
|
135
139
|
f.write(res['fixed_html'])
|
|
136
140
|
return 0 if res['status'] in ('reproduced', 'stale') else 1
|
|
137
141
|
res = build(html_text)
|
|
142
|
+
if res.get('error'):
|
|
143
|
+
# la auditoría que alimenta `not_applied` falló: nada se sella
|
|
144
|
+
print(json.dumps(res, ensure_ascii=False, indent=1))
|
|
145
|
+
return 1
|
|
138
146
|
payload = json.dumps(res['patch_set'], ensure_ascii=False, indent=1)
|
|
139
147
|
if a.out:
|
|
140
148
|
with open(a.out, 'w', encoding='utf-8') as f:
|
|
@@ -80,7 +80,7 @@ def _add(findings, lang, sev, code, key, **fmt):
|
|
|
80
80
|
|
|
81
81
|
def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None, browser='auto',
|
|
82
82
|
interactive=False, load_more=None):
|
|
83
|
-
from .a11ydom import _get_browser, _load_error, _load_page, _pooled_page
|
|
83
|
+
from .a11ydom import _LOAD_ERR, _get_browser, _load_error, _load_page, _pooled_page
|
|
84
84
|
nav = _get_browser(preferred=browser)
|
|
85
85
|
# BrowserContext.new_page() NO acepta viewport: _pooled_page lo manda al
|
|
86
86
|
# new_context cuando hay auth_state
|
|
@@ -90,7 +90,9 @@ def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None, bro
|
|
|
90
90
|
_load_page(page, url, timeout * 1000)
|
|
91
91
|
page.wait_for_timeout(500)
|
|
92
92
|
except Exception as e: # noqa: BLE001
|
|
93
|
-
|
|
93
|
+
# the bilingual template of the rendered family: the old hard-coded
|
|
94
|
+
# Spanish text came out in English reports (review 2026-11-25)
|
|
95
|
+
return _load_error(e, lang, _LOAD_ERR.get(lang, _LOAD_ERR['en']))
|
|
94
96
|
page.evaluate(_MON)
|
|
95
97
|
page.evaluate("(() => { const c = document.querySelector("
|
|
96
98
|
" 'article a[href], [role=article] a[href], main li a[href]');"
|
|
@@ -148,7 +148,7 @@
|
|
|
148
148
|
"lang_missing_rem": "Add lang=\"en\" (the real language) to <html>: screen readers pick the synthetic voice from it.",
|
|
149
149
|
"lang_region_invalid": "lang “{l}”: the region subtag does not exist (ISO 3166). Use the language alone (“en”) or a real region (“en-GB”).",
|
|
150
150
|
"lang_region_invalid_rem": "Validate the region against the IANA Language Subtag Registry: “en” alone or “en-GB” with a real region.",
|
|
151
|
-
"limits": "Automation ≈ one third of WCAG: this is an express filter, not a substitute for manual review (keyboard, screen reader, real contrast
|
|
151
|
+
"limits": "Automation ≈ one third of WCAG: this is an express filter, not a substitute for manual review (keyboard, screen reader, real contrast).",
|
|
152
152
|
"list_structure": "{n} illegal children inside <ul>/<ol> (only <li>, <script> and <template> are valid).",
|
|
153
153
|
"list_structure_rem": "Wrap loose content in <li> or use another container: screen readers announce the list with its item count and skip non-<li> content.",
|
|
154
154
|
"meta_refresh": "<meta http-equiv=\"refresh\"> with a timed reload/redirect ({v}s).",
|
|
@@ -148,7 +148,7 @@
|
|
|
148
148
|
"lang_missing_rem": "Añade lang=\"es\" (o el idioma real) a <html>: lectores de pantalla eligen la voz sintética por él.",
|
|
149
149
|
"lang_region_invalid": "lang «{l}»: la subetiqueta de región no existe (ISO 3166). Usa el idioma solo («es») o una región real («es-AR»).",
|
|
150
150
|
"lang_region_invalid_rem": "Valida la región en el IANA Language Subtag Registry: «es» a secas o «es-AR» con región real.",
|
|
151
|
-
"limits": "Automatización ≈ un tercio de WCAG: esto es un filtro exprés, no sustituye revisión manual (teclado, lector de pantalla, contraste real
|
|
151
|
+
"limits": "Automatización ≈ un tercio de WCAG: esto es un filtro exprés, no sustituye revisión manual (teclado, lector de pantalla, contraste real).",
|
|
152
152
|
"list_structure": "{n} hijos ilegales dentro de <ul>/<ol> (solo <li>, <script> y <template> son válidos).",
|
|
153
153
|
"list_structure_rem": "Mete el contenido suelto en <li> o usa otro contenedor: los lectores anuncian la lista con su número de ítems y se saltan lo que no es <li>.",
|
|
154
154
|
"meta_refresh": "<meta http-equiv=\"refresh\"> con recarga/redirección temporizada ({v}s).",
|
|
@@ -576,7 +576,7 @@
|
|
|
576
576
|
"pdfua_contradiction_rem": "O se completa (idioma, título, etiquetado) o se retira la declaración pdfuaid del XMP: un sello que miente es peor que no llevar sello."
|
|
577
577
|
},
|
|
578
578
|
"scroll": {
|
|
579
|
-
"limits": "Auditor de scroll infinito: heurística con foco real y observador de regiones vivas en {n} tandas. No sustituye la prueba con lector de
|
|
579
|
+
"limits": "Auditor de scroll infinito: heurística con foco real y observador de regiones vivas en {n} tandas. No sustituye la prueba con lector de pantalla en el feed real.",
|
|
580
580
|
"scroll_focus": "El elemento con foco {where} tras cargar una tanda ({detail}). Fallo documentado del scroll infinito: quien navega con teclado pierde su punto de lectura (2.4.3).",
|
|
581
581
|
"scroll_focus_rem": "No re-renderices el contenedor del feed: AÑADE nodos al final (appendChild/insertAdjacentHTML). Si el foco cae en contenido eliminado, devuélvelo al equivalente nuevo.",
|
|
582
582
|
"scroll_no_announce": "{n} tandas cargadas sin ningún anuncio: no hay región aria-live/status que reciba texto durante la carga ni role=\"feed\" en el contenedor (4.1.3).",
|
package/a11y_toolkit/server.py
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kinti/a11y-toolkit",
|
|
3
|
-
"version": "5.35.
|
|
3
|
+
"version": "5.35.4",
|
|
4
4
|
"mcpName": "io.github.kinti/a11y-toolkit",
|
|
5
5
|
"description": "Zero-dependency WCAG 2.2 accessibility engine (37 MCP tools + CLI): audits, contrast fixing, SHA-256-sealed evidence packs, SARIF, EARL/ACT, CI ratchet. Self-contained: the pure-stdlib Python engine ships inside and runs via python3 \u2014 no downloads, no installs.",
|
|
6
6
|
"license": "MIT",
|