"""AstrBot extension route resolution helpers. This module intentionally avoids starting a standalone web server. AstrBot can use these pure helpers while registering plugin extension routes in-process. """ from __future__ import annotations import importlib import re from dataclasses import dataclass from typing import Any, Callable from backend.route_registry import ROUTES, RouteSpec from backend.services.ui_service import API_BASE @dataclass(frozen=True) class RouteMatch: method: str endpoint: str permission: str handler_path: str handler: Callable[..., Any] path_params: dict[str, str] def normalize_extension_path(path: str) -> str: normalized = str(path or "").strip() if "?" in normalized: normalized = normalized.split("?", 1)[0] normalized = normalized.replace("\\", "/").strip("/") api_base = API_BASE.strip("/") if normalized == api_base: return "" if normalized.startswith(f"{api_base}/"): normalized = normalized[len(api_base) + 1 :] return normalized.strip("/") def resolve_route(method: str, path: str) -> RouteMatch | None: normalized_method = str(method or "").strip().upper() endpoint = normalize_extension_path(path) for route in ROUTES: if route.method != normalized_method: continue params = _match_endpoint(route.endpoint, endpoint) if params is None: continue return RouteMatch( method=route.method, endpoint=route.endpoint, permission=route.permission, handler_path=route.handler, handler=_load_handler(route.handler), path_params=params, ) return None def runtime_route_table() -> list[dict[str, Any]]: return [ { "method": route.method, "endpoint": route.endpoint, "path": f"{API_BASE}/{route.endpoint}", "permission": route.permission, "handler": route.handler, } for route in ROUTES ] def _match_endpoint(pattern: str, endpoint: str) -> dict[str, str] | None: param_names = re.findall(r"\{([^{}]+)\}", pattern) regex = "^" + re.sub(r"\{([^{}]+)\}", r"([^/]+)", pattern) + "$" match = re.match(regex, endpoint) if not match: return None return dict(zip(param_names, match.groups(), strict=False)) def _load_handler(handler_path: str) -> Callable[..., Any]: module_name, function_name = handler_path.rsplit(".", 1) handler = getattr(importlib.import_module(module_name), function_name) if not callable(handler): raise TypeError(f"route handler is not callable: {handler_path}") return handler