@kinti/a11y-toolkit 5.30.0 → 5.32.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.
@@ -6,7 +6,7 @@ the auditor now stamps every finding it can with `paths` (deterministic CSS
6
6
  routes computed during the parse: tag:nth-of-type(n) from the root — ids are
7
7
  ignored on purpose, duplicate ids cannot break identity), and
8
8
  `annotate(html, report)` re-parses the SAME html with the SAME route
9
- algorithm (shared: VOID_TAGS / path_segment from a11yaudit) to inject
9
+ algorithm (shared with a11yaudit) to inject
10
10
  `data-a11y-id="mN"` attributes at byte-exact positions — offset surgery,
11
11
  the rest of the document is preserved byte for byte.
12
12
 
@@ -29,10 +29,13 @@ CLI:
29
29
 
30
30
  import argparse
31
31
  import json
32
+ import re
32
33
  import sys
33
34
  from html.parser import HTMLParser
34
35
 
35
- from .a11yaudit import VOID_TAGS, path_segment
36
+ from .a11yaudit import _ElementPaths
37
+
38
+ _DIRECT_TABLE_ROW = re.compile(r'(?:^|>)table:nth-of-type\(\d+\)>tr:nth-of-type\(')
36
39
 
37
40
  # nota de mismatch, bilingüe (mismo patrón que _labels en a11yaudit):
38
41
  # annotate no tiene idioma propio — 'en' por defecto, idioma explícito opcional
@@ -51,11 +54,13 @@ class _Locator(HTMLParser):
51
54
  byte offset where an attribute could be injected (right after the tag
52
55
  name). Same route algorithm as the auditor → same routes → exact match."""
53
56
 
54
- def __init__(self):
57
+ def __init__(self, html_text, implicit_tbody=True):
55
58
  super().__init__(convert_charrefs=True)
56
- self.route_offset = {} # path → insertion offset
59
+ self.route_offset = {} # path index → insertion offset
57
60
  self._line_starts = None # built lazily at feed()
58
- self._stack = [] # mirrors the auditor's path stack
61
+ self._paths = _ElementPaths(implicit_tbody)
62
+ self.feed(html_text)
63
+ self.close()
59
64
 
60
65
  def feed(self, data):
61
66
  lines = data.split('\n')
@@ -68,30 +73,19 @@ class _Locator(HTMLParser):
68
73
 
69
74
  def handle_starttag(self, tag, attrs):
70
75
  pos = self.getpos() # (line, col) — 1-based line
71
- if self._stack:
72
- parent = self._stack[-1]
73
- parent[2][tag] = parent[2].get(tag, 0) + 1
74
- path = parent[1] + '>' + path_segment(tag, parent[2][tag])
75
- else:
76
- path = path_segment(tag, 1)
77
76
  # offset absoluto del '<' + largo de "<tag" → punto de inyección
78
77
  try:
79
78
  abs_off = self._line_starts[pos[0] - 1] + pos[1]
80
79
  except IndexError:
81
80
  return
82
- self.route_offset[path] = abs_off + 1 + len(tag)
83
- if tag not in VOID_TAGS:
84
- self._stack.append((tag, path, {}))
81
+ self.route_offset[self._paths.start(tag)] = abs_off + 1 + len(tag)
85
82
 
86
83
  def handle_endtag(self, tag):
87
- if self._stack:
88
- if self._stack[-1][0] == tag:
89
- self._stack.pop()
90
- else:
91
- for i in range(len(self._stack) - 1, -1, -1):
92
- if self._stack[i][0] == tag:
93
- del self._stack[i:]
94
- break
84
+ self._paths.end(tag)
85
+
86
+ def insertion_offset(self, path):
87
+ if isinstance(path, str):
88
+ return self.route_offset.get(self._paths.lookup(path))
95
89
 
96
90
 
97
91
  def annotate(html_text, report, lang='en'):
@@ -108,15 +102,6 @@ def annotate(html_text, report, lang='en'):
108
102
  mismatch = bool(src_hash) and src_hash != hashlib.sha256(
109
103
  html_text.encode('utf-8', 'replace')).hexdigest()
110
104
 
111
- loc = _Locator()
112
- try:
113
- loc.feed(html_text)
114
- loc.close()
115
- except Exception: # noqa: BLE001 — html hostil: sin marcas, sin caída
116
- return {'annotated_html': html_text, 'marks': [],
117
- 'unplaced': [{'criterion': h.get('criterion'), 'signal': h.get('signal')}
118
- for h in report.get('findings', []) if isinstance(h, dict)]}
119
-
120
105
  findings = [h for h in report.get('findings', []) if isinstance(h, dict)]
121
106
  if mismatch:
122
107
  # la puerta del docstring: un informe de OTRO html jamás se inyecta
@@ -126,21 +111,31 @@ def annotate(html_text, report, lang='en'):
126
111
  'source_mismatch': True,
127
112
  'note': _NOTES.get(lang, _NOTES['en'])}
128
113
 
129
- marks, unplaced, injections = [], [], [] # injections: (offset, id)
114
+ try:
115
+ loc = _Locator(html_text)
116
+ except Exception: # noqa: BLE001 — html hostil: sin marcas, sin caída
117
+ return {'annotated_html': html_text, 'marks': [],
118
+ 'unplaced': [{'criterion': h.get('criterion'), 'signal': h.get('signal')}
119
+ for h in findings]}
120
+
121
+ marks, unplaced = [], []
122
+ legacy = None
130
123
  by_off = {} # offset → id ya asignado: dos findings sobre el MISMO
131
124
  # elemento comparten marca (dos data-a11y-id en el mismo
132
125
  # offset serían HTML inválido — el DOM descarta el segundo)
133
- n = 0
134
126
  for h in findings:
135
127
  did_place = False
136
128
  for path in (h.get('paths') or []):
137
- off = loc.route_offset.get(path)
129
+ off = loc.insertion_offset(path)
130
+ # Older reports use a direct table>tr path for implicit tbody.
131
+ if off is None and isinstance(path, str) and _DIRECT_TABLE_ROW.search(path):
132
+ if legacy is None:
133
+ legacy = _Locator(html_text, implicit_tbody=False)
134
+ off = legacy.insertion_offset(path)
138
135
  if off is None:
139
136
  continue
140
137
  if off not in by_off:
141
- n += 1
142
- by_off[off] = f'm{n}'
143
- injections.append((off, by_off[off]))
138
+ by_off[off] = f'm{len(by_off) + 1}'
144
139
  marks.append({'id': by_off[off], 'path': path,
145
140
  'criterion': h.get('criterion'), 'severity': h.get('severity'),
146
141
  'signal': h.get('signal')})
@@ -148,11 +143,13 @@ def annotate(html_text, report, lang='en'):
148
143
  if not did_place:
149
144
  unplaced.append({'criterion': h.get('criterion'), 'signal': h.get('signal')})
150
145
 
151
- # cirugía por offsets, en orden DESCENDENTE para no invalidar posiciones
152
- out = html_text
153
- for off, mid in sorted(injections, key=lambda x: -x[0]):
154
- out = out[:off] + f' data-a11y-id="{mid}"' + out[off:]
155
- return {'annotated_html': out, 'marks': marks,
146
+ parts = []
147
+ start = 0
148
+ for off, mid in sorted(by_off.items()):
149
+ parts.extend((html_text[start:off], f' data-a11y-id="{mid}"'))
150
+ start = off
151
+ parts.append(html_text[start:])
152
+ return {'annotated_html': ''.join(parts), 'marks': marks,
156
153
  'unplaced': unplaced, 'source_mismatch': mismatch}
157
154
 
158
155