@kinti/a11y-toolkit 5.29.0 → 5.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -182,9 +182,30 @@ def pdf_screen(path_or_bytes, lang='en'):
182
182
  marked = present(rb'/Marked\s+true')
183
183
  tagged = present(rb'/StructTreeRoot\s+\d+\s+0\s+R') or \
184
184
  (marked and present(rb'/StructTreeRoot'))
185
- lang_doc = re.search(rb'/Lang\s*\(([^)]{2,20})\)', todo)
186
- title_meta = re.search(rb'/Title\s*\(([^)]{1,300})\)', todo) or \
187
- re.search(rb'<dc:title>.{0,200}?<rdf:li[^>]*>([^<]{1,300})</rdf:li>', todo, re.S)
185
+ lang_found = re.search(rb'/Lang\s*\(([^)]{2,20})\)', todo)
186
+ # (5ª pasada) el título SOLO de los metadatos del documento: el /Title
187
+ # del objeto /Info del trailer (o el dc:title del XMP) — el primer
188
+ # /Title de cualquier objeto era un MARCADOR («Chapter one») mientras el
189
+ # título real estaba vacío
190
+ title_meta = None
191
+ _info_refs = re.findall(rb'/Info\s+(\d+)\s+\d+\s+R', todo)
192
+ if _info_refs:
193
+ _obj_id = _info_refs[-1] # actualizaciones incrementales: el último manda
194
+ _m_obj = re.search(b'\b' + _obj_id + b'\s+\d+\s+obj(.{0,4000}?)endobj', todo, re.S)
195
+ if _m_obj:
196
+ title_meta = re.search(rb'/Title\s*\(([^)]{1,300})\)', _m_obj.group(1))
197
+ if not title_meta:
198
+ title_meta = re.search(rb'<dc:title>.{0,200}?<rdf:li[^>]*>([^<]{1,300})</rdf:li>', todo, re.S)
199
+ if not title_meta:
200
+ # respaldo para PDFs mínimos SIN trailer: un /Title cuyo diccionario
201
+ # lleva claves de METADATOS (/Producer, /Author, /Creator, /ModDate…)
202
+ # — los marcadores llevan /Dest//Parent//Next y jamás esas claves
203
+ for _dic in re.findall(rb'<<(?:[^<>]|<<[^<>]*>>){0,600}?>>', todo):
204
+ if rb'/Title' in _dic and re.search(rb'/(?:Producer|Author|Creator|ModDate|CreationDate)\b', _dic):
205
+ _m = re.search(rb'/Title\s*\(([^)]{1,300})\)', _dic)
206
+ if _m:
207
+ title_meta = _m
208
+ break
188
209
  n_pages = len(re.findall(rb'/Type\s*/Page[^s]', todo))
189
210
  # /Alt acepta literal (/Alt (…)) y hex (/Alt <FEFF…>, la forma natural
190
211
  # UTF-16BE para alt no latino) — misma paridad que /TU
@@ -282,7 +303,7 @@ def pdf_screen(path_or_bytes, lang='en'):
282
303
  add('pdf_untagged')
283
304
  if not title_meta:
284
305
  add('pdf_no_title')
285
- if not lang_doc:
306
+ if not lang_found:
286
307
  add('pdf_no_lang')
287
308
  if n_pages > 8 and not n_outline:
288
309
  add('pdf_no_outline')
@@ -301,7 +322,7 @@ def pdf_screen(path_or_bytes, lang='en'):
301
322
  'pages': n_pages or None,
302
323
  'tagged': bool(tagged and marked),
303
324
  'encrypted': encrypted,
304
- 'lang': lang_doc.group(1).decode('latin-1', 'replace') if lang_doc else None,
325
+ 'lang': lang_found.group(1).decode('latin-1', 'replace') if lang_found else None,
305
326
  'title': (title_meta.group(1).decode('utf-8', 'replace').strip()[:200]
306
327
  if title_meta else None),
307
328
  'images': n_imgs, 'alt_entries': n_alt, 'actual_text': n_actual,
@@ -73,12 +73,16 @@ def from_report(report, driver_version=None, standard=None, target=None):
73
73
  rules = {}
74
74
  results = []
75
75
  skipped = 0 # hallazgos truncados/hostiles: se saltan, jamás un KeyError
76
- _tgt = target or _enstd.target_for_mode(report.get('mode', 'static'))
77
76
  for pg in pages:
78
77
  if not isinstance(pg, dict):
79
78
  skipped += 1
80
79
  continue
81
- url = pg.get('url', '(html)')
80
+ # (6a pasada) el TARGET se resuelve por INFORME HIJO: en un lote
81
+ # mixto, el PDF exportado solo recibia clausulas 9.x (web) y en solitario
82
+ # 10.x — el modo que decide es el de CADA pagina. La ubicacion usa el
83
+ # file del hijo cuando no hay url (antes: '(html)' pese a existir file)
84
+ _tgt = target or _enstd.target_for_mode(pg.get('mode', report.get('mode', 'static')))
85
+ url = pg.get('url') or pg.get('file') or '(html)'
82
86
  for h in pg.get('findings', []) or []:
83
87
  if not isinstance(h, dict):
84
88
  skipped += 1
@@ -110,6 +114,10 @@ def from_report(report, driver_version=None, standard=None, target=None):
110
114
  'en301549': clause,
111
115
  'tags': [f'en301549:{clause}', 'wcag22:' + code],
112
116
  }
117
+ # lotes mixtos: la MISMA senal puede llegar con clausulas
118
+ # de targets distintos — ids distintos por clausula
119
+ rule['id'] = rule_id + '-' + clause.replace('.', '')
120
+ rule_id = rule['id']
113
121
  rules[rule_id] = rule
114
122
  message = issue
115
123
  if h.get('remediation'):
@@ -114,6 +114,25 @@ def build_scope(reports, standard='wcag22', target='web', answers=None,
114
114
  else:
115
115
  targets = [target]
116
116
  reports = [r for r in reports if isinstance(r, dict)]
117
+ # aplanar crawls (audit_site anida las páginas bajo 'reports'): sin esto,
118
+ # los features de las páginas DENTRO del crawl no se contaban y el scope
119
+ # proponía excluir criterios de subtítulos/formularios que la muestra SÍ
120
+ # contiene (revisión externa 2026-11-22). Misma doctrina que a11yevidence:
121
+ # hallazgos top-level = copias re-verificadas, se prefieren; informes con
122
+ # error jamás aportan evidencia
123
+ flat = []
124
+ for rep in reports:
125
+ if rep.get('error'):
126
+ continue
127
+ subs = rep.get('reports')
128
+ if isinstance(rep.get('findings'), list) and rep['findings']:
129
+ flat.append(rep)
130
+ elif isinstance(subs, list) and subs:
131
+ flat.extend(s for s in subs
132
+ if isinstance(s, dict) and not s.get('error'))
133
+ else:
134
+ flat.append(rep)
135
+ reports = flat
117
136
  findings_codes = set()
118
137
  for rep in reports:
119
138
  raw = rep.get('findings')
@@ -78,20 +78,18 @@ def _add(findings, lang, sev, code, key, **fmt):
78
78
  })
79
79
 
80
80
 
81
- def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None, browser='auto'):
82
- from playwright.sync_api import sync_playwright
83
- from .a11ydom import _get_browser
84
- with sync_playwright() as p:
85
- nav = _get_browser(p, preferred=browser)
86
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
87
- # BrowserContext.new_page() NO acepta viewport: va en el new_context
88
- page = (ctx.new_page() if auth_state
89
- else nav.new_page(viewport={'width': 1280, 'height': 800}))
81
+ def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None, browser='auto',
82
+ interactive=False, load_more=None):
83
+ from .a11ydom import _get_browser, _pooled_page
84
+ nav = _get_browser(preferred=browser)
85
+ # BrowserContext.new_page() NO acepta viewport: _pooled_page lo manda al
86
+ # new_context cuando hay auth_state
87
+ page, close_page = _pooled_page(nav, auth_state, viewport={'width': 1280, 'height': 800})
88
+ try:
90
89
  try:
91
90
  page.goto(url, wait_until='load', timeout=timeout * 1000)
92
91
  page.wait_for_timeout(500)
93
92
  except Exception as e: # noqa: BLE001
94
- nav.close()
95
93
  return {'error': f'no se pudo cargar: {e}'}
96
94
  page.evaluate(_MON)
97
95
  page.evaluate("(() => { const c = document.querySelector("
@@ -113,16 +111,22 @@ def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None, bro
113
111
  or e['scroll'] > (batches[-1]['scroll'] if batches else before['scroll']):
114
112
  grew = True
115
113
  break
116
- if not grew and not via_click:
117
- # el scroll no trae nada: ¿hay botón «cargar más»? (la alternativa sana)
118
- via_click = page.evaluate(
119
- "() => [...document.querySelectorAll('button, a')].some(b =>"
120
- " /más|more|cargar|load/i.test((b.innerText || '').trim()) && b.offsetParent)")
121
- if via_click:
114
+ if not grew and not via_click and interactive and load_more:
115
+ # (5ª pasada) la prueba ACTIVA exige un control IDENTIFICADO:
116
+ # texto visible EXACTO del «cargar más», nada de subcadenas —
117
+ # /load/ clicaba «Download monthly report» en un feed ajeno al
118
+ # botón. El modo por defecto es PASIVO (solo scroll, jamás
119
+ # click) y el MCP lo declara
120
+ target_found = page.evaluate(
121
+ "(txt) => { const b = [...document.querySelectorAll('button, a')]"
122
+ " .find(b => (b.innerText || '').trim() === txt && b.offsetParent);"
123
+ " return b ? 1 : 0; }", load_more.strip())
124
+ if target_found:
122
125
  page.evaluate(
123
- "() => { const b = [...document.querySelectorAll('button, a')].find("
124
- "b => /más|more|cargar|load/i.test((b.innerText || '').trim()) && b.offsetParent);"
125
- " if (b) b.click(); }")
126
+ "(txt) => { const b = [...document.querySelectorAll('button, a')]"
127
+ " .find(b => (b.innerText || '').trim() === txt && b.offsetParent);"
128
+ " if (b) b.click(); }", load_more.strip())
129
+ via_click = True
126
130
  for _wait in range(6):
127
131
  page.wait_for_timeout(500)
128
132
  e2 = page.evaluate(_STATE)
@@ -134,18 +138,26 @@ def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None, bro
134
138
  if not grew:
135
139
  end_reached = True
136
140
  break
137
-
138
- nav.close()
141
+ finally:
142
+ close_page()
139
143
 
140
144
  findings = []
141
145
  last = batches[-1] if batches else before
142
146
 
143
- # 1. foco (2.4.3): desaparecido o fuera de pantalla tras las tandas
147
+ # 1. foco (2.4.3), con la causa separada de la observación (5ª pasada):
148
+ # PERDIDO (activeElement → body) es hallazgo siempre; FUERA DE PANTALLA
149
+ # solo lo es si el feed creció de verdad (el contenido nuevo dejó atrás a
150
+ # un foco quieto) — en un feed estático es el PROPIO scrollTo de la
151
+ # prueba quien lo sacó del viewport, y eso no es un fallo de la página
152
+ focus_tracking = {'initial': initial_focus, 'final': last.get('focus'),
153
+ 'lost': bool(initial_focus) and last.get('focus') is None,
154
+ 'offscreen': bool(last.get('focus_offscreen')),
155
+ 'feed_grew': bool(last.get('items', 0) > before.get('items', 0))}
144
156
  if initial_focus:
145
157
  if last['focus'] is None:
146
158
  _add(findings, lang, 'high', '2.4.3', 'scroll_focus',
147
159
  where='disappeared', detail=f'was on {initial_focus}')
148
- elif last['focus_offscreen']:
160
+ elif last['focus_offscreen'] and focus_tracking['feed_grew']:
149
161
  _add(findings, lang, 'medium', '2.4.3', 'scroll_focus',
150
162
  where='went offscreen', detail=initial_focus)
151
163
 
@@ -160,6 +172,17 @@ def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None, bro
160
172
  'li en main): o el feed está tras login/muro de bots, o usa marcado no estándar. '
161
173
  'Las señales de anuncios/fin se omiten; valida feeds propios con marcado conocido.')
162
174
 
175
+ if not interactive:
176
+ _passive_note = ('passive walk: the load-more alternative was NOT '
177
+ 'clicked (read-only default). Re-run with '
178
+ 'interactive=true and load_more="exact visible text" '
179
+ 'to test it.' if lang == 'en' else
180
+ 'recorrido pasivo: la alternativa «cargar más» NO se '
181
+ 'pulsó (por defecto solo lectura). Re-ejecuta con '
182
+ 'interactive=true y load_more="texto exacto visible" '
183
+ 'para probarla.')
184
+ note = (note + ' ' + _passive_note) if note else _passive_note
185
+
163
186
  # 2. anuncios (4.1.3) — solo si hubo feed real
164
187
  if hay_feed_real and batches and not last['hasFeed'] and not last['events']:
165
188
  _add(findings, lang, 'medium', '4.1.3', 'scroll_no_announce',
@@ -187,6 +210,8 @@ def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None, bro
187
210
  'live_announcements': [e['text'] for e in last['events'][:5]],
188
211
  'focus': {'initial': initial_focus, 'final': last['focus'],
189
212
  'offscreen': last['focus_offscreen']},
213
+ 'focus_tracking': focus_tracking,
214
+ 'interactive': bool(interactive),
190
215
  'load_more_alternative': last['hasMore'],
191
216
  'note': note,
192
217
  'findings': findings,
@@ -145,16 +145,13 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
145
145
  of the keyboard walk. Each action becomes a recorded step; the announcement
146
146
  collector and the focus signature stay identical, so trace diff works the
147
147
  same over scripted traces."""
148
- from playwright.sync_api import sync_playwright
149
- from .a11ydom import _get_browser
150
- with sync_playwright() as p:
151
- nav = _get_browser(p, preferred=browser)
152
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
153
- page = ctx.new_page() if auth_state else nav.new_page()
148
+ from .a11ydom import _get_browser, _pooled_page
149
+ nav = _get_browser(preferred=browser)
150
+ page, close_page = _pooled_page(nav, auth_state)
151
+ try:
154
152
  try:
155
153
  page.goto(url, wait_until='load', timeout=timeout * 1000)
156
154
  except Exception as e: # noqa: BLE001
157
- nav.close()
158
155
  return {'error': f'could not load: {e}'}
159
156
  page.wait_for_timeout(400)
160
157
  page.evaluate(_COLLECTOR)
@@ -188,7 +185,8 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
188
185
  tree = tree[:60_000] + '\n… (truncated)'
189
186
  except Exception: # noqa: BLE001
190
187
  tree = None
191
- nav.close()
188
+ finally:
189
+ close_page()
192
190
 
193
191
  data = {'mode': 'trace', 'url': url,
194
192
  'ts': datetime.now(timezone.utc).isoformat(),
@@ -151,6 +151,10 @@ def generate_vpat(pack=None, reports=None, product='', product_version=None,
151
151
  if not isinstance(scope, dict):
152
152
  return {'error': t['error_scope']}
153
153
  from .a11yevidence import apply_scope
154
+ scope_sha = scope.get('sha256') if isinstance(scope, dict) else None
155
+ if not scope_sha and isinstance(scope, dict):
156
+ from .a11yevidence import _sha256
157
+ scope_sha = _sha256(scope)
154
158
  pack = apply_scope(pack, scope, lang=lang)
155
159
  if not isinstance(pack, dict) or 'criteria' not in pack:
156
160
  return {'error': t['error_no_pack']}
@@ -161,6 +165,10 @@ def generate_vpat(pack=None, reports=None, product='', product_version=None,
161
165
 
162
166
  from .a11ycrit import _C as _CAT
163
167
  pack_sha = pack.get('sha256', '')
168
+ try:
169
+ scope_sha
170
+ except NameError:
171
+ scope_sha = None
164
172
  by_code = _findings_by_code(pack)
165
173
  report_date = report_date or datetime.date.today().isoformat()
166
174
 
@@ -227,6 +235,7 @@ def generate_vpat(pack=None, reports=None, product='', product_version=None,
227
235
  + t['col_level'] + '</th><th scope="col">' + t['col_remarks']
228
236
  + '</th></tr></thead>\n<tbody>\n' + '\n'.join(rows_html) + '\n</tbody>\n</table>\n</div>\n'
229
237
  + f'<h2>{t["signature_title"]}</h2>\n<p>{t["signature"]} <code>{e(pack_sha)}</code></p>\n'
238
+ + (f'<p>{t["signature_scope"].format(sha=e(scope_sha))}</p>\n' if scope_sha else '')
230
239
  + '<p><em>' + t['signature_empty'] + '</em></p>\n'
231
240
  + (f'<p>{t["product"]}: {e((reviewer or {}).get("name", "________________"))} — '
232
241
  f'{t["credential"]}: {e((reviewer or {}).get("credential", "________________"))} — '
@@ -235,7 +244,8 @@ def generate_vpat(pack=None, reports=None, product='', product_version=None,
235
244
  + f'</main>\n<footer><p><small>{t["iti_note"]}</small></p></footer>\n</body>\n</html>'
236
245
  )
237
246
  res = {'html': doc, 'summary': summary, 'levels': {f['code']: f['conformance'] for f in rows},
238
- 'pack_sha256': pack_sha, 'draft': True, 'lang': lang}
247
+ 'pack_sha256': pack_sha, 'draft': True, 'lang': lang,
248
+ **({'scope_sha256': scope_sha, 'derived': True} if scope_sha else {})}
239
249
  if output_path:
240
250
  with open(output_path, 'w', encoding='utf-8') as f:
241
251
  f.write(doc)
@@ -40,7 +40,11 @@ def _seconds(h, m, s, ms):
40
40
  def vtt_check(url, duration=None, lang='en'):
41
41
  """Descarga y juzga un .vtt — el contenido de 1.2.2, no su mera presencia."""
42
42
  from .a11yaudit import _fetch, compute_score, CRIT
43
- data = _fetch(url, timeout=30, truncate_at=2_000_000)
43
+ # text/vtt es EL MIME del formato (WebVTT spec): el filtro anti-no-HTML
44
+ # del descargador lo rechazaba con err_not_html servido correctamente
45
+ # (revisión externa, 3ª pasada — la suite no lo veía porque sustituía el
46
+ # descargador)
47
+ data = _fetch(url, timeout=30, truncate_at=2_000_000, accept_ct=('text/vtt',))
44
48
  if isinstance(data, dict) and 'error' in data:
45
49
  return data
46
50
  if isinstance(data, bytes):
@@ -76,6 +80,12 @@ def vtt_check(url, duration=None, lang='en'):
76
80
  continue
77
81
  start = _seconds(*m.groups()[:4])
78
82
  end = _seconds(*m.groups()[4:])
83
+ if end <= start:
84
+ # intervalo INVÁLIDO (tiempos invertidos): cue malformada y FUERA
85
+ # de toda medida (revisión externa, 3ª pasada — antes fabricaba
86
+ # segundos NEGATIVOS y un «demasiado rápida» por el clamp dur=0.1)
87
+ malformed.append(m.group(0)[:30])
88
+ continue
79
89
  cues.append({'start': start, 'end': end, 'text': body})
80
90
 
81
91
  if malformed:
@@ -106,7 +116,10 @@ def vtt_check(url, duration=None, lang='en'):
106
116
  example=', '.join(f"{r['t']}… ({r['cps']}cps)" for r in too_fast[:3]))
107
117
 
108
118
  if duration:
109
- covered = sum(max(0.0, min(c['end'], duration) - c['start']) for c in cues if c['start'] < duration)
119
+ # cobertura por UNIÓN de intervalos (revisión externa, 3ª pasada: dos
120
+ # cues solapadas 0-5s en un vídeo de 10 contaban 10s cubiertos — el
121
+ # solape no añade subtítulo, el tiempo cubierto es el de la unión)
122
+ covered = _union_seconds(cues, duration)
110
123
  pct = round(100 * covered / max(duration, 1), 1)
111
124
  if pct < 95:
112
125
  add('medium', 'vtt_coverage', pct=pct, dur=round(duration))
@@ -115,6 +128,23 @@ def vtt_check(url, duration=None, lang='en'):
115
128
  return _report(url, findings, len(cues), n_char, lang, duration, cues)
116
129
 
117
130
 
131
+ def _union_seconds(cues, ceiling=None):
132
+ """Segundos cubiertos por la UNIÓN de los intervalos (el solape no suma:
133
+ dos cues sobre el mismo segundo cubren UN segundo, no dos)."""
134
+ covered, last_end = 0.0, None
135
+ for s0, e0 in sorted((c['start'], min(c['end'], ceiling) if ceiling else c['end'])
136
+ for c in cues):
137
+ if e0 <= s0:
138
+ continue
139
+ if last_end is None or s0 > last_end:
140
+ covered += e0 - s0
141
+ last_end = e0
142
+ elif e0 > last_end:
143
+ covered += e0 - last_end
144
+ last_end = e0
145
+ return covered
146
+
147
+
118
148
  def _report(url, findings, n_cues, n_char, lang, duration, cues):
119
149
  from .a11yaudit import compute_score
120
150
  order = {'high': 0, 'medium': 1, 'low': 2}
@@ -123,7 +153,7 @@ def _report(url, findings, n_cues, n_char, lang, duration, cues):
123
153
  'mode': 'vtt', 'url': url,
124
154
  'duration': duration,
125
155
  'cues': n_cues, 'characters': n_char,
126
- 'captioned_seconds': round(sum(c['end'] - c['start'] for c in cues), 1) if cues else 0,
156
+ 'captioned_seconds': round(_union_seconds(cues), 1) if cues else 0,
127
157
  'score': compute_score(findings),
128
158
  'findings': findings,
129
159
  'summary': {s: sum(1 for h in findings if h['severity'] == s)
@@ -14,6 +14,7 @@
14
14
  if (window.__ariaLiveMonitor) { window.__ariaLiveMonitor(); return; }
15
15
  var SEL = '[aria-live],[role=alert],[role=status],[role=log],[role=marquee],[role=timer]';
16
16
  var log = [];
17
+ var observadores = []; // (6a pasada) se desconectan al cerrar el monitor
17
18
  var observados = new WeakSet();
18
19
 
19
20
  var css = document.createElement('style');
@@ -50,6 +51,7 @@
50
51
  var cortesia = el.getAttribute('aria-live') ||
51
52
  ({ alert: 'assertive', status: 'polite', log: 'polite',
52
53
  marquee: 'off', timer: 'off' })[el.getAttribute('role')] || 'polite';
54
+ if (cortesia === 'off') return; // aria-live=off (o marquee/timer): la region NO anuncia
53
55
  var texto = (el.innerText || el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 220);
54
56
  var hora = new Date().toTimeString().slice(0, 8);
55
57
  log.push(hora + ' [' + cortesia + '] ' + rol + ' · ' + desc(el) + ' · ' + texto);
@@ -78,14 +80,14 @@
78
80
  if (!el.matches(SEL)) return;
79
81
  observados.add(el);
80
82
  if (el.getAttribute('role') === 'alert') anota(el, 'insertado');
81
- new MutationObserver(function () {
82
- anota(el, null);
83
- }).observe(el, { childList: true, characterData: true, subtree: true });
83
+ var o = new MutationObserver(function () { anota(el, null); });
84
+ observadores.push(o);
85
+ o.observe(el, { childList: true, characterData: true, subtree: true });
84
86
  }
85
87
 
86
88
  document.querySelectorAll(SEL).forEach(function (el) { vigila(el); });
87
89
 
88
- new MutationObserver(function (muts) {
90
+ var cuerpo = new MutationObserver(function (muts) {
89
91
  muts.forEach(function (m) {
90
92
  m.addedNodes.forEach(function (n) {
91
93
  if (n.nodeType !== 1) return;
@@ -93,15 +95,23 @@
93
95
  if (n.querySelectorAll) n.querySelectorAll(SEL).forEach(vigila);
94
96
  });
95
97
  });
96
- }).observe(document.body, { childList: true, subtree: true });
98
+ });
99
+ observadores.push(cuerpo);
100
+ cuerpo.observe(document.body, { childList: true, subtree: true });
97
101
 
98
102
  panel.addEventListener('click', function (ev) {
99
103
  var b = ev.target.closest('button');
100
104
  if (!b) return;
101
- if (b.dataset.alm === 'close') { panel.remove(); css.remove(); delete window.__ariaLiveMonitor; }
105
+ if (b.dataset.alm === 'close') { cierra(); }
102
106
  if (b.dataset.alm === 'copy' && navigator.clipboard)
103
107
  navigator.clipboard.writeText(log.join('\n'));
104
108
  });
105
109
 
106
- window.__ariaLiveMonitor = function () { panel.remove(); css.remove(); delete window.__ariaLiveMonitor; };
110
+ function cierra() {
111
+ // (6a pasada) los observadores se DESCONECTAN: tras el cierre, una
112
+ // actualizacion seguia aterrizando en el panel ya retirado del DOM
113
+ observadores.forEach(function (o) { o.disconnect(); });
114
+ panel.remove(); css.remove(); delete window.__ariaLiveMonitor;
115
+ }
116
+ window.__ariaLiveMonitor = cierra;
107
117
  })();
@@ -240,17 +240,24 @@ def pair(fg_s, bg_s, with_suggestion=True, lang='en'):
240
240
  if fg.get('a', 1) < 1:
241
241
  fg = composite(fg, bg)
242
242
  alpha_note = hexs(fg)
243
- # se redondea ANTES de los veredictos: lo mostrado y el veredicto nunca
244
- # discrepan (un ratio en [4.495,4.5) no puede imprimir "4.5" y fallar)
245
- r = round(ratio(fg, bg), 2)
243
+ # el UMBRAL se aplica al valor EXACTO y el redondeo es solo presentación
244
+ # (revisión externa, 3ª pasada: #557e7d sobre blanco da 4,499934646:1 —
245
+ # redondear a 4,50 ANTES del veredicto aprobaba un contraste que el
246
+ # estándar reprueba). Cuando el redondeo maquilla el veredicto (4,4999 →
247
+ # «4,50»), el valor exacto viaja aparte para que el lector vea el porqué.
248
+ r_exact = ratio(fg, bg)
249
+ r = round(r_exact, 2)
246
250
  out = {
247
251
  'text': hexs(fg), 'background': hexs(bg),
248
252
  'ratio': r,
249
- 'verdicts': verdicts(r, lang),
253
+ 'verdicts': verdicts(r_exact, lang),
250
254
  }
255
+ if [v['passes'] for v in out['verdicts']] != \
256
+ [v['passes'] for v in verdicts(r, lang)]:
257
+ out['ratio_exact'] = round(r_exact, 6)
251
258
  if alpha_note:
252
259
  out['effective_color'] = alpha_note
253
- if with_suggestion and r < 4.5:
260
+ if with_suggestion and r_exact < 4.5:
254
261
  s = suggest(fg, bg, 4.5, lang)
255
262
  if s:
256
263
  out['aa_suggestion'] = s
@@ -223,7 +223,11 @@
223
223
  "state_contrast": "",
224
224
  "state_contrast_rem": "",
225
225
  "target_small": "",
226
- "target_small_rem": ""
226
+ "target_small_rem": "",
227
+ "focus_static_indicator": "Ambiguous focus indicator on {n} controls: they carry a border/shadow that does NOT change on focus ({det}). Permanent decoration is not a demonstrated indicator.",
228
+ "focus_static_indicator_rem": "Tab through and watch whether anything visually changes at each stop. If nothing does, add a real outline on :focus (or :focus-visible) — permanent decoration guides nobody by keyboard.",
229
+ "form_untestable": "{n} form(s) with no fillable field taking invalid data (checkboxes/radios/buttons only): error identification was NOT tested on this sample.",
230
+ "form_untestable_rem": "Test the flow by hand: submit the form with real errors and check the error is announced in text. Required checkboxes can be invalidated too (uncheck them)."
227
231
  },
228
232
  "evidence": {
229
233
  "manual_remaining": "",
@@ -231,7 +235,8 @@
231
235
  "not_flagged": "",
232
236
  "notice": "",
233
237
  "reviewer_note": "",
234
- "verified": ""
238
+ "verified": "",
239
+ "not_run": "no check for this criterion ran on this sample — missing: {modes}"
235
240
  },
236
241
  "fix": {
237
242
  "between": "",
@@ -448,7 +453,8 @@
448
453
  "standards_section": "",
449
454
  "table_caption": "",
450
455
  "title": "",
451
- "version": ""
456
+ "version": "",
457
+ "signature_scope": "Applied applicability scope (human-confirmed exclusions): scope seal <code>{sha}</code>. The pack seal covers the reports; this one covers the exclusions that changed this matrix."
452
458
  },
453
459
  "vtt": {
454
460
  "limits": "",
@@ -301,6 +301,8 @@
301
301
  "focus_navigates_rem": "Receiving focus must never change context (3.2.1): check focus→location.href, focus→form.submit(), focus→window.open().",
302
302
  "focus_not_focusable": "{n} controls that never receive focus via .focus(): {det}.",
303
303
  "focus_not_focusable_rem": "If it must be interactive, make it focusable (tabindex=\"0\"); otherwise remove it from the tab path.",
304
+ "focus_static_indicator": "Ambiguous focus indicator on {n} controls: they carry a border/shadow that does NOT change on focus ({det}). Permanent decoration is not a demonstrated indicator.",
305
+ "focus_static_indicator_rem": "Tab through and watch whether anything visually changes at each stop. If nothing does, add a real outline on :focus (or :focus-visible) — permanent decoration guides nobody by keyboard.",
304
306
  "focus_obscured": "{n} controls end up hidden behind fixed/sticky elements when focused (sticky headers, banners): {det}. Review (2.4.11).",
305
307
  "focus_obscured_rem": "Author-fixed content must not hide the focused element (2.4.11, new in WCAG 2.2 AA): set scroll-padding-top to the fixed header height, or make it auto-collapse.",
306
308
  "forced_colors_svg": "{n} SVGs with hardcoded colored fill: under forced-colors (Windows High Contrast) the fill falls back to inherited and the icon can turn invisible.",
@@ -311,6 +313,8 @@
311
313
  "form_error_no_suggestion_rem": "When the correction is known, say it: \"Use DD/MM/YYYY\", not \"Invalid date\" (3.3.3). Suggestion pattern: format/example text near the field.",
312
314
  "form_navigated": "The form navigates on submit; error behavior is not measurable in-page ({example}).",
313
315
  "form_navigated_rem": "Capture the destination page or intercept the submit; judging errors requires the post-submit DOM.",
316
+ "form_untestable": "{n} form(s) with no fillable field taking invalid data (checkboxes/radios/buttons only): error identification was NOT tested on this sample.",
317
+ "form_untestable_rem": "Test the flow by hand: submit the form with real errors and check the error is announced in text. Required checkboxes can be invalidated too (uncheck them).",
314
318
  "hover_not_dismissible": "{n} tooltips/overlays appearing on hover/focus that do NOT dismiss on Escape (1.4.13).",
315
319
  "hover_not_dismissible_rem": "Hover/focus-triggered content must be dismissible with Escape without moving the pointer (1.4.13): add a keydown Escape handler that hides the tooltip.",
316
320
  "input_navigates": "Changing {example} triggered automatic navigation (URL: {url}) — 3.2.2.",
@@ -336,6 +340,7 @@
336
340
  "manual_remaining": "human review remaining after the machine, per class (MIN 1-3, MED 5-10, MAX 15-30 min per criterion)",
337
341
  "no_signal": "no automated signal exists for this criterion in this toolkit",
338
342
  "not_flagged": "not-flagged ≠ pass: no automated signal fired on this sample",
343
+ "not_run": "no check for this criterion ran on this sample — missing: {modes}",
339
344
  "notice": "This pack is evidence, not conformance: it says what machines found and what remains for a human. A conformance claim requires the signature block completed by a qualified person who reviewed the manual list.",
340
345
  "reviewer_note": "any countersignature must reference pack.sha256 and state which criteria the human reviewed beyond the automated matrix",
341
346
  "verified": "verified against this sample per the manual checklist protocol",
@@ -489,6 +494,8 @@
489
494
  "pattern_tabs_no_activation_rem": "Make selection follow focus (automatic activation) or activate on Enter/Space (manual) — aria-selected must reflect the visible panel.",
490
495
  "pattern_disclosure_state_frozen": "Activating “{name}” never flips aria-expanded: the exposed state contradicts the visual.",
491
496
  "pattern_disclosure_state_frozen_rem": "Toggle aria-expanded (true/false) on every activation and point aria-controls at the region it reveals.",
497
+ "pattern_disclosure_keyboard_dead": "“{name}” does not react to Enter or Space while focused: the disclosure is mouse-only.",
498
+ "pattern_disclosure_keyboard_dead_rem": "Disclosures must open from the keyboard: handle Enter and Space keydown (and ArrowDown for menu buttons) exactly as the APG Disclosure pattern.",
492
499
  "pattern_combobox_no_open": "A combobox never opens its popup with ArrowDown (no aria-expanded, no visible listbox).",
493
500
  "pattern_combobox_no_open_rem": "Open the listbox on ArrowDown / Alt+ArrowDown and flip aria-expanded=true; keep focus on the input while filtering.",
494
501
  "pattern_combobox_esc_no_close": "A combobox popup stays open after Escape.",
@@ -639,6 +646,7 @@
639
646
  "notes": "Notes",
640
647
  "product": "Product name",
641
648
  "signature": "This document is a <strong>DRAFT</strong> generated by automated screening. Levels marked \"Not Evaluated\" must be set by a qualified person after review; the signature statement must reference the evidence pack hash:",
649
+ "signature_scope": "Applied applicability scope (human-confirmed exclusions): scope seal <code>{sha}</code>. The pack seal covers the reports; this one covers the exclusions that changed this matrix.",
642
650
  "signature_empty": "Empty signature block: name, credential and date pending.",
643
651
  "signature_title": "Signature and evidence",
644
652
  "standard": "<abbr title=\"Web Content Accessibility Guidelines\">WCAG</abbr> 2.2 (Levels A and AA) — W3C Recommendation, October 2023.",
@@ -301,6 +301,8 @@
301
301
  "focus_navigates_rem": "Recibir foco nunca debe cambiar el contexto (3.2.1): revisa focus→location.href, focus→form.submit(), focus→window.open().",
302
302
  "focus_not_focusable": "{n} controles que no reciben foco con .focus(): {det}.",
303
303
  "focus_not_focusable_rem": "Si debe ser interactivo, que sea enfocable (tabindex=\"0\"); si no, quítalo de la ruta de tabulación.",
304
+ "focus_static_indicator": "Un indicador de foco ambiguo en {n} controles: tienen borde/sombra que NO cambia al recibir el foco ({det}). Decoración permanente no es indicador demostrado.",
305
+ "focus_static_indicator_rem": "Recorre con Tab y mira si ALGO cambia visualmente en cada parada. Si nada cambia, añade un outline real en :focus (o :focus-visible) — la decoración permanente no guía a nadie por teclado.",
304
306
  "focus_obscured": "{n} controles quedan tapados por elementos fijos/sticky al recibir el foco (cabeceras sticky, banners): {det}. Revisar (2.4.11).",
305
307
  "focus_obscured_rem": "Un elemento fijo no debe ocultar el elemento enfocado (2.4.11, nuevo en WCAG 2.2 AA): usa scroll-padding-top igual a la altura del header fijo, o hazlo auto-colapsable.",
306
308
  "forced_colors_svg": "{n} SVG con fill coloreado hardcoded: en forced-colors (Windows High Contrast) el fill cae al heredado y el icono puede volverse invisible.",
@@ -311,6 +313,8 @@
311
313
  "form_error_no_suggestion_rem": "Cuando la corrección se conoce, dila: «Usa DD/MM/AAAA», no «Fecha inválida» (3.3.3). Sugerimos patrón: texto con formato/ejemplo cerca del campo.",
312
314
  "form_navigated": "El formulario navega al enviar; el comportamiento del error no es medible en la página ({example}).",
313
315
  "form_navigated_rem": "Captura la página de destino o prueba con un intercepto; el juicio del error requiere ver el DOM tras el envío.",
316
+ "form_untestable": "{n} formulario(s) sin ningún campo rellenable con dato inválido (solo casillas/radios o botones): la identificación de errores NO se probó en esta muestra.",
317
+ "form_untestable_rem": "Prueba el flujo a mano: envía el formulario con errores reales y comprueba que el error se anuncia en texto. Las casillas obligatorias también pueden invalidarse (desmárcalas).",
314
318
  "hover_not_dismissible": "{n} tooltips/overlays aparecen al hover/focus que NO se cierran con Escape (1.4.13).",
315
319
  "hover_not_dismissible_rem": "El contenido emergente debe poder cerrarse con Escape sin mover el puntero (1.4.13): añade keydown Escape que oculte el tooltip.",
316
320
  "input_navigates": "Cambiar {example} provocó navegación automática (URL: {url}) — 3.2.2.",
@@ -336,6 +340,7 @@
336
340
  "manual_remaining": "revisión humana pendiente después de la máquina, por clase (MIN 1-3, MED 5-10, MAX 15-30 min por criterio)",
337
341
  "no_signal": "no hay señal automática para este criterio en este motor",
338
342
  "not_flagged": "sin señal ≠ pasa: ninguna señal automática saltó en esta muestra",
343
+ "not_run": "ninguna prueba de este criterio se ejecutó en la muestra — falta: {modes}",
339
344
  "notice": "Este pack es evidencia, no conformidad: dice qué encontró la máquina y qué queda para una persona. Una declaración de conformidad requiere el bloque de firma completo, de una persona cualificada que haya revisado la lista manual.",
340
345
  "reviewer_note": "cualquier contrafirma debe referenciar pack.sha256 e indicar qué criterios revisó la persona más allá de la matriz automática",
341
346
  "verified": "verificado sobre esta muestra según el protocolo del checklist manual",
@@ -489,6 +494,8 @@
489
494
  "pattern_tabs_no_activation_rem": "Haz que la selección siga al foco (activación automática) o activa con Enter/Espacio (manual) — aria-selected debe reflejar el panel visible.",
490
495
  "pattern_disclosure_state_frozen": "Activar «{name}» nunca cambia aria-expanded: el estado expuesto contradice lo visual.",
491
496
  "pattern_disclosure_state_frozen_rem": "Alterna aria-expanded (true/false) en cada activación y apunta aria-controls a la región que revela.",
497
+ "pattern_disclosure_keyboard_dead": "«{name}» no reacciona a Enter ni Espacio con el foco en el control: el desplegable solo funciona con ratón.",
498
+ "pattern_disclosure_keyboard_dead_rem": "Los disclosure deben abrirse con teclado: maneja keydown de Enter y Espacio (y ArrowDown en botones de menú) exactamente como el patrón Disclosure del APG.",
492
499
  "pattern_combobox_no_open": "Un combobox nunca abre su popup con ArrowDown (sin aria-expanded, sin listbox visible).",
493
500
  "pattern_combobox_no_open_rem": "Abre el listbox con ArrowDown / Alt+ArrowDown y pon aria-expanded=true; mantiene el foco en el input mientras filtra.",
494
501
  "pattern_combobox_esc_no_close": "El popup de un combobox sigue abierto tras Escape.",
@@ -639,6 +646,7 @@
639
646
  "notes": "Notas",
640
647
  "product": "Nombre del producto",
641
648
  "signature": "Este documento es un <strong>BORRADOR</strong> generado por cribado automatizado. Los niveles marcados «No evaluado» deben ser fijados por una persona cualificada tras la revisión; la declaración de firma debe referenciar el hash del paquete de evidencia:",
649
+ "signature_scope": "Alcance de aplicabilidad aplicado (exclusiones confirmadas por una persona): sello del alcance <code>{sha}</code>. El sello del pack cubre los informes; este cubre las exclusiones que cambian esta matriz.",
642
650
  "signature_empty": "Bloque de firma sin completar: nombre, credencial y fecha pendientes.",
643
651
  "signature_title": "Firma y evidencia",
644
652
  "standard": "<abbr lang=\"en\" title=\"Web Content Accessibility Guidelines\">WCAG</abbr> 2.2 (niveles A y AA) — Recomendación W3C de octubre de 2023.",