@kinti/a11y-toolkit 5.26.0 → 5.27.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.
- package/README.md +1 -1
- package/a11y_toolkit/a11y.py +27 -4
- package/a11y_toolkit/a11yact.py +9 -1
- package/a11y_toolkit/a11yannotate.py +185 -0
- package/a11y_toolkit/a11yaudit.py +853 -193
- package/a11y_toolkit/a11ybadge.py +24 -17
- package/a11y_toolkit/a11ybudget.py +145 -1
- package/a11y_toolkit/a11ycorpus.py +58 -24
- package/a11y_toolkit/a11ycrit.py +110 -53
- package/a11y_toolkit/a11ydiff.py +104 -34
- package/a11y_toolkit/a11ydisprove.py +15 -8
- package/a11y_toolkit/a11ydocx.py +8 -6
- package/a11y_toolkit/a11ydom.py +425 -95
- package/a11y_toolkit/a11yen301549.py +53 -1
- package/a11y_toolkit/a11yengines.py +157 -0
- package/a11y_toolkit/a11yevidence.py +81 -33
- package/a11y_toolkit/a11yfix.py +131 -52
- package/a11y_toolkit/a11yinit.py +30 -5
- package/a11y_toolkit/a11yjourney.py +110 -4
- package/a11y_toolkit/a11yledger.py +119 -12
- package/a11y_toolkit/a11ylocate.py +247 -0
- package/a11y_toolkit/a11yopenacr.py +10 -3
- package/a11y_toolkit/a11ypatches.py +154 -0
- package/a11y_toolkit/a11ypatterns.py +344 -0
- package/a11y_toolkit/a11ypdf.py +109 -53
- package/a11y_toolkit/a11yrgaa.py +60 -0
- package/a11y_toolkit/a11yroute.py +34 -12
- package/a11y_toolkit/a11ysarif.py +45 -18
- package/a11y_toolkit/a11yscope.py +67 -15
- package/a11y_toolkit/a11yscroll.py +7 -5
- package/a11y_toolkit/a11ystatement.py +30 -6
- package/a11y_toolkit/a11ytrace.py +293 -0
- package/a11y_toolkit/a11yvalidate.py +21 -15
- package/a11y_toolkit/a11yvpat.py +34 -7
- package/a11y_toolkit/a11yvtt.py +22 -6
- package/a11y_toolkit/a11ywiz.py +121 -0
- package/a11y_toolkit/contrast.py +62 -24
- package/a11y_toolkit/locales/en.json +177 -20
- package/a11y_toolkit/locales/es.json +178 -21
- package/a11y_toolkit/rgaa.json +2661 -0
- package/a11y_toolkit/server.py +149 -50
- package/package.json +2 -2
- package/a11y_toolkit/a11yplan.py +0 -214
- package/a11y_toolkit/a11ywcagem.py +0 -237
|
@@ -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
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
(
|
|
31
|
-
|
|
32
|
-
|
|
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':
|
|
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':
|
|
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': ('
|
|
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)
|
package/a11y_toolkit/a11yvpat.py
CHANGED
|
@@ -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'
|
|
10
|
-
|
|
11
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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'
|
|
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')
|
package/a11y_toolkit/a11yvtt.py
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
|
|
131
|
-
|
|
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
|
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""The guided wizard — the Canadian pattern, inverted, in the terminal.
|
|
3
|
+
|
|
4
|
+
2-3 questions a person CAN answer (what are you building, which standard
|
|
5
|
+
applies to your market) configure everything the engine already knows
|
|
6
|
+
how to do: the audit runs with the right standard and the scope artifact
|
|
7
|
+
carries the machine proposals. (The 508 product tree and the tender-annex
|
|
8
|
+
generator live in the private a11y-toolkit-pro layer.)
|
|
9
|
+
|
|
10
|
+
Everything the wizard does is also available as individual commands
|
|
11
|
+
(audit --standard …, scope --solicitation …): the wizard composes, it
|
|
12
|
+
does not hide. Interactive by design; a piped stdin works too (tests,
|
|
13
|
+
CI) and an exhausted stdin aborts gracefully with the non-interactive
|
|
14
|
+
commands as the message.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import argparse
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import sys
|
|
21
|
+
|
|
22
|
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
23
|
+
sys.path.insert(0, ROOT)
|
|
24
|
+
|
|
25
|
+
from a11y_toolkit.a11yaudit import audit_html, audit_url # noqa: E402
|
|
26
|
+
from a11y_toolkit.a11yscope import build_scope # noqa: E402
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _t(key):
|
|
30
|
+
from .a11yi18n import pack
|
|
31
|
+
return pack(_LANG).get('wiz', {}).get(key) or key
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _ask(prompt, valid=None, default=None):
|
|
35
|
+
"""input() con validación: reintenta hasta respuesta válida; en EOF
|
|
36
|
+
aborta con la salida no-interactiva como mensaje (el wizard compone
|
|
37
|
+
comandos que existen)."""
|
|
38
|
+
while True:
|
|
39
|
+
try:
|
|
40
|
+
ans = input(prompt).strip()
|
|
41
|
+
except EOFError:
|
|
42
|
+
print(_t('wiz_abort'))
|
|
43
|
+
sys.exit(1)
|
|
44
|
+
if not ans and default is not None:
|
|
45
|
+
return default
|
|
46
|
+
if valid is None:
|
|
47
|
+
return ans
|
|
48
|
+
if ans in valid:
|
|
49
|
+
return ans
|
|
50
|
+
print(' ' + '/'.join(valid) + '?')
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
_YESNO = ('y', 'Y', 's', 'S', 'si', 'sí', 'SI', 'yes', 'YES', 'Yes',
|
|
54
|
+
'n', 'N', 'no', 'NO', 'No')
|
|
55
|
+
_YES = ('y', 'Y', 's', 'S', 'si', 'sí', 'SI', 'yes', 'YES', 'Yes')
|
|
56
|
+
_NO = ('n', 'N', 'no', 'NO', 'No')
|
|
57
|
+
|
|
58
|
+
_LANG = 'en'
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def main(argv):
|
|
62
|
+
global _LANG
|
|
63
|
+
ap = argparse.ArgumentParser(
|
|
64
|
+
description='Guided wizard: 2-3 questions → standard, audit, scope '
|
|
65
|
+
'and tender annex. Also non-interactive commands exist.')
|
|
66
|
+
ap.add_argument('--url', help='page to audit (skipped from the questions if given)')
|
|
67
|
+
ap.add_argument('--file', help='local html to audit')
|
|
68
|
+
ap.add_argument('--lang', default='en', choices=['en', 'es'])
|
|
69
|
+
ap.add_argument('-o', '--out', default='scope.json',
|
|
70
|
+
help='where the scope artifact is written (default scope.json)')
|
|
71
|
+
a = ap.parse_args(argv)
|
|
72
|
+
_LANG = a.lang
|
|
73
|
+
|
|
74
|
+
# Q0: qué auditar (flag o pregunta)
|
|
75
|
+
url = (a.url or '').strip()
|
|
76
|
+
if not url and not a.file:
|
|
77
|
+
url = _ask(_t('wiz_need_url') + ' URL: ', valid=None)
|
|
78
|
+
|
|
79
|
+
# Q1: qué estás construyendo
|
|
80
|
+
tgt = _ask(_t('wiz_q_target'), valid={'1', '2', '3', '4'})
|
|
81
|
+
if tgt == '4':
|
|
82
|
+
raw = _ask(_t('wiz_q_multi'))
|
|
83
|
+
targets = [x.strip() for x in raw.split(',') if x.strip() in ('web', 'documents', 'software')] \
|
|
84
|
+
or ['web']
|
|
85
|
+
target = targets[0]
|
|
86
|
+
else:
|
|
87
|
+
target = {'1': 'web', '2': 'documents', '3': 'software'}[tgt]
|
|
88
|
+
targets = [target]
|
|
89
|
+
|
|
90
|
+
# Q2: qué norma (508 GSA tree: capa privada a11y-toolkit-pro)
|
|
91
|
+
std_map = {'1': 'wcag22', '2': 'en301549', '3': 'rgaa'}
|
|
92
|
+
std = std_map[_ask(_t('wiz_q_std'), valid={'1', '2', '3'})]
|
|
93
|
+
|
|
94
|
+
answers = {}
|
|
95
|
+
|
|
96
|
+
# auditoría con el estándar elegido
|
|
97
|
+
std_arg = std if std in ('en301549', 'rgaa') else None
|
|
98
|
+
if url:
|
|
99
|
+
report = audit_url(url, timeout=30, lang=a.lang, standard=std_arg, target=targets[0])
|
|
100
|
+
else:
|
|
101
|
+
report = audit_html(open(a.file, encoding='utf-8', errors='replace').read()[:2_000_000],
|
|
102
|
+
url=a.file, lang=a.lang, standard=std_arg, target=targets[0])
|
|
103
|
+
if 'error' in report:
|
|
104
|
+
print(json.dumps(report, ensure_ascii=False))
|
|
105
|
+
return 1
|
|
106
|
+
|
|
107
|
+
scope = build_scope([report], standard=std, target=target,
|
|
108
|
+
answers=answers or None, lang=a.lang, targets=targets)
|
|
109
|
+
with open(a.out, 'w', encoding='utf-8') as f:
|
|
110
|
+
json.dump(scope, f, ensure_ascii=False, indent=1)
|
|
111
|
+
|
|
112
|
+
# (el anexo de pliego se retiró: a11y-toolkit-pro lo genera desde este
|
|
113
|
+
# MISMO artifact sellado — wizard_pro en la capa privada)
|
|
114
|
+
print(_t('wiz_done').format(scope=a.out, annex='—', score=report.get('score'),
|
|
115
|
+
ins=scope['counters']['in_scope'],
|
|
116
|
+
pro=scope['counters']['proposed_excluded']))
|
|
117
|
+
return 0
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
if __name__ == '__main__':
|
|
121
|
+
sys.exit(main(sys.argv[1:]))
|