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.
- webcompy_cli/__init__.py +20 -0
- webcompy_cli/_argparser.py +232 -0
- webcompy_cli/_browser_probes.py +648 -0
- webcompy_cli/_browser_test_harness.py +554 -0
- webcompy_cli/_build.py +425 -0
- webcompy_cli/_console_types.py +15 -0
- webcompy_cli/_dependency_resolver.py +301 -0
- webcompy_cli/_dualrun_pytest_plugin.py +130 -0
- webcompy_cli/_exception.py +9 -0
- webcompy_cli/_generate.py +224 -0
- webcompy_cli/_init_project.py +54 -0
- webcompy_cli/_inspect.py +741 -0
- webcompy_cli/_inspect_pyexec.py +244 -0
- webcompy_cli/_lock.py +82 -0
- webcompy_cli/_lockfile.py +396 -0
- webcompy_cli/_lockfile_sync.py +343 -0
- webcompy_cli/_output.py +150 -0
- webcompy_cli/_prebuild.py +661 -0
- webcompy_cli/_pwa.py +474 -0
- webcompy_cli/_pyodide_downloader.py +113 -0
- webcompy_cli/_pyodide_lock.py +74 -0
- webcompy_cli/_runtime_downloader.py +222 -0
- webcompy_cli/_server.py +568 -0
- webcompy_cli/_static_files.py +27 -0
- webcompy_cli/_utils.py +72 -0
- webcompy_cli/_version_sweep.py +213 -0
- webcompy_cli/_wheel_builder.py +509 -0
- webcompy_cli/config/__init__.py +23 -0
- webcompy_cli/config/_build_config.py +168 -0
- webcompy_cli/config/_pwa_config.py +203 -0
- webcompy_cli/config/_server_config.py +53 -0
- webcompy_cli/py.typed +0 -0
- webcompy_cli/template_data/app/__init__.py +0 -0
- webcompy_cli/template_data/app/app.py +22 -0
- webcompy_cli/template_data/app/components/__init__.py +0 -0
- webcompy_cli/template_data/app/components/fizzbuzz.py +117 -0
- webcompy_cli/template_data/app/components/home.py +15 -0
- webcompy_cli/template_data/app/components/input.py +34 -0
- webcompy_cli/template_data/app/components/navigation.py +36 -0
- webcompy_cli/template_data/app/components/not_found.py +22 -0
- webcompy_cli/template_data/app/components/root.py +16 -0
- webcompy_cli/template_data/app/router.py +17 -0
- webcompy_cli/template_data/webcompy_config.py +12 -0
- webcompy_cli-0.0.14.dist-info/METADATA +53 -0
- webcompy_cli-0.0.14.dist-info/RECORD +47 -0
- webcompy_cli-0.0.14.dist-info/WHEEL +4 -0
- webcompy_cli-0.0.14.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,661 @@
|
|
|
1
|
+
"""Atomic build-once prebuild pipeline for SSR, hybrid, and SSG deployments."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import base64
|
|
7
|
+
import contextlib
|
|
8
|
+
import importlib.metadata
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import secrets
|
|
12
|
+
import shutil
|
|
13
|
+
import sys
|
|
14
|
+
from collections.abc import Coroutine, Mapping, Sequence
|
|
15
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import TYPE_CHECKING, Any, Literal, cast
|
|
19
|
+
|
|
20
|
+
import httpx
|
|
21
|
+
|
|
22
|
+
from webcompy.di._keys import ERROR_POLICY_KEY
|
|
23
|
+
from webcompy.router import LazyComponentGenerator
|
|
24
|
+
from webcompy_cli._argparser import get_params
|
|
25
|
+
from webcompy_cli._exception import WebComPyCliException
|
|
26
|
+
from webcompy_cli._generate import _collect_full_text_resources
|
|
27
|
+
from webcompy_cli._output import copy_static_files, materialize_build_assets, write_pwa_outputs
|
|
28
|
+
from webcompy_cli._server import _apply_cli_overrides, create_asgi_app
|
|
29
|
+
from webcompy_cli._utils import discover_config
|
|
30
|
+
from webcompy_server._html import (
|
|
31
|
+
PYSCRIPT_VERSION,
|
|
32
|
+
_resolve_loading_config,
|
|
33
|
+
_resolve_loading_template,
|
|
34
|
+
_validate_loading_template,
|
|
35
|
+
)
|
|
36
|
+
from webcompy_server._prebuild import (
|
|
37
|
+
PREBUILD_MANIFEST_FILENAME,
|
|
38
|
+
PREBUILD_SCHEMA_VERSION,
|
|
39
|
+
PrebuildManifest,
|
|
40
|
+
PrebuildStaticRouteMeta,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
if TYPE_CHECKING:
|
|
44
|
+
from webcompy.app._app import WebComPyApp
|
|
45
|
+
from webcompy_cli.config._build_config import WebComPyBuildConfig
|
|
46
|
+
|
|
47
|
+
_EMIT_RESOURCE_MAX_BYTES = 256 * 1024
|
|
48
|
+
_EMIT_RESOURCE_MAX_TOTAL_BYTES = 1024 * 1024
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class _PrerenderPlan:
|
|
53
|
+
history_mode: bool
|
|
54
|
+
target_route_indices: tuple[int, ...]
|
|
55
|
+
concrete_paths: tuple[str, ...]
|
|
56
|
+
has_404_html: bool
|
|
57
|
+
ssr_enabled: bool
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _resolve_output_dir(app_package_path: Path, prebuild_dir: str, output_dir: str | Path | None) -> Path:
|
|
61
|
+
raw = Path(prebuild_dir) if output_dir is None else Path(output_dir)
|
|
62
|
+
resolved = raw.resolve() if raw.is_absolute() else (app_package_path / raw).resolve()
|
|
63
|
+
cwd = Path.cwd().resolve()
|
|
64
|
+
pkg = app_package_path.resolve()
|
|
65
|
+
|
|
66
|
+
if resolved == resolved.parent:
|
|
67
|
+
raise WebComPyCliException(f"Refusing dangerous prebuild output path at filesystem root: {resolved}")
|
|
68
|
+
if resolved == cwd or resolved in cwd.parents:
|
|
69
|
+
raise WebComPyCliException(
|
|
70
|
+
f"Refusing dangerous prebuild output path {resolved}: matches or is an ancestor of CWD ({cwd})."
|
|
71
|
+
)
|
|
72
|
+
if resolved == pkg or resolved in pkg.parents:
|
|
73
|
+
raise WebComPyCliException(
|
|
74
|
+
f"Refusing dangerous prebuild output path {resolved}: matches or is an ancestor of app_package_path ({pkg})."
|
|
75
|
+
)
|
|
76
|
+
return resolved
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _is_path_within(path: Path, root: Path) -> bool:
|
|
80
|
+
try:
|
|
81
|
+
path.resolve().relative_to(root.resolve())
|
|
82
|
+
return True
|
|
83
|
+
except ValueError:
|
|
84
|
+
return False
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _validate_emit_python_path(emit_python_path: str | Path, app_package_path: Path) -> Path:
|
|
88
|
+
raw = Path(emit_python_path)
|
|
89
|
+
resolved = raw.resolve() if raw.is_absolute() else (Path.cwd() / raw).resolve()
|
|
90
|
+
if _is_path_within(resolved, app_package_path):
|
|
91
|
+
raise WebComPyCliException(
|
|
92
|
+
f"Refusing --emit-python target {resolved} inside app_package_path ({app_package_path.resolve()}): "
|
|
93
|
+
"server manifests must remain outside browser wheels."
|
|
94
|
+
)
|
|
95
|
+
return resolved
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _plan_prerender(
|
|
99
|
+
app: WebComPyApp,
|
|
100
|
+
prerender_mode: Literal["none", "static", "all"],
|
|
101
|
+
) -> _PrerenderPlan:
|
|
102
|
+
router = app.router
|
|
103
|
+
if app.router_mode == "history" and app.routes:
|
|
104
|
+
target_indices: list[int] = []
|
|
105
|
+
concrete_paths: list[str] = []
|
|
106
|
+
seen_paths: set[str] = set()
|
|
107
|
+
any_omitted = False
|
|
108
|
+
|
|
109
|
+
for i, (pattern, _, _, _, _) in enumerate(app.routes):
|
|
110
|
+
effective = router.get_route_prerender(i) if router is not None else None
|
|
111
|
+
variants = router.__route_variants__[i] if router is not None else None
|
|
112
|
+
is_enumerable = ("{" not in pattern) or (variants is not None)
|
|
113
|
+
display_path = "/" + pattern.lstrip("/")
|
|
114
|
+
|
|
115
|
+
if prerender_mode == "none":
|
|
116
|
+
if effective is True:
|
|
117
|
+
if not is_enumerable:
|
|
118
|
+
raise WebComPyCliException(
|
|
119
|
+
f"Cannot prerender route '{display_path}': dynamic route requires 'path_params' when prerender=True."
|
|
120
|
+
)
|
|
121
|
+
else:
|
|
122
|
+
any_omitted = True
|
|
123
|
+
continue
|
|
124
|
+
elif prerender_mode == "static":
|
|
125
|
+
if effective is False:
|
|
126
|
+
any_omitted = True
|
|
127
|
+
continue
|
|
128
|
+
if not is_enumerable:
|
|
129
|
+
if effective is True:
|
|
130
|
+
raise WebComPyCliException(
|
|
131
|
+
f"Cannot prerender route '{display_path}': dynamic route requires 'path_params' when prerender=True."
|
|
132
|
+
)
|
|
133
|
+
any_omitted = True
|
|
134
|
+
continue
|
|
135
|
+
else:
|
|
136
|
+
if effective is False:
|
|
137
|
+
raise WebComPyCliException(
|
|
138
|
+
f"Route '{display_path}' sets prerender=False, which conflicts with prerender='all'. "
|
|
139
|
+
"Remove prerender=False or use prerender='static'/'none'."
|
|
140
|
+
)
|
|
141
|
+
if not is_enumerable:
|
|
142
|
+
raise WebComPyCliException(
|
|
143
|
+
f"Cannot prerender route '{display_path}' with prerender='all': dynamic route lacks 'path_params'. "
|
|
144
|
+
"Add 'path_params' or use prerender='static'/'none'."
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
target_indices.append(i)
|
|
148
|
+
expanded = [pattern] if variants is None else [pattern.format(**params) for params in variants]
|
|
149
|
+
for cpath in expanded:
|
|
150
|
+
norm = cpath.strip("/")
|
|
151
|
+
if norm not in seen_paths:
|
|
152
|
+
seen_paths.add(norm)
|
|
153
|
+
concrete_paths.append(norm)
|
|
154
|
+
|
|
155
|
+
has_404_html = prerender_mode in ("static", "all")
|
|
156
|
+
if prerender_mode == "none":
|
|
157
|
+
ssr_enabled = True
|
|
158
|
+
elif prerender_mode == "static":
|
|
159
|
+
ssr_enabled = any_omitted
|
|
160
|
+
else:
|
|
161
|
+
ssr_enabled = False
|
|
162
|
+
return _PrerenderPlan(
|
|
163
|
+
history_mode=True,
|
|
164
|
+
target_route_indices=tuple(target_indices),
|
|
165
|
+
concrete_paths=tuple(concrete_paths),
|
|
166
|
+
has_404_html=has_404_html,
|
|
167
|
+
ssr_enabled=ssr_enabled,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
if prerender_mode in ("static", "all") and router is not None and app.routes:
|
|
171
|
+
for i, (pattern, _, _, _, _) in enumerate(app.routes):
|
|
172
|
+
if router.get_route_prerender(i) is False:
|
|
173
|
+
display_path = "/" + pattern.lstrip("/")
|
|
174
|
+
raise WebComPyCliException(
|
|
175
|
+
f"Route '{display_path}' sets prerender=False, which cannot remain dynamic in hash mode when prerender='{prerender_mode}'."
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
if prerender_mode == "none":
|
|
179
|
+
return _PrerenderPlan(
|
|
180
|
+
history_mode=False,
|
|
181
|
+
target_route_indices=(),
|
|
182
|
+
concrete_paths=(),
|
|
183
|
+
has_404_html=False,
|
|
184
|
+
ssr_enabled=True,
|
|
185
|
+
)
|
|
186
|
+
return _PrerenderPlan(
|
|
187
|
+
history_mode=False,
|
|
188
|
+
target_route_indices=(),
|
|
189
|
+
concrete_paths=("",),
|
|
190
|
+
has_404_html=False,
|
|
191
|
+
ssr_enabled=False,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _preload_target_routes(app: WebComPyApp, plan: _PrerenderPlan) -> None:
|
|
196
|
+
if not plan.history_mode or not app.routes or not plan.target_route_indices:
|
|
197
|
+
return
|
|
198
|
+
router = app.router
|
|
199
|
+
if (
|
|
200
|
+
router is not None
|
|
201
|
+
and len(plan.target_route_indices) == len(app.routes)
|
|
202
|
+
and getattr(router, "preload_lazy_routes", None) is not None
|
|
203
|
+
):
|
|
204
|
+
router.preload_lazy_routes(force=True)
|
|
205
|
+
return
|
|
206
|
+
for idx in plan.target_route_indices:
|
|
207
|
+
if router is not None:
|
|
208
|
+
for node in router.__chains__[idx].chain:
|
|
209
|
+
component = node.page["component"]
|
|
210
|
+
if isinstance(component, LazyComponentGenerator):
|
|
211
|
+
component._preload()
|
|
212
|
+
else:
|
|
213
|
+
component = app.routes[idx][4]["component"]
|
|
214
|
+
if isinstance(component, LazyComponentGenerator):
|
|
215
|
+
component._preload()
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _run_coro_sync[T](coro: Coroutine[Any, Any, T]) -> T:
|
|
219
|
+
try:
|
|
220
|
+
asyncio.get_running_loop()
|
|
221
|
+
except RuntimeError:
|
|
222
|
+
return asyncio.run(coro)
|
|
223
|
+
with ThreadPoolExecutor(max_workers=1) as executor:
|
|
224
|
+
return executor.submit(asyncio.run, coro).result()
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
async def _render_http_outputs(
|
|
228
|
+
app: WebComPyApp,
|
|
229
|
+
serving_asgi: Any,
|
|
230
|
+
public_dir: Path,
|
|
231
|
+
plan: _PrerenderPlan,
|
|
232
|
+
static_route_paths: tuple[str, ...],
|
|
233
|
+
) -> tuple[dict[str, str], tuple[PrebuildStaticRouteMeta, ...]]:
|
|
234
|
+
base_url_path = app.config.base_url.strip("/")
|
|
235
|
+
url_prefix = f"/{base_url_path}" if base_url_path else ""
|
|
236
|
+
prerendered_routes: dict[str, str] = {}
|
|
237
|
+
static_route_metas: list[PrebuildStaticRouteMeta] = []
|
|
238
|
+
|
|
239
|
+
if not plan.concrete_paths and not plan.has_404_html and not static_route_paths:
|
|
240
|
+
return prerendered_routes, ()
|
|
241
|
+
|
|
242
|
+
async with httpx.AsyncClient(
|
|
243
|
+
transport=httpx.ASGITransport(app=serving_asgi),
|
|
244
|
+
base_url="http://testserver",
|
|
245
|
+
) as client:
|
|
246
|
+
if plan.history_mode:
|
|
247
|
+
for norm in plan.concrete_paths:
|
|
248
|
+
req_url = f"{url_prefix}/{norm}" if norm else f"{url_prefix}/"
|
|
249
|
+
response = await client.get(req_url, headers={"Accept": "text/html"})
|
|
250
|
+
if response.status_code != 200:
|
|
251
|
+
raise WebComPyCliException(f"Failed to prerender route '/{norm}': HTTP {response.status_code}")
|
|
252
|
+
rel_html = f"{norm}/index.html" if norm else "index.html"
|
|
253
|
+
html_path = public_dir / rel_html
|
|
254
|
+
html_path.parent.mkdir(parents=True, exist_ok=True)
|
|
255
|
+
html_path.write_text(response.text, encoding="utf-8")
|
|
256
|
+
prerendered_routes[norm] = rel_html
|
|
257
|
+
|
|
258
|
+
if plan.has_404_html:
|
|
259
|
+
response_404 = await client.get(f"{url_prefix}/_webcompy_404", headers={"Accept": "text/html"})
|
|
260
|
+
html_404_path = public_dir / "404.html"
|
|
261
|
+
html_404_path.write_text(response_404.text, encoding="utf-8")
|
|
262
|
+
elif plan.concrete_paths:
|
|
263
|
+
response = await client.get(f"{url_prefix}/", headers={"Accept": "text/html"})
|
|
264
|
+
if response.status_code != 200:
|
|
265
|
+
raise WebComPyCliException(f"Failed to prerender hash root '/': HTTP {response.status_code}")
|
|
266
|
+
html_path = public_dir / "index.html"
|
|
267
|
+
html_path.write_text(response.text, encoding="utf-8")
|
|
268
|
+
prerendered_routes[""] = "index.html"
|
|
269
|
+
|
|
270
|
+
for rel_path in static_route_paths:
|
|
271
|
+
resp = await client.get(f"{url_prefix}/{rel_path}")
|
|
272
|
+
if resp.status_code != 200:
|
|
273
|
+
raise WebComPyCliException(
|
|
274
|
+
f"Failed to materialize virtual static route '/{rel_path}': HTTP {resp.status_code}"
|
|
275
|
+
)
|
|
276
|
+
dst = public_dir / rel_path
|
|
277
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
278
|
+
dst.write_bytes(resp.content)
|
|
279
|
+
static_route_metas.append(
|
|
280
|
+
PrebuildStaticRouteMeta(
|
|
281
|
+
path=rel_path,
|
|
282
|
+
media_type=resp.headers.get("content-type", "application/octet-stream"),
|
|
283
|
+
cache_control=resp.headers.get("cache-control", "public, max-age=0, must-revalidate"),
|
|
284
|
+
)
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
return prerendered_routes, tuple(static_route_metas)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _format_str_tuple(values: Sequence[str] | None, *, indent: int = 4) -> str:
|
|
291
|
+
if values is None:
|
|
292
|
+
return "None"
|
|
293
|
+
if not values:
|
|
294
|
+
return "()"
|
|
295
|
+
if len(values) == 1 and len(repr(values[0])) <= 70:
|
|
296
|
+
return f"({values[0]!r},)"
|
|
297
|
+
pad = " " * (indent + 4)
|
|
298
|
+
end_pad = " " * indent
|
|
299
|
+
items = "\n".join(f"{pad}{item!r}," for item in values)
|
|
300
|
+
return f"(\n{items}\n{end_pad})"
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _format_str_dict(mapping: Mapping[str, str], *, indent: int = 4) -> str:
|
|
304
|
+
if not mapping:
|
|
305
|
+
return "{}"
|
|
306
|
+
pad = " " * (indent + 4)
|
|
307
|
+
end_pad = " " * indent
|
|
308
|
+
items = "\n".join(f"{pad}{k!r}: {v!r}," for k, v in mapping.items())
|
|
309
|
+
return f"{{\n{items}\n{end_pad}}}"
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _format_static_routes(routes: tuple[PrebuildStaticRouteMeta, ...], *, indent: int = 4) -> str:
|
|
313
|
+
if not routes:
|
|
314
|
+
return "()"
|
|
315
|
+
pad = " " * (indent + 4)
|
|
316
|
+
inner_pad = " " * (indent + 8)
|
|
317
|
+
end_pad = " " * indent
|
|
318
|
+
parts: list[str] = []
|
|
319
|
+
for meta in routes:
|
|
320
|
+
parts.append(
|
|
321
|
+
f"{pad}PrebuildStaticRouteMeta(\n"
|
|
322
|
+
f"{inner_pad}path={meta.path!r},\n"
|
|
323
|
+
f"{inner_pad}media_type={meta.media_type!r},\n"
|
|
324
|
+
f"{inner_pad}cache_control={meta.cache_control!r},\n"
|
|
325
|
+
f"{pad}),"
|
|
326
|
+
)
|
|
327
|
+
return "(\n" + "\n".join(parts) + f"\n{end_pad})"
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _format_embedded_resources(resources: Mapping[str, bytes] | None, *, indent: int = 4) -> str:
|
|
331
|
+
if resources is None:
|
|
332
|
+
return "None"
|
|
333
|
+
if not resources:
|
|
334
|
+
return "{}"
|
|
335
|
+
pad = " " * (indent + 4)
|
|
336
|
+
chunk_pad = " " * (indent + 8)
|
|
337
|
+
end_pad = " " * indent
|
|
338
|
+
entries: list[str] = []
|
|
339
|
+
for rel_path, raw in resources.items():
|
|
340
|
+
b64 = base64.b64encode(raw).decode("ascii")
|
|
341
|
+
if len(b64) <= 72:
|
|
342
|
+
entries.append(f"{pad}{rel_path!r}: base64.b64decode({b64!r}),")
|
|
343
|
+
else:
|
|
344
|
+
chunks = "\n".join(f'{chunk_pad}"{b64[i : i + 72]}"' for i in range(0, len(b64), 72))
|
|
345
|
+
entries.append(f"{pad}{rel_path!r}: base64.b64decode(\n{chunks}\n{pad}),")
|
|
346
|
+
return "{\n" + "\n".join(entries) + f"\n{end_pad}}}"
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _collect_embedded_resources(
|
|
350
|
+
resource_allow_list: tuple[str, ...],
|
|
351
|
+
app_package_path: Path,
|
|
352
|
+
) -> dict[str, bytes]:
|
|
353
|
+
embedded: dict[str, bytes] = {}
|
|
354
|
+
for rel_path in resource_allow_list:
|
|
355
|
+
data = (app_package_path / rel_path).read_bytes()
|
|
356
|
+
if len(data) > _EMIT_RESOURCE_MAX_BYTES:
|
|
357
|
+
print(
|
|
358
|
+
f"Warning: embedded resource {rel_path!r} ({len(data)} bytes) exceeds {_EMIT_RESOURCE_MAX_BYTES} bytes.",
|
|
359
|
+
file=sys.stderr,
|
|
360
|
+
flush=True,
|
|
361
|
+
)
|
|
362
|
+
embedded[rel_path] = data
|
|
363
|
+
total = sum(len(data) for data in embedded.values())
|
|
364
|
+
if total > _EMIT_RESOURCE_MAX_TOTAL_BYTES:
|
|
365
|
+
print(
|
|
366
|
+
f"Warning: total embedded resources ({total} bytes) exceed {_EMIT_RESOURCE_MAX_TOTAL_BYTES} bytes; "
|
|
367
|
+
"consider --no-embed-resources paired with external asset storage.",
|
|
368
|
+
file=sys.stderr,
|
|
369
|
+
flush=True,
|
|
370
|
+
)
|
|
371
|
+
return embedded
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _emit_python_manifest(
|
|
375
|
+
manifest: PrebuildManifest,
|
|
376
|
+
resolved_emit_path: Path,
|
|
377
|
+
*,
|
|
378
|
+
app_package_path: Path,
|
|
379
|
+
embed_resources: bool,
|
|
380
|
+
) -> Path:
|
|
381
|
+
embedded = _collect_embedded_resources(manifest.resource_allow_list, app_package_path) if embed_resources else None
|
|
382
|
+
needs_base64 = bool(embedded)
|
|
383
|
+
needs_route_meta = bool(manifest.static_routes)
|
|
384
|
+
|
|
385
|
+
lines: list[str] = [
|
|
386
|
+
'"""Generated standalone WebComPy prebuild manifest."""',
|
|
387
|
+
"",
|
|
388
|
+
"from __future__ import annotations",
|
|
389
|
+
"",
|
|
390
|
+
]
|
|
391
|
+
if needs_base64:
|
|
392
|
+
lines.extend(["import base64", ""])
|
|
393
|
+
|
|
394
|
+
server_imports = ["PrebuildManifest", "PrebuildStaticRouteMeta"] if needs_route_meta else ["PrebuildManifest"]
|
|
395
|
+
lines.extend([f"from webcompy_server import {', '.join(server_imports)}", ""])
|
|
396
|
+
lines.extend(
|
|
397
|
+
[
|
|
398
|
+
"PREBUILD: PrebuildManifest = PrebuildManifest(",
|
|
399
|
+
f" schema_version={manifest.schema_version!r},",
|
|
400
|
+
f" webcompy_version={manifest.webcompy_version!r},",
|
|
401
|
+
f" pyscript_version={manifest.pyscript_version!r},",
|
|
402
|
+
f" app_package_name={manifest.app_package_name!r},",
|
|
403
|
+
f" app_version={manifest.app_version!r},",
|
|
404
|
+
f" base_url={manifest.base_url!r},",
|
|
405
|
+
f" wheel_mode={manifest.wheel_mode!r},",
|
|
406
|
+
f" wheel_filename={manifest.wheel_filename!r},",
|
|
407
|
+
f" fw_wheel_filename={manifest.fw_wheel_filename!r},",
|
|
408
|
+
f" extra_wheel_filenames={_format_str_tuple(manifest.extra_wheel_filenames)},",
|
|
409
|
+
f" pyodide_package_names={_format_str_tuple(manifest.pyodide_package_names)},",
|
|
410
|
+
f" wasm_serving={manifest.wasm_serving!r},",
|
|
411
|
+
f" wasm_asset_files={_format_str_dict(manifest.wasm_asset_files)},",
|
|
412
|
+
f" runtime_serving={manifest.runtime_serving!r},",
|
|
413
|
+
f" runtime_asset_files={_format_str_tuple(manifest.runtime_asset_files)},",
|
|
414
|
+
f" lockfile_url={manifest.lockfile_url!r},",
|
|
415
|
+
f" resource_allow_list={_format_str_tuple(manifest.resource_allow_list)},",
|
|
416
|
+
f" resource_version={manifest.resource_version!r},",
|
|
417
|
+
f" static_files={_format_str_tuple(manifest.static_files)},",
|
|
418
|
+
f" static_routes={_format_static_routes(manifest.static_routes)},",
|
|
419
|
+
f" asset_hashes={_format_str_dict(manifest.asset_hashes)},",
|
|
420
|
+
f" pwa_enabled={manifest.pwa_enabled!r},",
|
|
421
|
+
f" loading_template_html={manifest.loading_template_html!r},",
|
|
422
|
+
f" prerender_mode={manifest.prerender_mode!r},",
|
|
423
|
+
f" prerendered_routes={_format_str_dict(manifest.prerendered_routes)},",
|
|
424
|
+
f" has_404_html={manifest.has_404_html!r},",
|
|
425
|
+
f" ssr_enabled={manifest.ssr_enabled!r},",
|
|
426
|
+
f" embedded_resources={_format_embedded_resources(embedded)},",
|
|
427
|
+
")",
|
|
428
|
+
"",
|
|
429
|
+
'__all__ = ["PREBUILD"]',
|
|
430
|
+
"",
|
|
431
|
+
]
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
resolved_emit_path.parent.mkdir(parents=True, exist_ok=True)
|
|
435
|
+
tmp_file = resolved_emit_path.parent / f".{resolved_emit_path.name}.tmp-{os.getpid()}-{secrets.token_hex(4)}"
|
|
436
|
+
try:
|
|
437
|
+
tmp_file.write_text("\n".join(lines), encoding="utf-8")
|
|
438
|
+
os.replace(tmp_file, resolved_emit_path)
|
|
439
|
+
except BaseException:
|
|
440
|
+
with contextlib.suppress(OSError):
|
|
441
|
+
tmp_file.unlink()
|
|
442
|
+
raise
|
|
443
|
+
return resolved_emit_path
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _atomic_swap_directory(staging_dir: Path, target_dir: Path) -> None:
|
|
447
|
+
backup_dir: Path | None = None
|
|
448
|
+
try:
|
|
449
|
+
if target_dir.exists() or target_dir.is_symlink():
|
|
450
|
+
backup_dir = target_dir.parent / f".{target_dir.name}.backup-{os.getpid()}-{secrets.token_hex(4)}"
|
|
451
|
+
if backup_dir.exists():
|
|
452
|
+
shutil.rmtree(backup_dir)
|
|
453
|
+
os.replace(target_dir, backup_dir)
|
|
454
|
+
os.replace(staging_dir, target_dir)
|
|
455
|
+
except BaseException:
|
|
456
|
+
if backup_dir is not None and backup_dir.exists() and not target_dir.exists():
|
|
457
|
+
with contextlib.suppress(OSError):
|
|
458
|
+
os.replace(backup_dir, target_dir)
|
|
459
|
+
raise
|
|
460
|
+
else:
|
|
461
|
+
if backup_dir is not None and backup_dir.exists():
|
|
462
|
+
shutil.rmtree(backup_dir, ignore_errors=True)
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def prebuild_app(
|
|
466
|
+
app: WebComPyApp,
|
|
467
|
+
build_config: WebComPyBuildConfig,
|
|
468
|
+
*,
|
|
469
|
+
output_dir: str | Path | None = None,
|
|
470
|
+
emit_python_path: str | Path | None = None,
|
|
471
|
+
embed_resources: bool = True,
|
|
472
|
+
) -> Path:
|
|
473
|
+
"""Resolve build artifacts once and materialize an atomic prebuild directory.
|
|
474
|
+
|
|
475
|
+
Writes a self-contained directory containing ``.gitignore``, ``public/``
|
|
476
|
+
(wheels, local WASM/runtime assets, allow-listed resources, hash-rewritten
|
|
477
|
+
framework CSS, static files, materialized virtual static routes,
|
|
478
|
+
pre-rendered HTML pages, and optional PWA assets), and ``prebuild.json``
|
|
479
|
+
written last inside a staging directory before swapping atomically into
|
|
480
|
+
place. Rejects dangerous ``output_dir`` targets or ``emit_python_path``
|
|
481
|
+
values inside ``build_config.app_package_path`` with
|
|
482
|
+
``WebComPyCliException``, and propagates ``WebComPyException`` on asset,
|
|
483
|
+
template, static-route, or prerender errors without corrupting any existing
|
|
484
|
+
prebuild directory.
|
|
485
|
+
|
|
486
|
+
Args:
|
|
487
|
+
app: Target ``WebComPyApp`` instance to prebuild.
|
|
488
|
+
build_config: Build configuration describing packaging, resources,
|
|
489
|
+
``prebuild_dir``, and ``prerender`` depth.
|
|
490
|
+
output_dir: Optional output directory override. Relative paths resolve
|
|
491
|
+
against ``build_config.app_package_path``.
|
|
492
|
+
emit_python_path: Optional output path for a standalone Python manifest
|
|
493
|
+
module. Must resolve outside ``build_config.app_package_path``.
|
|
494
|
+
embed_resources: Whether allow-listed resources are embedded in-memory
|
|
495
|
+
when emitting a standalone Python manifest module.
|
|
496
|
+
|
|
497
|
+
Returns:
|
|
498
|
+
Resolved path to the materialized prebuild directory.
|
|
499
|
+
|
|
500
|
+
"""
|
|
501
|
+
target_dir = _resolve_output_dir(build_config.app_package_path, build_config.prebuild_dir, output_dir)
|
|
502
|
+
resolved_emit_path = (
|
|
503
|
+
_validate_emit_python_path(emit_python_path, build_config.app_package_path)
|
|
504
|
+
if emit_python_path is not None
|
|
505
|
+
else None
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
plan = _plan_prerender(app, build_config.prerender)
|
|
509
|
+
|
|
510
|
+
loading_cfg = _resolve_loading_config(app.config.loading)
|
|
511
|
+
resolved_loading_template = _resolve_loading_template(loading_cfg["template"], build_config.app_package_path)
|
|
512
|
+
if resolved_loading_template is not None:
|
|
513
|
+
_validate_loading_template(resolved_loading_template)
|
|
514
|
+
|
|
515
|
+
target_dir.parent.mkdir(parents=True, exist_ok=True)
|
|
516
|
+
staging_dir = target_dir.parent / f".{target_dir.name}.staging-{os.getpid()}-{secrets.token_hex(4)}"
|
|
517
|
+
staging_dir.mkdir(parents=True, exist_ok=False)
|
|
518
|
+
|
|
519
|
+
saved_ops = list(app._deferred_ops)
|
|
520
|
+
prev_dev = build_config.server.dev
|
|
521
|
+
artifacts = None
|
|
522
|
+
manifest: PrebuildManifest | None = None
|
|
523
|
+
succeeded = False
|
|
524
|
+
|
|
525
|
+
try:
|
|
526
|
+
(staging_dir / ".gitignore").write_text("*\n", encoding="utf-8")
|
|
527
|
+
public_dir = staging_dir / "public"
|
|
528
|
+
public_dir.mkdir(exist_ok=True)
|
|
529
|
+
|
|
530
|
+
app.provide(ERROR_POLICY_KEY, "ssg")
|
|
531
|
+
serving = create_asgi_app(app, build_config, mode="prod")
|
|
532
|
+
artifacts = serving.artifacts
|
|
533
|
+
assert artifacts is not None
|
|
534
|
+
|
|
535
|
+
static_files_dir = (build_config.app_package_path / build_config.static_files_dir).absolute()
|
|
536
|
+
static_files = copy_static_files(static_files_dir, public_dir)
|
|
537
|
+
materialize_build_assets(artifacts, build_config.app_package_path, public_dir)
|
|
538
|
+
|
|
539
|
+
_preload_target_routes(app, plan)
|
|
540
|
+
app._ssg_full_text_resources = _collect_full_text_resources(app, build_config, artifacts)
|
|
541
|
+
try:
|
|
542
|
+
prerendered_routes, static_route_metas = _run_coro_sync(
|
|
543
|
+
_render_http_outputs(app, serving.asgi, public_dir, plan, serving.static_route_paths)
|
|
544
|
+
)
|
|
545
|
+
finally:
|
|
546
|
+
app._ssg_full_text_resources = None
|
|
547
|
+
|
|
548
|
+
if build_config.pwa.enabled:
|
|
549
|
+
has_html_or_virtual = bool(prerendered_routes or static_route_metas or plan.has_404_html)
|
|
550
|
+
write_pwa_outputs(
|
|
551
|
+
build_config,
|
|
552
|
+
app,
|
|
553
|
+
artifacts,
|
|
554
|
+
public_dir,
|
|
555
|
+
precache_dir=public_dir if has_html_or_virtual else None,
|
|
556
|
+
)
|
|
557
|
+
|
|
558
|
+
wasm_asset_files = {pkg: url.rsplit("/", 1)[-1] for pkg, url in (artifacts.wasm_local_urls or {}).items()}
|
|
559
|
+
runtime_asset_files = tuple(sorted((artifacts.runtime_asset_files or {}).keys()))
|
|
560
|
+
resource_allow_list = tuple(sorted(artifacts.resource_allow_list or ()))
|
|
561
|
+
|
|
562
|
+
manifest = PrebuildManifest(
|
|
563
|
+
schema_version=PREBUILD_SCHEMA_VERSION,
|
|
564
|
+
webcompy_version=importlib.metadata.version("webcompy"),
|
|
565
|
+
pyscript_version=PYSCRIPT_VERSION,
|
|
566
|
+
app_package_name=build_config.app_package_path.name,
|
|
567
|
+
app_version=artifacts.app_version,
|
|
568
|
+
base_url=app.config.base_url,
|
|
569
|
+
wheel_mode=build_config.wheel_mode,
|
|
570
|
+
wheel_filename=artifacts.wheel_filename,
|
|
571
|
+
fw_wheel_filename=artifacts.fw_wheel_filename,
|
|
572
|
+
extra_wheel_filenames=(
|
|
573
|
+
tuple(artifacts.extra_wheel_filenames) if artifacts.extra_wheel_filenames is not None else None
|
|
574
|
+
),
|
|
575
|
+
pyodide_package_names=tuple(artifacts.pyodide_package_names),
|
|
576
|
+
wasm_serving=build_config.wasm_serving or "cdn",
|
|
577
|
+
wasm_asset_files=wasm_asset_files,
|
|
578
|
+
runtime_serving=cast("Literal['cdn', 'local']", artifacts.runtime_serving),
|
|
579
|
+
runtime_asset_files=runtime_asset_files,
|
|
580
|
+
lockfile_url=artifacts.lockfile_url,
|
|
581
|
+
resource_allow_list=resource_allow_list,
|
|
582
|
+
resource_version=artifacts.resource_version,
|
|
583
|
+
static_files=static_files,
|
|
584
|
+
static_routes=static_route_metas,
|
|
585
|
+
asset_hashes=dict(artifacts.asset_hashes) if artifacts.asset_hashes else {},
|
|
586
|
+
pwa_enabled=build_config.pwa.enabled,
|
|
587
|
+
loading_template_html=resolved_loading_template,
|
|
588
|
+
prerender_mode=build_config.prerender,
|
|
589
|
+
prerendered_routes=prerendered_routes,
|
|
590
|
+
has_404_html=plan.has_404_html,
|
|
591
|
+
ssr_enabled=plan.ssr_enabled,
|
|
592
|
+
)
|
|
593
|
+
(staging_dir / PREBUILD_MANIFEST_FILENAME).write_text(
|
|
594
|
+
json.dumps(manifest.to_dict(), indent=2) + "\n",
|
|
595
|
+
encoding="utf-8",
|
|
596
|
+
)
|
|
597
|
+
_atomic_swap_directory(staging_dir, target_dir)
|
|
598
|
+
succeeded = True
|
|
599
|
+
finally:
|
|
600
|
+
if not succeeded:
|
|
601
|
+
shutil.rmtree(staging_dir, ignore_errors=True)
|
|
602
|
+
app._deferred_ops = saved_ops
|
|
603
|
+
app._ssg_full_text_resources = None
|
|
604
|
+
build_config.server.dev = prev_dev
|
|
605
|
+
if artifacts is not None and artifacts.cdn_temp_dir_obj is not None:
|
|
606
|
+
artifacts.cdn_temp_dir_obj.cleanup()
|
|
607
|
+
|
|
608
|
+
if resolved_emit_path is not None and manifest is not None:
|
|
609
|
+
_emit_python_manifest(
|
|
610
|
+
manifest,
|
|
611
|
+
resolved_emit_path,
|
|
612
|
+
app_package_path=build_config.app_package_path,
|
|
613
|
+
embed_resources=embed_resources,
|
|
614
|
+
)
|
|
615
|
+
|
|
616
|
+
return target_dir
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def run_prebuild(args: dict[str, Any] | None = None) -> Path:
|
|
620
|
+
"""Execute the ``webcompy prebuild`` CLI workflow.
|
|
621
|
+
|
|
622
|
+
Args:
|
|
623
|
+
args: Optional parsed CLI argument dictionary. When ``None``, arguments
|
|
624
|
+
are read via ``get_params()``.
|
|
625
|
+
|
|
626
|
+
Returns:
|
|
627
|
+
Resolved path to the generated prebuild output directory.
|
|
628
|
+
|
|
629
|
+
Raises:
|
|
630
|
+
WebComPyCliException: When resource embedding flags are supplied without
|
|
631
|
+
``--emit-python``.
|
|
632
|
+
|
|
633
|
+
"""
|
|
634
|
+
if args is None:
|
|
635
|
+
_, args = get_params()
|
|
636
|
+
|
|
637
|
+
if args.get("embed_resources") is not None and not args.get("emit_python"):
|
|
638
|
+
raise WebComPyCliException("--embed-resources and --no-embed-resources require --emit-python.")
|
|
639
|
+
|
|
640
|
+
build_config = discover_config(args.get("config"))
|
|
641
|
+
_apply_cli_overrides(build_config, args)
|
|
642
|
+
prerender = args.get("prerender")
|
|
643
|
+
if prerender is not None:
|
|
644
|
+
build_config.prerender = prerender
|
|
645
|
+
|
|
646
|
+
raw_out = args.get("out")
|
|
647
|
+
output_dir = (
|
|
648
|
+
(Path(raw_out) if Path(raw_out).is_absolute() else Path.cwd() / raw_out) if raw_out is not None else None
|
|
649
|
+
)
|
|
650
|
+
raw_emit = args.get("emit_python")
|
|
651
|
+
emit_path = (
|
|
652
|
+
(Path(raw_emit) if Path(raw_emit).is_absolute() else Path.cwd() / raw_emit) if raw_emit is not None else None
|
|
653
|
+
)
|
|
654
|
+
embed_resources = True if args.get("embed_resources") is None else bool(args["embed_resources"])
|
|
655
|
+
return prebuild_app(
|
|
656
|
+
build_config.app,
|
|
657
|
+
build_config,
|
|
658
|
+
output_dir=output_dir,
|
|
659
|
+
emit_python_path=emit_path,
|
|
660
|
+
embed_resources=embed_resources,
|
|
661
|
+
)
|