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.
@@ -0,0 +1,832 @@
1
+ """Shared ASGI assembly and prebuilt production server builder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import inspect
7
+ import mimetypes
8
+ import os
9
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
10
+ from functools import partial
11
+ from operator import truth
12
+ from pathlib import Path
13
+ from re import compile as re_compile
14
+ from re import escape as re_escape
15
+ from typing import TYPE_CHECKING, Any, Final
16
+
17
+ from starlette.applications import Starlette
18
+ from starlette.exceptions import HTTPException
19
+ from starlette.responses import FileResponse, HTMLResponse, PlainTextResponse, Response
20
+ from starlette.routing import BaseRoute, Match, Mount, Route, WebSocketRoute
21
+
22
+ import webcompy.utils._environment as _env_mod
23
+ from webcompy.di import inject
24
+ from webcompy.exception import WebComPyException
25
+ from webcompy.ports._keys import ASYNC_SCHEDULER_PORT_KEY
26
+ from webcompy.ports._resource import ResourcePort
27
+ from webcompy.ui.theme._server import read_theme_from_cookie
28
+ from webcompy_server._context import ServerRenderContext
29
+ from webcompy_server._html import generate_html, get_runtime_asset_prefix
30
+ from webcompy_server._prebuild import (
31
+ PrebuildManifest,
32
+ load_prebuild_manifest,
33
+ validate_prebuild_manifest,
34
+ )
35
+ from webcompy_server._static_route import StaticRoute
36
+ from webcompy_server.ports._resource import InMemoryServerResourcePort, ServerResourcePort
37
+
38
+ if TYPE_CHECKING:
39
+ from starlette.requests import Request
40
+ from starlette.types import ASGIApp, Receive, Scope, Send
41
+
42
+ from webcompy.app._app import WebComPyApp
43
+ from webcompy.app._render_context import RenderContext
44
+ from webcompy.rpc._registry import ProcedureRegistry
45
+
46
+ WEBCOMPY_PREBUILT_DIR_ENV: Final[str] = "WEBCOMPY_PREBUILT_DIR"
47
+ """Environment variable consulted when ``prebuilt`` is omitted."""
48
+
49
+ MANIFEST_FILENAME: Final[str] = "manifest.webmanifest"
50
+ """Filename of the generated Web App Manifest."""
51
+
52
+ SW_FILENAME: Final[str] = "sw.js"
53
+ """Filename of the generated PWA Service Worker."""
54
+
55
+ PWA_OUTPUT_NAMES: Final[frozenset[str]] = frozenset({MANIFEST_FILENAME, SW_FILENAME})
56
+ """Filenames reserved for framework-generated PWA assets."""
57
+
58
+ MANIFEST_MEDIA_TYPE: Final[str] = "application/manifest+json"
59
+ """MIME media type served for ``manifest.webmanifest``."""
60
+
61
+ SW_MEDIA_TYPE: Final[str] = "application/javascript"
62
+ """MIME media type served for ``sw.js``."""
63
+
64
+
65
+ def _file_response(
66
+ path: Path,
67
+ *,
68
+ media_type: str,
69
+ headers: Mapping[str, str] | None = None,
70
+ status_code: int = 200,
71
+ ) -> Response:
72
+ if not path.is_file():
73
+ raise HTTPException(404)
74
+ resolved_headers = dict(headers) if headers else None
75
+ if _env_mod.IS_EMSCRIPTEN or status_code != 200:
76
+ return Response(
77
+ path.read_bytes(),
78
+ status_code=status_code,
79
+ media_type=media_type,
80
+ headers=resolved_headers,
81
+ )
82
+ return FileResponse(path, media_type=media_type, headers=resolved_headers)
83
+
84
+
85
+ async def _call_static_handler(
86
+ handler: Callable[[], bytes | str | Awaitable[bytes | str]],
87
+ ) -> bytes:
88
+ if inspect.iscoroutinefunction(handler):
89
+ payload = await handler()
90
+ elif _env_mod.IS_EMSCRIPTEN:
91
+ payload = handler()
92
+ if inspect.isawaitable(payload):
93
+ payload = await payload
94
+ else:
95
+ payload = await asyncio.to_thread(handler)
96
+ if inspect.isawaitable(payload):
97
+ payload = await payload
98
+ return payload.encode("utf-8") if isinstance(payload, str) else bytes(payload)
99
+
100
+
101
+ def _normalize_mount_prefix(prefix: str) -> str:
102
+ return "/" + prefix.strip("/") if prefix.strip("/") else "/"
103
+
104
+
105
+ def _page_static_prefix(path: str) -> list[str]:
106
+ segments: list[str] = []
107
+ for seg in path.strip("/").split("/"):
108
+ if not seg or "{" in seg:
109
+ break
110
+ segments.append(seg)
111
+ return segments
112
+
113
+
114
+ def _resolve_mounts(
115
+ app: WebComPyApp,
116
+ mounts_input: Mapping[str, ASGIApp] | Callable[[], Mapping[str, ASGIApp] | None] | None,
117
+ ) -> list[tuple[str, ASGIApp]]:
118
+ if mounts_input is None:
119
+ return []
120
+ mount_map = mounts_input() if callable(mounts_input) else mounts_input
121
+ if mount_map is None:
122
+ return []
123
+ if not isinstance(mount_map, Mapping):
124
+ raise WebComPyException(
125
+ f"WebComPyServerConfig.mounts callable must return a dict[str, ASGIApp], got {type(mount_map).__name__}"
126
+ )
127
+ conflicts: list[str] = []
128
+ resolved: list[tuple[str, ASGIApp]] = []
129
+ for prefix, asgi_app in mount_map.items():
130
+ normalized = _normalize_mount_prefix(prefix)
131
+ if normalized == "/":
132
+ conflicts.append(f" '{prefix}': mounting at '/' would shadow all page routes")
133
+ continue
134
+ if normalized.startswith("/_webcompy"):
135
+ conflicts.append(f" '{prefix}': prefixes starting with '/_webcompy' are reserved by the framework")
136
+ continue
137
+ mount_segments = normalized.strip("/").split("/")
138
+ for route in app.routes or []:
139
+ static = _page_static_prefix(route[0])
140
+ if len(static) >= len(mount_segments) and static[: len(mount_segments)] == mount_segments:
141
+ conflicts.append(f" '{prefix}': collides with page route '/{route[0]}'")
142
+ resolved.append((normalized, asgi_app))
143
+
144
+ if conflicts:
145
+ raise WebComPyException("ASGI mount path collisions detected:\n" + "\n".join(dict.fromkeys(conflicts)))
146
+ return resolved
147
+
148
+
149
+ def _resolve_static_routes(
150
+ app: WebComPyApp,
151
+ static_routes_input: Sequence[StaticRoute] | Callable[[], Sequence[StaticRoute] | None] | None,
152
+ static_relative_paths: tuple[str, ...],
153
+ *,
154
+ pwa_enabled: bool = False,
155
+ mount_prefixes: tuple[str, ...] = (),
156
+ ) -> list[tuple[str, StaticRoute]]:
157
+ if static_routes_input is None:
158
+ return []
159
+ raw_routes = static_routes_input() if callable(static_routes_input) else static_routes_input
160
+ if raw_routes is None:
161
+ return []
162
+ if isinstance(raw_routes, (str, bytes)) or not isinstance(raw_routes, Sequence):
163
+ raise WebComPyException(
164
+ "WebComPyBuildConfig.static_routes callable must return a sequence of StaticRoute, "
165
+ f"got {type(raw_routes).__name__}"
166
+ )
167
+
168
+ page_paths = {route[0].strip("/") for route in (app.routes or []) if route[0].strip("/")}
169
+ static_file_set = set(static_relative_paths)
170
+ pwa_outputs = PWA_OUTPUT_NAMES if pwa_enabled else frozenset()
171
+ normalized_mounts = tuple(p.strip("/") for p in mount_prefixes if p.strip("/"))
172
+ seen: set[str] = set()
173
+ errors: list[str] = []
174
+ resolved: list[tuple[str, StaticRoute]] = []
175
+
176
+ for entry in raw_routes:
177
+ if not isinstance(entry, StaticRoute):
178
+ errors.append(f" expected StaticRoute instance, got {type(entry).__name__}")
179
+ continue
180
+ raw_path = entry.path
181
+ if not raw_path or "\\" in raw_path or raw_path.strip("/") == "":
182
+ errors.append(f" {raw_path!r}: virtual static route path must be a non-empty non-root path")
183
+ continue
184
+ if raw_path != "/" and raw_path.endswith("/"):
185
+ errors.append(f" {raw_path!r}: virtual static route path must not end with '/'")
186
+ continue
187
+ if "{" in raw_path or "}" in raw_path:
188
+ errors.append(f" {raw_path!r}: virtual static route path must not contain '{{' or '}}' characters")
189
+ continue
190
+ rel_path = raw_path.lstrip("/")
191
+ segments = rel_path.split("/")
192
+ if any(seg in ("", ".", "..") for seg in segments):
193
+ errors.append(f" {raw_path!r}: virtual static route path contains an invalid segment")
194
+ continue
195
+ if rel_path.startswith("_webcompy"):
196
+ errors.append(f" {raw_path!r}: prefixes starting with '/_webcompy' are reserved by the framework")
197
+ continue
198
+ if rel_path in ("index.html", "404.html"):
199
+ errors.append(f" {raw_path!r}: collides with framework-generated HTML output '/{rel_path}'")
200
+ continue
201
+ if rel_path in seen:
202
+ errors.append(f" {raw_path!r}: duplicate virtual static route path")
203
+ continue
204
+ if any(other.startswith(rel_path + "/") or rel_path.startswith(other + "/") for other in seen):
205
+ errors.append(f" {raw_path!r}: directory prefix overlaps another virtual static route")
206
+ continue
207
+ if (
208
+ rel_path in page_paths
209
+ or any(page_path.startswith(rel_path + "/") for page_path in page_paths)
210
+ or any(rel_path == f"{page_path}/index.html" for page_path in page_paths)
211
+ ):
212
+ errors.append(f" {raw_path!r}: collides with page route '/{rel_path}'")
213
+ continue
214
+ if rel_path in pwa_outputs:
215
+ errors.append(f" {raw_path!r}: collides with framework-generated PWA output '/{rel_path}'")
216
+ continue
217
+ if rel_path in static_file_set or any(
218
+ sf.startswith(rel_path + "/") or rel_path.startswith(sf + "/") for sf in static_file_set
219
+ ):
220
+ errors.append(f" {raw_path!r}: collides with static file '{rel_path}'")
221
+ continue
222
+ if any(
223
+ rel_path == m or rel_path.startswith(m + "/") or m.startswith(rel_path + "/") for m in normalized_mounts
224
+ ):
225
+ errors.append(f" {raw_path!r}: collides with ASGI mount prefix '/{rel_path}'")
226
+ continue
227
+ seen.add(rel_path)
228
+ resolved.append((rel_path, entry))
229
+
230
+ if errors:
231
+ raise WebComPyException("Virtual static route errors detected:\n" + "\n".join(dict.fromkeys(errors)))
232
+ return resolved
233
+
234
+
235
+ def _normalize_static_route_headers(
236
+ rel_path: str,
237
+ static_route: StaticRoute,
238
+ *,
239
+ dev_mode: bool = False,
240
+ ) -> tuple[str, str]:
241
+ media_type = static_route.media_type or mimetypes.guess_type(rel_path)[0] or "application/octet-stream"
242
+ if media_type.startswith("text/") and "charset=" not in media_type.lower():
243
+ media_type = f"{media_type}; charset=utf-8"
244
+ cache_control = (
245
+ static_route.cache_control
246
+ if static_route.cache_control is not None
247
+ else ("no-cache, must-revalidate" if dev_mode else "public, max-age=0, must-revalidate")
248
+ )
249
+ return media_type, cache_control
250
+
251
+
252
+ def _build_dynamic_static_routes(
253
+ static_entries: Sequence[tuple[str, StaticRoute]],
254
+ *,
255
+ base_url_prefix: str,
256
+ dev_mode: bool,
257
+ ) -> list[Route]:
258
+ routes: list[Route] = []
259
+ for rel_path, static_route in static_entries:
260
+ resolved_media_type, resolved_cache_control = _normalize_static_route_headers(
261
+ rel_path,
262
+ static_route,
263
+ dev_mode=dev_mode,
264
+ )
265
+ cached_body: list[bytes] = []
266
+
267
+ async def send_virtual_static(
268
+ request: Request,
269
+ _handler=static_route.handler,
270
+ _media_type=resolved_media_type,
271
+ _cache_control=resolved_cache_control,
272
+ _dev_mode=dev_mode,
273
+ _cache=cached_body,
274
+ ):
275
+ if not _dev_mode and _cache:
276
+ return Response(_cache[0], media_type=_media_type, headers={"Cache-Control": _cache_control})
277
+
278
+ body = await _call_static_handler(_handler)
279
+ if not _dev_mode and not _cache:
280
+ _cache.append(body)
281
+ return Response(body, media_type=_media_type, headers={"Cache-Control": _cache_control})
282
+
283
+ routes.append(Route("/" + rel_path, send_virtual_static))
284
+ if base_url_prefix:
285
+ routes.append(Route(base_url_prefix + "/" + rel_path, send_virtual_static))
286
+ return routes
287
+
288
+
289
+ class _StaticMapRoute(BaseRoute):
290
+ """Exact O(1) dictionary-backed route for prebuilt static files and assets."""
291
+
292
+ def __init__(self, entries: Mapping[str, tuple[Path, str, str | None]]) -> None:
293
+ self._entries = dict(entries)
294
+
295
+ def matches(self, scope: Scope) -> tuple[Match, Scope]:
296
+ if scope.get("type") != "http":
297
+ return Match.NONE, {}
298
+ path = scope.get("path", "")
299
+ if path in self._entries:
300
+ if scope.get("method", "GET") in ("GET", "HEAD"):
301
+ return Match.FULL, {}
302
+ return Match.PARTIAL, {"methods": ("GET", "HEAD")}
303
+ return Match.NONE, {}
304
+
305
+ async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:
306
+ path = scope.get("path", "")
307
+ entry = self._entries.get(path)
308
+ if entry is None:
309
+ resp: Response = PlainTextResponse("Not Found", status_code=404)
310
+ await resp(scope, receive, send)
311
+ return
312
+ if scope.get("method", "GET") not in ("GET", "HEAD"):
313
+ resp = PlainTextResponse("Method Not Allowed", status_code=405, headers={"Allow": "GET, HEAD"})
314
+ await resp(scope, receive, send)
315
+ return
316
+ file_path, media_type, cache_control = entry
317
+ headers = {"Cache-Control": cache_control} if cache_control is not None else None
318
+ resp = _file_response(file_path, media_type=media_type, headers=headers)
319
+ await resp(scope, receive, send)
320
+
321
+
322
+ def _make_rpc_route(registry: ProcedureRegistry, path: str) -> Route:
323
+ from webcompy_server.rpc import create_dispatcher_app
324
+
325
+ return Route(path, create_dispatcher_app(registry), methods=["POST"])
326
+
327
+
328
+ def _make_rpc_ws_route(registry: ProcedureRegistry, path: str) -> WebSocketRoute:
329
+ from webcompy_server.rpc import create_rpc_ws_endpoint
330
+
331
+ return WebSocketRoute(path, create_rpc_ws_endpoint(registry))
332
+
333
+
334
+ def _build_rpc_routes(app: WebComPyApp) -> tuple[list[BaseRoute], list[str]]:
335
+ rpc_routes: list[BaseRoute] = []
336
+ rpc_mount_prefixes: list[str] = []
337
+ rpc_registry = app.rpc
338
+ if rpc_registry.has_procedures:
339
+ rpc_routes.append(_make_rpc_route(rpc_registry, rpc_registry.path))
340
+ rpc_routes.append(_make_rpc_ws_route(rpc_registry, rpc_registry.path))
341
+ prefixed_rpc_path = app.config.base_url.rstrip("/") + rpc_registry.path
342
+ if prefixed_rpc_path != rpc_registry.path:
343
+ rpc_routes.append(_make_rpc_route(rpc_registry, prefixed_rpc_path))
344
+ rpc_routes.append(_make_rpc_ws_route(rpc_registry, prefixed_rpc_path))
345
+ rpc_mount_prefixes.append(prefixed_rpc_path)
346
+ return rpc_routes, rpc_mount_prefixes
347
+
348
+
349
+ def _read_initial_theme(cookie_header: str) -> Any:
350
+ if not cookie_header:
351
+ return None
352
+ return read_theme_from_cookie({"cookie": cookie_header})
353
+
354
+
355
+ def _extract_requested_path(request: Request, base_url_segment: str, base_url_stripper: Callable[[str], str]) -> str:
356
+ raw_path = str(request.path_params.get("path", ""))
357
+ root_path = str(request.scope.get("root_path", ""))
358
+ if base_url_segment and not root_path:
359
+ normalized = "/" + raw_path.lstrip("/")
360
+ return base_url_stripper(normalized).strip("/")
361
+ return base_url_stripper(raw_path).strip("/")
362
+
363
+
364
+ def _accepts_html(request: Request) -> bool:
365
+ return any(
366
+ part.split(";", 1)[0].strip().lower() == "text/html" for part in request.headers.get("accept", "").split(",")
367
+ )
368
+
369
+
370
+ def _assemble_ssr_asgi(
371
+ app: WebComPyApp,
372
+ *,
373
+ html_generator: Callable[[RenderContext], Any],
374
+ hash_cache: list[str],
375
+ dev_routes: Sequence[BaseRoute] = (),
376
+ asset_routes: Sequence[BaseRoute] = (),
377
+ static_map_routes: Sequence[BaseRoute] = (),
378
+ virtual_static_routes: Sequence[BaseRoute] = (),
379
+ mount_entries: Sequence[tuple[str, ASGIApp]] = (),
380
+ prerendered_html_files: Mapping[str, Path] | None = None,
381
+ html_404_file: Path | None = None,
382
+ ssr_enabled: bool = True,
383
+ serve_prerendered: bool = True,
384
+ include_html_catchall: bool = True,
385
+ configure_fetch: bool = True,
386
+ ) -> Starlette:
387
+ base_url = app.config.base_url
388
+ base_url_segment = base_url.strip("/")
389
+ base_url_stripper = (
390
+ partial(re_compile("^" + re_escape("/" + base_url_segment) + "(?=/|$)").sub, "")
391
+ if base_url_segment
392
+ else lambda value: value
393
+ )
394
+ prerender_map = dict(prerendered_html_files) if prerendered_html_files else {}
395
+
396
+ routes: list[BaseRoute] = [
397
+ *dev_routes,
398
+ *asset_routes,
399
+ *virtual_static_routes,
400
+ *static_map_routes,
401
+ *[Mount(path=prefix, app=mounted) for prefix, mounted in mount_entries],
402
+ ]
403
+ rpc_routes, rpc_mount_prefixes = _build_rpc_routes(app)
404
+ routes.extend(rpc_routes)
405
+
406
+ if include_html_catchall:
407
+ if app.router_mode == "history" and app.routes:
408
+
409
+ async def send_html(request: Request) -> Response:
410
+ requested_path = _extract_requested_path(request, base_url_segment, base_url_stripper)
411
+ if serve_prerendered and requested_path in prerender_map:
412
+ html_file = prerender_map[requested_path]
413
+ if not html_file.is_file():
414
+ raise HTTPException(404)
415
+ return _file_response(html_file, media_type="text/html; charset=utf-8")
416
+
417
+ accepts_html = _accepts_html(request)
418
+ if ssr_enabled:
419
+ registered = r if (r := app.routes) else []
420
+ is_matched = truth(tuple(filter(lambda r: r[1](requested_path), registered)))
421
+ if is_matched or accepts_html:
422
+ cookie_header = request.headers.get("cookie", "")
423
+ initial_theme = _read_initial_theme(cookie_header)
424
+ ctx = app.create_render_context(
425
+ requested_path,
426
+ initial_theme=initial_theme,
427
+ cookie_header=cookie_header,
428
+ )
429
+ assert isinstance(ctx, ServerRenderContext)
430
+ try:
431
+ scheduler = inject(ASYNC_SCHEDULER_PORT_KEY)
432
+ await scheduler.await_pending()
433
+ response = HTMLResponse(await html_generator(ctx))
434
+ for header in ctx.get_pending_set_cookie_headers():
435
+ response.headers.append("set-cookie", header)
436
+ return response
437
+ finally:
438
+ scheduler = inject(ASYNC_SCHEDULER_PORT_KEY)
439
+ await scheduler.await_pending()
440
+ ctx.dispose()
441
+ raise HTTPException(404)
442
+
443
+ if serve_prerendered and accepts_html and html_404_file is not None:
444
+ return _file_response(html_404_file, media_type="text/html; charset=utf-8", status_code=404)
445
+ raise HTTPException(404)
446
+
447
+ routes.append(Route("/{path:path}", send_html))
448
+ else:
449
+
450
+ async def send_hash_html(request: Request) -> Response:
451
+ if serve_prerendered and "" in prerender_map:
452
+ html_file = prerender_map[""]
453
+ if not html_file.is_file():
454
+ raise HTTPException(404)
455
+ return _file_response(html_file, media_type="text/html; charset=utf-8")
456
+ if not ssr_enabled:
457
+ raise HTTPException(404)
458
+ if hash_cache:
459
+ return HTMLResponse(hash_cache[0])
460
+ cookie_header = request.headers.get("cookie", "")
461
+ initial_theme = _read_initial_theme(cookie_header)
462
+ ctx = app.create_render_context(
463
+ "/",
464
+ initial_theme=initial_theme,
465
+ cookie_header=cookie_header,
466
+ )
467
+ try:
468
+ scheduler = inject(ASYNC_SCHEDULER_PORT_KEY)
469
+ await scheduler.await_pending()
470
+ return HTMLResponse(await html_generator(ctx))
471
+ finally:
472
+ scheduler = inject(ASYNC_SCHEDULER_PORT_KEY)
473
+ await scheduler.await_pending()
474
+ ctx.dispose()
475
+
476
+ routes.append(Route("/", send_hash_html))
477
+ if base_url_segment:
478
+ routes.append(Route(f"/{base_url_segment}/", send_hash_html))
479
+
480
+ asgi = Starlette(routes=routes)
481
+
482
+ if configure_fetch:
483
+ fetch_port = app._server_fetch_port
484
+ if fetch_port is not None:
485
+ blocked_paths = [route[0] for route in (app.routes or []) if route[3] is not None]
486
+ fetch_port.configure(
487
+ asgi,
488
+ blocked_paths,
489
+ base_url=app.config.base_url,
490
+ mount_prefixes=[prefix for prefix, _ in mount_entries] + rpc_mount_prefixes,
491
+ )
492
+
493
+ return asgi
494
+
495
+
496
+ def _build_prebuilt_asset_routes(
497
+ manifest: PrebuildManifest,
498
+ public_dir: Path,
499
+ base_url: str,
500
+ ) -> tuple[list[BaseRoute], list[BaseRoute]]:
501
+ asset_routes: list[BaseRoute] = []
502
+ allowed_wheels = {manifest.wheel_filename} | set(manifest.extra_wheel_filenames or ())
503
+
504
+ async def send_app_package_file(request: Request) -> Response:
505
+ filename = str(request.path_params.get("filename", ""))
506
+ if filename not in allowed_wheels:
507
+ raise HTTPException(404)
508
+ wheel_path = public_dir / "_webcompy-app-package" / filename
509
+ media_type = mimetypes.guess_type(str(wheel_path))[0] or "application/octet-stream"
510
+ return _file_response(
511
+ wheel_path,
512
+ media_type=media_type,
513
+ headers={"Cache-Control": "public, max-age=31536000, immutable"},
514
+ )
515
+
516
+ base_url_stripped = "/" + base_url.strip("/") if base_url.strip("/") else ""
517
+ asset_routes.append(Route("/_webcompy-app-package/{filename:path}", send_app_package_file))
518
+ if base_url_stripped:
519
+ asset_routes.append(
520
+ Route(f"{base_url_stripped}/_webcompy-app-package/{{filename:path}}", send_app_package_file)
521
+ )
522
+
523
+ if manifest.wasm_serving == "local" and manifest.wasm_asset_files:
524
+ allowed_wasm = set(manifest.wasm_asset_files.values())
525
+
526
+ async def send_wasm_asset(request: Request) -> Response:
527
+ filename = str(request.path_params.get("filename", ""))
528
+ if filename not in allowed_wasm:
529
+ raise HTTPException(404)
530
+ asset_path = public_dir / "_webcompy-assets" / "packages" / filename
531
+ return _file_response(
532
+ asset_path,
533
+ media_type="application/octet-stream",
534
+ headers={"Cache-Control": "public, max-age=31536000, immutable"},
535
+ )
536
+
537
+ asset_routes.append(Route("/_webcompy-assets/packages/{filename:path}", send_wasm_asset))
538
+ if base_url_stripped:
539
+ asset_routes.append(
540
+ Route(f"{base_url_stripped}/_webcompy-assets/packages/{{filename:path}}", send_wasm_asset)
541
+ )
542
+
543
+ if manifest.runtime_serving == "local" and manifest.runtime_asset_files:
544
+ allowed_runtime = set(manifest.runtime_asset_files)
545
+ runtime_prefix = get_runtime_asset_prefix(manifest.pyscript_version)
546
+
547
+ async def send_runtime_asset(request: Request) -> Response:
548
+ filename = str(request.path_params.get("filename", ""))
549
+ if filename not in allowed_runtime:
550
+ raise HTTPException(404)
551
+ asset_path = public_dir / runtime_prefix / filename
552
+ media_type = mimetypes.guess_type(str(asset_path))[0] or "application/octet-stream"
553
+ return _file_response(
554
+ asset_path,
555
+ media_type=media_type,
556
+ headers={"Cache-Control": "public, max-age=31536000, immutable"},
557
+ )
558
+
559
+ asset_routes.append(Route(f"/{runtime_prefix}/{{filename:path}}", send_runtime_asset))
560
+ if base_url_stripped:
561
+ asset_routes.append(Route(f"{base_url_stripped}/{runtime_prefix}/{{filename:path}}", send_runtime_asset))
562
+
563
+ async def send_framework_ui_css(request: Request) -> Response:
564
+ filename = str(request.path_params.get("filename", ""))
565
+ if not filename or "/" in filename or "\\" in filename or filename.startswith("."):
566
+ raise HTTPException(404)
567
+ css_path = public_dir / "_webcompy-ui" / filename
568
+ if not css_path.is_file():
569
+ raise HTTPException(404)
570
+ return _file_response(
571
+ css_path,
572
+ media_type="text/css",
573
+ headers={"Cache-Control": "public, max-age=0, must-revalidate"},
574
+ )
575
+
576
+ asset_routes.append(Route("/_webcompy-ui/{filename:path}", send_framework_ui_css))
577
+ if base_url_stripped:
578
+ asset_routes.append(Route(f"{base_url_stripped}/_webcompy-ui/{{filename:path}}", send_framework_ui_css))
579
+
580
+ resource_root = public_dir / "_webcompy-resource"
581
+ allow_list = frozenset(manifest.resource_allow_list)
582
+ if allow_list or resource_root.is_dir():
583
+ resolved_resource_root = resource_root.resolve()
584
+
585
+ async def send_resource(request: Request) -> Response:
586
+ rel = str(request.path_params.get("path", ""))
587
+ if rel not in allow_list:
588
+ raise HTTPException(404)
589
+ try:
590
+ target = (resource_root / rel).resolve()
591
+ target.relative_to(resolved_resource_root)
592
+ except (ValueError, OSError):
593
+ raise HTTPException(403) from None
594
+ if not target.is_file():
595
+ raise HTTPException(404)
596
+ media_type = mimetypes.guess_type(str(target))[0] or "application/octet-stream"
597
+ cache_control = (
598
+ "public, max-age=31536000, immutable"
599
+ if request.query_params.get("v", "").strip()
600
+ else "public, max-age=3600"
601
+ )
602
+ return _file_response(target, media_type=media_type, headers={"Cache-Control": cache_control})
603
+
604
+ asset_routes.append(Route(base_url_stripped + "/_webcompy-resource/{path:path}", send_resource))
605
+ if base_url_stripped:
606
+ asset_routes.append(Route("/_webcompy-resource/{path:path}", send_resource))
607
+
608
+ if manifest.pwa_enabled:
609
+
610
+ async def send_manifest(_request: Request) -> Response:
611
+ return _file_response(public_dir / MANIFEST_FILENAME, media_type=MANIFEST_MEDIA_TYPE)
612
+
613
+ async def send_service_worker(_request: Request) -> Response:
614
+ return _file_response(
615
+ public_dir / SW_FILENAME,
616
+ media_type=SW_MEDIA_TYPE,
617
+ headers={"Cache-Control": "no-cache"},
618
+ )
619
+
620
+ asset_routes.append(Route(f"/{MANIFEST_FILENAME}", send_manifest))
621
+ asset_routes.append(Route(f"/{SW_FILENAME}", send_service_worker))
622
+ if base_url_stripped:
623
+ asset_routes.append(Route(f"{base_url_stripped}/{MANIFEST_FILENAME}", send_manifest))
624
+ asset_routes.append(Route(f"{base_url_stripped}/{SW_FILENAME}", send_service_worker))
625
+
626
+ static_map: dict[str, tuple[Path, str, str | None]] = {}
627
+ for rel_path in manifest.static_files:
628
+ file_path = public_dir / rel_path
629
+ media_type = mimetypes.guess_type(str(file_path))[0] or "application/octet-stream"
630
+ static_map["/" + rel_path] = (file_path, media_type, "public, max-age=0, must-revalidate")
631
+ if base_url_stripped:
632
+ static_map[f"{base_url_stripped}/{rel_path}"] = (
633
+ file_path,
634
+ media_type,
635
+ "public, max-age=0, must-revalidate",
636
+ )
637
+
638
+ for sr_meta in manifest.static_routes:
639
+ file_path = public_dir / sr_meta.path
640
+ static_map["/" + sr_meta.path] = (file_path, sr_meta.media_type, sr_meta.cache_control)
641
+ if base_url_stripped:
642
+ static_map[f"{base_url_stripped}/{sr_meta.path}"] = (file_path, sr_meta.media_type, sr_meta.cache_control)
643
+
644
+ static_map_routes: list[BaseRoute] = [_StaticMapRoute(static_map)] if static_map else []
645
+ return asset_routes, static_map_routes
646
+
647
+
648
+ def _resolve_prebuilt_manifest(prebuilt: str | Path | PrebuildManifest | None) -> PrebuildManifest:
649
+ if isinstance(prebuilt, PrebuildManifest):
650
+ return prebuilt
651
+ if prebuilt is not None:
652
+ return load_prebuild_manifest(prebuilt)
653
+ env_dir = os.environ.get(WEBCOMPY_PREBUILT_DIR_ENV, "").strip()
654
+ if not env_dir:
655
+ raise WebComPyException(
656
+ f"Prebuilt directory not provided and environment variable {WEBCOMPY_PREBUILT_DIR_ENV!r} is not set."
657
+ )
658
+ return load_prebuild_manifest(env_dir)
659
+
660
+
661
+ def _resolve_runtime_resource_port(
662
+ manifest: PrebuildManifest,
663
+ resource_port: ResourcePort | None,
664
+ resources_dir: str | Path | None,
665
+ ) -> ResourcePort:
666
+ if resource_port is not None:
667
+ return resource_port
668
+ allow_list = frozenset(manifest.resource_allow_list)
669
+ if resources_dir is not None:
670
+ return ServerResourcePort(app_package_path=Path(resources_dir), allow_list=allow_list, cache=True)
671
+ if manifest.embedded_resources is not None:
672
+ return InMemoryServerResourcePort(resources=manifest.embedded_resources, allow_list=allow_list)
673
+ if manifest.prebuilt_dir is not None:
674
+ return ServerResourcePort(
675
+ app_package_path=manifest.prebuilt_dir / "public" / "_webcompy-resource",
676
+ allow_list=allow_list,
677
+ cache=True,
678
+ )
679
+ return InMemoryServerResourcePort(resources={}, allow_list=allow_list)
680
+
681
+
682
+ def _build_prebuilt_serving_components(
683
+ app: WebComPyApp,
684
+ manifest: PrebuildManifest,
685
+ *,
686
+ mounts: Mapping[str, ASGIApp] | Callable[[], Mapping[str, ASGIApp] | None] | None = None,
687
+ static_routes: Sequence[StaticRoute] | Callable[[], Sequence[StaticRoute] | None] | None = None,
688
+ root_app: ASGIApp | None = None,
689
+ serve_assets: bool = True,
690
+ resource_port: ResourcePort | None = None,
691
+ resources_dir: str | Path | None = None,
692
+ ) -> tuple[Starlette, partial[Any], list[str], tuple[str, ...], bool]:
693
+ from webcompy_server import configure_server_context
694
+
695
+ validate_prebuild_manifest(manifest, app, serve_assets=serve_assets)
696
+
697
+ resolved_port = _resolve_runtime_resource_port(manifest, resource_port, resources_dir)
698
+ configure_server_context(app, resource_port=resolved_port, root_app=root_app)
699
+
700
+ base_url = app.config.base_url
701
+ base_url_prefix = "/" + base_url.strip("/") if base_url.strip("/") else ""
702
+ mount_entries = _resolve_mounts(app, mounts)
703
+
704
+ extra_static_entries = _resolve_static_routes(
705
+ app,
706
+ static_routes,
707
+ manifest.static_files,
708
+ pwa_enabled=manifest.pwa_enabled,
709
+ mount_prefixes=tuple(prefix for prefix, _ in mount_entries),
710
+ )
711
+ virtual_static_routes = _build_dynamic_static_routes(
712
+ extra_static_entries,
713
+ base_url_prefix=base_url_prefix,
714
+ dev_mode=False,
715
+ )
716
+
717
+ asset_routes: list[BaseRoute] = []
718
+ static_map_routes: list[BaseRoute] = []
719
+ prerendered_html_files: dict[str, Path] = {}
720
+ html_404_file: Path | None = None
721
+
722
+ if serve_assets:
723
+ if manifest.prebuilt_dir is None:
724
+ raise WebComPyException("Cannot serve prebuilt assets without a prebuilt_dir on PrebuildManifest.")
725
+ public_dir = manifest.prebuilt_dir / "public"
726
+ asset_routes, static_map_routes = _build_prebuilt_asset_routes(manifest, public_dir, base_url)
727
+ for route_key, rel_html in manifest.prerendered_routes.items():
728
+ prerendered_html_files[route_key] = public_dir / rel_html
729
+ if manifest.has_404_html:
730
+ html_404_file = public_dir / "404.html"
731
+
732
+ extra_wheel_filenames = list(manifest.extra_wheel_filenames) if manifest.extra_wheel_filenames is not None else None
733
+ wasm_local_urls = (
734
+ {pkg: f"{base_url}_webcompy-assets/packages/{wheel}" for pkg, wheel in manifest.wasm_asset_files.items()}
735
+ if manifest.wasm_serving == "local" and manifest.wasm_asset_files
736
+ else None
737
+ )
738
+ html_generator = partial(
739
+ generate_html,
740
+ app_package_name=manifest.app_package_name,
741
+ dev_mode=False,
742
+ prerender=True,
743
+ wheel_filename=manifest.wheel_filename,
744
+ pyodide_package_names=list(manifest.pyodide_package_names) if manifest.pyodide_package_names else None,
745
+ wasm_local_urls=wasm_local_urls,
746
+ lockfile_url=manifest.lockfile_url,
747
+ runtime_serving=manifest.runtime_serving,
748
+ extra_wheel_filenames=extra_wheel_filenames,
749
+ app_package_path=None,
750
+ pwa_enabled=manifest.pwa_enabled,
751
+ asset_hashes=dict(manifest.asset_hashes) if manifest.asset_hashes else None,
752
+ resource_version=manifest.resource_version,
753
+ preloaded_loading_template=manifest.loading_template_html,
754
+ )
755
+
756
+ hash_cache: list[str] = []
757
+ asgi = _assemble_ssr_asgi(
758
+ app,
759
+ html_generator=html_generator,
760
+ hash_cache=hash_cache,
761
+ asset_routes=asset_routes,
762
+ static_map_routes=static_map_routes,
763
+ virtual_static_routes=virtual_static_routes,
764
+ mount_entries=mount_entries,
765
+ prerendered_html_files=prerendered_html_files,
766
+ html_404_file=html_404_file,
767
+ ssr_enabled=manifest.ssr_enabled,
768
+ serve_prerendered=serve_assets,
769
+ include_html_catchall=serve_assets or manifest.ssr_enabled,
770
+ configure_fetch=root_app is None,
771
+ )
772
+ static_route_paths = tuple(
773
+ dict.fromkeys([*(sr.path for sr in manifest.static_routes), *(rel for rel, _ in extra_static_entries)])
774
+ )
775
+ needs_hash_prerender = manifest.ssr_enabled and not (serve_assets and "" in manifest.prerendered_routes)
776
+ return asgi, html_generator, hash_cache, static_route_paths, needs_hash_prerender
777
+
778
+
779
+ def create_prebuilt_asgi_app(
780
+ app: WebComPyApp,
781
+ prebuilt: str | Path | PrebuildManifest | None = None,
782
+ *,
783
+ mounts: Mapping[str, ASGIApp] | Callable[[], Mapping[str, ASGIApp] | None] | None = None,
784
+ static_routes: Sequence[StaticRoute] | Callable[[], Sequence[StaticRoute] | None] | None = None,
785
+ root_app: ASGIApp | None = None,
786
+ serve_assets: bool = True,
787
+ resource_port: ResourcePort | None = None,
788
+ resources_dir: str | Path | None = None,
789
+ ) -> ASGIApp:
790
+ """Create a production ASGI application from prebuilt artifacts.
791
+
792
+ Loads and validates build metadata in O(1) without rewriting lockfiles,
793
+ rebuilding wheels, hashing assets, or pulling CLI/dev dependencies.
794
+ Fails fast with ``WebComPyException`` if ``prebuilt`` is omitted without
795
+ ``WEBCOMPY_PREBUILT_DIR`` set, if manifest validation fails, or if mount,
796
+ static-route, or asset checks detect an invalid configuration.
797
+
798
+ Args:
799
+ app: Target ``WebComPyApp`` instance to serve.
800
+ prebuilt: Path to the prebuild directory, an in-memory
801
+ ``PrebuildManifest`` instance, or ``None`` to read from
802
+ ``WEBCOMPY_PREBUILT_DIR``.
803
+ mounts: Optional mapping (or zero-argument callable returning a
804
+ mapping) of path prefixes to sub-mounted ASGI applications.
805
+ static_routes: Optional sequence (or callable returning a sequence)
806
+ of dynamic ``StaticRoute`` overrides registered at runtime.
807
+ root_app: Optional host ASGI application for single-call embedded
808
+ self-site fetch wiring.
809
+ serve_assets: Whether this ASGI app serves files from
810
+ ``<prebuilt_dir>/public``. Set ``False`` when static assets and
811
+ pre-rendered HTML are offloaded to a CDN or edge asset layer.
812
+ resource_port: Optional custom ``ResourcePort`` used during SSR.
813
+ resources_dir: Optional directory overriding where disk-backed
814
+ resources are read from during SSR.
815
+
816
+ Returns:
817
+ Configured Starlette ``ASGIApp`` ready for Uvicorn, Mangum,
818
+ Cloudflare Workers ASGI, or mounting into a host application.
819
+
820
+ """
821
+ manifest = _resolve_prebuilt_manifest(prebuilt)
822
+ asgi, _, _, _, _ = _build_prebuilt_serving_components(
823
+ app,
824
+ manifest,
825
+ mounts=mounts,
826
+ static_routes=static_routes,
827
+ root_app=root_app,
828
+ serve_assets=serve_assets,
829
+ resource_port=resource_port,
830
+ resources_dir=resources_dir,
831
+ )
832
+ return asgi