@kinti/a11y-toolkit 5.35.0 → 5.35.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,7 +16,7 @@ As an MCP server (stdio):
16
16
 
17
17
  ```json
18
18
  { "mcpServers": { "a11y-toolkit": {
19
- "command": "npx", "args": ["-y", "@kinti/a11y-toolkit", "a11y-toolkit-mcp"] } } }
19
+ "command": "npx", "args": ["-y", "-p", "@kinti/a11y-toolkit", "a11y-toolkit-mcp"] } } }
20
20
  ```
21
21
 
22
22
  ## Requirements
@@ -18,7 +18,7 @@ CLI:
18
18
  import argparse
19
19
  import json
20
20
 
21
- from .a11yaudit import normalize_signal # noqa: E402 (compat 5.10)
21
+ from .a11yaudit import completed_report_pages, normalize_signal # noqa: E402 (compat 5.10)
22
22
  import sys
23
23
  from datetime import datetime, timezone
24
24
 
@@ -96,6 +96,9 @@ def act_ids(signal):
96
96
 
97
97
  def earl(report, url=None):
98
98
  """Informe de auditoría → EARL 1.0 JSON-LD (solo hallazgos con mapeo ACT)."""
99
+ _, error = completed_report_pages(report)
100
+ if error:
101
+ return error
99
102
  assertions = []
100
103
  # site crawls anidan en reports[]: cada hallazgo pertenece a SU página —
101
104
  # aplanar sin más atribuía el fallo de /gallery a la PORTADA (revisión
@@ -162,15 +165,23 @@ def main(argv):
162
165
  print(json.dumps({'act_map': ACT_MAP, 'act_notes': ACT_NOTES},
163
166
  ensure_ascii=False, indent=1))
164
167
  return 0
165
- if a.from_audit:
166
- report = json.load(open(a.from_audit, encoding='utf-8'))
167
- elif a.url:
168
- from .a11yaudit import audit_url
169
- report = audit_url(a.url)
170
- else:
171
- ap.print_help()
172
- return 2
168
+ try:
169
+ if a.from_audit:
170
+ with open(a.from_audit, encoding='utf-8') as f:
171
+ report = json.load(f)
172
+ elif a.url:
173
+ from .a11yaudit import audit_url
174
+ report = audit_url(a.url)
175
+ else:
176
+ ap.print_help()
177
+ return 2
178
+ except (OSError, ValueError) as error:
179
+ print(json.dumps({'error': str(error)}, ensure_ascii=False))
180
+ return 1
173
181
  res = earl(report, url=a.url)
182
+ if 'error' in res:
183
+ print(json.dumps(res, ensure_ascii=False))
184
+ return 1
174
185
  if a.out:
175
186
  with open(a.out, 'w', encoding='utf-8') as f:
176
187
  json.dump(res, f, ensure_ascii=False, indent=1)
@@ -1984,14 +1984,27 @@ def page_identity(url):
1984
1984
  def audit_conditions(report):
1985
1985
  """Identify recorded capture conditions that affect comparability."""
1986
1986
  if report.get('mode') == 'rendered':
1987
- return {'color_scheme': report.get('color_scheme') or report.get('scheme')}
1987
+ return {'color_scheme': report.get('color_scheme') or report.get('scheme'),
1988
+ 'authenticated': report.get('authenticated'), 'browser': report.get('browser')}
1988
1989
  return {}
1989
1990
 
1990
1991
 
1992
+ def rendered_conditions_recorded(conditions):
1993
+ return (conditions.get('color_scheme') in ('light', 'dark')
1994
+ and isinstance(conditions.get('authenticated'), bool)
1995
+ and isinstance(conditions.get('browser'), str) and bool(conditions['browser']))
1996
+
1997
+
1998
+ def audit_conditions_match(mode, previous, current):
1999
+ return previous == current and (mode != 'rendered' or rendered_conditions_recorded(current))
2000
+
2001
+
1991
2002
  def completed_report_pages(report):
1992
2003
  """Return measured pages or the reason they cannot support a comparison."""
1993
- if not isinstance(report, dict) or report.get('error'):
2004
+ if not isinstance(report, dict):
1994
2005
  return [], {'error': 'the audit failed or was not a report'}
2006
+ if report.get('error'):
2007
+ return [], {'error': report['error']}
1995
2008
  pages = report.get('reports', [report])
1996
2009
  if not isinstance(pages, list) or not pages:
1997
2010
  return [], {'error': 'the audit contains no page reports'}
@@ -2003,12 +2016,12 @@ def completed_report_pages(report):
2003
2016
  if not isinstance(page, dict):
2004
2017
  return [], {'error': 'the audit contains an invalid page report'}
2005
2018
  status = page.get('http_status')
2006
- if (page.get('error') or not isinstance(page.get('findings'), list)
2019
+ if (page.get('error') or page.get('truncated') or not isinstance(page.get('findings'), list)
2007
2020
  or status is not None and (type(status) is not int or not 200 <= status < 400)):
2008
2021
  failures.append(page)
2009
- if failures or report.get('budget_exhausted'):
2022
+ if failures or report.get('budget_exhausted') or report.get('truncated'):
2010
2023
  return [], {'error': 'the audit did not complete; compare after all pages are measured',
2011
- 'pages_failed': [page.get('url') for page in failures]}
2024
+ 'pages_failed': [page.get('url') or page.get('file') for page in failures]}
2012
2025
  return pages, None
2013
2026
 
2014
2027
 
@@ -2897,7 +2910,7 @@ class _CheckedRedirect(urllib.request.HTTPRedirectHandler):
2897
2910
  _OPENER = urllib.request.build_opener(_CheckedRedirect)
2898
2911
 
2899
2912
 
2900
- def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None):
2913
+ def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None, *, require_complete=False):
2901
2914
  scheme = url.split(':', 1)[0].lower() if ':' in url else ''
2902
2915
  if scheme not in ('http', 'https'):
2903
2916
  # política única para TODAS las rutas de descarga (audit_url la
@@ -2915,6 +2928,7 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None):
2915
2928
  _meta['final_url'] = r.geturl()
2916
2929
  _meta['status'] = getattr(r, 'status', None)
2917
2930
  ceiling = truncate_at or MAX_HTML
2931
+ complete = truncate_at is None or require_complete
2918
2932
  # TOTAL-CLOCK reading: the socket timeout is per-operation and a server
2919
2933
  # dribbling one byte per operation reset it forever. Read in chunks
2920
2934
  # with a global deadline. A full audit requires a complete response.
@@ -2927,16 +2941,16 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None):
2927
2941
  data = b''
2928
2942
  while len(data) < ceiling + 1:
2929
2943
  if time.monotonic() >= read_deadline:
2930
- if truncate_at is None:
2944
+ if complete:
2931
2945
  raise _FetchError('err_incomplete_html')
2932
2946
  break
2933
2947
  chunk = r.read(min(65536, ceiling + 1 - len(data)))
2934
2948
  if not chunk:
2935
2949
  break
2936
2950
  data += chunk
2937
- if truncate_at is None:
2951
+ if complete:
2938
2952
  if len(data) > ceiling:
2939
- raise _FetchError('err_too_big', mb=MAX_HTML // 1000000)
2953
+ raise _FetchError('err_too_big', mb=ceiling // 1000000)
2940
2954
  if getattr(r, 'length', 0):
2941
2955
  raise _FetchError('err_incomplete_html')
2942
2956
  if (r.headers.get('Content-Encoding') or '').lower() == 'gzip' or data[:2] == b'\x1f\x8b':
@@ -2947,8 +2961,8 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None):
2947
2961
  data = stream.read(ceiling + 1)
2948
2962
  except EOFError as err:
2949
2963
  raise _FetchError('err_incomplete_html') from err
2950
- if truncate_at is None and len(data) > ceiling:
2951
- raise _FetchError('err_too_big', mb=MAX_HTML // 1000000)
2964
+ if complete and len(data) > ceiling:
2965
+ raise _FetchError('err_too_big', mb=ceiling // 1000000)
2952
2966
  if truncate_at is not None:
2953
2967
  data = data[:ceiling]
2954
2968
  ctype = (r.headers.get('Content-Type') or '').lower()
@@ -3200,7 +3214,7 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
3200
3214
  continue
3201
3215
  reports.append(report)
3202
3216
  parsers.append(pg)
3203
- if len(reports) < max_pages and not from_sitemap:
3217
+ if len(reports) < max_pages and not urls_sm:
3204
3218
  for new in _internal_links(html_pg, next_final, url):
3205
3219
  if new not in seen:
3206
3220
  queue.append(new)
@@ -44,7 +44,7 @@ import datetime
44
44
  import json
45
45
  from collections import Counter
46
46
 
47
- from .a11yaudit import audit_conditions, completed_report_pages, normalize_signal
47
+ from .a11yaudit import audit_conditions, audit_conditions_match, completed_report_pages, normalize_signal
48
48
  import sys
49
49
 
50
50
  # mensajes CLI bilingües (patrón _labels): el stdin de --init espera el JSON
@@ -145,7 +145,8 @@ def _compare_instances(budget, pages, blocking):
145
145
  prior = base.get(url)
146
146
  if prior and prior['mode'] != page['mode']:
147
147
  return {'error': 'the audit mode changed for a baseline page', 'url': url}
148
- if prior and prior.get('conditions', {}) != page['conditions']:
148
+ if prior and not audit_conditions_match(page['mode'], prior.get('conditions', {}),
149
+ page['conditions']):
149
150
  return {'error': 'the capture conditions changed or were not recorded in the baseline',
150
151
  'url': url}
151
152
  old = prior['findings'] if prior else {}
@@ -198,6 +199,8 @@ def compare(budget, audit, today=None):
198
199
  if budget.get('format') == BUDGET_FORMAT:
199
200
  verdict = _compare_instances(budget, _page_index(pages), blocking)
200
201
  else:
202
+ if any(p.get('mode') == 'rendered' for p in pages):
203
+ return {'error': 'a rendered audit needs a baseline with recorded capture conditions'}
201
204
  verdict = _compare_signals(budget, pages, blocking)
202
205
  except (ValueError, KeyError, TypeError) as err:
203
206
  return {'error': f'invalid budget input: {err}'}
@@ -142,7 +142,12 @@ def snapshot(url, output=None, auth_state=None, engine='chromium'):
142
142
  nav = launch(p)
143
143
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
144
144
  page = ctx.new_page() if auth_state else nav.new_page()
145
- page.goto(url, wait_until='networkidle', timeout=45000)
145
+ from .a11ydom import _NavigationHTTPError, _load_page
146
+ try:
147
+ _load_page(page, url, timeout=45000, wait_until='networkidle')
148
+ except _NavigationHTTPError as error:
149
+ nav.close()
150
+ return error.report()
146
151
  elements = page.evaluate(COLLECTOR)
147
152
 
148
153
  # Árbol de accesibilidad REAL (roles/nombres computados, lo que anuncia
@@ -177,6 +182,9 @@ _NOTE = {
177
182
 
178
183
 
179
184
  def diff(a, b, lang='en'):
185
+ for capture in (a, b):
186
+ if 'error' in capture:
187
+ return {**capture, 'ok': False}
180
188
  # multiset por firma: dos controles con el MISMO nombre (Edit por fila,
181
189
  # botones-icono sin name) son dos elementos — un dict por clave los
182
190
  # colapsaba y el diff decía «sin cambios» ante una duplicación
@@ -258,6 +266,9 @@ def main(argv):
258
266
  except ImportError:
259
267
  print(json.dumps({'error': 'Playwright not installed: pip install playwright && playwright install chromium'}))
260
268
  return 1
269
+ if 'error' in d:
270
+ print(json.dumps(d, ensure_ascii=False))
271
+ return 1
261
272
  print(json.dumps({'url': d['url'], 'elements': len(d['elements']),
262
273
  'focus_steps': len(d['focus_order']), 'out': a.out},
263
274
  ensure_ascii=False, indent=1))
@@ -266,8 +277,10 @@ def main(argv):
266
277
  ja = json.load(f)
267
278
  with open(a.b, encoding='utf-8') as f:
268
279
  jb = json.load(f)
269
- print(json.dumps(diff(ja, jb), ensure_ascii=False, indent=1))
270
280
  verdict = diff(ja, jb)
281
+ print(json.dumps(verdict, ensure_ascii=False, indent=1))
282
+ if 'error' in verdict:
283
+ return 1
271
284
  return 0 if verdict['ok'] else 2
272
285
 
273
286
 
@@ -26,16 +26,18 @@ import json
26
26
 
27
27
  import sys
28
28
 
29
- from .a11yaudit import audit_url, normalize_signal, page_identity
29
+ from .a11yaudit import (audit_conditions, audit_conditions_match, audit_url, normalize_signal,
30
+ page_identity, rendered_conditions_recorded)
30
31
 
31
32
 
32
- def _recheck(url, expected_url, timeout, lang, color_scheme=None):
33
+ def _recheck(url, expected_url, timeout, lang, color_scheme=None, auth_state=None, browser='auto'):
33
34
  """Obtain a successful measurement of the same page."""
34
35
  if color_scheme is None:
35
36
  fresh = audit_url(url, timeout=timeout, lang=lang)
36
37
  else:
37
38
  from .a11ydom import audit_dom_url
38
- fresh = audit_dom_url(url, timeout=timeout, lang=lang, color_scheme=color_scheme)
39
+ fresh = audit_dom_url(url, timeout=timeout, lang=lang, color_scheme=color_scheme,
40
+ auth_state=auth_state, browser=browser)
39
41
  if 'error' in fresh:
40
42
  return None, fresh['error']
41
43
  if page_identity(fresh.get('url')) != page_identity(expected_url):
@@ -87,12 +89,21 @@ def _classify_findings(previous, current, lang):
87
89
  return current, historical
88
90
 
89
91
 
90
- def disprove(url, report=None, timeout=30, lang='en'):
92
+ def _unverified(report, reason):
93
+ findings = [dict(h, disprover_status='not-rechecked') for h in report.get('findings', [])]
94
+ return dict(report, findings=findings, disprover={'executed': False, 'reason': reason})
95
+
96
+
97
+ def disprove(url, report=None, timeout=30, lang='en', auth_state=None):
91
98
  """Audit a URL and disprove findings, or verify an existing report.
92
99
 
93
100
  Return the fresh measurement and the outcomes of prior findings."""
94
101
  if report is None:
95
- report = audit_url(url, timeout=timeout, lang=lang)
102
+ if auth_state:
103
+ from .a11ydom import audit_dom_url
104
+ report = audit_dom_url(url, timeout=timeout, lang=lang, auth_state=auth_state)
105
+ else:
106
+ report = audit_url(url, timeout=timeout, lang=lang)
96
107
  if report.get('error'):
97
108
  return report
98
109
  mode_name = report.get('mode', 'static')
@@ -116,35 +127,35 @@ def disprove(url, report=None, timeout=30, lang='en'):
116
127
  return res
117
128
 
118
129
  if mode_name == 'static':
130
+ if auth_state:
131
+ return _unverified(report, 'El informe estático no admite una sesión de navegador.'
132
+ if lang == 'es' else
133
+ 'The static report does not support a browser session.')
119
134
  fresh, err = _recheck(url, expected_url, timeout, lang)
120
135
  elif mode_name == 'rendered':
121
- # condición necesaria: el esquema de color bajo el que se auditó. Sin
122
- # él no se reverifica (rechazar un contrast_fail de dark mode tras
123
- # mirar la página en claro es exactamente el falso «arreglado» que
124
- # este patrón existe para impedir)
125
- scheme = report.get('color_scheme') or report.get('scheme')
126
- if scheme not in ('light', 'dark'):
127
- res = dict(report)
128
- res['findings'] = [dict(h, disprover_status='not-rechecked') for h in findings]
129
- res['disprover'] = {
130
- 'executed': False,
131
- 'reason': ('the rendered report does not record its color_scheme '
132
- '— re-verifying under a different condition could reject '
133
- 'real findings (a dark-only contrast fail looks fixed '
134
- 'under light); re-audit with a11y_audit_dom and disprove '
135
- 'THAT report')}
136
- return res
137
- fresh, err = _recheck(url, expected_url, timeout, lang, color_scheme=scheme)
136
+ conditions = audit_conditions(report)
137
+ if not rendered_conditions_recorded(conditions):
138
+ return _unverified(report, ('El informe no registra todas las condiciones de captura. '
139
+ 'Vuelve a auditar con a11y_audit_dom.' if lang == 'es' else
140
+ 'Capture conditions are missing. Re-audit with a11y_audit_dom.'))
141
+ if bool(auth_state) != conditions['authenticated']:
142
+ return _unverified(report, ('La reauditoría necesita el mismo tipo de sesión que la captura. '
143
+ 'Usa auth_state para una captura con sesión.' if lang == 'es' else
144
+ 'Re-audit with the same session type as the capture. '
145
+ 'Use auth_state for an authenticated capture.'))
146
+ scheme = conditions['color_scheme']
147
+ fresh, err = _recheck(url, expected_url, timeout, lang, color_scheme=scheme,
148
+ auth_state=auth_state, browser=conditions['browser'])
149
+ if not err and not audit_conditions_match(mode_name, conditions, audit_conditions(fresh)):
150
+ return _unverified(report, 'La reauditoría cambió las condiciones de captura.'
151
+ if lang == 'es' else 'Capture conditions changed during re-audit.')
138
152
  else:
139
153
  # no re-verifier for this mode: report not-rechecked, never a proxy
140
154
  # audit (a keyboard finding must not vanish just because the wrong
141
155
  # method ran). `rejected` is reserved for an equivalent check that
142
156
  # actually disproves the original finding.
143
- res = dict(report)
144
- res['findings'] = [dict(h, disprover_status='not-rechecked') for h in findings]
145
- res['disprover'] = {'executed': False,
146
- 'reason': f"no re-verifier for mode {mode_name!r}"}
147
- return res
157
+ return _unverified(report, (f'No hay reauditoría para el modo {mode_name!r}.' if lang == 'es'
158
+ else f'No re-verifier for mode {mode_name!r}.'))
148
159
 
149
160
  if err:
150
161
  return dict(report, error=err, disprover={'executed': False, 'reason': err})
@@ -170,6 +181,7 @@ def main(argv):
170
181
  ap = argparse.ArgumentParser(description='Disprover: re-verify findings against the live page')
171
182
  ap.add_argument('--url', required=True, help='URL to audit and disprove')
172
183
  ap.add_argument('--file', help='existing report JSON (optional; if absent, audits first)')
184
+ ap.add_argument('--auth-state', help='local Playwright session for the original capture')
173
185
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
174
186
  ap.add_argument('--timeout', type=int, default=30)
175
187
  ap.add_argument('-o', '--out', help='save result JSON here')
@@ -178,7 +190,7 @@ def main(argv):
178
190
  if a.file:
179
191
  with open(a.file, encoding='utf-8') as f:
180
192
  report = json.load(f)
181
- res = disprove(a.url, report=report, timeout=a.timeout, lang=a.lang)
193
+ res = disprove(a.url, report=report, timeout=a.timeout, lang=a.lang, auth_state=a.auth_state)
182
194
  if 'error' in res:
183
195
  print(json.dumps(res))
184
196
  return 1