statement-fetch 1.1.0__tar.gz → 1.2.0__tar.gz
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.
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/CHANGELOG.md +13 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/PKG-INFO +1 -1
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/pyproject.toml +1 -1
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/_contracts.py +1 -0
- statement_fetch-1.2.0/src/statement_fetch/_diagnostics.py +346 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/_playwright.py +246 -95
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/_runner.py +137 -6
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/_staging.py +14 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/cli.py +15 -1
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/tests/test_public_hygiene.py +1 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/uv.lock +1 -1
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/.github/workflows/ci.yml +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/.github/workflows/pypi.yml +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/.github/workflows/release.yml +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/.gitignore +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/CONTRIBUTING.md +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/LICENSE +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/Makefile +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/README.md +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/SECURITY.md +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/__init__.py +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/_registry.py +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/_validators.py +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/api.py +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/demo.py +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/providers/__init__.py +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/providers/example_bank.py +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/py.typed +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/sinks/__init__.py +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/src/statement_fetch/sinks/directory.py +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/tests/test_async_core_and_example.py +0 -0
- {statement_fetch-1.1.0 → statement_fetch-1.2.0}/tests/test_demo_e2e_playwright.py +0 -0
|
@@ -2,6 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.2.0] - 2026-12-05
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
- OSS-safe host-boundary diagnostics (`_diagnostics.py`, `FetchResult.diagnostics`, `Stage.note()`) with automatic breadcrumb recording (capped at 25 steps / 4 KiB) and strict URL/token/IBAN/path redaction.
|
|
9
|
+
- Opt-in local CLI `--debug-dir` flag for writing redacted failure diagnostic bundles and `-v`/`--verbose` log level control.
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
- Emitted `[provider] stage=...` progress markers to stderr even when `--json` is passed (unless `--quiet`).
|
|
13
|
+
|
|
14
|
+
### Upgrade
|
|
15
|
+
- Action required: none.
|
|
16
|
+
- Rollback: compatible with `v1.1.0`.
|
|
17
|
+
|
|
5
18
|
## [1.1.0] - 2026-12-05
|
|
6
19
|
|
|
7
20
|
### Changed
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: statement-fetch
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.2.0
|
|
4
4
|
Summary: Zero-LLM async fetcher, structural validator, and pluggable sink runner for statements, invoices, and documents from authenticated portals and apps.
|
|
5
5
|
Project-URL: Homepage, https://github.com/benjamin-di/statement-fetch-oss
|
|
6
6
|
Project-URL: Repository, https://github.com/benjamin-di/statement-fetch-oss
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "statement-fetch"
|
|
7
|
-
version = "1.
|
|
7
|
+
version = "1.2.0"
|
|
8
8
|
description = "Zero-LLM async fetcher, structural validator, and pluggable sink runner for statements, invoices, and documents from authenticated portals and apps."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "MIT"
|
|
@@ -587,6 +587,7 @@ class FetchResult:
|
|
|
587
587
|
skipped: tuple[dict[str, str], ...] = ()
|
|
588
588
|
errors: tuple[str, ...] = ()
|
|
589
589
|
timings_s: dict[str, float] = field(default_factory=dict)
|
|
590
|
+
diagnostics: dict[str, Any] = field(default_factory=dict)
|
|
590
591
|
|
|
591
592
|
@property
|
|
592
593
|
def ok(self) -> bool:
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
"""OSS-safe host-boundary diagnostics, URL/text redaction, and opt-in local debug bundles."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import time
|
|
9
|
+
from collections import deque
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
from urllib.parse import urlsplit
|
|
13
|
+
|
|
14
|
+
from ._staging import write_private_text_atomic
|
|
15
|
+
|
|
16
|
+
MAX_DIAGNOSTIC_STEPS = 25
|
|
17
|
+
MAX_DIAGNOSTIC_BYTES = 4096
|
|
18
|
+
MAX_REPORT_FIELD_CHARS = 200
|
|
19
|
+
|
|
20
|
+
_UUID_RE = re.compile(
|
|
21
|
+
r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
|
|
22
|
+
)
|
|
23
|
+
_SIX_DIGITS_RE = re.compile(r"\d{6,}")
|
|
24
|
+
_PURE_HEX_16_RE = re.compile(r"^[0-9a-fA-F]{16,}$")
|
|
25
|
+
_TOKEN_CHARS_RE = re.compile(r"^[A-Za-z0-9+/=_-]{16,}$")
|
|
26
|
+
_EMBEDDED_URL_RE = re.compile(r"https?://[^\s'\"<>]+", re.IGNORECASE)
|
|
27
|
+
_AUTH_HEADER_RE = re.compile(
|
|
28
|
+
r"""(?i)(?:"|')?authorization(?:"|')?\s*[:=]\s*(?:"|')?(?:bearer\s+|basic\s+)?[^\s,;\"'}\]]+(?:"|')?"""
|
|
29
|
+
)
|
|
30
|
+
_COOKIE_HEADER_RE = re.compile(r"""(?i)(?<![A-Za-z0-9_-])(?:"|')?(?:set-)?cookie(?:"|')?\s*[:=][^\r\n]+""")
|
|
31
|
+
_BEARER_RE = re.compile(r"(?i)\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+")
|
|
32
|
+
_SECRET_KV_RE = re.compile(
|
|
33
|
+
r"""(?i)(?:"|')?(\b[A-Za-z0-9_.-]*(?:password|passwd|secret|token|api[_-]?key|session[_-]?id|jsessionid))(?:"|')?\s*[:=]\s*(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;\"'}\]]+)"""
|
|
34
|
+
)
|
|
35
|
+
_IBAN_RE = re.compile(r"\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b")
|
|
36
|
+
_CARD_NUMBER_RE = re.compile(r"(?<!\d)(?:\d{4}[-\s]?){3}\d{4}(?!\d)")
|
|
37
|
+
_LONG_DIGITS_RE = re.compile(r"(?<!\d)\d{8,}(?!\d)")
|
|
38
|
+
_WIN_PATH_RE = re.compile(r"\b[A-Za-z]:[\\/][^\s\"'<>|;,]+")
|
|
39
|
+
_UNC_PATH_RE = re.compile(r"\\\\[^\s\"'<>|;,]+")
|
|
40
|
+
_POSIX_PATH_RE = re.compile(r"(?<!://)(?<![A-Za-z0-9_./}>-])/(?:[A-Za-z0-9._-]+/)+[A-Za-z0-9._-]*")
|
|
41
|
+
_SEMICOLON_PARAM_RE = re.compile(r";[^/\s?#]*")
|
|
42
|
+
|
|
43
|
+
# Text-stripped structural DOM skeleton for opt-in local `--debug-dir` captures.
|
|
44
|
+
# Deliberately omits innerText, textContent, input values, href query strings, and balances.
|
|
45
|
+
STRUCTURAL_DOM_SNAPSHOT_JS = """() => {
|
|
46
|
+
const MAX_NODES = 400;
|
|
47
|
+
const MAX_DEPTH = 14;
|
|
48
|
+
let count = 0;
|
|
49
|
+
const lines = [];
|
|
50
|
+
const keepAttrs = ['id', 'name', 'type', 'role', 'data-testid', 'aria-expanded', 'aria-selected', 'aria-disabled'];
|
|
51
|
+
function walk(el, depth) {
|
|
52
|
+
if (!el || count >= MAX_NODES || depth > MAX_DEPTH) return;
|
|
53
|
+
if (el.nodeType !== 1) return;
|
|
54
|
+
const tag = (el.tagName || '').toLowerCase();
|
|
55
|
+
if (tag === 'script' || tag === 'style' || tag === 'svg' || tag === 'noscript') return;
|
|
56
|
+
count += 1;
|
|
57
|
+
const parts = [tag];
|
|
58
|
+
for (const attr of keepAttrs) {
|
|
59
|
+
const val = el.getAttribute && el.getAttribute(attr);
|
|
60
|
+
if (val) {
|
|
61
|
+
const clean = String(val).replace(/\\s+/g, ' ').trim().slice(0, 48);
|
|
62
|
+
if (clean) parts.push(`${attr}=${clean}`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const cls = typeof el.className === 'string' ? el.className.trim().replace(/\\s+/g, '.').slice(0, 64) : '';
|
|
66
|
+
if (cls) parts.push(`.${cls}`);
|
|
67
|
+
if (el.disabled) parts.push('[disabled]');
|
|
68
|
+
if (el.hidden) parts.push('[hidden]');
|
|
69
|
+
lines.push(' '.repeat(depth) + parts.join(' '));
|
|
70
|
+
const children = el.children || [];
|
|
71
|
+
for (let i = 0; i < children.length && count < MAX_NODES; i += 1) {
|
|
72
|
+
walk(children[i], depth + 1);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
walk(document.body || document.documentElement, 0);
|
|
76
|
+
return lines.join('\\n');
|
|
77
|
+
}"""
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _looks_like_opaque_token(segment: str) -> bool:
|
|
81
|
+
if not segment:
|
|
82
|
+
return False
|
|
83
|
+
if _SIX_DIGITS_RE.search(segment):
|
|
84
|
+
return True
|
|
85
|
+
if _UUID_RE.fullmatch(segment):
|
|
86
|
+
return True
|
|
87
|
+
if _PURE_HEX_16_RE.fullmatch(segment):
|
|
88
|
+
return True
|
|
89
|
+
if len(segment) >= 16 and _TOKEN_CHARS_RE.fullmatch(segment):
|
|
90
|
+
has_digit = any(c.isdigit() for c in segment)
|
|
91
|
+
has_alpha = any(c.isalpha() for c in segment)
|
|
92
|
+
has_upper = any(c.isupper() for c in segment)
|
|
93
|
+
has_lower = any(c.islower() for c in segment)
|
|
94
|
+
if has_digit and has_alpha:
|
|
95
|
+
return True
|
|
96
|
+
if "=" in segment and (has_digit or has_upper):
|
|
97
|
+
return True
|
|
98
|
+
if has_upper and has_lower and "-" not in segment:
|
|
99
|
+
return True
|
|
100
|
+
return False
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def redact_url_host_path(url: str) -> str:
|
|
104
|
+
"""Return redacted `<host><path>` with `;params`, query, fragment, userinfo, and opaque ID segments stripped."""
|
|
105
|
+
raw = str(url or "").strip()
|
|
106
|
+
if not raw:
|
|
107
|
+
return ""
|
|
108
|
+
low = raw.lower()
|
|
109
|
+
if low.startswith("about:"):
|
|
110
|
+
return raw.split("?", 1)[0].split("#", 1)[0][:64]
|
|
111
|
+
if low.startswith(("data:", "blob:")):
|
|
112
|
+
return low.split(":", 1)[0] + ":"
|
|
113
|
+
try:
|
|
114
|
+
parts = urlsplit(raw)
|
|
115
|
+
except ValueError:
|
|
116
|
+
return redact_text(raw, max_len=120)
|
|
117
|
+
host = (parts.hostname or "").lower().rstrip(".")
|
|
118
|
+
raw_path = parts.path or ""
|
|
119
|
+
if raw_path:
|
|
120
|
+
raw_segs = raw_path.split("/")
|
|
121
|
+
clean_segs: list[str] = []
|
|
122
|
+
for seg in raw_segs:
|
|
123
|
+
# Strip matrix/session params such as ;jsessionid=...
|
|
124
|
+
base = seg.split(";", 1)[0]
|
|
125
|
+
if base and _looks_like_opaque_token(base):
|
|
126
|
+
clean_segs.append("{id}")
|
|
127
|
+
else:
|
|
128
|
+
clean_segs.append(base)
|
|
129
|
+
norm_path = "/".join(clean_segs)
|
|
130
|
+
if not norm_path.startswith("/"):
|
|
131
|
+
norm_path = "/" + norm_path
|
|
132
|
+
else:
|
|
133
|
+
norm_path = ""
|
|
134
|
+
if host:
|
|
135
|
+
return f"{host}{norm_path}"
|
|
136
|
+
return norm_path
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def redact_text(text: str, *, max_len: int = MAX_REPORT_FIELD_CHARS) -> str:
|
|
140
|
+
"""Collapse whitespace, redact URLs/tokens/IBANs/long numeric IDs, and cap length."""
|
|
141
|
+
raw = str(text or "")
|
|
142
|
+
if not raw:
|
|
143
|
+
return ""
|
|
144
|
+
collapsed = re.sub(r"[\x00-\x1f\x7f\s]+", " ", raw).strip()
|
|
145
|
+
if not collapsed:
|
|
146
|
+
return ""
|
|
147
|
+
collapsed = _AUTH_HEADER_RE.sub("Authorization=[redacted]", collapsed)
|
|
148
|
+
collapsed = _COOKIE_HEADER_RE.sub("Cookie=[redacted]", collapsed)
|
|
149
|
+
collapsed = _EMBEDDED_URL_RE.sub(lambda m: redact_url_host_path(m.group(0)), collapsed)
|
|
150
|
+
collapsed = _SEMICOLON_PARAM_RE.sub("", collapsed)
|
|
151
|
+
collapsed = _SECRET_KV_RE.sub(lambda m: f"{m.group(1)}=[redacted]", collapsed)
|
|
152
|
+
collapsed = _BEARER_RE.sub("[redacted]", collapsed)
|
|
153
|
+
collapsed = _IBAN_RE.sub("{iban}", collapsed)
|
|
154
|
+
collapsed = _CARD_NUMBER_RE.sub("{id}", collapsed)
|
|
155
|
+
collapsed = _LONG_DIGITS_RE.sub("{id}", collapsed)
|
|
156
|
+
collapsed = _WIN_PATH_RE.sub("[path]", collapsed)
|
|
157
|
+
collapsed = _UNC_PATH_RE.sub("[path]", collapsed)
|
|
158
|
+
collapsed = _POSIX_PATH_RE.sub("[path]", collapsed)
|
|
159
|
+
if max_len > 0 and len(collapsed) > max_len:
|
|
160
|
+
if max_len <= 1:
|
|
161
|
+
return collapsed[:max_len]
|
|
162
|
+
return collapsed[: max_len - 1] + "…"
|
|
163
|
+
return collapsed
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def configure_logging(
|
|
167
|
+
*,
|
|
168
|
+
level_name: str | None = None,
|
|
169
|
+
default_level: str = "WARNING",
|
|
170
|
+
loggers: tuple[str, ...] = ("statement-fetch",),
|
|
171
|
+
) -> str:
|
|
172
|
+
"""Configure stdlib logging for `statement-fetch` loggers and return the normalized lowercase level name."""
|
|
173
|
+
raw = (level_name or os.environ.get("STATEMENT_FETCH_LOG_LEVEL") or default_level).strip().upper()
|
|
174
|
+
valid = {
|
|
175
|
+
"DEBUG": logging.DEBUG,
|
|
176
|
+
"INFO": logging.INFO,
|
|
177
|
+
"WARNING": logging.WARNING,
|
|
178
|
+
"WARN": logging.WARNING,
|
|
179
|
+
"ERROR": logging.ERROR,
|
|
180
|
+
"CRITICAL": logging.CRITICAL,
|
|
181
|
+
}
|
|
182
|
+
numeric = valid.get(raw)
|
|
183
|
+
if numeric is None:
|
|
184
|
+
raw = default_level.strip().upper()
|
|
185
|
+
numeric = valid.get(raw, logging.WARNING)
|
|
186
|
+
if raw == "WARN":
|
|
187
|
+
raw = "WARNING"
|
|
188
|
+
|
|
189
|
+
root = logging.getLogger()
|
|
190
|
+
formatter = logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")
|
|
191
|
+
for name in loggers:
|
|
192
|
+
lg = logging.getLogger(name)
|
|
193
|
+
lg.setLevel(numeric)
|
|
194
|
+
if not lg.handlers and not root.handlers:
|
|
195
|
+
handler = logging.StreamHandler()
|
|
196
|
+
handler.setFormatter(formatter)
|
|
197
|
+
lg.addHandler(handler)
|
|
198
|
+
lg.propagate = False
|
|
199
|
+
return raw.lower()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class DiagnosticRecorder:
|
|
203
|
+
"""Bounded, OSS-safe breadcrumb recorder for host/session boundaries and stage transitions."""
|
|
204
|
+
|
|
205
|
+
def __init__(self, *, max_steps: int = MAX_DIAGNOSTIC_STEPS) -> None:
|
|
206
|
+
self.max_steps = max(1, int(max_steps))
|
|
207
|
+
self._t0 = time.monotonic()
|
|
208
|
+
self._steps: deque[dict[str, Any]] = deque(maxlen=self.max_steps)
|
|
209
|
+
self.last_stage: str = ""
|
|
210
|
+
self.url_host_path: str = ""
|
|
211
|
+
self.exc_type: str = ""
|
|
212
|
+
self.error_code: str = ""
|
|
213
|
+
|
|
214
|
+
def set_stage(self, stage: str) -> None:
|
|
215
|
+
cleaned = redact_text(stage, max_len=64)
|
|
216
|
+
if cleaned:
|
|
217
|
+
self.last_stage = cleaned
|
|
218
|
+
|
|
219
|
+
def set_url(self, url: str) -> None:
|
|
220
|
+
redacted = redact_url_host_path(url)
|
|
221
|
+
if redacted:
|
|
222
|
+
self.url_host_path = redacted[:MAX_REPORT_FIELD_CHARS]
|
|
223
|
+
|
|
224
|
+
def set_error(self, exc: BaseException | str, *, error_code: str = "") -> None:
|
|
225
|
+
if isinstance(exc, BaseException):
|
|
226
|
+
self.exc_type = redact_text(exc.__class__.__name__, max_len=80)
|
|
227
|
+
code = error_code or str(exc) or exc.__class__.__name__
|
|
228
|
+
else:
|
|
229
|
+
code = error_code or str(exc)
|
|
230
|
+
if code:
|
|
231
|
+
self.error_code = redact_text(code, max_len=MAX_REPORT_FIELD_CHARS)
|
|
232
|
+
|
|
233
|
+
def record(
|
|
234
|
+
self,
|
|
235
|
+
action: str,
|
|
236
|
+
*,
|
|
237
|
+
detail: str = "",
|
|
238
|
+
ok: bool = True,
|
|
239
|
+
duration_ms: int | None = None,
|
|
240
|
+
url: str = "",
|
|
241
|
+
) -> None:
|
|
242
|
+
if url:
|
|
243
|
+
self.set_url(url)
|
|
244
|
+
entry: dict[str, Any] = {
|
|
245
|
+
"t_ms": max(0, round((time.monotonic() - self._t0) * 1000)),
|
|
246
|
+
"action": redact_text(action, max_len=64) or "step",
|
|
247
|
+
}
|
|
248
|
+
if detail:
|
|
249
|
+
clean_detail = redact_text(detail, max_len=160)
|
|
250
|
+
if clean_detail:
|
|
251
|
+
entry["detail"] = clean_detail
|
|
252
|
+
if not ok:
|
|
253
|
+
entry["ok"] = False
|
|
254
|
+
if duration_ms is not None:
|
|
255
|
+
entry["ms"] = max(0, int(duration_ms))
|
|
256
|
+
self._steps.append(entry)
|
|
257
|
+
|
|
258
|
+
def last_step_summary(self) -> str:
|
|
259
|
+
if not self._steps:
|
|
260
|
+
return ""
|
|
261
|
+
last = self._steps[-1]
|
|
262
|
+
action = str(last.get("action") or "")
|
|
263
|
+
detail = str(last.get("detail") or "")
|
|
264
|
+
text = f"{action}: {detail}" if detail else action
|
|
265
|
+
return redact_text(text, max_len=MAX_REPORT_FIELD_CHARS)
|
|
266
|
+
|
|
267
|
+
def to_dict(self, *, include_steps: bool = True, max_bytes: int = MAX_DIAGNOSTIC_BYTES) -> dict[str, Any]:
|
|
268
|
+
out: dict[str, Any] = {}
|
|
269
|
+
if self.last_stage:
|
|
270
|
+
out["last_stage"] = self.last_stage
|
|
271
|
+
if self.url_host_path:
|
|
272
|
+
out["url_host_path"] = self.url_host_path
|
|
273
|
+
if self.exc_type:
|
|
274
|
+
out["exc_type"] = self.exc_type
|
|
275
|
+
if self.error_code:
|
|
276
|
+
out["error_code"] = self.error_code
|
|
277
|
+
if include_steps and self._steps:
|
|
278
|
+
out["steps"] = [dict(s) for s in self._steps]
|
|
279
|
+
|
|
280
|
+
cap = max(64, int(max_bytes))
|
|
281
|
+
if len(json.dumps(out, ensure_ascii=False).encode("utf-8")) <= cap:
|
|
282
|
+
return out
|
|
283
|
+
|
|
284
|
+
if "steps" in out:
|
|
285
|
+
steps_list = list(out["steps"])
|
|
286
|
+
out["truncated"] = True
|
|
287
|
+
while steps_list and len(json.dumps({**out, "steps": steps_list}, ensure_ascii=False).encode("utf-8")) > cap:
|
|
288
|
+
# Drop oldest breadcrumbs first so the most recent failure context survives.
|
|
289
|
+
steps_list.pop(0)
|
|
290
|
+
if steps_list:
|
|
291
|
+
out["steps"] = steps_list
|
|
292
|
+
else:
|
|
293
|
+
out.pop("steps", None)
|
|
294
|
+
|
|
295
|
+
if len(json.dumps(out, ensure_ascii=False).encode("utf-8")) <= cap:
|
|
296
|
+
return out
|
|
297
|
+
|
|
298
|
+
# Final safeguard: trim string fields if still above cap.
|
|
299
|
+
for key in ("error_code", "url_host_path", "exc_type", "last_stage"):
|
|
300
|
+
val = out.get(key)
|
|
301
|
+
if isinstance(val, str) and len(val) > 32:
|
|
302
|
+
out[key] = redact_text(val, max_len=32)
|
|
303
|
+
if len(json.dumps(out, ensure_ascii=False).encode("utf-8")) <= cap:
|
|
304
|
+
break
|
|
305
|
+
return out
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def redact_multiline_snapshot(text: str, *, max_lines: int = 500, max_line_len: int = 200) -> str:
|
|
309
|
+
"""Redact a multi-line UI or DOM snapshot line-by-line."""
|
|
310
|
+
lines = (text or "").splitlines()[:max_lines]
|
|
311
|
+
out: list[str] = []
|
|
312
|
+
for line in lines:
|
|
313
|
+
leading = len(line) - len(line.lstrip(" "))
|
|
314
|
+
indent = " " * min(leading, 32)
|
|
315
|
+
body = redact_text(line.strip(), max_len=max_line_len)
|
|
316
|
+
if body:
|
|
317
|
+
out.append(f"{indent}{body}")
|
|
318
|
+
return "\n".join(out) + ("\n" if out else "")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def write_debug_bundle(
|
|
322
|
+
debug_dir: Path,
|
|
323
|
+
*,
|
|
324
|
+
diagnostics: dict[str, Any],
|
|
325
|
+
dom_snapshot: str | None = None,
|
|
326
|
+
ui_snapshot: str | None = None,
|
|
327
|
+
) -> Path:
|
|
328
|
+
"""Write redacted local debug artifacts (`diagnostics.json` + optional structural snapshot) with 0o700/0o600 perms."""
|
|
329
|
+
target_dir = Path(debug_dir)
|
|
330
|
+
target_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
331
|
+
os.chmod(target_dir, 0o700)
|
|
332
|
+
write_private_text_atomic(
|
|
333
|
+
target_dir / "diagnostics.json",
|
|
334
|
+
json.dumps(diagnostics, indent=2, ensure_ascii=False) + "\n",
|
|
335
|
+
)
|
|
336
|
+
if dom_snapshot is not None:
|
|
337
|
+
write_private_text_atomic(
|
|
338
|
+
target_dir / "dom-snapshot.txt",
|
|
339
|
+
redact_multiline_snapshot(dom_snapshot),
|
|
340
|
+
)
|
|
341
|
+
if ui_snapshot is not None:
|
|
342
|
+
write_private_text_atomic(
|
|
343
|
+
target_dir / "ui-snapshot.txt",
|
|
344
|
+
redact_multiline_snapshot(ui_snapshot),
|
|
345
|
+
)
|
|
346
|
+
return target_dir
|