@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.
@@ -27,6 +27,7 @@ CLI:
27
27
  import argparse
28
28
  import hashlib
29
29
  import json
30
+ import re
30
31
 
31
32
  from .a11yaudit import normalize_report # noqa: E402 (compat 5.10)
32
33
  import sys
@@ -68,6 +69,11 @@ def _is_page_report(report):
68
69
  and (status is None or type(status) is int and 200 <= status < 400))
69
70
 
70
71
 
72
+ def _complete_page(report):
73
+ return (_is_page_report(report) and not report.get('truncated')
74
+ and not report.get('budget_exhausted') and not report.get('page_errors'))
75
+
76
+
71
77
  def _canon(obj):
72
78
  return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
73
79
 
@@ -163,26 +169,30 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
163
169
  if isinstance(inf, dict) and inf.get('error'):
164
170
  state = 'failed'
165
171
  elif isinstance(inf, dict) and isinstance(inf.get('reports'), list):
166
- usable = [normalize_report(p) for p in inf['reports'] if _is_page_report(p)]
172
+ usable = [normalize_report(p) for p in inf['reports'] if _complete_page(p)]
167
173
  if usable:
168
174
  state = ('partial' if len(usable) != len(inf['reports']) or inf.get('page_errors')
169
- or inf.get('budget_exhausted') else 'complete')
175
+ or inf.get('budget_exhausted') or inf.get('truncated') else 'complete')
170
176
  modes_included.update(p.get('mode', 'static') for p in usable)
171
177
  # The disprover puts its revised findings on the site wrapper.
172
178
  # Only actual page reports contribute executed modes.
173
- if _is_page_report(inf) and inf['findings']:
179
+ if state == 'complete' and _complete_page(inf) and inf['findings']:
174
180
  inf = normalize_report(inf)
175
181
  pages.append(inf)
176
182
  else:
177
183
  pages.extend(usable)
184
+ elif any(_is_page_report(p) for p in inf['reports']):
185
+ state = 'partial'
178
186
  elif inf.get('page_errors') or any(isinstance(p, dict) and p.get('error')
179
187
  for p in inf['reports']):
180
188
  state = 'failed'
181
189
  elif _is_page_report(inf):
182
190
  inf = normalize_report(inf)
183
- state = 'complete'
184
- pages.append(inf)
185
- modes_included.add(inf.get('mode', 'static'))
191
+ state = 'partial'
192
+ if _complete_page(inf):
193
+ state = 'complete'
194
+ pages.append(inf)
195
+ modes_included.add(inf.get('mode', 'static'))
186
196
  metadata = inf if isinstance(inf, dict) else {}
187
197
  mode = metadata.get('mode')
188
198
  report_artifacts.append({'type': f"report:{mode if isinstance(mode, str) else 'static'}",
@@ -193,10 +203,11 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
193
203
  # matriz de criterios: los que tocamos (estado según hallazgos) + manuales
194
204
  from .a11ycrit import _C as _CAT, effort
195
205
  codes_aa = sorted(k for k, v in _CAT.items() if v[0] in ('A', 'AA'))
196
- touched = {}
206
+ touched, values = {}, {}
197
207
  for inf in pages:
198
208
  for h in inf.get('findings', []):
199
- if h.get('status') == 'rejected' or h.get('disprover_status') == 'rejected':
209
+ if (not isinstance(h, dict) or h.get('status') == 'rejected'
210
+ or h.get('disprover_status') == 'rejected'):
200
211
  continue
201
212
  crit = h.get('criterion')
202
213
  if not crit or not isinstance(crit, str): # informe malformado: saltar
@@ -210,8 +221,23 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
210
221
  and h.get('disprover_status') != 'not-rechecked'
211
222
  else 'automated-review')
212
223
  # el peor estado gana: fail > review
213
- if touched.get(code) != 'automated-fail':
224
+ previous = touched.get(code)
225
+ if previous != 'automated-fail':
214
226
  touched[code] = state
227
+ if previous != state:
228
+ values.pop(code, None)
229
+ if touched[code] == state and code not in values:
230
+ value = {}
231
+ issue = str(h.get('issue') or '')
232
+ if 'ratio' in issue.lower() or ':' in issue:
233
+ match = re.search(r'([\d.]+):1', issue)
234
+ if match:
235
+ value['measured'] = f'{match.group(1)}:1'
236
+ examples = h.get('examples')
237
+ if isinstance(examples, list) and examples:
238
+ value['example'] = str(examples[0])[:80]
239
+ if value:
240
+ values[code] = value
215
241
 
216
242
  verified = {v.split(' ')[0] for v in (verified or [])}
217
243
 
@@ -232,25 +258,6 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
232
258
  continue
233
259
  reason = row.get('reason')
234
260
  excluded[crit.split(' ')[0]] = reason if isinstance(reason, str) else ''
235
- # extraer valores medidos clave de los hallazgos (ratio, ejemplos)
236
- values = {}
237
- for inf in pages:
238
- for h in inf.get('findings', []):
239
- code = str(h.get('criterion') or '').split(' ')[0]
240
- if code not in values:
241
- val = {}
242
- issue_txt = str(h.get('issue') or '')
243
- if 'ratio' in issue_txt.lower() or ':' in issue_txt:
244
- import re as _re
245
- m = _re.search(r'([\d.]+):1', issue_txt)
246
- if m:
247
- val['measured'] = f'{m.group(1)}:1'
248
- _ex_list = h.get('examples', [])
249
- if isinstance(_ex_list, list) and _ex_list:
250
- val['example'] = str(_ex_list[0])[:80]
251
- if val:
252
- values[code] = val
253
-
254
261
  # criterios que requieren modos que este pack no incluye → not-run con el
255
262
  # nombre de la herramienta que falta (canónico en a11ycrit, re-derivado)
256
263
  from .a11ycrit import MODES_BY_CRITERION as _MODES_BY
@@ -30,7 +30,8 @@ from datetime import datetime, timezone
30
30
 
31
31
  import tempfile
32
32
 
33
- from .a11yaudit import audit_conditions, completed_report_pages, normalize_signal, page_identity
33
+ from .a11yaudit import (audit_conditions, audit_conditions_match, completed_report_pages,
34
+ normalize_signal, page_identity)
34
35
 
35
36
  # per-path lock: always multi-thread; multi-process on POSIX (fcntl).
36
37
  # Without it, two concurrent writes left a truncated JSON (external review
@@ -154,8 +155,9 @@ def _record(url, report, ledger=None, path='a11y-ledger.json', lang='en'):
154
155
  'Use a different ledger for a different scope.')}
155
156
  current_conditions = {page_identity(page): value for page, value in page_conditions.items()}
156
157
  previous_conditions = prev.get('page_conditions', {})
157
- if prev and any(previous_conditions.get(page, {}) != current_conditions.get(page_identity(page), {})
158
- for page in previous_pages):
158
+ if prev and any(not audit_conditions_match(page_mode, previous_conditions.get(page, {}),
159
+ current_conditions.get(page_identity(page), {}))
160
+ for page, page_mode in previous_pages.items()):
159
161
  return {'error': ('Cambiaron las condiciones de captura o el historial antiguo no las registra.'
160
162
  if lang == 'es' else
161
163
  'Capture conditions changed or were not recorded in the old ledger.')}
@@ -356,16 +356,16 @@ def _test_sliders(page, findings, lang, cap=3):
356
356
 
357
357
  def audit_patterns(url, timeout=45, lang='en', auth_state=None, browser='auto'):
358
358
  """One url → widget patterns found + contract findings (filter, not verdict)."""
359
- from .a11ydom import _get_browser, _pooled_page
359
+ from .a11ydom import _get_browser, _load_error, _load_page, _pooled_page
360
360
  lang = 'es' if lang == 'es' else 'en'
361
361
  nav = _get_browser(preferred=browser)
362
362
  page, close_page = _pooled_page(nav, auth_state)
363
363
  try:
364
364
  try:
365
- page.goto(url, wait_until='load', timeout=timeout * 1000)
365
+ _load_page(page, url, timeout * 1000)
366
366
  page.wait_for_timeout(400)
367
367
  except Exception as e: # noqa: BLE001
368
- return {'error': f'could not load: {e}'}
368
+ return _load_error(e, lang, 'could not load: {e}')
369
369
 
370
370
  counts = page.evaluate(_COUNTS)
371
371
  findings = []
@@ -43,6 +43,7 @@ def _t(lang, key):
43
43
  # llegó hasta el techo basta para auditar — doctrina de lectura parcial).
44
44
  _STREAM_CAP = 20_000_000 # 20 MB por stream descomprimido
45
45
  _STREAM_BUDGET = 120_000_000 # 120 MB en total entre todos los streams
46
+ _MAX_PDF_BYTES = 30_000_000
46
47
 
47
48
 
48
49
  def _decode_filters(chunk, filters_declared):
@@ -183,19 +184,25 @@ def _stream_low_contrast(text):
183
184
 
184
185
  def pdf_screen(path_or_bytes, lang='en'):
185
186
  """Cribado estructural de accesibilidad de un PDF (fichero local)."""
187
+ limit = _MAX_PDF_BYTES
186
188
  if isinstance(path_or_bytes, (bytes, bytearray)):
187
- data = bytes(path_or_bytes)
189
+ data = bytes(path_or_bytes[:limit + 1])
188
190
  name = '(bytes)'
189
- truncated = False
190
191
  else:
191
- tam = os.path.getsize(path_or_bytes)
192
- with open(path_or_bytes, 'rb') as f:
193
- data = f.read(30_000_000) # techo duro: 30 MB
194
- truncated = tam > len(data)
195
- name = str(path_or_bytes).rsplit('/', 1)[-1]
192
+ name = os.path.basename(path_or_bytes)
193
+ try:
194
+ with open(path_or_bytes, 'rb') as f:
195
+ data = f.read(limit + 1)
196
+ except OSError as error:
197
+ message = 'No se pudo leer el PDF' if lang == 'es' else 'Could not read PDF'
198
+ return {'error': f'{message}: {error}', 'mode': 'pdf', 'file': name}
196
199
 
197
200
  if not data.startswith(b'%PDF-'):
198
- return {'error': 'not a PDF (no %PDF- marker)'}
201
+ message = 'Falta la cabecera %PDF-' if lang == 'es' else 'Missing %PDF- header'
202
+ return {'error': message, 'mode': 'pdf', 'file': name}
203
+ if len(data) > limit:
204
+ message = 'El PDF supera el límite de 30 MB' if lang == 'es' else 'PDF exceeds the 30 MB limit'
205
+ return {'error': message, 'mode': 'pdf', 'file': name, 'truncated': True}
199
206
 
200
207
  streams = _uncompressed_streams(data)
201
208
  # `todo` respeta el MISMO presupuesto acumulado: ensamblar 40 streams de
@@ -429,7 +436,7 @@ def pdf_screen(path_or_bytes, lang='en'):
429
436
  'tag_counts': {'td': n_tag_td, 'th': n_tag_th, 'h': n_tag_h},
430
437
  'ocr_layer_only': bool(_t_inv and not _t_vis),
431
438
  'form_fields': n_fields, 'form_labels': n_tu,
432
- 'truncated': truncated,
439
+ 'truncated': False,
433
440
  'score': compute_score(findings),
434
441
  'findings': findings,
435
442
  'summary': {s: sum(1 for h in findings if h['severity'] == s)
@@ -446,8 +453,9 @@ def main(argv):
446
453
  ap.add_argument('pdf', help='local PDF file')
447
454
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
448
455
  a = ap.parse_args(argv)
449
- print(json.dumps(pdf_screen(a.pdf, lang=a.lang), ensure_ascii=False, indent=1))
450
- return 0
456
+ result = pdf_screen(a.pdf, lang=a.lang)
457
+ print(json.dumps(result, ensure_ascii=False, indent=1))
458
+ return 1 if 'error' in result else 0
451
459
 
452
460
 
453
461
  if __name__ == '__main__':
@@ -21,7 +21,7 @@ from .a11yact import _NOT_DEAD
21
21
  from .a11yaudit import normalize_signal # noqa: E402 (compat 5.10)
22
22
  import sys
23
23
 
24
- from .a11yaudit import audit_url, audit_site, audit_html
24
+ from .a11yaudit import audit_url, audit_site, audit_html, completed_report_pages
25
25
 
26
26
  LEVEL = {'high': 'error', 'medium': 'warning', 'low': 'note'}
27
27
 
@@ -63,13 +63,15 @@ def from_report(report, driver_version=None, standard=None, target=None):
63
63
  (con la lista 'reports'). Con standard='en301549' cada regla gana
64
64
  properties/tags con su cláusula EN 301 549 V4.1.1 (9.x web por defecto,
65
65
  10.x documents, 11.x software) — filtrable en code scanning."""
66
+ pages, error = completed_report_pages(report)
67
+ if error:
68
+ return error
66
69
  if driver_version is None:
67
70
  # versión del driver = fuente única (estaba congelada en '3.2.0' con el
68
71
  # motor en 5.26: GitHub mostraba una versión muerta en code scanning)
69
72
  from .server import VERSION as _V # lazy: server importa este módulo
70
73
  driver_version = _V
71
74
  from . import a11yen301549 as _enstd
72
- pages = report.get('reports') if isinstance(report.get('reports'), list) else [report]
73
75
  rules = {}
74
76
  results = []
75
77
  skipped = 0 # hallazgos truncados/hostiles: se saltan, jamás un KeyError
@@ -167,19 +169,23 @@ def main(argv):
167
169
  default=None, help='target EN: web=9.x, documents=10.x, '
168
170
  'software=11.x (default: según el modo del informe)')
169
171
  a = ap.parse_args(argv)
170
- if a.from_audit:
171
- with open(a.from_audit, encoding='utf-8') as f:
172
- report = json.load(f)
173
- elif a.url:
174
- report = (audit_site(a.url, max_pages=a.pages, lang=a.lang)
175
- if a.pages > 1 else audit_url(a.url, lang=a.lang))
176
- else:
177
- with open(a.file, encoding='utf-8', errors='replace') as f:
178
- report = audit_html(f.read(), a.file, lang=a.lang)
179
- if 'error' in report:
180
- print(json.dumps(report))
172
+ try:
173
+ if a.from_audit:
174
+ with open(a.from_audit, encoding='utf-8') as f:
175
+ report = json.load(f)
176
+ elif a.url:
177
+ report = (audit_site(a.url, max_pages=a.pages, lang=a.lang)
178
+ if a.pages > 1 else audit_url(a.url, lang=a.lang))
179
+ else:
180
+ with open(a.file, encoding='utf-8', errors='replace') as f:
181
+ report = audit_html(f.read(), a.file, lang=a.lang)
182
+ except (OSError, ValueError) as error:
183
+ print(json.dumps({'error': str(error)}, ensure_ascii=False))
181
184
  return 1
182
185
  sarif = from_report(report, standard=a.standard, target=a.target)
186
+ if 'error' in sarif:
187
+ print(json.dumps(sarif, ensure_ascii=False))
188
+ return 1
183
189
  with open(a.out, 'w', encoding='utf-8') as f:
184
190
  json.dump(sarif, f, ensure_ascii=False, indent=1)
185
191
  summary = report.get('summary', {'high': 0, 'medium': 0, 'low': 0})
@@ -80,17 +80,17 @@ 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, _pooled_page
83
+ from .a11ydom import _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
87
87
  page, close_page = _pooled_page(nav, auth_state, viewport={'width': 1280, 'height': 800})
88
88
  try:
89
89
  try:
90
- page.goto(url, wait_until='load', timeout=timeout * 1000)
90
+ _load_page(page, url, timeout * 1000)
91
91
  page.wait_for_timeout(500)
92
92
  except Exception as e: # noqa: BLE001
93
- return {'error': f'no se pudo cargar: {e}'}
93
+ return _load_error(e, lang, 'no se pudo cargar: {e}')
94
94
  page.evaluate(_MON)
95
95
  page.evaluate("(() => { const c = document.querySelector("
96
96
  " 'article a[href], [role=article] a[href], main li a[href]');"
@@ -33,6 +33,7 @@ import sys
33
33
  from datetime import datetime, timezone
34
34
 
35
35
  from . import a11ydiff
36
+ from .a11ydom import _NavigationHTTPError, _load_page
36
37
 
37
38
  # Silent live-region collector: accumulates announcements and exposes a
38
39
  # drain() so each trace step reads EXACTLY the announcements it triggered.
@@ -97,19 +98,6 @@ _DIALOG_STATE_JS = '''() => {
97
98
  }'''
98
99
 
99
100
 
100
- class _TraceHttpError(Exception):
101
- def __init__(self, status, url):
102
- super().__init__(f'HTTP {status}: could not capture the requested page')
103
- self.status = status
104
- self.url = url
105
-
106
-
107
- def _goto(page, url, timeout):
108
- response = page.goto(url, wait_until='load', timeout=timeout)
109
- if response is not None and response.status >= 400:
110
- raise _TraceHttpError(response.status, page.url)
111
-
112
-
113
101
  def _run_script_action(page, act):
114
102
  """One scripted action → (label, ok). Selector-valued actions target CSS."""
115
103
  kind = act.get('kind', '')
@@ -131,7 +119,7 @@ def _run_script_action(page, act):
131
119
  page.wait_for_timeout(int(act.get('ms', 300)))
132
120
  return f'wait:{act.get("ms", 300)}', True
133
121
  if kind == 'goto':
134
- _goto(page, act.get('url', ''), timeout=30000)
122
+ _load_page(page, act.get('url', ''), timeout=30000)
135
123
  # la navegación destruye el recolector (contexto nuevo): re-inyectarlo
136
124
  # o el drain de ESTE paso y de los siguientes tronaría/volvería vacío
137
125
  page.evaluate(_COLLECTOR)
@@ -146,15 +134,17 @@ def _run_script(page, script, dialog_state=False, check_navigation=None):
146
134
  navigations = 0
147
135
  url_now = page.url
148
136
  for i, act in enumerate(script):
149
- if not isinstance(act, dict):
150
- continue
151
137
  try:
152
- label, _ok = _run_script_action(page, act)
153
- except _TraceHttpError:
138
+ if isinstance(act, dict):
139
+ label, succeeded = _run_script_action(page, act)
140
+ else:
141
+ label, succeeded = 'invalid action', False
142
+ except _NavigationHTTPError:
154
143
  raise
155
144
  except Exception as e: # noqa: BLE001 — a failed action is a recorded step too
156
145
  label = f'{act.get("kind", "?")}:{act.get("selector") or act.get("key") or ""}'
157
146
  label += f' (failed: {str(e)[:60]})'
147
+ succeeded = False
158
148
  page.wait_for_timeout(200)
159
149
  if check_navigation is not None:
160
150
  check_navigation()
@@ -163,7 +153,7 @@ def _run_script(page, script, dialog_state=False, check_navigation=None):
163
153
  if page.url != url_now:
164
154
  navigations += 1
165
155
  url_now = page.url
166
- step = {'step': i + 1, 'action': label, 'focus': info,
156
+ step = {'step': i + 1, 'action': label, 'action_succeeded': succeeded, 'focus': info,
167
157
  'announcements': anns, 'url': page.url}
168
158
  if dialog_state:
169
159
  try:
@@ -190,6 +180,8 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
190
180
  el foco al opener pero DEJA el modal abierto es una divergencia de
191
181
  estado que el foco solo no ve."""
192
182
  from .a11ydom import _get_browser, _pooled_page
183
+ if script is not None and (not isinstance(script, list) or not script):
184
+ return {'error': 'the trace script must be a non-empty list of actions'}
193
185
  nav = _get_browser(preferred=browser)
194
186
  page, close_page = _pooled_page(nav, auth_state)
195
187
  navigation_error = None
@@ -199,7 +191,7 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
199
191
  request = response.request
200
192
  if (navigation_error is None and response.status >= 400
201
193
  and request.is_navigation_request() and request.frame == page.main_frame):
202
- navigation_error = _TraceHttpError(response.status, response.url)
194
+ navigation_error = _NavigationHTTPError(response.status, response.url)
203
195
 
204
196
  def check_navigation():
205
197
  if navigation_error is not None:
@@ -208,8 +200,8 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
208
200
  try:
209
201
  page.on('response', observe_response)
210
202
  try:
211
- _goto(page, url, timeout=timeout * 1000)
212
- except _TraceHttpError:
203
+ _load_page(page, url, timeout=timeout * 1000)
204
+ except _NavigationHTTPError:
213
205
  raise
214
206
  except Exception as e: # noqa: BLE001
215
207
  return {'error': f'could not load: {e}'}
@@ -256,8 +248,8 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
256
248
  except Exception: # noqa: BLE001
257
249
  tree = None
258
250
  check_navigation()
259
- except _TraceHttpError as e:
260
- return {'error': str(e), 'url': e.url, 'http_status': e.status}
251
+ except _NavigationHTTPError as e:
252
+ return e.report()
261
253
  finally:
262
254
  close_page()
263
255
 
@@ -266,6 +258,7 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
266
258
  **({'dialog_state_captured': True} if capture_dialog_state else {}),
267
259
  'steps': walk,
268
260
  'summary': {'steps_taken': len(walk),
261
+ 'failed_actions': sum(s.get('action_succeeded') is False for s in walk),
269
262
  'announcements': sum(len(s.get('announcements') or [])
270
263
  for s in walk),
271
264
  'navigations': navigations,
@@ -339,17 +332,25 @@ def _trace_error(trace):
339
332
  or (step.get('announcements') is not None
340
333
  and not isinstance(step['announcements'], list))):
341
334
  return f'invalid step {index}'
335
+ succeeded = step.get('action_succeeded')
336
+ if 'action_succeeded' in step and type(succeeded) is not bool:
337
+ return f'invalid action status at step {index}'
338
+ action = step.get('action')
339
+ legacy_failure = (succeeded is None and isinstance(action, str)
340
+ and (action.startswith('unknown:') or ' (failed:' in action))
341
+ if succeeded is False or legacy_failure:
342
+ return f'script action failed at step {index}'
342
343
  return None
343
344
 
344
345
 
345
346
  def trace_diff(a, b, gate_dialog_state=False):
346
- """Two traces → verdict. Focus behavior gates; announcements inform.
347
+ """Two traces → verdict. Failed actions invalidate a capture.
347
348
 
348
349
  gate_dialog_state (issue #16): OPT-IN — compara también el estado de
349
350
  diálogo capturado (trace --capture-dialog-state). Sin foco perdido ni
350
351
  reordenado pero con el modal ABIERTO donde antes cerraba: regresión.
351
352
  Evidencia faltante o acciones distintas → INCONCLUSIVE, nunca un falso
352
- PASS. El foco sigue siendo el único gate por defecto."""
353
+ PASS. El foco se compara después de validar la ejecución."""
353
354
  for label, capture in (('reference', a), ('candidate', b)):
354
355
  error = _trace_error(capture)
355
356
  if error:
@@ -382,7 +383,8 @@ def trace_diff(a, b, gate_dialog_state=False):
382
383
  'focus': {'before': fa, 'after': fb, 'lost': lost, 'gained': gained,
383
384
  'first_divergence': first_divergence},
384
385
  **({'dialog_gate': gate} if gate_dialog_state else {}),
385
- 'note': ('focus behavior is the gate: a lost or forked tab sequence '
386
+ 'note': ('failed scripted actions invalidate the capture (exit 1); '
387
+ 'a lost or forked tab sequence '
386
388
  'blocks (exit 2). Announcement counts are reported, not '
387
389
  'gated — content changes legitimately between builds; a '
388
390
  'collapsed layer (had announcements, now zero) is flagged '
@@ -17,10 +17,14 @@ import argparse
17
17
  import json
18
18
  import re
19
19
  import sys
20
+ from http.client import HTTPException
20
21
  from . import a11yi18n
21
22
 
22
23
  _RE_TIME = re.compile(
23
- r'(?:(\d{2,}):)?(\d{2}):(\d{2})[.,](\d{3})\s*-->\s*(?:(\d{2,}):)?(\d{2}):(\d{2})[.,](\d{3})')
24
+ r'(?:([0-9]{2,}):)?([0-5][0-9]):([0-5][0-9])\.([0-9]{3})[ \t]+-->[ \t]+'
25
+ r'(?:([0-9]{2,}):)?([0-5][0-9]):([0-5][0-9])\.([0-9]{3})(?=$|[ \t])')
26
+ _RE_HEADER = re.compile(r'WEBVTT(?:[ \t].*)?')
27
+ _MAX_BYTES = 2_000_000
24
28
 
25
29
  # etiquetas de marcado WebVTT — <v>, <i>, <b>, <c.cls>, anclas/timestamps
26
30
  # <00:00:01.000>: no se leen en voz alta, no cuentan como caracteres de lectura
@@ -39,14 +43,30 @@ def _seconds(h, m, s, ms):
39
43
 
40
44
  def vtt_check(url, duration=None, lang='en'):
41
45
  """Descarga y juzga un .vtt — el contenido de 1.2.2, no su mera presencia."""
42
- from .a11yaudit import _fetch, compute_score, CRIT
46
+ from .a11yaudit import _fetch, _FetchError, _t as audit_text, CRIT
43
47
  # text/vtt es EL MIME del formato (WebVTT spec): el filtro anti-no-HTML
44
48
  # del descargador lo rechazaba con err_not_html servido correctamente
45
49
  # (revisión externa, 3ª pasada — la suite no lo veía porque sustituía el
46
50
  # descargador)
47
- data = _fetch(url, timeout=30, truncate_at=2_000_000, accept_ct=('text/vtt',))
51
+ def error(message):
52
+ return {'error': message, 'mode': 'vtt', 'url': url}
53
+
54
+ try:
55
+ data = _fetch(url, timeout=30, truncate_at=_MAX_BYTES, accept_ct=('text/vtt',),
56
+ require_complete=True)
57
+ except _FetchError as failure:
58
+ if failure.key == 'err_too_big':
59
+ return error('WebVTT supera el límite de 2 MB' if lang == 'es'
60
+ else 'WebVTT exceeds the 2 MB limit')
61
+ if failure.key == 'err_incomplete_html':
62
+ return error('Descarga de WebVTT incompleta' if lang == 'es'
63
+ else 'Incomplete WebVTT download')
64
+ return error(audit_text(lang, failure.key).format(**failure.fmt))
65
+ except (OSError, HTTPException, ValueError) as failure:
66
+ message = 'No se pudo descargar el WebVTT' if lang == 'es' else 'Could not fetch WebVTT'
67
+ return error(f'{message}: {failure}')
48
68
  if isinstance(data, dict) and 'error' in data:
49
- return data
69
+ return error(data['error'])
50
70
  if isinstance(data, bytes):
51
71
  text = data.decode('utf-8', errors='replace')
52
72
  else:
@@ -59,34 +79,36 @@ def vtt_check(url, duration=None, lang='en'):
59
79
  'signal': key, 'issue': _t(lang, key).format(**fmt),
60
80
  'remediation': _t(lang, key + '_rem').format(**fmt)})
61
81
 
62
- # un BOM UTF-8 (U+FEFF) delante de WEBVTT es válido — lstrip() no lo quita
63
- if not text.removeprefix('\ufeff').lstrip().startswith('WEBVTT'):
64
- return {'error': 'does not declare WEBVTT (is it .srt or another format?)',
65
- 'primeros_bytes': text[:40]}
82
+ text = text.removeprefix('\ufeff').replace('\r\n', '\n').replace('\r', '\n')
83
+ header = text.partition('\n')[0]
84
+ if not _RE_HEADER.fullmatch(header) or '-->' in header:
85
+ return error('Cabecera WebVTT inválida' if lang == 'es' else 'Invalid WebVTT header')
66
86
 
67
87
  blocks = [b for b in re.split(r'\n\s*\n', text) if b.strip()]
68
88
  cues, malformed = [], []
69
89
  for b in blocks[1:]: # el primero es la cabecera
70
90
  lines = [l for l in b.splitlines() if l.strip()]
71
- m = None
72
- for i, l in enumerate(lines):
73
- m = _RE_TIME.search(l)
74
- if m:
75
- body = '\n'.join(lines[i + 1:]).strip()
76
- break
91
+ if (lines[0] in ('NOTE', 'STYLE', 'REGION') or lines[0].startswith(('NOTE ', 'NOTE\t'))):
92
+ continue
93
+ timing = 0 if '-->' in lines[0] else 1
94
+ m = _RE_TIME.match(lines[timing]) if timing < len(lines) else None
77
95
  if not m:
78
96
  if '-->' in b:
79
97
  malformed.append(lines[0][:30])
80
98
  continue
81
- start = _seconds(*m.groups()[:4])
82
- end = _seconds(*m.groups()[4:])
83
- if end <= start:
99
+ try:
100
+ start = _seconds(*m.groups()[:4])
101
+ end = _seconds(*m.groups()[4:])
102
+ except (ValueError, OverflowError):
103
+ malformed.append(m.group(0)[:30])
104
+ continue
105
+ if end <= start or (cues and start < cues[-1]['start']):
84
106
  # intervalo INVÁLIDO (tiempos invertidos): cue malformada y FUERA
85
107
  # de toda medida (revisión externa, 3ª pasada — antes fabricaba
86
108
  # segundos NEGATIVOS y un «demasiado rápida» por el clamp dur=0.1)
87
109
  malformed.append(m.group(0)[:30])
88
110
  continue
89
- cues.append({'start': start, 'end': end, 'text': body})
111
+ cues.append({'start': start, 'end': end, 'text': '\n'.join(lines[timing + 1:]).strip()})
90
112
 
91
113
  if malformed:
92
114
  add('high', 'vtt_malformed', n=len(malformed), example=', '.join(malformed[:3]))
@@ -168,14 +190,9 @@ def main(argv):
168
190
  ap.add_argument('--duration', type=float, help='media duration in seconds (coverage check)')
169
191
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
170
192
  a = ap.parse_args(argv)
171
- try:
172
- res = vtt_check(a.url, duration=a.duration, lang=a.lang)
173
- except ValueError as e: # _FetchError incluido (descarga/scheme/HTML-size)
174
- print(json.dumps({'error': str(e)}, ensure_ascii=False))
175
- return 1
193
+ res = vtt_check(a.url, duration=a.duration, lang=a.lang)
176
194
  print(json.dumps(res, ensure_ascii=False, indent=1))
177
- return 0
178
- return 0
195
+ return 1 if 'error' in res else 0
179
196
 
180
197
 
181
198
  if __name__ == '__main__':