import 'dart:async'; import 'dart:convert'; import 'dart:io'; /// Drives the Settings probe in real headless Chrome through the DevTools /// protocol and writes PNG captures. It only talks to the local probe origin /// passed with `--url`; it never contacts the production server. /// /// Usage: /// dart run tool/settings_probe_capture.dart \ /// --url http://127.0.0.1:PORT/ --out /path/to/captures /// /// Set CHROME_PATH if Chrome is not at the default macOS location. Future main(List arguments) async { final url = _argument(arguments, '--url'); final outPath = _argument(arguments, '--out'); if (url == null || outPath == null) { stderr.writeln('usage: ... --url URL --out DIRECTORY'); exitCode = 64; return; } final out = Directory(outPath)..createSync(recursive: true); final chromePath = Platform.environment['CHROME_PATH'] ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; final profile = await Directory.systemTemp.createTemp('settings-probe-'); final chrome = await Process.start(chromePath, [ '--headless=new', '--disable-gpu', '--hide-scrollbars', '--no-first-run', '--no-default-browser-check', '--remote-debugging-port=0', '--user-data-dir=${profile.path}', 'about:blank', ]); final stderrLines = chrome.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .asBroadcastStream(); try { final browserWs = await stderrLines .firstWhere((line) => line.contains('DevTools listening on ')) .timeout(const Duration(seconds: 20)); final browserUrl = browserWs.substring(browserWs.indexOf('ws://')); final parsed = Uri.parse(browserUrl); final pageWs = await _pageTarget(parsed); final cdp = Cdp(await WebSocket.connect(pageWs)); await cdp.send('Page.enable'); await cdp.send('Runtime.enable'); final scenarios = [ 'idle', 'connected', 'validation', 'workspace', 'dark', 'ios', 'narrow', ]; for (final scenario in scenarios) { await _runScenario(cdp, url, out, scenario); stdout.writeln('captured $scenario'); } await cdp.close(); } finally { chrome.kill(ProcessSignal.sigterm); await profile.delete(recursive: true).catchError((_) => profile); } } Future _runScenario( Cdp cdp, String base, Directory out, String scenario, ) async { var target = base; var width = 1200; var height = 900; switch (scenario) { case 'idle': break; case 'connected': target = '$base?connect=1'; break; case 'validation': target = '$base?endpoint=http%3A%2F%2Fexample.test'; break; case 'workspace': target = '$base?connect=1'; break; case 'dark': target = '$base?connect=1&theme=dark'; break; case 'ios': target = '$base?connect=1&platform=ios'; break; case 'narrow': width = 390; height = 844; target = '$base?connect=1&scale=1.6'; } await cdp.send('Emulation.setDeviceMetricsOverride', { 'width': width, 'height': height, 'deviceScaleFactor': 1, 'mobile': false, }); await cdp.send('Page.navigate', {'url': target}); await Future.delayed(const Duration(seconds: 4)); if (scenario == 'validation' || scenario == 'workspace') { await _enableSemantics(cdp); if (scenario == 'validation') { await _click(cdp, 'Connect'); await Future.delayed(const Duration(milliseconds: 800)); } else { await _typeWorkspace(cdp, '/srv/pipelines'); await _click(cdp, 'Save workspace'); await Future.delayed(const Duration(milliseconds: 800)); } } final shot = await cdp.send('Page.captureScreenshot', { 'format': 'png', 'captureBeyondViewport': false, }); final data = (shot['result'] as Map)['data'] as String; File( '${out.path}/settings-$scenario.png', ).writeAsBytesSync(base64Decode(data)); } Future _enableSemantics(Cdp cdp) async { await cdp.evaluate(''' (() => { const placeholder = document.querySelector('flt-semantics-placeholder'); if (placeholder) { placeholder.click(); return 'semantics requested'; } return 'no placeholder'; })() '''); await Future.delayed(const Duration(milliseconds: 900)); if (Platform.environment['DUMP_DOM'] == '1') { stdout.writeln( await cdp.evaluate( "document.querySelector('flt-semantics-host')?.innerHTML ?? 'none'", ), ); } } Future _click(Cdp cdp, String label) async { final result = await cdp.evaluate(''' (() => { const byLabel = [...document.querySelectorAll('[aria-label]')] .find((element) => element.getAttribute('aria-label') === ${jsonEncode(label)}); const byRole = [...document.querySelectorAll('[role="button"]')] .find((element) => (element.textContent || '').trim() === ${jsonEncode(label)}); const target = byLabel || byRole; if (!target) { return 'missing; labels=' + [...document.querySelectorAll('[aria-label]')] .map((element) => element.getAttribute('aria-label')).join('|') + '; roles=' + [...document.querySelectorAll('[role="button"]')] .map((element) => (element.textContent || '').trim()).join('|'); } target.click(); return 'clicked ' + target.tagName + ' ' + (target.getAttribute('role') || ''); })() '''); stdout.writeln('click "$label": $result'); } Future _typeWorkspace(Cdp cdp, String value) async { final found = await cdp.evaluate(''' (() => { const target = [...document.querySelectorAll('[aria-label]')] .find((element) => (element.getAttribute('aria-label') || '') .startsWith('Workspace path')); if (!target) return 'missing'; target.click(); target.focus(); return 'focused ' + target.tagName; })() '''); stdout.writeln('workspace field: $found'); await Future.delayed(const Duration(milliseconds: 400)); final rect = await cdp.evaluate(''' (() => { const target = [...document.querySelectorAll('[aria-label]')] .find((element) => (element.getAttribute('aria-label') || '') .startsWith('Workspace path')); if (!target) return null; const r = target.getBoundingClientRect(); return {x: r.left + r.width / 2, y: r.top + r.height / 2}; })() '''); if (rect != 'null') { final match = RegExp(r'x: ([0-9.]+), y: ([0-9.]+)').firstMatch(rect); if (match != null) { final x = double.parse(match.group(1)!); final y = double.parse(match.group(2)!); for (final type in ['mousePressed', 'mouseReleased']) { await cdp.send('Input.dispatchMouseEvent', { 'type': type, 'x': x, 'y': y, 'button': 'left', 'clickCount': 1, }); } await Future.delayed(const Duration(milliseconds: 300)); } } await cdp.send('Input.insertText', {'text': value}); await Future.delayed(const Duration(milliseconds: 300)); final typed = await cdp.evaluate(''' (() => { const el = document.activeElement; if (!el) return 'no active element'; if (el.value === ${jsonEncode(value)}) return 'insertText worked'; el.value = ${jsonEncode(value)}; el.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: ${jsonEncode(value)}, })); el.dispatchEvent(new Event('change', {bubbles: true})); return 'dispatched input; value=' + el.value; })() '''); stdout.writeln('workspace input: $typed'); await Future.delayed(const Duration(milliseconds: 500)); } Future _pageTarget(Uri browserWs) async { final client = HttpClient(); try { final request = await client.getUrl( Uri( scheme: 'http', host: browserWs.host, port: browserWs.port, path: '/json/list', ), ); final response = await request.close(); final body = await response.transform(utf8.decoder).join(); final targets = jsonDecode(body) as List; final page = targets.cast>().firstWhere( (target) => target['type'] == 'page', ); return page['webSocketDebuggerUrl'] as String; } finally { client.close(force: true); } } String? _argument(List arguments, String name) { final index = arguments.indexOf(name); if (index < 0 || index + 1 >= arguments.length) return null; return arguments[index + 1]; } class Cdp { Cdp(this._socket) { _socket.listen(_onMessage); } final WebSocket _socket; final Map>> _pending = {}; int _next = 0; Future> send( String method, [ Map params = const {}, ]) { final id = ++_next; final completer = Completer>(); _pending[id] = completer; _socket.add( jsonEncode({ 'id': id, 'method': method, 'params': params, }), ); return completer.future.timeout(const Duration(seconds: 30)); } Future evaluate(String expression) async { final reply = await send('Runtime.evaluate', { 'expression': expression, 'returnByValue': true, 'awaitPromise': true, }); final result = reply['result'] as Map; return '${result['result']?['value']}'; } void _onMessage(dynamic data) { if (data is! String) return; final message = jsonDecode(data) as Map; final id = message['id']; if (id is! int) return; final completer = _pending.remove(id); if (completer == null) return; final error = message['error']; if (error != null) { completer.completeError(StateError('$error')); } else { completer.complete(message); } } Future close() => _socket.close(); }