@kinti/a11y-toolkit 5.29.0 → 5.31.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.
@@ -44,7 +44,16 @@ _LIMITS_MOTION = {
44
44
  }
45
45
 
46
46
  from . import a11yi18n
47
- # browser pool: Chromium reutilizable entre llamadas consecutivas
47
+ import atexit
48
+
49
+ # browser pool: Chromium reutilizable entre llamadas consecutivas. El pool ES
50
+ # el dueño del driver — browser y Playwright nacen y mueren JUNTOS (la lección
51
+ # del «Event loop is closed»: una función abría `with sync_playwright()`,
52
+ # guardaba el browser en el pool y el with mataba la sesión que lo creó; el
53
+ # objeto huérfano quedaba en el pool con is_connected() rancio y envenenaba
54
+ # TODAS las llamadas siguientes del servidor MCP). Las auditorías nunca cierran
55
+ # el navegador del pool: cierran su página/contexto y lo devuelven caliente;
56
+ # el driver muere una sola vez, al reciclar el pool o al acabar el proceso.
48
57
  _POOL = {'playwright': None, 'browser': None, 'type': None}
49
58
 
50
59
  # cadena de detección: el primer navegador disponible gana.
@@ -89,27 +98,69 @@ def _detect_browser(pw, preferred=None):
89
98
  'pip install playwright && playwright install chromium')
90
99
 
91
100
 
92
- def _get_browser(pw, headless=True, preferred=None):
93
- """Devuelve un browser del pool (o crea uno si no existe)."""
101
+ def _get_browser(headless=True, preferred=None):
102
+ """Devuelve un browser del pool (o crea uno si no existe). El driver de
103
+ Playwright lo arranca y posee el PROPIO pool: el browser devuelto vive
104
+ mientras viva el pool, no la sesión de quien lo pidió."""
94
105
  if _POOL['browser'] is not None and _POOL['browser'].is_connected() and \
95
106
  (preferred in (None, 'auto') or _POOL['type'] == preferred):
96
107
  return _POOL['browser']
97
108
  _close_pool()
109
+ from playwright.sync_api import sync_playwright
110
+ pw = sync_playwright().start()
98
111
  br, kind = _detect_browser(pw, preferred)
112
+ _POOL['playwright'] = pw
99
113
  _POOL['browser'] = br
100
114
  _POOL['type'] = kind
101
115
  return br
102
116
 
103
117
 
104
118
  def _close_pool():
105
- """Cierra el pool (llamar al terminar el proceso o bajo demanda)."""
106
- if _POOL['browser']:
107
- try:
108
- _POOL['browser'].close()
109
- except Exception:
110
- pass
119
+ """Cierra el pool: browser y driver JUNTOS, en orden (browser, luego
120
+ playwright.stop). Llamada al reciclar y al terminar el proceso (atexit)."""
121
+ br, pw = _POOL['browser'], _POOL['playwright']
111
122
  _POOL['browser'] = None
112
123
  _POOL['playwright'] = None
124
+ _POOL['type'] = None
125
+ if br is not None:
126
+ try:
127
+ br.close()
128
+ except Exception: # noqa: BLE001
129
+ pass
130
+ if pw is not None:
131
+ try:
132
+ pw.stop()
133
+ except Exception: # noqa: BLE001
134
+ pass
135
+
136
+
137
+ atexit.register(_close_pool)
138
+
139
+
140
+ def _pooled_page(nav, auth_state=None, **kw):
141
+ """(page, close_page) sobre el navegador del pool: con auth_state abre un
142
+ contexto propio (storage_state) cuyo cierre se lleva también la página;
143
+ sin él, página directa. close_page traga errores — el navegador del pool
144
+ queda caliente para la siguiente llamada, JAMÁS se cierra aquí."""
145
+ if auth_state:
146
+ ctx = nav.new_context(storage_state=auth_state, **kw)
147
+ page = ctx.new_page()
148
+
149
+ def close_page():
150
+ try:
151
+ ctx.close()
152
+ except Exception: # noqa: BLE001
153
+ pass
154
+ return page, close_page
155
+
156
+ page = nav.new_page(**kw)
157
+
158
+ def close_page():
159
+ try:
160
+ page.close()
161
+ except Exception: # noqa: BLE001
162
+ pass
163
+ return page, close_page
113
164
 
114
165
  MAX_EXAMPLES = 6
115
166
 
@@ -172,7 +223,8 @@ _JS = r'''(maxEj) => {
172
223
  placeholderContrast: [],
173
224
  imgs: [], canvasNoName: [], chartsNoEquiv: [], iframes: [], headings: [], tabindex: [], ariaHidden: [],
174
225
  blank: 0, videos: 0, videoSubs: 0, tables: 0, tableTh: 0,
175
- focus: [], focusFail: [], focusContrast: [], focusObscured: [], marks: 0,
226
+ focus: [], focusFail: [], focusReview: [], focusContrast: [], focusObscured: [], marks: 0,
227
+ colorUnparsed: 0,
176
228
  ids: {}, lang: null, title: '', viewport: null, refresh: null,
177
229
  main: false, skip: false, elements: 0, shadow_roots: 0,
178
230
  colorOnly: [], orderInversions: 0, loopingAnims: 0 };
@@ -251,10 +303,31 @@ _JS = r'''(maxEj) => {
251
303
 
252
304
  // ---- contraste real: fondo efectivo con composición de alfas ----
253
305
  const parseCol = c => {
254
- const m = /rgba?\(([^)]+)\)/.exec(c || '');
255
- if (!m) return null;
256
- const p = m[1].split(',').map(x => parseFloat(x));
257
- return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 };
306
+ const s = String(c || '');
307
+ let m = /rgba?\(([^)]+)\)/.exec(s);
308
+ if (m) {
309
+ const p = m[1].split(',').map(x => parseFloat(x));
310
+ return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 };
311
+ }
312
+ // color(srgb r g b [/ a]) — CSS Color 4: Chromium devuelve ESTO para
313
+ // colores declarados modernos y sin parseo el texto se omitía en
314
+ // silencio (revisión externa, 3ª pasada). Otros espacios (display-p3,
315
+ // lab…) no se convierten: cuentan como no convertidos, jamás inventados
316
+ m = /color\(\s*srgb\s+([^)]+)\)/.exec(s);
317
+ if (m) {
318
+ const parts = m[1].split('/');
319
+ const rgb = parts[0].trim().split(/\s+/);
320
+ const conv = v => v.endsWith('%') ? parseFloat(v) * 2.55 : parseFloat(v) * 255;
321
+ const a = parts.length > 1
322
+ ? (parts[1].trim().endsWith('%') ? parseFloat(parts[1]) / 100 : parseFloat(parts[1]))
323
+ : 1;
324
+ if (rgb.length >= 3 && isFinite(conv(rgb[0])) && isFinite(conv(rgb[1]))
325
+ && isFinite(conv(rgb[2])) && isFinite(a)) {
326
+ return { r: Math.round(conv(rgb[0])), g: Math.round(conv(rgb[1])),
327
+ b: Math.round(conv(rgb[2])), a };
328
+ }
329
+ }
330
+ return null;
258
331
  };
259
332
  const over = (fg, bg) => ({
260
333
  r: Math.round(fg.r * fg.a + bg.r * (1 - fg.a)),
@@ -314,7 +387,7 @@ _JS = r'''(maxEj) => {
314
387
  }
315
388
  const s = getComputedStyle(el);
316
389
  const fg = parseCol(s.color);
317
- if (!fg) continue;
390
+ if (!fg) { out.colorUnparsed++; continue; } // declarado, jamás omitido en silencio
318
391
  // text-shadow: los colores de la sombra pintan DETRÁS del text_ y
319
392
  // participan como fondo peor-caso (8c33: #666 con sombra #aaa sobre
320
393
  // blanco falla por 1.6:1 aunque el fondo dé 5.7) — se decide, no se
@@ -587,6 +660,9 @@ _JS = r'''(maxEj) => {
587
660
  }
588
661
  for (const r of roots) {
589
662
  for (const el of r.querySelectorAll('[aria-hidden="true"]')) {
663
+ // (7a pasada) inert saca el subarbol de la interaccion: un boton
664
+ // dentro de inert aria-hidden NO es enfocable aunque el atributo siga
665
+ if (el.closest('[inert]')) continue;
590
666
  if (el.matches(INTER)) {
591
667
  if (el.getAttribute('tabindex') !== '-1') out.ariaHidden.push(path(el));
592
668
  } else if ([...(el.querySelectorAll(INTER) || [])]
@@ -638,20 +714,34 @@ _JS = r'''(maxEj) => {
638
714
  const activeEl = () => { let a = document.activeElement;
639
715
  while (a && a.shadowRoot && a.shadowRoot.activeElement) a = a.shadowRoot.activeElement;
640
716
  return a; };
717
+ // firma de la APARIENCIA relevante para el foco (outline/sombra/bordes):
718
+ // comparar reposo vs foco distingue un indicador REAL (aparece/cambia al
719
+ // enfocar) de un borde PERMANENTE que estaba ahí antes y seguirá ahí
720
+ // después — la revisión externa 2026-11-22 cazó un botón con borde 2px y
721
+ // outline:none puntuando como foco visible
722
+ const sigOf = el => { const s = getComputedStyle(el);
723
+ return [s.outlineStyle + '/' + s.outlineWidth, s.boxShadow || '',
724
+ ['Top', 'Right', 'Bottom', 'Left'].map(
725
+ k => s['border' + k + 'Width'] + s['border' + k + 'Style'] + s['border' + k + 'Color']).join(';')].join('|');
726
+ };
641
727
  const prevFocus = document.activeElement;
642
728
  for (const el of stops) {
729
+ const before = sigOf(el);
643
730
  try { el.focus(); } catch (e) { /* no enfocable */ }
644
731
  if (activeEl() !== el) {
645
732
  out.focusFail.push({ example: path(el), why: 'nofocus' });
646
733
  continue;
647
734
  }
648
735
  const s = getComputedStyle(el);
736
+ const changed = sigOf(el) !== before;
649
737
  const outline = s.outlineStyle !== 'none' && parseFloat(s.outlineWidth || '0') > 0;
650
738
  const shadow = s.boxShadow && s.boxShadow !== 'none';
651
739
  const edgePx = ['Top', 'Right', 'Bottom', 'Left'].some(
652
740
  k => parseFloat(s['border' + k + 'Width'] || '0') >= 2
653
741
  && s['border' + k + 'Style'] !== 'none');
654
742
  if (!outline && !shadow && !edgePx) out.focus.push(path(el));
743
+ else if (!changed && out.focusReview.length < 20)
744
+ out.focusReview.push({ example: path(el), why: 'static-appearance' });
655
745
  const fgf = parseCol(s.color);
656
746
  const bgf = bgOf(el);
657
747
  if (fgf && !bgf.image) {
@@ -788,6 +878,13 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
788
878
  _add(findings, lang, 'low', '2.4.7', 'focus_not_focusable',
789
879
  examples=[f['example'] for f in data['focusFail']],
790
880
  n=len(data['focusFail']), det=', '.join(f['example'] for f in data['focusFail'][:4]))
881
+ # 3b. indicador AMBIGUO: hay borde/sombra/outline pero NO cambia al enfocar
882
+ # — decoración permanente, no indicador demostrado. Reseña (low), no fallo:
883
+ # el foco programático no dispara :focus-visible y el veredicto se reserva
884
+ if data.get('focusReview'):
885
+ _add(findings, lang, 'low', '2.4.7', 'focus_static_indicator',
886
+ examples=[f['example'] for f in data['focusReview']],
887
+ n=len(data['focusReview']), det=', '.join(f['example'] for f in data['focusReview'][:4]))
791
888
 
792
889
  # 4. Resto de señales (renderizadas)
793
890
  if data.get('unnamed'):
@@ -872,6 +969,10 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
872
969
  'color_scheme': color_scheme,
873
970
  'nested_iframes': data.get('nested_iframes', 0),
874
971
  'shadow_roots': data.get('shadow_roots', 0),
972
+ # colores computados que ningún parser pudo convertir a sRGB (color
973
+ # spaces exóticos): DECLARADOS, jamás omitidos en silencio
974
+ **({'unparsed_colors': data['colorUnparsed']}
975
+ if data.get('colorUnparsed') else {}),
875
976
  'score': compute_score(findings),
876
977
  'score_note': _t(lang, 'score_note'),
877
978
  'interactive_elements': data.get('elements', 0),
@@ -911,11 +1012,15 @@ _JS_FORM_FILL = r'''() => {
911
1012
  }'''
912
1013
 
913
1014
  _JS_FORM_PRE = r'''() => {
914
- // PRE-submit: la ayuda ordinaria que ya existía (describedby, contexto).
915
- // Sin esto, "Tu email" contaba como identificación de error y "Use…"
916
- // como sugerencia — la crítica externa lo destapó: ayuda ≠ error.
1015
+ // PRE-submit: la ayuda ordinaria que ya existía (describedby, contexto,
1016
+ // alertas vivas). Sin esto, "Tu email" contaba como identificación de error
1017
+ // y "Use…" como sugerencia — la crítica externa lo destapó: ayuda ≠ error.
917
1018
  const FIELDS_JS = 'input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]):not([type=image]), select, textarea';
918
- const pre = {};
1019
+ const pre = { __alerts: [] };
1020
+ for (const a of document.querySelectorAll('[role=alert], [aria-live]')) {
1021
+ const t = (a.innerText || '').trim();
1022
+ if (t) pre.__alerts.push(t);
1023
+ }
919
1024
  for (const el of document.querySelectorAll(FIELDS_JS)) {
920
1025
  if (el.disabled) continue;
921
1026
  const key = (el.name || el.id || el.type) + '@' + (el.form ? (el.form.id || el.form.action || '') : '');
@@ -939,8 +1044,14 @@ _JS_FORM_STATE = r'''(pre) => {
939
1044
  const RX_SUG = /(format|example|ejemplo|usa |use |dd\/mm|mm\/dd|pattern|como |like |must be|debe)/i;
940
1045
  pre = pre || {};
941
1046
  const out = { forms: [], alerts: 0 };
1047
+ const prev_alerts = (pre.__alerts || []);
942
1048
  for (const a of document.querySelectorAll('[role=alert], [aria-live]')) {
943
- if ((a.innerText || '').trim() && RX_ERR.test(a.innerText)) out.alerts++;
1049
+ const t = (a.innerText || '').trim();
1050
+ // SOLO alertas NUEVAS o CAMBIADAS tras el envío cuentan como
1051
+ // identificación del error (revisión externa, 3ª pasada): una alerta
1052
+ // AJENA preexistente en la página hacia 100 al formulario que fallaba
1053
+ // en silencio
1054
+ if (t && RX_ERR.test(t) && !prev_alerts.includes(t)) out.alerts++;
944
1055
  }
945
1056
  const FIELDS_JS = 'input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]):not([type=image]), select, textarea';
946
1057
  for (const f of document.querySelectorAll('form')) {
@@ -952,7 +1063,9 @@ _JS_FORM_STATE = r'''(pre) => {
952
1063
  const key = (el.name || el.id || el.type) + '@' + (f.id || f.action || '');
953
1064
  const shot_before = pre[key] || {};
954
1065
  let identified = false, sugerido = false;
955
- if (el.getAttribute('aria-invalid') === 'true') identified = true;
1066
+ // aria-invalid SOLO no identifica (3.3.1 exige TEXTO que describa el
1067
+ // error): el atributo marca el estado, no lo explica — cuenta únicamente
1068
+ // acompañado de texto vía describedby/contexto/mensaje nativo abajo
956
1069
  const db = el.getAttribute('aria-describedby');
957
1070
  if (db) for (const id of db.split(/\s+/)) {
958
1071
  const r = document.getElementById(id);
@@ -1022,16 +1135,13 @@ def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1022
1135
  """3.3.1 Error Identification / 3.3.3 Error Suggestion — the guided flow:
1023
1136
  fill every validatable field with INVALID data, really submit, then judge
1024
1137
  how errors are identified and announced in the post-submit DOM."""
1025
- from playwright.sync_api import sync_playwright
1026
- with sync_playwright() as p:
1027
- nav = _get_browser(p, preferred=browser)
1028
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1029
- page = ctx.new_page() if auth_state else nav.new_page()
1138
+ nav = _get_browser(preferred=browser)
1139
+ page, close_page = _pooled_page(nav, auth_state)
1140
+ try:
1030
1141
  try:
1031
1142
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1032
1143
  page.wait_for_timeout(400)
1033
1144
  except Exception as e: # noqa: BLE001
1034
- nav.close()
1035
1145
  return {'error': _t(lang, 'fetch_error').format(e=e)}
1036
1146
  url_before = page.url
1037
1147
  pre = page.evaluate(_JS_FORM_PRE)
@@ -1043,7 +1153,8 @@ def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1043
1153
  page.wait_for_timeout(900)
1044
1154
  navigated = page.url.split('#')[0] != url_before.split('#')[0]
1045
1155
  state = None if navigated else page.evaluate(_JS_FORM_STATE, pre)
1046
- nav.close()
1156
+ finally:
1157
+ close_page()
1047
1158
 
1048
1159
  findings = []
1049
1160
 
@@ -1064,6 +1175,12 @@ def audit_forms(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1064
1175
  suggested_fields = sum(f['suggested'] for f in state['forms'])
1065
1176
  if error_fields > 0 and suggested_fields == 0:
1066
1177
  add('low', '3.3.3', 'form_error_no_suggestion', n=error_fields)
1178
+ elif not touched and state is not None and state['forms']:
1179
+ # alcance declarado (revisión externa, 3ª pasada): un formulario sin
1180
+ # NINGÚN campo rellenable con dato inválido (solo casillas/radios)
1181
+ # devolvía 100 sin haber probado nada — esto es una reseña de alcance,
1182
+ # no una aprobación
1183
+ add('low', '3.3.1', 'form_untestable', n=len(state['forms']))
1067
1184
 
1068
1185
  from .a11yaudit import compute_score
1069
1186
  return {
@@ -1088,77 +1205,87 @@ def sr_transcript(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1088
1205
  structure; this function returns it as prose an agent can READ and
1089
1206
  understand from a blind user's perspective.
1090
1207
  """
1091
- # J4 (ronda 4): el driver de playwright NUNCA se paraba — una fuga
1092
- # de proceso por llamada en un servidor MCP de larga vida
1093
- from playwright.sync_api import sync_playwright
1094
- pw = sync_playwright().start()
1208
+ # J4 (ronda 4): el driver de playwright NUNCA se paraba — una fuga de
1209
+ # proceso por llamada en un servidor MCP de larga vida. Hoy el POOL posee
1210
+ # el driver (browser y playwright mueren juntos en _close_pool, atexit
1211
+ # incluido): esta función solo pide prestado y devuelve la página.
1212
+ nav = _get_browser(preferred=browser)
1213
+ page, close_page = _pooled_page(nav, auth_state)
1095
1214
  try:
1096
- nav = _get_browser(pw, preferred=browser)
1097
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1098
- page = ctx.new_page() if auth_state else nav.new_page()
1099
1215
  try:
1100
1216
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1101
1217
  page.wait_for_timeout(400)
1102
1218
  except Exception as e:
1103
- ctx.close()
1104
- _close_pool()
1105
1219
  return {'error': str(e)[:100]}
1106
1220
 
1107
1221
  try:
1108
1222
  tree = page.locator('body').aria_snapshot()
1109
1223
  except Exception:
1110
1224
  tree = None
1111
- try:
1112
- ctx.close()
1113
- except Exception:
1114
- pass
1115
-
1116
- if not tree:
1117
- return {'url': url, 'mode': 'sr-transcript',
1118
- 'error': 'accessibility tree not available (Playwright >= 1.49 required)'}
1119
-
1120
- # parse the YAML-like snapshot into linearized announcements
1121
- import re
1122
- announcements = []
1123
- for line in tree.split('\n'):
1124
- stripped = line.strip()
1125
- if not stripped.startswith('- '):
1126
- continue
1127
- # quitar el guion inicial; el resto es el anuncio
1128
- announcement = stripped[2:].rstrip(':')
1129
- if announcement:
1130
- announcements.append(announcement)
1131
-
1132
- return {
1133
- 'url': url,
1134
- 'mode': 'sr-transcript',
1135
- 'announcements': announcements[:200], # cap
1136
- 'total': len(announcements),
1137
- 'arbol_raw': tree[:5000] if len(tree) > 5000 else tree,
1138
- 'note': ('Linearized announcement order — what a screen reader user hears. '
1139
- 'Roles and names as computed by the browser. Use this to understand '
1140
- 'the page from a blind user\'s perspective.'),
1141
- }
1225
+ finally:
1226
+ close_page()
1227
+
1228
+ if not tree:
1229
+ return {'url': url, 'mode': 'sr-transcript',
1230
+ 'error': 'accessibility tree not available (Playwright >= 1.49 required)'}
1231
+
1232
+ # parse the YAML-like snapshot into linearized announcements
1233
+ import re
1234
+ announcements = []
1235
+ for line in tree.split('\n'):
1236
+ stripped = line.strip()
1237
+ if not stripped.startswith('- '):
1238
+ continue
1239
+ # quitar el guion inicial; el resto es el anuncio
1240
+ announcement = stripped[2:].rstrip(':')
1241
+ if announcement:
1242
+ announcements.append(announcement)
1142
1243
 
1244
+ return {
1245
+ 'url': url,
1246
+ 'mode': 'sr-transcript',
1247
+ 'announcements': announcements[:200], # cap
1248
+ 'total': len(announcements),
1249
+ 'arbol_raw': tree[:5000] if len(tree) > 5000 else tree,
1250
+ 'note': ('Linearized announcement order — what a screen reader user hears. '
1251
+ 'Roles and names as computed by the browser. Use this to understand '
1252
+ 'the page from a blind user\'s perspective.'),
1253
+ }
1254
+ # (6a pasada) identidad de los tooltips visibles AHORA: una sola
1255
+ # definicion para antes/durante/despues, en vez de tres literales
1256
+ _TOOLTIPS_VISIBLE_JS = (
1257
+ "() => [...document.querySelectorAll("
1258
+ "'[role=tooltip], [class*=tooltip], [class*=popover]')]"
1259
+ ".filter(el => {"
1260
+ " if (el.checkVisibility) "
1261
+ " return el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true});"
1262
+ " const s = getComputedStyle(el);"
1263
+ " const box = el.getBoundingClientRect();"
1264
+ " return el.offsetParent !== null && s.visibility !== 'hidden'"
1265
+ " && parseFloat(s.opacity || '1') > 0.01 && box.width > 0;"
1266
+ "})"
1267
+ ".map(el => el.tagName + '#' + (el.id || '') + '.' + (el.className.toString().slice(0, 30)))")
1143
1268
 
1144
- finally:
1145
- try:
1146
- pw.stop()
1147
- except Exception: # noqa: BLE001
1148
- pass
1149
1269
  _JS_HOVER_TEST = r'''() => {
1150
- // find elements that show tooltips/overlays on hover
1270
+ // find elements that show tooltips/overlays on hover. (6a pasada) cada
1271
+ // candidato se SELLA con data-a11yhover=<i>: el hover va a ESTE nodo --
1272
+ // el selector tag/id antiguo probaba el PRIMER nodo homonimo dos veces
1273
+ // y se perdia el tooltip persistente del segundo
1151
1274
  const candidates = [];
1275
+ let n = 0;
1152
1276
  for (const el of document.querySelectorAll('[title], [data-tooltip], [aria-describedby]')) {
1153
1277
  if (candidates.length >= 10) break;
1154
1278
  const r = el.getBoundingClientRect();
1155
1279
  if (r.width > 10 && r.height > 10 && r.top >= 0 && r.top < innerHeight) {
1280
+ el.setAttribute('data-a11yhover', String(n));
1156
1281
  candidates.push({
1157
1282
  tag: el.tagName.toLowerCase(),
1158
1283
  id: el.id || '',
1284
+ idx: n,
1159
1285
  desc: el.getAttribute('aria-describedby') || el.getAttribute('title') || '',
1160
1286
  rect: {x: r.x, y: r.y, w: r.width, h: r.height}
1161
1287
  });
1288
+ n++;
1162
1289
  }
1163
1290
  }
1164
1291
  return candidates;
@@ -1166,64 +1293,47 @@ _JS_HOVER_TEST = r'''() => {
1166
1293
 
1167
1294
  def audit_hover(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1168
1295
  """1.4.13 Content on Hover or Focus: do tooltips dismiss on Escape?"""
1169
- from playwright.sync_api import sync_playwright
1170
- with sync_playwright() as p:
1171
- nav = _get_browser(p, preferred=browser)
1172
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1173
- page = ctx.new_page() if auth_state else nav.new_page()
1296
+ nav = _get_browser(preferred=browser)
1297
+ page, close_page = _pooled_page(nav, auth_state)
1298
+ try:
1174
1299
  try:
1175
1300
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1176
1301
  page.wait_for_timeout(400)
1177
1302
  except Exception as e:
1178
- nav.close()
1179
1303
  return {'error': str(e)[:100]}
1304
+ # tooltips visibles ANTES de tocar nada: los preexistentes (ajenos)
1305
+ # jamas se atribuyen a un control por el mero hecho de hoverear
1306
+ _preexisting_tips = page.evaluate(_TOOLTIPS_VISIBLE_JS)
1180
1307
 
1181
1308
  candidates = page.evaluate(_JS_HOVER_TEST)
1182
1309
  no_dismissibles = []
1183
- for c in candidates[:8]:
1184
- try:
1185
- # hover sobre el elemento
1186
- sel = f'{c["tag"]}#{c["id"]}' if c['id'] else c['tag']
1187
- page.hover(sel, timeout=2000)
1188
- page.wait_for_timeout(400)
1189
- # identidad de los tooltips visibles ANTES (por elemento, no
1190
- # por recuento global: other tooltip podía aparecer a la vez y
1191
- # el contador antiguo enmascaraba un cierre correcto)
1192
- before = page.evaluate(
1193
- "() => [...document.querySelectorAll("
1194
- "'[role=tooltip], [class*=tooltip], [class*=popover]')]"
1195
- ".filter(el => {"
1196
- " if (el.checkVisibility) "
1197
- " return el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true});"
1198
- " const s = getComputedStyle(el);"
1199
- " const box = el.getBoundingClientRect();"
1200
- " return el.offsetParent !== null && s.visibility !== 'hidden'"
1201
- " && parseFloat(s.opacity || '1') > 0.01 && box.width > 0;"
1202
- "})"
1203
- ".map(el => el.tagName + '#' + (el.id || '') + '.' + (el.className.toString().slice(0, 30)))")
1204
- if not before:
1205
- continue # nada visible → no aplica
1206
- # Escape
1207
- page.keyboard.press('Escape')
1208
- page.wait_for_timeout(300)
1209
- after = page.evaluate(
1210
- "() => [...document.querySelectorAll("
1211
- "'[role=tooltip], [class*=tooltip], [class*=popover]')]"
1212
- ".filter(el => {"
1213
- " if (el.checkVisibility) "
1214
- " return el.checkVisibility({checkOpacity: true, checkVisibilityCSS: true});"
1215
- " const s = getComputedStyle(el);"
1216
- " const box = el.getBoundingClientRect();"
1217
- " return el.offsetParent !== null && s.visibility !== 'hidden'"
1218
- " && parseFloat(s.opacity || '1') > 0.01 && box.width > 0;"
1219
- "})"
1220
- ".map(el => el.tagName + '#' + (el.id || '') + '.' + (el.className.toString().slice(0, 30)))")
1221
- if set(before) <= set(after):
1222
- # los mismos (o más) siguen visibles: no se cerró con Escape
1223
- no_dismissibles.append(f'{c["tag"]}#{c["id"] or "no-id"}')
1224
- except Exception:
1225
- continue
1226
- nav.close()
1310
+ try:
1311
+ for c in candidates[:8]:
1312
+ try:
1313
+ # (6a pasada) hover sobre ESTE nodo por su sello; y solo
1314
+ # cuentan los tooltips que APARECEN al activarlo -- un
1315
+ # tooltip ajeno ya visible no se atribuye al control
1316
+ page.hover(f'[data-a11yhover="{c["idx"]}"]', timeout=2000)
1317
+ page.wait_for_timeout(400)
1318
+ _during = page.evaluate(_TOOLTIPS_VISIBLE_JS)
1319
+ _new_tips = [t for t in _during if t not in _preexisting_tips]
1320
+ if not _new_tips:
1321
+ continue # este control no mostro nada nuevo: no aplica
1322
+ page.keyboard.press('Escape')
1323
+ page.wait_for_timeout(300)
1324
+ _after_esc = page.evaluate(_TOOLTIPS_VISIBLE_JS)
1325
+ if set(_new_tips) <= set(_after_esc):
1326
+ # los mismos (o mas) siguen visibles: no se cerro
1327
+ no_dismissibles.append(f'{c["tag"]}#{c["id"] or "no-id"}')
1328
+ except Exception:
1329
+ continue
1330
+ finally:
1331
+ # limpiar los sellos: la pagina queda como estaba
1332
+ page.evaluate(
1333
+ "() => document.querySelectorAll('[data-a11yhover]')"
1334
+ ".forEach(el => el.removeAttribute('data-a11yhover'))")
1335
+ finally:
1336
+ close_page()
1227
1337
 
1228
1338
  findings = []
1229
1339
  if no_dismissibles:
@@ -1242,22 +1352,51 @@ def audit_hover(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1242
1352
 
1243
1353
 
1244
1354
  _JS_SPACING = r'''() => {
1245
- // WCAG 1.4.12 Text Spacing: the documented override set, applied globally,
1246
- // then measure which texts get clipped by height-constrained containers.
1355
+ // WCAG 1.4.12 (5a pasada): ANTES y DESPUES de inyectar los overrides, y
1356
+ // el recorte del CONTENEDOR (propio o de cualquier ancestro con overflow
1357
+ // hidden O clip) -- antes: una sola medicion acusaba parrafos ya recortados
1358
+ // de antes y no veia los que empezaban a recortarse con el espaciado.
1359
+ const SEL = 'p, li, h1, h2, h3, h4, h5, h6, a, span, label';
1360
+ const clippedBy = el => {
1361
+ let n = el;
1362
+ while (n && n !== document.body) {
1363
+ const s = getComputedStyle(n);
1364
+ const modes = [s.overflow, s.overflowY, s.overflowX];
1365
+ if (modes.includes('hidden') || modes.includes('clip')) {
1366
+ const rb = n.getBoundingClientRect(), re = el.getBoundingClientRect();
1367
+ if (n === el) {
1368
+ // (7a pasada) el elemento recortado por SU PROPIA caja (clip no
1369
+ // crea contenedor de scroll: scrollHeight no sirve): un Range
1370
+ // mide el TEXTO real — comparar la caja consigo misma daba falso
1371
+ const rg = document.createRange();
1372
+ rg.selectNodeContents(el);
1373
+ const rt = rg.getBoundingClientRect();
1374
+ return rt.bottom > rb.bottom + 3 || rt.right > rb.right + 3;
1375
+ }
1376
+ if (re.bottom > rb.bottom + 3 || re.right > rb.right + 3) return true;
1377
+ return false; // ancestro recortante y el elemento dentro: no clip
1378
+ }
1379
+ n = n.parentElement;
1380
+ }
1381
+ return false;
1382
+ };
1383
+ const snap = {};
1384
+ document.querySelectorAll(SEL).forEach((el, i) => {
1385
+ if (!el.offsetParent) return;
1386
+ snap[i] = clippedBy(el);
1387
+ });
1247
1388
  const css = document.createElement('style');
1248
1389
  css.id = 'a11y-spacing-1412';
1249
1390
  css.textContent = '*{line-height:1.5!important;letter-spacing:0.12em!important;'
1250
1391
  + 'word-spacing:0.16em!important} p{margin-bottom:2em!important}';
1251
1392
  document.head.appendChild(css);
1252
1393
  const clip = [];
1253
- for (const el of document.querySelectorAll('p, li, h1, h2, h3, h4, h5, h6, a, span, label')) {
1254
- if (clip.length >= 15) break;
1255
- if (!el.offsetParent) continue;
1256
- const s = getComputedStyle(el);
1257
- const clipped = (s.overflow === 'hidden' || s.overflowY === 'hidden')
1258
- && el.scrollHeight > el.clientHeight + 3;
1259
- if (clipped) clip.push(el.tagName.toLowerCase() + (el.id ? '#' + el.id : ''));
1260
- }
1394
+ document.querySelectorAll(SEL).forEach((el, i) => {
1395
+ if (clip.length >= 15) return;
1396
+ if (!el.offsetParent) return;
1397
+ if (!snap[i] && clippedBy(el))
1398
+ clip.push(el.tagName.toLowerCase() + (el.id ? '#' + el.id : ''));
1399
+ });
1261
1400
  css.remove();
1262
1401
  return clip;
1263
1402
  }'''
@@ -1266,6 +1405,7 @@ _JS_HOVER = r'''(i) => {
1266
1405
  const el = document.querySelector('[data-a11yidx="' + i + '"]');
1267
1406
  if (!el) return null;
1268
1407
  const parseCol = c => { const m = /rgba?\(([^)]+)\)/.exec(c || '');
1408
+ if(!m){const m3=/color\(\s*srgb\s+([^)]+)\)/.exec(c||'');if(m3){const ps=m3[1].split('/');const rgb=ps[0].trim().split(/\s+/);const cv=v=>v.endsWith('%')?parseFloat(v)*2.55:parseFloat(v)*255;const al=ps.length>1?(ps[1].trim().endsWith('%')?parseFloat(ps[1])/100:parseFloat(ps[1])):1;if(rgb.length>=3&&isFinite(cv(rgb[0]))&&isFinite(cv(rgb[1]))&&isFinite(cv(rgb[2]))&&isFinite(al))return{r:Math.round(cv(rgb[0])),g:Math.round(cv(rgb[1])),b:Math.round(cv(rgb[2])),a:al};}return null;}
1269
1409
  if (!m) return null;
1270
1410
  const p = m[1].split(',').map(x => parseFloat(x));
1271
1411
  return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 }; };
@@ -1345,21 +1485,23 @@ def audit_reflow(url, timeout=45, lang='en', auth_state=None, browser='auto'):
1345
1485
  un viewport de 320px, no emular zoom con CSS (validado empíricamente:
1346
1486
  el truco de zoom CSS marca en falso páginas sanas porque no re-lleva a cabo
1347
1487
  el layout)."""
1348
- from playwright.sync_api import sync_playwright
1349
- with sync_playwright() as p:
1350
- nav = _get_browser(p, preferred=browser)
1351
- page = nav.new_page(viewport={'width': 1280, 'height': 800})
1488
+ nav = _get_browser(preferred=browser)
1489
+ # auth_state aplica por fin aquí también (la revisión externa lo cazó:
1490
+ # el parámetro existía y se IGNORABA — con la cookie fuera, la pantalla
1491
+ # de login puntuaba 100); con sesión, el viewport viaja en el contexto
1492
+ page, close_page = _pooled_page(nav, auth_state, viewport={'width': 1280, 'height': 800})
1493
+ try:
1352
1494
  try:
1353
1495
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1354
1496
  page.wait_for_timeout(300)
1355
1497
  except Exception as e: # noqa: BLE001
1356
- nav.close()
1357
1498
  return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1358
1499
 
1359
1500
  page.set_viewport_size({'width': 320, 'height': 800})
1360
1501
  page.wait_for_timeout(500)
1361
1502
  r320 = page.evaluate(_JS_OVERFLOW)
1362
- nav.close()
1503
+ finally:
1504
+ close_page()
1363
1505
 
1364
1506
  findings = []
1365
1507
 
@@ -1467,16 +1609,13 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1467
1609
  ESCAPE libera el ciclo. Un modal que cicla y suelta con Escape es correcto;
1468
1610
  uno que no suelta es trampa — hallazgo 'high'.
1469
1611
  """
1470
- from playwright.sync_api import sync_playwright
1471
- with sync_playwright() as p:
1472
- nav = _get_browser(p, preferred=browser)
1473
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1474
- page = ctx.new_page() if auth_state else nav.new_page()
1612
+ nav = _get_browser(preferred=browser)
1613
+ page, close_page = _pooled_page(nav, auth_state)
1614
+ try:
1475
1615
  try:
1476
1616
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1477
1617
  page.wait_for_timeout(400)
1478
1618
  except Exception as e: # noqa: BLE001
1479
- nav.close()
1480
1619
  return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1481
1620
 
1482
1621
  page.evaluate("document.querySelectorAll('[data-a11ystop]').forEach(e => {"
@@ -1496,9 +1635,14 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1496
1635
  seq.append(stop)
1497
1636
  if stop not in paths:
1498
1637
  paths[stop] = page.evaluate(_STOP_META, stop)
1499
- # detección de ciclo: el final de la secuencia se repite con periodo p
1638
+ # detección de ciclo: el final de la secuencia se repite con periodo p.
1639
+ # El tope de periodo sale de la SECUENCIA OBSERVADA (len/2; con 2
1640
+ # repeticiones completas exigidas ya no puede afirmar un periodo que
1641
+ # no ocurrió dos veces) — el tope fijo de 12 dejaba trampas de 13+
1642
+ # paradas sin hallazgo consumiendo el presupuesto entero (revisión
1643
+ # externa, 3ª pasada)
1500
1644
  cycle = None
1501
- for p_ in range(1, min(12, len(seq) // 2) + 1):
1645
+ for p_ in range(1, len(seq) // 2 + 1):
1502
1646
  if seq[-p_:] == seq[-2 * p_:-p_] and len(set(seq[-p_:])) >= 1:
1503
1647
  # needs al menos 2 repeticiones completas del periodo
1504
1648
  reps = sum(1 for k in range(len(seq) - p_, 0, -p_)
@@ -1506,6 +1650,9 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1506
1650
  if reps >= 2:
1507
1651
  cycle = seq[-p_:]
1508
1652
  break
1653
+ # presupuesto agotado sin círculo completo: el veredicto de trampa es
1654
+ # INDECISO, no «sin trampa» — se declara
1655
+ budget_exhausted = (cycle is None and len(seq) >= max_steps)
1509
1656
 
1510
1657
  # 3.2.1: ¿el foco provocó navegación? (context destroyed = navegación)
1511
1658
  focus_navigated = None
@@ -1515,22 +1662,49 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1515
1662
  except Exception:
1516
1663
  focus_navigated = url_before + ' → (navigated away)'
1517
1664
 
1518
- # 3.2.2: ¿un select provoca navegación al cambiar?
1665
+ # 3.2.2: ¿un select provoca navegación al cambiar? (6a pasada) TODOS
1666
+ # los selects (hasta 3), y el AVISO PREVIO se juzga aparte de la
1667
+ # observación: un aria-describedby que anuncia el cambio EXIME; la
1668
+ # navegación silenciosa se registra por CONTROL — antes solo se
1669
+ # probaba el primer select y uno CON aviso disparaba el hallazgo
1519
1670
  input_navigated = None
1520
1671
  input_elem = None
1672
+ select_observations = []
1521
1673
  if not focus_navigated:
1522
1674
  try:
1523
- sel = page.query_selector('select')
1524
- if sel:
1675
+ url_pre = page.url
1676
+ for sel in page.query_selector_all('select')[:3]:
1525
1677
  opts = sel.query_selector_all('option')
1526
- if len(opts) > 1:
1527
- url_pre = page.url
1678
+ if len(opts) <= 1:
1679
+ continue
1680
+ _advisory = sel.evaluate(
1681
+ 'el => { const db = el.getAttribute("aria-describedby");'
1682
+ ' if (!db) return false;'
1683
+ ' const AVISO = /naviga|ir[áa]s|ir a|go(es)? to|take(s)? you|'
1684
+ 'p[áa]gina|page|redirect|redirig|cambiar[áa]|change|jump|salta|'
1685
+ 'send|llevar|abrir|open|visit|visita/i;'
1686
+ ' return db.split(/\\s+/).some(id => {'
1687
+ ' const r = document.getElementById(id);'
1688
+ ' const t = r ? (r.innerText || "").trim() : "";'
1689
+ ' return t && AVISO.test(t); }); }')
1690
+ _name = (sel.get_attribute('aria-label')
1691
+ or sel.get_attribute('id') or 'select')[:40]
1692
+ try:
1528
1693
  sel.select_option(index=1)
1529
- page.wait_for_timeout(600)
1530
- if page.url != url_pre:
1531
- input_navigated = page.url
1532
- input_elem = 'select'
1533
- except Exception:
1694
+ except Exception: # noqa: BLE001
1695
+ continue
1696
+ page.wait_for_timeout(600)
1697
+ if page.url.split('#')[0] != url_pre.split('#')[0]:
1698
+ input_navigated = page.url
1699
+ input_elem = _name
1700
+ select_observations.append(
1701
+ {'control': _name, 'navigated': True,
1702
+ 'prior_advisory': bool(_advisory)})
1703
+ break # la página ya no está: no hay más que probar
1704
+ select_observations.append(
1705
+ {'control': _name, 'navigated': False,
1706
+ 'prior_advisory': bool(_advisory)})
1707
+ except Exception: # noqa: BLE001
1534
1708
  pass
1535
1709
 
1536
1710
  esc_releases = None
@@ -1573,10 +1747,8 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1573
1747
  skip['broken'].append(found['id'])
1574
1748
  except Exception: # noqa: BLE001 — SPA o contexto destruido: sin dato
1575
1749
  pass
1576
- try:
1577
- nav.close()
1578
- except Exception:
1579
- pass
1750
+ finally:
1751
+ close_page()
1580
1752
 
1581
1753
  findings = []
1582
1754
  if focus_navigated:
@@ -1585,7 +1757,9 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1585
1757
  'signal': 'focus_navigates',
1586
1758
  'issue': _t(lang, 'focus_navigates').format(example='un elemento', url=focus_navigated[:60]),
1587
1759
  'remediation': _t(lang, 'focus_navigates_rem')})
1588
- if input_navigated:
1760
+ if input_navigated and not any(o['prior_advisory'] for o in select_observations
1761
+ if o['control'] == input_elem):
1762
+ # navegación REAL sin aviso previo asociado al control que navegó
1589
1763
  findings.append({
1590
1764
  'severity': 'high', 'criterion': CRIT.get(lang, CRIT['es']).get('3.2.2', '3.2.2'),
1591
1765
  'signal': 'input_navigates',
@@ -1615,8 +1789,10 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1615
1789
  'summary': {s_: sum(1 for h in findings if h['severity'] == s_)
1616
1790
  for s_ in ('high', 'medium', 'low')},
1617
1791
  'steps': len(seq),
1792
+ 'select_observations': select_observations,
1618
1793
  'tab_stops': [paths.get(i, f'tab stop {i}') for i in seq],
1619
1794
  'cycle': {'detected': bool(cycle),
1795
+ 'budget_exhausted': budget_exhausted,
1620
1796
  'elements': [paths.get(i, f'tab stop {i}') for i in cycle] if cycle else [],
1621
1797
  'escape_releases': esc_releases},
1622
1798
  'skip_link': {'checked': skip['checked'], 'label': skip.get('label'),
@@ -1759,7 +1935,6 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
1759
1935
  dependen del color del autor pueden quedar invisible_els sobre el fondo
1760
1936
  del sistema), y bordes usados como único indicador visual. Nadie más
1761
1937
  lo automatiza."""
1762
- from playwright.sync_api import sync_playwright
1763
1938
  _JS_FC = r'''() => {
1764
1939
  const invisible_els = [];
1765
1940
  let n = 0;
@@ -1790,10 +1965,9 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
1790
1965
  }'''
1791
1966
  from .a11yaudit import _t as _t_audit, CRIT, compute_score
1792
1967
 
1793
- with sync_playwright() as p:
1794
- nav = _get_browser(p, preferred=browser)
1795
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1796
- page = ctx.new_page() if auth_state else nav.new_page()
1968
+ nav = _get_browser(preferred=browser)
1969
+ page, close_page = _pooled_page(nav, auth_state)
1970
+ try:
1797
1971
  try:
1798
1972
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1799
1973
  page.wait_for_timeout(400)
@@ -1802,9 +1976,9 @@ def audit_forced_colors(url, timeout=45, lang='en', auth_state=None, browser='au
1802
1976
  page.wait_for_timeout(400)
1803
1977
  forced = page.evaluate(_JS_FC)
1804
1978
  except Exception as e: # noqa: BLE001
1805
- nav.close()
1806
1979
  return {'error': _t_audit(lang, 'fetch_error').format(e=e)}
1807
- nav.close()
1980
+ finally:
1981
+ close_page()
1808
1982
 
1809
1983
  findings = []
1810
1984
  if forced['coloredSvgs']:
@@ -1835,31 +2009,37 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
1835
2009
  vez. Si el número NO baja, el sitio ignora la preferencia del usuario
1836
2010
  (2.2.2: pausa/parada/ocultar; 2.3.3 AAA). Nadie más lo automatiza:
1837
2011
  axe lo deja en revisión manual."""
1838
- from playwright.sync_api import sync_playwright
1839
2012
  _JS_RM = r'''() => {
1840
- let n = 0, examples = [];
2013
+ // (5a pasada) por ELEMENTO y con estado de reproduccion: una lista con
2014
+ // una animacion infinita y otra finita no contaba (iterationCount es
2015
+ // una LISTA 'infinite,1'), y pausar por CSS daba 'no respeta' aunque
2016
+ // el movimiento estuviera detenido
2017
+ const out = {};
1841
2018
  for (const el of document.querySelectorAll('*')) {
1842
- if (n >= 40) break;
2019
+ if (Object.keys(out).length >= 40) break;
1843
2020
  const cs = getComputedStyle(el);
1844
- if (cs.animationIterationCount !== 'infinite' || cs.animationName === 'none') continue;
2021
+ const counts = (cs.animationIterationCount || '').split(',');
1845
2022
  const durs = (cs.animationDuration || '0s').split(',').map(
1846
2023
  x => { const v = parseFloat(x) || 0; return x.includes('ms') ? v / 1000 : v; });
1847
- const dur = Math.max(...durs, 0);
1848
- if (dur <= 0.15) continue;
1849
- n++;
1850
- if (examples.length < 6) examples.push(
1851
- el.tagName.toLowerCase() + (el.id ? '#' + el.id : '')
1852
- + '.' + String(el.className).slice(0, 25) + ' (' + cs.animationName.slice(0, 30) + ')');
2024
+ let loops = false;
2025
+ for (let i = 0; i < counts.length; i++)
2026
+ if (counts[i].trim() === 'infinite' && (durs[i] || 0) > 0.15) { loops = true; break; }
2027
+ if (!loops) continue;
2028
+ const paused = (cs.animationPlayState || '').split(',').every(p => p.trim() === 'paused');
2029
+ const key = el.tagName.toLowerCase() + (el.id ? '#' + el.id : '')
2030
+ + ':' + String(cs.animationName).slice(0, 40);
2031
+ if (!(key in out)) out[key] = { paused: paused,
2032
+ example: el.tagName.toLowerCase() + (el.id ? '#' + el.id : '')
2033
+ + ' (' + String(cs.animationName).slice(0, 30) + ')' };
1853
2034
  }
1854
2035
  const videos = document.querySelectorAll('video[autoplay]').length;
1855
- return { anims: n, examples: examples, videos };
2036
+ return { anims: out, videos };
1856
2037
  }'''
1857
2038
  from .a11yaudit import _t as _t_audit, CRIT, compute_score
1858
2039
 
1859
- with sync_playwright() as p:
1860
- nav = _get_browser(p, preferred=browser)
1861
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1862
- page = ctx.new_page() if auth_state else nav.new_page()
2040
+ nav = _get_browser(preferred=browser)
2041
+ page, close_page = _pooled_page(nav, auth_state)
2042
+ try:
1863
2043
  try:
1864
2044
  page.goto(url, wait_until='load', timeout=timeout * 1000)
1865
2045
  page.wait_for_timeout(600)
@@ -1868,25 +2048,40 @@ def audit_reduced_motion(url, timeout=45, lang='en', auth_state=None, browser='a
1868
2048
  page.wait_for_timeout(600)
1869
2049
  reduced = page.evaluate(_JS_RM)
1870
2050
  except Exception as e: # noqa: BLE001
1871
- nav.close()
1872
2051
  return {'error': _t_audit(lang, 'fetch_error').format(e=e)}
1873
- nav.close()
1874
-
1875
- respects = reduced['anims'] < normal['anims']
2052
+ finally:
2053
+ close_page()
2054
+
2055
+ # veredicto por ELEMENTO (5a pasada): solo cuentan las que CORREN (las
2056
+ # pausadas por CSS estan controladas); reduccion total, PARCIAL (unas
2057
+ # paran y otras siguen -- antes "respeta" con una viva) y sin datos
2058
+ _norm = {k: v for k, v in (normal.get('anims') or {}).items() if not v.get('paused')}
2059
+ _red = {k for k, v in (reduced.get('anims') or {}).items() if not v.get('paused')}
2060
+ _n, _r = len(_norm), len(_red)
2061
+ _stopped = [k for k in _norm if k not in _red]
2062
+ motion = {'normal': _n, 'reduced': _r, 'stopped': len(_stopped),
2063
+ 'partial': bool(_stopped) and _r > 0,
2064
+ 'paused_css': sum(1 for v in (normal.get('anims') or {}).values() if v.get('paused')),
2065
+ 'still_running': [_norm[k]['example'] for k in _norm if k in _red][:6]}
2066
+ respects = (True if (_n > 0 and _r == 0) else (False if _n > 0 else None))
1876
2067
  findings = []
1877
- if normal['anims'] > 0 and not respects:
2068
+ if _n > 0 and not respects:
1878
2069
  findings.append({
1879
2070
  'severity': 'medium', 'criterion': CRIT.get(lang, CRIT['es']).get('2.2.2', '2.2.2'),
1880
2071
  'signal': 'reduced_motion_ignored',
1881
- 'issue': _t_audit(lang, 'reduced_motion_ignored').format(
1882
- n=normal['anims'], nr=reduced['anims']),
2072
+ 'issue': _t_audit(lang, 'reduced_motion_ignored').format(n=_n, nr=_r),
1883
2073
  'remediation': _t_audit(lang, 'reduced_motion_ignored_rem'),
1884
- 'examples': normal['examples'][:4]})
2074
+ 'examples': (motion['still_running']
2075
+ or [v['example'] for v in _norm.values()])[:4]})
1885
2076
  order = {'high': 0, 'medium': 1, 'low': 2}
1886
2077
  findings.sort(key=lambda h: order[h['severity']])
1887
2078
  return {
1888
2079
  'mode': 'reduced-motion', 'url': url,
1889
- 'normal': normal, 'reduced': reduced,
2080
+ 'normal': {'anims': len(normal.get('anims') or {}),
2081
+ 'videos': normal.get('videos', 0)},
2082
+ 'reduced': {'anims': len(reduced.get('anims') or {}),
2083
+ 'videos': reduced.get('videos', 0)},
2084
+ 'motion': motion,
1890
2085
  'respects': respects,
1891
2086
  'score': compute_score(findings),
1892
2087
  'findings': findings,
@@ -1903,72 +2098,97 @@ def audit_dom_url(url, timeout=45, lang='en', auth_state=None, browser='auto', c
1903
2098
  :hover reales de los primeros controles marcados. auth_state: ruta a un
1904
2099
  storage_state de Playwright (cookies/localStorage exportados con la sesión
1905
2100
  iniciada) para auditar detrás de login."""
1906
- from playwright.sync_api import sync_playwright
1907
- with sync_playwright() as p:
1908
- nav = _get_browser(p, preferred=browser)
1909
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1910
- page = ctx.new_page() if auth_state else nav.new_page()
2101
+ nav = _get_browser(preferred=browser)
2102
+ page, close_page = _pooled_page(nav, auth_state)
2103
+ _resp = None
2104
+ page_url_final = None
2105
+ try:
1911
2106
  if color_scheme in ('dark', 'light'):
1912
2107
  # contraste por esquema: los temas oscuros fallan donde el claro
1913
2108
  # pasa — nadie audita ambos (axe tampoco)
1914
2109
  page.emulate_media(color_scheme=color_scheme)
1915
2110
  try:
1916
- page.goto(url, wait_until='load', timeout=timeout * 1000)
2111
+ _resp = page.goto(url, wait_until='load', timeout=timeout * 1000)
1917
2112
  page.wait_for_timeout(400)
1918
2113
  except Exception as e: # noqa: BLE001
1919
2114
  if not page.content() or page.url in ('about:blank', ''):
1920
- nav.close()
1921
2115
  return {'error': _LOAD_ERR.get(lang, _LOAD_ERR['en']).format(e=e)}
1922
- try:
1923
- data = page.evaluate(_JS, MAX_EXAMPLES)
1924
- # 1.4.12: inject the WCAG spacing overrides, count clipped texts
1925
- data['spacingClipped'] = page.evaluate(_JS_SPACING)
1926
- # 1.4.3 real: captura + muestreo píxel a píxel de las zonas sobre
1927
- # imagen/degradado que el contraste computado no puede calcular
1928
- # (main frame; los iframes quedan como conteo de "revisar")
1929
- measured = []
1930
- for z in (data.get('contrastZones') or [])[:8]:
1931
- try:
1932
- c = parse_color(z['fg'])
1933
- if not c:
1934
- continue
1935
- m = _samples_background(
1936
- page.locator(f'[data-a11ytxt="{z["i"]}"]'),
1937
- {'x': z.get('x', 0), 'y': z.get('y', 0),
1938
- 'width': z.get('w', 1400), 'height': z.get('h', 400)}, c)
1939
- if m:
1940
- measured.append({'example': z['example'], 'fg': z['fg'],
1941
- 'large': bool(z.get('large')),
1942
- 'measured': m})
1943
- except Exception: # noqa: BLE001
1944
- continue
1945
- data['contrastMeasured'] = measured
1946
- # iframes same-origin: mismo colector por frame
1947
- subframes = []
1948
- for fr in page.frames[1:5]:
1949
- try:
1950
- subframes.append(fr.evaluate(_JS, MAX_EXAMPLES))
1951
- except Exception: # noqa: BLE001
1952
- continue # cross-origin o no escaneable
1953
- data['iframes_data'] = subframes
1954
- # hover real sobre los controles marcados
1955
- hover = []
1956
- for i in range(min(10, int(data.get('marks', 0)))):
1957
- try:
1958
- page.hover(f'[data-a11yidx="{i}"]', timeout=1000)
1959
- r = page.evaluate(_JS_HOVER, i)
1960
- if r and r['ratio'] < 3:
1961
- hover.append(dict(r, example=f'hover #{i}'))
1962
- except Exception: # noqa: BLE001
2116
+ data = page.evaluate(_JS, MAX_EXAMPLES)
2117
+ # 1.4.12: inject the WCAG spacing overrides, count clipped texts
2118
+ data['spacingClipped'] = page.evaluate(_JS_SPACING)
2119
+ # 1.4.3 real: captura + muestreo píxel a píxel de las zonas sobre
2120
+ # imagen/degradado que el contraste computado no puede calcular
2121
+ # (main frame; los iframes quedan como conteo de "revisar")
2122
+ measured = []
2123
+ for z in (data.get('contrastZones') or [])[:8]:
2124
+ try:
2125
+ c = parse_color(z['fg'])
2126
+ if not c:
1963
2127
  continue
1964
- data['hover'] = hover
1965
- finally:
2128
+ m = _samples_background(
2129
+ page.locator(f'[data-a11ytxt="{z["i"]}"]'),
2130
+ {'x': z.get('x', 0), 'y': z.get('y', 0),
2131
+ 'width': z.get('w', 1400), 'height': z.get('h', 400)}, c)
2132
+ if m:
2133
+ measured.append({'example': z['example'], 'fg': z['fg'],
2134
+ 'large': bool(z.get('large')),
2135
+ 'measured': m})
2136
+ except Exception: # noqa: BLE001
2137
+ continue
2138
+ data['contrastMeasured'] = measured
2139
+ # iframes same-origin: mismo colector por frame
2140
+ subframes = []
2141
+ for fr in page.frames[1:5]:
1966
2142
  try:
1967
- ctx.close()
1968
- except Exception:
1969
- pass
2143
+ subframes.append(fr.evaluate(_JS, MAX_EXAMPLES))
2144
+ except Exception: # noqa: BLE001
2145
+ continue # cross-origin o no escaneable
2146
+ data['iframes_data'] = subframes
2147
+ # hover real sobre los controles marcados
2148
+ hover = []
2149
+ for i in range(min(10, int(data.get('marks', 0)))):
2150
+ try:
2151
+ page.hover(f'[data-a11yidx="{i}"]', timeout=1000)
2152
+ r = page.evaluate(_JS_HOVER, i)
2153
+ if r and r['ratio'] < 3:
2154
+ hover.append(dict(r, example=f'hover #{i}'))
2155
+ except Exception: # noqa: BLE001
2156
+ continue
2157
+ data['hover'] = hover
2158
+ page_url_final = page.url
2159
+ finally:
2160
+ close_page()
1970
2161
  _merge_iframes(data)
1971
- return audit_dom(data, url, lang=lang, color_scheme=color_scheme)
2162
+ # (7ª pasada) el informe ES de la página final: url=/signin cuando
2163
+ # /account redirigió — antes conservaba /account y solo añadía la nota
2164
+ final_url = (page_url_final or url).split('#')[0]
2165
+ report_out = audit_dom(data, final_url, lang=lang, color_scheme=color_scheme)
2166
+ try:
2167
+ _st = _resp.status if _resp is not None else None
2168
+ except Exception: # noqa: BLE001 — respuesta ya consumida
2169
+ _st = None
2170
+ if final_url != url.split('#')[0]:
2171
+ report_out['requested_url'] = url
2172
+ report_out['redirect_note'] = (
2173
+ 'la URL pedida redirigió: el informe es de la página FINAL'
2174
+ if lang == 'es' else
2175
+ 'the requested URL redirected: this report is for the FINAL page')
2176
+ if _st:
2177
+ report_out['http_status'] = _st
2178
+ if _st >= 400:
2179
+ # (7ª pasada) el falso verde HTTP: la nota informaba pero budget,
2180
+ # evidencia y CI seguían aceptando el resultado. Error explícito
2181
+ # machine-readable — las capas de arriba lo rechazan por contrato
2182
+ report_out['error'] = (
2183
+ f'HTTP {_st}: this is an error response, not the requested '
2184
+ 'page — the content was still audited and is in this report, '
2185
+ 'but no gate should pass on it'
2186
+ if lang == 'en' else
2187
+ f'HTTP {_st}: respuesta de error, no la página pedida — el '
2188
+ 'contenido se auditó igualmente y va en este informe, pero '
2189
+ 'ningún gate debe pasar con esto')
2190
+ report_out['http_error_note'] = report_out['error']
2191
+ return report_out
1972
2192
 
1973
2193
 
1974
2194
  def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45,
@@ -1982,58 +2202,52 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
1982
2202
  Para text_ sobre imágenes, degradados, vídeo o cualquier fondo que el
1983
2203
  cálculo CSS no puede resolver. Requiere Playwright.
1984
2204
  """
1985
- from playwright.sync_api import sync_playwright
1986
2205
  from .contrast import T as _TC
1987
2206
  t9 = _TC.get(lang, _TC['es'])
1988
- with sync_playwright() as p:
1989
- nav = _get_browser(p, preferred=browser)
1990
- ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
1991
- page = ctx.new_page() if auth_state else nav.new_page()
2207
+ nav = _get_browser(preferred=browser)
2208
+ page, close_page = _pooled_page(nav, auth_state)
2209
+ try:
2210
+ page.goto(url, wait_until='load', timeout=timeout * 1000)
2211
+ page.wait_for_timeout(300)
2212
+ loc = page.locator(selector).first
1992
2213
  try:
1993
- page.goto(url, wait_until='load', timeout=timeout * 1000)
1994
- page.wait_for_timeout(300)
1995
- loc = page.locator(selector).first
1996
- try:
1997
- loc.wait_for(timeout=timeout * 1000)
1998
- except Exception: # noqa: BLE001
1999
- return {'error': t9['selector_missing'].format(s=selector)}
2000
- if text_color:
2001
- c = parse_color(text_color)
2002
- if not c:
2003
- return {'error': t9['invalid_color']}
2004
- else:
2005
- comp = loc.evaluate('el => getComputedStyle(el).color')
2006
- c = parse_color(comp)
2007
- if not c:
2008
- return {'error': f"{t9['invalid_color']} (computed: {comp})"}
2009
- if c.get('a', 1) < 1:
2010
- return {'error': t9['opaque_text']}
2011
- try:
2012
- box = loc.bounding_box()
2013
- if not box or box['width'] < 3 or box['height'] < 3:
2014
- return {'error': t9['no_box'].format(s=selector)}
2015
- m = _samples_background(loc, box, c)
2016
- except Exception: # noqa: BLE001
2214
+ loc.wait_for(timeout=timeout * 1000)
2215
+ except Exception: # noqa: BLE001
2216
+ return {'error': t9['selector_missing'].format(s=selector)}
2217
+ if text_color:
2218
+ c = parse_color(text_color)
2219
+ if not c:
2220
+ return {'error': t9['invalid_color']}
2221
+ else:
2222
+ comp = loc.evaluate('el => getComputedStyle(el).color')
2223
+ c = parse_color(comp)
2224
+ if not c:
2225
+ return {'error': f"{t9['invalid_color']} (computed: {comp})"}
2226
+ if c.get('a', 1) < 1:
2227
+ return {'error': t9['opaque_text']}
2228
+ try:
2229
+ box = loc.bounding_box()
2230
+ if not box or box['width'] < 3 or box['height'] < 3:
2017
2231
  return {'error': t9['no_box'].format(s=selector)}
2018
- if not m:
2019
- return {'error': t9['no_pixels']}
2020
- out = {'url': url, 'selector': selector, 'text_color': hexs(c),
2021
- 'image': f'{selector} ({round(box["width"])}×{round(box["height"])})',
2022
- 'worst_ratio': m['worst_ratio'],
2023
- 'median_ratio': m['median_ratio'],
2024
- 'p95_ratio': m['p95_ratio'],
2025
- 'area_passes_aa_normal_text_4_5': m['area_passes_aa_normal_text_4_5'],
2026
- 'area_passes_aa_min_3_0': m['area_passes_aa_min_3_0'],
2027
- 'sampled_pixels': m['sampled_pixels'],
2028
- 'interpretation': t9['interp']}
2029
- if 'worst_zone' in m:
2030
- out['worst_zone'] = m['worst_zone']
2031
- return out
2032
- finally:
2033
- try:
2034
- ctx.close()
2035
- except Exception: # noqa: BLE001
2036
- pass
2232
+ m = _samples_background(loc, box, c)
2233
+ except Exception: # noqa: BLE001
2234
+ return {'error': t9['no_box'].format(s=selector)}
2235
+ if not m:
2236
+ return {'error': t9['no_pixels']}
2237
+ out = {'url': url, 'selector': selector, 'text_color': hexs(c),
2238
+ 'image': f'{selector} ({round(box["width"])}×{round(box["height"])})',
2239
+ 'worst_ratio': m['worst_ratio'],
2240
+ 'median_ratio': m['median_ratio'],
2241
+ 'p95_ratio': m['p95_ratio'],
2242
+ 'area_passes_aa_normal_text_4_5': m['area_passes_aa_normal_text_4_5'],
2243
+ 'area_passes_aa_min_3_0': m['area_passes_aa_min_3_0'],
2244
+ 'sampled_pixels': m['sampled_pixels'],
2245
+ 'interpretation': t9['interp']}
2246
+ if 'worst_zone' in m:
2247
+ out['worst_zone'] = m['worst_zone']
2248
+ return out
2249
+ finally:
2250
+ close_page()
2037
2251
 
2038
2252
 
2039
2253
  # --- contrast walk: perceptual pass over EVERY rendered text element --------
@@ -2041,7 +2255,13 @@ def contrast_dom(url, selector, text_color=None, sample=4, lang='en', timeout=45
2041
2255
  _JS_WALK = r'''(maxEls) => {
2042
2256
  const visible = el => !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
2043
2257
  const directText = el => [...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim());
2044
- const parseC = s => { const m = String(s).match(/rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\)/);
2258
+ const parseC = s => { const m3 = /color\(\s*srgb\s+([^)]+)\)/.exec(String(s));
2259
+ if (m3) { const ps = m3[1].split('/'); const rgb = ps[0].trim().split(/\s+/);
2260
+ const cv = v => v.endsWith('%') ? parseFloat(v) * 2.55 : parseFloat(v) * 255;
2261
+ const al = ps.length > 1 ? (ps[1].trim().endsWith('%') ? parseFloat(ps[1]) / 100 : parseFloat(ps[1])) : 1;
2262
+ if (rgb.length >= 3 && isFinite(cv(rgb[0])) && isFinite(cv(rgb[1])) && isFinite(cv(rgb[2])) && isFinite(al))
2263
+ return {r: Math.round(cv(rgb[0])), g: Math.round(cv(rgb[1])), b: Math.round(cv(rgb[2])), a: al}; }
2264
+ const m = String(s).match(/rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\)/);
2045
2265
  return m ? {r:+m[1], g:+m[2], b:+m[3], a: m[4] === undefined ? 1 : +m[4]} : null; };
2046
2266
  const effBg = el => {
2047
2267
  const layers = [];
@@ -2081,7 +2301,7 @@ _JS_WALK = r'''(maxEls) => {
2081
2301
  if (!visible(el) || !directText(el)) continue;
2082
2302
  const cs = getComputedStyle(el);
2083
2303
  const color = parseC(cs.color);
2084
- if (!color) continue;
2304
+ if (!color) { out.push({skip: 'unparsed-color', path: path(el)}); continue; }
2085
2305
  if (color.a < 1) { out.push({skip: 'translucent', path: path(el)}); continue; }
2086
2306
  const fs = parseFloat(cs.fontSize) || 16;
2087
2307
  const fw = parseInt(cs.fontWeight) || 400;
@@ -2114,21 +2334,28 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2114
2334
  Filtro honesto, no veredicto: text_ en shadow DOM, canvas, vídeo y
2115
2335
  pseudo-elementos no se captura; lo no medido se declara, jamás inventado.
2116
2336
  """
2117
- from playwright.sync_api import sync_playwright
2118
2337
  from .contrast import ratio as _ratio, suggest as _suggest, parse_color
2119
2338
 
2120
2339
  def _verdicts(entries):
2121
2340
  for e in entries:
2122
2341
  if e['ratio'] is not None:
2123
- e['verdict'] = 'pass' if e['ratio'] >= e['threshold'] else 'fail'
2342
+ exact = e.pop('_exact', None)
2343
+ value = exact if exact is not None else e['ratio']
2344
+ e['verdict'] = 'pass' if value >= e['threshold'] else 'fail'
2345
+ if exact is not None and (value >= e['threshold']) != \
2346
+ (e['ratio'] >= e['threshold']):
2347
+ e['ratio_exact'] = round(exact, 6) # el redondeo maquilla: declararlo
2124
2348
 
2125
2349
  def _pass(page):
2126
2350
  raw = page.evaluate(_JS_WALK, max_walk)
2127
- entries, shot_jobs, skipped = [], [], 0
2351
+ entries, shot_jobs, skipped, unparsed = [], [], 0, 0
2128
2352
  for row in raw:
2129
2353
  if row.get('skip') == 'translucent':
2130
2354
  skipped += 1
2131
2355
  continue
2356
+ if row.get('skip') == 'unparsed-color':
2357
+ unparsed += 1
2358
+ continue
2132
2359
  fg = {k: row['color'][k] for k in ('r', 'g', 'b')}
2133
2360
  bg = {k: row['bg'][k] for k in ('r', 'g', 'b')}
2134
2361
  large = row['font_px'] >= 24 or (row['font_px'] >= 18.66 and row['bold'])
@@ -2142,7 +2369,12 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2142
2369
  if row['bg_image']:
2143
2370
  shot_jobs.append((entry, fg))
2144
2371
  else:
2145
- entry['ratio'] = round(_ratio(fg, bg), 2)
2372
+ # umbral sobre el valor EXACTO (revisión externa, 3ª pasada:
2373
+ # 4,4999346 redondeado a 4,50 pasaba por válido); el redondeo
2374
+ # es presentación — _exact viaja interno hasta el veredicto
2375
+ r_exact = _ratio(fg, bg)
2376
+ entry['ratio'] = round(r_exact, 2)
2377
+ entry['_exact'] = r_exact
2146
2378
  entries.append(entry)
2147
2379
  sampled = 0
2148
2380
  for entry, fg in shot_jobs:
@@ -2162,9 +2394,9 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2162
2394
  except Exception: # noqa: BLE001 — one dead locator must not kill the walk
2163
2395
  continue
2164
2396
  _verdicts(entries)
2165
- return entries, skipped
2397
+ return entries, skipped, unparsed
2166
2398
 
2167
- def _summarize(entries, skipped):
2399
+ def _summarize(entries, skipped, unparsed_n=0):
2168
2400
  fails = [e for e in entries if e['verdict'] == 'fail']
2169
2401
  worst = min((e for e in entries if e['ratio'] is not None),
2170
2402
  key=lambda e: e['ratio'], default=None)
@@ -2174,71 +2406,70 @@ def contrast_walk(url, max_walk=400, max_sample=24, dark=False,
2174
2406
  'fails_4_5_normal_text': sum(1 for e in fails if e['threshold'] >= 4.5),
2175
2407
  'fails_3_0_large_text': sum(1 for e in fails if e['threshold'] < 4.5),
2176
2408
  'translucent_text_skipped': skipped,
2409
+ 'unparsed_colors': unparsed_n,
2177
2410
  'pixel_sampled': sum(1 for e in entries if e['pixel_sampled']),
2178
2411
  'worst_ratio': worst['ratio'] if worst else None,
2179
2412
  'worst_element': worst['path'] if worst else None}
2180
2413
 
2181
- with sync_playwright() as p:
2182
- def _run(scheme):
2183
- nav = _get_browser(p, preferred=browser)
2184
- ctx = (nav.new_context(storage_state=auth_state, color_scheme=scheme)
2185
- if auth_state else nav.new_context(color_scheme=scheme))
2186
- page = ctx.new_page()
2414
+ def _run(scheme):
2415
+ nav = _get_browser(preferred=browser)
2416
+ ctx = (nav.new_context(storage_state=auth_state, color_scheme=scheme)
2417
+ if auth_state else nav.new_context(color_scheme=scheme))
2418
+ page = ctx.new_page()
2419
+ try:
2420
+ page.goto(url, wait_until='load', timeout=timeout * 1000)
2421
+ page.wait_for_timeout(300)
2422
+ return _pass(page)
2423
+ finally:
2187
2424
  try:
2188
- page.goto(url, wait_until='load', timeout=timeout * 1000)
2189
- page.wait_for_timeout(300)
2190
- return _pass(page)
2191
- finally:
2192
- try:
2193
- ctx.close()
2194
- nav.close()
2195
- except Exception: # noqa: BLE001
2196
- pass
2197
-
2198
- entries, skipped = _run('light')
2199
- report = {'mode': 'contrast-walk', 'url': url, 'scheme': 'light',
2200
- 'checked': len(entries),
2201
- 'elements': entries,
2202
- 'summary': _summarize(entries, skipped)}
2203
-
2204
- # suggestions for the worst flat-background fails (pixel zones have no
2205
- # single background to suggest against — honest skip)
2206
- fails = sorted((e for e in entries if e['verdict'] == 'fail' and not e['bg_image']),
2207
- key=lambda e: e['ratio'])
2208
- for e in fails[:8]:
2209
- s = _suggest(parse_color(e['color']), parse_color(e['bg']),
2210
- target=e['threshold'], lang=lang)
2211
- if s:
2212
- e['suggestion'] = s
2213
-
2214
- if dark:
2215
- entries_d, skipped_d = _run('dark')
2216
- report['dark'] = {'scheme': 'dark', 'checked': len(entries_d),
2217
- 'elements': entries_d,
2218
- 'summary': _summarize(entries_d, skipped_d)}
2219
- light_fails = {e['path'] for e in entries if e['verdict'] == 'fail'}
2220
- dark_fails = {e['path'] for e in entries_d if e['verdict'] == 'fail'}
2221
- report['dark_delta'] = {
2222
- 'new_fails': sorted(dark_fails - light_fails)[:20],
2223
- 'resolved': sorted(light_fails - dark_fails)[:20],
2224
- 'note': ('a site that ignores prefers-color-scheme shows a zero '
2225
- 'delta: same colors in both passes')}
2226
-
2227
- report['limits'] = (
2228
- 'Computed ratios cover effective background-color with alpha '
2229
- 'compositing; text over images/gradients is pixel-sampled '
2230
- '(worst-case) up to the cap, the rest is declared unmeasured. Text '
2231
- 'in shadow DOM, canvas, video and pseudo-elements is not captured. '
2232
- 'A fail is a filter finding (1.4.3), not a verdict — judge the '
2233
- 'zone with contrast-dom.'
2234
- if lang == 'en' else
2235
- 'Los ratios computados cubren background-color efectivo con '
2236
- 'composición alfa; el text_ sobre imágenes/gradientes se muestrea '
2237
- 'por píxeles (peor caso) hasta el tope y el resto se declara sin '
2238
- 'medir. El text_ en shadow DOM, canvas, vídeo y pseudo-elementos '
2239
- 'no se captura. Un fallo es un hallazgo de filtro (1.4.3), no un '
2240
- 'veredicto — juzga la zona con contrast-dom.')
2241
- return report
2425
+ ctx.close()
2426
+ except Exception: # noqa: BLE001
2427
+ pass
2428
+
2429
+ entries, skipped, unparsed = _run('light')
2430
+ report = {'mode': 'contrast-walk', 'url': url, 'scheme': 'light',
2431
+ 'checked': len(entries),
2432
+ 'elements': entries,
2433
+ 'summary': _summarize(entries, skipped, unparsed)}
2434
+
2435
+ # suggestions for the worst flat-background fails (pixel zones have no
2436
+ # single background to suggest against — honest skip)
2437
+ fails = sorted((e for e in entries if e['verdict'] == 'fail' and not e['bg_image']),
2438
+ key=lambda e: e['ratio'])
2439
+ for e in fails[:8]:
2440
+ s = _suggest(parse_color(e['color']), parse_color(e['bg']),
2441
+ target=e['threshold'], lang=lang)
2442
+ if s:
2443
+ e['suggestion'] = s
2444
+
2445
+ if dark:
2446
+ entries_d, skipped_d, _unp_d = _run('dark')
2447
+ report['dark'] = {'scheme': 'dark', 'checked': len(entries_d),
2448
+ 'elements': entries_d,
2449
+ 'summary': _summarize(entries_d, skipped_d, _unp_d)}
2450
+ light_fails = {e['path'] for e in entries if e['verdict'] == 'fail'}
2451
+ dark_fails = {e['path'] for e in entries_d if e['verdict'] == 'fail'}
2452
+ report['dark_delta'] = {
2453
+ 'new_fails': sorted(dark_fails - light_fails)[:20],
2454
+ 'resolved': sorted(light_fails - dark_fails)[:20],
2455
+ 'note': ('a site that ignores prefers-color-scheme shows a zero '
2456
+ 'delta: same colors in both passes')}
2457
+
2458
+ report['limits'] = (
2459
+ 'Computed ratios cover effective background-color with alpha '
2460
+ 'compositing; text over images/gradients is pixel-sampled '
2461
+ '(worst-case) up to the cap, the rest is declared unmeasured. Text '
2462
+ 'in shadow DOM, canvas, video and pseudo-elements is not captured. '
2463
+ 'A fail is a filter finding (1.4.3), not a verdict — judge the '
2464
+ 'zone with contrast-dom.'
2465
+ if lang == 'en' else
2466
+ 'Los ratios computados cubren background-color efectivo con '
2467
+ 'composición alfa; el text_ sobre imágenes/gradientes se muestrea '
2468
+ 'por píxeles (peor caso) hasta el tope y el resto se declara sin '
2469
+ 'medir. El text_ en shadow DOM, canvas, vídeo y pseudo-elementos '
2470
+ 'no se captura. Un fallo es un hallazgo de filtro (1.4.3), no un '
2471
+ 'veredicto — juzga la zona con contrast-dom.')
2472
+ return report
2242
2473
 
2243
2474
 
2244
2475
  def contrast_dom_main(argv):
@@ -2290,7 +2521,7 @@ def main(argv):
2290
2521
  print(json.dumps({'error': str(e)}))
2291
2522
  return 1
2292
2523
  print(json.dumps(res, ensure_ascii=False, indent=1))
2293
- return 0
2524
+ return 1 if isinstance(res, dict) and 'error' in res else 0
2294
2525
 
2295
2526
 
2296
2527
  def reflow_main(argv):
@@ -2298,14 +2529,17 @@ def reflow_main(argv):
2298
2529
  ap.add_argument('url')
2299
2530
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
2300
2531
  ap.add_argument('--timeout', type=int, default=45)
2532
+ ap.add_argument('--auth-state', dest='auth_state',
2533
+ help='Path to a Playwright storage_state JSON to audit behind login')
2301
2534
  a = ap.parse_args(argv)
2302
2535
  try:
2303
- res = audit_reflow(a.url, timeout=a.timeout, lang=a.lang)
2536
+ res = audit_reflow(a.url, timeout=a.timeout, lang=a.lang,
2537
+ auth_state=a.auth_state)
2304
2538
  except ImportError:
2305
2539
  print(json.dumps({'error': 'Playwright not installed'}))
2306
2540
  return 1
2307
2541
  print(json.dumps(res, ensure_ascii=False, indent=1))
2308
- return 0
2542
+ return 1 if isinstance(res, dict) and 'error' in res else 0
2309
2543
 
2310
2544
 
2311
2545
  def forms_main(argv):
@@ -2320,7 +2554,7 @@ def forms_main(argv):
2320
2554
  print(json.dumps({'error': 'Playwright not installed'}))
2321
2555
  return 1
2322
2556
  print(json.dumps(res, ensure_ascii=False, indent=1))
2323
- return 0
2557
+ return 1 if isinstance(res, dict) and 'error' in res else 0
2324
2558
 
2325
2559
 
2326
2560
  def kbd_main(argv):
@@ -2335,7 +2569,7 @@ def kbd_main(argv):
2335
2569
  print(json.dumps({'error': 'Playwright not installed'}))
2336
2570
  return 1
2337
2571
  print(json.dumps(res, ensure_ascii=False, indent=1))
2338
- return 0
2572
+ return 1 if isinstance(res, dict) and 'error' in res else 0
2339
2573
 
2340
2574
 
2341
2575
  def hover_main(argv):
@@ -2354,7 +2588,7 @@ def hover_main(argv):
2354
2588
  print(json.dumps({'error': 'Playwright not installed'}))
2355
2589
  return 1
2356
2590
  print(json.dumps(res, ensure_ascii=False, indent=1))
2357
- return 0
2591
+ return 1 if isinstance(res, dict) and 'error' in res else 0
2358
2592
 
2359
2593
 
2360
2594
  if __name__ == '__main__':