@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.
@@ -18,9 +18,11 @@ CLI:
18
18
 
19
19
  import argparse
20
20
  import json
21
+ import os
21
22
  import re
22
23
  import sys
23
24
  import zipfile
25
+ from xml.etree import ElementTree as ET
24
26
  from . import a11yi18n
25
27
 
26
28
  T = a11yi18n.pair('docx') # locales/<lang>.json — community-editable
@@ -28,6 +30,18 @@ T = a11yi18n.pair('docx') # locales/<lang>.json — community-editable
28
30
  # techo de ingesta por miembro ZIP: 40 MB descomprimidos — un .docx legítimo
29
31
  # no llega ni de lejos; una bomba ZIP sí
30
32
  _MAX_MEMBER_BYTES = 40 * 1024 * 1024
33
+ _WORD_NS = ('http://schemas.openxmlformats.org/wordprocessingml/2006/main',
34
+ 'http://purl.oclc.org/ooxml/wordprocessingml/main')
35
+ _DRAWING_PROPERTIES = {
36
+ '{http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing}docPr',
37
+ '{http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing}docPr',
38
+ }
39
+ _RELATIONSHIP_IDS = (
40
+ '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id',
41
+ '{http://purl.oclc.org/ooxml/officeDocument/relationships}id',
42
+ )
43
+ _RELATIONSHIP = '{http://schemas.openxmlformats.org/package/2006/relationships}Relationship'
44
+ _HEADING_NAME = re.compile(r'^(?:heading|encabezado|t[ií]tulo|überschrift|titre)\s*([1-9])$', re.I)
31
45
 
32
46
  _CRIT = {
33
47
  'docx_no_alt': ('1.1.1', 'high'), 'docx_fake_headings': ('1.3.1', 'medium'),
@@ -57,7 +71,7 @@ class _OverCap(Exception):
57
71
 
58
72
 
59
73
  def _capped_read(z, member):
60
- """Texto de un miembro del ZIP (None si no existe). El techo de
74
+ """Bytes de un miembro del ZIP (None si no existe). El techo de
61
75
  descompresión por miembro vive AQUÍ, en la única puerta de lectura del
62
76
  cribado: file_size es el declarado del directorio central, el estándar
63
77
  contra bombas ZIP de los descompresores serios. Toda lectura pasa por
@@ -70,195 +84,159 @@ def _capped_read(z, member):
70
84
  if info.file_size > _MAX_MEMBER_BYTES:
71
85
  raise _OverCap(f'{member} declares {info.file_size} bytes '
72
86
  f'(>{_MAX_MEMBER_BYTES}): over the intake cap')
73
- return z.read(member).decode('utf-8', errors='replace')
87
+ return z.read(member)
88
+
89
+
90
+ class _DocumentTree(ET.TreeBuilder):
91
+ def doctype(self, name, pubid, system):
92
+ raise ET.ParseError('DOCTYPE is not supported in DOCX parts')
93
+
94
+
95
+ def _read_xml(z, member):
96
+ data = _capped_read(z, member)
97
+ if data is None:
98
+ return None
99
+ return ET.fromstring(data, parser=ET.XMLParser(target=_DocumentTree()))
74
100
 
75
101
 
76
102
  def docx_screen(path, lang='en'):
77
- """Cribado de accesibilidad de un .docx (solo stdlib: zipfile + regex XML)."""
103
+ """Screen a local DOCX using the standard library ZIP and XML readers."""
78
104
  try:
79
- z = zipfile.ZipFile(path)
80
- except (zipfile.BadZipFile, FileNotFoundError, IsADirectoryError, PermissionError) as e:
81
- return {'error': f'no es un .docx legible: {e}'}
82
- if 'word/document.xml' not in z.namelist():
83
- return {'error': 'ZIP without word/document.xml (is this really a .docx?)'}
84
- try:
85
- return _screen_zip(z, lang, path)
86
- except _OverCap as e:
87
- # contenido NO confiable: la ingesta no descomprime sin límite
88
- return {'error': str(e)}
105
+ with zipfile.ZipFile(path) as archive:
106
+ return _screen_zip(archive, lang, path)
107
+ except (OSError, zipfile.BadZipFile, RuntimeError, ET.ParseError, ValueError, _OverCap) as error:
108
+ message = 'No se pudo leer el DOCX' if lang == 'es' else 'Could not read DOCX'
109
+ return {'error': f'{message}: {error}', 'mode': 'docx', 'file': os.path.basename(path)}
89
110
 
90
111
 
91
112
  def _screen_zip(z, lang, path):
92
- body = _capped_read(z, 'word/document.xml')
93
-
113
+ body = _read_xml(z, 'word/document.xml')
114
+ if body is None or body.tag not in {f'{{{uri}}}document' for uri in _WORD_NS}:
115
+ message = ('Falta el documento XML de WordprocessingML' if lang == 'es'
116
+ else 'Missing WordprocessingML document')
117
+ return {'error': message, 'mode': 'docx', 'file': os.path.basename(path)}
118
+ word = body.tag.split('}', 1)[0] + '}'
119
+ namespaces = {'w': word[1:-1]}
120
+ value = word + 'val'
121
+ styles = _read_xml(z, 'word/styles.xml')
122
+ relationships = _read_xml(z, 'word/_rels/document.xml.rels')
94
123
  findings = []
95
124
 
96
- def add(key):
97
- crit, sev = _CRIT[key]
98
- findings.append({'severity': sev, 'criterion': f'{crit} (DOCX)',
99
- 'signal': key, 'issue': _t(lang, key),
125
+ def add(key, **fields):
126
+ criterion, severity = _CRIT[key]
127
+ findings.append({'severity': severity, 'criterion': f'{criterion} (DOCX)',
128
+ 'signal': key, 'issue': _t(lang, key).format(**fields),
100
129
  'remediation': _t(lang, key + '_rem')})
101
130
 
102
- # imágenes: cada <wp:docPr> es una imagen/gráfico; descr = alt text
103
- docprs = re.findall(r'<wp:docPr\b[^>]*>', body)
104
- no_alt = [d for d in docprs
105
- if 'descr=' not in d or re.search(r'descr="\s*"', d)]
106
- if docprs and no_alt:
107
- n = len(no_alt)
108
- findings.append({'severity': 'high', 'criterion': '1.1.1 (DOCX)',
109
- 'signal': 'docx_no_alt',
110
- 'issue': _t(lang, 'docx_no_alt').format(n=n),
111
- 'remediation': _t(lang, 'docx_no_alt_rem')})
112
-
113
- # idioma: w:lang en styles.xml (default del documento)
131
+ def paragraph_text(element):
132
+ return ''.join(text.text or '' for text in element.iter(word + 't')).strip()
133
+
134
+ docprs = [node for node in body.iter() if node.tag in _DRAWING_PROPERTIES]
135
+ no_alt = sum(not node.get('descr', '').strip() for node in docprs)
136
+ if no_alt:
137
+ add('docx_no_alt', n=no_alt)
138
+
114
139
  language = None
115
- styles = _capped_read(z, 'word/styles.xml')
116
140
  if styles is not None:
117
- m = re.search(r'<w:lang[^>]*w:val="([^"]+)"', styles)
118
- language = m.group(1) if m else None
141
+ default = styles.find('w:docDefaults/w:rPrDefault/w:rPr/w:lang', namespaces)
142
+ if default is None:
143
+ default = styles.find('.//w:lang', namespaces)
144
+ if default is not None:
145
+ language = default.get(value)
119
146
  if not language:
120
147
  add('docx_no_lang')
121
148
 
122
- # tablas sin fila de encabezado (tblHeader) — POR TABLA (5ª pasada: el
123
- # encabezado de la primera tapaba la falta de la segunda con un conteo
124
- # global, y <w:tblHeader w:val="true"/> —con atributos— no casaba con el
125
- # regex de elemento vacío)
126
- n_tables = len(re.findall(r'<w:tbl>', body))
149
+ tables = list(body.iter(word + 'tbl'))
127
150
  tables_missing = 0
128
- for tbl in re.findall(r'<w:tbl>.*?</w:tbl>', body, re.S):
129
- marked = [m for m in re.findall(r'<w:tblHeader\b[^>]*/?>', tbl)
130
- if not re.search(r'w:val="(?:0|false|off)"', m, re.I)]
131
- if not marked:
151
+ for table in tables:
152
+ pending, has_header = list(table), False
153
+ for node in pending:
154
+ if node.tag == word + 'tr':
155
+ header = node.find('w:trPr/w:tblHeader', namespaces)
156
+ if header is not None and header.get(value, 'true').lower() not in ('0', 'false', 'off'):
157
+ has_header = True
158
+ break
159
+ elif node.tag != word + 'tbl':
160
+ pending.extend(node)
161
+ if not has_header:
132
162
  tables_missing += 1
133
- if n_tables and tables_missing:
134
- add('docx_table_no_header')
135
-
136
- # falsos encabezados: párrafo todo-bold + tamaño grande sin estilo Heading
137
- fake = 0
138
- for para in re.findall(r'<w:p\b.*?</w:p>', body, re.S):
139
- if 'w:val="Heading' in para:
140
- continue
141
- # bold real: <w:b> presente SIN val de apagado explícito (0/false)
142
- # — `<w:b w:val="0"/>` es bold-OFF y no cuenta
143
- has_bold = any(not re.search(r'w:val="(?:0|false)"', tag)
144
- for tag in re.findall(r'<w:b\b[^>]*>', para))
145
- m_sz = re.search(r'<w:sz w:val="(\d+)"', para)
146
- large = bool(m_sz) and int(m_sz.group(1)) >= 28
147
- text = ''.join(re.findall(r'<w:t[^>]*>([^<]*)</w:t>', para)).strip()
148
- if has_bold and large and 2 < len(text) < 120:
149
- fake += 1
150
- if fake:
151
- findings.append({'severity': 'medium', 'criterion': '1.3.1 (DOCX)',
152
- 'signal': 'docx_fake_headings',
153
- 'issue': _t(lang, 'docx_fake_headings').format(n=fake),
154
- 'remediation': _t(lang, 'docx_fake_headings_rem')})
155
-
156
- # ── listas falsas: párrafos con viñetas/números TIPOGRAFIADOS en vez de
157
- # lista de Word (sin w:numPr). Umbral anti-FP: 2+ párrafos CONSECUTIVOS
158
- # con glifo de viñeta, o 3+ consecutivos numerados con incremento +1
159
- # (los «1. Enero» de las fechas no incrementan y quedan fuera).
160
- _doc_paragraphs = re.findall(r'<w:p\b.*?</w:p>|<w:p\b[^>]*/>', body, re.S)
161
- def _ptext(p):
162
- return ''.join(re.findall(r'<w:t[^>]*>([^<]*)</w:t>', p)).strip()
163
- fake_list_groups, _run = 0, []
164
- def _flush():
165
- nonlocal _run, fake_list_groups
166
- n_bul = sum(1 for t in _run if t[0] == 'b')
167
- if n_bul >= 2:
163
+ if tables_missing:
164
+ add('docx_table_no_header', n=tables_missing)
165
+
166
+ heading_styles = {}
167
+ if styles is not None:
168
+ for style in styles.iter(word + 'style'):
169
+ name = style.find('w:name', namespaces)
170
+ if name is not None:
171
+ match = _HEADING_NAME.fullmatch(name.get(value, '').strip())
172
+ if match:
173
+ heading_styles[style.get(word + 'styleId')] = int(match.group(1))
174
+
175
+ levels, fake = [], 0
176
+ fake_list_groups, sequence = 0, []
177
+
178
+ def flush():
179
+ nonlocal fake_list_groups
180
+ if sequence.count(None) >= 2:
181
+ fake_list_groups += 1
182
+ elif (len(sequence) >= 3 and sequence[0] in (0, 1)
183
+ and all(number == sequence[0] + i for i, number in enumerate(sequence))):
168
184
  fake_list_groups += 1
169
- elif len(_run) >= 3:
170
- nums = [t[1] for t in _run if t[0] == 'n']
171
- if len(nums) == len(_run):
172
- ok = all(nums[i+1] == nums[i] + 1 for i in range(len(nums)-1))
173
- if ok and nums[0] in (0, 1):
174
- fake_list_groups += 1
175
- _run = []
176
- for p in _doc_paragraphs:
177
- if '<w:numPr' in p:
178
- _flush(); continue
179
- t = _ptext(p)
180
- if not t:
181
- _flush(); continue
182
- if t[0] in _BULLET:
183
- _run.append(('b', None)); continue
184
- m = re.match(r'^(\d{1,3})[.)]\s+\S', t)
185
- if m:
186
- _run.append(('n', int(m.group(1)))); continue
187
- _flush()
188
- _flush()
185
+ sequence.clear()
186
+
187
+ for paragraph in body.iter(word + 'p'):
188
+ style = paragraph.find('w:pPr/w:pStyle', namespaces)
189
+ style_id = style.get(value, '') if style is not None else ''
190
+ direct = re.fullmatch(r'Heading([1-9])', style_id, re.I)
191
+ level = int(direct.group(1)) if direct else heading_styles.get(style_id)
192
+ text = paragraph_text(paragraph)
193
+ if level and not re.match(r'(?i)^TOC\d|Sumario|TDC', style_id):
194
+ levels.append(level)
195
+ elif not style_id.startswith('Heading') and 2 < len(text) < 120:
196
+ has_bold = any(node.get(value, 'true').lower() not in ('0', 'false')
197
+ for node in paragraph.iter(word + 'b'))
198
+ size = paragraph.find('.//w:sz', namespaces)
199
+ size_value = size.get(value, '') if size is not None else ''
200
+ if has_bold and size_value.isascii() and size_value.isdecimal() and int(size_value) >= 28:
201
+ fake += 1
202
+
203
+ if not text or paragraph.find('.//w:numPr', namespaces) is not None:
204
+ flush()
205
+ elif text[0] in _BULLET:
206
+ sequence.append(None)
207
+ else:
208
+ number = re.match(r'^(\d{1,3})[.)]\s+\S', text)
209
+ if number:
210
+ sequence.append(int(number.group(1)))
211
+ else:
212
+ flush()
213
+ flush()
214
+ if fake:
215
+ add('docx_fake_headings', n=fake)
189
216
  if fake_list_groups:
190
- findings.append({'severity': 'medium', 'criterion': '1.3.1 (DOCX)',
191
- 'signal': 'docx_fake_list',
192
- 'issue': _t(lang, 'docx_fake_list').format(n=fake_list_groups),
193
- 'remediation': _t(lang, 'docx_fake_list_rem')})
194
-
195
- # ── saltos de nivel de encabezado: Heading1 → Heading3 aplana la
196
- # navegación. Niveles por pStyle directo (HeadingN) O por styles.xml
197
- # (los Word localizados escriben styleIds numéricos cuyo NOMBRE es
198
- # «heading N» / «Encabezado N» / «Título N»)
199
- _style_heads = {}
200
- sx = _capped_read(z, 'word/styles.xml') or ''
201
- for m in re.finditer(
202
- r'<w:style [^>]*w:styleId="([^"]+)"[^>]*>.*?'
203
- r'<w:name w:val="([^"]*)"', sx, re.S):
204
- mn = re.match(r'(?i)^(?:heading|encabezado|t[ií]tulo|'
205
- r'berschrift|titre)\s*([1-9])$', m.group(2).strip())
206
- if mn:
207
- _style_heads[m.group(1)] = int(mn.group(1))
208
- levels = []
209
- for p in _doc_paragraphs:
210
- ms = re.search(r'<w:pStyle w:val="([^"]+)"', p)
211
- if not ms:
212
- continue
213
- sid = ms.group(1)
214
- if re.match(r'(?i)^TOC\d|Sumario|TDC', sid):
215
- continue
216
- md = re.match(r'(?i)^Heading([1-9])$', sid)
217
- if md:
218
- levels.append(int(md.group(1)))
219
- elif sid in _style_heads:
220
- levels.append(_style_heads[sid])
221
- skips = sum(1 for i in range(1, len(levels))
222
- if levels[i] > levels[i-1] + 1)
223
- if levels and skips:
224
- findings.append({'severity': 'low', 'criterion': '1.3.1 (DOCX)',
225
- 'signal': 'docx_heading_skips',
226
- 'issue': _t(lang, 'docx_heading_skips').format(n=skips),
227
- 'remediation': _t(lang, 'docx_heading_skips_rem')})
228
-
229
- # ── enlaces genéricos: «pincha aquí» (repetido), la URL cruda como
230
- # texto, o el mismo genérico apuntando a destinos distintos. Relaciones
231
- # desde word/_rels/document.xml.rels
232
- rels = {}
233
- rx = _capped_read(z, 'word/_rels/document.xml.rels') or ''
234
- for m in re.finditer(r'<Relationship [^>]*Id="([^"]+)"[^>]*Target="([^"]+)"', rx):
235
- rels[m.group(1)] = m.group(2)
236
- gen_counts, gen_multi, raw_url, img_links_noalt = {}, 0, 0, 0
237
- for hl in re.findall(r'<w:hyperlink\b.*?</w:hyperlink>', body, re.S):
238
- txt = ''.join(re.findall(r'<w:t[^>]*>([^<]*)</w:t>', hl)).strip()
239
- target = ''
240
- mr = re.search(r'r:id="([^"]+)"', hl)
241
- if mr:
242
- target = rels.get(mr.group(1), '')
243
- low = txt.lower().rstrip('.…: ')
244
- if txt and target and txt.replace(' ', '') in target:
245
- raw_url += 1
246
- elif low in _GENERIC_LINK:
247
- if gen_counts.get(low, (0, set()))[0] >= 1:
248
- gen_multi += 1
249
- n0, t0 = gen_counts.get(low, (0, set()))
250
- gen_counts[low] = (n0 + 1, t0 | {target})
251
- # enlace solo-imagen sin alt (el docPr dentro del hyperlink sin descr)
252
- if '<w:drawing' in hl or '<a:blip' in hl:
253
- for dp in re.findall(r'<wp:docPr\b[^>]*>', hl):
254
- if 'descr=' not in dp or re.search(r'descr="\s*"', dp):
255
- img_links_noalt += 1
256
- generic_n = gen_multi + raw_url + img_links_noalt
257
- if generic_n:
258
- findings.append({'severity': 'medium', 'criterion': '2.4.4 (DOCX)',
259
- 'signal': 'docx_generic_link',
260
- 'issue': _t(lang, 'docx_generic_link').format(n=generic_n),
261
- 'remediation': _t(lang, 'docx_generic_link_rem')})
217
+ add('docx_fake_list', n=fake_list_groups)
218
+ skips = sum(right > left + 1 for left, right in zip(levels, levels[1:]))
219
+ if skips:
220
+ add('docx_heading_skips', n=skips)
221
+
222
+ targets = ({rel.get('Id'): rel.get('Target', '') for rel in relationships.iter(_RELATIONSHIP)}
223
+ if relationships is not None else {})
224
+ generic_links, seen_generic = 0, set()
225
+ for hyperlink in body.iter(word + 'hyperlink'):
226
+ text = paragraph_text(hyperlink)
227
+ rel_id = hyperlink.get(_RELATIONSHIP_IDS[0]) or hyperlink.get(_RELATIONSHIP_IDS[1])
228
+ target = targets.get(rel_id, '')
229
+ label = text.lower().rstrip('.…: ')
230
+ if text and target and text.replace(' ', '') in target:
231
+ generic_links += 1
232
+ elif label in _GENERIC_LINK:
233
+ if label in seen_generic:
234
+ generic_links += 1
235
+ seen_generic.add(label)
236
+ generic_links += sum(not node.get('descr', '').strip() for node in hyperlink.iter()
237
+ if node.tag in _DRAWING_PROPERTIES)
238
+ if generic_links:
239
+ add('docx_generic_link', n=generic_links)
262
240
 
263
241
  order = {'high': 0, 'medium': 1, 'low': 2}
264
242
  findings.sort(key=lambda h: order[h['severity']])
@@ -268,9 +246,9 @@ def _screen_zip(z, lang, path):
268
246
  from .a11yaudit import compute_score
269
247
 
270
248
  return {
271
- 'mode': 'docx', 'file': str(path).rsplit('/', 1)[-1],
249
+ 'mode': 'docx', 'file': os.path.basename(path),
272
250
  'language': language, 'images': len(docprs),
273
- 'tables': n_tables, 'tables_without_header': tables_missing,
251
+ 'tables': len(tables), 'tables_without_header': tables_missing,
274
252
  'heading_levels': levels,
275
253
  'score': compute_score(findings),
276
254
  'findings': findings,
@@ -285,8 +263,9 @@ def main(argv):
285
263
  ap.add_argument('docx', help='local .docx file')
286
264
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
287
265
  a = ap.parse_args(argv)
288
- print(json.dumps(docx_screen(a.docx, lang=a.lang), ensure_ascii=False, indent=1))
289
- return 0
266
+ result = docx_screen(a.docx, lang=a.lang)
267
+ print(json.dumps(result, ensure_ascii=False, indent=1))
268
+ return 1 if 'error' in result else 0
290
269
 
291
270
 
292
271
  if __name__ == '__main__':
@@ -26,6 +26,32 @@ from .contrast import parse_color, decode_png, sample_rgb, hexs, luminance, rati
26
26
  # carga y limits): bilingües aquí, igual que el catálogo (invariante es/en)
27
27
  _LOAD_ERR = {'es': 'no se pudo cargar: {e}',
28
28
  'en': 'could not load: {e}'}
29
+
30
+
31
+ class _NavigationHTTPError(RuntimeError):
32
+ def __init__(self, status, url):
33
+ super().__init__(f'HTTP {status}: could not load the requested page')
34
+ self.status = status
35
+ self.url = url
36
+
37
+ def report(self, lang='en'):
38
+ message = (f'HTTP {self.status}: no se pudo cargar la página solicitada'
39
+ if lang == 'es' else str(self))
40
+ return {'error': message, 'url': self.url, 'http_status': self.status}
41
+
42
+
43
+ def _load_page(page, url, timeout, wait_until='load'):
44
+ response = page.goto(url, wait_until=wait_until, timeout=timeout)
45
+ if response is not None and response.status >= 400:
46
+ raise _NavigationHTTPError(response.status, page.url)
47
+
48
+
49
+ def _load_error(error, lang, template='{e}'):
50
+ if isinstance(error, _NavigationHTTPError):
51
+ return error.report(lang)
52
+ return {'error': template.format(e=error)}
53
+
54
+
29
55
  _LIMITS_HCM = {
30
56
  'es': ('Heurística de revisión (1.4.3/1.4.11 en HCM): los fills '
31
57
  'coloreados hardcoded en SVG suelen caer al heredado con '
@@ -155,7 +181,7 @@ class _NoPoolBrowser:
155
181
  def __init__(self, headless, preferred):
156
182
  from playwright.sync_api import sync_playwright
157
183
  self._pw = sync_playwright().start()
158
- self._nav, kind = _detect_browser(self._pw, preferred)
184
+ self._nav, self.kind = _detect_browser(self._pw, preferred)
159
185
  self._live_pages = 0
160
186
 
161
187
  def new_context(self, **kw):
@@ -1185,10 +1211,10 @@ def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1185
1211
  page, close_page = _pooled_page(nav, auth_state)
1186
1212
  try:
1187
1213
  try:
1188
- page.goto(url, wait_until='load', timeout=timeout * 1000)
1214
+ _load_page(page, url, timeout * 1000)
1189
1215
  page.wait_for_timeout(400)
1190
1216
  except Exception as e: # noqa: BLE001
1191
- return {'error': _t(lang, 'fetch_error').format(e=e)}
1217
+ return _load_error(e, lang, _t(lang, 'fetch_error'))
1192
1218
  url_before = page.url
1193
1219
  pre = page.evaluate(_JS_FORM_PRE)
1194
1220
  try:
@@ -1259,10 +1285,10 @@ def sr_transcript(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1259
1285
  page, close_page = _pooled_page(nav, auth_state)
1260
1286
  try:
1261
1287
  try:
1262
- page.goto(url, wait_until='load', timeout=timeout * 1000)
1288
+ _load_page(page, url, timeout * 1000)
1263
1289
  page.wait_for_timeout(400)
1264
1290
  except Exception as e:
1265
- return {'error': str(e)[:100]}
1291
+ return _load_error(e, lang, '{e!s:.100}')
1266
1292
 
1267
1293
  try:
1268
1294
  tree = page.locator('body').aria_snapshot()
@@ -1343,10 +1369,10 @@ def audit_hover(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1343
1369
  page, close_page = _pooled_page(nav, auth_state)
1344
1370
  try:
1345
1371
  try:
1346
- page.goto(url, wait_until='load', timeout=timeout * 1000)
1372
+ _load_page(page, url, timeout * 1000)
1347
1373
  page.wait_for_timeout(400)
1348
1374
  except Exception as e:
1349
- return {'error': str(e)[:100]}
1375
+ return _load_error(e, lang, '{e!s:.100}')
1350
1376
  # tooltips visibles ANTES de tocar nada: los preexistentes (ajenos)
1351
1377
  # jamas se atribuyen a un control por el mero hecho de hoverear
1352
1378
  _preexisting_tips = page.evaluate(_TOOLTIPS_VISIBLE_JS)
@@ -1538,10 +1564,10 @@ def audit_reflow(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1538
1564
  page, close_page = _pooled_page(nav, auth_state, viewport={'width': 1280, 'height': 800})
1539
1565
  try:
1540
1566
  try:
1541
- page.goto(url, wait_until='load', timeout=timeout * 1000)
1567
+ _load_page(page, url, timeout * 1000)
1542
1568
  page.wait_for_timeout(300)
1543
1569
  except Exception as e: # noqa: BLE001
1544
- return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1570
+ return _load_error(e, lang, _LOAD_ERR.get(lang, _LOAD_ERR['en']))
1545
1571
 
1546
1572
  page.set_viewport_size({'width': 320, 'height': 800})
1547
1573
  page.wait_for_timeout(500)
@@ -1659,10 +1685,10 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1659
1685
  page, close_page = _pooled_page(nav, auth_state)
1660
1686
  try:
1661
1687
  try:
1662
- page.goto(url, wait_until='load', timeout=timeout * 1000)
1688
+ _load_page(page, url, timeout * 1000)
1663
1689
  page.wait_for_timeout(400)
1664
1690
  except Exception as e: # noqa: BLE001
1665
- return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1691
+ return _load_error(e, lang, _LOAD_ERR.get(lang, _LOAD_ERR['en']))
1666
1692
 
1667
1693
  page.evaluate("document.querySelectorAll('[data-a11ystop]').forEach(e => {"
1668
1694
  " e.removeAttribute('data-a11ystop'); e.removeAttribute('data-a11yruta'); })")
@@ -2015,14 +2041,14 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
2015
2041
  page, close_page = _pooled_page(nav, auth_state)
2016
2042
  try:
2017
2043
  try:
2018
- page.goto(url, wait_until='load', timeout=timeout * 1000)
2044
+ _load_page(page, url, timeout * 1000)
2019
2045
  page.wait_for_timeout(400)
2020
2046
  normal = page.evaluate(_JS_FC)
2021
2047
  page.emulate_media(forced_colors='active')
2022
2048
  page.wait_for_timeout(400)
2023
2049
  forced = page.evaluate(_JS_FC)
2024
2050
  except Exception as e: # noqa: BLE001
2025
- return {'error': _t_audit(lang, 'fetch_error').format(e=e)}
2051
+ return _load_error(e, lang, _t_audit(lang, 'fetch_error'))
2026
2052
  finally:
2027
2053
  close_page()
2028
2054
 
@@ -2087,14 +2113,14 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
2087
2113
  page, close_page = _pooled_page(nav, auth_state)
2088
2114
  try:
2089
2115
  try:
2090
- page.goto(url, wait_until='load', timeout=timeout * 1000)
2116
+ _load_page(page, url, timeout * 1000)
2091
2117
  page.wait_for_timeout(600)
2092
2118
  normal = page.evaluate(_JS_RM)
2093
2119
  page.emulate_media(reduced_motion='reduce')
2094
2120
  page.wait_for_timeout(600)
2095
2121
  reduced = page.evaluate(_JS_RM)
2096
2122
  except Exception as e: # noqa: BLE001
2097
- return {'error': _t_audit(lang, 'fetch_error').format(e=e)}
2123
+ return _load_error(e, lang, _t_audit(lang, 'fetch_error'))
2098
2124
  finally:
2099
2125
  close_page()
2100
2126
 
@@ -2145,6 +2171,7 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
2145
2171
  storage_state de Playwright (cookies/localStorage exportados con la sesión
2146
2172
  iniciada) para auditar detrás de login."""
2147
2173
  nav = _get_browser(preferred=browser)
2174
+ browser_kind = nav.kind if isinstance(nav, _NoPoolBrowser) else _POOL['type']
2148
2175
  page, close_page = _pooled_page(nav, auth_state)
2149
2176
  _resp = None
2150
2177
  page_url_final = None
@@ -2157,8 +2184,7 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
2157
2184
  _resp = page.goto(url, wait_until='load', timeout=timeout * 1000)
2158
2185
  page.wait_for_timeout(400)
2159
2186
  except Exception as e: # noqa: BLE001
2160
- if not page.content() or page.url in ('about:blank', ''):
2161
- return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
2187
+ return _load_error(e, lang, _LOAD_ERR.get(lang, _LOAD_ERR['en']))
2162
2188
  data = page.evaluate(_JS, MAX_EXAMPLES)
2163
2189
  # 1.4.12: inject the WCAG spacing overrides, count clipped texts
2164
2190
  data['spacingClipped'] = page.evaluate(_JS_SPACING)
@@ -2209,6 +2235,8 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
2209
2235
  # /account redirigió — antes conservaba /account y solo añadía la nota
2210
2236
  final_url = (page_url_final or url).split('#')[0]
2211
2237
  report_out = audit_dom(data, final_url, lang=lang, color_scheme=color_scheme)
2238
+ report_out['authenticated'] = bool(auth_state)
2239
+ report_out['browser'] = browser_kind
2212
2240
  try:
2213
2241
  _st = _resp.status if _resp is not None else None
2214
2242
  except Exception: # noqa: BLE001 — respuesta ya consumida
@@ -2253,7 +2281,10 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
2253
2281
  nav = _get_browser(preferred=browser)
2254
2282
  page, close_page = _pooled_page(nav, auth_state)
2255
2283
  try:
2256
- page.goto(url, wait_until='load', timeout=timeout * 1000)
2284
+ try:
2285
+ _load_page(page, url, timeout * 1000)
2286
+ except Exception as e: # noqa: BLE001
2287
+ return _load_error(e, lang, _LOAD_ERR.get(lang, _LOAD_ERR['en']))
2257
2288
  page.wait_for_timeout(300)
2258
2289
  loc = page.locator(selector).first
2259
2290
  try:
@@ -2463,7 +2494,7 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2463
2494
  if auth_state else nav.new_context(color_scheme=scheme))
2464
2495
  page = ctx.new_page()
2465
2496
  try:
2466
- page.goto(url, wait_until='load', timeout=timeout * 1000)
2497
+ _load_page(page, url, timeout * 1000)
2467
2498
  page.wait_for_timeout(300)
2468
2499
  return _pass(page)
2469
2500
  finally:
@@ -2472,7 +2503,10 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2472
2503
  except Exception: # noqa: BLE001
2473
2504
  pass
2474
2505
 
2475
- entries, skipped, unparsed = _run('light')
2506
+ try:
2507
+ entries, skipped, unparsed = _run('light')
2508
+ except _NavigationHTTPError as error:
2509
+ return error.report(lang)
2476
2510
  report = {'mode': 'contrast-walk', 'url': url, 'scheme': 'light',
2477
2511
  'checked': len(entries),
2478
2512
  'elements': entries,
@@ -2489,7 +2523,10 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2489
2523
  e['suggestion'] = s
2490
2524
 
2491
2525
  if dark:
2492
- entries_d, skipped_d, _unp_d = _run('dark')
2526
+ try:
2527
+ entries_d, skipped_d, _unp_d = _run('dark')
2528
+ except _NavigationHTTPError as error:
2529
+ return error.report(lang)
2493
2530
  report['dark'] = {'scheme': 'dark', 'checked': len(entries_d),
2494
2531
  'elements': entries_d,
2495
2532
  'summary': _summarize(entries_d, skipped_d, _unp_d)}
@@ -41,7 +41,7 @@ DEFAULT_ENGINES = ('chromium', 'firefox', 'webkit')
41
41
 
42
42
 
43
43
  def _capture(url, engine, auth_state=None):
44
- """One engine's snapshot; raises on engine failure (caller records it)."""
44
+ """Capture one engine's snapshot."""
45
45
  return a11ydiff.snapshot(url, engine=engine, auth_state=auth_state)
46
46
 
47
47
 
@@ -90,8 +90,11 @@ def matrix(url, engines=None, auth_state=None, capture=None):
90
90
  failed.append({'engine': name, 'error': f'unknown engine (known: {", ".join(ENGINES)})'})
91
91
  continue
92
92
  try:
93
- snaps[name] = capture(url, name, auth_state)
94
- s = snaps[name]
93
+ s = capture(url, name, auth_state)
94
+ if 'error' in s:
95
+ failed.append({**s, 'engine': name})
96
+ continue
97
+ snaps[name] = s
95
98
  ok.append({'engine': name, 'elements': len(s.get('elements', [])),
96
99
  'focus_steps': len(s.get('focus_order', [])),
97
100
  'tree': 'accessibility_tree' in s or 'arbol_accesible' in s})
@@ -127,9 +130,8 @@ def matrix(url, engines=None, auth_state=None, capture=None):
127
130
  'conformance claim.'),
128
131
  }
129
132
  if not enough:
130
- report['note'] = ('fewer than 2 engines launched: install them with '
131
- '`playwright install firefox webkit` — a matrix of one '
132
- 'engine cannot see cross-engine behavior')
133
+ report['note'] = ('fewer than 2 engines captured the page. Check the reported '
134
+ 'errors. Install missing engines with `playwright install firefox webkit`.')
133
135
  return report
134
136
 
135
137