ui-capture 0.3.0b4__py3-none-any.whl
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.
- ui_capture/__init__.py +1 -0
- ui_capture/__main__.py +2 -0
- ui_capture/cli.py +442 -0
- ui_capture-0.3.0b4.dist-info/METADATA +59 -0
- ui_capture-0.3.0b4.dist-info/RECORD +9 -0
- ui_capture-0.3.0b4.dist-info/WHEEL +5 -0
- ui_capture-0.3.0b4.dist-info/entry_points.txt +2 -0
- ui_capture-0.3.0b4.dist-info/licenses/LICENSE +21 -0
- ui_capture-0.3.0b4.dist-info/top_level.txt +1 -0
ui_capture/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.3.0b4"
|
ui_capture/__main__.py
ADDED
ui_capture/cli.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Capture configured web screens in isolated Playwright contexts."""
|
|
3
|
+
import argparse
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
import errno
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
import hashlib
|
|
8
|
+
import html
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
import re
|
|
13
|
+
import subprocess
|
|
14
|
+
import stat
|
|
15
|
+
import shutil
|
|
16
|
+
import sys
|
|
17
|
+
import zipfile
|
|
18
|
+
from urllib.parse import urljoin, urlsplit
|
|
19
|
+
from . import __version__
|
|
20
|
+
|
|
21
|
+
DEVICES = {'desktop': (1440, 900), 'tablet': (768, 1024), 'mobile': (390, 844), 'small-mobile': (320, 568), 'large-mobile': (430, 932), 'large-desktop': (1920, 1080)}
|
|
22
|
+
BROWSERS = ('chromium', 'webkit', 'firefox')
|
|
23
|
+
|
|
24
|
+
def slug(value):
|
|
25
|
+
if not isinstance(value, str) or not re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}', value):
|
|
26
|
+
raise ValueError('Names must be safe filename identifiers')
|
|
27
|
+
return value
|
|
28
|
+
|
|
29
|
+
def origin(url):
|
|
30
|
+
if '\\' in url or any(ord(char) <= 32 or ord(char) == 127 for char in url):
|
|
31
|
+
raise ValueError('URL must percent-encode spaces and contain no backslashes or control characters')
|
|
32
|
+
p = urlsplit(url)
|
|
33
|
+
if p.scheme not in ('http', 'https') or not p.hostname or p.username or p.password:
|
|
34
|
+
raise ValueError('Use an HTTP(S) URL without embedded credentials')
|
|
35
|
+
port = p.port
|
|
36
|
+
if port == 0:
|
|
37
|
+
raise ValueError('Invalid URL port')
|
|
38
|
+
return p.scheme, p.hostname, port if port is not None else (443 if p.scheme == 'https' else 80)
|
|
39
|
+
|
|
40
|
+
def _object(value, allowed, label):
|
|
41
|
+
if not isinstance(value, dict):
|
|
42
|
+
raise ValueError(f'{label} must be an object')
|
|
43
|
+
if set(value) - set(allowed):
|
|
44
|
+
raise ValueError(f'Unknown {label} properties')
|
|
45
|
+
|
|
46
|
+
def _string(value, label, allow_empty=False):
|
|
47
|
+
if not isinstance(value, str) or (not allow_empty and not value.strip()):
|
|
48
|
+
raise ValueError(f'Invalid {label}')
|
|
49
|
+
return value
|
|
50
|
+
|
|
51
|
+
def screenshot_names(config, screen):
|
|
52
|
+
mode = screen.get('capture_mode', config.get('capture_mode'))
|
|
53
|
+
if mode is None:
|
|
54
|
+
mode = 'full' if screen.get('full_page', config.get('full_page', True)) else 'viewport'
|
|
55
|
+
name = screen['name']
|
|
56
|
+
if mode == 'both':
|
|
57
|
+
return [('full', f'{name}-full.png'), ('viewport', f'{name}-viewport.png')]
|
|
58
|
+
return [(mode, f'{name}.png')]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def validate(config):
|
|
62
|
+
from copy import deepcopy
|
|
63
|
+
_object(config, ('project','url','devices','browsers','themes','screens','scale','timeout_ms','capture_mode','full_page'), 'configuration')
|
|
64
|
+
config = deepcopy(config)
|
|
65
|
+
slug(config.get('project'))
|
|
66
|
+
base = _string(config.get('url'), 'url')
|
|
67
|
+
origin(base)
|
|
68
|
+
for key, allowed, default in (
|
|
69
|
+
('devices', DEVICES, ['desktop','mobile']),
|
|
70
|
+
('browsers', BROWSERS, ['chromium']),
|
|
71
|
+
('themes', ('light','dark'), ['light']),
|
|
72
|
+
):
|
|
73
|
+
values = config.get(key, default)
|
|
74
|
+
if not isinstance(values, list) or not values or any(not isinstance(v,str) or v not in allowed for v in values) or len(set(values)) != len(values):
|
|
75
|
+
raise ValueError(f'Invalid {key}')
|
|
76
|
+
config[key] = values
|
|
77
|
+
screens = config.get('screens', [{'name':'home'}])
|
|
78
|
+
if not isinstance(screens,list) or not screens:
|
|
79
|
+
raise ValueError('Provide screens')
|
|
80
|
+
if len(screens) * len(config['devices']) * len(config['browsers']) * len(config['themes']) > 300:
|
|
81
|
+
raise ValueError('Capture matrix exceeds 300 screen contexts')
|
|
82
|
+
names = set()
|
|
83
|
+
for screen in screens:
|
|
84
|
+
_object(screen, ('name','path','fixture','steps','ready','capture_mode','full_page'), 'screen')
|
|
85
|
+
name = slug(screen.get('name'))
|
|
86
|
+
if name.casefold() in names:
|
|
87
|
+
raise ValueError('Duplicate screen name')
|
|
88
|
+
names.add(name.casefold())
|
|
89
|
+
path = _string(screen.get('path',''), 'screen path', allow_empty=True)
|
|
90
|
+
if origin(urljoin(base,path)) != origin(base):
|
|
91
|
+
raise ValueError('Cross-origin screen URL')
|
|
92
|
+
if 'ready' in screen:
|
|
93
|
+
_string(screen['ready'], 'ready selector')
|
|
94
|
+
fixture = screen.get('fixture')
|
|
95
|
+
if fixture is not None:
|
|
96
|
+
_object(fixture, ('path','storage_key'), 'fixture')
|
|
97
|
+
_string(fixture.get('storage_key'), 'storage_key')
|
|
98
|
+
path = Path(_string(fixture.get('path'), 'fixture path'))
|
|
99
|
+
if path.is_absolute() or '..' in path.parts or path.suffix != '.json':
|
|
100
|
+
raise ValueError('Fixture must be a repository-relative JSON file')
|
|
101
|
+
steps = screen.get('steps', [])
|
|
102
|
+
if not isinstance(steps,list) or len(steps) > 100:
|
|
103
|
+
raise ValueError('Steps must be an array')
|
|
104
|
+
for step in steps:
|
|
105
|
+
_object(step, ('action','selector','value'), 'step')
|
|
106
|
+
action = step.get('action')
|
|
107
|
+
if action not in ('click','click_if_visible','wait','fill'):
|
|
108
|
+
raise ValueError('Invalid step action')
|
|
109
|
+
_string(step.get('selector'), 'step selector')
|
|
110
|
+
if action == 'fill':
|
|
111
|
+
_string(step.get('value'), 'fill value', allow_empty=True)
|
|
112
|
+
elif 'value' in step:
|
|
113
|
+
raise ValueError('Only fill accepts a value')
|
|
114
|
+
config['screens'] = screens
|
|
115
|
+
for scope in [config, *screens]:
|
|
116
|
+
if 'capture_mode' in scope and scope['capture_mode'] not in ('viewport','full','both'):
|
|
117
|
+
raise ValueError('Invalid capture_mode')
|
|
118
|
+
if 'full_page' in scope and type(scope['full_page']) is not bool:
|
|
119
|
+
raise ValueError('full_page must be boolean')
|
|
120
|
+
filenames = set()
|
|
121
|
+
for screen in screens:
|
|
122
|
+
for _, filename in screenshot_names(config, screen):
|
|
123
|
+
if filename.casefold() in filenames:
|
|
124
|
+
raise ValueError('Conflicting screenshot filenames')
|
|
125
|
+
filenames.add(filename.casefold())
|
|
126
|
+
scale = config.get('scale',1)
|
|
127
|
+
if type(scale) not in (int,float) or not 1 <= scale <= 3:
|
|
128
|
+
raise ValueError('Scale must be 1–3')
|
|
129
|
+
timeout = config.get('timeout_ms',15000)
|
|
130
|
+
if type(timeout) is not int or not 100 <= timeout <= 60000:
|
|
131
|
+
raise ValueError('Timeout must be 100–60000ms')
|
|
132
|
+
return config
|
|
133
|
+
|
|
134
|
+
def revision(repo):
|
|
135
|
+
if not repo:
|
|
136
|
+
return None
|
|
137
|
+
commit = subprocess.check_output(
|
|
138
|
+
['git', '-C', str(repo), 'rev-parse', '--verify', 'HEAD'],
|
|
139
|
+
text=True, stderr=subprocess.DEVNULL, timeout=10,
|
|
140
|
+
).strip()
|
|
141
|
+
return {'commit': commit, 'dirty': None}
|
|
142
|
+
|
|
143
|
+
def gallery_html(manifest):
|
|
144
|
+
cards=[]
|
|
145
|
+
for r in manifest['captures']:
|
|
146
|
+
title=html.escape(' / '.join(r[k] for k in ('browser','device','theme','screen')))
|
|
147
|
+
if r.get('images'):
|
|
148
|
+
body=''.join(f'<p>{html.escape(im["mode"])}</p><a href="{html.escape(im["file"],quote=True)}"><img loading="lazy" src="{html.escape(im["file"],quote=True)}" alt="{title}"></a>' for im in r['images'])
|
|
149
|
+
elif r.get('file'):
|
|
150
|
+
path=html.escape(r['file'],quote=True)
|
|
151
|
+
body=f'<a href="{path}"><img loading="lazy" src="{path}" alt="{title}"></a>'
|
|
152
|
+
else: body='<p>Capture failed; inspect manifest.</p>'
|
|
153
|
+
cards.append(f'<article><h2>{title}</h2><p>{html.escape(r["status"])}</p>{body}</article>')
|
|
154
|
+
return ('<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>UI Capture</title><style>body{font:16px system-ui;margin:24px;background:#f4f6f8;color:#172033}main{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(320px,100%),1fr));gap:20px}article{background:white;border:1px solid #dce1e7;border-radius:12px;padding:16px}h2{font-size:16px}img{width:100%;height:420px;object-fit:contain;object-position:top}</style><h1>'+html.escape(manifest['project'])+' — capture gallery</h1><p>'+html.escape(manifest['created_at'])+' · Local review evidence</p><main>'+''.join(cards)+'</main></html>')
|
|
155
|
+
|
|
156
|
+
def gallery(folder, manifest):
|
|
157
|
+
(folder / 'index.html').write_text(gallery_html(manifest), encoding='utf-8')
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def fixture_data(screen, repo):
|
|
161
|
+
fixture=screen.get('fixture')
|
|
162
|
+
if fixture is None: return None
|
|
163
|
+
if repo is None: raise ValueError('Fixture requires --repo')
|
|
164
|
+
root=Path(repo).expanduser().resolve()
|
|
165
|
+
path=(root/fixture['path']).resolve()
|
|
166
|
+
if not path.is_relative_to(root): raise ValueError('Fixture escapes repository')
|
|
167
|
+
if not path.is_file(): raise ValueError('Fixture must be a regular file')
|
|
168
|
+
with path.open('rb') as stream:
|
|
169
|
+
raw=stream.read(5_000_001)
|
|
170
|
+
if len(raw)>5_000_000: raise ValueError('Fixture exceeds 5 MB')
|
|
171
|
+
try:
|
|
172
|
+
value = json.dumps(json.loads(raw), ensure_ascii=False)
|
|
173
|
+
except RecursionError:
|
|
174
|
+
raise ValueError('Fixture nesting exceeds the JSON parser limit') from None
|
|
175
|
+
return {'key': fixture['storage_key'], 'value': value, 'sha256': hashlib.sha256(raw).hexdigest()}
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@contextmanager
|
|
180
|
+
def open_directory(path, parent=None, *, create=False, private=False):
|
|
181
|
+
if create:
|
|
182
|
+
try:
|
|
183
|
+
os.mkdir(path, mode=0o700, dir_fd=parent)
|
|
184
|
+
except FileExistsError:
|
|
185
|
+
pass
|
|
186
|
+
try:
|
|
187
|
+
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
|
|
188
|
+
except OSError as error:
|
|
189
|
+
if error.errno in (errno.ELOOP, errno.ENOTDIR):
|
|
190
|
+
raise ValueError('Expected a real directory') from error
|
|
191
|
+
raise
|
|
192
|
+
try:
|
|
193
|
+
info = os.fstat(fd)
|
|
194
|
+
if private and (info.st_uid != os.getuid() or info.st_mode & 0o077):
|
|
195
|
+
raise ValueError('Directory must be private and owned by the current user')
|
|
196
|
+
yield fd
|
|
197
|
+
finally:
|
|
198
|
+
os.close(fd)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@contextmanager
|
|
202
|
+
def output_root(path):
|
|
203
|
+
# Resolve aliases such as macOS /var, then open every component without following links.
|
|
204
|
+
path = Path(path).expanduser().resolve()
|
|
205
|
+
fd = os.open(path.anchor, os.O_RDONLY | os.O_DIRECTORY)
|
|
206
|
+
try:
|
|
207
|
+
for part in path.parts[1:]:
|
|
208
|
+
with open_directory(part, fd, create=True) as child:
|
|
209
|
+
next_fd = os.dup(child)
|
|
210
|
+
os.close(fd)
|
|
211
|
+
fd = next_fd
|
|
212
|
+
yield path, fd
|
|
213
|
+
finally:
|
|
214
|
+
os.close(fd)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def archive_entries(archive, directory, prefix):
|
|
218
|
+
for name in sorted(os.listdir(directory)):
|
|
219
|
+
try:
|
|
220
|
+
fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK,
|
|
221
|
+
dir_fd=directory)
|
|
222
|
+
except OSError as error:
|
|
223
|
+
if error.errno == errno.ELOOP:
|
|
224
|
+
raise ValueError('Archive refuses symbolic links') from error
|
|
225
|
+
raise
|
|
226
|
+
try:
|
|
227
|
+
info = os.fstat(fd)
|
|
228
|
+
member = prefix / name
|
|
229
|
+
if stat.S_ISDIR(info.st_mode):
|
|
230
|
+
archive_entries(archive, fd, member)
|
|
231
|
+
elif stat.S_ISREG(info.st_mode) and info.st_nlink == 1:
|
|
232
|
+
with os.fdopen(os.dup(fd), 'rb') as source, archive.open(
|
|
233
|
+
member.as_posix(), 'w', force_zip64=True
|
|
234
|
+
) as target:
|
|
235
|
+
shutil.copyfileobj(source, target)
|
|
236
|
+
else:
|
|
237
|
+
raise ValueError('Archive refuses special files and hard links')
|
|
238
|
+
finally:
|
|
239
|
+
os.close(fd)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def write_archive(parent, directory, name):
|
|
243
|
+
filename = Path(name).with_suffix('.zip').name
|
|
244
|
+
fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=parent)
|
|
245
|
+
try:
|
|
246
|
+
with os.fdopen(fd, 'wb') as stream:
|
|
247
|
+
with zipfile.ZipFile(stream, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
|
|
248
|
+
archive_entries(archive, directory, Path(name))
|
|
249
|
+
except BaseException:
|
|
250
|
+
os.unlink(filename, dir_fd=parent)
|
|
251
|
+
raise
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def package(folder):
|
|
255
|
+
folder = Path(folder)
|
|
256
|
+
with open_directory(folder.parent) as parent:
|
|
257
|
+
with open_directory(folder.name, parent) as directory:
|
|
258
|
+
write_archive(parent, directory, folder.name)
|
|
259
|
+
return folder.with_suffix('.zip')
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@contextmanager
|
|
263
|
+
def open_run_folder(output, project, stamp):
|
|
264
|
+
name = stamp.strftime('%Y%m%dT%H%M%S%fZ')
|
|
265
|
+
with output_root(output) as (root, root_fd):
|
|
266
|
+
with open_directory(slug(project), root_fd, create=True, private=True) as parent:
|
|
267
|
+
os.mkdir(name, mode=0o700, dir_fd=parent)
|
|
268
|
+
with open_directory(name, parent, private=True) as directory:
|
|
269
|
+
yield root / project / name, parent, directory
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def create_run_folder(output, project, stamp):
|
|
273
|
+
with open_run_folder(output, project, stamp) as (folder, _, _):
|
|
274
|
+
return folder
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def write_output(directory, name, content):
|
|
278
|
+
fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=directory)
|
|
279
|
+
try:
|
|
280
|
+
with os.fdopen(fd, 'wb') as stream:
|
|
281
|
+
stream.write(content)
|
|
282
|
+
except BaseException:
|
|
283
|
+
os.unlink(name, dir_fd=directory)
|
|
284
|
+
raise
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
@contextmanager
|
|
288
|
+
def screenshot_directory(directory, engine, device, theme):
|
|
289
|
+
with open_directory(engine, directory, create=True, private=True) as engine_fd:
|
|
290
|
+
with open_directory(device, engine_fd, create=True, private=True) as device_fd:
|
|
291
|
+
with open_directory(theme, device_fd, create=True, private=True) as theme_fd:
|
|
292
|
+
yield theme_fd
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def run(config, output, repo=None, executable=None, make_zip=False):
|
|
296
|
+
previous_umask=os.umask(0o077)
|
|
297
|
+
try:
|
|
298
|
+
return _run(config, output, repo, executable, make_zip)
|
|
299
|
+
finally:
|
|
300
|
+
os.umask(previous_umask)
|
|
301
|
+
|
|
302
|
+
def _run(config, output, repo=None, executable=None, make_zip=False):
|
|
303
|
+
config=validate(config)
|
|
304
|
+
fixtures={screen["name"]:fixture_data(screen,repo) for screen in config["screens"]}
|
|
305
|
+
stamp=datetime.now(timezone.utc)
|
|
306
|
+
git_revision=revision(repo)
|
|
307
|
+
with open_run_folder(output, config['project'], stamp) as (folder, parent, directory):
|
|
308
|
+
return capture_run(config, fixtures, stamp, git_revision, folder, parent,
|
|
309
|
+
directory, executable, make_zip)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def capture_run(config, fixtures, stamp, git_revision, folder, parent, directory,
|
|
313
|
+
executable, make_zip):
|
|
314
|
+
from playwright.sync_api import sync_playwright
|
|
315
|
+
manifest={'schema':3,'tool_version':__version__,'served_revision':{'status':'unverified'},'git_scope':'supplied_checkout','project':config['project'],'created_at':stamp.isoformat(),'git':git_revision,'config_sha256':hashlib.sha256(json.dumps(config,sort_keys=True).encode()).hexdigest(),'captures':[]}
|
|
316
|
+
failed=False
|
|
317
|
+
try:
|
|
318
|
+
with sync_playwright() as pw:
|
|
319
|
+
for engine in config['browsers']:
|
|
320
|
+
try: browser=getattr(pw,engine).launch(**({'executable_path':executable} if executable and engine=='chromium' else {}))
|
|
321
|
+
except Exception as error:
|
|
322
|
+
manifest['captures'].append({'browser':engine,'device':'all','theme':'all','screen':'all','status':'browser launch failed','error_type':type(error).__name__}); failed=True; continue
|
|
323
|
+
try:
|
|
324
|
+
for device in config['devices']:
|
|
325
|
+
w,h=DEVICES[device]
|
|
326
|
+
for theme in config['themes']:
|
|
327
|
+
for screen in config['screens']:
|
|
328
|
+
r={'browser':engine,'browser_version':browser.version,'device':device,'viewport':[w,h],'theme':theme,'screen':screen['name'],'status':'failed','console_errors':0,'page_errors':0,'http_errors':0,'http_status_counts':{},'request_failures':0,'data_mode':'fixture' if fixtures[screen['name']] is not None else 'unseeded'}
|
|
329
|
+
manifest['captures'].append(r)
|
|
330
|
+
context=None
|
|
331
|
+
stage='context'
|
|
332
|
+
expected_origin=origin(config['url'])
|
|
333
|
+
written=[]
|
|
334
|
+
image_directory=None
|
|
335
|
+
try:
|
|
336
|
+
context=browser.new_context(viewport={'width':w,'height':h},device_scale_factor=config.get('scale',1),color_scheme=theme, reduced_motion='reduce', service_workers='block')
|
|
337
|
+
page=context.new_page(); page.set_default_timeout(config.get('timeout_ms',15000))
|
|
338
|
+
def count(key): r[key]+=1
|
|
339
|
+
page.on('console',lambda m: count('console_errors') if m.type=='error' else None)
|
|
340
|
+
page.on('pageerror',lambda e: count('page_errors'))
|
|
341
|
+
def record_response(response):
|
|
342
|
+
if response.status>=400:
|
|
343
|
+
count('http_errors')
|
|
344
|
+
key=str(response.status)
|
|
345
|
+
r['http_status_counts'][key]=r['http_status_counts'].get(key,0)+1
|
|
346
|
+
page.on('response',record_response)
|
|
347
|
+
page.on('requestfailed',lambda request: count('request_failures'))
|
|
348
|
+
stage='navigation'
|
|
349
|
+
response=page.goto(urljoin(config['url'],screen.get('path','')),wait_until='load')
|
|
350
|
+
if response is not None and response.status>=400: raise RuntimeError('Navigation failed')
|
|
351
|
+
if origin(page.url)!=expected_origin: raise RuntimeError('Unexpected redirect')
|
|
352
|
+
fixture=fixtures[screen['name']]
|
|
353
|
+
if fixture is not None:
|
|
354
|
+
stage='fixture'
|
|
355
|
+
r['fixture_sha256']=fixture['sha256']
|
|
356
|
+
page.evaluate('(f) => localStorage.setItem(f.key, f.value)', {'key':fixture['key'],'value':fixture['value']})
|
|
357
|
+
response=page.reload(wait_until='load')
|
|
358
|
+
if origin(page.url)!=expected_origin or (response and response.status>=400): raise RuntimeError('Fixture reload failed')
|
|
359
|
+
stage='screen steps'
|
|
360
|
+
for step in screen.get('steps',[]):
|
|
361
|
+
locator=page.locator(step['selector'])
|
|
362
|
+
if step['action']=='click': locator.click()
|
|
363
|
+
elif step['action']=='click_if_visible':
|
|
364
|
+
if locator.is_visible(): locator.click()
|
|
365
|
+
elif step['action']=='fill': locator.fill(step['value'])
|
|
366
|
+
else: locator.wait_for(state='visible')
|
|
367
|
+
if origin(page.url)!=expected_origin: raise RuntimeError('Unexpected redirect')
|
|
368
|
+
stage='readiness'
|
|
369
|
+
if screen.get('ready'): page.locator(screen['ready']).wait_for(state='visible')
|
|
370
|
+
if origin(page.url)!=expected_origin: raise RuntimeError('Unexpected redirect')
|
|
371
|
+
page.evaluate('() => Promise.race([document.fonts.ready, new Promise((_, reject) => setTimeout(() => reject(new Error("Font timeout")), 10000))])')
|
|
372
|
+
stage='screenshot'
|
|
373
|
+
with screenshot_directory(directory, engine, device, theme) as image_fd:
|
|
374
|
+
image_directory = os.dup(image_fd)
|
|
375
|
+
r['images']=[]
|
|
376
|
+
for variant, filename in screenshot_names(config, screen):
|
|
377
|
+
if origin(page.url)!=expected_origin: raise RuntimeError('Unexpected redirect')
|
|
378
|
+
rel=f'{engine}/{device}/{theme}/{filename}'
|
|
379
|
+
data = page.screenshot(full_page=variant=='full', animations='disabled',
|
|
380
|
+
timeout=config.get('timeout_ms',15000))
|
|
381
|
+
if origin(page.url)!=expected_origin:
|
|
382
|
+
raise RuntimeError('Unexpected redirect during screenshot')
|
|
383
|
+
write_output(image_directory, filename, data)
|
|
384
|
+
written.append(filename)
|
|
385
|
+
r['images'].append({'mode':variant,'file':rel,'sha256':hashlib.sha256(data).hexdigest()})
|
|
386
|
+
r.update(file=r['images'][0]['file'],sha256=r['images'][0]['sha256'],horizontal_overflow=page.evaluate('document.documentElement.scrollWidth > innerWidth'))
|
|
387
|
+
if origin(page.url)!=expected_origin: raise RuntimeError('Unexpected redirect')
|
|
388
|
+
stage='context cleanup'
|
|
389
|
+
completed_context, context = context, None
|
|
390
|
+
completed_context.close()
|
|
391
|
+
r['status']='warnings' if any(r[k] for k in ('console_errors','page_errors','http_errors','request_failures','horizontal_overflow')) else 'captured'
|
|
392
|
+
if r['status']=='warnings': failed=True
|
|
393
|
+
except Exception as error:
|
|
394
|
+
for filename in written:
|
|
395
|
+
try:
|
|
396
|
+
os.unlink(filename, dir_fd=image_directory)
|
|
397
|
+
except FileNotFoundError:
|
|
398
|
+
pass
|
|
399
|
+
for key in ('images','file','sha256','horizontal_overflow'):
|
|
400
|
+
r.pop(key,None)
|
|
401
|
+
r['status']='failed'
|
|
402
|
+
r['error_type']=type(error).__name__; r['failed_stage']=stage; failed=True
|
|
403
|
+
finally:
|
|
404
|
+
if image_directory is not None:
|
|
405
|
+
os.close(image_directory)
|
|
406
|
+
if context:
|
|
407
|
+
try:
|
|
408
|
+
context.close()
|
|
409
|
+
except Exception as error:
|
|
410
|
+
r['cleanup_error_type']=type(error).__name__
|
|
411
|
+
finally: browser.close()
|
|
412
|
+
finally:
|
|
413
|
+
write_output(directory, 'manifest.json', (json.dumps(manifest, indent=2) + '\n').encode())
|
|
414
|
+
write_output(directory, 'index.html', gallery_html(manifest).encode())
|
|
415
|
+
print(folder)
|
|
416
|
+
if make_zip:
|
|
417
|
+
write_archive(parent, directory, folder.name)
|
|
418
|
+
print(folder.with_suffix('.zip'))
|
|
419
|
+
return 1 if failed else 0
|
|
420
|
+
|
|
421
|
+
def main():
|
|
422
|
+
p=argparse.ArgumentParser(description=__doc__); p.add_argument('--config',type=Path); p.add_argument('--url'); p.add_argument('--project'); p.add_argument('--devices'); p.add_argument('--browser'); p.add_argument('--themes'); p.add_argument('--output',default='~/.ui-capture/runs'); p.add_argument('--repo',type=Path); p.add_argument('--chromium-path'); p.add_argument('--viewport-only',action='store_true')
|
|
423
|
+
p.add_argument('--zip',action='store_true',help='Create a private ZIP beside the run directory')
|
|
424
|
+
p.add_argument('--version',action='version',version=__version__)
|
|
425
|
+
p.add_argument('--capture-mode',choices=['full','viewport','both'])
|
|
426
|
+
args=p.parse_args()
|
|
427
|
+
try:
|
|
428
|
+
config=json.loads(args.config.read_text()) if args.config else {'url':args.url,'project':args.project}
|
|
429
|
+
if not isinstance(config,dict): raise ValueError('Configuration must be an object')
|
|
430
|
+
for key,value in [('devices',args.devices),('browsers',args.browser),('themes',args.themes)]:
|
|
431
|
+
if value: config[key]=value.split(',')
|
|
432
|
+
if args.viewport_only and args.capture_mode: raise ValueError('Choose one capture mode option')
|
|
433
|
+
if args.viewport_only or args.capture_mode:
|
|
434
|
+
config['capture_mode']='viewport' if args.viewport_only else args.capture_mode
|
|
435
|
+
screens=config.get('screens',[])
|
|
436
|
+
if not isinstance(screens,list) or any(not isinstance(s,dict) for s in screens): raise ValueError('Invalid screens')
|
|
437
|
+
for screen in screens: screen['capture_mode']=config['capture_mode']
|
|
438
|
+
return run(config,args.output,args.repo,args.chromium_path,args.zip)
|
|
439
|
+
except (ValueError,KeyError,TypeError,OSError,subprocess.SubprocessError,ImportError) as e:
|
|
440
|
+
print(f'Capture setup failed: {type(e).__name__}. Check configuration, browser installation and repository path.',file=sys.stderr); return 2
|
|
441
|
+
|
|
442
|
+
if __name__=='__main__': sys.exit(main())
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ui-capture
|
|
3
|
+
Version: 0.3.0b4
|
|
4
|
+
Summary: Local browser screenshot and UI evidence bundles
|
|
5
|
+
Author: Kusse Sukuta Bersha
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: playwright<2,>=1.48
|
|
11
|
+
Dynamic: license-file
|
|
12
|
+
|
|
13
|
+
# UI Capture (engineering preview)
|
|
14
|
+
|
|
15
|
+
Local-first browser UI evidence utility. UI Capture is currently in beta and distributed under the MIT License.
|
|
16
|
+
|
|
17
|
+
## Setup
|
|
18
|
+
|
|
19
|
+
From the source directory, use a Python 3.10+ interpreter compatible with Playwright:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
python3 -m venv .venv
|
|
23
|
+
.venv/bin/python -m pip install .
|
|
24
|
+
.venv/bin/python -m playwright install chromium
|
|
25
|
+
.venv/bin/ui-capture --version
|
|
26
|
+
.venv/bin/ui-capture --url http://127.0.0.1:3000/ --project example --capture-mode both --zip
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Install other browser engines via `python -m playwright install firefox webkit` inside the environment. Use `--help` for options. Configurations support devices, browsers, themes, scale, timeout_ms, capture_mode (full, viewport, both), and screens with name, path, ready selector and ordered click, click_if_visible, wait or fill steps. A screen can specify a repository-relative JSON fixture with path and storage_key; use --repo. Each screen receives an isolated browser context. Existing full_page configuration remains supported. CLI capture mode overrides per-screen modes.
|
|
30
|
+
|
|
31
|
+
## Evidence and limitations
|
|
32
|
+
|
|
33
|
+
Outputs are stored locally under `~/.ui-capture/runs` by default. The manifest records per-screen error counts, HTTP status counts, request failures, screenshot hashes, fixture hash and whether state was seeded. Use `--repo` with a trusted checkout. Git metadata records its HEAD commit and reports working-tree cleanliness as unknown (`dirty: null`). The served revision is explicitly unverified. Raw console messages, HTTP paths, query strings and exception messages are not recorded. Screenshots may expose confidential data; inspect before sharing. Do not include secrets in configs. Loaded pages can make network requests or change backend data; this tool is not a network or security sandbox. Use trusted apps and disposable data. CSS viewport emulation is not physical-device testing. Capture is not visual regression or accessibility certification. Exit codes: 0 clean, 1 warnings/failures, 2 setup failure.
|
|
34
|
+
|
|
35
|
+
## Development
|
|
36
|
+
|
|
37
|
+
`python -m unittest discover -s tests -v` after installation. The included browser test uses system Chromium if available, otherwise Playwright-managed Chromium (install it first); actual macOS and other engine validation remain release gates. The private legacy configurations used during development are excluded from the distributable source archive.
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
### Browser validation
|
|
41
|
+
|
|
42
|
+
Install Playwright-managed engines with `python -m playwright install chromium firefox webkit`.
|
|
43
|
+
Run the existing capture assertions against each engine on the target macOS machine:
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
for browser in chromium firefox webkit; do
|
|
47
|
+
UI_CAPTURE_TEST_MANAGED=1 UI_CAPTURE_TEST_BROWSER="$browser" \
|
|
48
|
+
python -m unittest discover -s tests -v || exit 1
|
|
49
|
+
done
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Package validation
|
|
53
|
+
|
|
54
|
+
Build a wheel and source archive with `python -m build` in a development environment
|
|
55
|
+
with the `build` frontend installed. In separate fresh virtual environments, install
|
|
56
|
+
each artifact with `python -m pip install /path/to/artifact`, run `python -m pip check`
|
|
57
|
+
and verify `ui-capture --version` and `ui-capture --help`. The browser installation is
|
|
58
|
+
a separate step. Use a private output location you control, including its parent directories. Keep run directories protected from concurrent edits while creating a ZIP. ZIP bundles and screenshots
|
|
59
|
+
can contain private UI data and should be reviewed before sharing.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
ui_capture/__init__.py,sha256=DRDpz7UIoy2dCV-z_tQg_DZPcWwbglN1jBIBddwa6sc,24
|
|
2
|
+
ui_capture/__main__.py,sha256=ee5vE0xcUZM3fPmxicvcw-IJXkm6nOwxARREHBWpF8Q,47
|
|
3
|
+
ui_capture/cli.py,sha256=qf3EZ9sSW1PADQ0Kxnvh_rbj5ghrGLdqjodlCtTEmxs,24463
|
|
4
|
+
ui_capture-0.3.0b4.dist-info/licenses/LICENSE,sha256=tINSmU7qBRv0ZyeDrmKuAbjY7s3MToK-W-yIF6gG6tA,1076
|
|
5
|
+
ui_capture-0.3.0b4.dist-info/METADATA,sha256=aY8GIdSY5mnzyarzBmyT3CKr2Y5i_m3KIyX1SjTSdpA,3711
|
|
6
|
+
ui_capture-0.3.0b4.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
ui_capture-0.3.0b4.dist-info/entry_points.txt,sha256=ltTUmpKBthIw5vXTuqwj69xvxupf2t0WcEjDhW_B42E,51
|
|
8
|
+
ui_capture-0.3.0b4.dist-info/top_level.txt,sha256=WvQIUUuRvsseV70fpThKJO_g6dQZq--vi_9pjE-f8hM,11
|
|
9
|
+
ui_capture-0.3.0b4.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kusse Sukuta Bersha
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ui_capture
|