@kinti/a11y-toolkit 5.22.1 → 5.22.3

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 (38) hide show
  1. package/LICENSE +21 -0
  2. package/a11y_toolkit/__init__.py +5 -0
  3. package/a11y_toolkit/a11y.py +117 -0
  4. package/a11y_toolkit/a11yact.py +167 -0
  5. package/a11y_toolkit/a11yaudit.py +1951 -0
  6. package/a11y_toolkit/a11ybadge.py +102 -0
  7. package/a11y_toolkit/a11ybudget.py +122 -0
  8. package/a11y_toolkit/a11ycrit.py +1017 -0
  9. package/a11y_toolkit/a11ydiff.py +192 -0
  10. package/a11y_toolkit/a11ydisprove.py +175 -0
  11. package/a11y_toolkit/a11ydocx.py +132 -0
  12. package/a11y_toolkit/a11ydom.py +1831 -0
  13. package/a11y_toolkit/a11yevidence.py +272 -0
  14. package/a11y_toolkit/a11yfix.py +330 -0
  15. package/a11y_toolkit/a11yi18n.py +100 -0
  16. package/a11y_toolkit/a11yinit.py +113 -0
  17. package/a11y_toolkit/a11yjourney.py +284 -0
  18. package/a11y_toolkit/a11yledger.py +210 -0
  19. package/a11y_toolkit/a11ymutants.py +406 -0
  20. package/a11y_toolkit/a11yopenacr.py +207 -0
  21. package/a11y_toolkit/a11ypdf.py +273 -0
  22. package/a11y_toolkit/a11yroute.py +378 -0
  23. package/a11y_toolkit/a11ysarif.py +139 -0
  24. package/a11y_toolkit/a11yscroll.py +212 -0
  25. package/a11y_toolkit/a11ystatement.py +158 -0
  26. package/a11y_toolkit/a11yvalidate.py +127 -0
  27. package/a11y_toolkit/a11yvpat.py +238 -0
  28. package/a11y_toolkit/a11yvtt.py +136 -0
  29. package/a11y_toolkit/a11ywcag3.py +262 -0
  30. package/a11y_toolkit/a11ywcagem.py +177 -0
  31. package/a11y_toolkit/arialive.js +107 -0
  32. package/a11y_toolkit/arialive_js.py +113 -0
  33. package/a11y_toolkit/contrast.py +536 -0
  34. package/a11y_toolkit/locales/_template.json +468 -0
  35. package/a11y_toolkit/locales/en.json +525 -0
  36. package/a11y_toolkit/locales/es.json +525 -0
  37. package/a11y_toolkit/server.py +1529 -0
  38. package/package.json +7 -2
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env python3
2
+ """WCAG-EM 2.0 evaluation mode — the sampling/aggregation layer.
3
+
4
+ WCAG-EM (W3C Group Note, 2026-07-23) is HOW a full evaluation is scoped,
5
+ sampled and reported. This module does the machine half honestly:
6
+
7
+ plan JSON → what is being evaluated (Step 1), the sample set (Step 3)
8
+ packs[] → the sealed evidence per sample (Step 4, a11y_evidence output)
9
+ report → per-criterion rollup ACROSS the sample (Step 5), sealed with
10
+ a root hash over the pack seals
11
+
12
+ What it deliberately does NOT do: claim conformance. The report carries
13
+ evidence-status per criterion (the worst across the sample wins), the
14
+ priced human work that remains, and the standard's step trace. Random
15
+ sample selection stays with the evaluator (their methodology, their name);
16
+ structured samples and complete processes (journeys) are first-class.
17
+
18
+ CLI:
19
+ a11ywcagem.py --plan plan.json --packs p1.json p2.json -o report.json
20
+ """
21
+
22
+ import argparse
23
+ import hashlib
24
+ import json
25
+ import sys
26
+
27
+ # El worst peor gana al agregar samples; never-flagged en TODAS no es pass
28
+ # (es "ninguna señal saltó en esta sample"), exactamente como el pack.
29
+ _RANK = {'automated-fail': 0, 'not-run': 1, 'automated-review': 2,
30
+ 'manual-only': 3, 'not-flagged': 4, 'agent-verified': 5}
31
+
32
+ _TYPES = ('structured', 'random', 'process', 'common-view')
33
+
34
+ _STEPS = [
35
+ {'step': '1', 'what': 'Define the evaluation scope',
36
+ 'where': 'plan.product (enclosure: all views, states, functionality)'},
37
+ {'step': '1.2', 'what': 'Conformance target', 'where': 'plan.conformance_target'},
38
+ {'step': '1.3', 'what': 'Accessibility support baseline', 'where': 'plan.support_baseline'},
39
+ {'step': '2', 'what': 'Explore the target product', 'where': 'plan.sample[].why'},
40
+ {'step': '3', 'what': 'Select a representative sample set',
41
+ 'where': 'plan.sample[] (structured / random / process) + packs per sample'},
42
+ {'step': '4', 'what': 'Evaluate the selected sample set',
43
+ 'where': 'the evidence packs (a11y-evidence-pack/2)'},
44
+ {'step': '5', 'what': 'Report the evaluation findings', 'where': 'this report'},
45
+ ]
46
+
47
+
48
+ def _canon(obj):
49
+ return json.dumps(obj, ensure_ascii=False, sort_keys=True,
50
+ separators=(',', ':'))
51
+
52
+
53
+ def validate_plan(plan):
54
+ """Plan (dict) → (ok, error). Solo estructura; el muestreo es del auditor."""
55
+ if not isinstance(plan, dict):
56
+ return False, 'el plan debe ser un objeto'
57
+ for field in ('product', 'conformance_target', 'sample'):
58
+ if field not in plan:
59
+ return False, f'falta {field} (WCAG-EM paso 1/3)'
60
+ if not isinstance(plan['product'], dict) or not plan['product'].get('name'):
61
+ return False, 'product.name es obligatorio (¿qué se evalúa?)'
62
+ if not isinstance(plan['conformance_target'], str):
63
+ return False, 'conformance_target debe ser texto (p. ej. "WCAG 2.2 AA")'
64
+ sample = plan['sample']
65
+ if not isinstance(sample, list) or not sample:
66
+ return False, 'sample debe ser una lista no vacía de samples'
67
+ for i, m in enumerate(sample):
68
+ if not isinstance(m, dict):
69
+ return False, f'sample #{i + 1} debe ser objeto'
70
+ for field in ('id', 'type'):
71
+ if not m.get(field):
72
+ return False, f'sample #{i + 1} sin {field}'
73
+ if m['type'] not in _TYPES:
74
+ return False, (f"sample {m['id']}: type debe ser "
75
+ f"{'/'.join(_TYPES)} (WCAG-EM 3.1-3.3)")
76
+ if not m.get('url') and not m.get('file'):
77
+ return False, f"sample {m['id']}: url o file requeridos"
78
+ return True, ''
79
+
80
+
81
+ def aggregate(plan, packs):
82
+ """Plan válido + packs sellados → report agregado con sello raíz.
83
+
84
+ Regla de agregado por criterio: el PEOR worst de todas las samples
85
+ (un fallo en cualquier página muestreada es un fallo del report).
86
+ agent-verified no borra un fail (misma honestidad que el pack).
87
+ """
88
+ ok, err = validate_plan(plan)
89
+ if not ok:
90
+ raise ValueError(err)
91
+ if len(packs) != len(plan['sample']):
92
+ raise ValueError(f'{len(plan["sample"])} samples, {len(packs)} packs: deben emparejar')
93
+
94
+ codes, names, effort = set(), {}, {'MIN': 0, 'MED': 0, 'MAX': 0}
95
+ worst = {} # code → peor worst
96
+ fail_counts = {} # code → cuántas samples fallaron
97
+ for pack in packs:
98
+ for c in pack.get('criteria', []):
99
+ code = c['criterion'].split(' ')[0]
100
+ codes.add(code)
101
+ names[code] = c['criterion']
102
+ st = c['status']
103
+ if code not in worst or _RANK[st] < _RANK[worst[code]]:
104
+ worst[code] = st
105
+ if st == 'automated-fail':
106
+ fail_counts[code] = fail_counts.get(code, 0) + 1
107
+ ef = c.get('effort', {}).get('class')
108
+ if ef in effort and st != 'agent-verified':
109
+ effort[ef] += 1
110
+
111
+ criteria = []
112
+ for code in sorted(codes, key=lambda x: tuple(int(n) for n in x.split('.'))):
113
+ row = {'criterion': names[code], 'status': worst[code],
114
+ 'samples_failing': fail_counts.get(code, 0),
115
+ 'total_samples': len(packs)}
116
+ if worst[code] == 'not-flagged':
117
+ row['note'] = ('no signal fired on ANY sampled page — explicitly '
118
+ 'NOT pass; the human still owns this criterion')
119
+ criteria.append(row)
120
+
121
+ report = {
122
+ 'format': 'a11y-wcagem-report/1',
123
+ 'method': 'WCAG-EM 2.0 (W3C Group Note, 2026-07-23)',
124
+ 'product': plan['product'],
125
+ 'conformance_target': plan['conformance_target'],
126
+ 'support_baseline': plan.get('support_baseline', []),
127
+ 'sample': plan['sample'],
128
+ 'wcag_em': {'steps': _STEPS,
129
+ 'note': ('random selection (3.2) stays with the evaluator: '
130
+ 'this tool aggregates, never chooses')},
131
+ 'criteria': criteria,
132
+ 'summary': {s: sum(1 for c in criteria if c['status'] == s)
133
+ for s in _RANK},
134
+ 'effort_pending': effort,
135
+ 'packs': [{'sample': m['id'], 'type': m['type'],
136
+ 'sha256': p['sha256'], 'format': p.get('format')}
137
+ for m, p in zip(plan['sample'], packs)],
138
+ # sin claim de conformidad: el report ES evidencia para el humano
139
+ }
140
+ report['sha256'] = hashlib.sha256(
141
+ _canon({k: v for k, v in report.items() if k != 'sha256'}).encode('utf-8')
142
+ ).hexdigest()
143
+ return report
144
+
145
+
146
+ def verify_report(report):
147
+ """(ok, detalle): el sello raíz del report (menos sha256)."""
148
+ expected = hashlib.sha256(
149
+ _canon({k: v for k, v in report.items() if k != 'sha256'}).encode('utf-8')
150
+ ).hexdigest()
151
+ return expected == report.get('sha256'), 'root sha256'
152
+
153
+
154
+ def main(argv):
155
+ ap = argparse.ArgumentParser(description='WCAG-EM 2.0 aggregated evaluation report')
156
+ ap.add_argument('--plan', required=True, help='evaluation plan JSON (scope + sample set)')
157
+ ap.add_argument('--packs', nargs='+', required=True,
158
+ help='evidence pack JSON per sample, in plan.sample order')
159
+ ap.add_argument('-o', '--out', default='wcagem-report.json')
160
+ a = ap.parse_args(argv)
161
+ plan = json.load(open(a.plan, encoding='utf-8'))
162
+ packs = [json.load(open(p, encoding='utf-8')) for p in a.packs]
163
+ try:
164
+ report = aggregate(plan, packs)
165
+ except ValueError as e:
166
+ print(json.dumps({'error': str(e)}))
167
+ return 2
168
+ with open(a.out, 'w', encoding='utf-8') as f:
169
+ json.dump(report, f, ensure_ascii=False, indent=1)
170
+ print(json.dumps({'report': a.out, 'sha256': report['sha256'],
171
+ 'criteria': len(report['criteria']),
172
+ 'summary': report['summary']}, ensure_ascii=False))
173
+ return 0
174
+
175
+
176
+ if __name__ == '__main__':
177
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,107 @@
1
+ /* Monitor de anuncios aria-live · v1.0 · jquin.net/lab
2
+ * Inyectable como bookmarklet o vía Playwright (page.evaluate).
3
+ * Registra cada anuncio de regiones dinámicas (aria-live, role=alert/status/
4
+ * log) con hora, cortesía, rol y texto — lo que un lector de pantalla
5
+ * "diría", visible en pantalla. Sin dependencias.
6
+ */
7
+ (function () {
8
+ 'use strict';
9
+ var LANG = (window.ALM_LANG === 'en')
10
+ ? { titulo: 'aria-live monitor', copiar: 'Copy', cerrar: 'Close',
11
+ label: 'aria-live announcement monitor' }
12
+ : { titulo: 'aria-live monitor', copiar: 'Copiar', cerrar: 'Cerrar',
13
+ label: 'Monitor de anuncios aria-live' };
14
+ if (window.__ariaLiveMonitor) { window.__ariaLiveMonitor(); return; }
15
+ var SEL = '[aria-live],[role=alert],[role=status],[role=log],[role=marquee],[role=timer]';
16
+ var log = [];
17
+ var observados = new WeakSet();
18
+
19
+ var css = document.createElement('style');
20
+ css.textContent = '.alm-panel{position:fixed;bottom:12px;right:12px;z-index:2147483647;' +
21
+ 'width:min(420px,90vw);max-height:45vh;overflow:auto;background:#111;color:#fff;' +
22
+ 'font:12px/1.5 ui-monospace,monospace;border:2px solid #ffd33d;border-radius:8px;padding:8px}' +
23
+ '.alm-panel button{background:#ffd33d;color:#111;border:0;border-radius:4px;padding:3px 8px;' +
24
+ 'font:inherit;cursor:pointer;margin-left:6px}' +
25
+ '.alm-e{padding:4px 6px;border-bottom:1px solid #333;white-space:pre-wrap}' +
26
+ '.alm-t{color:#ffd33d}.alm-e b{color:#8ec2f5}';
27
+ document.head.appendChild(css);
28
+
29
+ var panel = document.createElement('div');
30
+ panel.className = 'alm-panel';
31
+ // Sin role="log" a propósito: una región viva casaría con nuestro propio
32
+ // selector y crearía un bucle de auto-observación infinito.
33
+ panel.setAttribute('aria-label', LANG.label);
34
+ panel.innerHTML = '<div><span class="alm-t">' + LANG.titulo + '</span>' +
35
+ '<button type="button" data-alm="copy">' + LANG.copiar + '</button>' +
36
+ '<button type="button" data-alm="close">' + LANG.cerrar + '</button></div><div data-alm="log"></div>';
37
+ document.body.appendChild(panel);
38
+ var cont = panel.querySelector('[data-alm=log]');
39
+
40
+ function desc(el) {
41
+ var d = el.tagName.toLowerCase();
42
+ if (el.id) d += '#' + el.id;
43
+ else if (el.className && typeof el.className === 'string')
44
+ d += '.' + el.className.trim().split(/\s+/).slice(0, 2).join('.');
45
+ return d;
46
+ }
47
+
48
+ function anota(el, razon) {
49
+ var rol = el.getAttribute('role') || '(sin role)';
50
+ var cortesia = el.getAttribute('aria-live') ||
51
+ ({ alert: 'assertive', status: 'polite', log: 'polite',
52
+ marquee: 'off', timer: 'off' })[el.getAttribute('role')] || 'polite';
53
+ var texto = (el.innerText || el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 220);
54
+ var hora = new Date().toTimeString().slice(0, 8);
55
+ log.push(hora + ' [' + cortesia + '] ' + rol + ' · ' + desc(el) + ' · ' + texto);
56
+ var fila = document.createElement('div');
57
+ fila.className = 'alm-e';
58
+ // DOM-safe: el contenido de la página auditada NUNCA va a innerHTML
59
+ var t = document.createElement('span'); t.className = 'alm-t'; t.textContent = hora;
60
+ fila.appendChild(t);
61
+ fila.appendChild(document.createTextNode(' [' + cortesia + '] '));
62
+ var b = document.createElement('b'); b.textContent = rol; fila.appendChild(b);
63
+ fila.appendChild(document.createTextNode(' \u00b7 ' + desc(el)));
64
+ if (razon) {
65
+ var i = document.createElement('i'); i.textContent = ' (' + razon + ')';
66
+ fila.appendChild(i);
67
+ }
68
+ fila.appendChild(document.createElement('br'));
69
+ fila.appendChild(document.createTextNode(texto));
70
+ cont.appendChild(fila);
71
+ panel.scrollTop = panel.scrollHeight;
72
+ }
73
+
74
+ function vigila(el) {
75
+ if (!el || observados.has(el) || el.nodeType !== 1) return;
76
+ // Nunca monitorizar nuestro propio panel (bucle de auto-observación).
77
+ if (el.closest && el.closest('.alm-panel')) return;
78
+ if (!el.matches(SEL)) return;
79
+ observados.add(el);
80
+ if (el.getAttribute('role') === 'alert') anota(el, 'insertado');
81
+ new MutationObserver(function () {
82
+ anota(el, null);
83
+ }).observe(el, { childList: true, characterData: true, subtree: true });
84
+ }
85
+
86
+ document.querySelectorAll(SEL).forEach(function (el) { vigila(el); });
87
+
88
+ new MutationObserver(function (muts) {
89
+ muts.forEach(function (m) {
90
+ m.addedNodes.forEach(function (n) {
91
+ if (n.nodeType !== 1) return;
92
+ vigila(n);
93
+ if (n.querySelectorAll) n.querySelectorAll(SEL).forEach(vigila);
94
+ });
95
+ });
96
+ }).observe(document.body, { childList: true, subtree: true });
97
+
98
+ panel.addEventListener('click', function (ev) {
99
+ var b = ev.target.closest('button');
100
+ if (!b) return;
101
+ if (b.dataset.alm === 'close') { panel.remove(); css.remove(); delete window.__ariaLiveMonitor; }
102
+ if (b.dataset.alm === 'copy' && navigator.clipboard)
103
+ navigator.clipboard.writeText(log.join('\n'));
104
+ });
105
+
106
+ window.__ariaLiveMonitor = function () { panel.remove(); css.remove(); delete window.__ariaLiveMonitor; };
107
+ })();
@@ -0,0 +1,113 @@
1
+ """Embedded aria-live monitor JS (arialive.js) so pip installs can read it.
2
+
3
+ Regenerated from arialive.js — edit that file, then regenerate this one.
4
+ """
5
+
6
+ ARIALIVE_JS = r"""/* Monitor de anuncios aria-live · v1.0 · jquin.net/lab
7
+ * Inyectable como bookmarklet o vía Playwright (page.evaluate).
8
+ * Registra cada anuncio de regiones dinámicas (aria-live, role=alert/status/
9
+ * log) con hora, cortesía, rol y texto — lo que un lector de pantalla
10
+ * "diría", visible en pantalla. Sin dependencias.
11
+ */
12
+ (function () {
13
+ 'use strict';
14
+ var LANG = (window.ALM_LANG === 'en')
15
+ ? { titulo: 'aria-live monitor', copiar: 'Copy', cerrar: 'Close',
16
+ label: 'aria-live announcement monitor' }
17
+ : { titulo: 'aria-live monitor', copiar: 'Copiar', cerrar: 'Cerrar',
18
+ label: 'Monitor de anuncios aria-live' };
19
+ if (window.__ariaLiveMonitor) { window.__ariaLiveMonitor(); return; }
20
+ var SEL = '[aria-live],[role=alert],[role=status],[role=log],[role=marquee],[role=timer]';
21
+ var log = [];
22
+ var observados = new WeakSet();
23
+
24
+ var css = document.createElement('style');
25
+ css.textContent = '.alm-panel{position:fixed;bottom:12px;right:12px;z-index:2147483647;' +
26
+ 'width:min(420px,90vw);max-height:45vh;overflow:auto;background:#111;color:#fff;' +
27
+ 'font:12px/1.5 ui-monospace,monospace;border:2px solid #ffd33d;border-radius:8px;padding:8px}' +
28
+ '.alm-panel button{background:#ffd33d;color:#111;border:0;border-radius:4px;padding:3px 8px;' +
29
+ 'font:inherit;cursor:pointer;margin-left:6px}' +
30
+ '.alm-e{padding:4px 6px;border-bottom:1px solid #333;white-space:pre-wrap}' +
31
+ '.alm-t{color:#ffd33d}.alm-e b{color:#8ec2f5}';
32
+ document.head.appendChild(css);
33
+
34
+ var panel = document.createElement('div');
35
+ panel.className = 'alm-panel';
36
+ // Sin role="log" a propósito: una región viva casaría con nuestro propio
37
+ // selector y crearía un bucle de auto-observación infinito.
38
+ panel.setAttribute('aria-label', LANG.label);
39
+ panel.innerHTML = '<div><span class="alm-t">' + LANG.titulo + '</span>' +
40
+ '<button type="button" data-alm="copy">' + LANG.copiar + '</button>' +
41
+ '<button type="button" data-alm="close">' + LANG.cerrar + '</button></div><div data-alm="log"></div>';
42
+ document.body.appendChild(panel);
43
+ var cont = panel.querySelector('[data-alm=log]');
44
+
45
+ function desc(el) {
46
+ var d = el.tagName.toLowerCase();
47
+ if (el.id) d += '#' + el.id;
48
+ else if (el.className && typeof el.className === 'string')
49
+ d += '.' + el.className.trim().split(/\s+/).slice(0, 2).join('.');
50
+ return d;
51
+ }
52
+
53
+ function anota(el, razon) {
54
+ var rol = el.getAttribute('role') || '(sin role)';
55
+ var cortesia = el.getAttribute('aria-live') ||
56
+ ({ alert: 'assertive', status: 'polite', log: 'polite',
57
+ marquee: 'off', timer: 'off' })[el.getAttribute('role')] || 'polite';
58
+ var texto = (el.innerText || el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 220);
59
+ var hora = new Date().toTimeString().slice(0, 8);
60
+ log.push(hora + ' [' + cortesia + '] ' + rol + ' · ' + desc(el) + ' · ' + texto);
61
+ var fila = document.createElement('div');
62
+ fila.className = 'alm-e';
63
+ // DOM-safe: el contenido de la página auditada NUNCA va a innerHTML
64
+ var t = document.createElement('span'); t.className = 'alm-t'; t.textContent = hora;
65
+ fila.appendChild(t);
66
+ fila.appendChild(document.createTextNode(' [' + cortesia + '] '));
67
+ var b = document.createElement('b'); b.textContent = rol; fila.appendChild(b);
68
+ fila.appendChild(document.createTextNode(' \u00b7 ' + desc(el)));
69
+ if (razon) {
70
+ var i = document.createElement('i'); i.textContent = ' (' + razon + ')';
71
+ fila.appendChild(i);
72
+ }
73
+ fila.appendChild(document.createElement('br'));
74
+ fila.appendChild(document.createTextNode(texto));
75
+ cont.appendChild(fila);
76
+ panel.scrollTop = panel.scrollHeight;
77
+ }
78
+
79
+ function vigila(el) {
80
+ if (!el || observados.has(el) || el.nodeType !== 1) return;
81
+ // Nunca monitorizar nuestro propio panel (bucle de auto-observación).
82
+ if (el.closest && el.closest('.alm-panel')) return;
83
+ if (!el.matches(SEL)) return;
84
+ observados.add(el);
85
+ if (el.getAttribute('role') === 'alert') anota(el, 'insertado');
86
+ new MutationObserver(function () {
87
+ anota(el, null);
88
+ }).observe(el, { childList: true, characterData: true, subtree: true });
89
+ }
90
+
91
+ document.querySelectorAll(SEL).forEach(function (el) { vigila(el); });
92
+
93
+ new MutationObserver(function (muts) {
94
+ muts.forEach(function (m) {
95
+ m.addedNodes.forEach(function (n) {
96
+ if (n.nodeType !== 1) return;
97
+ vigila(n);
98
+ if (n.querySelectorAll) n.querySelectorAll(SEL).forEach(vigila);
99
+ });
100
+ });
101
+ }).observe(document.body, { childList: true, subtree: true });
102
+
103
+ panel.addEventListener('click', function (ev) {
104
+ var b = ev.target.closest('button');
105
+ if (!b) return;
106
+ if (b.dataset.alm === 'close') { panel.remove(); css.remove(); delete window.__ariaLiveMonitor; }
107
+ if (b.dataset.alm === 'copy' && navigator.clipboard)
108
+ navigator.clipboard.writeText(log.join('\n'));
109
+ });
110
+
111
+ window.__ariaLiveMonitor = function () { panel.remove(); css.remove(); delete window.__ariaLiveMonitor; };
112
+ })();
113
+ """