@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,272 @@
1
+ #!/usr/bin/env python3
2
+ """Evidence pack — the machine→human handoff object for WCAG conformance work.
3
+
4
+ The design lesson comes from outside: an agent can produce a thorough audit
5
+ and still not produce a conformance statement, because conformance needs a
6
+ named person behind it, reachable later by a supervising authority. This
7
+ module builds the vendor-neutral bridge: a tamper-evident bundle of what the
8
+ machines found, what remains for a human, and an empty signature block whose
9
+ statement references the pack's own hash.
10
+
11
+ No third parties, no network, no claim of conformance: the pack IS the thing
12
+ any qualified human (the maintainer, a marketplace auditor, a regulator-facing
13
+ consultant) reviews and signs.
14
+
15
+ criterios: full matrix — every WCAG 2.2 A/AA criterion with a status:
16
+ automated-fail / automated-review / not-flagged / manual-only
17
+ (not-flagged ≠ pass: it means no signal fired on this sample)
18
+ artefactos: the input reports with their SHA-256, timestamps, tool version
19
+ firma: empty human block (nombre, credencial, fecha, alcance) — any
20
+ signature must reference pack.sha256 to be verifiable
21
+ pack.sha256: hash of the pack without the hash field itself
22
+
23
+ CLI:
24
+ a11yevidence.py audit.json [otro.json …] [--snapshot snap.json] -o pack.json
25
+ """
26
+
27
+ import argparse
28
+ import hashlib
29
+ import json
30
+
31
+ from .a11yaudit import normalize_report # noqa: E402 (compat 5.10)
32
+ import sys
33
+ from datetime import datetime, timezone
34
+
35
+ # Criterios A/AA de WCAG 2.2 SIN señal automatizada en este toolkit:
36
+ # lo que toda evaluación humana pendiente debe cubrir, digan lo que digan
37
+ # las herramientas.
38
+ MANUAL_AA = [
39
+ '1.2.1 Audio-only and Video-only (Prerecorded)',
40
+ '1.2.4 Captions (Live)',
41
+ '2.3.1 Three Flashes or Below Threshold',
42
+ '3.3.7 Redundant Entry',
43
+ ]
44
+
45
+ _STATES = ('automated-fail', 'automated-review', 'not-flagged', 'manual-only',
46
+ 'agent-verified', 'not-run')
47
+
48
+
49
+ def _canon(obj):
50
+ return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
51
+
52
+
53
+ def _sha256(obj):
54
+ return hashlib.sha256(_canon(obj).encode('utf-8')).hexdigest()
55
+
56
+
57
+ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
58
+ sr_transcript=None, lang='en'):
59
+ """Informes (lista de dicts JSON) → paquete de evidencia verificable.
60
+
61
+ verificados: lista de códigos de criterio ("1.4.1", "3.3.1"…) que un
62
+ agente o una persona han verificado manualmente sobre esta muestra
63
+ (protocolo del checklist del skill). El criterio pasa a estado
64
+ 'agent-verified' — salvo que una señal automática diera fail, que
65
+ permanece como fail (el fallo no se borra verificando). La fuente
66
+ (agente/humano, fecha) queda registrada en el bloque verificacion."""
67
+ now = datetime.now(timezone.utc).isoformat(timespec='seconds')
68
+ from . import a11yi18n
69
+ tx = a11yi18n.pack(lang).get('evidence', {})
70
+ language = lang if tx else 'en'
71
+ tx = tx or a11yi18n.pack('en')['evidence']
72
+ reports = [normalize_report(i) for i in reports] # compat 5.10: señales previas al rename
73
+
74
+ # matriz de criterios: los que tocamos (estado según hallazgos) + manuales
75
+ from .a11ycrit import _C as _CAT, effort
76
+ codes_aa = sorted(k for k, v in _CAT.items() if v[0] in ('A', 'AA'))
77
+ modes_included = {inf.get('mode', 'static') for inf in reports}
78
+ touched = {}
79
+ for inf in reports:
80
+ for h in inf.get('findings', []):
81
+ if (h.get('status') == 'rejected'
82
+ or h.get('disprover_status') in ('rejected', 'not-rechecked')):
83
+ # un hallazgo desmentido (o no reverificado) no puede volver a
84
+ # convertirse en fallo dentro del pack
85
+ continue
86
+ crit = h.get('criterion')
87
+ if not crit or not isinstance(crit, str): # informe malformado: saltar
88
+ continue
89
+ code = crit.split(' ')[0]
90
+ severity = h.get('severity')
91
+ state = 'automated-review' if severity == 'low' else 'automated-fail'
92
+ # el peor estado gana: fail > review
93
+ if touched.get(code) != 'automated-fail':
94
+ touched[code] = state
95
+
96
+ verified = {v.split(' ')[0] for v in (verified or [])}
97
+ # extraer valores medidos clave de los hallazgos (ratio, ejemplos)
98
+ values = {}
99
+ for inf in reports:
100
+ for h in inf.get('findings', []):
101
+ code = (h.get('criterion') or '').split(' ')[0]
102
+ if code not in values:
103
+ val = {}
104
+ if 'ratio' in h.get('issue', '').lower() or ':' in h.get('issue', ''):
105
+ import re as _re
106
+ m = _re.search(r'([\d.]+):1', h.get('issue', ''))
107
+ if m:
108
+ val['measured'] = f'{m.group(1)}:1'
109
+ _ex_list = h.get('examples', [])
110
+ if _ex_list:
111
+ val['example'] = str(_ex_list[0])[:80]
112
+ if val:
113
+ values[code] = val
114
+
115
+ # criterios que requieren modo rendered (si solo corrió static, su estado
116
+ # real es not-run, no not-flagged: la herramienta SÍ tiene señal pero el
117
+ # modo que la produce no se incluyó)
118
+ from .a11ycrit import RENDERED_ONLY as _RENDERED_ONLY # canónico (a11ycrit)
119
+
120
+ verified_set = {v.split(' ')[0] for v in (verified or [])}
121
+
122
+ matrix = []
123
+ _manual_codes = {m.split(' ')[0] for m in MANUAL_AA}
124
+ for code in codes_aa:
125
+ if code in _manual_codes:
126
+ continue # covered by the manual-only rows appended below
127
+ state = touched.get(code, 'not-flagged')
128
+
129
+ # not-run: el criterio requiere rendered y este pack no lo incluye
130
+ if state == 'not-flagged' and code in _RENDERED_ONLY and 'rendered' not in modes_included:
131
+ state = 'not-run'
132
+
133
+ # verificados: promueve not-flagged/not-run/manual-only → agent-verified
134
+ # (pero automated-fail permanece: un fallo no se borra verificando)
135
+ if code in verified_set and state != 'automated-fail':
136
+ state = 'agent-verified'
137
+
138
+ note = None
139
+ if state == 'not-flagged':
140
+ note = tx['not_flagged']
141
+ elif state == 'not-run':
142
+ note = ('requires rendered mode (a11y_audit_dom) — this pack only '
143
+ 'includes the static audit, so no signal was tried')
144
+ elif state == 'agent-verified':
145
+ note = tx['verified']
146
+
147
+ entry = {'criterion': f"{code} {(_CAT[code][1].get(language) or _CAT[code][1]['en'])[0]}",
148
+ 'status': state, 'note': note}
149
+ ef = effort(code)
150
+ if ef:
151
+ # human-effort class: what the HUMAN still does after the machine's
152
+ # best signal (pricing input for human-review scoping)
153
+ entry['effort'] = {'class': ef['class'], 'minutes': ef['minutes'],
154
+ 'why': ef['why']}
155
+ if code in values:
156
+ entry['value'] = values[code]
157
+ matrix.append(entry)
158
+ manual_remaining = [m for m in MANUAL_AA if m.split(' ')[0] not in verified]
159
+ # los not-run son adicionalmente "pendientes" (la máquina no miró)
160
+ for name in manual_remaining:
161
+ code = name.split(' ')[0]
162
+ # el nombre viaja en el idioma del pack como el resto de la matriz:
163
+ # manual_pending también es un entregable que va al cliente
164
+ row = {'criterion': f"{code} {(_CAT[code][1].get(language) or _CAT[code][1]['en'])[0]}",
165
+ 'status': 'manual-only',
166
+ 'note': tx['no_signal']}
167
+ ef = effort(code)
168
+ if ef:
169
+ row['effort'] = {'class': ef['class'], 'minutes': ef['minutes'],
170
+ 'why': ef['why']}
171
+ matrix.append(row)
172
+ for code in sorted(verified):
173
+ if any(code in m for m in MANUAL_AA) and not any(m.startswith(code) for m in manual_remaining):
174
+ row = {'criterion': f"{code} {(_CAT[code][1].get(language) or _CAT[code][1]['en'])[0]}",
175
+ 'status': 'agent-verified',
176
+ 'note': 'verified against this sample per the manual checklist protocol'}
177
+ ef = effort(code)
178
+ if ef:
179
+ row['effort'] = {'class': ef['class'], 'minutes': ef['minutes'],
180
+ 'why': ef['why']}
181
+ matrix.append(row)
182
+
183
+ summary = {e: sum(1 for m in matrix if m['status'] == e) for e in _STATES}
184
+
185
+ # remaining human review, in minutes: MIN/MED/MAX per class summed over
186
+ # every row a human still has to touch (everything except agent-verified).
187
+ # This is the scope input for human review: agent output in,
188
+ # priced human scope out.
189
+ _MIN = {'MIN': (1, 3), 'MED': (5, 10), 'MAX': (15, 30)}
190
+ pend = {}
191
+ for m in matrix:
192
+ if m['status'] == 'agent-verified':
193
+ continue
194
+ ef = m.get('effort')
195
+ if ef:
196
+ lo, hi = _MIN[ef['class']]
197
+ pend.setdefault(ef['class'], [0, 0])
198
+ pend[ef['class']][0] += lo
199
+ pend[ef['class']][1] += hi
200
+ pending_effort = {
201
+ 'by_class': {k: {'criteria': sum(1 for m in matrix
202
+ if m['status'] != 'agent-verified'
203
+ and m.get('effort', {}).get('class') == k),
204
+ 'minutes': v}
205
+ for k, v in sorted(pend.items())},
206
+ 'total_minutes': [sum(v[0] for v in pend.values()), sum(v[1] for v in pend.values())],
207
+ 'note': tx['manual_remaining'],
208
+ }
209
+
210
+ artifacts = []
211
+ for i, inf in enumerate(reports):
212
+ artifacts.append({'type': f"report:{inf.get('mode', 'static')}",
213
+ 'url': inf.get('url'), 'sha256': _sha256(inf),
214
+ 'score': inf.get('score'),
215
+ 'body': inf}) # embedded: pack self-verifying
216
+ if snapshot:
217
+ artifacts.append({'type': 'snapshot:a11y', 'url': snapshot.get('url'),
218
+ 'sha256': _sha256(snapshot), 'elements': len(snapshot.get('elements', []))})
219
+ if sr_transcript:
220
+ artifacts.append({'type': 'sr_transcript', 'url': sr_transcript.get('url'),
221
+ 'sha256': _sha256(sr_transcript), 'announcements': sr_transcript.get('total', 0),
222
+ 'linearized': sr_transcript.get('announcements', [])[:50]})
223
+
224
+ pack = {
225
+ 'format': 'a11y-evidence-pack/2',
226
+ 'lang': language,
227
+ 'generated': now,
228
+ 'tool': 'a11y-toolkit (github.com/kinti/a11y-toolkit)',
229
+ 'summary': summary,
230
+ 'effort_pending': pending_effort,
231
+ 'criteria': matrix,
232
+ 'manual_pending': [m['criterion'] for m in matrix if m['status'] == 'manual-only'],
233
+ 'verification': ({'source': 'agent', 'protocol': 'skill manual checklist'}
234
+ if verified else None),
235
+ 'artifacts': artifacts,
236
+ 'reviewer': { # bloque a completar por la persona que firma
237
+ 'name': (reviewer or {}).get('name'),
238
+ 'credential': (reviewer or {}).get('credential'),
239
+ 'review_date': (reviewer or {}).get('review_date'),
240
+ 'statement': None,
241
+ 'note': tx['reviewer_note'],
242
+ },
243
+ 'notes': notes,
244
+ 'notice': tx['notice'],
245
+ }
246
+ # the seal excludes sha256 AND the clock ('generated'): re-emitting the
247
+ # same evidence later MUST produce the same sha (re-emission, not a new row)
248
+ pack['sha256'] = _sha256({k: v for k, v in pack.items()
249
+ if k not in ('sha256', 'generated')})
250
+ return pack
251
+
252
+
253
+ def main(argv):
254
+ ap = argparse.ArgumentParser(description='Evidence pack (verifiable handoff)')
255
+ ap.add_argument('reports', nargs='+', help='audit report JSON files (any mode)')
256
+ ap.add_argument('--snapshot', help='a11y snapshot JSON (optional)')
257
+ ap.add_argument('--reviewer', help='JSON: {"name":…, "credential":…, "review_date":…}')
258
+ ap.add_argument('-o', '--out', default='evidence-pack.json')
259
+ a = ap.parse_args(argv)
260
+ reports = [json.load(open(f, encoding='utf-8')) for f in a.reports]
261
+ snapshot = json.load(open(a.snapshot, encoding='utf-8')) if a.snapshot else None
262
+ reviewer = json.loads(a.reviewer) if a.reviewer else None
263
+ pack = build_pack(reports, snapshot=snapshot, reviewer=reviewer)
264
+ with open(a.out, 'w', encoding='utf-8') as f:
265
+ json.dump(pack, f, ensure_ascii=False, indent=1)
266
+ print(json.dumps({'pack': a.out, 'sha256': pack['sha256'],
267
+ 'summary': pack['summary']}, ensure_ascii=False))
268
+ return 0
269
+
270
+
271
+ if __name__ == '__main__':
272
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,330 @@
1
+ #!/usr/bin/env python3
2
+ """Deterministic autofix — ONLY provably safe corrections.
3
+
4
+ The industry lesson (overlay vendors, the accessiBe FTC fine): fixing
5
+ accessibility by injecting guesses ends in fines. This module does the
6
+ opposite: a short closed list of transformations where the correct fix is
7
+ UNIQUE and verifiable, and for everything else an honest "not touched —
8
+ here is what it would take".
9
+
10
+ Transformations (closed, auditable list):
11
+ 1. viewport — removes user-scalable=no/0 and maximum-scale<2 (1.4.4).
12
+ 2. autocomplete — adds the deterministic token to inputs that require it
13
+ (1.3.5): type=email→email, tel→tel, url→url, and name/id
14
+ matching the personal-data pattern (name, postal-code…).
15
+ 3. <html> lang — ONLY if missing and the caller provides --lang.
16
+ 4. empty <title> — ONLY if the caller provides --title.
17
+
18
+ Everything else (alt, contrast, accessible names…) requires human or agent
19
+ judgment: listed under "no_aplicados" with the remediation.
20
+
21
+ CLI:
22
+ a11yfix.py --file page.html [--lang es] [--title "T"] [-o fixed.html]
23
+ """
24
+
25
+ import argparse
26
+ import html as _html
27
+ import json
28
+ import re
29
+ import sys
30
+
31
+ from .a11yaudit import audit_html, _PERSONAL_DATA
32
+
33
+ from . import a11yi18n
34
+ # token autocomplete por type de input (determinista por especificación)
35
+ _TOKEN_BY_TYPE = {'email': 'email', 'tel': 'tel', 'url': 'url'}
36
+ # token por pista de name/id (mismas pistas que usa el auditor 1.3.5)
37
+ _TOKEN_BY_HINT = [
38
+ (re.compile(r'postal|zip|cp\b', re.I), 'postal-code'),
39
+ (re.compile(r'street|direccion|address|calle', re.I), 'street-address'),
40
+ (re.compile(r'ciudad|city', re.I), 'address-level2'),
41
+ (re.compile(r'country|pais', re.I), 'country-name'),
42
+ (re.compile(r'organi[sz]ation|company|empresa', re.I), 'organization'),
43
+ (re.compile(r'phone|telefono|tel\b', re.I), 'tel'),
44
+ (re.compile(r'email|correo', re.I), 'email'),
45
+ (re.compile(r'(?:^|[\W_])(?:full)?name|nombre', re.I), 'name'),
46
+ ]
47
+
48
+ _RE_FORM = re.compile(r'<form\b[^>]*>', re.I)
49
+ _RE_TAG_Q = r'(?:[^>\"\']|\"[^\"]*\"|\'[^\']*\')*'
50
+ _RE_FIELD = re.compile(r'<input' + _RE_TAG_Q + r'>|<(select|textarea)' + _RE_TAG_Q + r'>.*?</\1\s*>', re.I | re.S)
51
+ _RE_SCRIPTS = re.compile(r'<script\b.*?</script>', re.S | re.I)
52
+ _RE_FORM_BLOCK = re.compile(r'<form\b.*?</form>', re.S | re.I)
53
+
54
+ _PHRASES = a11yi18n.pair('fix') # locales/<lang>.json — community-editable
55
+
56
+ _JS_PHRASES = """<script>
57
+ (function(){
58
+ var F = {req:%(req)s,email:%(email)s,url:%(url)s,num:%(num)s,between:%(between)s,short:%(short)s,pattern:%(pattern)s};
59
+ function sug(el){var v=el.validity;if(!v)return '';
60
+ if(v.valueMissing)return F.req;
61
+ if(v.typeMismatch){if(el.type==='email')return F.email;if(el.type==='url')return F.url;if(el.type==='number')return F.num;}
62
+ if(v.rangeUnderflow||v.rangeOverflow)return F.between.replace('%%a',el.min).replace('%%b',el.max);
63
+ if(v.tooShort)return F.short.replace('%%n',el.minLength);
64
+ if(v.patternMismatch)return el.pattern?F.pattern.replace('%%p',el.pattern):F.req;
65
+ return '';}
66
+ document.querySelectorAll('form[data-a11yfx]').forEach(function(f){
67
+ f.noValidate=true;
68
+ f.addEventListener('submit',function(ev){
69
+ var first=null;
70
+ f.querySelectorAll('input,select,textarea').forEach(function(el){
71
+ var id=el.getAttribute('data-a11yfx-err'),msg=id?document.getElementById(id):null;
72
+ if(!el.checkValidity()){var t=sug(el)||el.validationMessage||'';
73
+ el.setAttribute('aria-invalid','true');
74
+ if(msg){msg.hidden=false;msg.textContent=t;}
75
+ if(!first)first=el;
76
+ }else{el.removeAttribute('aria-invalid');if(msg){msg.hidden=true;msg.textContent='';}}
77
+ });
78
+ if(first){ev.preventDefault();first.focus();}
79
+ });
80
+ f.addEventListener('input',function(ev){var el=ev.target;if(!el.getAttribute)return;
81
+ var id=el.getAttribute('data-a11yfx-err');if(!id)return;
82
+ if(el.checkValidity()){el.removeAttribute('aria-invalid');var m=document.getElementById(id);
83
+ if(m){m.hidden=true;m.textContent='';}}
84
+ });
85
+ });
86
+ })();
87
+ </script>"""
88
+
89
+ _RE_INPUT = re.compile(r'<input' + _RE_TAG_Q + r'>', re.I)
90
+ _RE_VIEWPORT = re.compile(r'(<meta\s[^>]*name=["\']viewport["\'][^>]*content=["\'])([^"\']*)(["\'])', re.I)
91
+ _RE_HTML_TAG = re.compile(r'<html\b([^>]*)>', re.I)
92
+ _RE_TITLE = re.compile(r'<title>\s*</title>', re.I)
93
+
94
+
95
+ def _attrs(tag_html):
96
+ out = {}
97
+ for m in re.finditer(
98
+ r'([\w-]+)\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s>]+))', tag_html):
99
+ dbl, sgl, bare = m.group(2), m.group(3), m.group(4)
100
+ out[m.group(1)] = dbl if dbl is not None else (sgl if sgl is not None else bare)
101
+ return out
102
+
103
+
104
+ def _clean_viewport(content):
105
+ parts = [p.strip() for p in content.split(',') if p.strip()]
106
+ removed = []
107
+ clean = []
108
+ for p in parts:
109
+ if re.match(r'user-scalable\s*=\s*(no|0)', p, re.I):
110
+ removed.append(p)
111
+ continue
112
+ m = re.match(r'maximum-scale\s*=\s*([\d.]+)', p, re.I)
113
+ if m and float(m.group(1)) < 2:
114
+ removed.append(p)
115
+ continue
116
+ clean.append(p)
117
+ return ', '.join(clean), removed
118
+
119
+
120
+ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
121
+ """Aplica los arreglos seguros. Devuelve fixed_html + aplicados + no_aplicados."""
122
+ applied = []
123
+ fixed = html_text
124
+
125
+ # 0. máscara REAL: el contenido de script/style/textarea y los comentarios
126
+ # no son marcado — ninguna regex de transformación debe verlo. Sin este
127
+ # paso, el "no toco scripts" era falso (revisión externa, ronda 2).
128
+ _masks = []
129
+
130
+ def _mask(text):
131
+ def _pon(m):
132
+ tok = '\x00A11YFXMASK%d\x00' % len(_masks)
133
+ _masks.append((tok, m.group(0)))
134
+ return tok
135
+ text = re.sub(r'<script\b[^>]*>.*?</script\s*>', _pon, text, flags=re.I | re.S)
136
+ text = re.sub(r'<style\b[^>]*>.*?</style\s*>', _pon, text, flags=re.I | re.S)
137
+ # textarea NO se enmascara: la capa de error se inserta tras su cierre
138
+ # (5.2.1) y el contenido queda intacto; ocultarlo quitaría el 3.3.1
139
+ text = re.sub(r'<!--.*?-->', _pon, text, flags=re.S)
140
+ return text
141
+
142
+ def _unmask(text):
143
+ for tok, original in _masks:
144
+ text = text.replace(tok, original)
145
+ return text
146
+
147
+ fixed = _mask(fixed)
148
+
149
+ # 1. viewport: zoom sin bloqueos (1.4.4)
150
+ m = _RE_VIEWPORT.search(fixed)
151
+ if m and (re.search(r'user-scalable\s*=\s*(no|0)', m.group(2), re.I)
152
+ or re.search(r'maximum-scale\s*=\s*([\d.]+)', m.group(2), re.I)):
153
+ clean, removed = _clean_viewport(m.group(2))
154
+ if clean:
155
+ fixed = fixed[:m.start()] + m.group(1) + clean + m.group(3) + fixed[m.end():]
156
+ else:
157
+ # eliminar el meta COMPLETO: escanear el final de etiqueta
158
+ # respetando comillas (un `>` dentro de value= no cierra el tag)
159
+ end = m.end()
160
+ q = None
161
+ while end < len(fixed):
162
+ ch = fixed[end]
163
+ if q:
164
+ if ch == q:
165
+ q = None
166
+ elif ch in ('"', "'"):
167
+ q = ch
168
+ elif ch == '>':
169
+ break
170
+ end += 1
171
+ fixed = fixed[:m.start()] + (fixed[end + 1:] if end < len(fixed) else '')
172
+ applied.append({'signal': 'zoom_no',
173
+ 'fix': f'viewport without {", ".join(removed)} (1.4.4: zoom no longer blocked)'})
174
+
175
+ # 2. autocomplete determinista (1.3.5)
176
+ n_ac = 0
177
+
178
+ def _input_fix(mtag):
179
+ nonlocal n_ac
180
+ tag = mtag.group(0)
181
+ if 'autocomplete' in tag.lower():
182
+ return tag
183
+ a = _attrs(tag)
184
+ kind = (a.get('type') or 'text').lower()
185
+ token = _TOKEN_BY_TYPE.get(kind)
186
+ if not token:
187
+ hint = (a.get('name') or '') + ' ' + (a.get('id') or '')
188
+ if kind in ('search', 'password'):
189
+ return tag
190
+ for rx, tok in _TOKEN_BY_HINT:
191
+ if rx.search(hint):
192
+ token = tok
193
+ break
194
+ if not token:
195
+ return tag
196
+ n_ac += 1
197
+ return tag[:-1].rstrip() + f' autocomplete="{token}">'
198
+ fixed = _RE_INPUT.sub(_input_fix, fixed)
199
+ if n_ac:
200
+ applied.append({'signal': 'autocomplete',
201
+ 'fix': f'{n_ac} inputs with their autocomplete token (1.3.5)'})
202
+
203
+ # 3. lang de <html> (solo si falta y lo dan); BCP-47 validado y escapado:
204
+ # este toolkit ESCRIBE HTML, no puede ser vector de inyección
205
+ if lang and re.fullmatch(r'[a-zA-Z]{2,3}(-[a-zA-Z0-9]{2,8})*', lang.strip()):
206
+ m = _RE_HTML_TAG.search(fixed)
207
+ if m and 'lang=' not in m.group(1).lower():
208
+ fixed = fixed[:m.start()] + f'<html lang="{_html.escape(lang.strip())}"' + m.group(1) + '>' + fixed[m.end():]
209
+ applied.append({'signal': 'lang_missing',
210
+ 'fix': f'<html lang="{lang.strip()}"> added (3.1.1)'})
211
+
212
+ # 4. title (solo si vacío y lo dan); escapado por la misma razón
213
+ if title and _RE_TITLE.search(fixed):
214
+ fixed = _RE_TITLE.sub(lambda _m: f'<title>{_html.escape(title)}</title>', fixed, count=1)
215
+ applied.append({'signal': 'title_missing', 'fix': '<title> added (2.4.2)'})
216
+
217
+ # 4b. form errors: accessible error layer (3.3.1 + 3.3.3 from attributes)
218
+ if form_errors and 'a11yfx' not in fixed:
219
+ scripts = _RE_SCRIPTS.findall(fixed)
220
+ if not any(('aria-invalid' in s or 'setCustomValidity' in s) for s in scripts):
221
+ import json as _json
222
+ state = {'forms': 0, 'fields': 0}
223
+
224
+ def _input_type(tag):
225
+ m = re.search(r'type=["\']([\w-]+)', tag, re.I)
226
+ return m.group(1).lower() if m else ''
227
+
228
+ def _validable(tag):
229
+ kind = _input_type(tag)
230
+ if re.search(r'\b(required|pattern|minlength)\b|\bmin\s*=', tag, re.I):
231
+ return True
232
+ return kind in ('email', 'url', 'number', 'tel', 'date', 'time',
233
+ 'datetime-local', 'month', 'week')
234
+
235
+ def _process_field(elem):
236
+ if 'data-a11yfx-err' in elem or not _validable(elem):
237
+ return elem
238
+ state['fields'] += 1
239
+ fid = "a11yfx-e-%d-%d" % (state['forms'], state['fields'])
240
+ opening = re.match(r'<[a-zA-Z]+(?:[^>"\']|"[^"]*"|\'[^\']*\')*>', elem).group(0)
241
+ mdb = re.search(r'aria-describedby=["\']([^"\']*)["\']', opening, re.I)
242
+ if mdb: # merge, preserving the existing reference
243
+ new = 'aria-describedby="%s %s"' % (mdb.group(1), fid)
244
+ opening = opening[:mdb.start()] + new + opening[mdb.end():]
245
+ opening = opening[:-1] + ' data-a11yfx-err="%s">' % fid
246
+ else:
247
+ opening = opening[:-1] + ' data-a11yfx-err="%s" aria-describedby="%s">' % (fid, fid)
248
+ layer = '\n<p class="a11yfx-err" id="%s" hidden></p>' % fid
249
+ if opening.lower().startswith(('<textarea', '<select')):
250
+ # content-bearing element: the layer goes AFTER the close,
251
+ # never inside (inside would become its value — a real
252
+ # data-corruption regression, caught in external review)
253
+ return elem.replace(re.match(r'<[^>]*>', elem).group(0), opening, 1) + layer
254
+ return opening + layer
255
+
256
+ def _own_handling(atrs_form):
257
+ m = re.search(r'onsubmit=["\']([^"\']*)', atrs_form, re.I)
258
+ if not m:
259
+ return False
260
+ body = m.group(1).strip().lower()
261
+ # a pure navigation guard is NOT error handling — common fixture/SPA pattern
262
+ return body not in ('return false', 'return!1', 'return !1')
263
+
264
+ def _process_block(mb):
265
+ block = mb.group(0)
266
+ opening = re.match(r'<form\b[^>]*>', block, re.I).group(0)
267
+ if 'data-a11yfx' in opening or _own_handling(opening):
268
+ return block # custom error handling present: never fight it
269
+ state['forms'] += 1
270
+ rest = block[len(opening):]
271
+ rest = _RE_FIELD.sub(lambda mc: _process_field(mc.group(0)), rest)
272
+ return opening[:-1] + ' data-a11yfx>' + rest
273
+
274
+ fixed = _RE_FORM_BLOCK.sub(_process_block, fixed)
275
+ if state['fields']:
276
+ fr = _PHRASES.get(lang, _PHRASES['en'])
277
+ js = _JS_PHRASES % {k: _json.dumps(v) for k, v in fr.items()}
278
+ fixed = fixed.replace('</body>', js + '\n</body>', 1)
279
+ applied.append({'signal': 'form_error_missing',
280
+ 'fix': f"accessible error layer on {state['forms']} form(s), "
281
+ f"{state['fields']} field(s) — 3.3.1 identification + "
282
+ f"3.3.3 attribute-derived suggestions"})
283
+
284
+ # 5. lo que NO se toca — honestidad operativa
285
+ report = audit_html(html_text, url, lang='en')
286
+ do_not_touch = {
287
+ 'img_no_alt': 'we cannot know if the image is decorative: alt="" vs descriptive is a human call',
288
+ 'ctrl_name': 'the accessible name requires knowing what the control does',
289
+ 'field_label': 'the label text is dictated by the content',
290
+ 'contrast_fail': 'picking the new color is a design decision (use a11y_suggest_color)',
291
+ 'target_small': 'needs a layout redesign',
292
+ 'list_structure': 'rebuilding the markup requires understanding the structure',
293
+ }
294
+ already = {a['signal'] for a in applied}
295
+ not_applied = []
296
+ seen = set()
297
+ for h in report.get('findings', []):
298
+ signal = h['signal']
299
+ if signal in do_not_touch and signal not in seen and signal not in already:
300
+ seen.add(signal)
301
+ not_applied.append({'signal': signal, 'criterion': h['criterion'],
302
+ 'why_not': do_not_touch[signal],
303
+ 'remediation': h['remediation']})
304
+
305
+ fixed = _unmask(fixed)
306
+ return {'fixed_html': fixed, 'applied': applied, 'not_applied': not_applied}
307
+
308
+
309
+ def main(argv):
310
+ ap = argparse.ArgumentParser(description=__doc__)
311
+ ap.add_argument('--file', required=True)
312
+ ap.add_argument('--lang', choices=['es', 'en', 'pt', 'fr', 'de', 'it', 'gl', 'ca', 'eu'])
313
+ ap.add_argument('--title')
314
+ ap.add_argument('-o', '--out')
315
+ a = ap.parse_args(argv)
316
+ with open(a.file, encoding='utf-8', errors='replace') as f:
317
+ html_text = f.read()
318
+ res = autofix(html_text, lang=a.lang, title=a.title, url=a.file)
319
+ if a.out:
320
+ with open(a.out, 'w', encoding='utf-8') as f:
321
+ f.write(res['fixed_html'])
322
+ print(json.dumps({'file': a.out, 'applied': res['applied'],
323
+ 'not_applied': res['not_applied']}, ensure_ascii=False, indent=1))
324
+ else:
325
+ print(res['fixed_html'])
326
+ return 0
327
+
328
+
329
+ if __name__ == '__main__':
330
+ sys.exit(main(sys.argv[1:]))