""" YAZ Care Platform - Factory Static Files & Templates Setup Static file serving (with pre-compressed Brotli/Gzip support), template discovery, and template filter registration. Version: 5.3.0 """ from pathlib import Path # Re-import these from Starlette for ASGI middleware classes from starlette.staticfiles import StaticFiles from starlette.templating import Jinja2Templates from ._config import PROJECT_ROOT, FastAPI, logger, settings def _setup_static_and_templates(app: FastAPI) -> None: """Consolidated static files and templates setup - PRIORITIZE BEAUTIFUL UI""" # Static files - modern structure with fallbacks static_paths = [settings.static_dir] # Fallback paths static_paths.extend( [ PROJECT_ROOT / "src" / "ui" / "static", PROJECT_ROOT / "static", PROJECT_ROOT / "src" / "static", ] ) # ── HTTP Early Hints / Link preload headers for HTML responses ───────── from starlette.types import ASGIApp, Receive, Scope, Send _PRELOAD_LINK = ( b"; rel=preload; as=style, " b"; rel=preload; as=script, " b"; rel=preload; as=script" ) class _EarlyHintMiddleware: """Add Link preload headers on text/html responses (Early Hints / H2 push).""" def __init__(self, wrapped: ASGIApp) -> None: self._app = wrapped async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] != "http": await self._app(scope, receive, send) return path: str = scope.get("path", "") if path.startswith("/static/") or path.startswith("/api/"): await self._app(scope, receive, send) return async def _send_with_hints(message: dict) -> None: if message.get("type") == "http.response.start": ct = "" for k, v in message.get("headers", []): if k.lower() == b"content-type": ct = v.decode("latin-1", errors="ignore") break if "text/html" in ct: headers = list(message.get("headers", [])) headers.append((b"link", _PRELOAD_LINK)) message = {**message, "headers": headers} await send(message) await self._app(scope, receive, _send_with_hints) # type: ignore[arg-type, assignment] app.add_middleware(_EarlyHintMiddleware) logger.info("✓ Early Hint / Link preload middleware registered (tailwind + htmx + alpine)") # ── Cache-Control + Pre-compressed static asset middleware ────────────── _IMMUTABLE_PREFIXES = ("/static/vendor/", "/static/fonts/") _IMMUTABLE_EXTS = frozenset([".woff2", ".woff", ".ttf", ".eot"]) _COMPRESSIBLE_EXTS = frozenset([".js", ".css", ".svg", ".json", ".html"]) class _StaticCacheMiddleware: """ Inject Cache-Control headers and serve pre-compressed variants for /static/*. Priority: Brotli (.br) > Gzip (.gz) > raw Immutable cache for vendor/* and fonts/*; 7-day SWR for app assets. """ def __init__(self, wrapped: ASGIApp, static_dir: str) -> None: self._app = wrapped self._static_dir = static_dir async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] != "http": await self._app(scope, receive, send) return path: str = scope.get("path", "") if not path.startswith("/static/"): await self._app(scope, receive, send) return # ── Try to serve a pre-compressed variant ──────────────────────── if any(path.endswith(ext) for ext in _COMPRESSIBLE_EXTS): accept_enc = "" for k, v in scope.get("headers", []): if k == b"accept-encoding": accept_enc = v.decode("latin-1", errors="ignore") break rel_path = path[len("/static/") :] if "br" in accept_enc: br_file = Path(self._static_dir) / (rel_path + ".br") if br_file.exists(): scope = dict(scope) scope["path"] = path + ".br" await self._app( scope, receive, lambda msg, enc=b"br": self._patch(msg, enc, path, send) ) # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] return if "gzip" in accept_enc: gz_file = Path(self._static_dir) / (rel_path + ".gz") if gz_file.exists(): scope = dict(scope) scope["path"] = path + ".gz" await self._app( scope, receive, lambda msg, enc=b"gzip": self._patch(msg, enc, path, send), ) # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] return # ── Fall through to raw file ────────────────────────────────────── is_immutable = any(path.startswith(p) for p in _IMMUTABLE_PREFIXES) or any( path.endswith(ext) for ext in _IMMUTABLE_EXTS ) cache_value = ( b"public, max-age=31536000, immutable" if is_immutable else b"public, max-age=604800, stale-while-revalidate=86400" ) async def _send_with_cache(message: dict) -> None: if message.get("type") == "http.response.start": headers = [ (k, v) for k, v in message.get("headers", []) if k.lower() != b"cache-control" ] headers.append((b"cache-control", cache_value)) headers.append((b"vary", b"Accept-Encoding")) message = {**message, "headers": headers} await send(message) await self._app(scope, receive, _send_with_cache) # type: ignore[arg-type, assignment] @staticmethod async def _patch(message: dict, content_encoding: bytes, orig_path: str, send) -> None: """Fix headers for pre-compressed variant response.""" if message.get("type") == "http.response.start": headers = [ (k, v) for k, v in message.get("headers", []) if k.lower() not in (b"cache-control", b"content-type", b"content-encoding") ] if orig_path.endswith(".js"): ct = b"application/javascript; charset=utf-8" elif orig_path.endswith(".css"): ct = b"text/css; charset=utf-8" elif orig_path.endswith(".svg"): ct = b"image/svg+xml" elif orig_path.endswith(".json"): ct = b"application/json" else: ct = b"text/plain" is_immutable = any(orig_path.startswith(p) for p in _IMMUTABLE_PREFIXES) cache = ( b"public, max-age=31536000, immutable" if is_immutable else b"public, max-age=604800, stale-while-revalidate=86400" ) headers += [ (b"content-type", ct), (b"content-encoding", content_encoding), (b"cache-control", cache), (b"vary", b"Accept-Encoding"), ] message = {**message, "headers": headers} await send(message) for static_dir in static_paths: if static_dir.exists(): try: static_app = StaticFiles(directory=str(static_dir)) app.mount( "/static", _StaticCacheMiddleware(static_app, str(static_dir)), name="static" ) logger.info("✓ Static files mounted (cache + pre-compressed): %s", static_dir) break except Exception as e: logger.info("Failed to mount static files from %s: %s", static_dir, e) continue # Templates - PRIORITIZE beautiful base.html location template_paths = [ PROJECT_ROOT / "src" / "ui" / "templates", ] template_paths.append(settings.templates_dir) template_paths.extend([PROJECT_ROOT / "src" / "templates", PROJECT_ROOT / "templates"]) templates_found = False for templates_dir in template_paths: if templates_dir.exists(): try: base_file = templates_dir / "base.html" if base_file.exists(): app.state.templates = Jinja2Templates(directory=str(templates_dir)) app.state.templates.env.auto_reload = True app.state.templates.env.cache_size = 0 logger.info("✅ Beautiful UI templates found with base.html: %s", templates_dir) file_size = base_file.stat().st_size if file_size > 100000: logger.info( "✅ Confirmed beautiful base.html template (%d bytes)", file_size ) templates_found = True break home_file = templates_dir / "home.html" if home_file.exists(): app.state.templates = Jinja2Templates(directory=str(templates_dir)) app.state.templates.env.auto_reload = True app.state.templates.env.cache_size = 0 logger.info("✓ Templates with home.html: %s", templates_dir) templates_found = True break else: logger.info( "Templates directory exists but no base.html or home.html: %s", templates_dir, ) except Exception as e: logger.warning("Failed to setup templates from %s: %s", templates_dir, e) continue if not templates_found: logger.warning("No templates directory with base.html found, creating fallback") try: fallback_template_dir = PROJECT_ROOT / "src" / "ui" / "templates" if fallback_template_dir.exists(): app.state.templates = Jinja2Templates(directory=str(fallback_template_dir)) logger.info("✓ Fallback templates (your beautiful UI): %s", fallback_template_dir) templates_found = True except Exception as e: logger.error("Failed to setup fallback templates: %s", e) if templates_found and hasattr(app.state, "templates"): templates_env = app.state.templates.env if hasattr(templates_env, "loader") and hasattr(templates_env.loader, "searchpath"): app.state.templates_dir = templates_env.loader.searchpath[0] logger.info("✅ Templates directory stored: %s", app.state.templates_dir) else: app.state.templates_dir = str(PROJECT_ROOT / "src" / "ui" / "templates") logger.info("✅ Templates directory fallback: %s", app.state.templates_dir) # Register custom template filters if hasattr(app.state, "templates") and hasattr(app.state.templates, "env"): try: import sys src_path = str(PROJECT_ROOT / "src") if src_path not in sys.path: sys.path.insert(0, src_path) from ui.template_filters import asset_url app.state.templates.env.globals["asset_url"] = asset_url app.state.templates.env.filters["asset_url"] = asset_url logger.info("✓ Template filters registered (asset_url)") except ImportError as e: logger.warning("Could not import template filters: %s", e) def fallback_asset_url(path): return path app.state.templates.env.globals["asset_url"] = fallback_asset_url app.state.templates.env.filters["asset_url"] = fallback_asset_url logger.info("✓ Fallback template filter registered") except Exception as e: logger.error("Failed to register template filters: %s", e) # Register domain navigation globals (sidebar uses these) try: from apps_routes import DOMAINS domain_groups: dict = {} for _slug, _cfg in DOMAINS.items(): g = _cfg.get("group", "other") domain_groups.setdefault(g, []).append({"slug": _slug, **_cfg}) app.state.templates.env.globals["nav_domains"] = DOMAINS app.state.templates.env.globals["nav_domain_groups"] = domain_groups logger.info("✓ Domain navigation globals registered (%d domains)", len(DOMAINS)) except Exception as e: app.state.templates.env.globals["nav_domains"] = {} app.state.templates.env.globals["nav_domain_groups"] = {} logger.warning("Could not register domain navigation globals: %s", e)