webcompy-server 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_server/__init__.py +91 -0
- webcompy_server/_asgi.py +832 -0
- webcompy_server/_context.py +106 -0
- webcompy_server/_html.py +925 -0
- webcompy_server/_prebuild.py +487 -0
- webcompy_server/_static_route.py +41 -0
- webcompy_server/_teleport_emission.py +94 -0
- webcompy_server/contrib/__init__.py +0 -0
- webcompy_server/contrib/fastapi.py +42 -0
- webcompy_server/ports/__init__.py +35 -0
- webcompy_server/ports/_async_scheduler.py +74 -0
- webcompy_server/ports/_cookie.py +154 -0
- webcompy_server/ports/_custom_element.py +72 -0
- webcompy_server/ports/_dom.py +380 -0
- webcompy_server/ports/_event_source.py +48 -0
- webcompy_server/ports/_fetch.py +290 -0
- webcompy_server/ports/_ffi.py +72 -0
- webcompy_server/ports/_history.py +47 -0
- webcompy_server/ports/_host.py +71 -0
- webcompy_server/ports/_media_query.py +27 -0
- webcompy_server/ports/_resource.py +280 -0
- webcompy_server/ports/_selector.py +238 -0
- webcompy_server/ports/_transition.py +75 -0
- webcompy_server/ports/_virtual_dom.py +590 -0
- webcompy_server/ports/_websocket.py +54 -0
- webcompy_server/py.typed +0 -0
- webcompy_server/rpc/__init__.py +8 -0
- webcompy_server/rpc/_dispatcher.py +424 -0
- webcompy_server/rpc/_streams.py +102 -0
- webcompy_server/rpc/_subscriptions.py +235 -0
- webcompy_server/rpc/_ws_endpoint.py +102 -0
- webcompy_server-0.0.14.dist-info/METADATA +45 -0
- webcompy_server-0.0.14.dist-info/RECORD +35 -0
- webcompy_server-0.0.14.dist-info/WHEEL +4 -0
- webcompy_server-0.0.14.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
"""Prebuild manifest serialization, loading, and fast startup validation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.metadata
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from types import MappingProxyType
|
|
12
|
+
from typing import TYPE_CHECKING, Any, Final, Literal, cast
|
|
13
|
+
|
|
14
|
+
from webcompy.exception import WebComPyException
|
|
15
|
+
from webcompy_server._html import PYSCRIPT_VERSION, _validate_loading_template
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from webcompy.app._app import WebComPyApp
|
|
19
|
+
|
|
20
|
+
_logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
PREBUILD_SCHEMA_VERSION: Final[int] = 1
|
|
23
|
+
"""Current JSON schema version for serialized ``prebuild.json`` manifests."""
|
|
24
|
+
|
|
25
|
+
PREBUILD_MANIFEST_FILENAME: Final[str] = "prebuild.json"
|
|
26
|
+
"""Filename of the serialized prebuild manifest in a prebuilt directory."""
|
|
27
|
+
|
|
28
|
+
_VALID_WHEEL_MODES: Final[tuple[str, ...]] = ("bundled", "split")
|
|
29
|
+
_VALID_SERVING_MODES: Final[tuple[str, ...]] = ("cdn", "local")
|
|
30
|
+
_VALID_PRERENDER_MODES: Final[tuple[str, ...]] = ("none", "static", "all")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _require_str(data: Mapping[str, Any], key: str) -> str:
|
|
34
|
+
if key not in data or not isinstance(data[key], str):
|
|
35
|
+
raise WebComPyException(f"Invalid prebuild manifest: {key!r} must be a string")
|
|
36
|
+
return data[key]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _optional_str(data: Mapping[str, Any], key: str, default: str | None = None) -> str | None:
|
|
40
|
+
if key not in data:
|
|
41
|
+
return default
|
|
42
|
+
val = data[key]
|
|
43
|
+
if val is not None and not isinstance(val, str):
|
|
44
|
+
raise WebComPyException(f"Invalid prebuild manifest: {key!r} must be a string or null")
|
|
45
|
+
return val
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _require_bool(data: Mapping[str, Any], key: str) -> bool:
|
|
49
|
+
if key not in data or not isinstance(data[key], bool):
|
|
50
|
+
raise WebComPyException(f"Invalid prebuild manifest: {key!r} must be a boolean")
|
|
51
|
+
return data[key]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _require_str_tuple(data: Mapping[str, Any], key: str) -> tuple[str, ...]:
|
|
55
|
+
if key not in data:
|
|
56
|
+
raise WebComPyException(f"Invalid prebuild manifest: missing required key {key!r}")
|
|
57
|
+
raw = data[key]
|
|
58
|
+
if isinstance(raw, (str, bytes)) or not isinstance(raw, (list, tuple)) or not all(isinstance(x, str) for x in raw):
|
|
59
|
+
raise WebComPyException(f"Invalid prebuild manifest: {key!r} must be a list of strings")
|
|
60
|
+
return tuple(raw)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _optional_str_tuple(data: Mapping[str, Any], key: str) -> tuple[str, ...] | None:
|
|
64
|
+
if key not in data or data[key] is None:
|
|
65
|
+
return None
|
|
66
|
+
return _require_str_tuple(data, key)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _require_str_dict(data: Mapping[str, Any], key: str) -> dict[str, str]:
|
|
70
|
+
if key not in data:
|
|
71
|
+
raise WebComPyException(f"Invalid prebuild manifest: missing required key {key!r}")
|
|
72
|
+
raw = data[key]
|
|
73
|
+
if not isinstance(raw, Mapping) or not all(isinstance(k, str) and isinstance(v, str) for k, v in raw.items()):
|
|
74
|
+
raise WebComPyException(f"Invalid prebuild manifest: {key!r} must be a string-to-string mapping")
|
|
75
|
+
return dict(raw)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class PrebuildStaticRouteMeta:
|
|
80
|
+
"""Serialized metadata for a materialized virtual static route.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
path: Normalized relative URL path (no leading slash).
|
|
84
|
+
media_type: Resolved MIME content type.
|
|
85
|
+
cache_control: Resolved ``Cache-Control`` response header value.
|
|
86
|
+
|
|
87
|
+
Attributes:
|
|
88
|
+
path: Normalized relative URL path.
|
|
89
|
+
media_type: Resolved MIME content type.
|
|
90
|
+
cache_control: Resolved ``Cache-Control`` header value.
|
|
91
|
+
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
path: str
|
|
95
|
+
media_type: str
|
|
96
|
+
cache_control: str
|
|
97
|
+
|
|
98
|
+
def to_dict(self) -> dict[str, str]:
|
|
99
|
+
"""Serialize route metadata to a JSON-compatible dictionary.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
Dictionary containing ``path``, ``media_type``, and ``cache_control``.
|
|
103
|
+
|
|
104
|
+
"""
|
|
105
|
+
return {
|
|
106
|
+
"path": self.path,
|
|
107
|
+
"media_type": self.media_type,
|
|
108
|
+
"cache_control": self.cache_control,
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
@classmethod
|
|
112
|
+
def from_dict(cls, data: Mapping[str, Any]) -> PrebuildStaticRouteMeta:
|
|
113
|
+
"""Deserialize route metadata from a dictionary.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
data: Mapping containing ``path``, ``media_type``, and
|
|
117
|
+
``cache_control`` string entries.
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
Parsed ``PrebuildStaticRouteMeta`` instance.
|
|
121
|
+
|
|
122
|
+
Raises:
|
|
123
|
+
WebComPyException: If any required field is missing or invalid.
|
|
124
|
+
|
|
125
|
+
"""
|
|
126
|
+
if not isinstance(data, Mapping):
|
|
127
|
+
raise WebComPyException("Invalid prebuild manifest: static_routes entries must be objects")
|
|
128
|
+
return cls(
|
|
129
|
+
path=_require_str(data, "path"),
|
|
130
|
+
media_type=_require_str(data, "media_type"),
|
|
131
|
+
cache_control=_require_str(data, "cache_control"),
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass(frozen=True)
|
|
136
|
+
class PrebuildManifest:
|
|
137
|
+
"""Immutable metadata describing prebuilt WebComPy deployment artifacts.
|
|
138
|
+
|
|
139
|
+
Produced by build-time prebuild tooling and consumed by the runtime ASGI
|
|
140
|
+
loader to start without rebuilding wheels, hashing assets, or writing
|
|
141
|
+
to the filesystem.
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
schema_version: Prebuild manifest schema version.
|
|
145
|
+
webcompy_version: Version of ``webcompy`` used when prebuilding.
|
|
146
|
+
pyscript_version: Target PyScript runtime version.
|
|
147
|
+
app_package_name: Importable name of the application package.
|
|
148
|
+
app_version: Application version used for wheel/cache keys.
|
|
149
|
+
base_url: Normalized application base URL (e.g. ``"/"`` or ``"/app/"``).
|
|
150
|
+
wheel_mode: Wheel bundling mode (``"bundled"`` or ``"split"``).
|
|
151
|
+
wheel_filename: Filename of the generated application wheel.
|
|
152
|
+
fw_wheel_filename: Filename of the framework wheel in split mode, else ``""``.
|
|
153
|
+
extra_wheel_filenames: Additional wheel filenames in split mode, or ``None``.
|
|
154
|
+
pyodide_package_names: Additional Pyodide/WASM package names.
|
|
155
|
+
wasm_serving: WASM package serving mode (``"cdn"`` or ``"local"``).
|
|
156
|
+
wasm_asset_files: Mapping from package name to local wheel filename.
|
|
157
|
+
runtime_serving: PyScript/Pyodide runtime serving mode (``"cdn"`` or ``"local"``).
|
|
158
|
+
runtime_asset_files: Relative runtime asset paths stored under ``_webcompy-assets``.
|
|
159
|
+
lockfile_url: Explicit Pyodide lockfile URL when applicable, else ``None``.
|
|
160
|
+
resource_allow_list: Allow-listed package-relative resource paths.
|
|
161
|
+
resource_version: Aggregate resource hash digest for ``<meta>``, or ``None``.
|
|
162
|
+
static_files: Relative paths copied from the static files directory.
|
|
163
|
+
static_routes: Materialized virtual static route descriptors.
|
|
164
|
+
asset_hashes: Content hashes for framework UI stylesheets and static files.
|
|
165
|
+
pwa_enabled: Whether PWA manifest and Service Worker outputs were enabled.
|
|
166
|
+
loading_template_html: Pre-resolved custom loading template markup, or ``None``.
|
|
167
|
+
prerender_mode: Configured prerender depth (``"none"``, ``"static"``, or ``"all"``).
|
|
168
|
+
prerendered_routes: Mapping from normalized route path to HTML path under ``public/``.
|
|
169
|
+
has_404_html: Whether ``public/404.html`` was emitted.
|
|
170
|
+
ssr_enabled: Whether dynamic per-request SSR remains active at runtime.
|
|
171
|
+
prebuilt_dir: Optional directory on disk containing ``prebuild.json`` and ``public/``.
|
|
172
|
+
embedded_resources: Optional in-memory resource bytes for zero-FS deployments.
|
|
173
|
+
|
|
174
|
+
Attributes:
|
|
175
|
+
schema_version: Manifest schema version integer.
|
|
176
|
+
webcompy_version: Framework version string recorded at build time.
|
|
177
|
+
pyscript_version: PyScript version string required at runtime.
|
|
178
|
+
app_package_name: Importable application package name.
|
|
179
|
+
app_version: Resolved application version string.
|
|
180
|
+
base_url: Normalized application base URL.
|
|
181
|
+
wheel_mode: Wheel bundling mode (``"bundled"`` or ``"split"``).
|
|
182
|
+
wheel_filename: Application wheel filename.
|
|
183
|
+
fw_wheel_filename: Framework wheel filename in split mode, else empty string.
|
|
184
|
+
extra_wheel_filenames: Extra preloaded wheel filenames, or ``None``.
|
|
185
|
+
pyodide_package_names: Extra Pyodide/WASM packages loaded by PyScript.
|
|
186
|
+
wasm_serving: Local or CDN WASM serving mode.
|
|
187
|
+
wasm_asset_files: Immutable mapping of package names to wheel filenames.
|
|
188
|
+
runtime_serving: Local or CDN PyScript runtime serving mode.
|
|
189
|
+
runtime_asset_files: Relative asset paths under the PyScript runtime prefix.
|
|
190
|
+
lockfile_url: Lockfile URL override or ``None``.
|
|
191
|
+
resource_allow_list: Tuple of allow-listed relative resource paths.
|
|
192
|
+
resource_version: Deterministic aggregate resource version digest or ``None``.
|
|
193
|
+
static_files: Relative static file paths present in ``public/``.
|
|
194
|
+
static_routes: Materialized virtual static route descriptors.
|
|
195
|
+
asset_hashes: Immutable mapping of asset paths to short SHA-256 hashes.
|
|
196
|
+
pwa_enabled: Whether PWA outputs were generated.
|
|
197
|
+
loading_template_html: Pre-resolved custom loading template HTML or ``None``.
|
|
198
|
+
prerender_mode: Build-time prerender depth setting.
|
|
199
|
+
prerendered_routes: Immutable mapping from normalized route paths to ``public/`` HTML files.
|
|
200
|
+
has_404_html: Whether ``public/404.html`` exists.
|
|
201
|
+
ssr_enabled: Whether dynamic SSR fallback is enabled at runtime.
|
|
202
|
+
prebuilt_dir: Resolved root prebuild directory when loaded from disk, or ``None``.
|
|
203
|
+
embedded_resources: Immutable mapping of embedded resource bytes, or ``None``.
|
|
204
|
+
|
|
205
|
+
"""
|
|
206
|
+
|
|
207
|
+
schema_version: int
|
|
208
|
+
webcompy_version: str
|
|
209
|
+
pyscript_version: str
|
|
210
|
+
app_package_name: str
|
|
211
|
+
app_version: str
|
|
212
|
+
base_url: str
|
|
213
|
+
wheel_mode: Literal["bundled", "split"]
|
|
214
|
+
wheel_filename: str
|
|
215
|
+
fw_wheel_filename: str
|
|
216
|
+
extra_wheel_filenames: tuple[str, ...] | None
|
|
217
|
+
pyodide_package_names: tuple[str, ...]
|
|
218
|
+
wasm_serving: Literal["cdn", "local"]
|
|
219
|
+
wasm_asset_files: Mapping[str, str]
|
|
220
|
+
runtime_serving: Literal["cdn", "local"]
|
|
221
|
+
runtime_asset_files: tuple[str, ...]
|
|
222
|
+
lockfile_url: str | None
|
|
223
|
+
resource_allow_list: tuple[str, ...]
|
|
224
|
+
resource_version: str | None
|
|
225
|
+
static_files: tuple[str, ...]
|
|
226
|
+
static_routes: tuple[PrebuildStaticRouteMeta, ...]
|
|
227
|
+
asset_hashes: Mapping[str, str]
|
|
228
|
+
pwa_enabled: bool
|
|
229
|
+
loading_template_html: str | None
|
|
230
|
+
prerender_mode: Literal["none", "static", "all"]
|
|
231
|
+
prerendered_routes: Mapping[str, str]
|
|
232
|
+
has_404_html: bool
|
|
233
|
+
ssr_enabled: bool
|
|
234
|
+
prebuilt_dir: Path | None = field(default=None, compare=False, repr=False)
|
|
235
|
+
embedded_resources: Mapping[str, bytes] | None = field(default=None, compare=False, repr=False)
|
|
236
|
+
|
|
237
|
+
def __post_init__(self) -> None:
|
|
238
|
+
object.__setattr__(
|
|
239
|
+
self,
|
|
240
|
+
"extra_wheel_filenames",
|
|
241
|
+
tuple(self.extra_wheel_filenames) if self.extra_wheel_filenames is not None else None,
|
|
242
|
+
)
|
|
243
|
+
object.__setattr__(self, "pyodide_package_names", tuple(self.pyodide_package_names))
|
|
244
|
+
object.__setattr__(self, "wasm_asset_files", MappingProxyType(dict(self.wasm_asset_files)))
|
|
245
|
+
object.__setattr__(self, "runtime_asset_files", tuple(self.runtime_asset_files))
|
|
246
|
+
object.__setattr__(self, "resource_allow_list", tuple(self.resource_allow_list))
|
|
247
|
+
object.__setattr__(self, "static_files", tuple(self.static_files))
|
|
248
|
+
object.__setattr__(self, "static_routes", tuple(self.static_routes))
|
|
249
|
+
object.__setattr__(self, "asset_hashes", MappingProxyType(dict(self.asset_hashes)))
|
|
250
|
+
object.__setattr__(self, "prerendered_routes", MappingProxyType(dict(self.prerendered_routes)))
|
|
251
|
+
if self.embedded_resources is not None:
|
|
252
|
+
object.__setattr__(self, "embedded_resources", MappingProxyType(dict(self.embedded_resources)))
|
|
253
|
+
|
|
254
|
+
def to_dict(self) -> dict[str, Any]:
|
|
255
|
+
"""Serialize the manifest to a JSON-compatible dictionary.
|
|
256
|
+
|
|
257
|
+
Excludes runtime-only ``prebuilt_dir`` and ``embedded_resources`` fields.
|
|
258
|
+
|
|
259
|
+
Returns:
|
|
260
|
+
JSON-serializable representation conforming to ``schema_version == 1``.
|
|
261
|
+
|
|
262
|
+
"""
|
|
263
|
+
return {
|
|
264
|
+
"schema_version": self.schema_version,
|
|
265
|
+
"webcompy_version": self.webcompy_version,
|
|
266
|
+
"pyscript_version": self.pyscript_version,
|
|
267
|
+
"app_package_name": self.app_package_name,
|
|
268
|
+
"app_version": self.app_version,
|
|
269
|
+
"base_url": self.base_url,
|
|
270
|
+
"wheel_mode": self.wheel_mode,
|
|
271
|
+
"wheel_filename": self.wheel_filename,
|
|
272
|
+
"fw_wheel_filename": self.fw_wheel_filename,
|
|
273
|
+
"extra_wheel_filenames": (
|
|
274
|
+
list(self.extra_wheel_filenames) if self.extra_wheel_filenames is not None else None
|
|
275
|
+
),
|
|
276
|
+
"pyodide_package_names": list(self.pyodide_package_names),
|
|
277
|
+
"wasm_serving": self.wasm_serving,
|
|
278
|
+
"wasm_asset_files": dict(self.wasm_asset_files),
|
|
279
|
+
"runtime_serving": self.runtime_serving,
|
|
280
|
+
"runtime_asset_files": list(self.runtime_asset_files),
|
|
281
|
+
"lockfile_url": self.lockfile_url,
|
|
282
|
+
"resource_allow_list": list(self.resource_allow_list),
|
|
283
|
+
"resource_version": self.resource_version,
|
|
284
|
+
"static_files": list(self.static_files),
|
|
285
|
+
"static_routes": [route.to_dict() for route in self.static_routes],
|
|
286
|
+
"asset_hashes": dict(self.asset_hashes),
|
|
287
|
+
"pwa_enabled": self.pwa_enabled,
|
|
288
|
+
"loading_template_html": self.loading_template_html,
|
|
289
|
+
"prerender_mode": self.prerender_mode,
|
|
290
|
+
"prerendered_routes": dict(self.prerendered_routes),
|
|
291
|
+
"has_404_html": self.has_404_html,
|
|
292
|
+
"ssr_enabled": self.ssr_enabled,
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
@classmethod
|
|
296
|
+
def from_dict(
|
|
297
|
+
cls,
|
|
298
|
+
data: Mapping[str, Any],
|
|
299
|
+
*,
|
|
300
|
+
prebuilt_dir: Path | None = None,
|
|
301
|
+
embedded_resources: Mapping[str, bytes] | None = None,
|
|
302
|
+
) -> PrebuildManifest:
|
|
303
|
+
"""Deserialize and validate schema fields into a ``PrebuildManifest``.
|
|
304
|
+
|
|
305
|
+
Args:
|
|
306
|
+
data: Deserialized JSON manifest dictionary.
|
|
307
|
+
prebuilt_dir: Optional directory path owning this manifest on disk.
|
|
308
|
+
embedded_resources: Optional pre-loaded resource byte map for zero-FS
|
|
309
|
+
deployments.
|
|
310
|
+
|
|
311
|
+
Returns:
|
|
312
|
+
Immutable ``PrebuildManifest`` instance.
|
|
313
|
+
|
|
314
|
+
Raises:
|
|
315
|
+
WebComPyException: If ``schema_version`` is unsupported or any
|
|
316
|
+
manifest field has an invalid type or value.
|
|
317
|
+
|
|
318
|
+
"""
|
|
319
|
+
if not isinstance(data, Mapping):
|
|
320
|
+
raise WebComPyException("Invalid prebuild manifest: expected a JSON object")
|
|
321
|
+
schema_version = data.get("schema_version")
|
|
322
|
+
if isinstance(schema_version, bool) or not isinstance(schema_version, int):
|
|
323
|
+
raise WebComPyException("Invalid prebuild manifest: 'schema_version' must be an integer")
|
|
324
|
+
if schema_version != PREBUILD_SCHEMA_VERSION:
|
|
325
|
+
raise WebComPyException(
|
|
326
|
+
f"Unsupported prebuild manifest schema_version={schema_version}; "
|
|
327
|
+
f"expected {PREBUILD_SCHEMA_VERSION}. Rebuild prebuild artifacts."
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
wheel_mode = _require_str(data, "wheel_mode")
|
|
331
|
+
if wheel_mode not in _VALID_WHEEL_MODES:
|
|
332
|
+
raise WebComPyException(f"Invalid prebuild manifest: unsupported wheel_mode={wheel_mode!r}")
|
|
333
|
+
|
|
334
|
+
wasm_serving = _require_str(data, "wasm_serving")
|
|
335
|
+
if wasm_serving not in _VALID_SERVING_MODES:
|
|
336
|
+
raise WebComPyException(f"Invalid prebuild manifest: unsupported wasm_serving={wasm_serving!r}")
|
|
337
|
+
|
|
338
|
+
runtime_serving = _require_str(data, "runtime_serving")
|
|
339
|
+
if runtime_serving not in _VALID_SERVING_MODES:
|
|
340
|
+
raise WebComPyException(f"Invalid prebuild manifest: unsupported runtime_serving={runtime_serving!r}")
|
|
341
|
+
|
|
342
|
+
prerender_mode = _require_str(data, "prerender_mode")
|
|
343
|
+
if prerender_mode not in _VALID_PRERENDER_MODES:
|
|
344
|
+
raise WebComPyException(f"Invalid prebuild manifest: unsupported prerender_mode={prerender_mode!r}")
|
|
345
|
+
|
|
346
|
+
raw_static_routes = data.get("static_routes", [])
|
|
347
|
+
if isinstance(raw_static_routes, (str, bytes)) or not isinstance(raw_static_routes, (list, tuple)):
|
|
348
|
+
raise WebComPyException("Invalid prebuild manifest: 'static_routes' must be a list")
|
|
349
|
+
static_routes = tuple(PrebuildStaticRouteMeta.from_dict(item) for item in raw_static_routes)
|
|
350
|
+
|
|
351
|
+
return cls(
|
|
352
|
+
schema_version=schema_version,
|
|
353
|
+
webcompy_version=_require_str(data, "webcompy_version"),
|
|
354
|
+
pyscript_version=_require_str(data, "pyscript_version"),
|
|
355
|
+
app_package_name=_require_str(data, "app_package_name"),
|
|
356
|
+
app_version=_require_str(data, "app_version"),
|
|
357
|
+
base_url=_require_str(data, "base_url"),
|
|
358
|
+
wheel_mode=cast('Literal["bundled", "split"]', wheel_mode),
|
|
359
|
+
wheel_filename=_require_str(data, "wheel_filename"),
|
|
360
|
+
fw_wheel_filename=_require_str(data, "fw_wheel_filename"),
|
|
361
|
+
extra_wheel_filenames=_optional_str_tuple(data, "extra_wheel_filenames"),
|
|
362
|
+
pyodide_package_names=_require_str_tuple(data, "pyodide_package_names"),
|
|
363
|
+
wasm_serving=cast('Literal["cdn", "local"]', wasm_serving),
|
|
364
|
+
wasm_asset_files=_require_str_dict(data, "wasm_asset_files"),
|
|
365
|
+
runtime_serving=cast('Literal["cdn", "local"]', runtime_serving),
|
|
366
|
+
runtime_asset_files=_require_str_tuple(data, "runtime_asset_files"),
|
|
367
|
+
lockfile_url=_optional_str(data, "lockfile_url"),
|
|
368
|
+
resource_allow_list=_require_str_tuple(data, "resource_allow_list"),
|
|
369
|
+
resource_version=_optional_str(data, "resource_version"),
|
|
370
|
+
static_files=_require_str_tuple(data, "static_files"),
|
|
371
|
+
static_routes=static_routes,
|
|
372
|
+
asset_hashes=_require_str_dict(data, "asset_hashes"),
|
|
373
|
+
pwa_enabled=_require_bool(data, "pwa_enabled"),
|
|
374
|
+
loading_template_html=_optional_str(data, "loading_template_html"),
|
|
375
|
+
prerender_mode=cast('Literal["none", "static", "all"]', prerender_mode),
|
|
376
|
+
prerendered_routes=_require_str_dict(data, "prerendered_routes"),
|
|
377
|
+
has_404_html=_require_bool(data, "has_404_html"),
|
|
378
|
+
ssr_enabled=_require_bool(data, "ssr_enabled"),
|
|
379
|
+
prebuilt_dir=prebuilt_dir,
|
|
380
|
+
embedded_resources=embedded_resources,
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def load_prebuild_manifest(prebuilt_dir: str | Path) -> PrebuildManifest:
|
|
385
|
+
"""Load a ``PrebuildManifest`` from a prebuilt artifact directory.
|
|
386
|
+
|
|
387
|
+
Reads only ``<prebuilt_dir>/prebuild.json`` without computing file hashes,
|
|
388
|
+
fetching remote resources, or modifying the filesystem.
|
|
389
|
+
|
|
390
|
+
Args:
|
|
391
|
+
prebuilt_dir: Directory produced by ``webcompy prebuild``.
|
|
392
|
+
|
|
393
|
+
Returns:
|
|
394
|
+
Loaded immutable ``PrebuildManifest`` bound to ``prebuilt_dir``.
|
|
395
|
+
|
|
396
|
+
Raises:
|
|
397
|
+
WebComPyException: If the directory or ``prebuild.json`` is missing,
|
|
398
|
+
unreadable, malformed JSON, or uses an unsupported schema version.
|
|
399
|
+
|
|
400
|
+
"""
|
|
401
|
+
base_dir = Path(prebuilt_dir).resolve()
|
|
402
|
+
manifest_path = base_dir / PREBUILD_MANIFEST_FILENAME
|
|
403
|
+
if not manifest_path.is_file():
|
|
404
|
+
raise WebComPyException(
|
|
405
|
+
f"Prebuild manifest not found: {manifest_path}. Run 'python -m webcompy prebuild' first."
|
|
406
|
+
)
|
|
407
|
+
try:
|
|
408
|
+
raw_text = manifest_path.read_text(encoding="utf-8")
|
|
409
|
+
except OSError as exc:
|
|
410
|
+
raise WebComPyException(f"Failed to read prebuild manifest at {manifest_path}: {exc}") from exc
|
|
411
|
+
try:
|
|
412
|
+
parsed = json.loads(raw_text)
|
|
413
|
+
except json.JSONDecodeError as exc:
|
|
414
|
+
raise WebComPyException(f"Invalid JSON in prebuild manifest {manifest_path}: {exc}") from exc
|
|
415
|
+
return PrebuildManifest.from_dict(parsed, prebuilt_dir=base_dir)
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def validate_prebuild_manifest(
|
|
419
|
+
manifest: PrebuildManifest,
|
|
420
|
+
app: WebComPyApp,
|
|
421
|
+
*,
|
|
422
|
+
serve_assets: bool = True,
|
|
423
|
+
) -> None:
|
|
424
|
+
"""Validate runtime compatibility of a loaded ``PrebuildManifest`` in O(1).
|
|
425
|
+
|
|
426
|
+
Performs zero SHA-256 hashing, zero filesystem writes, and zero network I/O.
|
|
427
|
+
|
|
428
|
+
Args:
|
|
429
|
+
manifest: Loaded prebuild manifest to validate.
|
|
430
|
+
app: Target ``WebComPyApp`` instance being served.
|
|
431
|
+
serve_assets: Whether asset files under ``<prebuilt_dir>/public`` will
|
|
432
|
+
be served by the runtime ASGI app.
|
|
433
|
+
|
|
434
|
+
Raises:
|
|
435
|
+
WebComPyException: On unsupported schema version, ``pyscript_version``
|
|
436
|
+
mismatch, ``base_url`` mismatch, invalid pre-resolved loading
|
|
437
|
+
template, or missing required files under ``public/`` when
|
|
438
|
+
``serve_assets`` is ``True``.
|
|
439
|
+
|
|
440
|
+
"""
|
|
441
|
+
if manifest.schema_version != PREBUILD_SCHEMA_VERSION:
|
|
442
|
+
raise WebComPyException(
|
|
443
|
+
f"Unsupported prebuild manifest schema_version={manifest.schema_version}; "
|
|
444
|
+
f"expected {PREBUILD_SCHEMA_VERSION}. Rebuild prebuild artifacts."
|
|
445
|
+
)
|
|
446
|
+
if manifest.pyscript_version != PYSCRIPT_VERSION:
|
|
447
|
+
raise WebComPyException(
|
|
448
|
+
f"Prebuild manifest pyscript_version={manifest.pyscript_version!r} does not match "
|
|
449
|
+
f"current runtime PYSCRIPT_VERSION={PYSCRIPT_VERSION!r}. "
|
|
450
|
+
"Rebuild prebuild artifacts with the current webcompy version."
|
|
451
|
+
)
|
|
452
|
+
if manifest.base_url != app.config.base_url:
|
|
453
|
+
raise WebComPyException(
|
|
454
|
+
f"Prebuild manifest base_url={manifest.base_url!r} does not match "
|
|
455
|
+
f"app.config.base_url={app.config.base_url!r}. "
|
|
456
|
+
"Rebuild prebuild artifacts for the target base_url."
|
|
457
|
+
)
|
|
458
|
+
try:
|
|
459
|
+
installed_version = importlib.metadata.version("webcompy")
|
|
460
|
+
except importlib.metadata.PackageNotFoundError:
|
|
461
|
+
installed_version = None
|
|
462
|
+
if installed_version is not None and installed_version != manifest.webcompy_version:
|
|
463
|
+
_logger.warning(
|
|
464
|
+
"Prebuild manifest was built with webcompy %s, running with webcompy %s",
|
|
465
|
+
manifest.webcompy_version,
|
|
466
|
+
installed_version,
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
if serve_assets:
|
|
470
|
+
if manifest.prebuilt_dir is None:
|
|
471
|
+
raise WebComPyException(
|
|
472
|
+
"Cannot serve prebuild assets without a prebuilt_dir on PrebuildManifest; "
|
|
473
|
+
"pass a prebuild directory path or set serve_assets=False."
|
|
474
|
+
)
|
|
475
|
+
public_dir = manifest.prebuilt_dir / "public"
|
|
476
|
+
if not public_dir.is_dir():
|
|
477
|
+
raise WebComPyException(f"Prebuild public directory not found: {public_dir}")
|
|
478
|
+
wheel_path = public_dir / "_webcompy-app-package" / manifest.wheel_filename
|
|
479
|
+
if not wheel_path.is_file():
|
|
480
|
+
raise WebComPyException(f"Prebuilt application wheel not found: {wheel_path}")
|
|
481
|
+
for extra_wheel in manifest.extra_wheel_filenames or ():
|
|
482
|
+
extra_path = public_dir / "_webcompy-app-package" / extra_wheel
|
|
483
|
+
if not extra_path.is_file():
|
|
484
|
+
raise WebComPyException(f"Prebuilt extra wheel not found: {extra_path}")
|
|
485
|
+
|
|
486
|
+
if manifest.loading_template_html is not None:
|
|
487
|
+
_validate_loading_template(manifest.loading_template_html)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Programmatic virtual static route definition."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class StaticRoute:
|
|
11
|
+
"""Programmatic virtual static endpoint served alongside the app.
|
|
12
|
+
|
|
13
|
+
Registered as an exact ASGI route during serving and materialized
|
|
14
|
+
into static or prebuild output directories during builds. Production
|
|
15
|
+
mode caches rendered bytes per route, whereas development mode
|
|
16
|
+
evaluates the handler on every request.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
path: Non-empty, non-root URL path (e.g. ``"/llms.txt"``). Must not
|
|
20
|
+
contain ``..`` segments, ``{``/``}`` template braces, trailing
|
|
21
|
+
slashes, ``/_webcompy*`` reserved prefixes, ``index.html`` /
|
|
22
|
+
``404.html``, or directory/mount collisions.
|
|
23
|
+
handler: Zero-argument sync or async callable returning ``bytes`` or
|
|
24
|
+
UTF-8 ``str`` content.
|
|
25
|
+
media_type: Explicit ``Content-Type`` media type, or ``None`` to
|
|
26
|
+
infer from ``path`` with UTF-8 charset for ``text/*`` responses.
|
|
27
|
+
cache_control: Explicit ``Cache-Control`` header value, or ``None``
|
|
28
|
+
to use serving-mode defaults.
|
|
29
|
+
|
|
30
|
+
Attributes:
|
|
31
|
+
path: Normalized target URL path for the virtual static route.
|
|
32
|
+
handler: Zero-argument sync or async content producer.
|
|
33
|
+
media_type: Explicit MIME type override, or ``None`` for inference.
|
|
34
|
+
cache_control: Explicit ``Cache-Control`` override, or ``None``.
|
|
35
|
+
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
path: str
|
|
39
|
+
handler: Callable[[], bytes | str | Awaitable[bytes | str]]
|
|
40
|
+
media_type: str | None = None
|
|
41
|
+
cache_control: str | None = None
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Server-side emission of teleported children into the rendered document."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from logging import getLogger
|
|
6
|
+
from typing import TYPE_CHECKING, cast
|
|
7
|
+
|
|
8
|
+
from webcompy.di import inject
|
|
9
|
+
from webcompy.di._keys import _TELEPORT_REGISTRY_KEY
|
|
10
|
+
from webcompy.elements.types._teleport import (
|
|
11
|
+
_PendingTeleportEntry,
|
|
12
|
+
_TeleportTargetRegistry,
|
|
13
|
+
block_end_data,
|
|
14
|
+
block_start_data,
|
|
15
|
+
)
|
|
16
|
+
from webcompy.ports._dom import DOMNode
|
|
17
|
+
from webcompy.ports._keys import DOM_PORT_KEY
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from webcompy_server.ports._dom import ServerDOMPort
|
|
21
|
+
|
|
22
|
+
_logger = getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
async def emit_teleport_blocks(app_root_node: DOMNode | None) -> None:
|
|
26
|
+
"""Render pending teleport children into their resolved targets.
|
|
27
|
+
|
|
28
|
+
Drains the per-context registry repeatedly so teleports nested inside
|
|
29
|
+
already-emitted content are emitted in later rounds, with their anchors
|
|
30
|
+
mounted inside the freshly created subtree.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
app_root_node: The application mount container node used for
|
|
34
|
+
rejection checks; ``None`` when unavailable.
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
``None``.
|
|
38
|
+
|
|
39
|
+
"""
|
|
40
|
+
registry = cast("_TeleportTargetRegistry | None", inject(_TELEPORT_REGISTRY_KEY, default=None))
|
|
41
|
+
if registry is None:
|
|
42
|
+
return
|
|
43
|
+
dom_port = inject(DOM_PORT_KEY)
|
|
44
|
+
while True:
|
|
45
|
+
entries = registry.take_pending_entries()
|
|
46
|
+
if not entries:
|
|
47
|
+
break
|
|
48
|
+
for entry in entries:
|
|
49
|
+
await _emit_entry(dom_port, registry, entry, app_root_node)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
async def _emit_entry(
|
|
53
|
+
dom_port: ServerDOMPort,
|
|
54
|
+
registry: _TeleportTargetRegistry,
|
|
55
|
+
entry: _PendingTeleportEntry,
|
|
56
|
+
app_root_node: DOMNode | None,
|
|
57
|
+
) -> None:
|
|
58
|
+
teleport = entry.teleport
|
|
59
|
+
try:
|
|
60
|
+
target = dom_port.query_selector(entry.to)
|
|
61
|
+
except ValueError:
|
|
62
|
+
_logger.warning("Teleport target '%s' uses unsupported selector syntax; emitting anchor only.", entry.to)
|
|
63
|
+
return
|
|
64
|
+
if target is None:
|
|
65
|
+
_logger.warning("Teleport target '%s' not found in the server document; emitting anchor only.", entry.to)
|
|
66
|
+
return
|
|
67
|
+
if _is_rejected_target(target, app_root_node):
|
|
68
|
+
_logger.warning(
|
|
69
|
+
"Teleport target '%s' resolves inside the application subtree or head; emitting anchor only.",
|
|
70
|
+
entry.to,
|
|
71
|
+
)
|
|
72
|
+
return
|
|
73
|
+
teleport._target_node = target
|
|
74
|
+
registry.register(target, teleport)
|
|
75
|
+
start = dom_port.create_comment(block_start_data(entry.ordinal, entry.to))
|
|
76
|
+
end = dom_port.create_comment(block_end_data(entry.ordinal))
|
|
77
|
+
target.appendChild(start)
|
|
78
|
+
index = target.childNodes.length
|
|
79
|
+
for child in entry.children:
|
|
80
|
+
child._node_idx = index
|
|
81
|
+
await child._render()
|
|
82
|
+
index += child._node_count
|
|
83
|
+
target.appendChild(end)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _is_rejected_target(node: DOMNode, app_root_node: DOMNode | None) -> bool:
|
|
87
|
+
current: DOMNode | None = node
|
|
88
|
+
while current is not None:
|
|
89
|
+
if current.nodeName.lower() == "head":
|
|
90
|
+
return True
|
|
91
|
+
if app_root_node is not None and current is app_root_node:
|
|
92
|
+
return True
|
|
93
|
+
current = current.parentNode
|
|
94
|
+
return False
|
|
File without changes
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""FastAPI integration providing typed JSON responses."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from json import dumps as json_dumps
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
from starlette.responses import JSONResponse
|
|
10
|
+
except ImportError as err:
|
|
11
|
+
raise ImportError(
|
|
12
|
+
"webcompy_server.contrib.fastapi requires Starlette/FastAPI. Install it with: pip install fastapi"
|
|
13
|
+
) from err
|
|
14
|
+
|
|
15
|
+
from webcompy.hydration._transfer_meta import META_HEADER_NAME, encode_with_meta, merge_meta_into_body
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TypedJSONResponse(JSONResponse):
|
|
19
|
+
"""JSON response that encodes Python values with transfer metadata.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
content: Value to serialize with metadata support.
|
|
23
|
+
transfer_mode: Where to place metadata (``"header"`` or ``"body"``).
|
|
24
|
+
**kwargs: Forwarded to ``JSONResponse``.
|
|
25
|
+
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
content: Any,
|
|
31
|
+
*,
|
|
32
|
+
transfer_mode: Literal["header", "body"] = "header",
|
|
33
|
+
**kwargs: Any,
|
|
34
|
+
) -> None:
|
|
35
|
+
json_data, meta = encode_with_meta(content)
|
|
36
|
+
if transfer_mode == "body":
|
|
37
|
+
json_data = merge_meta_into_body(json_data, meta)
|
|
38
|
+
elif meta:
|
|
39
|
+
headers = dict(kwargs.pop("headers", None) or {})
|
|
40
|
+
headers[META_HEADER_NAME] = json_dumps(meta, separators=(",", ":"))
|
|
41
|
+
kwargs["headers"] = headers
|
|
42
|
+
super().__init__(json_data, **kwargs)
|