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
webcompy_cli/_build.py ADDED
@@ -0,0 +1,425 @@
1
+ """Build artifact resolution for the dev server, SSG, and wheel packaging."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import pathlib
7
+ import re
8
+ import sys
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from tempfile import TemporaryDirectory
12
+
13
+ from webcompy.app._app import WebComPyApp
14
+ from webcompy_cli._lockfile import (
15
+ LOCKFILE_NAME,
16
+ get_bundled_deps,
17
+ get_cdn_pure_python_package_names,
18
+ get_wasm_package_names,
19
+ resolve_lockfile,
20
+ validate_local_environment,
21
+ verify_and_update_runtime_assets,
22
+ )
23
+ from webcompy_cli._lockfile_sync import resolve_dependencies
24
+ from webcompy_cli._pyodide_downloader import (
25
+ PyodideDownloadError,
26
+ download_pyodide_wheel,
27
+ download_wasm_wheels,
28
+ extract_wheel,
29
+ )
30
+ from webcompy_cli._pyodide_lock import PYODIDE_LOCK_URL_TEMPLATE, get_pyodide_version
31
+ from webcompy_cli._runtime_downloader import RuntimeDownloadError, download_runtime_assets
32
+ from webcompy_cli._utils import (
33
+ ensure_webcompy_modules_dir,
34
+ generate_app_version,
35
+ get_webcompy_packge_dir,
36
+ )
37
+ from webcompy_cli._wheel_builder import (
38
+ make_browser_webcompy_wheel,
39
+ make_webcompy_app_package,
40
+ )
41
+ from webcompy_cli.config._build_config import WebComPyBuildConfig
42
+ from webcompy_server import configure_server_context
43
+ from webcompy_server._html import PYSCRIPT_VERSION
44
+ from webcompy_server.ports._resource import ServerResourcePort
45
+
46
+ _DEFAULT_INCLUDE_PATTERNS: list[str] = [
47
+ "**/*.html",
48
+ "**/*.css",
49
+ "**/*.md",
50
+ "**/*.svg",
51
+ "**/*.txt",
52
+ ]
53
+
54
+ _ALWAYS_EXCLUDED_NAMES: frozenset[str] = frozenset(
55
+ {"__pycache__", ".git", ".venv", "venv", ".webcompy_modules", ".webcompy-build"}
56
+ )
57
+ _ALWAYS_EXCLUDED_SUFFIXES: frozenset[str] = frozenset({".pyc", ".tmp"})
58
+
59
+
60
+ def _build_output_exclude_prefixes(build_config: WebComPyBuildConfig) -> tuple[str, ...]:
61
+ pkg_resolved = build_config.app_package_path.resolve()
62
+ prefixes: list[str] = []
63
+ for raw in (build_config.prebuild_dir, build_config.dist):
64
+ if not raw or not raw.strip():
65
+ continue
66
+ candidate = pathlib.Path(raw)
67
+ target = candidate.resolve() if candidate.is_absolute() else (pkg_resolved / candidate).resolve()
68
+ if target == pkg_resolved:
69
+ continue
70
+ try:
71
+ rel = target.relative_to(pkg_resolved).as_posix()
72
+ except ValueError:
73
+ continue
74
+ if rel and rel != ".":
75
+ prefixes.append(rel.strip("/"))
76
+ return tuple(dict.fromkeys(prefixes))
77
+
78
+
79
+ def _is_excluded_rel_path(rel_posix: str, extra_excluded_prefixes: tuple[str, ...] = ()) -> bool:
80
+ parts = rel_posix.split("/")
81
+ if _ALWAYS_EXCLUDED_NAMES.intersection(parts):
82
+ return True
83
+ if any(p.startswith(".staging-") or (p.startswith(".") and ".staging-" in p) for p in parts):
84
+ return True
85
+ return any(rel_posix == prefix or rel_posix.startswith(prefix + "/") for prefix in extra_excluded_prefixes)
86
+
87
+
88
+ def _matches_pattern(rel_posix: str, pattern: str) -> bool:
89
+ """Match a POSIX-relative path against a glob pattern. ``**/`` at the start is treated as "zero or more path components" (matching files at any depth, including the package root), and trailing ``/**`` matches any descendant path beneath the prefix; otherwise pure ``pathlib`` glob semantics apply."""
90
+ rel_path = Path(rel_posix)
91
+ if pattern.startswith("**/"):
92
+ suffix = pattern[3:]
93
+ # Match root-level and nested paths against the suffix only.
94
+ if rel_path.match(suffix):
95
+ return True
96
+ # Pathlib's ``match`` requires a directory for ``**``; allow the
97
+ # suffix to also match by basename via a multi-component prefix.
98
+ suffix_name = suffix.split("/")[-1]
99
+ return "/" not in suffix and rel_path.match(suffix_name)
100
+ if pattern.endswith("/**"):
101
+ prefix = pattern[:-3].strip("/")
102
+ return rel_posix == prefix or rel_posix.startswith(prefix + "/")
103
+ return rel_path.match(pattern)
104
+
105
+
106
+ def _detect_resources(
107
+ app_package_path: Path,
108
+ include_patterns: list[str] | None,
109
+ exclude_patterns: list[str] | None,
110
+ *,
111
+ extra_excluded_prefixes: tuple[str, ...] = (),
112
+ ) -> frozenset[str]:
113
+ """Walk ``app_package_path`` and return POSIX-relative paths whose filenames match the include patterns and don't match any exclude rule."""
114
+ if include_patterns is None:
115
+ include_patterns = _DEFAULT_INCLUDE_PATTERNS
116
+ if include_patterns == []:
117
+ return frozenset()
118
+
119
+ found: set[str] = set()
120
+ for path in app_package_path.rglob("*"):
121
+ if not path.is_file():
122
+ continue
123
+ rel = path.relative_to(app_package_path).as_posix()
124
+ if _is_excluded_rel_path(rel, extra_excluded_prefixes):
125
+ continue
126
+ if path.suffix in _ALWAYS_EXCLUDED_SUFFIXES:
127
+ continue
128
+ if exclude_patterns and any(_matches_pattern(rel, pat) for pat in exclude_patterns):
129
+ continue
130
+ if any(_matches_pattern(rel, pat) for pat in include_patterns):
131
+ found.add(rel)
132
+ return frozenset(found)
133
+
134
+
135
+ _CSS_IMPORT_RE = re.compile(r'(@import\s+url\(\s*)(["\'])\./([^"\'?#)]+)(\2\s*\)\s*;)')
136
+
137
+
138
+ def _compute_asset_hashes(static_files_dir: pathlib.Path | None) -> tuple[dict[str, str], bytes]:
139
+ from webcompy.ui._styles import get_styles_files
140
+ from webcompy_cli._static_files import get_static_files
141
+
142
+ hashes: dict[str, str] = {}
143
+ styles_files = get_styles_files()
144
+ for name, content in styles_files.items():
145
+ if name == "index.css":
146
+ continue
147
+ hashes[f"_webcompy-ui/{name}"] = hashlib.sha256(content).hexdigest()[:8]
148
+
149
+ raw_index = styles_files.get("index.css", b"").decode("utf-8")
150
+
151
+ def _rewrite_import(match: re.Match[str]) -> str:
152
+ prefix, quote, target, suffix = match.groups()
153
+ digest = hashes.get(f"_webcompy-ui/{target}")
154
+ if digest is None:
155
+ return match.group(0)
156
+ return f"{prefix}{quote}./{target}?v={digest}{suffix}"
157
+
158
+ rewritten_index_bytes = _CSS_IMPORT_RE.sub(_rewrite_import, raw_index).encode("utf-8")
159
+ if "index.css" in styles_files:
160
+ hashes["_webcompy-ui/index.css"] = hashlib.sha256(rewritten_index_bytes).hexdigest()[:8]
161
+
162
+ if static_files_dir is not None and static_files_dir.is_dir():
163
+ for rel_path in get_static_files(static_files_dir):
164
+ file_bytes = (static_files_dir / rel_path).read_bytes()
165
+ hashes[rel_path.lstrip("/")] = hashlib.sha256(file_bytes).hexdigest()[:8]
166
+
167
+ return hashes, rewritten_index_bytes
168
+
169
+
170
+ def _compute_resource_version(
171
+ app_package_path: pathlib.Path,
172
+ resource_allow_list: frozenset[str] | None,
173
+ ) -> str | None:
174
+ if not resource_allow_list:
175
+ return None
176
+ digest = hashlib.sha256()
177
+ has_entry = False
178
+ for rel_path in sorted(resource_allow_list):
179
+ target = app_package_path / rel_path
180
+ if not target.is_file():
181
+ continue
182
+ file_hash = hashlib.sha256(target.read_bytes()).hexdigest()
183
+ digest.update(f"{rel_path}:{file_hash}\n".encode())
184
+ has_entry = True
185
+ return digest.hexdigest()[:8] if has_entry else None
186
+
187
+
188
+ @dataclass
189
+ class BuildArtifacts:
190
+ app_version: str
191
+ wheel_filename: str
192
+ fw_wheel_filename: str = ""
193
+ extra_wheel_filenames: list[str] | None = None
194
+ pyodide_package_names: list[str] = field(default_factory=list)
195
+ wasm_local_urls: dict[str, str] | None = None
196
+ lockfile_url: str | None = None
197
+ runtime_serving: str = "cdn"
198
+ app_package_files: dict[str, tuple[bytes, str]] | None = None
199
+ wasm_asset_files: dict[str, pathlib.Path] | None = None
200
+ runtime_asset_files: dict[str, pathlib.Path] | None = None
201
+ resource_allow_list: frozenset[str] | None = None
202
+ resource_version: str | None = None
203
+ asset_hashes: dict[str, str] | None = None
204
+ framework_ui_index_css: bytes | None = None
205
+ dist_dir: pathlib.Path | None = None
206
+ dev_mode: bool = False
207
+ cdn_temp_dir_obj: TemporaryDirectory | None = None
208
+
209
+
210
+ def resolve_build_artifacts(
211
+ app: WebComPyApp,
212
+ build_config: WebComPyBuildConfig,
213
+ *,
214
+ dev_mode: bool = False,
215
+ dist_dir: pathlib.Path | None = None,
216
+ ) -> BuildArtifacts:
217
+ build_config.pwa.validate(
218
+ app_package_path=build_config.app_package_path,
219
+ static_files_dir=build_config.static_files_dir,
220
+ )
221
+ extra_excluded_prefixes = _build_output_exclude_prefixes(build_config)
222
+ resource_allow_list = _detect_resources(
223
+ build_config.app_package_path,
224
+ build_config.resources,
225
+ build_config.resource_exclude,
226
+ extra_excluded_prefixes=extra_excluded_prefixes,
227
+ )
228
+ resource_port = ServerResourcePort(
229
+ app_package_path=build_config.app_package_path,
230
+ allow_list=resource_allow_list,
231
+ )
232
+ configure_server_context(app, resource_port=resource_port)
233
+ print(
234
+ f"Detected {len(resource_allow_list)} resource file(s)",
235
+ file=sys.stderr,
236
+ flush=True,
237
+ )
238
+
239
+ modules_dir = build_config.app_package_path / ".webcompy_modules"
240
+ ensure_webcompy_modules_dir(modules_dir)
241
+ resolve_dependencies(build_config)
242
+ assert build_config.dependencies is not None
243
+
244
+ lockfile, lockfile_errors, lockfile_warnings = resolve_lockfile(
245
+ build_config.dependencies,
246
+ PYSCRIPT_VERSION,
247
+ build_config.app_package_path / LOCKFILE_NAME,
248
+ modules_dir,
249
+ wasm_serving=build_config.wasm_serving or "cdn",
250
+ runtime_serving=build_config.runtime_serving or "cdn",
251
+ standalone=build_config.standalone,
252
+ )
253
+ for warning in lockfile_warnings:
254
+ print(f"Warning: {warning}", file=sys.stderr, flush=True)
255
+ for err in lockfile_errors:
256
+ print(f"Error: {err}", file=sys.stderr, flush=True)
257
+
258
+ if lockfile is not None:
259
+ env_errors, env_warnings = validate_local_environment(lockfile, serve_all_deps=build_config.serve_all_deps)
260
+ for warning in env_warnings:
261
+ print(f"Warning: {warning}", file=sys.stderr, flush=True)
262
+ for err in env_errors:
263
+ print(f"Error: {err}", file=sys.stderr, flush=True)
264
+ lockfile_errors.extend(env_errors)
265
+
266
+ if lockfile_errors:
267
+ print("Build failed due to lock file errors. Fix the above issues and try again.", file=sys.stderr)
268
+ sys.exit(1)
269
+
270
+ bundled_deps = get_bundled_deps(lockfile, serve_all_deps=build_config.serve_all_deps)
271
+ wasm_package_names = get_wasm_package_names(lockfile)
272
+
273
+ resolved_wasm_serving = build_config.wasm_serving or "cdn"
274
+ resolved_runtime_serving = build_config.runtime_serving or "cdn"
275
+ base_url = app.config.base_url
276
+ wasm_local_urls: dict[str, str] = {}
277
+ wasm_asset_files: dict[str, pathlib.Path] = {}
278
+ lockfile_url: str | None = None
279
+
280
+ if resolved_wasm_serving == "local" and lockfile is not None:
281
+ pyodide_version = lockfile.pyodide_version
282
+ lockfile_url = PYODIDE_LOCK_URL_TEMPLATE.format(version=pyodide_version)
283
+ downloaded_paths = download_wasm_wheels(lockfile, modules_dir)
284
+ for name, entry in lockfile.wasm_packages.items():
285
+ if entry.file_name and entry.sha256:
286
+ wasm_local_urls[name] = f"{base_url}_webcompy-assets/packages/{entry.file_name}"
287
+ if name in downloaded_paths:
288
+ wasm_asset_files[entry.file_name] = downloaded_paths[name]
289
+
290
+ runtime_asset_files: dict[str, pathlib.Path] = {}
291
+ cdn_temp_dir_obj: TemporaryDirectory | None = None
292
+ if resolved_runtime_serving == "local":
293
+ try:
294
+ runtime_results = download_runtime_assets(
295
+ lockfile.pyodide_version if lockfile else get_pyodide_version(PYSCRIPT_VERSION),
296
+ PYSCRIPT_VERSION,
297
+ modules_dir,
298
+ lock_file=lockfile,
299
+ )
300
+ if lockfile is not None:
301
+ verify_and_update_runtime_assets(
302
+ runtime_results,
303
+ lockfile,
304
+ PYSCRIPT_VERSION,
305
+ build_config.app_package_path / LOCKFILE_NAME,
306
+ )
307
+ for rel_path, (asset_path, _sha256) in runtime_results.items():
308
+ runtime_asset_files[rel_path] = asset_path
309
+ except RuntimeDownloadError as e:
310
+ print(f"Error: {e}", file=sys.stderr)
311
+ sys.exit(1)
312
+ lockfile_url = None
313
+
314
+ cdn_pure_python_names: list[str] = []
315
+ cdn_extracted_deps: list[tuple[str, pathlib.Path]] = []
316
+ if not build_config.serve_all_deps:
317
+ cdn_pure_python_names = get_cdn_pure_python_package_names(lockfile)
318
+ elif lockfile is not None:
319
+ for name, entry in lockfile.pure_python_packages.items():
320
+ if entry.in_pyodide_cdn and entry.pyodide_file_name and entry.pyodide_sha256:
321
+ try:
322
+ wheel_path = download_pyodide_wheel(
323
+ entry.pyodide_file_name,
324
+ lockfile.pyodide_version,
325
+ entry.pyodide_sha256,
326
+ modules_dir,
327
+ )
328
+ except PyodideDownloadError as e:
329
+ print(f"Error: {e}", file=sys.stderr)
330
+ sys.exit(1)
331
+ if cdn_temp_dir_obj is None:
332
+ cdn_temp_dir_obj = TemporaryDirectory()
333
+ cdn_temp_dir_obj.__enter__()
334
+ extract_dest = pathlib.Path(cdn_temp_dir_obj.name) / name
335
+ extract_dest.mkdir(parents=True, exist_ok=True)
336
+ extracted = extract_wheel(wheel_path, extract_dest)
337
+ cdn_extracted_deps.extend(extracted)
338
+
339
+ all_bundled_deps = bundled_deps + cdn_extracted_deps
340
+
341
+ app_version = generate_app_version(build_config.version)
342
+ wheel_mode = build_config.wheel_mode
343
+
344
+ with TemporaryDirectory() as _temp:
345
+ temp_path = pathlib.Path(_temp)
346
+ if wheel_mode == "split":
347
+ fw_wheel = make_browser_webcompy_wheel(
348
+ get_webcompy_packge_dir(),
349
+ temp_path,
350
+ app_version,
351
+ )
352
+ app_wheel_path = make_webcompy_app_package(
353
+ temp_path,
354
+ get_webcompy_packge_dir(),
355
+ build_config.app_package_path,
356
+ app_version,
357
+ bundled_deps=all_bundled_deps or None,
358
+ skip_webcompy=True,
359
+ exclude_rel_prefixes=extra_excluded_prefixes,
360
+ )
361
+ app_wheel_filename = app_wheel_path.name
362
+ fw_wheel_filename = fw_wheel.name
363
+ else:
364
+ app_wheel_path = make_webcompy_app_package(
365
+ temp_path,
366
+ get_webcompy_packge_dir(),
367
+ build_config.app_package_path,
368
+ app_version,
369
+ bundled_deps=all_bundled_deps or None,
370
+ exclude_rel_prefixes=extra_excluded_prefixes,
371
+ )
372
+ app_wheel_filename = app_wheel_path.name
373
+ fw_wheel_filename = ""
374
+
375
+ import mimetypes
376
+
377
+ app_package_files: dict[str, tuple[bytes, str]] = {
378
+ p.name: (
379
+ p.read_bytes(),
380
+ mimetypes.guess_type(str(p))[0] or "application/octet-stream",
381
+ )
382
+ for p in sorted(temp_path.iterdir(), key=lambda path: path.name)
383
+ }
384
+
385
+ extra_wheel_filenames: list[str] | None = None
386
+ if wheel_mode == "split":
387
+ extra_wheel_filenames = sorted(
388
+ f.name for f in temp_path.iterdir() if f.name.endswith(".whl") and f.name != app_wheel_filename
389
+ )
390
+
391
+ pyodide_package_names = wasm_package_names + cdn_pure_python_names
392
+
393
+ if cdn_temp_dir_obj is not None:
394
+ cdn_temp_dir_obj.__exit__(None, None, None)
395
+ cdn_temp_dir_obj = None
396
+
397
+ if not dev_mode:
398
+ static_files_dir = (build_config.app_package_path / build_config.static_files_dir).absolute()
399
+ asset_hashes, framework_ui_index_css = _compute_asset_hashes(static_files_dir)
400
+ resource_version = _compute_resource_version(build_config.app_package_path, resource_allow_list)
401
+ else:
402
+ asset_hashes = None
403
+ framework_ui_index_css = None
404
+ resource_version = None
405
+
406
+ return BuildArtifacts(
407
+ app_version=app_version,
408
+ wheel_filename=app_wheel_filename,
409
+ fw_wheel_filename=fw_wheel_filename,
410
+ extra_wheel_filenames=extra_wheel_filenames,
411
+ pyodide_package_names=pyodide_package_names,
412
+ wasm_local_urls=wasm_local_urls or None,
413
+ lockfile_url=lockfile_url,
414
+ runtime_serving=resolved_runtime_serving,
415
+ app_package_files=app_package_files,
416
+ wasm_asset_files=wasm_asset_files or None,
417
+ runtime_asset_files=runtime_asset_files or None,
418
+ resource_allow_list=resource_allow_list,
419
+ resource_version=resource_version,
420
+ asset_hashes=asset_hashes,
421
+ framework_ui_index_css=framework_ui_index_css,
422
+ dist_dir=dist_dir,
423
+ dev_mode=dev_mode,
424
+ cdn_temp_dir_obj=cdn_temp_dir_obj,
425
+ )
@@ -0,0 +1,15 @@
1
+ """Console message types for browser automation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass
9
+ class ConsoleMessage:
10
+ type: str
11
+ text: str
12
+ location: str
13
+
14
+ def format(self) -> str:
15
+ return f"[{self.type}] {self.text} ({self.location})"