papersearch 0.4.7 → 0.4.9
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.
- package/.env.example +3 -0
- package/README.en.md +37 -12
- package/README.md +37 -12
- package/assets/logo.svg +15 -0
- package/assets/overview.en.png +0 -0
- package/assets/overview.png +0 -0
- package/assets/progress-capsule.en.png +0 -0
- package/assets/progress-capsule.png +0 -0
- package/carsi/paper_search_carsi/assets/capsule.html +87 -11
- package/carsi/paper_search_carsi/assets/icon-32.png +0 -0
- package/carsi/paper_search_carsi/assets/icon-512.png +0 -0
- package/carsi/paper_search_carsi/assets/icon-64.png +0 -0
- package/carsi/paper_search_carsi/assets/icon.svg +13 -16
- package/carsi/paper_search_carsi/browser/backend.py +7 -0
- package/carsi/paper_search_carsi/browser/challenge_interaction.py +53 -36
- package/carsi/paper_search_carsi/capsule_placement.py +266 -0
- package/carsi/paper_search_carsi/cli.py +27 -0
- package/carsi/paper_search_carsi/engine/batch.py +5 -1
- package/carsi/paper_search_carsi/engine/batch_access.py +2 -4
- package/carsi/paper_search_carsi/engine/batch_diagnostics.py +33 -27
- package/carsi/paper_search_carsi/engine/batch_institution.py +26 -6
- package/carsi/paper_search_carsi/engine/batch_login.py +49 -24
- package/carsi/paper_search_carsi/engine/batch_waits.py +73 -32
- package/carsi/paper_search_carsi/engine/bridge.py +5 -0
- package/carsi/paper_search_carsi/engine/page_activity.py +15 -15
- package/carsi/paper_search_carsi/failure_export.py +239 -0
- package/carsi/paper_search_carsi/issues.py +8 -6
- package/carsi/paper_search_carsi/page_snapshot.py +64 -0
- package/carsi/paper_search_carsi/progress_capsule.py +233 -93
- package/carsi/paper_search_carsi/report_sanitizer.py +248 -0
- package/carsi/paper_search_carsi/user_settings.py +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
- package/dist/cli.js +56 -5
- package/dist/cli.js.map +1 -1
- package/dist/config/ConfigService.d.ts +1 -1
- package/dist/config/ConfigService.d.ts.map +1 -1
- package/dist/config/ConfigService.js +1 -0
- package/dist/config/ConfigService.js.map +1 -1
- package/dist/management/failures/exportReport.d.ts +20 -0
- package/dist/management/failures/exportReport.d.ts.map +1 -0
- package/dist/management/failures/exportReport.js +73 -0
- package/dist/management/failures/exportReport.js.map +1 -0
- package/dist/management/failures/index.d.ts +20 -0
- package/dist/management/failures/index.d.ts.map +1 -1
- package/dist/management/failures/index.js +69 -43
- package/dist/management/failures/index.js.map +1 -1
- package/dist/management/updates/index.d.ts +37 -0
- package/dist/management/updates/index.d.ts.map +1 -0
- package/dist/management/updates/index.js +185 -0
- package/dist/management/updates/index.js.map +1 -0
- package/package.json +2 -1
- package/skills/paper-search/SKILL.md +3 -1
- package/skills/paper-search/references/browser-download.md +17 -4
- package/skills/paper-search/references/carsi-setup.md +1 -1
- package/skills/paper-search/references/cli-contract.md +2 -1
- package/skills/paper-search/references/management-layer.md +8 -0
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Offline failure packet export. Never opens a browser or modifies evidence."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import re
|
|
9
|
+
import tempfile
|
|
10
|
+
import zipfile
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from .report_sanitizer import MAX_HTML_BYTES, Redactor, sanitize_html
|
|
15
|
+
|
|
16
|
+
MAX_REQUEST_BYTES = 8 * 1024 * 1024
|
|
17
|
+
MAX_JSON_BYTES = 4 * 1024 * 1024
|
|
18
|
+
MAX_IMAGE_BYTES = 2 * 1024 * 1024
|
|
19
|
+
MAX_PACKAGE_BYTES = 64 * 1024 * 1024
|
|
20
|
+
MAX_PAPERS = 100
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ExportError(ValueError):
|
|
24
|
+
"""Stable public error code; never includes original contents/paths."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _read(path: Path, limit: int) -> bytes:
|
|
28
|
+
if path.is_symlink() or not path.is_file():
|
|
29
|
+
raise ExportError('missing_or_unsafe_file')
|
|
30
|
+
with path.open('rb') as handle:
|
|
31
|
+
data = handle.read(limit + 1)
|
|
32
|
+
if len(data) > limit:
|
|
33
|
+
raise ExportError('file_size_limit')
|
|
34
|
+
return data
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _artifact(root: Path, raw: str, limit: int) -> bytes:
|
|
38
|
+
path = Path(raw)
|
|
39
|
+
if not path.is_absolute():
|
|
40
|
+
path = root / path
|
|
41
|
+
# No symlinks or traversal out of the diagnostic directory. We never glob
|
|
42
|
+
# a download directory (which can contain PDFs, cookies and profiles).
|
|
43
|
+
try:
|
|
44
|
+
relative = path.absolute().relative_to(root.absolute())
|
|
45
|
+
if '..' in relative.parts:
|
|
46
|
+
raise ValueError()
|
|
47
|
+
current = root
|
|
48
|
+
for part in relative.parts:
|
|
49
|
+
current = current / part
|
|
50
|
+
if current.is_symlink():
|
|
51
|
+
raise ValueError()
|
|
52
|
+
path.resolve().relative_to(root.resolve())
|
|
53
|
+
except ValueError:
|
|
54
|
+
raise ExportError('unsafe_artifact_path') from None
|
|
55
|
+
return _read(path, limit)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _load_record(row: dict) -> tuple[dict, Path | None, str | None]:
|
|
59
|
+
source = row.get('diagnostic') or row.get('record')
|
|
60
|
+
if not isinstance(source, str) or not source:
|
|
61
|
+
return row.get('detail') or {}, None, 'diagnostic_missing; ledger_only'
|
|
62
|
+
path = Path(source)
|
|
63
|
+
try:
|
|
64
|
+
data = json.loads(_read(path, MAX_JSON_BYTES))
|
|
65
|
+
if not isinstance(data, dict) or str(data.get('doi') or data.get('raw_doi') or '').lower() != row['doi'].lower():
|
|
66
|
+
raise ExportError('diagnostic_identity_mismatch')
|
|
67
|
+
if any(key in data and not isinstance(data[key], list) for key in ('events', 'snapshots', 'pages')):
|
|
68
|
+
raise ExportError('invalid_diagnostic_shape')
|
|
69
|
+
return data, path.parent, None
|
|
70
|
+
except (OSError, ValueError) as exc:
|
|
71
|
+
reason = str(exc) if isinstance(exc, ExportError) else 'diagnostic_unreadable'
|
|
72
|
+
return row.get('detail') or {}, None, reason + '; ledger_only'
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def export_report(request: dict, output: Path, config: dict | None = None) -> dict:
|
|
76
|
+
if request.get('schemaVersion') != 1 or not isinstance(request.get('papers'), list):
|
|
77
|
+
raise ExportError('invalid_export_request')
|
|
78
|
+
rows = request['papers']
|
|
79
|
+
if not rows:
|
|
80
|
+
raise ExportError('no_matching_failures')
|
|
81
|
+
if len(rows) > MAX_PAPERS:
|
|
82
|
+
raise ExportError('too_many_failures; select_a_run_or_doi; limit=100')
|
|
83
|
+
if any(not isinstance(row, dict) or not isinstance(row.get('doi'), str)
|
|
84
|
+
or ('detail' in row and not isinstance(row['detail'], dict)) for row in rows):
|
|
85
|
+
raise ExportError('invalid_export_request')
|
|
86
|
+
if output.suffix.lower() != '.zip':
|
|
87
|
+
raise ExportError('export_path_must_end_in_zip')
|
|
88
|
+
if output.exists() or output.is_symlink():
|
|
89
|
+
raise ExportError('export_target_exists')
|
|
90
|
+
redactor = Redactor(config)
|
|
91
|
+
loaded = []
|
|
92
|
+
total_input = 0
|
|
93
|
+
for row in rows:
|
|
94
|
+
data, root, problem = _load_record(row)
|
|
95
|
+
total_input += len(json.dumps(data, ensure_ascii=False).encode('utf-8'))
|
|
96
|
+
if total_input > MAX_PACKAGE_BYTES:
|
|
97
|
+
raise ExportError('source_size_limit; select_a_run_or_doi')
|
|
98
|
+
loaded.append((row, data, root, problem))
|
|
99
|
+
redactor.observe(row)
|
|
100
|
+
redactor.observe(data)
|
|
101
|
+
manifest = {
|
|
102
|
+
'schemaVersion': 1, 'createdAt': datetime.now(timezone.utc).isoformat(),
|
|
103
|
+
'version': redactor.text(str(request.get('version') or 'unknown')),
|
|
104
|
+
'exportSystem': platform.system(),
|
|
105
|
+
'reviewRequired': True, 'papers': [], 'files': [],
|
|
106
|
+
'limits': {'papers': MAX_PAPERS, 'htmlBytes': MAX_HTML_BYTES,
|
|
107
|
+
'imageBytes': MAX_IMAGE_BYTES, 'packageBytes': MAX_PACKAGE_BYTES},
|
|
108
|
+
}
|
|
109
|
+
output = output.expanduser().absolute()
|
|
110
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
fd, temp = tempfile.mkstemp(prefix='.papersearch-report-', suffix='.zip', dir=output.parent)
|
|
112
|
+
os.close(fd)
|
|
113
|
+
total = 0
|
|
114
|
+
try:
|
|
115
|
+
with zipfile.ZipFile(temp, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
|
|
116
|
+
def add(name: str, content: bytes) -> None:
|
|
117
|
+
nonlocal total
|
|
118
|
+
total += len(content)
|
|
119
|
+
if total > MAX_PACKAGE_BYTES:
|
|
120
|
+
raise ExportError('package_size_limit; select_a_run_or_doi')
|
|
121
|
+
archive.writestr(name, content)
|
|
122
|
+
manifest['files'].append({'path': name, 'bytes': len(content),
|
|
123
|
+
'sha256': hashlib.sha256(content).hexdigest()})
|
|
124
|
+
|
|
125
|
+
for i, (row, data, root, problem) in enumerate(loaded, 1):
|
|
126
|
+
folder = f'papers/{i:03d}' # no DOI/path/user content in archive paths
|
|
127
|
+
paper = redactor.clean({k: row.get(k) for k in
|
|
128
|
+
('doi', 'runId', 'publisher', 'failureClass', 'code', 'part', 'stoppedAt', 'evidence')})
|
|
129
|
+
paper.update(folder=folder, materials=[], omitted=[])
|
|
130
|
+
if not paper.get('stoppedAt'):
|
|
131
|
+
steps = [e for e in data.get('events', []) if isinstance(e, dict) and e.get('state')
|
|
132
|
+
and e['state'] not in {'snapshot', 'wait', 'publisher_session_saved'}]
|
|
133
|
+
paper['stoppedAt'] = redactor.text(str(steps[-1]['state'] if steps else data.get('state') or row.get('code') or 'unknown'))
|
|
134
|
+
paper['finalUrl'] = redactor.text(str(data.get('final_url') or data.get('article_url') or 'unknown'))
|
|
135
|
+
paper['captureSystem'] = redactor.clean(data.get('capture_system') or 'unknown (legacy record)')
|
|
136
|
+
paper['captureVersion'] = redactor.clean(data.get('capture_version') or 'unknown (legacy record)')
|
|
137
|
+
if problem:
|
|
138
|
+
paper['omitted'].append(problem)
|
|
139
|
+
clean = redactor.clean(data)
|
|
140
|
+
add(folder + '/diagnostic.json', _json(clean))
|
|
141
|
+
# Ledger provides the caller's attachment outcome even when the
|
|
142
|
+
# backend's original record pre-dates the supplementary step.
|
|
143
|
+
add(folder + '/outcome.json', _json(redactor.clean(row.get('outcome') or {})))
|
|
144
|
+
pages = [p for key in ('snapshots', 'pages') for p in (data.get(key) or []) if isinstance(p, dict)]
|
|
145
|
+
if len(pages) > 8:
|
|
146
|
+
paper['omitted'].append('page_count_limit')
|
|
147
|
+
for number, page in enumerate(pages[:8], 1):
|
|
148
|
+
for kind, limit, suffix in (('html', MAX_HTML_BYTES, '.html'), ('screenshot', MAX_IMAGE_BYTES, '.png')):
|
|
149
|
+
source = page.get(kind)
|
|
150
|
+
if not source or root is None:
|
|
151
|
+
if page.get(kind + '_omitted'):
|
|
152
|
+
paper['omitted'].append(f'page{number}/{kind}: capture_unavailable')
|
|
153
|
+
continue
|
|
154
|
+
if kind == 'screenshot':
|
|
155
|
+
if (page.get('screenshot_masked') is not True or page.get('screenshot_private') is True
|
|
156
|
+
or page.get('html_omitted') or redactor.private_page(
|
|
157
|
+
str(page.get('url') or ''), str(page.get('title') or ''), str(page.get('why') or '')
|
|
158
|
+
)):
|
|
159
|
+
paper['omitted'].append(f'page{number}/screenshot: login_school_or_unverified_origin')
|
|
160
|
+
continue
|
|
161
|
+
try:
|
|
162
|
+
content = _artifact(root, str(source), limit)
|
|
163
|
+
if kind == 'html':
|
|
164
|
+
content, truncated = sanitize_html(content.decode('utf-8'), redactor)
|
|
165
|
+
content = content.encode('utf-8')
|
|
166
|
+
if truncated or page.get('html_truncated'):
|
|
167
|
+
paper['omitted'].append(f'page{number}/html: truncated')
|
|
168
|
+
else:
|
|
169
|
+
if content.startswith(b'\x89PNG\r\n\x1a\n'):
|
|
170
|
+
suffix = '.png'
|
|
171
|
+
elif content.startswith(b'\xff\xd8\xff'):
|
|
172
|
+
suffix = '.jpg'
|
|
173
|
+
else:
|
|
174
|
+
raise ExportError('invalid_image')
|
|
175
|
+
name = f'{folder}/pages/{number:02d}{suffix}'
|
|
176
|
+
add(name, content)
|
|
177
|
+
paper['materials'].append({'path': name, 'kind': kind,
|
|
178
|
+
'url': redactor.text(str(page.get('url') or '')),
|
|
179
|
+
'why': redactor.text(str(page.get('why') or ''))})
|
|
180
|
+
except (OSError, ValueError, UnicodeError) as exc:
|
|
181
|
+
if isinstance(exc, ExportError) and str(exc).startswith('package_size_limit'):
|
|
182
|
+
raise
|
|
183
|
+
code = str(exc) if isinstance(exc, ExportError) else 'artifact_unreadable'
|
|
184
|
+
paper['omitted'].append(f'page{number}/{kind}: {code}')
|
|
185
|
+
if not any(p['kind'] == 'html' for p in paper['materials']):
|
|
186
|
+
paper['omitted'].append('html_unavailable; original_page_cannot_be_reconstructed')
|
|
187
|
+
if not any(p['kind'] == 'screenshot' for p in paper['materials']):
|
|
188
|
+
paper['omitted'].append('screenshots_unavailable_or_excluded')
|
|
189
|
+
manifest['papers'].append(paper)
|
|
190
|
+
add('summary.md', _summary(manifest).encode('utf-8'))
|
|
191
|
+
manifest_bytes = _json(manifest)
|
|
192
|
+
if total + len(manifest_bytes) > MAX_PACKAGE_BYTES:
|
|
193
|
+
raise ExportError('package_size_limit; select_a_run_or_doi')
|
|
194
|
+
archive.writestr('manifest.json', manifest_bytes)
|
|
195
|
+
# Exclusive final publication: a racing export cannot overwrite another
|
|
196
|
+
# report. Temporary file is on the same filesystem on Windows and Unix.
|
|
197
|
+
os.link(temp, output)
|
|
198
|
+
finally:
|
|
199
|
+
Path(temp).unlink(missing_ok=True)
|
|
200
|
+
return {'ok': True, 'schemaVersion': 1, 'path': str(output), 'papers': len(rows),
|
|
201
|
+
'files': len(manifest['files']) + 1, 'bytes': output.stat().st_size,
|
|
202
|
+
'reviewRequired': True,
|
|
203
|
+
'incompletePapers': sum(bool(p['omitted']) for p in manifest['papers'])}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _json(data) -> bytes:
|
|
207
|
+
return json.dumps(data, ensure_ascii=False, indent=2).encode('utf-8')
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _summary(manifest: dict) -> str:
|
|
211
|
+
# Keep site text from becoming active Markdown/HTML or injected issue UI.
|
|
212
|
+
def plain(value) -> str:
|
|
213
|
+
text = str(value or 'unknown').replace('\n', ' ').replace('\r', ' ').replace('<', '<').replace('>', '>').replace('`', "'")
|
|
214
|
+
return re.sub(r'([\\*_{}\[\]()#+!|])', r'\\\1', text)
|
|
215
|
+
|
|
216
|
+
lines = ['# PaperSearch 下载失败记录', '',
|
|
217
|
+
f"导出版本:{plain(manifest['version'])};导出系统:{plain(manifest['exportSystem'])}", '',
|
|
218
|
+
'## 公开前请核对', '',
|
|
219
|
+
'- [ ] 检查所有 HTML、诊断文本和截图中的姓名、邮箱、学号、学校标识及其他个人信息。',
|
|
220
|
+
'- [ ] 检查图片;字符串脱敏不能保证移除图片像素中的个人信息。',
|
|
221
|
+
'- [ ] 确认只分享这个导出包,不附原始 diagnostics、浏览器 profile、Cookie 或下载正文。',
|
|
222
|
+
'', 'HTML 为不可执行结构快照,href/action 记录为 data-href/data-action;只保留有限文本片段。',
|
|
223
|
+
'旧记录缺失的材料不会补造;导出不会重跑下载。', '']
|
|
224
|
+
for p in manifest['papers']:
|
|
225
|
+
lines.extend([f"## {plain(p['doi'])}", '',
|
|
226
|
+
f"- 出版社:{plain(p['publisher'])}",
|
|
227
|
+
f"- 失败部分:{plain(p.get('part') or 'main')};分类:{plain(p['failureClass'])};原因:{plain(p['code'])}",
|
|
228
|
+
f"- 停止步骤:{plain(p['stoppedAt'])}",
|
|
229
|
+
f"- 最后网址:`{plain(p['finalUrl'])}`",
|
|
230
|
+
f"- 采集版本 / 系统:{plain(p['captureVersion'])} / {plain(p['captureSystem'])}",
|
|
231
|
+
f"- 材料目录:{p['folder']}"])
|
|
232
|
+
if p.get('evidence'):
|
|
233
|
+
lines.append(f"- 依据:{plain(p['evidence'])}")
|
|
234
|
+
for material in p['materials']:
|
|
235
|
+
lines.append(f"- 检查文件:{material['path']}")
|
|
236
|
+
for omission in p['omitted']:
|
|
237
|
+
lines.append(f"- 材料缺项或限制:{plain(omission)}")
|
|
238
|
+
lines.append('')
|
|
239
|
+
return '\n'.join(lines)
|
|
@@ -150,6 +150,9 @@ def attach_page(folder: Path, page: Any, events: list[dict[str, Any]] | None = N
|
|
|
150
150
|
tabs = [p for p in list(page.context.pages) if not p.is_closed()]
|
|
151
151
|
except Exception:
|
|
152
152
|
tabs = [page]
|
|
153
|
+
from .page_snapshot import capture_structure, masked_screenshot
|
|
154
|
+
from .config import load_config
|
|
155
|
+
config = load_config()
|
|
153
156
|
for index, tab in enumerate(tabs[:6], 1):
|
|
154
157
|
row: dict[str, Any] = {"index": index, "working_tab": tab is page}
|
|
155
158
|
for key, getter in (("url", lambda t: t.url), ("title", lambda t: t.title())):
|
|
@@ -161,12 +164,11 @@ def attach_page(folder: Path, page: Any, events: list[dict[str, Any]] | None = N
|
|
|
161
164
|
row["text_excerpt"] = tab.evaluate("() => (document.body ? document.body.innerText : '').slice(0, 3000)")
|
|
162
165
|
except Exception:
|
|
163
166
|
row["text_excerpt"] = ""
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
pass
|
|
167
|
+
row.update(capture_structure(tab, folder / f"tab{index}.html", config))
|
|
168
|
+
row.update(masked_screenshot(tab, folder / f"tab{index}.png"))
|
|
169
|
+
for key in ("html", "screenshot"):
|
|
170
|
+
if key in row:
|
|
171
|
+
row[key] = Path(row[key]).name
|
|
170
172
|
info["tabs"].append(row)
|
|
171
173
|
if events is not None:
|
|
172
174
|
info["recent_events"] = events[-40:]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Bounded, inert page specimens shared by download diagnostics and issues."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .report_sanitizer import MAX_HTML_BYTES, Redactor, sanitize_html
|
|
8
|
+
|
|
9
|
+
# Walk live DOM without copying a script, a form value or an entire article.
|
|
10
|
+
# The RPC is bounded in time, number of nodes, depth, text and returned size.
|
|
11
|
+
_STRUCTURE = r"""(root, limit) => {
|
|
12
|
+
let size = 0, nodes = 0, textLeft = 6000, truncated = false;
|
|
13
|
+
const out = [], drop = new Set(['SCRIPT','STYLE','NOSCRIPT','IFRAME','OBJECT','EMBED','SVG','MATH','TEMPLATE','CANVAS']);
|
|
14
|
+
const attrs = new Set(['id','class','role','name','type','title','alt','aria-label','aria-labelledby','aria-describedby','aria-expanded','aria-controls','data-testid','data-test','href','action','disabled']);
|
|
15
|
+
const esc = s => s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
|
16
|
+
const push = s => { if (size + s.length <= limit) { out.push(s); size += s.length; } else truncated = true; };
|
|
17
|
+
const walk = (node, depth) => {
|
|
18
|
+
if (++nodes > 6000 || depth > 60 || size >= limit - 1024) { truncated = true; return; }
|
|
19
|
+
if (node.nodeType === 3) {
|
|
20
|
+
const s = node.textContent.trim().slice(0, Math.min(160, textLeft));
|
|
21
|
+
textLeft -= s.length; if (s) push(esc(s)); return;
|
|
22
|
+
}
|
|
23
|
+
if (node.nodeType !== 1 || drop.has(node.tagName) || (node.tagName === 'INPUT' && node.type === 'hidden')) return;
|
|
24
|
+
const tag = node.tagName.toLowerCase();
|
|
25
|
+
push('<' + tag + Array.from(node.attributes).filter(a => attrs.has(a.name)).map(a => ' ' + a.name + '="' + esc(a.value.slice(0,500)) + '"').join('') + '>');
|
|
26
|
+
if (['textarea','select'].includes(tag)) { push('</' + tag + '>'); return; }
|
|
27
|
+
for (const child of node.childNodes) { if (nodes >= 6000 || size >= limit - 1024) { truncated = true; break; } walk(child, depth + 1); }
|
|
28
|
+
if (!['input','img','br','hr','meta','link'].includes(tag)) push('</' + tag + '>');
|
|
29
|
+
};
|
|
30
|
+
walk(root, 0); return {html: out.join(''), truncated: truncated || textLeft <= 0,
|
|
31
|
+
private: !!root.querySelector('input[type=password],input[autocomplete=username],input[autocomplete=current-password]')};
|
|
32
|
+
}"""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def capture_structure(page: Any, path: Path, config: dict | None = None) -> dict:
|
|
36
|
+
"""Optional evidence failure is recorded, never changes the download result."""
|
|
37
|
+
try:
|
|
38
|
+
from .browser import watchdog
|
|
39
|
+
if watchdog.fired:
|
|
40
|
+
return {'html_omitted': 'browser_stopped'}
|
|
41
|
+
raw = page.locator('html').evaluate(_STRUCTURE, MAX_HTML_BYTES // 2, timeout=3000)
|
|
42
|
+
if not isinstance(raw, dict) or not isinstance(raw.get('html'), str):
|
|
43
|
+
return {'html_omitted': 'capture_unavailable'}
|
|
44
|
+
content, truncated = sanitize_html(raw['html'], Redactor(config))
|
|
45
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
path.write_text(content, encoding='utf-8')
|
|
47
|
+
return {'html': str(path), 'html_truncated': bool(truncated or raw.get('truncated')),
|
|
48
|
+
'screenshot_private': bool(raw.get('private'))}
|
|
49
|
+
except Exception as exc:
|
|
50
|
+
return {'html_omitted': type(exc).__name__}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def masked_screenshot(page: Any, path: Path) -> dict:
|
|
54
|
+
try:
|
|
55
|
+
from .browser import watchdog
|
|
56
|
+
if watchdog.fired:
|
|
57
|
+
return {'screenshot_omitted': 'browser_stopped'}
|
|
58
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
59
|
+
encoding = {"type": "jpeg", "quality": 50} if path.suffix.lower() in {".jpg", ".jpeg"} else {"type": "png"}
|
|
60
|
+
page.screenshot(path=str(path), **encoding, full_page=False, timeout=3000,
|
|
61
|
+
mask=[page.locator('input, textarea, select, [contenteditable]')])
|
|
62
|
+
return {'screenshot': str(path), 'screenshot_masked': True}
|
|
63
|
+
except Exception as exc:
|
|
64
|
+
return {'screenshot_omitted': type(exc).__name__}
|