@kinti/a11y-toolkit 5.26.0 → 5.28.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.
Files changed (45) hide show
  1. package/README.md +1 -1
  2. package/a11y_toolkit/a11y.py +30 -4
  3. package/a11y_toolkit/a11yact.py +9 -1
  4. package/a11y_toolkit/a11yannotate.py +185 -0
  5. package/a11y_toolkit/a11yaudit.py +924 -196
  6. package/a11y_toolkit/a11ybadge.py +24 -17
  7. package/a11y_toolkit/a11ybudget.py +145 -1
  8. package/a11y_toolkit/a11ycorpus.py +58 -24
  9. package/a11y_toolkit/a11ycrit.py +114 -53
  10. package/a11y_toolkit/a11ydiff.py +104 -34
  11. package/a11y_toolkit/a11ydisprove.py +15 -8
  12. package/a11y_toolkit/a11ydocx.py +8 -6
  13. package/a11y_toolkit/a11ydom.py +567 -97
  14. package/a11y_toolkit/a11yen301549.py +53 -1
  15. package/a11y_toolkit/a11yengines.py +157 -0
  16. package/a11y_toolkit/a11yevidence.py +81 -33
  17. package/a11y_toolkit/a11yfix.py +131 -52
  18. package/a11y_toolkit/a11ygate.py +225 -0
  19. package/a11y_toolkit/a11yinit.py +73 -7
  20. package/a11y_toolkit/a11yjourney.py +110 -4
  21. package/a11y_toolkit/a11yledger.py +119 -12
  22. package/a11y_toolkit/a11ylocate.py +247 -0
  23. package/a11y_toolkit/a11yopenacr.py +10 -3
  24. package/a11y_toolkit/a11ypatches.py +154 -0
  25. package/a11y_toolkit/a11ypatterns.py +344 -0
  26. package/a11y_toolkit/a11ypdf.py +109 -53
  27. package/a11y_toolkit/a11yrgaa.py +60 -0
  28. package/a11y_toolkit/a11yroute.py +34 -12
  29. package/a11y_toolkit/a11ysarif.py +45 -18
  30. package/a11y_toolkit/a11yscope.py +67 -15
  31. package/a11y_toolkit/a11yscroll.py +7 -5
  32. package/a11y_toolkit/a11ystatement.py +30 -6
  33. package/a11y_toolkit/a11ytrace.py +293 -0
  34. package/a11y_toolkit/a11yvalidate.py +21 -15
  35. package/a11y_toolkit/a11yvpat.py +34 -7
  36. package/a11y_toolkit/a11yvtt.py +22 -6
  37. package/a11y_toolkit/a11ywiz.py +121 -0
  38. package/a11y_toolkit/contrast.py +62 -24
  39. package/a11y_toolkit/locales/en.json +185 -20
  40. package/a11y_toolkit/locales/es.json +186 -21
  41. package/a11y_toolkit/rgaa.json +2661 -0
  42. package/a11y_toolkit/server.py +157 -54
  43. package/package.json +2 -2
  44. package/a11y_toolkit/a11yplan.py +0 -214
  45. package/a11y_toolkit/a11ywcagem.py +0 -237
@@ -78,13 +78,15 @@ 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):
81
+ def audit_scroll(url, max_batches=5, lang='en', timeout=45, auth_state=None, browser='auto'):
82
82
  from playwright.sync_api import sync_playwright
83
+ from .a11ydom import _get_browser
83
84
  with sync_playwright() as p:
84
- nav = p.chromium.launch()
85
+ nav = _get_browser(p, preferred=browser)
85
86
  ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
86
- page = ctx.new_page(viewport={'width': 1280, 'height': 800}) if auth_state \
87
- else nav.new_page(viewport={'width': 1280, 'height': 800})
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}))
88
90
  try:
89
91
  page.goto(url, wait_until='load', timeout=timeout * 1000)
90
92
  page.wait_for_timeout(500)
@@ -205,7 +207,7 @@ def main(argv):
205
207
  print(json.dumps({'error': 'Playwright not installed'}))
206
208
  return 1
207
209
  print(json.dumps(res, ensure_ascii=False, indent=1))
208
- return 0
210
+ return 1 if 'error' in res else 0
209
211
 
210
212
 
211
213
  if __name__ == '__main__':
@@ -13,6 +13,11 @@ Usage:
13
13
  declaracion.py --entity "Name" --url "https://…" --status partial \
14
14
  --inaccessible "…" --feedback "a@b.gal" [--framework rd1112|eaa] \
15
15
  [--lang es|en] [--output decl.html]
16
+
17
+ FROZEN LAYER (2026-11-04, founder decision "freeze the docs"): this
18
+ module stays public as an HONEST DRAFT generator (the machine fills
19
+ Remarks/texts, never the claim). Maintenance fixes only; new
20
+ capabilities live in the SaaS (a11y.es / Lince).
16
21
  """
17
22
 
18
23
  import argparse
@@ -50,9 +55,11 @@ def generate(entity, url, status, inaccessible_content=None, method=None,
50
55
  return {'error': t['error_inconsistent']}
51
56
 
52
57
  e = lambda s: html.escape(str(s), quote=True) # noqa: E731
58
+ today = TODAY() # una sola lectura del reloj: una ejecución que cruce la
59
+ # medianoche no puede fechar cuerpo y resumen con días distintos
53
60
  status_title, status_text = STATES.get(lang, STATES['es'])[status]
54
- evaluation_date = evaluation_date or TODAY()
55
- review_date = review_date or TODAY()
61
+ evaluation_date = evaluation_date or today
62
+ review_date = review_date or today
56
63
  method = method or t['method_default']
57
64
  feedback = feedback or t['feedback_default']
58
65
 
@@ -75,6 +82,23 @@ def generate(entity, url, status, inaccessible_content=None, method=None,
75
82
  <h2>{t['h_alt_access']}</h2>
76
83
  <p>{e(alternative_format)}</p>'''
77
84
 
85
+ # RD 1112/2018 art. 10.1(b): el procedimiento de reclamación se ENLAZA,
86
+ # no queda en texto inerte — un valor http(s) se renderiza como <a>
87
+ # (escapado); el texto que no es URL se queda plano (también escapado).
88
+ # El canal de feedback recibe el MISMO trato (es un canal de contacto)
89
+ feedback_html = ''
90
+ if feedback:
91
+ esc_f = e(feedback)
92
+ feedback_html = (f'<a href="{esc_f}">{esc_f}</a>'
93
+ if str(feedback).lower().startswith(('http://', 'https://'))
94
+ else esc_f)
95
+ complaints_html = ''
96
+ if complaints:
97
+ esc_c = e(complaints)
98
+ complaints_html = (f'<a href="{esc_c}">{esc_c}</a>'
99
+ if str(complaints).lower().startswith(('http://', 'https://'))
100
+ else esc_c)
101
+
78
102
  doc_title = t['title'][framework]
79
103
  doc = f'''<!doctype html>
80
104
  <html lang="{html.escape(str(lang), quote=True)}">
@@ -97,14 +121,14 @@ def generate(entity, url, status, inaccessible_content=None, method=None,
97
121
  <h2>{t['h_preparation']}</h2>
98
122
  <ul>
99
123
  <li>{t['l_evaluation']}: <time datetime="{e(evaluation_date)}">{e(evaluation_date)}</time></li>
100
- <li>{t['l_declared']} <time datetime="{e(TODAY())}">{e(TODAY())}</time></li>
124
+ <li>{t['l_declared']} <time datetime="{e(today)}">{e(today)}</time></li>
101
125
  <li>{t['l_method']}: {e(method)}</li>
102
126
  <li>{t['l_review']}: <time datetime="{e(review_date)}">{e(review_date)}</time></li>
103
127
  </ul>
104
128
 
105
129
  <h2>{t['h_contact']}</h2>
106
- <p>{t['contact'].format(f=e(feedback))}</p>
107
- <p>{e(complaints) if complaints else t['complaints'][framework]}</p>
130
+ <p>{t['contact'].format(f=feedback_html)}</p>
131
+ <p>{complaints_html if complaints else t['complaints'][framework]}</p>
108
132
  {disalt}
109
133
  </main>
110
134
  </body>
@@ -116,7 +140,7 @@ def generate(entity, url, status, inaccessible_content=None, method=None,
116
140
  'entity': entity, 'url': url, 'framework': framework, 'lang': lang,
117
141
  'status': status_title,
118
142
  'inaccessible_items': len(inaccessible_content),
119
- 'dates': {'evaluation': evaluation_date, 'declaration': TODAY(),
143
+ 'dates': {'evaluation': evaluation_date, 'declaration': today,
120
144
  'review': review_date},
121
145
  },
122
146
  }
@@ -0,0 +1,293 @@
1
+ #!/usr/bin/env python3
2
+ """a11y_trace — the behavioral trace: what a keyboard user LIVES, step by step.
3
+
4
+ The deterministic core of the journey-replay idea family (replayable journeys,
5
+ screen-reader release gates, behavioral debugging): one walk of the page
6
+ recording, PER TAB STEP, the focused element's stable signature (the same
7
+ key doctrine as the snapshot), the aria-live announcements the step
8
+ triggered, and the url — plus the accessibility tree at the end.
9
+ `trace diff` compares two traces: FOCUS BEHAVIOR IS THE GATE (a forked or
10
+ lost tab sequence blocks, exit 2); announcements are reported, not gated
11
+ (content changes legitimately between builds — a collapsed announcement
12
+ layer is flagged informationally).
13
+
14
+ Honesty: this captures the accessibility-tree / live-region layer — what a
15
+ screen reader would have AVAILABLE, not the synthesized speech of NVDA/JAWS
16
+ (real AT is a different beast; the agent-side complement is
17
+ a11y_journey_verdict). The collector is SILENT (no panel injected): a trace
18
+ must not mutate the page it measures.
19
+
20
+ CLI (infrastructure, not a tool — D17, like corpus/mutants/engines):
21
+ a11ytrace.py https://web [--steps 25] [-o trace.json] # needs Playwright
22
+ a11ytrace.py https://web --script journey.json -o t.json # scripted real journey
23
+ a11ytrace.py diff before.json after.json # exit 0 ok / 2 divergences
24
+
25
+ Script file: a JSON list of actions — {"kind":"click","selector":"#pay"},
26
+ {"kind":"fill","selector":"#email","value":"…"}, {"kind":"select",…},
27
+ {"kind":"press","key":"Enter"}, {"kind":"wait","ms":300}, {"kind":"goto","url":…}.
28
+ """
29
+
30
+ import argparse
31
+ import json
32
+ import sys
33
+ from datetime import datetime, timezone
34
+
35
+ from . import a11ydiff
36
+
37
+ # Silent live-region collector: accumulates announcements and exposes a
38
+ # drain() so each trace step reads EXACTLY the announcements it triggered.
39
+ # Same selector set as the arialive monitor, but no DOM panel — the trace
40
+ # must not mutate the page it measures.
41
+ _COLLECTOR = r'''() => {
42
+ if (window.__a11yTraceDrain) return window.__a11yTraceDrain();
43
+ const SEL = '[aria-live],[role=alert],[role=status],[role=log],[role=marquee],[role=timer]';
44
+ const seen = new WeakSet(); const log = [];
45
+ const politeness = el => el.getAttribute('aria-live') ||
46
+ ({ alert: 'assertive', status: 'polite', log: 'polite',
47
+ marquee: 'off', timer: 'off' })[el.getAttribute('role')] || 'polite';
48
+ const target = el => el.id ? '#' + el.id
49
+ : (el.className && typeof el.className === 'string'
50
+ ? el.tagName.toLowerCase() + '.' + el.className.trim().split(/\s+/).slice(0, 2).join('.')
51
+ : el.tagName.toLowerCase());
52
+ const push = (el, reason) => {
53
+ if (log.length >= 500) return;
54
+ log.push({ politeness: politeness(el),
55
+ role: el.getAttribute('role') || 'aria-live',
56
+ target: target(el),
57
+ text: ((el.innerText || el.textContent || '').trim()
58
+ .replace(/\s+/g, ' ')).slice(0, 220),
59
+ reason: reason || 'update' });
60
+ };
61
+ const watch = el => {
62
+ if (!el || el.nodeType !== 1 || seen.has(el)) return;
63
+ if (!el.matches || !el.matches(SEL)) return;
64
+ seen.add(el);
65
+ if (el.getAttribute('role') === 'alert') push(el, 'inserted');
66
+ new MutationObserver(() => push(el))
67
+ .observe(el, { childList: true, characterData: true, subtree: true });
68
+ };
69
+ document.querySelectorAll(SEL).forEach(watch);
70
+ new MutationObserver(muts => muts.forEach(m => m.addedNodes.forEach(n => {
71
+ if (n.nodeType !== 1) return;
72
+ watch(n);
73
+ if (n.querySelectorAll) n.querySelectorAll(SEL).forEach(watch);
74
+ }))).observe(document.body, { childList: true, subtree: true });
75
+ window.__a11yTraceDrain = () => log.splice(0);
76
+ return [];
77
+ }'''
78
+
79
+ # Drenaje defensivo: un `goto` destruye window.__a11yTraceDrain (navegación =
80
+ # contexto nuevo); pedirlo sin guardia tronaría el paso entero. La expresión
81
+ # es estática (nada del page entra aquí) y devuelve [] cuando el recolector
82
+ # aún no existe — el paso se graba, simplemente sin anuncios de ese instante.
83
+ _DRAIN = '() => window.__a11yTraceDrain ? window.__a11yTraceDrain() : []'
84
+
85
+
86
+ def _run_script_action(page, act):
87
+ """One scripted action → (label, ok). Selector-valued actions target CSS."""
88
+ kind = act.get('kind', '')
89
+ sel = act.get('selector') or act.get('target') or ''
90
+ if kind == 'click':
91
+ loc = page.locator(sel).first
92
+ loc.click(timeout=5000)
93
+ return f'click:{sel}', True
94
+ if kind == 'fill':
95
+ page.locator(sel).first.fill(str(act.get('value', '')), timeout=5000)
96
+ return f'fill:{sel}', True
97
+ if kind == 'select':
98
+ page.locator(sel).first.select_option(str(act.get('value', '')), timeout=5000)
99
+ return f'select:{sel}', True
100
+ if kind == 'press':
101
+ page.keyboard.press(act.get('key', 'Enter'))
102
+ return f'press:{act.get("key", "Enter")}', True
103
+ if kind == 'wait':
104
+ page.wait_for_timeout(int(act.get('ms', 300)))
105
+ return f'wait:{act.get("ms", 300)}', True
106
+ if kind == 'goto':
107
+ page.goto(act.get('url', ''), wait_until='load', timeout=30000)
108
+ # la navegación destruye el recolector (contexto nuevo): re-inyectarlo
109
+ # o el drain de ESTE paso y de los siguientes tronaría/volvería vacío
110
+ page.evaluate(_COLLECTOR)
111
+ return f'goto:{act.get("url", "")}', True
112
+ return f'unknown:{kind or sel}', False
113
+
114
+
115
+ def _run_script(page, script):
116
+ """Scripted actions → (walk, navigations). Factored out of trace() so the
117
+ loop is testable against a fake page (no Playwright needed)."""
118
+ walk = []
119
+ navigations = 0
120
+ url_now = page.url
121
+ for i, act in enumerate(script):
122
+ if not isinstance(act, dict):
123
+ continue
124
+ try:
125
+ label, _ok = _run_script_action(page, act)
126
+ except Exception as e: # noqa: BLE001 — a failed action is a recorded step too
127
+ label = f'{act.get("kind", "?")}:{act.get("selector") or act.get("key") or ""}'
128
+ label += f' (failed: {str(e)[:60]})'
129
+ page.wait_for_timeout(200)
130
+ info = page.evaluate(a11ydiff.FOCUS_KEY_JS)
131
+ anns = page.evaluate(_DRAIN)
132
+ if page.url != url_now:
133
+ navigations += 1
134
+ url_now = page.url
135
+ walk.append({'step': i + 1, 'action': label, 'focus': info,
136
+ 'announcements': anns, 'url': page.url})
137
+ return walk, navigations
138
+
139
+
140
+ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None, browser='auto'):
141
+ """One url → the behavioral trace (replayable JSON).
142
+
143
+ script: optional list of scripted actions (click/fill/select/press/wait/
144
+ goto, each with a CSS selector where applicable) — a REAL journey instead
145
+ of the keyboard walk. Each action becomes a recorded step; the announcement
146
+ collector and the focus signature stay identical, so trace diff works the
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()
154
+ try:
155
+ page.goto(url, wait_until='load', timeout=timeout * 1000)
156
+ except Exception as e: # noqa: BLE001
157
+ nav.close()
158
+ return {'error': f'could not load: {e}'}
159
+ page.wait_for_timeout(400)
160
+ page.evaluate(_COLLECTOR)
161
+
162
+ walk = []
163
+ navigations = 0
164
+ url_now = page.url
165
+ if script:
166
+ ended_by = 'script_done'
167
+ walk, navigations = _run_script(page, script)
168
+ else:
169
+ ended_by = 'step_cap'
170
+ for i in range(steps):
171
+ page.keyboard.press('Tab')
172
+ info = page.evaluate(a11ydiff.FOCUS_KEY_JS)
173
+ if info is None:
174
+ ended_by = 'no_more_focusables'
175
+ break
176
+ page.wait_for_timeout(150) # let the observers flush
177
+ anns = page.evaluate(_DRAIN)
178
+ if page.url != url_now:
179
+ navigations += 1
180
+ url_now = page.url
181
+ walk.append({'step': i + 1, 'focus': info,
182
+ 'announcements': anns, 'url': page.url})
183
+
184
+ tree = None
185
+ try:
186
+ tree = page.locator('body').aria_snapshot()
187
+ if len(tree) > 60_000:
188
+ tree = tree[:60_000] + '\n… (truncated)'
189
+ except Exception: # noqa: BLE001
190
+ tree = None
191
+ nav.close()
192
+
193
+ data = {'mode': 'trace', 'url': url,
194
+ 'ts': datetime.now(timezone.utc).isoformat(),
195
+ 'steps': walk,
196
+ 'summary': {'steps_taken': len(walk),
197
+ 'announcements': sum(len(s.get('announcements') or [])
198
+ for s in walk),
199
+ 'navigations': navigations,
200
+ 'ended_by': ended_by}}
201
+ if tree is not None:
202
+ data['tree'] = tree
203
+ if output:
204
+ with open(output, 'w', encoding='utf-8') as f:
205
+ json.dump(data, f, ensure_ascii=False, indent=1)
206
+ return data
207
+
208
+
209
+ def trace_diff(a, b):
210
+ """Two traces → verdict. Focus behavior gates; announcements inform."""
211
+ fa = [s.get('focus') for s in a.get('steps', [])]
212
+ fb = [s.get('focus') for s in b.get('steps', [])]
213
+ set_a, set_b = set(fa), set(fb)
214
+ common_a = [x for x in fa if x in set_b]
215
+ common_b = [x for x in fb if x in set_a]
216
+ lost = [x for x in fa if x not in set_b]
217
+ gained = [x for x in fb if x not in set_a]
218
+ reordered = common_a != common_b
219
+ first_divergence = next((i for i, (x, y) in enumerate(zip(common_a, common_b))
220
+ if x != y), None)
221
+ ann_a = sum(len(s.get('announcements', [])) for s in a.get('steps', []))
222
+ ann_b = sum(len(s.get('announcements', [])) for s in b.get('steps', []))
223
+ collapsed = ann_a > 0 and ann_b == 0
224
+ ok = not (lost or reordered)
225
+ return {
226
+ 'ok': ok,
227
+ 'summary': {'steps': {'before': len(fa), 'after': len(fb)},
228
+ 'focus_lost': len(lost), 'focus_gained': len(gained),
229
+ 'reordered': reordered,
230
+ 'announcements': {'before': ann_a, 'after': ann_b,
231
+ 'collapsed': collapsed}},
232
+ 'focus': {'before': fa, 'after': fb, 'lost': lost, 'gained': gained,
233
+ 'first_divergence': first_divergence},
234
+ 'note': ('focus behavior is the gate: a lost or forked tab sequence '
235
+ 'blocks (exit 2). Announcement counts are reported, not '
236
+ 'gated — content changes legitimately between builds; a '
237
+ 'collapsed layer (had announcements, now zero) is flagged '
238
+ 'informationally'),
239
+ }
240
+
241
+
242
+ def main(argv):
243
+ # el hub del CLI pasa el argv SIN el subcomando (['url', …]): el parser
244
+ # exige trace|diff — prepend 'trace' cuando el primer token no es subcmd
245
+ if argv and argv[0] not in ('trace', 'diff') and not argv[0].startswith('-'):
246
+ argv = ['trace'] + argv
247
+ p = argparse.ArgumentParser(description=__doc__)
248
+ sub = p.add_subparsers(dest='cmd', required=True)
249
+ s1 = sub.add_parser('trace')
250
+ s1.add_argument('url')
251
+ s1.add_argument('--steps', type=int, default=25)
252
+ s1.add_argument('--script', help='JSON file: scripted journey (click/fill/select/press/wait/goto)')
253
+ s1.add_argument('--auth-state', help='Playwright storage_state JSON (session)')
254
+ s1.add_argument('--timeout', type=int, default=45)
255
+ s1.add_argument('-o', '--out', default='trace.json')
256
+ s2 = sub.add_parser('diff')
257
+ s2.add_argument('a')
258
+ s2.add_argument('b')
259
+ a = p.parse_args(argv)
260
+
261
+ if a.cmd == 'trace':
262
+ script = None
263
+ if a.script:
264
+ try:
265
+ with open(a.script, encoding='utf-8') as f:
266
+ script = json.load(f)
267
+ except (OSError, json.JSONDecodeError) as e:
268
+ print(json.dumps({'error': f'bad script file: {e}'}))
269
+ return 1
270
+ try:
271
+ d = trace(a.url, steps=a.steps, output=a.out, auth_state=a.auth_state,
272
+ timeout=a.timeout, script=script)
273
+ except ImportError:
274
+ print(json.dumps({'error': 'Playwright not installed: pip install '
275
+ 'playwright && playwright install chromium'}))
276
+ return 1
277
+ if 'error' in d:
278
+ print(json.dumps(d, ensure_ascii=False))
279
+ return 1
280
+ print(json.dumps({'url': d['url'], 'summary': d['summary'],
281
+ 'out': a.out}, ensure_ascii=False, indent=1))
282
+ return 0
283
+ with open(a.a, encoding='utf-8') as f:
284
+ ja = json.load(f)
285
+ with open(a.b, encoding='utf-8') as f:
286
+ jb = json.load(f)
287
+ verdict = trace_diff(ja, jb)
288
+ print(json.dumps(verdict, ensure_ascii=False, indent=1))
289
+ return 0 if verdict['ok'] else 2
290
+
291
+
292
+ if __name__ == '__main__':
293
+ sys.exit(main(sys.argv[1:]))
@@ -22,16 +22,13 @@ import urllib.request
22
22
  from .a11yaudit import compute_score
23
23
 
24
24
  BASE = 'https://validator.w3.org/nu/'
25
- UA = 'a11y-toolkit/3.16 (WCAG audit; github.com/kinti/a11y-toolkit)'
26
25
 
27
- # known Nu messages → WCAG criteria (the honest subset; the rest are
28
- # plain HTML validity findings, reported under their own label)
29
- _MAPPING = (
30
- ('must have an "alt" attribute', '1.1.1'),
31
- ('"lang" attribute', '3.1.1'),
32
- ('Bad value' and 'role', None), # placeholder, refined below
33
- ('duplicate id', None),
34
- )
26
+
27
+ def _ua():
28
+ # lazy: server importa este módulo arriba; la versión vive en un solo
29
+ # sitio (antes: UA hardcodeado dos majors atrás)
30
+ from .server import VERSION
31
+ return f'a11y-toolkit/{VERSION} (WCAG audit; github.com/kinti/a11y-toolkit)'
35
32
 
36
33
 
37
34
  def _criterion_for(message):
@@ -49,11 +46,11 @@ def _call(data=None, url=None, timeout=60, base_url=None):
49
46
  target = (base_url or BASE).rstrip('/') + '/'
50
47
  if url:
51
48
  target += '?' + urllib.parse.urlencode({'doc': url, 'out': 'json'})
52
- req = urllib.request.Request(target, headers={'User-Agent': UA})
49
+ req = urllib.request.Request(target, headers={'User-Agent': _ua()})
53
50
  else:
54
51
  target += '?out=json'
55
52
  req = urllib.request.Request(target, data=data.encode('utf-8'),
56
- headers={'User-Agent': UA,
53
+ headers={'User-Agent': _ua(),
57
54
  'Content-Type': 'text/html; charset=utf-8'},
58
55
  method='POST')
59
56
  with urllib.request.urlopen(req, timeout=timeout) as r:
@@ -85,13 +82,22 @@ def _process(resp, origin, lang='en'):
85
82
  'summary': {s_: sum(1 for h in findings if h['severity'] == s_)
86
83
  for s_ in ('high', 'medium', 'low')},
87
84
  'findings': findings,
88
- 'notice': ('Report from the W3C Nu validator (validator.w3.org/nu). Complements the '
89
- 'toolkit audits with the W3C parser view: doctype, encoding, structural '
90
- 'validity. HTML validity is not WCAG by itself; mapped criteria where they '
91
- 'overlap are labeled.'),
85
+ 'notice': _NOTICE.get(lang, _NOTICE['en']),
92
86
  }
93
87
 
94
88
 
89
+ _NOTICE = {
90
+ 'es': ('Informe del validador Nu del W3C (validator.w3.org/nu). Complementa las '
91
+ 'auditorías del toolkit con la vista del parser del W3C: doctype, '
92
+ 'codificación, validez estructural. La validez HTML no es WCAG por sí '
93
+ 'misma; los criterios mapeados donde se solapan van etiquetados.'),
94
+ 'en': ('Report from the W3C Nu validator (validator.w3.org/nu). Complements the '
95
+ 'toolkit audits with the W3C parser view: doctype, encoding, structural '
96
+ 'validity. HTML validity is not WCAG by itself; mapped criteria where they '
97
+ 'overlap are labeled.'),
98
+ }
99
+
100
+
95
101
  def validate_url(url, timeout=60, lang='en', base_url=None):
96
102
  resp = _call(url=url, timeout=timeout, base_url=base_url)
97
103
  return _process(resp, url, lang)
@@ -6,9 +6,11 @@ or raw audit reports (the pack is built here). Output: an accessible HTML
6
6
  VPAT with the full 55-criterion WCAG 2.2 A/AA table.
7
7
 
8
8
  Honesty rule (non-negotiable, mirrors the pack): the machine fills Remarks,
9
- never the Conformance Level. Every row starts at 'Not Evaluated' unless an
10
- automated fail forces 'Does Not Support' (or 'Partially Supports' for
11
- review-level signals). A qualified human sets the final level via `overrides`
9
+ never the Conformance Level. Every row starts at 'Not Evaluated'; the only
10
+ machine-set level is 'Does Not Support', forced by an automated fail.
11
+ Review-level signals stay 'Not Evaluated' with the evidence in Remarks —
12
+ the machine never prints a conformance claim from review-level evidence.
13
+ A qualified human sets the final level via `overrides`
12
14
  and signs; until then the document is a DRAFT and says so. The signature
13
15
  statement must reference the evidence pack's sha256 — same tamper-evidence
14
16
  rule as the pack itself. VPAT is a vendor self-declaration, not a certificate.
@@ -17,6 +19,11 @@ CLI:
17
19
  a11yvpat.py pack.json --product "Acme App" --contact a11y@acme.example \
18
20
  --overrides '{"1.1.1": "does_not_support", "1.2.2": "not_applicable"}' \
19
21
  -o vpat.html
22
+
23
+ FROZEN LAYER (2026-11-04, founder decision "freeze the docs"): this
24
+ module stays public as an HONEST DRAFT generator (the machine fills
25
+ Remarks/texts, never the claim). Maintenance fixes only; new
26
+ capabilities live in the SaaS (a11y.es / Lince).
20
27
  """
21
28
 
22
29
  import argparse
@@ -25,12 +32,16 @@ import html
25
32
  import json
26
33
  import sys
27
34
  from . import a11yi18n
35
+ from .a11yact import _NOT_DEAD
28
36
 
29
37
  LEVELS = a11yi18n.pair('vpat_levels') # locales/<lang>.json — community-editable
30
38
 
31
39
  _STATUS_TO_LEVEL = {
32
40
  'automated-fail': 'does_not_support',
33
- 'automated-review': 'partially_supports',
41
+ # review-level evidence is NOT a conformance claim: it stays not-evaluated
42
+ # and the finding travels in the Remarks (evidence, never conformance —
43
+ # only a human sets a level above does-not-support)
44
+ 'automated-review': 'not_evaluated',
34
45
  # not-flagged ≠ pass; agent-verified no es una firma humana
35
46
  'not-flagged': 'not_evaluated',
36
47
  'not-run': 'not_evaluated',
@@ -48,11 +59,27 @@ def _t(lang):
48
59
 
49
60
 
50
61
  def _findings_by_code(pack):
51
- """Código de criterio → primer hallazgo con issue+remediation (de los artefactos)."""
62
+ """Código de criterio → primer hallazgo VIVO con issue+remediation (de los artefactos).
63
+
64
+ Un hallazgo muerto (el disprover lo marcó rejected, o quedó not-rechecked)
65
+ NO es evidencia: se salta — mismo filtro que a11yact (EARL) y build_pack.
66
+ Si existe otro hallazgo vivo del mismo código, ese es el que se cita; el
67
+ muerto nunca enmascara al vivo (ni viceversa)."""
52
68
  by_code = {}
53
69
  for art in pack.get('artifacts', []):
54
70
  body = art.get('body') or {}
55
- for h in body.get('findings', []):
71
+ # artifacts de site-crawl anidan los hallazgos en reports[] — sin
72
+ # este descenso TODOS los Remarks de un pack de crawl salían sin cita
73
+ _hls = body.get('findings')
74
+ if not _hls and isinstance(body.get('reports'), list):
75
+ _hls = [h for sub in body['reports']
76
+ if isinstance(sub, dict) for h in sub.get('findings', [])
77
+ if isinstance(h, dict)]
78
+ for h in (_hls or []):
79
+ if not isinstance(h, dict):
80
+ continue # artefacto hostil: sin crash
81
+ if h.get('status') in _NOT_DEAD or h.get('disprover_status') in _NOT_DEAD:
82
+ continue
56
83
  code = (h.get('criterion') or '').split(' ')[0]
57
84
  if code and code not in by_code:
58
85
  by_code[code] = h
@@ -82,7 +109,7 @@ def _remarks(t, row, finding, level, pack_sha):
82
109
  if chunks:
83
110
  parts.append('; '.join(chunks))
84
111
  if finding:
85
- parts.append(f"issue: {finding.get('issue', '')[:220]}")
112
+ parts.append(f"issue: {str(finding.get('issue') or '')[:220]}")
86
113
  if finding.get('remediation'):
87
114
  parts.append(f"remediation: {finding['remediation'][:220]}")
88
115
  ef = row.get('effort')
@@ -22,6 +22,10 @@ from . import a11yi18n
22
22
  _RE_TIME = re.compile(
23
23
  r'(?:(\d{2,}):)?(\d{2}):(\d{2})[.,](\d{3})\s*-->\s*(?:(\d{2,}):)?(\d{2}):(\d{2})[.,](\d{3})')
24
24
 
25
+ # etiquetas de marcado WebVTT — <v>, <i>, <b>, <c.cls>, anclas/timestamps
26
+ # <00:00:01.000>: no se leen en voz alta, no cuentan como caracteres de lectura
27
+ _RE_TAG = re.compile(r'<[^>]+>')
28
+
25
29
  T = a11yi18n.pair('vtt') # locales/<lang>.json — community-editable
26
30
 
27
31
 
@@ -51,7 +55,8 @@ def vtt_check(url, duration=None, lang='en'):
51
55
  'signal': key, 'issue': _t(lang, key).format(**fmt),
52
56
  'remediation': _t(lang, key + '_rem').format(**fmt)})
53
57
 
54
- if not text.lstrip().startswith('WEBVTT'):
58
+ # un BOM UTF-8 (U+FEFF) delante de WEBVTT es válido — lstrip() no lo quita
59
+ if not text.removeprefix('\ufeff').lstrip().startswith('WEBVTT'):
55
60
  return {'error': 'does not declare WEBVTT (is it .srt or another format?)',
56
61
  'primeros_bytes': text[:40]}
57
62
 
@@ -87,9 +92,15 @@ def vtt_check(url, duration=None, lang='en'):
87
92
  if overlaps:
88
93
  add('low', 'vtt_overlap', n=overlaps)
89
94
 
90
- too_fast = [{'t': c['text'][:30], 'cps': round(len(c['text']) / max(c['end'] - c['start'], 0.1), 1)}
91
- for c in cues if not c['text'].startswith('<') and c['text']
92
- and len(c['text']) / max(c['end'] - c['start'], 0.1) > 21]
95
+ # cps sobre el texto VISIBLE: las etiquetas (<v>, <i>, <c.cls>, anclas)
96
+ # no se leen en voz alta — se miden TODAS las cues, incluidas las que
97
+ # empiezan con etiqueta de voz
98
+ too_fast = []
99
+ for c in cues:
100
+ visible = _RE_TAG.sub('', c['text']).strip()
101
+ dur = max(c['end'] - c['start'], 0.1)
102
+ if visible and len(visible) / dur > 21:
103
+ too_fast.append({'t': visible[:30], 'cps': round(len(visible) / dur, 1)})
93
104
  if too_fast:
94
105
  add('medium', 'vtt_too_fast', n=len(too_fast),
95
106
  example=', '.join(f"{r['t']}… ({r['cps']}cps)" for r in too_fast[:3]))
@@ -127,8 +138,13 @@ def main(argv):
127
138
  ap.add_argument('--duration', type=float, help='media duration in seconds (coverage check)')
128
139
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
129
140
  a = ap.parse_args(argv)
130
- print(json.dumps(vtt_check(a.url, duration=a.duration, lang=a.lang),
131
- ensure_ascii=False, indent=1))
141
+ try:
142
+ res = vtt_check(a.url, duration=a.duration, lang=a.lang)
143
+ except ValueError as e: # _FetchError incluido (descarga/scheme/HTML-size)
144
+ print(json.dumps({'error': str(e)}, ensure_ascii=False))
145
+ return 1
146
+ print(json.dumps(res, ensure_ascii=False, indent=1))
147
+ return 0
132
148
  return 0
133
149
 
134
150