litestar-vite 0.2.8__py3-none-any.whl → 0.7.0__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.

Potentially problematic release.


This version of litestar-vite might be problematic. Click here for more details.

@@ -1,370 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import itertools
4
- from collections import defaultdict
5
- from functools import lru_cache
6
- from mimetypes import guess_type
7
- from pathlib import PurePath
8
- from textwrap import dedent
9
- from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Mapping, TypeVar, cast
10
- from urllib.parse import quote, urlparse, urlunparse
11
-
12
- from litestar import Litestar, MediaType, Request, Response
13
- from litestar.datastructures.cookie import Cookie
14
- from litestar.exceptions import ImproperlyConfiguredException
15
- from litestar.response import Redirect
16
- from litestar.response.base import ASGIResponse
17
- from litestar.serialization import get_serializer
18
- from litestar.status_codes import HTTP_200_OK, HTTP_303_SEE_OTHER, HTTP_307_TEMPORARY_REDIRECT, HTTP_409_CONFLICT
19
- from litestar.utils.deprecation import warn_deprecation
20
- from litestar.utils.empty import value_or_default
21
- from litestar.utils.helpers import get_enum_string_value
22
- from litestar.utils.scope.state import ScopeState
23
- from markupsafe import Markup
24
-
25
- from litestar_vite.inertia._utils import get_headers
26
- from litestar_vite.inertia.types import InertiaHeaderType, PageProps
27
- from litestar_vite.plugin import VitePlugin
28
-
29
- if TYPE_CHECKING:
30
- from litestar.app import Litestar
31
- from litestar.background_tasks import BackgroundTask, BackgroundTasks
32
- from litestar.connection import ASGIConnection
33
- from litestar.connection.base import AuthT, StateT, UserT
34
- from litestar.types import ResponseCookies, ResponseHeaders, TypeEncodersMap
35
-
36
- from litestar_vite.inertia.request import InertiaRequest
37
- from litestar_vite.inertia.routes import Routes
38
-
39
- from .plugin import InertiaPlugin
40
-
41
- T = TypeVar("T")
42
-
43
-
44
- def share(
45
- connection: ASGIConnection[Any, Any, Any, Any],
46
- key: str,
47
- value: Any,
48
- ) -> None:
49
- try:
50
- connection.session.setdefault("_shared", {}).update({key: value})
51
- except (AttributeError, ImproperlyConfiguredException):
52
- msg = "Unable to set `share` session state. A valid session was not found for this request."
53
- connection.logger.warning(msg)
54
-
55
-
56
- def error(
57
- connection: ASGIConnection[Any, Any, Any, Any],
58
- key: str,
59
- message: str,
60
- ) -> None:
61
- try:
62
- connection.session.setdefault("_errors", {}).update({key: message})
63
- except (AttributeError, ImproperlyConfiguredException):
64
- msg = "Unable to set `error` session state. A valid session was not found for this request."
65
- connection.logger.warning(msg)
66
-
67
-
68
- def get_shared_props(request: ASGIConnection[Any, Any, Any, Any]) -> Dict[str, Any]: # noqa: UP006
69
- """Return shared session props for a request
70
-
71
-
72
- Be sure to call this before `self.create_template_context` if you would like to include the `flash` message details.
73
- """
74
- props: dict[str, Any] = {}
75
- flash: dict[str, list[str]] = defaultdict(list)
76
- errors: dict[str, Any] = {}
77
- error_bag = request.headers.get("X-Inertia-Error-Bag", None)
78
- try:
79
- errors = request.session.pop("_errors", {})
80
- props.update(cast("Dict[str,Any]", request.session.pop("_shared", {})))
81
- for message in cast("List[Dict[str,Any]]", request.session.pop("_messages", [])):
82
- flash[message["category"]].append(message["message"])
83
-
84
- inertia_plugin = cast("InertiaPlugin", request.app.plugins.get("InertiaPlugin"))
85
- props.update(inertia_plugin.config.extra_static_page_props)
86
- for session_prop in inertia_plugin.config.extra_session_page_props:
87
- if session_prop not in props and session_prop in request.session:
88
- props[session_prop] = request.session.get(session_prop)
89
-
90
- except (AttributeError, ImproperlyConfiguredException):
91
- msg = "Unable to generate all shared props. A valid session was not found for this request."
92
- request.logger.warning(msg)
93
- props["flash"] = flash
94
- props["errors"] = {error_bag: errors} if error_bag is not None else errors
95
- props["csrf_token"] = value_or_default(ScopeState.from_scope(request.scope).csrf_token, "")
96
- return props
97
-
98
-
99
- def js_routes_script(js_routes: Routes) -> Markup:
100
- @lru_cache
101
- def _markup_safe_json_dumps(js_routes: str) -> Markup:
102
- js = js_routes.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026").replace("'", "\\u0027")
103
- return Markup(js)
104
-
105
- return Markup(
106
- dedent(f"""
107
- <script type="module">
108
- globalThis.routes = JSON.parse('{_markup_safe_json_dumps(js_routes.formatted_routes)}')
109
- </script>
110
- """),
111
- )
112
-
113
-
114
- class InertiaResponse(Response[T]):
115
- """Inertia Response"""
116
-
117
- def __init__(
118
- self,
119
- content: T,
120
- *,
121
- template_name: str | None = None,
122
- template_str: str | None = None,
123
- background: BackgroundTask | BackgroundTasks | None = None,
124
- context: dict[str, Any] | None = None,
125
- cookies: ResponseCookies | None = None,
126
- encoding: str = "utf-8",
127
- headers: ResponseHeaders | None = None,
128
- media_type: MediaType | str | None = None,
129
- status_code: int = HTTP_200_OK,
130
- type_encoders: TypeEncodersMap | None = None,
131
- ) -> None:
132
- """Handle the rendering of a given template into a bytes string.
133
-
134
- Args:
135
- content: A value for the response body that will be rendered into bytes string.
136
- template_name: Path-like name for the template to be rendered, e.g. ``index.html``.
137
- template_str: A string representing the template, e.g. ``tmpl = "Hello <strong>World</strong>"``.
138
- background: A :class:`BackgroundTask <.background_tasks.BackgroundTask>` instance or
139
- :class:`BackgroundTasks <.background_tasks.BackgroundTasks>` to execute after the response is finished.
140
- Defaults to ``None``.
141
- context: A dictionary of key/value pairs to be passed to the temple engine's render method.
142
- cookies: A list of :class:`Cookie <.datastructures.Cookie>` instances to be set under the response
143
- ``Set-Cookie`` header.
144
- encoding: Content encoding
145
- headers: A string keyed dictionary of response headers. Header keys are insensitive.
146
- media_type: A string or member of the :class:`MediaType <.enums.MediaType>` enum. If not set, try to infer
147
- the media type based on the template name. If this fails, fall back to ``text/plain``.
148
- status_code: A value for the response HTTP status code.
149
- type_encoders: A mapping of types to callables that transform them into types supported for serialization.
150
- """
151
- if template_name and template_str:
152
- msg = "Either template_name or template_str must be provided, not both."
153
- raise ValueError(msg)
154
- self.content = content
155
- self.background = background
156
- self.cookies: list[Cookie] = (
157
- [Cookie(key=key, value=value) for key, value in cookies.items()]
158
- if isinstance(cookies, Mapping)
159
- else list(cookies or [])
160
- )
161
- self.encoding = encoding
162
- self.headers: dict[str, Any] = (
163
- dict(headers) if isinstance(headers, Mapping) else {h.name: h.value for h in headers or {}}
164
- )
165
- self.media_type = media_type
166
- self.status_code = status_code
167
- self.response_type_encoders = {**(self.type_encoders or {}), **(type_encoders or {})}
168
- self.context = context or {}
169
- self.template_name = template_name
170
- self.template_str = template_str
171
-
172
- def create_template_context(
173
- self,
174
- request: Request[UserT, AuthT, StateT],
175
- page_props: PageProps[T],
176
- type_encoders: TypeEncodersMap | None = None,
177
- ) -> dict[str, Any]:
178
- """Create a context object for the template.
179
-
180
- Args:
181
- request: A :class:`Request <.connection.Request>` instance.
182
- page_props: A formatted object to return the inertia configuration.
183
- type_encoders: A mapping of types to callables that transform them into types supported for serialization.
184
-
185
- Returns:
186
- A dictionary holding the template context
187
- """
188
- csrf_token = value_or_default(ScopeState.from_scope(request.scope).csrf_token, "")
189
- inertia_props = self.render(page_props, MediaType.JSON, get_serializer(type_encoders)).decode()
190
- return {
191
- **self.context,
192
- "inertia": inertia_props,
193
- "js_routes": js_routes_script(request.app.state.js_routes),
194
- "request": request,
195
- "csrf_input": f'<input type="hidden" name="_csrf_token" value="{csrf_token}" />',
196
- }
197
-
198
- def to_asgi_response(
199
- self,
200
- app: Litestar | None,
201
- request: Request[UserT, AuthT, StateT],
202
- *,
203
- background: BackgroundTask | BackgroundTasks | None = None,
204
- cookies: Iterable[Cookie] | None = None,
205
- encoded_headers: Iterable[tuple[bytes, bytes]] | None = None,
206
- headers: dict[str, str] | None = None,
207
- is_head_response: bool = False,
208
- media_type: MediaType | str | None = None,
209
- status_code: int | None = None,
210
- type_encoders: TypeEncodersMap | None = None,
211
- ) -> ASGIResponse:
212
- if app is not None:
213
- warn_deprecation(
214
- version="2.1",
215
- deprecated_name="app",
216
- kind="parameter",
217
- removal_in="3.0.0",
218
- alternative="request.app",
219
- )
220
- inertia_enabled = getattr(request, "inertia_enabled", False) or getattr(request, "is_inertia", False)
221
- is_inertia = getattr(request, "is_inertia", False)
222
-
223
- headers = {**headers, **self.headers} if headers is not None else self.headers
224
- cookies = self.cookies if cookies is None else itertools.chain(self.cookies, cookies)
225
- type_encoders = (
226
- {**type_encoders, **(self.response_type_encoders or {})} if type_encoders else self.response_type_encoders
227
- )
228
- if not inertia_enabled:
229
- media_type = get_enum_string_value(self.media_type or media_type or MediaType.JSON)
230
- return ASGIResponse(
231
- background=self.background or background,
232
- body=self.render(self.content, media_type, get_serializer(type_encoders)),
233
- cookies=cookies,
234
- encoded_headers=encoded_headers,
235
- encoding=self.encoding,
236
- headers=headers,
237
- is_head_response=is_head_response,
238
- media_type=media_type,
239
- status_code=self.status_code or status_code,
240
- )
241
- vite_plugin = request.app.plugins.get(VitePlugin)
242
- template_engine = vite_plugin.template_config.to_engine()
243
- headers.update(
244
- {"Vary": "Accept", **get_headers(InertiaHeaderType(enabled=True))},
245
- )
246
- shared_props = get_shared_props(request)
247
- page_props = PageProps[T](
248
- component=request.inertia.route_component, # type: ignore[attr-defined] # pyright: ignore[reportUnknownArgumentType,reportUnknownMemberType,reportAttributeAccessIssue]
249
- props={"content": self.content, **shared_props}, # pyright: ignore[reportArgumentType]
250
- version=template_engine.asset_loader.version_id,
251
- url=request.url.path,
252
- )
253
- if is_inertia:
254
- media_type = get_enum_string_value(self.media_type or media_type or MediaType.JSON)
255
- body = self.render(page_props, media_type, get_serializer(type_encoders))
256
- return ASGIResponse(
257
- background=self.background or background,
258
- body=body,
259
- cookies=cookies,
260
- encoded_headers=encoded_headers,
261
- encoding=self.encoding,
262
- headers=headers,
263
- is_head_response=is_head_response,
264
- media_type=media_type,
265
- status_code=self.status_code or status_code,
266
- )
267
-
268
- if not template_engine:
269
- msg = "Template engine is not configured"
270
- raise ImproperlyConfiguredException(msg)
271
- # it should default to HTML at this point unless the user specified something
272
- media_type = media_type or MediaType.HTML
273
- if not media_type:
274
- if self.template_name:
275
- suffixes = PurePath(self.template_name).suffixes
276
- for suffix in suffixes:
277
- if _type := guess_type(f"name{suffix}")[0]:
278
- media_type = _type
279
- break
280
- else:
281
- media_type = MediaType.TEXT
282
- else:
283
- media_type = MediaType.HTML
284
- context = self.create_template_context(request, page_props, type_encoders) # pyright: ignore[reportUnknownMemberType]
285
- if self.template_str is not None:
286
- body = template_engine.render_string(self.template_str, context).encode(self.encoding)
287
- else:
288
- inertia_plugin = cast("InertiaPlugin", request.app.plugins.get("InertiaPlugin"))
289
- template_name = self.template_name or inertia_plugin.config.root_template
290
- # cast to str b/c we know that either template_name cannot be None if template_str is None
291
- template = template_engine.get_template(template_name)
292
- body = template.render(**context).encode(self.encoding)
293
-
294
- return ASGIResponse(
295
- background=self.background or background,
296
- body=body,
297
- cookies=cookies,
298
- encoded_headers=encoded_headers,
299
- encoding=self.encoding,
300
- headers=headers,
301
- is_head_response=is_head_response,
302
- media_type=media_type,
303
- status_code=self.status_code or status_code,
304
- )
305
-
306
-
307
- class InertiaExternalRedirect(Response[Any]):
308
- """Client side redirect."""
309
-
310
- def __init__(
311
- self,
312
- request: Request[Any, Any, Any],
313
- redirect_to: str,
314
- **kwargs: Any,
315
- ) -> None:
316
- """Initialize external redirect, Set status code to 409 (required by Inertia),
317
- and pass redirect url.
318
- """
319
- super().__init__(
320
- content=b"",
321
- status_code=HTTP_409_CONFLICT,
322
- headers={"X-Inertia-Location": quote(redirect_to, safe="/#%[]=:;$&()+,!?*@'~")},
323
- cookies=request.cookies,
324
- **kwargs,
325
- )
326
-
327
-
328
- class InertiaRedirect(Redirect):
329
- """Client side redirect."""
330
-
331
- def __init__(
332
- self,
333
- request: Request[Any, Any, Any],
334
- redirect_to: str,
335
- **kwargs: Any,
336
- ) -> None:
337
- """Initialize external redirect, Set status code to 409 (required by Inertia),
338
- and pass redirect url.
339
- """
340
- referer = urlparse(request.headers.get("referer", str(request.base_url)))
341
- redirect_to = urlunparse(urlparse(redirect_to)._replace(scheme=referer.scheme))
342
- super().__init__(
343
- path=redirect_to,
344
- status_code=HTTP_307_TEMPORARY_REDIRECT if request.method == "GET" else HTTP_303_SEE_OTHER,
345
- cookies=request.cookies,
346
- **kwargs,
347
- )
348
-
349
-
350
- class InertiaBack(Redirect):
351
- """Client side redirect."""
352
-
353
- def __init__(
354
- self,
355
- request: Request[Any, Any, Any],
356
- **kwargs: Any,
357
- ) -> None:
358
- """Initialize external redirect, Set status code to 409 (required by Inertia),
359
- and pass redirect url.
360
- """
361
- referer = request.headers.get("referer", str(request.base_url))
362
- inertia_enabled = getattr(request, "inertia_enabled", False) or getattr(request, "is_inertia", False)
363
- if inertia_enabled:
364
- referer = cast("InertiaRequest[Any, Any, Any]", request).inertia.referer or referer
365
- super().__init__(
366
- path=request.headers.get("referer", str(request.base_url)),
367
- status_code=HTTP_307_TEMPORARY_REDIRECT if request.method == "GET" else HTTP_303_SEE_OTHER,
368
- cookies=request.cookies,
369
- **kwargs,
370
- )
@@ -1,54 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from dataclasses import dataclass
4
- from functools import cached_property
5
- from typing import TYPE_CHECKING
6
-
7
- from litestar.app import DEFAULT_OPENAPI_CONFIG
8
- from litestar.cli._utils import (
9
- remove_default_schema_routes,
10
- remove_routes_with_patterns,
11
- )
12
- from litestar.routes import ASGIRoute, WebSocketRoute
13
- from litestar.serialization import encode_json
14
-
15
- if TYPE_CHECKING:
16
- from litestar import Litestar
17
-
18
-
19
- @dataclass(frozen=True)
20
- class Routes:
21
- routes: dict[str, str]
22
-
23
- @cached_property
24
- def formatted_routes(self) -> str:
25
- return encode_json(self.routes).decode(encoding="utf-8")
26
-
27
-
28
- EXCLUDED_METHODS = {"HEAD", "OPTIONS", "TRACE"}
29
-
30
-
31
- def generate_js_routes(
32
- app: Litestar,
33
- exclude: tuple[str, ...] | None = None,
34
- schema: bool = False,
35
- ) -> Routes:
36
- sorted_routes = sorted(app.routes, key=lambda r: r.path)
37
- if not schema:
38
- openapi_config = app.openapi_config or DEFAULT_OPENAPI_CONFIG
39
- sorted_routes = remove_default_schema_routes(sorted_routes, openapi_config)
40
- if exclude is not None:
41
- sorted_routes = remove_routes_with_patterns(sorted_routes, exclude)
42
- route_list: dict[str, str] = {}
43
- for route in sorted_routes:
44
- if isinstance(route, (ASGIRoute, WebSocketRoute)):
45
- route_name = route.route_handler.name or route.route_handler.handler_name
46
- if len(route.methods.difference(EXCLUDED_METHODS)) > 0:
47
- route_list[route_name] = route.path
48
- else:
49
- for handler in route.route_handlers:
50
- route_name = handler.name or handler.handler_name
51
- if handler.http_methods.isdisjoint(EXCLUDED_METHODS):
52
- route_list[route_name] = route.path
53
-
54
- return Routes(routes=route_list)
@@ -1,39 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from dataclasses import dataclass
4
- from typing import Any, Generic, TypedDict, TypeVar
5
-
6
- __all__ = (
7
- "InertiaHeaderType",
8
- "PageProps",
9
- )
10
-
11
-
12
- T = TypeVar("T")
13
-
14
-
15
- @dataclass
16
- class PageProps(Generic[T]):
17
- """Inertia Page Props Type."""
18
-
19
- component: str
20
- url: str
21
- version: str
22
- props: dict[str, Any]
23
-
24
-
25
- @dataclass
26
- class InertiaProps(Generic[T]):
27
- """Inertia Props Type."""
28
-
29
- page: PageProps[T]
30
-
31
-
32
- class InertiaHeaderType(TypedDict, total=False):
33
- """Type for inertia_headers parameter in get_headers()."""
34
-
35
- enabled: bool | None
36
- version: str | None
37
- location: str | None
38
- partial_data: str | None
39
- partial_component: str | None
litestar_vite/loader.py DELETED
@@ -1,220 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import json
4
- from functools import cached_property
5
- from pathlib import Path
6
- from textwrap import dedent
7
- from typing import TYPE_CHECKING, Any, ClassVar
8
- from urllib.parse import urljoin
9
-
10
- if TYPE_CHECKING:
11
- from litestar_vite.config import ViteConfig
12
-
13
-
14
- class ViteAssetLoader:
15
- """Vite manifest loader.
16
-
17
- Please see: https://vitejs.dev/guide/backend-integration.html
18
- """
19
-
20
- _instance: ClassVar[ViteAssetLoader | None] = None
21
-
22
- def __init__(self, config: ViteConfig) -> None:
23
- self._config = config
24
- self._manifest: dict[str, Any] = {}
25
- self._manifest_content: str = ""
26
- self._vite_base_path: str | None = None
27
-
28
- @classmethod
29
- def initialize_loader(cls, config: ViteConfig) -> ViteAssetLoader:
30
- """Singleton manifest loader."""
31
- if cls._instance is None:
32
- cls._instance = cls(config=config)
33
- cls._instance.parse_manifest()
34
- return cls._instance
35
-
36
- @cached_property
37
- def version_id(self) -> str:
38
- if self._manifest_content != "":
39
- return str(hash(self.manifest_content))
40
- return "1.0"
41
-
42
- def parse_manifest(self) -> None:
43
- """Read and parse the Vite manifest file.
44
-
45
- Example manifest:
46
- ```json
47
- {
48
- "main.js": {
49
- "file": "assets/main.4889e940.js",
50
- "src": "main.js",
51
- "isEntry": true,
52
- "dynamicImports": ["views/foo.js"],
53
- "css": ["assets/main.b82dbe22.css"],
54
- "assets": ["assets/asset.0ab0f9cd.png"]
55
- },
56
- "views/foo.js": {
57
- "file": "assets/foo.869aea0d.js",
58
- "src": "views/foo.js",
59
- "isDynamicEntry": true,
60
- "imports": ["_shared.83069a53.js"]
61
- },
62
- "_shared.83069a53.js": {
63
- "file": "assets/shared.83069a53.js"
64
- }
65
- }
66
- ```
67
-
68
- Raises:
69
- RuntimeError: if cannot load the file or JSON in file is malformed.
70
- """
71
- if self._config.hot_reload and self._config.dev_mode:
72
- hot_file_path = Path(
73
- f"{self._config.bundle_dir}/{self._config.hot_file}",
74
- )
75
- if hot_file_path.exists():
76
- with hot_file_path.open() as hot_file:
77
- self._vite_base_path = hot_file.read()
78
-
79
- else:
80
- manifest_path = Path(f"{self._config.bundle_dir}/{self._config.manifest_name}")
81
- try:
82
- if manifest_path.exists():
83
- with manifest_path.open() as manifest_file:
84
- self.manifest_content = manifest_file.read()
85
- self._manifest = json.loads(self.manifest_content)
86
- else:
87
- self._manifest = {}
88
- except Exception as exc:
89
- msg = "There was an issue reading the Vite manifest file at %s. Did you forget to build your assets?"
90
- raise RuntimeError(
91
- msg,
92
- manifest_path,
93
- ) from exc
94
-
95
- def generate_ws_client_tags(self) -> str:
96
- """Generate the script tag for the Vite WS client for HMR.
97
-
98
- Only used when hot module reloading is enabled, in production this method returns an empty string.
99
-
100
- Returns:
101
- str: The script tag or an empty string.
102
- """
103
- if self._config.hot_reload and self._config.dev_mode:
104
- return self._script_tag(
105
- self._vite_server_url("@vite/client"),
106
- {"type": "module"},
107
- )
108
- return ""
109
-
110
- def generate_react_hmr_tags(self) -> str:
111
- """Generate the script tag for the Vite WS client for HMR.
112
-
113
- Only used when hot module reloading is enabled, in production this method returns an empty string.
114
-
115
- Returns:
116
- str: The script tag or an empty string.
117
- """
118
- if self._config.is_react and self._config.hot_reload and self._config.dev_mode:
119
- return dedent(f"""
120
- <script type="module">
121
- import RefreshRuntime from '{self._vite_server_url()}@react-refresh'
122
- RefreshRuntime.injectIntoGlobalHook(window)
123
- window.$RefreshReg$ = () => {{}}
124
- window.$RefreshSig$ = () => (type) => type
125
- window.__vite_plugin_react_preamble_installed__=true
126
- </script>
127
- """)
128
- return ""
129
-
130
- def generate_asset_tags(self, path: str | list[str], scripts_attrs: dict[str, str] | None = None) -> str:
131
- """Generate all assets include tags for the file in argument.
132
-
133
- Returns:
134
- str: All tags to import this asset in your HTML page.
135
- """
136
- if isinstance(path, str):
137
- path = [path]
138
- if self._config.hot_reload and self._config.dev_mode:
139
- return "".join(
140
- [
141
- self._style_tag(self._vite_server_url(p))
142
- if p.endswith(".css")
143
- else self._script_tag(
144
- self._vite_server_url(p),
145
- {"type": "module", "async": "", "defer": ""},
146
- )
147
- for p in path
148
- ],
149
- )
150
-
151
- if any(p for p in path if p not in self._manifest):
152
- msg = "Cannot find %s in Vite manifest at %s. Did you forget to build your assets after an update?"
153
- raise RuntimeError(
154
- msg,
155
- path,
156
- Path(f"{self._config.bundle_dir}/{self._config.manifest_name}"),
157
- )
158
-
159
- tags: list[str] = []
160
- manifest_entry: dict[str, Any] = {}
161
- manifest_entry.update({p: self._manifest[p] for p in path})
162
- if not scripts_attrs:
163
- scripts_attrs = {"type": "module", "async": "", "defer": ""}
164
- for manifest in manifest_entry.values():
165
- if "css" in manifest:
166
- tags.extend(
167
- self._style_tag(urljoin(self._config.asset_url, css_path)) for css_path in manifest.get("css", {})
168
- )
169
- # Add dependent "vendor"
170
- if "imports" in manifest:
171
- tags.extend(
172
- self.generate_asset_tags(vendor_path, scripts_attrs=scripts_attrs)
173
- for vendor_path in manifest.get("imports", {})
174
- )
175
- # Add the script by itself
176
- if manifest.get("file").endswith(".css"):
177
- tags.append(
178
- self._style_tag(urljoin(self._config.asset_url, manifest["file"])),
179
- )
180
- else:
181
- tags.append(
182
- self._script_tag(
183
- urljoin(self._config.asset_url, manifest["file"]),
184
- attrs=scripts_attrs,
185
- ),
186
- )
187
- return "".join(tags)
188
-
189
- def _vite_server_url(self, path: str | None = None) -> str:
190
- """Generate an URL to and asset served by the Vite development server.
191
-
192
- Keyword Arguments:
193
- path: Path to the asset. (default: {None})
194
-
195
- Returns:
196
- str: Full URL to the asset.
197
- """
198
- base_path = self._vite_base_path or f"{self._config.protocol}://{self._config.host}:{self._config.port}"
199
- return urljoin(
200
- base_path,
201
- urljoin(self._config.asset_url, path if path is not None else ""),
202
- )
203
-
204
- def _script_tag(self, src: str, attrs: dict[str, str] | None = None) -> str:
205
- """Generate an HTML script tag."""
206
- if attrs is None:
207
- attrs = {}
208
- attrs_str = " ".join([f'{key}="{value}"' for key, value in attrs.items()])
209
- return f'<script {attrs_str} src="{src}"></script>'
210
-
211
- def _style_tag(self, href: str) -> str:
212
- """Generate and HTML <link> stylesheet tag for CSS.
213
-
214
- Args:
215
- href: CSS file URL.
216
-
217
- Returns:
218
- str: CSS link tag.
219
- """
220
- return f'<link rel="stylesheet" href="{href}" />'