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,290 @@
1
+ """Server-side fetch port with self-site ASGI support."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from typing import TYPE_CHECKING
7
+
8
+ import httpx
9
+
10
+ from webcompy.exception import WebComPyException
11
+ from webcompy.hydration._payload import TransferFetchEntry
12
+ from webcompy.ports._fetch import FetchPort, Response
13
+
14
+ if TYPE_CHECKING:
15
+ from starlette.types import ASGIApp
16
+
17
+
18
+ class ServerFetchPort(FetchPort):
19
+ """Server-side ``FetchPort``.
20
+
21
+ ``noop = True`` marks this port as a pure no-op for realtime
22
+ connections: ``use_event_source`` (non-GET) uses it as the signal that
23
+ SSR/SSG degradation (warning + empty closed handle) applies, rather than
24
+ issuing a fetch request through the port. The port itself remains fully
25
+ functional for ordinary ``fetch()`` calls during SSR/SSG.
26
+ """
27
+
28
+ noop = True
29
+
30
+ def __init__(self, external_client: httpx.AsyncClient | None = None) -> None:
31
+ self._external_client = external_client
32
+ self._prototype: ServerFetchPort | None = None
33
+ self._self_site_client: httpx.AsyncClient | None = None
34
+ self._asgi_app: ASGIApp | None = None
35
+ self._blocked_paths: list[str] = []
36
+ self._mount_prefixes: list[str] = []
37
+ self._base_url: str = "/"
38
+ self._embedded: bool = False
39
+ self._response_cache: dict[str, Response] = {}
40
+
41
+ def is_self_site_url(self, url: str) -> bool:
42
+ """Return whether ``url`` targets the same site.
43
+
44
+ Args:
45
+ url: URL to check.
46
+
47
+ Returns:
48
+ ``True`` for relative URLs starting with ``/`` or ``.``.
49
+
50
+ """
51
+ if url.startswith("//"):
52
+ return False
53
+ return url.startswith("/") or url.startswith(".")
54
+
55
+ def configure(
56
+ self,
57
+ asgi_app: ASGIApp,
58
+ blocked_paths: list[str] | None = None,
59
+ base_url: str | None = None,
60
+ mount_prefixes: list[str] | None = None,
61
+ *,
62
+ embedded: bool = False,
63
+ ) -> None:
64
+ """Configure the ASGI app and routing for self-site fetches.
65
+
66
+ Args:
67
+ asgi_app: ASGI application handling self-site requests.
68
+ blocked_paths: Page routes blocked during SSR to avoid recursion.
69
+ base_url: Base URL prefix for resolving relative paths.
70
+ mount_prefixes: Mount prefixes considered self-site.
71
+ embedded: Whether the app is embedded under a host app.
72
+
73
+ Returns:
74
+ ``None``.
75
+
76
+ Raises:
77
+ WebComPyException: If the port is already configured.
78
+
79
+ """
80
+ if self._asgi_app is not None:
81
+ raise WebComPyException("ServerFetchPort is already configured")
82
+ self._asgi_app = asgi_app
83
+ self._blocked_paths = blocked_paths or []
84
+ self._mount_prefixes = ["/" + p.strip("/") for p in (mount_prefixes or []) if p.strip("/")]
85
+ if base_url is not None:
86
+ self._base_url = base_url
87
+ self._embedded = embedded
88
+ self._self_site_client = httpx.AsyncClient(
89
+ transport=httpx.ASGITransport(app=asgi_app),
90
+ )
91
+
92
+ def _is_mount_path(self, path: str) -> bool:
93
+ clean_path = path.split("?", 1)[0].split("#", 1)[0]
94
+ return any(clean_path == prefix or clean_path.startswith(prefix + "/") for prefix in self._mount_prefixes)
95
+
96
+ def _resolve_self_site_path(self, url: str) -> str:
97
+ if self._embedded:
98
+ if url.startswith("."):
99
+ base = self._base_url.rstrip("/")
100
+ url = url.lstrip(".")
101
+ url = url.lstrip("/")
102
+ return f"{base}/{url}" if base else f"/{url}"
103
+ return url
104
+ if url.startswith("/") and self._is_mount_path(url):
105
+ return url
106
+ base = self._base_url.rstrip("/")
107
+ if url.startswith("."):
108
+ url = url.lstrip(".")
109
+ url = url.lstrip("/")
110
+ return f"{base}/{url}" if base else f"/{url}"
111
+ return f"{base}{url}" if base else url
112
+
113
+ def _is_blocked(self, path: str) -> bool:
114
+ if path in self._blocked_paths:
115
+ return True
116
+ path_segments = path.strip("/").split("/")
117
+ for blocked in self._blocked_paths:
118
+ blocked_clean = blocked.strip("/")
119
+ blocked_segments = blocked_clean.split("/")
120
+ if len(path_segments) != len(blocked_segments):
121
+ continue
122
+ match = True
123
+ for ps, bs in zip(path_segments, blocked_segments, strict=False):
124
+ if bs.startswith(":"):
125
+ continue
126
+ if ps != bs:
127
+ match = False
128
+ break
129
+ if match:
130
+ return True
131
+ return False
132
+
133
+ def _cache_key(self, url: str, method: str, body: str | bytes | None = None) -> str:
134
+ if method == "GET":
135
+ return url
136
+ if body is None:
137
+ key_body = ""
138
+ elif isinstance(body, str):
139
+ key_body = body
140
+ else:
141
+ key_body = hashlib.sha256(body).hexdigest()
142
+ return f"{method}:{url}:{key_body}"
143
+
144
+ @staticmethod
145
+ def _extract_url_from_cache_key(key: str) -> str:
146
+ for method in ("GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"):
147
+ prefix = f"{method}:"
148
+ if key.startswith(prefix):
149
+ return key[len(prefix) :].rsplit(":", 1)[0]
150
+ return key
151
+
152
+ def _ensure_external_client(self) -> httpx.AsyncClient:
153
+ if self._external_client is None:
154
+ self._external_client = httpx.AsyncClient()
155
+ return self._external_client
156
+
157
+ async def fetch(
158
+ self,
159
+ url: str,
160
+ *,
161
+ method: str = "GET",
162
+ headers: dict[str, str] | None = None,
163
+ body: str | bytes | None = None,
164
+ ) -> Response:
165
+ """Fetch ``url`` via external client or in-process ASGI transport.
166
+
167
+ Args:
168
+ url: Target URL.
169
+ method: HTTP method.
170
+ headers: Optional request headers.
171
+ body: Optional request body as text or bytes.
172
+
173
+ Returns:
174
+ HTTP ``Response``.
175
+
176
+ """
177
+ if not self.is_self_site_url(url):
178
+ client = (
179
+ self._prototype._ensure_external_client()
180
+ if self._prototype is not None
181
+ else self._ensure_external_client()
182
+ )
183
+ res = await client.request(method, url, headers=headers, content=body)
184
+ return Response(
185
+ text=res.text,
186
+ content=res.content,
187
+ headers=dict(res.headers),
188
+ status_code=res.status_code,
189
+ status_text=res.reason_phrase,
190
+ ok=res.is_success,
191
+ )
192
+
193
+ if self._asgi_app is None:
194
+ return Response(
195
+ text="ServerFetchPort is not configured. Call configure() before fetching self-site URLs.",
196
+ headers={},
197
+ status_code=500,
198
+ status_text="Internal Server Error",
199
+ ok=False,
200
+ )
201
+
202
+ resolved_path = self._resolve_self_site_path(url)
203
+ cache_key = self._cache_key(resolved_path, method, body)
204
+ if cache_key in self._response_cache:
205
+ return self._response_cache[cache_key]
206
+
207
+ if not self._is_mount_path(resolved_path) and self._is_blocked(resolved_path):
208
+ return Response(
209
+ text=(
210
+ f"Path '{resolved_path}' is blocked during server-side rendering "
211
+ f"because it matches a page route. Fetching a page URL during SSR "
212
+ f"would cause infinite recursion."
213
+ ),
214
+ headers={},
215
+ status_code=500,
216
+ status_text="Internal Server Error",
217
+ ok=False,
218
+ )
219
+
220
+ assert self._self_site_client is not None
221
+ request_url = f"http://webcompy-internal{resolved_path}"
222
+ res = await self._self_site_client.request(
223
+ method,
224
+ request_url,
225
+ headers=headers,
226
+ content=body,
227
+ )
228
+ response = Response(
229
+ text=res.text,
230
+ content=res.content,
231
+ headers=dict(res.headers),
232
+ status_code=res.status_code,
233
+ status_text=res.reason_phrase,
234
+ ok=res.is_success,
235
+ )
236
+ self._response_cache[cache_key] = response
237
+ return response
238
+
239
+ def _clone_for_context(self) -> ServerFetchPort:
240
+ clone = ServerFetchPort(external_client=self._external_client)
241
+ clone._prototype = self
242
+ clone._asgi_app = self._asgi_app
243
+ clone._blocked_paths = self._blocked_paths
244
+ clone._mount_prefixes = self._mount_prefixes
245
+ clone._base_url = self._base_url
246
+ clone._embedded = self._embedded
247
+ clone._self_site_client = self._self_site_client
248
+ return clone
249
+
250
+ def get_transfer_data(self) -> dict[str, TransferFetchEntry]:
251
+ """Collect cache entries eligible for hydration transfer.
252
+
253
+ Returns:
254
+ Mapping of cache keys to transfer entries for self-site responses.
255
+
256
+ """
257
+ result: dict[str, TransferFetchEntry] = {}
258
+ for key, response in self._response_cache.items():
259
+ url = self._extract_url_from_cache_key(key)
260
+ if not self.is_self_site_url(url):
261
+ continue
262
+ if response.status_code == 204 or not response.text:
263
+ continue
264
+ result[key] = TransferFetchEntry(
265
+ status_code=response.status_code,
266
+ headers=response.headers,
267
+ body=response.text,
268
+ )
269
+ return result
270
+
271
+ def clear_cache(self) -> None:
272
+ """Clear the response cache.
273
+
274
+ Returns:
275
+ ``None``.
276
+
277
+ """
278
+ self._response_cache.clear()
279
+
280
+ async def close(self) -> None:
281
+ """Close underlying HTTP clients.
282
+
283
+ Returns:
284
+ ``None``.
285
+
286
+ """
287
+ if self._external_client is not None:
288
+ await self._external_client.aclose()
289
+ if self._self_site_client is not None:
290
+ await self._self_site_client.aclose()
@@ -0,0 +1,72 @@
1
+ """Server-side FFI port."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from webcompy.ports._ffi import FFIPort
8
+
9
+
10
+ class ServerFFIPort(FFIPort):
11
+ """Server-side no-op FFI port."""
12
+
13
+ def create_proxy(self, obj: Any) -> Any:
14
+ """Create a proxy for ``obj``.
15
+
16
+ Args:
17
+ obj: Object to wrap.
18
+
19
+ Returns:
20
+ ``obj`` unchanged on the server.
21
+
22
+ """
23
+ return obj
24
+
25
+ def destroy_proxy(self, proxy: Any) -> None:
26
+ """Destroy a previously created proxy.
27
+
28
+ Args:
29
+ proxy: Proxy to destroy.
30
+
31
+ Returns:
32
+ ``None``.
33
+
34
+ """
35
+ pass
36
+
37
+ def is_none(self, obj: Any) -> bool:
38
+ """Return whether ``obj`` is ``None``.
39
+
40
+ Args:
41
+ obj: Value to check.
42
+
43
+ Returns:
44
+ ``True`` if ``obj`` is ``None``.
45
+
46
+ """
47
+ return obj is None
48
+
49
+ def to_js(self, obj: Any) -> Any:
50
+ """Convert ``obj`` to a JavaScript value.
51
+
52
+ Args:
53
+ obj: Value to convert.
54
+
55
+ Returns:
56
+ ``obj`` unchanged on the server.
57
+
58
+ """
59
+ return obj
60
+
61
+ def assign(self, target: Any, source: Any) -> None:
62
+ """Assign properties from ``source`` to ``target``.
63
+
64
+ Args:
65
+ target: Target object.
66
+ source: Source object.
67
+
68
+ Returns:
69
+ ``None``.
70
+
71
+ """
72
+ pass
@@ -0,0 +1,47 @@
1
+ """Server-side history port."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from webcompy.ports._history import HistoryPort
8
+
9
+
10
+ class ServerHistoryPort(HistoryPort):
11
+ """Server-side history port without browser navigation.
12
+
13
+ Args:
14
+ mode: Routing mode.
15
+ initial_path: Initial path.
16
+
17
+ """
18
+
19
+ def __init__(self, *, mode: Literal["hash", "history"], initial_path: str = "/") -> None:
20
+ super().__init__(initial_path, mode=mode)
21
+
22
+ def current_search(self) -> str:
23
+ """Return the current search string.
24
+
25
+ Returns:
26
+ Empty string on the server.
27
+
28
+ """
29
+ return ""
30
+
31
+ def history_state(self) -> object | None:
32
+ """Return the current history state.
33
+
34
+ Returns:
35
+ Current state object.
36
+
37
+ """
38
+ return self._state
39
+
40
+ def refresh_from_window(self) -> None:
41
+ """Sync history state from the window.
42
+
43
+ Returns:
44
+ ``None``.
45
+
46
+ """
47
+ pass
@@ -0,0 +1,71 @@
1
+ """Server-side host port."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any, TypeVar, overload
7
+
8
+ from webcompy.ports._host import HostPort
9
+
10
+ T_co = TypeVar("T_co", covariant=True)
11
+
12
+
13
+ class ServerHostPort(HostPort):
14
+ """Server-side host port with synchronous task execution."""
15
+
16
+ def schedule_macro_task(self, callback: Callable[..., Any]) -> None:
17
+ """Schedule ``callback`` as a macro task.
18
+
19
+ Args:
20
+ callback: Callback to execute.
21
+
22
+ Returns:
23
+ ``None``.
24
+
25
+ """
26
+ callback()
27
+
28
+ def add_window_event_listener(self, event_type: str, handler: Any) -> Callable[[], None]:
29
+ """Add a window event listener.
30
+
31
+ Args:
32
+ event_type: Event type.
33
+ handler: Event handler.
34
+
35
+ Returns:
36
+ Callable that removes the listener.
37
+
38
+ """
39
+ return lambda: None
40
+
41
+ @overload
42
+ def create_js_global_getter(self, name: str, *, wrapper: Callable[[Any | None], T_co]) -> Callable[[], T_co]: ...
43
+ @overload
44
+ def create_js_global_getter(self, name: str, *, default: T_co) -> Callable[[], Any | T_co]: ...
45
+ @overload
46
+ def create_js_global_getter(self, name: str) -> Callable[[], Any | None]: ...
47
+ def create_js_global_getter(
48
+ self,
49
+ name: str,
50
+ *,
51
+ wrapper: Callable[[Any | None], Any] | None = None,
52
+ default: Any = None,
53
+ ) -> Callable[[], Any]:
54
+ """Create a getter for a JavaScript global.
55
+
56
+ Args:
57
+ name: Global name.
58
+ wrapper: Optional wrapper for the global value.
59
+ default: Default value when the global is absent.
60
+
61
+ Returns:
62
+ Callable that returns the global value or ``default``.
63
+
64
+ """
65
+
66
+ def _getter() -> Any:
67
+ if wrapper is not None:
68
+ return wrapper(None)
69
+ return default
70
+
71
+ return _getter
@@ -0,0 +1,27 @@
1
+ """Server-side media query port."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from webcompy.ports._media_query import MediaQueryPort
6
+
7
+
8
+ class ServerMediaQueryPort(MediaQueryPort):
9
+ """Server-side media query port returning defaults."""
10
+
11
+ def prefers_dark(self) -> bool:
12
+ """Return whether the user prefers a dark theme.
13
+
14
+ Returns:
15
+ ``False`` on the server.
16
+
17
+ """
18
+ return False
19
+
20
+ def prefers_reduced_motion(self) -> bool:
21
+ """Return whether the user prefers reduced motion.
22
+
23
+ Returns:
24
+ ``False`` on the server.
25
+
26
+ """
27
+ return False