@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
@@ -0,0 +1,154 @@
1
+ #!/usr/bin/env python3
2
+ """a11y_patches — the sealed record of an autofix run: what changed, on what
3
+ page, reproducible or stale.
4
+
5
+ The doctrine this serves: fixing the ORIGINAL web is the client's job (their
6
+ agent, their CI, their credentials). The engine never touches the real web;
7
+ what it hands over is a patch-set — a versioned, sha-keyed artifact listing
8
+ the deterministic fixes that were applied to a copy, so anyone can repeat
9
+ them upstream and PROVE they did the right thing.
10
+
11
+ The honesty rules, same as everywhere:
12
+ - A patch-set is keyed by the source page's SHA-256. Hand it a different
13
+ page and it declares itself `stale` — patches never blind-apply.
14
+ - `verify` re-runs the deterministic autofix and cross-checks: same engine,
15
+ same page → the same fixes must reproduce, patch for patch. Anything else
16
+ is reported as a mismatch, never silently accepted.
17
+ - Fixes that autofix declined to apply travel in the set too (`not_applied`),
18
+ so the record matches the run.
19
+
20
+ Artifact (format a11y-patches/1):
21
+ {'format': 'a11y-patches/1', 'source_sha256': str, 'engine_version': str,
22
+ 'created_at': iso8601, 'params': {lang, title, form_errors}, 'count': int,
23
+ 'fixes': [{signal, fix}, ...], 'not_applied': [{signal, criterion, ...}]}
24
+
25
+ `params` are SEALED in the set: `verify` repeats the autofix with exactly the
26
+ arguments of the build (an older set without `params` verifies with the build
27
+ defaults). Without them, every set carrying the form-error layer verified as
28
+ `mismatch` — the replay silently dropped lang/title/form_errors.
29
+
30
+ CLI:
31
+ a11ytoolkit patches --file page.html -o patches.json # build
32
+ a11ytoolkit patches --file page.html --verify patches.json # verify
33
+ """
34
+
35
+ import argparse
36
+ import datetime
37
+ import hashlib
38
+ import json
39
+ import sys
40
+
41
+ from .a11yfix import autofix as _autofix
42
+ from . import a11yi18n
43
+
44
+ FORMAT = 'a11y-patches/1'
45
+
46
+ T = a11yi18n.pair('patches')
47
+
48
+
49
+ def _t(lang, key):
50
+ return T.get(lang, T['en']).get(key, key)
51
+
52
+
53
+ def _sha(text):
54
+ return hashlib.sha256(text.encode('utf-8', 'replace')).hexdigest()
55
+
56
+
57
+ def build(html_text, lang=None, title=None, form_errors=True):
58
+ """Run the deterministic autofix once; return its sealed patch-set and
59
+ the fixed html. The record is a fact about this run, not a promise."""
60
+ from .server import VERSION # lazy: server importa este módulo arriba
61
+ res = _autofix(html_text, lang=lang, title=title, form_errors=form_errors)
62
+ patch_set = {
63
+ 'format': FORMAT,
64
+ 'source_sha256': _sha(html_text),
65
+ 'engine_version': VERSION,
66
+ 'created_at': datetime.datetime.now(
67
+ datetime.timezone.utc).isoformat(timespec='seconds'),
68
+ # params sellados: verify repite el autofix CON ESTOS argumentos
69
+ 'params': {'lang': lang, 'title': title, 'form_errors': form_errors},
70
+ 'count': len(res['applied']),
71
+ 'fixes': res['applied'],
72
+ 'not_applied': res['not_applied'],
73
+ }
74
+ return {'patch_set': patch_set, 'fixed_html': res['fixed_html'],
75
+ 'result': res}
76
+
77
+
78
+ def apply_patches(html_text, patch_set, lang='en'):
79
+ """Verify-and-repeat: the patch-set is reproduced on the SAME page.
80
+
81
+ Returns {'status': 'reproduced'|'stale'|'mismatch', ...}. `stale` means
82
+ the page is not the one the set was built from (sha mismatch) — the set
83
+ invalidates itself rather than blind-applying. `mismatch` means the same
84
+ page no longer produces the same fixes (engine drift or tampered set)."""
85
+ if not isinstance(patch_set, dict) or patch_set.get('format') != FORMAT:
86
+ return {'status': 'mismatch', 'note': _t(lang, 'pat_bad_format')}
87
+ sha = _sha(html_text)
88
+ if sha != patch_set.get('source_sha256'):
89
+ return {'status': 'stale', 'source_sha256': sha,
90
+ 'expected_sha256': patch_set.get('source_sha256'),
91
+ 'note': _t(lang, 'pat_stale')}
92
+ # replay with the SEALED build params (build defaults for pre-params sets):
93
+ # re-running with different arguments invents a mismatch that is not there
94
+ params = patch_set.get('params') or {}
95
+ res = _autofix(html_text,
96
+ lang=params.get('lang'),
97
+ title=params.get('title'),
98
+ form_errors=params.get('form_errors', True))
99
+ if res['applied'] != patch_set.get('fixes'):
100
+ return {'status': 'mismatch', 'source_sha256': sha,
101
+ 'reproduced': res['applied'],
102
+ 'recorded': patch_set.get('fixes'),
103
+ 'note': _t(lang, 'pat_mismatch')}
104
+ return {'status': 'reproduced', 'source_sha256': sha,
105
+ 'count': len(res['applied']), 'fixed_html': res['fixed_html'],
106
+ 'note': _t(lang, 'pat_reproduced')}
107
+
108
+
109
+ def main(argv):
110
+ ap = argparse.ArgumentParser(
111
+ description='Build or verify a sealed patch-set of deterministic fixes')
112
+ ap.add_argument('html_file', nargs='?', help='the HTML file')
113
+ ap.add_argument('--file', dest='html_opt', help='the HTML file (alt form)')
114
+ ap.add_argument('-o', '--out', help='write the patch-set JSON here (build)')
115
+ ap.add_argument('--verify', metavar='PATCHSET',
116
+ help='verify this patch-set against the HTML instead')
117
+ ap.add_argument('--fixed', dest='fixed_out',
118
+ help='write the fixed html here (build)')
119
+ ap.add_argument('--lang', default='en', choices=['es', 'en'])
120
+ a = ap.parse_args(argv)
121
+ path = a.html_file or a.html_opt
122
+ if not path:
123
+ ap.error('an HTML file is required (positional or --file)')
124
+ html_text = open(path, encoding='utf-8', errors='replace').read()
125
+ if a.verify:
126
+ patch_set = json.load(open(a.verify, encoding='utf-8'))
127
+ res = apply_patches(html_text, patch_set)
128
+ # JSON SIEMPRE válido: el fixed_html completo no se imprime (una
129
+ # salida cortada a [:2000] partía escapes y dejaba JSON roto) —
130
+ # quien quiera la copia arreglada usa --fixed
131
+ out = {k: v for k, v in res.items() if k != 'fixed_html'}
132
+ print(json.dumps(out, ensure_ascii=False, indent=1))
133
+ if a.fixed_out and res.get('status') == 'reproduced':
134
+ with open(a.fixed_out, 'w', encoding='utf-8') as f:
135
+ f.write(res['fixed_html'])
136
+ return 0 if res['status'] in ('reproduced', 'stale') else 1
137
+ res = build(html_text)
138
+ payload = json.dumps(res['patch_set'], ensure_ascii=False, indent=1)
139
+ if a.out:
140
+ with open(a.out, 'w', encoding='utf-8') as f:
141
+ f.write(payload)
142
+ print(json.dumps({'out': a.out, 'count': res['patch_set']['count'],
143
+ 'source_sha256': res['patch_set']['source_sha256']},
144
+ ensure_ascii=False))
145
+ else:
146
+ print(payload)
147
+ if a.fixed_out:
148
+ with open(a.fixed_out, 'w', encoding='utf-8') as f:
149
+ f.write(res['fixed_html'])
150
+ return 0
151
+
152
+
153
+ if __name__ == '__main__':
154
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,344 @@
1
+ #!/usr/bin/env python3
2
+ """a11y_patterns — APG keyboard contracts for high-risk ARIA widgets, tested live.
3
+
4
+ The deterministic piece of "screen-reader regression testing for web
5
+ components": detect the widget pattern in the rendered page and PROVE its
6
+ keyboard contract against the ARIA Authoring Practices Guide:
7
+
8
+ dialog / alertdialog Esc closes it; focus stays inside while open
9
+ (modal), focus returns after close
10
+ tablist ArrowRight/Left move focus between tabs (roving
11
+ tabindex); the tab becomes selected — by focus
12
+ (automatic) or by Enter/Space (manual)
13
+ disclosure activating the button FLIPS aria-expanded (the
14
+ state must be exposed, not just the visual)
15
+
16
+ Findings are family `pattern_*` with bilingual remediation. Honesty (what
17
+ v1 deliberately does NOT do): only patterns VISIBLE at load are tested —
18
+ opening a closed dialog means guessing a trigger flow (side effects on a
19
+ real site are never acceptable); nesting/corner cases (combobox, menu,
20
+ slider) are future operators, not silent gaps — this is a filter, not a
21
+ verdict.
22
+
23
+ CLI (infrastructure, not a tool — D17, like corpus/mutants/engines):
24
+ a11ypatterns.py https://web [--lang en] [-o report.json]
25
+ """
26
+
27
+ import argparse
28
+ import json
29
+ import sys
30
+ from datetime import datetime, timezone
31
+
32
+ from . import a11yi18n
33
+
34
+ _P = a11yi18n.pair('patterns') # locales/<lang>.json — community-editable
35
+
36
+ # patterns visibles en carga: dialogs abiertos, tablists, disclosures, combobox,
37
+ # menu buttons y sliders (widgets ARIA de alto riesgo, contratos APG v1+v2)
38
+ _COUNTS = r'''() => {
39
+ const vis = el => !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
40
+ return {
41
+ dialogs: [...document.querySelectorAll('[role=dialog], [role=alertdialog], dialog[open]')]
42
+ .filter(vis).length,
43
+ tablists: [...document.querySelectorAll('[role=tablist]')].filter(vis)
44
+ .map(l => l.querySelectorAll('[role=tab]').length),
45
+ disclosures: [...document.querySelectorAll('button[aria-expanded]:not([aria-haspopup="menu"]), [role=button][aria-expanded]:not([aria-haspopup="menu"])')]
46
+ .filter(vis).length,
47
+ comboboxes: [...document.querySelectorAll('[role=combobox]')].filter(vis).length,
48
+ menus: [...document.querySelectorAll('button[aria-haspopup="menu"], [role="button"][aria-haspopup="menu"]')]
49
+ .filter(vis).length,
50
+ sliders: [...document.querySelectorAll('[role="slider"]')].filter(vis).length,
51
+ };
52
+ }'''
53
+
54
+ _INSIDE = r'''() => {
55
+ const el = document.activeElement;
56
+ return !!el && !!el.closest('[role=dialog], [role=alertdialog], dialog');
57
+ }'''
58
+
59
+
60
+ def _finding(findings, lang, severity, criterion, key, **fmt):
61
+ cat = _P['es' if lang == 'es' else 'en']
62
+ findings.append({'severity': severity, 'criterion': criterion,
63
+ 'signal': key,
64
+ 'issue': cat[key].format(**fmt),
65
+ 'remediation': cat[key + '_rem']})
66
+
67
+
68
+ def _test_dialogs(page, findings, lang, cap=3):
69
+ """Visible dialogs: Esc closes; focus stays inside (modal); returns after."""
70
+ loc = page.locator('[role="dialog"]:visible, [role="alertdialog"]:visible, '
71
+ 'dialog[open]:visible')
72
+ n = min(loc.count(), cap)
73
+ for i in range(n):
74
+ d = loc.nth(i)
75
+ try:
76
+ d.evaluate('el => (el.querySelector("a[href],button,input,select,textarea,[tabindex]") '
77
+ '|| el).focus()')
78
+ except Exception: # noqa: BLE001
79
+ continue
80
+ is_modal = (d.get_attribute('aria-modal') or '').lower() == 'true'
81
+ if is_modal:
82
+ page.keyboard.press('Tab')
83
+ page.wait_for_timeout(120)
84
+ try:
85
+ inside = page.evaluate(_INSIDE)
86
+ except Exception: # noqa: BLE001
87
+ inside = True
88
+ if not inside:
89
+ _finding(findings, lang, 'medium', '2.4.3', 'pattern_modal_focus_escapes')
90
+ page.keyboard.press('Escape')
91
+ page.wait_for_timeout(250)
92
+ try:
93
+ still_open = d.is_visible()
94
+ except Exception: # noqa: BLE001
95
+ still_open = False
96
+ if still_open:
97
+ _finding(findings, lang, 'high', '2.1.2', 'pattern_dialog_esc_no_close')
98
+
99
+
100
+ def _test_tablists(page, findings, lang, cap=3):
101
+ """Visible tablists: arrows move focus (roving tabindex); activation follows."""
102
+ locs = page.locator('[role="tablist"]:visible')
103
+ n = min(locs.count(), cap)
104
+ for i in range(n):
105
+ tabs = locs.nth(i).locator('[role="tab"]')
106
+ total = tabs.count()
107
+ if total < 2:
108
+ continue
109
+ # APG tablist: horizontal usa Right/Left; VERTICAL (aria-orientation)
110
+ # prescribe Up/Down — acusar de HIGH una tablist vertical correcta era
111
+ # un FP. Se acepta que CUALQUIERA de las dos flechas mueva el foco
112
+ try:
113
+ tabs.nth(0).evaluate('el => el.focus()')
114
+ page.keyboard.press('ArrowRight')
115
+ page.wait_for_timeout(120)
116
+ is_second = page.evaluate(
117
+ '''(tab) => document.activeElement === tab''',
118
+ tabs.nth(1).element_handle())
119
+ if not is_second:
120
+ page.keyboard.press('ArrowDown')
121
+ page.wait_for_timeout(120)
122
+ is_second = page.evaluate(
123
+ '''(tab) => document.activeElement === tab''',
124
+ tabs.nth(1).element_handle())
125
+ if not is_second:
126
+ _finding(findings, lang, 'high', '2.1.1', 'pattern_tabs_arrows_dead',
127
+ n=total)
128
+ continue
129
+ # selección: automática (aria-selected sigue al foco) o manual
130
+ # (Enter/Space activa) — ninguna = estado expuesto muerto
131
+ if (tabs.nth(1).get_attribute('aria-selected') or '').lower() != 'true':
132
+ page.keyboard.press('Enter')
133
+ page.wait_for_timeout(150)
134
+ if (tabs.nth(1).get_attribute('aria-selected') or '').lower() != 'true':
135
+ page.keyboard.press(' ') # Space, la otra vía manual
136
+ page.wait_for_timeout(150)
137
+ if (tabs.nth(1).get_attribute('aria-selected') or '').lower() != 'true':
138
+ _finding(findings, lang, 'medium', '4.1.2',
139
+ 'pattern_tabs_no_activation')
140
+ except Exception: # noqa: BLE001 — un widget roto no debe matar el pase
141
+ continue
142
+
143
+
144
+ def _test_disclosures(page, findings, lang, cap=8):
145
+ """Disclosure buttons: activation must FLIP the exposed state.
146
+ Menu buttons are excluded — they are the menu pattern's subject."""
147
+ loc = page.locator('button[aria-expanded]:visible:not([aria-haspopup="menu"]), '
148
+ '[role="button"][aria-expanded]:visible:not([aria-haspopup="menu"])')
149
+ n = min(loc.count(), cap)
150
+ for i in range(n):
151
+ b = loc.nth(i)
152
+ try:
153
+ before = (b.get_attribute('aria-expanded') or '').lower()
154
+ name = ((b.get_attribute('aria-label') or '') or b.inner_text()
155
+ or 'disclosure').strip().replace('\n', ' ')[:40]
156
+ b.click()
157
+ page.wait_for_timeout(250)
158
+ after = (b.get_attribute('aria-expanded') or '').lower()
159
+ if before == after and before in ('true', 'false'):
160
+ _finding(findings, lang, 'medium', '4.1.2',
161
+ 'pattern_disclosure_state_frozen', name=name)
162
+ elif after in ('true', 'false') and after != before:
163
+ b.click() # dejar la página como estaba
164
+ page.wait_for_timeout(150)
165
+ except Exception: # noqa: BLE001
166
+ continue
167
+
168
+
169
+ def _visible_open(page, sel):
170
+ """Is a matching element visible right now?"""
171
+ try:
172
+ return page.locator(sel).first.is_visible()
173
+ except Exception: # noqa: BLE001
174
+ return False
175
+
176
+
177
+ def _test_comboboxes(page, findings, lang, cap=3):
178
+ """Comboboxes: activation opens the popup; Escape closes it."""
179
+ loc = page.locator('[role="combobox"]:visible')
180
+ n = min(loc.count(), cap)
181
+ for i in range(n):
182
+ c = loc.nth(i)
183
+ try:
184
+ c.evaluate('el => el.focus()')
185
+ before = (c.get_attribute('aria-expanded') or '').lower()
186
+ page.keyboard.press('ArrowDown')
187
+ page.wait_for_timeout(300)
188
+ after = (c.get_attribute('aria-expanded') or '').lower()
189
+ opened = after == 'true' or _visible_open(page, '[role="listbox"]:visible')
190
+ if not opened and before != 'true':
191
+ _finding(findings, lang, 'medium', '2.1.1', 'pattern_combobox_no_open')
192
+ continue
193
+ page.keyboard.press('Escape')
194
+ page.wait_for_timeout(250)
195
+ closed = (c.get_attribute('aria-expanded') or '').lower() != 'true' \
196
+ and not _visible_open(page, '[role="listbox"]:visible')
197
+ if not closed:
198
+ _finding(findings, lang, 'medium', '2.1.1', 'pattern_combobox_esc_no_close')
199
+ except Exception: # noqa: BLE001
200
+ continue
201
+
202
+
203
+ def _test_menu_buttons(page, findings, lang, cap=3):
204
+ """Menu buttons: activation opens the menu; Escape closes + refocuses."""
205
+ loc = page.locator('button[aria-haspopup="menu"]:visible, '
206
+ '[role="button"][aria-haspopup="menu"]:visible')
207
+ n = min(loc.count(), cap)
208
+ for i in range(n):
209
+ b = loc.nth(i)
210
+ try:
211
+ b.click()
212
+ page.wait_for_timeout(300)
213
+ opened = _visible_open(page, '[role="menu"]:visible') \
214
+ or (b.get_attribute('aria-expanded') or '').lower() == 'true'
215
+ if not opened:
216
+ _finding(findings, lang, 'medium', '2.1.1', 'pattern_menu_no_open')
217
+ continue
218
+ page.keyboard.press('Escape')
219
+ page.wait_for_timeout(250)
220
+ closed = not _visible_open(page, '[role="menu"]:visible') \
221
+ and (b.get_attribute('aria-expanded') or '').lower() != 'true'
222
+ if not closed:
223
+ _finding(findings, lang, 'medium', '2.1.1', 'pattern_menu_esc_no_close')
224
+ except Exception: # noqa: BLE001
225
+ continue
226
+
227
+
228
+ def _test_sliders(page, findings, lang, cap=3):
229
+ """Custom sliders: arrows change the value; the state trio must be exposed."""
230
+ loc = page.locator('[role="slider"]:visible')
231
+ n = min(loc.count(), cap)
232
+ for i in range(n):
233
+ s = loc.nth(i)
234
+ try:
235
+ has_state = all((s.get_attribute(a) or '').strip() not in ('', None)
236
+ for a in ('aria-valuenow', 'aria-valuemin', 'aria-valuemax'))
237
+ if not has_state:
238
+ _finding(findings, lang, 'medium', '4.1.2', 'pattern_slider_no_state',
239
+ name=((s.get_attribute('aria-label') or '') or 'slider')[:40])
240
+ now = (s.get_attribute('aria-valuenow') or '').strip()
241
+ s.evaluate('el => el.focus()')
242
+ page.keyboard.press('ArrowRight')
243
+ page.wait_for_timeout(150)
244
+ after_r = (s.get_attribute('aria-valuenow') or '').strip()
245
+ if after_r == now:
246
+ page.keyboard.press('ArrowUp')
247
+ page.wait_for_timeout(150)
248
+ after_up = (s.get_attribute('aria-valuenow') or '').strip()
249
+ if after_up == now:
250
+ _finding(findings, lang, 'high', '2.1.1', 'pattern_slider_arrows_dead')
251
+ continue
252
+ # devolver el valor original (dejar la página como estaba)
253
+ if now and (s.get_attribute('aria-valuenow') or '').strip() != now:
254
+ s.evaluate('(el, v) => el.setAttribute("aria-valuenow", v)', now)
255
+ except Exception: # noqa: BLE001
256
+ continue
257
+
258
+
259
+ def audit_patterns(url, timeout=45, lang='en', auth_state=None, browser='auto'):
260
+ """One url → widget patterns found + contract findings (filter, not verdict)."""
261
+ from playwright.sync_api import sync_playwright
262
+ from .a11ydom import _get_browser
263
+ lang = 'es' if lang == 'es' else 'en'
264
+ with sync_playwright() as p:
265
+ nav = _get_browser(p, preferred=browser)
266
+ ctx = nav.new_context(storage_state=auth_state) if auth_state else nav
267
+ page = ctx.new_page() if auth_state else nav.new_page()
268
+ try:
269
+ page.goto(url, wait_until='load', timeout=timeout * 1000)
270
+ page.wait_for_timeout(400)
271
+ except Exception as e: # noqa: BLE001
272
+ nav.close()
273
+ return {'error': f'could not load: {e}'}
274
+
275
+ counts = page.evaluate(_COUNTS)
276
+ findings = []
277
+ _test_dialogs(page, findings, lang)
278
+ _test_tablists(page, findings, lang)
279
+ _test_disclosures(page, findings, lang)
280
+ _test_comboboxes(page, findings, lang)
281
+ _test_menu_buttons(page, findings, lang)
282
+ _test_sliders(page, findings, lang)
283
+ nav.close()
284
+
285
+ limits = ('Only patterns VISIBLE at page load are tested: opening a closed '
286
+ 'dialog means guessing a trigger flow — never acceptable on a '
287
+ 'live site. Operators: dialog (Esc + modal containment), '
288
+ 'tablist (arrows + activation), disclosure (aria-expanded flips), '
289
+ 'combobox (opens + Esc closes), menu button (opens + Esc closes), '
290
+ 'slider (arrows change value + value trio exposed). A '
291
+ 'clean pass proves THESE contracts at THIS moment — not full '
292
+ 'APG conformance.'
293
+ if lang == 'en' else
294
+ 'Solo se prueban patrones VISIBLES en carga: abrir un diálogo '
295
+ 'cerrado exige adivinar un disparador — jamás aceptable en un '
296
+ 'sitio real. Operadores: dialog (Esc + contención modal), '
297
+ 'tablist (flechas + activación), disclosure (aria-expanded '
298
+ 'cambia), combobox (abre + Esc cierra), menu button (abre + Esc '
299
+ 'cierra), slider (flechas cambian el valor + trío de estado '
300
+ 'expuesto). Un pase limpio prueba ESTOS contratos en '
301
+ 'ESTE momento — no conformidad APG completa.')
302
+ return {'mode': 'patterns', 'url': url,
303
+ 'ts': datetime.now(timezone.utc).isoformat(),
304
+ 'patterns_seen': {'dialog': counts.get('dialogs', 0),
305
+ 'tablist': len(counts.get('tablists', [])),
306
+ 'tabs': sum(counts.get('tablists', [])),
307
+ 'disclosure': counts.get('disclosures', 0),
308
+ 'combobox': counts.get('comboboxes', 0),
309
+ 'menu': counts.get('menus', 0),
310
+ 'slider': counts.get('sliders', 0)},
311
+ 'findings': findings,
312
+ 'limits': limits}
313
+
314
+
315
+ def main(argv):
316
+ ap = argparse.ArgumentParser(description=__doc__)
317
+ ap.add_argument('url')
318
+ ap.add_argument('--lang', default='en', choices=['en', 'es'])
319
+ ap.add_argument('--timeout', type=int, default=45)
320
+ ap.add_argument('--auth-state', help='Playwright storage_state JSON (session)')
321
+ ap.add_argument('-o', '--out', help='write the report here (default: stdout)')
322
+ a = ap.parse_args(argv)
323
+ try:
324
+ res = audit_patterns(a.url, timeout=a.timeout, lang=a.lang,
325
+ auth_state=a.auth_state)
326
+ except ImportError:
327
+ print(json.dumps({'error': 'Playwright not installed: pip install '
328
+ 'playwright && playwright install chromium'}))
329
+ return 1
330
+ out = json.dumps(res, ensure_ascii=False, indent=1)
331
+ if a.out:
332
+ with open(a.out, 'w', encoding='utf-8') as f:
333
+ f.write(out + '\n')
334
+ print(json.dumps({'url': a.url,
335
+ 'patterns_seen': res.get('patterns_seen'),
336
+ 'findings': len(res.get('findings', [])),
337
+ 'out': a.out}, ensure_ascii=False))
338
+ else:
339
+ print(out)
340
+ return 1 if 'error' in res else 0
341
+
342
+
343
+ if __name__ == '__main__':
344
+ sys.exit(main(sys.argv[1:]))