webcompy-cli 0.0.14__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.
Files changed (47) hide show
  1. webcompy_cli/__init__.py +20 -0
  2. webcompy_cli/_argparser.py +232 -0
  3. webcompy_cli/_browser_probes.py +648 -0
  4. webcompy_cli/_browser_test_harness.py +554 -0
  5. webcompy_cli/_build.py +425 -0
  6. webcompy_cli/_console_types.py +15 -0
  7. webcompy_cli/_dependency_resolver.py +301 -0
  8. webcompy_cli/_dualrun_pytest_plugin.py +130 -0
  9. webcompy_cli/_exception.py +9 -0
  10. webcompy_cli/_generate.py +224 -0
  11. webcompy_cli/_init_project.py +54 -0
  12. webcompy_cli/_inspect.py +741 -0
  13. webcompy_cli/_inspect_pyexec.py +244 -0
  14. webcompy_cli/_lock.py +82 -0
  15. webcompy_cli/_lockfile.py +396 -0
  16. webcompy_cli/_lockfile_sync.py +343 -0
  17. webcompy_cli/_output.py +150 -0
  18. webcompy_cli/_prebuild.py +661 -0
  19. webcompy_cli/_pwa.py +474 -0
  20. webcompy_cli/_pyodide_downloader.py +113 -0
  21. webcompy_cli/_pyodide_lock.py +74 -0
  22. webcompy_cli/_runtime_downloader.py +222 -0
  23. webcompy_cli/_server.py +568 -0
  24. webcompy_cli/_static_files.py +27 -0
  25. webcompy_cli/_utils.py +72 -0
  26. webcompy_cli/_version_sweep.py +213 -0
  27. webcompy_cli/_wheel_builder.py +509 -0
  28. webcompy_cli/config/__init__.py +23 -0
  29. webcompy_cli/config/_build_config.py +168 -0
  30. webcompy_cli/config/_pwa_config.py +203 -0
  31. webcompy_cli/config/_server_config.py +53 -0
  32. webcompy_cli/py.typed +0 -0
  33. webcompy_cli/template_data/app/__init__.py +0 -0
  34. webcompy_cli/template_data/app/app.py +22 -0
  35. webcompy_cli/template_data/app/components/__init__.py +0 -0
  36. webcompy_cli/template_data/app/components/fizzbuzz.py +117 -0
  37. webcompy_cli/template_data/app/components/home.py +15 -0
  38. webcompy_cli/template_data/app/components/input.py +34 -0
  39. webcompy_cli/template_data/app/components/navigation.py +36 -0
  40. webcompy_cli/template_data/app/components/not_found.py +22 -0
  41. webcompy_cli/template_data/app/components/root.py +16 -0
  42. webcompy_cli/template_data/app/router.py +17 -0
  43. webcompy_cli/template_data/webcompy_config.py +12 -0
  44. webcompy_cli-0.0.14.dist-info/METADATA +53 -0
  45. webcompy_cli-0.0.14.dist-info/RECORD +47 -0
  46. webcompy_cli-0.0.14.dist-info/WHEEL +4 -0
  47. webcompy_cli-0.0.14.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,741 @@
1
+ """Browser inspection utilities for launching servers and running Playwright checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import os
8
+ import pathlib
9
+ import signal
10
+ import socket
11
+ import subprocess
12
+ import sys
13
+ import time
14
+ import urllib.error
15
+ import urllib.request
16
+ from argparse import ArgumentParser, Namespace
17
+ from typing import TYPE_CHECKING, Any
18
+
19
+ from webcompy_cli._console_types import ConsoleMessage
20
+
21
+ if TYPE_CHECKING:
22
+ from playwright.sync_api import Browser, Page, Playwright
23
+
24
+ PID_DIR = pathlib.Path(".tmp/webcompy-inspect")
25
+
26
+ _DEFAULT_WAIT_SECONDS = 5
27
+
28
+ _CONSOLE_LEVEL_ORDER: dict[str, int] = {
29
+ "off": 0,
30
+ "error": 1,
31
+ "warning": 2,
32
+ "info": 3,
33
+ "log": 4,
34
+ "debug": 5,
35
+ }
36
+
37
+
38
+ def _find_free_port() -> int:
39
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
40
+ s.bind(("", 0))
41
+ port = s.getsockname()[1]
42
+ return port
43
+
44
+
45
+ def _check_playwright() -> None:
46
+ try:
47
+ from playwright.sync_api import sync_playwright # noqa: F401
48
+ except ImportError:
49
+ print(
50
+ "Error: playwright is not installed.\n"
51
+ "Install it with:\n"
52
+ " uv sync --group dev\n"
53
+ " uv run playwright install chromium\n"
54
+ "Or:\n"
55
+ " pip install playwright\n"
56
+ " playwright install chromium",
57
+ file=sys.stderr,
58
+ )
59
+ sys.exit(1)
60
+
61
+
62
+ def _write_json(data: dict[str, Any]) -> None:
63
+ print(json.dumps(data))
64
+
65
+
66
+ def _write_json_error(message: str) -> None:
67
+ print(json.dumps({"error": message}))
68
+
69
+
70
+ def _ensure_pid_dir() -> None:
71
+ PID_DIR.mkdir(parents=True, exist_ok=True)
72
+
73
+
74
+ def _pid_file_path(port: int) -> pathlib.Path:
75
+ return PID_DIR / f"{port}.pid"
76
+
77
+
78
+ def _read_pid_file(port: int) -> dict[str, Any] | None:
79
+ path = _pid_file_path(port)
80
+ if not path.exists():
81
+ return None
82
+ try:
83
+ data = json.loads(path.read_text(encoding="utf-8"))
84
+ return data
85
+ except (json.JSONDecodeError, OSError):
86
+ return None
87
+
88
+
89
+ def _write_pid_file(port: int, pid: int, url: str, config_path: str | None) -> None:
90
+ _ensure_pid_dir()
91
+ path = _pid_file_path(port)
92
+ path.write_text(
93
+ json.dumps({"pid": pid, "port": port, "url": url, "config_path": config_path}),
94
+ encoding="utf-8",
95
+ )
96
+
97
+
98
+ def _remove_pid_file(port: int) -> None:
99
+ path = _pid_file_path(port)
100
+ if path.exists():
101
+ path.unlink()
102
+
103
+
104
+ def _is_process_running(pid: int) -> bool:
105
+ try:
106
+ os.kill(pid, 0)
107
+ return True
108
+ except ProcessLookupError:
109
+ return False
110
+ except PermissionError:
111
+ return True
112
+
113
+
114
+ def _verify_process_identity(pid: int, port: int) -> bool:
115
+ cmdline = _get_process_cmdline(pid)
116
+ if cmdline and (("webcompy" in cmdline and "start" in cmdline) or ("http.server" in cmdline)):
117
+ return True
118
+ try:
119
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
120
+ s.settimeout(1)
121
+ s.connect(("127.0.0.1", port))
122
+ return True
123
+ except OSError:
124
+ return False
125
+
126
+
127
+ def _get_process_cmdline(pid: int) -> str | None:
128
+ try:
129
+ cmdline_path = pathlib.Path(f"/proc/{pid}/cmdline")
130
+ if cmdline_path.exists():
131
+ return cmdline_path.read_bytes().decode(encoding="utf-8", errors="replace").replace("\0", " ")
132
+ except OSError:
133
+ pass
134
+ try:
135
+ result = subprocess.run(
136
+ ["ps", "-p", str(pid), "-o", "command="],
137
+ capture_output=True,
138
+ text=True,
139
+ timeout=2,
140
+ )
141
+ if result.returncode == 0 and result.stdout.strip():
142
+ return result.stdout.strip()
143
+ except (OSError, subprocess.TimeoutExpired):
144
+ pass
145
+ return None
146
+
147
+
148
+ def _wait_for_http(url: str, timeout: float = 10.0) -> bool:
149
+ deadline = time.monotonic() + timeout
150
+ while time.monotonic() < deadline:
151
+ try:
152
+ with urllib.request.urlopen(url, timeout=1) as resp:
153
+ if 200 <= resp.status < 500:
154
+ return True
155
+ except (urllib.error.URLError, OSError):
156
+ pass
157
+ time.sleep(0.2)
158
+ return False
159
+
160
+
161
+ def cmd_serve(args: Namespace) -> None:
162
+ from webcompy_cli._exception import WebComPyCliException
163
+ from webcompy_cli._utils import discover_config
164
+
165
+ source: str = args.source
166
+ config_path: str | None = args.config
167
+ dev: bool = args.dev
168
+ port: int = args.port if args.port is not None else 0
169
+ runtime_serving: str | None = args.runtime_serving
170
+ dist_path: str | None = args.dist
171
+
172
+ if port == 0:
173
+ port = _find_free_port()
174
+
175
+ if source == "app":
176
+ if dist_path is not None:
177
+ _write_json_error("--dist is only valid with --source=ssg")
178
+ sys.exit(1)
179
+ try:
180
+ discover_config(config_path)
181
+ except WebComPyCliException as e:
182
+ _write_json_error(str(e))
183
+ sys.exit(1)
184
+ actual_config_path = config_path
185
+ cmd: list[str] = [
186
+ sys.executable,
187
+ "-m",
188
+ "webcompy",
189
+ "start",
190
+ "--port",
191
+ str(port),
192
+ ]
193
+ if config_path:
194
+ cmd.extend(["--config", config_path])
195
+ if dev:
196
+ cmd.append("--dev")
197
+ if runtime_serving:
198
+ cmd.extend(["--runtime-serving", runtime_serving])
199
+ server_kind = "app"
200
+ else:
201
+ if runtime_serving is not None or dev:
202
+ _write_json_error("--dev and --runtime-serving are only valid with --source=app")
203
+ sys.exit(1)
204
+ if dist_path is None:
205
+ _write_json_error("--dist is required when --source=ssg")
206
+ sys.exit(1)
207
+ dist_dir = pathlib.Path(dist_path).resolve()
208
+ if not dist_dir.is_dir():
209
+ _write_json_error(f"--dist path is not a directory: {dist_path}")
210
+ sys.exit(1)
211
+ actual_config_path = None
212
+ cmd = [
213
+ sys.executable,
214
+ "-m",
215
+ "http.server",
216
+ "--bind",
217
+ "127.0.0.1",
218
+ "--directory",
219
+ str(dist_dir),
220
+ str(port),
221
+ ]
222
+ server_kind = "ssg"
223
+
224
+ existing_pid = _read_pid_file(port)
225
+ if existing_pid is not None:
226
+ existing_pid_val = existing_pid.get("pid", 0)
227
+ if _is_process_running(existing_pid_val) and _verify_process_identity(existing_pid_val, port):
228
+ _write_json_error(f"Port {port} is already in use by process {existing_pid_val}")
229
+ sys.exit(1)
230
+ _remove_pid_file(port)
231
+
232
+ log_file_path = PID_DIR / f"{port}.log"
233
+ _ensure_pid_dir()
234
+ log_file = log_file_path.open("w")
235
+ try:
236
+ proc = subprocess.Popen(cmd, stdout=log_file, stderr=subprocess.STDOUT)
237
+ except Exception as e:
238
+ log_file.close()
239
+ _write_json_error(f"Failed to start server: {e}")
240
+ sys.exit(1)
241
+ finally:
242
+ log_file.close()
243
+
244
+ url = f"http://localhost:{port}/"
245
+ try:
246
+ if not _wait_for_http(url, timeout=10.0):
247
+ with contextlib.suppress(ProcessLookupError):
248
+ proc.terminate()
249
+ with contextlib.suppress(ProcessLookupError):
250
+ proc.wait(timeout=2)
251
+ _write_json_error(f"Server failed to respond on {url} within 10 seconds")
252
+ sys.exit(1)
253
+ except Exception:
254
+ with contextlib.suppress(ProcessLookupError):
255
+ proc.terminate()
256
+ with contextlib.suppress(ProcessLookupError):
257
+ proc.wait(timeout=2)
258
+ raise
259
+
260
+ _write_pid_file(port, proc.pid, url, actual_config_path)
261
+ _write_json({"port": port, "url": url, "pid": proc.pid, "source": server_kind})
262
+
263
+
264
+ def cmd_stop(args: Namespace) -> None:
265
+ port: int = args.port
266
+ timeout: int = args.timeout
267
+
268
+ pid_data = _read_pid_file(port)
269
+ if pid_data is None:
270
+ _write_json_error(f"No server found on port {port}")
271
+ sys.exit(1)
272
+
273
+ pid: int = pid_data.get("pid", 0)
274
+
275
+ if not _is_process_running(pid):
276
+ _remove_pid_file(port)
277
+ _write_json({"stopped": False, "port": port, "error": f"No server found on port {port}"})
278
+ sys.exit(1)
279
+
280
+ if not _verify_process_identity(pid, port):
281
+ _remove_pid_file(port)
282
+ _write_json({"stopped": False, "port": port, "error": f"Process {pid} on port {port} is not a webcompy server"})
283
+ sys.exit(1)
284
+
285
+ try:
286
+ os.kill(pid, signal.SIGTERM)
287
+ except ProcessLookupError:
288
+ _remove_pid_file(port)
289
+ _write_json({"stopped": False, "port": port, "error": f"No server found on port {port}"})
290
+ sys.exit(1)
291
+
292
+ deadline = time.monotonic() + timeout
293
+ while time.monotonic() < deadline:
294
+ if not _is_process_running(pid):
295
+ break
296
+ time.sleep(0.1)
297
+
298
+ if _is_process_running(pid):
299
+ with contextlib.suppress(ProcessLookupError):
300
+ os.kill(pid, signal.SIGKILL)
301
+
302
+ _remove_pid_file(port)
303
+ log_file_path = PID_DIR / f"{port}.log"
304
+ if log_file_path.exists():
305
+ log_file_path.unlink()
306
+
307
+ _write_json({"stopped": True, "port": port})
308
+
309
+
310
+ def _launch_browser(
311
+ url: str,
312
+ wait_for: str | None = None,
313
+ on_console: Any | None = None,
314
+ ) -> tuple[Playwright, Browser, Page]:
315
+ from playwright.sync_api import sync_playwright
316
+
317
+ pw = sync_playwright().start()
318
+ browser = pw.chromium.launch(headless=True)
319
+ page = browser.new_page()
320
+ if on_console is not None:
321
+ page.on("console", on_console)
322
+ page.goto(url, wait_until="domcontentloaded")
323
+ if wait_for:
324
+ page.wait_for_selector(wait_for, timeout=30000)
325
+ return pw, browser, page
326
+
327
+
328
+ def _close_browser(pw: Playwright, browser: Browser, page: Page) -> None:
329
+ page.close()
330
+ browser.close()
331
+ pw.stop()
332
+
333
+
334
+ def cmd_screenshot(args: Namespace) -> None:
335
+ _check_playwright()
336
+
337
+ url: str = args.url
338
+ selector: str | None = args.selector
339
+ full_page: bool = args.full_page
340
+ output: str | None = args.output
341
+ wait_for: str | None = args.wait_for
342
+
343
+ pw, browser, page = _launch_browser(url, wait_for)
344
+
345
+ try:
346
+ if selector:
347
+ element = page.query_selector(selector)
348
+ if element is None:
349
+ _write_json_error(f"Element not found: {selector}")
350
+ sys.exit(1)
351
+ screenshot_bytes = element.screenshot()
352
+ else:
353
+ screenshot_bytes = page.screenshot(full_page=full_page)
354
+
355
+ if output:
356
+ pathlib.Path(output).write_bytes(screenshot_bytes)
357
+ _write_json({"output": output, "size": len(screenshot_bytes)})
358
+ else:
359
+ import base64
360
+
361
+ _write_json({"screenshot": base64.b64encode(screenshot_bytes).decode("ascii")})
362
+ finally:
363
+ _close_browser(pw, browser, page)
364
+
365
+
366
+ def _filter_messages(messages: list[ConsoleMessage], level: str) -> list[ConsoleMessage]:
367
+ min_level = _CONSOLE_LEVEL_ORDER.get(level, 1)
368
+ return [m for m in messages if _CONSOLE_LEVEL_ORDER.get(m.type, 0) <= min_level]
369
+
370
+
371
+ def cmd_console(args: Namespace) -> None:
372
+ _check_playwright()
373
+
374
+ url: str = args.url
375
+ level: str = args.level
376
+ wait_ms: int = args.wait
377
+ wait_for: str | None = args.wait_for
378
+
379
+ collected: list[ConsoleMessage] = []
380
+
381
+ def on_console_msg(msg):
382
+ loc = msg.location if isinstance(msg.location, dict) else {}
383
+ collected.append(
384
+ ConsoleMessage(
385
+ type=msg.type,
386
+ text=msg.text,
387
+ location=f"{loc.get('url', '')}:{loc.get('lineNumber', '')}:{loc.get('columnNumber', '')}",
388
+ )
389
+ )
390
+
391
+ pw, browser, page = _launch_browser(url, on_console=on_console_msg)
392
+
393
+ try:
394
+ if wait_for:
395
+ page.wait_for_selector(wait_for, timeout=30000)
396
+ time.sleep(wait_ms / 1000)
397
+
398
+ filtered = _filter_messages(collected, level)
399
+ _write_json({"messages": [{"type": m.type, "text": m.text, "location": m.location} for m in filtered]})
400
+ finally:
401
+ _close_browser(pw, browser, page)
402
+
403
+
404
+ def cmd_query(args: Namespace) -> None:
405
+ _check_playwright()
406
+
407
+ url: str = args.url
408
+ selector: str = args.selector
409
+ property_name: str = args.property
410
+ wait_for: str | None = args.wait_for
411
+
412
+ pw, browser, page = _launch_browser(url, wait_for)
413
+
414
+ try:
415
+ elements = page.query_selector_all(selector)
416
+ results: list[Any] = []
417
+ for el in elements:
418
+ if property_name == "text":
419
+ results.append(el.text_content())
420
+ elif property_name == "html":
421
+ results.append(el.inner_html())
422
+ elif property_name.startswith("attr:"):
423
+ attr_name = property_name[5:]
424
+ results.append(el.get_attribute(attr_name))
425
+ elif property_name == "visible":
426
+ results.append(el.is_visible())
427
+ elif property_name == "count":
428
+ results.append(len(elements))
429
+ break
430
+ else:
431
+ _write_json_error(f"Unknown property: {property_name}")
432
+ sys.exit(1)
433
+
434
+ _write_json({"results": results})
435
+ finally:
436
+ _close_browser(pw, browser, page)
437
+
438
+
439
+ def cmd_click(args: Namespace) -> None:
440
+ _check_playwright()
441
+
442
+ url: str = args.url
443
+ selector: str = args.selector
444
+ wait_for: str | None = args.wait_for
445
+
446
+ pw, browser, page = _launch_browser(url)
447
+
448
+ try:
449
+ try:
450
+ element = page.wait_for_selector(selector, timeout=30000)
451
+ except Exception:
452
+ element = None
453
+ if element is None:
454
+ _write_json_error(f"Element not found: {selector}")
455
+ sys.exit(1)
456
+ element.click()
457
+
458
+ result: dict[str, Any] = {"clicked": True, "selector": selector}
459
+
460
+ if wait_for:
461
+ try:
462
+ page.wait_for_selector(wait_for, timeout=10000)
463
+ result["wait_for"] = wait_for
464
+ result["appeared"] = True
465
+ except Exception:
466
+ result["wait_for"] = wait_for
467
+ result["appeared"] = False
468
+
469
+ _write_json(result)
470
+ finally:
471
+ _close_browser(pw, browser, page)
472
+
473
+
474
+ def cmd_navigate(args: Namespace) -> None:
475
+ _check_playwright()
476
+
477
+ url: str = args.url
478
+ path: str = args.path
479
+ wait_for: str | None = args.wait_for
480
+
481
+ pw, browser, page = _launch_browser(url)
482
+
483
+ try:
484
+ full_url = url.rstrip("/") + "/" + path.lstrip("/")
485
+ page.goto(full_url, wait_until="domcontentloaded")
486
+
487
+ if wait_for:
488
+ page.wait_for_selector(wait_for, timeout=30000)
489
+
490
+ _write_json({"current_url": page.url, "title": page.title()})
491
+ finally:
492
+ _close_browser(pw, browser, page)
493
+
494
+
495
+ def _parse_expect(expectation: str) -> tuple[str, str, str]:
496
+ if expectation.startswith("console:"):
497
+ return ("console", expectation, "")
498
+
499
+ if ":attr:" in expectation:
500
+ selector, rest = expectation.split(":attr:", 1)
501
+ attr_name, attr_value = rest.split("=", 1)
502
+ return (selector, f"{attr_name}={attr_value}", "attr")
503
+
504
+ if expectation.endswith(":visible"):
505
+ selector = expectation[: -len(":visible")]
506
+ return (selector, "visible", "visible")
507
+
508
+ if "*=" in expectation:
509
+ selector, text = expectation.split("*=", 1)
510
+ return (selector, text, "contains")
511
+
512
+ if "=" in expectation:
513
+ selector, text = expectation.split("=", 1)
514
+ return (selector, text, "exact")
515
+
516
+ raise ValueError(f"Invalid expectation format: {expectation}")
517
+
518
+
519
+ def cmd_verify(args: Namespace) -> None:
520
+ _check_playwright()
521
+
522
+ url: str = args.url
523
+ expectations: list[str] = args.expect
524
+ wait_for: str | None = args.wait_for
525
+
526
+ console_messages: list[ConsoleMessage] = []
527
+
528
+ def on_console_msg(msg):
529
+ loc = msg.location if isinstance(msg.location, dict) else {}
530
+ console_messages.append(
531
+ ConsoleMessage(
532
+ type=msg.type,
533
+ text=msg.text,
534
+ location=f"{loc.get('url', '')}:{loc.get('lineNumber', '')}:{loc.get('columnNumber', '')}",
535
+ )
536
+ )
537
+
538
+ pw, browser, page = _launch_browser(url, on_console=on_console_msg)
539
+
540
+ try:
541
+ if wait_for:
542
+ page.wait_for_selector(wait_for, timeout=30000)
543
+ else:
544
+ time.sleep(_DEFAULT_WAIT_SECONDS)
545
+
546
+ passed: list[str] = []
547
+ failed: list[dict[str, Any]] = []
548
+
549
+ for expectation in expectations:
550
+ selector, value, kind = _parse_expect(expectation)
551
+
552
+ if selector == "console":
553
+ if value == "console:no-error":
554
+ errors = [m for m in console_messages if m.type == "error"]
555
+ if not errors:
556
+ passed.append(expectation)
557
+ else:
558
+ failed.append({"expect": expectation, "actual": f"{len(errors)} error(s) found"})
559
+ elif value.startswith("console:no-level="):
560
+ level = value[len("console:no-level=") :]
561
+ level_messages = [m for m in console_messages if m.type == level]
562
+ if not level_messages:
563
+ passed.append(expectation)
564
+ else:
565
+ failed.append(
566
+ {"expect": expectation, "actual": f"{len(level_messages)} {level} message(s) found"}
567
+ )
568
+ else:
569
+ failed.append({"expect": expectation, "actual": f"Unknown console assertion: {value}"})
570
+ continue
571
+
572
+ if kind == "visible":
573
+ el = page.query_selector(selector)
574
+ if el and el.is_visible():
575
+ passed.append(expectation)
576
+ else:
577
+ failed.append({"expect": expectation, "actual": "element not visible"})
578
+ elif kind == "attr":
579
+ el = page.query_selector(selector)
580
+ if el is None:
581
+ failed.append({"expect": expectation, "actual": "element not found"})
582
+ continue
583
+ attr_name, attr_val = value.split("=", 1) if "=" in value else (value, "")
584
+ actual_val = el.get_attribute(attr_name)
585
+ if actual_val == attr_val:
586
+ passed.append(expectation)
587
+ else:
588
+ failed.append({"expect": expectation, "actual": f"attr {attr_name}={actual_val}"})
589
+ elif kind == "exact":
590
+ el = page.query_selector(selector)
591
+ if el is None:
592
+ failed.append({"expect": expectation, "actual": "element not found"})
593
+ continue
594
+ actual_text = el.text_content()
595
+ if actual_text == value:
596
+ passed.append(expectation)
597
+ else:
598
+ failed.append({"expect": expectation, "actual": actual_text})
599
+ elif kind == "contains":
600
+ el = page.query_selector(selector)
601
+ if el is None:
602
+ failed.append({"expect": expectation, "actual": "element not found"})
603
+ continue
604
+ actual_text = el.text_content()
605
+ if value in (actual_text or ""):
606
+ passed.append(expectation)
607
+ else:
608
+ failed.append({"expect": expectation, "actual": actual_text})
609
+
610
+ _write_json({"passed": passed, "failed": failed})
611
+ sys.exit(0 if not failed else 1)
612
+ finally:
613
+ _close_browser(pw, browser, page)
614
+
615
+
616
+ def get_inspect_parser() -> ArgumentParser:
617
+ parser = ArgumentParser(
618
+ prog="python -m webcompy inspect",
619
+ description="Inspect a WebComPy application in a browser",
620
+ )
621
+ subparsers = parser.add_subparsers(dest="inspect_command")
622
+
623
+ serve_parser = subparsers.add_parser("serve", help="Launch a WebComPy app server")
624
+ serve_parser.add_argument(
625
+ "--source",
626
+ choices=["app", "ssg"],
627
+ default="app",
628
+ help=(
629
+ "What to serve: 'app' launches the WebComPy app server (default), "
630
+ "'ssg' serves a pre-generated static site from a directory"
631
+ ),
632
+ )
633
+ serve_parser.add_argument(
634
+ "--dist",
635
+ type=str,
636
+ default=None,
637
+ help="Path to the SSG output directory (required when --source=ssg)",
638
+ )
639
+ serve_parser.add_argument(
640
+ "--config", type=str, help="Python import path for config module (used with --source=app)"
641
+ )
642
+ serve_parser.add_argument("--dev", action="store_true", help="Enable hot-reload mode (used with --source=app)")
643
+ serve_parser.add_argument("--port", type=int, default=None, help="Port number (0 for auto-detect)")
644
+ serve_parser.add_argument(
645
+ "--runtime-serving",
646
+ choices=["cdn", "local"],
647
+ default=None,
648
+ help="Runtime serving mode (used with --source=app)",
649
+ )
650
+ serve_parser.set_defaults(func=cmd_serve)
651
+
652
+ stop_parser = subparsers.add_parser("stop", help="Stop a running WebComPy app server")
653
+ stop_parser.add_argument("port", type=int, help="Port number of the server to stop")
654
+ stop_parser.add_argument("--timeout", type=int, default=10, help="Timeout in seconds (default: 10)")
655
+ stop_parser.set_defaults(func=cmd_stop)
656
+
657
+ screenshot_parser = subparsers.add_parser("screenshot", help="Capture a screenshot of a URL")
658
+ screenshot_parser.add_argument("url", type=str, help="URL to screenshot")
659
+ screenshot_parser.add_argument("--selector", type=str, default=None, help="CSS selector for element screenshot")
660
+ screenshot_parser.add_argument("--full-page", action="store_true", help="Capture the full scrollable page")
661
+ screenshot_parser.add_argument(
662
+ "--output", type=str, default=None, help="Output file path (default: base64 to stdout)"
663
+ )
664
+ screenshot_parser.add_argument(
665
+ "--wait-for", type=str, default=None, help="CSS selector to wait for before capturing"
666
+ )
667
+ screenshot_parser.set_defaults(func=cmd_screenshot)
668
+
669
+ console_parser = subparsers.add_parser("console", help="Collect browser console messages")
670
+ console_parser.add_argument("url", type=str, help="URL to inspect")
671
+ console_parser.add_argument(
672
+ "--level",
673
+ type=str,
674
+ default="warning",
675
+ choices=list(_CONSOLE_LEVEL_ORDER.keys())[1:],
676
+ help="Minimum console level to include (default: warning)",
677
+ )
678
+ console_parser.add_argument(
679
+ "--wait", type=int, default=5000, help="Collection duration in milliseconds (default: 5000)"
680
+ )
681
+ console_parser.add_argument("--wait-for", type=str, default=None, help="CSS selector to wait for before collecting")
682
+ console_parser.set_defaults(func=cmd_console)
683
+
684
+ query_parser = subparsers.add_parser("query", help="Query DOM element properties")
685
+ query_parser.add_argument("url", type=str, help="URL to inspect")
686
+ query_parser.add_argument("selector", type=str, help="CSS selector to query")
687
+ query_parser.add_argument(
688
+ "--property",
689
+ type=str,
690
+ default="text",
691
+ help="Property to retrieve: text, html, attr:NAME, visible, count (default: text)",
692
+ )
693
+ query_parser.add_argument("--wait-for", type=str, default=None, help="CSS selector to wait for before querying")
694
+ query_parser.set_defaults(func=cmd_query)
695
+
696
+ click_parser = subparsers.add_parser("click", help="Click an element in the browser")
697
+ click_parser.add_argument("url", type=str, help="URL to navigate to")
698
+ click_parser.add_argument("selector", type=str, help="CSS selector of element to click")
699
+ click_parser.add_argument("--wait-for", type=str, default=None, help="CSS selector to wait for after clicking")
700
+ click_parser.set_defaults(func=cmd_click)
701
+
702
+ navigate_parser = subparsers.add_parser("navigate", help="Navigate to a path within the app")
703
+ navigate_parser.add_argument("url", type=str, help="Base URL to navigate to")
704
+ navigate_parser.add_argument("path", type=str, help="Path to navigate to within the app")
705
+ navigate_parser.add_argument("--wait-for", type=str, default=None, help="CSS selector to wait for after navigation")
706
+ navigate_parser.set_defaults(func=cmd_navigate)
707
+
708
+ verify_parser = subparsers.add_parser("verify", help="Verify expectations about a page")
709
+ verify_parser.add_argument("url", type=str, help="URL to verify")
710
+ verify_parser.add_argument(
711
+ "--expect",
712
+ action="append",
713
+ default=[],
714
+ help="Expectation: selector=text, selector*=text, selector:visible, selector:attr:name=value, console:no-error, console:no-level=LEVEL. Use :attr: for selectors containing =",
715
+ )
716
+ verify_parser.add_argument("--wait-for", type=str, default=None, help="CSS selector to wait for before checking")
717
+ verify_parser.set_defaults(func=cmd_verify)
718
+
719
+ from webcompy_cli._inspect_pyexec import register_pyexec_parser
720
+
721
+ register_pyexec_parser(subparsers)
722
+
723
+ return parser
724
+
725
+
726
+ def run_inspect() -> None:
727
+ """Run the ``webcompy inspect`` CLI command.
728
+
729
+ Parses ``sys.argv`` for the inspect subcommands and dispatches to
730
+ the selected handler.
731
+
732
+ Returns:
733
+ ``None``.
734
+
735
+ """
736
+ parser = get_inspect_parser()
737
+ args = parser.parse_args(sys.argv[2:])
738
+ if not hasattr(args, "func") or args.func is None:
739
+ parser.print_help()
740
+ sys.exit(1)
741
+ args.func(args)