litestar-vite 0.9.0__py3-none-any.whl → 0.11.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.

litestar_vite/__init__.py CHANGED
@@ -1,9 +1,8 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from litestar_vite import inertia
4
- from litestar_vite.config import ViteConfig, ViteTemplateConfig
4
+ from litestar_vite.config import ViteConfig
5
5
  from litestar_vite.loader import ViteAssetLoader
6
6
  from litestar_vite.plugin import VitePlugin
7
- from litestar_vite.template_engine import ViteTemplateEngine
8
7
 
9
- __all__ = ("ViteAssetLoader", "ViteConfig", "VitePlugin", "ViteTemplateConfig", "ViteTemplateEngine", "inertia")
8
+ __all__ = ("ViteAssetLoader", "ViteConfig", "VitePlugin", "inertia")
litestar_vite/cli.py CHANGED
@@ -113,8 +113,8 @@ def vite_init(
113
113
  )
114
114
  from rich.prompt import Confirm
115
115
 
116
+ from litestar_vite import VitePlugin
116
117
  from litestar_vite.commands import execute_command, init_vite
117
- from litestar_vite.plugin import VitePlugin
118
118
 
119
119
  if callable(ctx.obj):
120
120
  ctx.obj = ctx.obj()
litestar_vite/commands.py CHANGED
@@ -14,7 +14,7 @@ DEFAULT_RESOURCES: set[str] = {"styles.css.j2", "main.ts.j2"}
14
14
  DEFAULT_DEV_DEPENDENCIES: dict[str, str] = {
15
15
  "typescript": "^5.7.2",
16
16
  "vite": "^6.0.3",
17
- "litestar-vite-plugin": "^0.9.0",
17
+ "litestar-vite-plugin": "^0.11.0",
18
18
  "@types/node": "^22.10.1",
19
19
  }
20
20
  DEFAULT_DEPENDENCIES: dict[str, str] = {"axios": "^1.7.2"}
litestar_vite/config.py CHANGED
@@ -2,21 +2,9 @@ from __future__ import annotations
2
2
 
3
3
  import os
4
4
  from dataclasses import dataclass, field
5
- from functools import cached_property
6
- from inspect import isclass
7
5
  from pathlib import Path
8
- from typing import TYPE_CHECKING, cast
9
6
 
10
- from litestar.exceptions import ImproperlyConfiguredException
11
- from litestar.template import TemplateConfig
12
- from litestar.template.config import EngineType
13
-
14
- if TYPE_CHECKING:
15
- from collections.abc import Callable
16
-
17
- from litestar.types import PathType
18
-
19
- __all__ = ("ViteConfig", "ViteTemplateConfig")
7
+ __all__ = ("ViteConfig",)
20
8
  TRUE_VALUES = {"True", "true", "1", "yes", "Y", "T"}
21
9
 
22
10
 
@@ -39,8 +27,6 @@ class ViteConfig:
39
27
 
40
28
  In a standalone Vue or React application, this would be equivalent to the ``./src`` directory.
41
29
  """
42
- template_dir: Path | str | None = field(default="templates")
43
- """Location of the Jinja2 template file."""
44
30
  public_dir: Path | str = field(default="public")
45
31
  """The optional public directory Vite serves assets from.
46
32
 
@@ -113,8 +99,6 @@ class ViteConfig:
113
99
  self.root_dir = Path(self.root_dir)
114
100
  elif self.root_dir is None:
115
101
  self.root_dir = Path()
116
- if self.template_dir is not None and isinstance(self.template_dir, str):
117
- self.template_dir = Path(self.template_dir)
118
102
  if self.public_dir and isinstance(self.public_dir, str):
119
103
  self.public_dir = Path(self.public_dir)
120
104
  if isinstance(self.resource_dir, str):
@@ -123,53 +107,3 @@ class ViteConfig:
123
107
  self.bundle_dir = Path(self.bundle_dir)
124
108
  if isinstance(self.ssr_output_dir, str):
125
109
  self.ssr_output_dir = Path(self.ssr_output_dir)
126
-
127
-
128
- @dataclass
129
- class ViteTemplateConfig(TemplateConfig[EngineType]):
130
- """Configuration for Templating.
131
-
132
- To enable templating, pass an instance of this class to the
133
- :class:`Litestar <litestar.app.Litestar>` constructor using the
134
- 'template_config' key.
135
- """
136
-
137
- config: ViteConfig = field(default_factory=lambda: ViteConfig())
138
- """A a config for the vite engine`."""
139
- engine: type[EngineType] | EngineType | None = field(default=None)
140
- """A template engine adhering to the :class:`TemplateEngineProtocol <litestar.template.TemplateEngineProtocol>`."""
141
- directory: PathType | list[PathType] | None = field(default=None)
142
- """A directory or list of directories from which to serve templates."""
143
- engine_callback: Callable[[EngineType], None] | None = field(default=None)
144
- """A callback function that allows modifying the instantiated templating
145
- protocol."""
146
-
147
- instance: EngineType | None = field(default=None)
148
- """An instance of the templating protocol."""
149
-
150
- def __post_init__(self) -> None:
151
- """Ensure that directory is set if engine is a class."""
152
- if isclass(self.engine) and not self.directory: # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
153
- msg = "directory is a required kwarg when passing a template engine class"
154
- raise ImproperlyConfiguredException(msg)
155
- """Ensure that directory is not set if instance is."""
156
- if self.instance is not None and self.directory is not None: # pyright: ignore[reportUnknownMemberType]
157
- msg = "directory cannot be set if instance is"
158
- raise ImproperlyConfiguredException(msg)
159
-
160
- def to_engine(self) -> EngineType:
161
- """Instantiate the template engine."""
162
- template_engine = cast(
163
- "EngineType",
164
- self.engine(directory=self.directory, config=self.config, engine_instance=None) # pyright: ignore[reportUnknownMemberType,reportCallIssue]
165
- if isclass(self.engine) # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
166
- else self.engine, # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
167
- )
168
- if callable(self.engine_callback):
169
- self.engine_callback(template_engine) # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
170
- return template_engine
171
-
172
- @cached_property
173
- def engine_instance(self) -> EngineType:
174
- """Return the template engine instance."""
175
- return self.to_engine() if self.instance is None else self.instance
@@ -26,8 +26,7 @@ async def redirect_on_asset_version_mismatch(request: Request[UserT, AuthT, Stat
26
26
  return None
27
27
 
28
28
  vite_plugin = request.app.plugins.get(VitePlugin)
29
- template_engine = vite_plugin.template_config.to_engine()
30
- if inertia_version == template_engine.asset_loader.version_id:
29
+ if inertia_version == vite_plugin.asset_loader.version_id:
31
30
  return None
32
31
  return InertiaRedirect(request, redirect_to=str(request.url))
33
32
 
@@ -245,7 +245,7 @@ class InertiaResponse(Response[T]):
245
245
  is_partial_render = cast("bool", getattr(request, "is_partial_render", False))
246
246
  partial_keys = cast("set[str]", getattr(request, "partial_keys", {}))
247
247
  vite_plugin = request.app.plugins.get(VitePlugin)
248
- template_engine = vite_plugin.template_config.to_engine()
248
+ template_engine = request.app.template_engine # pyright: ignore[reportUnknownVariableType,reportUnknownMemberType]
249
249
  headers.update(
250
250
  {"Vary": "Accept", **get_headers(InertiaHeaderType(enabled=True))},
251
251
  )
@@ -254,13 +254,13 @@ class InertiaResponse(Response[T]):
254
254
  page_props = PageProps[T](
255
255
  component=request.inertia.route_component, # type: ignore[attr-defined] # pyright: ignore[reportUnknownArgumentType,reportUnknownMemberType,reportAttributeAccessIssue]
256
256
  props=shared_props, # pyright: ignore[reportArgumentType]
257
- version=template_engine.asset_loader.version_id,
257
+ version=vite_plugin.asset_loader.version_id,
258
258
  url=request.url.path,
259
259
  )
260
260
  if is_inertia:
261
261
  media_type = get_enum_string_value(self.media_type or media_type or MediaType.JSON)
262
262
  body = self.render(page_props, media_type, get_serializer(type_encoders))
263
- return ASGIResponse(
263
+ return ASGIResponse( # pyright: ignore[reportUnknownMemberType]
264
264
  background=self.background or background,
265
265
  body=body,
266
266
  cookies=cookies,
@@ -290,17 +290,16 @@ class InertiaResponse(Response[T]):
290
290
  media_type = MediaType.HTML
291
291
  context = self.create_template_context(request, page_props, type_encoders) # pyright: ignore[reportUnknownMemberType]
292
292
  if self.template_str is not None:
293
- body = template_engine.render_string(self.template_str, context).encode(self.encoding)
293
+ body = template_engine.render_string(self.template_str, context).encode(self.encoding) # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
294
294
  else:
295
295
  inertia_plugin = cast("InertiaPlugin", request.app.plugins.get("InertiaPlugin"))
296
296
  template_name = self.template_name or inertia_plugin.config.root_template
297
- # cast to str b/c we know that either template_name cannot be None if template_str is None
298
- template = template_engine.get_template(template_name)
299
- body = template.render(**context).encode(self.encoding)
297
+ template = template_engine.get_template(template_name) # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType]
298
+ body = template.render(**context).encode(self.encoding) # pyright: ignore[reportUnknownVariableType,reportUnknownMemberType]
300
299
 
301
- return ASGIResponse(
300
+ return ASGIResponse( # pyright: ignore[reportUnknownMemberType]
302
301
  background=self.background or background,
303
- body=body,
302
+ body=body, # pyright: ignore[reportUnknownArgumentType]
304
303
  cookies=cookies,
305
304
  encoded_headers=encoded_headers,
306
305
  encoding=self.encoding,
litestar_vite/loader.py CHANGED
@@ -4,11 +4,61 @@ import json
4
4
  from functools import cached_property
5
5
  from pathlib import Path
6
6
  from textwrap import dedent
7
- from typing import TYPE_CHECKING, Any, ClassVar
7
+ from typing import TYPE_CHECKING, Any, ClassVar, Mapping, cast
8
8
  from urllib.parse import urljoin
9
9
 
10
+ import markupsafe
11
+ from litestar.exceptions import ImproperlyConfiguredException
12
+
10
13
  if TYPE_CHECKING:
14
+ from litestar.connection import Request
15
+
11
16
  from litestar_vite.config import ViteConfig
17
+ from litestar_vite.plugin import VitePlugin
18
+
19
+
20
+ def _get_request_from_context(context: Mapping[str, Any]) -> Request[Any, Any, Any]:
21
+ """Get the request from the template context.
22
+
23
+ Args:
24
+ context: The template context.
25
+
26
+ Returns:
27
+ The request object.
28
+ """
29
+ return cast("Request[Any, Any, Any]", context["request"])
30
+
31
+
32
+ def render_hmr_client(context: Mapping[str, Any], /) -> markupsafe.Markup:
33
+ """Render the HMR client.
34
+
35
+ Args:
36
+ context: The template context.
37
+
38
+ Returns:
39
+ The HMR client.
40
+ """
41
+ return cast(
42
+ "VitePlugin", _get_request_from_context(context).app.plugins.get("VitePlugin")
43
+ ).asset_loader.render_hmr_client()
44
+
45
+
46
+ def render_asset_tag(
47
+ context: Mapping[str, Any], /, path: str | list[str], scripts_attrs: dict[str, str] | None = None
48
+ ) -> markupsafe.Markup:
49
+ """Render an asset tag.
50
+
51
+ Args:
52
+ context: The template context.
53
+ path: The path to the asset.
54
+ scripts_attrs: The attributes for the script tag.
55
+
56
+ Returns:
57
+ The asset tag.
58
+ """
59
+ return cast(
60
+ "VitePlugin", _get_request_from_context(context).app.plugins.get("VitePlugin")
61
+ ).asset_loader.render_asset_tag(path, scripts_attrs)
12
62
 
13
63
 
14
64
  class ViteAssetLoader:
@@ -39,6 +89,19 @@ class ViteAssetLoader:
39
89
  return str(hash(self.manifest_content))
40
90
  return "1.0"
41
91
 
92
+ def render_hmr_client(self) -> markupsafe.Markup:
93
+ """Generate the script tag for the Vite WS client for HMR."""
94
+ return markupsafe.Markup(
95
+ f"{self.generate_react_hmr_tags()}{self.generate_ws_client_tags()}",
96
+ )
97
+
98
+ def render_asset_tag(self, path: str | list[str], scripts_attrs: dict[str, str] | None = None) -> markupsafe.Markup:
99
+ """Generate all assets include tags for the file in argument."""
100
+ path = [str(p) for p in path] if isinstance(path, list) else [str(path)]
101
+ return markupsafe.Markup(
102
+ "".join([self.generate_asset_tags(p, scripts_attrs=scripts_attrs) for p in path]),
103
+ )
104
+
42
105
  def parse_manifest(self) -> None:
43
106
  """Parse the Vite manifest file.
44
107
 
@@ -151,7 +214,7 @@ class ViteAssetLoader:
151
214
 
152
215
  if any(p for p in path if p not in self._manifest):
153
216
  msg = "Cannot find %s in Vite manifest at %s. Did you forget to build your assets after an update?"
154
- raise RuntimeError(
217
+ raise ImproperlyConfiguredException(
155
218
  msg,
156
219
  path,
157
220
  Path(f"{self._config.bundle_dir}/{self._config.manifest_name}"),
@@ -159,7 +222,7 @@ class ViteAssetLoader:
159
222
 
160
223
  tags: list[str] = []
161
224
  manifest_entry: dict[str, Any] = {}
162
- manifest_entry.update({p: self._manifest[p] for p in path})
225
+ manifest_entry.update({p: self._manifest[p] for p in path if p})
163
226
  if not scripts_attrs:
164
227
  scripts_attrs = {"type": "module", "async": "", "defer": ""}
165
228
  for manifest in manifest_entry.values():
litestar_vite/plugin.py CHANGED
@@ -1,24 +1,24 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import os
4
+ import signal
5
+ import threading
4
6
  from contextlib import contextmanager
5
7
  from pathlib import Path
6
8
  from typing import TYPE_CHECKING, Iterator, cast
7
9
 
10
+ from litestar.contrib.jinja import JinjaTemplateEngine
11
+ from litestar.exceptions import ImproperlyConfiguredException
8
12
  from litestar.plugins import CLIPlugin, InitPluginProtocol
9
- from litestar.static_files import (
10
- create_static_files_router, # pyright: ignore[reportUnknownVariableType]
11
- )
12
-
13
- from litestar_vite.config import ViteConfig
13
+ from litestar.static_files import create_static_files_router # pyright: ignore[reportUnknownVariableType]
14
14
 
15
15
  if TYPE_CHECKING:
16
16
  from click import Group
17
17
  from litestar import Litestar
18
18
  from litestar.config.app import AppConfig
19
19
 
20
- from litestar_vite.config import ViteTemplateConfig
21
- from litestar_vite.template_engine import ViteTemplateEngine
20
+ from litestar_vite.config import ViteConfig
21
+ from litestar_vite.loader import ViteAssetLoader
22
22
 
23
23
 
24
24
  def set_environment(config: ViteConfig) -> None:
@@ -28,40 +28,96 @@ def set_environment(config: ViteConfig) -> None:
28
28
  os.environ.setdefault("VITE_PORT", str(config.port))
29
29
  os.environ.setdefault("VITE_HOST", config.host)
30
30
  os.environ.setdefault("VITE_PROTOCOL", config.protocol)
31
- os.environ.setdefault("APP_URL", f"http://localhost:{os.environ.get('LITESTAR_PORT',8000)}")
31
+ os.environ.setdefault("APP_URL", f"http://localhost:{os.environ.get('LITESTAR_PORT', 8000)}")
32
32
  if config.dev_mode:
33
33
  os.environ.setdefault("VITE_DEV_MODE", str(config.dev_mode))
34
34
 
35
35
 
36
+ class ViteProcess:
37
+ """Manages the Vite process."""
38
+
39
+ def __init__(self) -> None:
40
+ self.process: threading.Thread | None = None
41
+ self._lock = threading.Lock()
42
+
43
+ def start(self, command: list[str], cwd: Path | str | None) -> None:
44
+ """Start the Vite process."""
45
+ from litestar.cli._utils import console
46
+
47
+ from litestar_vite.commands import execute_command
48
+
49
+ try:
50
+ with self._lock:
51
+ if self.process and self.process.is_alive():
52
+ return
53
+
54
+ self.process = threading.Thread(
55
+ name="vite",
56
+ target=execute_command,
57
+ args=[],
58
+ kwargs={"command_to_run": command, "cwd": cwd},
59
+ daemon=True, # Make thread daemon so it exits when main thread exits
60
+ )
61
+ console.print(f"Starting Vite process with command: {command}")
62
+ self.process.start()
63
+ except Exception as e:
64
+ console.print(f"[red]Failed to start Vite process: {e!s}[/]")
65
+ raise
66
+
67
+ def stop(self, timeout: float = 5.0) -> None:
68
+ """Stop the Vite process."""
69
+ from litestar.cli._utils import console
70
+
71
+ try:
72
+ with self._lock:
73
+ if self.process and self.process.is_alive():
74
+ # Send SIGTERM to child process
75
+ if hasattr(signal, "SIGTERM") and self.process.ident is not None:
76
+ os.kill(self.process.ident, signal.SIGTERM)
77
+ self.process.join(timeout=timeout)
78
+
79
+ # Force kill if still alive
80
+ if self.process.is_alive():
81
+ if hasattr(signal, "SIGKILL") and self.process.ident is not None:
82
+ os.kill(self.process.ident, signal.SIGKILL)
83
+ self.process.join(timeout=1.0)
84
+ console.print("Stopping Vite process")
85
+ except Exception as e:
86
+ console.print(f"[red]Failed to stop Vite process: {e!s}[/]")
87
+ raise
88
+
89
+
36
90
  class VitePlugin(InitPluginProtocol, CLIPlugin):
37
91
  """Vite plugin."""
38
92
 
39
- __slots__ = ("_config",)
93
+ __slots__ = ("_asset_loader", "_config", "_vite_process")
40
94
 
41
- def __init__(self, config: ViteConfig | None = None) -> None:
95
+ def __init__(self, config: ViteConfig | None = None, asset_loader: ViteAssetLoader | None = None) -> None:
42
96
  """Initialize ``Vite``.
43
97
 
44
98
  Args:
45
99
  config: configuration to use for starting Vite. The default configuration will be used if it is not provided.
100
+ asset_loader: an initialized asset loader to use for rendering asset tags.
46
101
  """
102
+ from litestar_vite.config import ViteConfig
103
+
47
104
  if config is None:
48
105
  config = ViteConfig()
49
106
  self._config = config
107
+ self._asset_loader = asset_loader
108
+ self._vite_process = ViteProcess()
50
109
 
51
110
  @property
52
111
  def config(self) -> ViteConfig:
53
112
  return self._config
54
113
 
55
114
  @property
56
- def template_config(self) -> ViteTemplateConfig[ViteTemplateEngine]:
57
- from litestar_vite.config import ViteTemplateConfig
58
- from litestar_vite.template_engine import ViteTemplateEngine
59
-
60
- return ViteTemplateConfig[ViteTemplateEngine](
61
- engine=ViteTemplateEngine,
62
- config=self._config,
63
- directory=self._config.template_dir,
64
- )
115
+ def asset_loader(self) -> ViteAssetLoader:
116
+ from litestar_vite.loader import ViteAssetLoader
117
+
118
+ if self._asset_loader is None:
119
+ self._asset_loader = ViteAssetLoader.initialize_loader(config=self._config)
120
+ return self._asset_loader
65
121
 
66
122
  def on_cli_init(self, cli: Group) -> None:
67
123
  from litestar_vite.cli import vite_group
@@ -72,12 +128,24 @@ class VitePlugin(InitPluginProtocol, CLIPlugin):
72
128
  """Configure application for use with Vite.
73
129
 
74
130
  Args:
75
- app_config: The :class:`AppConfig <.config.app.AppConfig>` instance.
131
+ app_config: The :class:`AppConfig <litestar.config.app.AppConfig>` instance.
76
132
  """
77
-
78
- if self._config.template_dir is not None:
79
- app_config.template_config = self.template_config
80
-
133
+ from litestar_vite.loader import render_asset_tag, render_hmr_client
134
+
135
+ if app_config.template_config is None: # pyright: ignore[reportUnknownMemberType]
136
+ msg = "A template configuration is required for Vite."
137
+ raise ImproperlyConfiguredException(msg)
138
+ if not isinstance(app_config.template_config.engine_instance, JinjaTemplateEngine): # pyright: ignore[reportUnknownMemberType]
139
+ msg = "Jinja2 template engine is required for Vite."
140
+ raise ImproperlyConfiguredException(msg)
141
+ app_config.template_config.engine_instance.register_template_callable( # pyright: ignore[reportUnknownMemberType]
142
+ key="vite_hmr",
143
+ template_callable=render_hmr_client,
144
+ )
145
+ app_config.template_config.engine_instance.register_template_callable( # pyright: ignore[reportUnknownMemberType]
146
+ key="vite",
147
+ template_callable=render_asset_tag,
148
+ )
81
149
  if self._config.set_static_folders:
82
150
  static_dirs = [Path(self._config.bundle_dir), Path(self._config.resource_dir)]
83
151
  if Path(self._config.public_dir).exists() and self._config.public_dir != self._config.bundle_dir:
@@ -99,34 +167,26 @@ class VitePlugin(InitPluginProtocol, CLIPlugin):
99
167
 
100
168
  @contextmanager
101
169
  def server_lifespan(self, app: Litestar) -> Iterator[None]:
102
- import threading
103
-
170
+ """Manage Vite server process lifecycle."""
104
171
  from litestar.cli._utils import console
105
172
 
106
- from litestar_vite.commands import execute_command
107
-
108
173
  if self._config.use_server_lifespan and self._config.dev_mode:
109
174
  command_to_run = self._config.run_command if self._config.hot_reload else self._config.build_watch_command
175
+
110
176
  if self.config.hot_reload:
111
177
  console.rule("[yellow]Starting Vite process with HMR Enabled[/]", align="left")
112
178
  else:
113
179
  console.rule("[yellow]Starting Vite watch and build process[/]", align="left")
180
+
114
181
  if self._config.set_environment:
115
182
  set_environment(config=self._config)
116
- vite_thread = threading.Thread(
117
- name="vite",
118
- target=execute_command,
119
- args=[],
120
- kwargs={"command_to_run": command_to_run, "cwd": self._config.root_dir},
121
- )
183
+
122
184
  try:
123
- vite_thread.start()
185
+ self._vite_process.start(command_to_run, self._config.root_dir)
124
186
  yield
125
187
  finally:
126
- if vite_thread.is_alive():
127
- vite_thread.join(timeout=5)
188
+ self._vite_process.stop()
128
189
  console.print("[yellow]Vite process stopped.[/]")
129
-
130
190
  else:
131
191
  manifest_path = Path(f"{self._config.bundle_dir}/{self._config.manifest_name}")
132
192
  if manifest_path.exists():
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: litestar-vite
3
- Version: 0.9.0
3
+ Version: 0.11.0
4
4
  Summary: Vite plugin for Litestar
5
5
  Project-URL: Changelog, https://cofin.github.io/litestar-vite/latest/changelog
6
6
  Project-URL: Discord, https://discord.gg/X3FJqy8d2j
@@ -53,6 +53,8 @@ from pathlib import Path
53
53
  from litestar import Controller, get, Litestar
54
54
  from litestar.response import Template
55
55
  from litestar.status_codes import HTTP_200_OK
56
+ from litestar.template.config import TemplateConfig
57
+ from litestar.contrib.jinja import JinjaTemplateEngine
56
58
  from litestar_vite import ViteConfig, VitePlugin
57
59
 
58
60
  class WebController(Controller):
@@ -64,9 +66,9 @@ class WebController(Controller):
64
66
  async def index(self) -> Template:
65
67
  return Template(template_name="index.html.j2")
66
68
 
67
-
68
- vite = VitePlugin(config=ViteConfig(template_dir='templates/'))
69
- app = Litestar(plugins=[vite], route_handlers=[WebController])
69
+ template_config = TemplateConfig(engine=JinjaTemplateEngine(directory='templates/'))
70
+ vite = VitePlugin(config=ViteConfig())
71
+ app = Litestar(plugins=[vite], template_config=template_config, route_handlers=[WebController])
70
72
 
71
73
  ```
72
74
 
@@ -1,20 +1,19 @@
1
- litestar_vite/__init__.py,sha256=S2zgWHas3O16FhXukd1j3tGCMP9skj7Rp-BvMQA7sd8,402
1
+ litestar_vite/__init__.py,sha256=OioNGhH88mdivQlFz9JlbJV8R6wyjSYE3c8C-RIM4Ls,277
2
2
  litestar_vite/__metadata__.py,sha256=_Wo-vNQuj5co9J4FwJAB2rRafbFo8ztTHrXmEPrYrV8,514
3
- litestar_vite/cli.py,sha256=iRJlHa72ch9IPtu88BsalrqzDGXI3F78b2ug8JT5UWA,10756
4
- litestar_vite/commands.py,sha256=pszP0xdLL8fRDb8PQuilfpqLa2jpqprfZ0XDHTqxg7U,5227
5
- litestar_vite/config.py,sha256=IA5MU6TOxXPYrCehGoBK_dFniu2PrYvOGwQPV7XkX5I,7756
6
- litestar_vite/loader.py,sha256=gK0RlenM-enNV_pS-jEwW9hanAmq053m2P75rfQuGCg,8227
7
- litestar_vite/plugin.py,sha256=p4VPKYdWw5qIYZ1OwfdMRcwM_Q-vfoDEmIbu3IyF7oI,5166
3
+ litestar_vite/cli.py,sha256=CBSRohDLU9cDeKMAfSbFiw1x8OE_b15ZlUaxji9Rdw8,10749
4
+ litestar_vite/commands.py,sha256=aGpSmrRfArSg4hkpL6GTuKZPRyZm1y-qhon0P5mUoEQ,5228
5
+ litestar_vite/config.py,sha256=cZWIwTwNnBYScCty8OxxPaOL8cELx57dm7JQeV8og3Y,4565
6
+ litestar_vite/loader.py,sha256=nrXL2txXoBZEsdLZnysgBYZSreMXQ7ckLuNcu7MqnSM,10277
7
+ litestar_vite/plugin.py,sha256=XZ1RxyRS9aX3coJis02Uv2AMB2frI2eqKSlK_zZWwSY,8091
8
8
  litestar_vite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
- litestar_vite/template_engine.py,sha256=lFFJsD-sgf3LIaFDoD1NysRUg49WV-ELE53SHiBDeeA,3837
10
9
  litestar_vite/inertia/__init__.py,sha256=Fab61KXbBnyub2Nx-2AHYv2U6QiYUIrqhEZia_f9xik,863
11
10
  litestar_vite/inertia/_utils.py,sha256=ijO9Lgka7ZPIAHkby9szbTGoSg0nDShC2bqWT9cDxi0,1956
12
11
  litestar_vite/inertia/config.py,sha256=0Je9SLg0acv0eRvudk3aJLj5k1DjPxULoVOwAfpjnUc,1232
13
12
  litestar_vite/inertia/exception_handler.py,sha256=0FiW8jVib0xT453BzMPOeJa7bRwnxkOUdJ91kiFHPIo,5308
14
- litestar_vite/inertia/middleware.py,sha256=NEDcAoT7GMWA9hEGvANZ3MG5_p3MmZX57RF95T71les,1716
13
+ litestar_vite/inertia/middleware.py,sha256=23HfQ8D2wNGXUXt_isuGfZ8AFKrr1d_498qGFLynocs,1650
15
14
  litestar_vite/inertia/plugin.py,sha256=OgXmmvjl7KWlt4KEkYhS3mU2EY4iYN9JtJ20S3Qlht8,2349
16
15
  litestar_vite/inertia/request.py,sha256=Ogt_ikauWrsgKafaip7IL1YhbybwjdBAQ0PQS7cImoQ,3848
17
- litestar_vite/inertia/response.py,sha256=Au7jQnqjY3wJAHNmiwteCZxKTKGCpnkjMTSzBVRwkXs,15927
16
+ litestar_vite/inertia/response.py,sha256=drOn8wdxEhoffPJLBpLGqEX1UJVgSOL-qbsTR3bJG2M,16222
18
17
  litestar_vite/inertia/routes.py,sha256=QksJm2RUfL-WbuhOieYnPXXWO5GYnPtmsYEm6Ef8Yeo,1782
19
18
  litestar_vite/inertia/types.py,sha256=tLp0pm1N__hcWC875khf6wH1nuFlKS9-VjDqgsRkXnw,702
20
19
  litestar_vite/templates/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -24,7 +23,7 @@ litestar_vite/templates/package.json.j2,sha256=0JWgdTuaSZ25EmCltF_zbqDdpxfvCLeYu
24
23
  litestar_vite/templates/styles.css.j2,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
25
24
  litestar_vite/templates/tsconfig.json.j2,sha256=q1REIuVyXUHCy4Zi2kgTkmrhdT98vyY89k-WTrImOj8,843
26
25
  litestar_vite/templates/vite.config.ts.j2,sha256=bF5kOPFafYMkhhV0VkIwetN-_zoVMGVM1jEMX_wKoNc,1037
27
- litestar_vite-0.9.0.dist-info/METADATA,sha256=VY0pL6yNgte4PGdsQ_Lm4LNtCkop7ILu5TarD-BjcyY,6022
28
- litestar_vite-0.9.0.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
29
- litestar_vite-0.9.0.dist-info/licenses/LICENSE,sha256=HeTiEfEgvroUXZe_xAmYHxtTBgw--mbXyZLsWDYabHc,1069
30
- litestar_vite-0.9.0.dist-info/RECORD,,
26
+ litestar_vite-0.11.0.dist-info/METADATA,sha256=vwSng0cRQYYu4oWOP7a0auIl2p7kLiaxUCOS3TT5fAA,6222
27
+ litestar_vite-0.11.0.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
28
+ litestar_vite-0.11.0.dist-info/licenses/LICENSE,sha256=HeTiEfEgvroUXZe_xAmYHxtTBgw--mbXyZLsWDYabHc,1069
29
+ litestar_vite-0.11.0.dist-info/RECORD,,
@@ -1,103 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from typing import TYPE_CHECKING, Any, Mapping, TypeVar
4
-
5
- import markupsafe
6
- from litestar.contrib.jinja import JinjaTemplateEngine
7
- from litestar.template.base import TemplateEngineProtocol
8
-
9
- from litestar_vite.loader import ViteAssetLoader
10
-
11
- if TYPE_CHECKING:
12
- from pathlib import Path
13
-
14
- from jinja2 import Environment
15
- from jinja2 import Template as JinjaTemplate
16
-
17
- from litestar_vite.config import ViteConfig
18
-
19
- T = TypeVar("T", bound=TemplateEngineProtocol["JinjaTemplate", Mapping[str, Any]])
20
-
21
-
22
- class ViteTemplateEngine(JinjaTemplateEngine):
23
- """Jinja Template Engine with Vite Integration.
24
-
25
- This class extends :class:`litestar.contrib.jinja.JinjaTemplateEngine` to provide Vite asset integration
26
- and hot module reloading support.
27
-
28
- Raises:
29
- TemplateNotFoundException: If template is not found.
30
- """
31
-
32
- def __init__(
33
- self,
34
- directory: Path | list[Path] | None = None,
35
- engine_instance: Environment | None = None,
36
- config: ViteConfig | None = None,
37
- ) -> None:
38
- """Jinja2 based TemplateEngine.
39
-
40
- Args:
41
- directory: Direct path or list of directory paths from which to serve templates.
42
- engine_instance: A jinja Environment instance.
43
- config: Vite config
44
- """
45
- super().__init__(directory=directory, engine_instance=engine_instance)
46
- if config is None:
47
- msg = "Please configure the `ViteConfig` instance."
48
- raise ValueError(msg)
49
- self.config = config
50
- self.asset_loader = ViteAssetLoader.initialize_loader(config=self.config)
51
- self.engine.globals.update({"vite_hmr": self.get_hmr_client, "vite": self.get_asset_tag}) # pyright: ignore[reportCallIssue,reportUnknownMemberType,reportArgumentType]
52
-
53
- def get_hmr_client(self) -> markupsafe.Markup:
54
- """Generate the script tag for the Vite WS client for HMR.
55
-
56
- Only used when hot module reloading is enabled, in production this method returns an empty string.
57
-
58
- Returns:
59
- markupsafe.Markup: The script tag or an empty string.
60
- """
61
- return markupsafe.Markup(
62
- f"{self.asset_loader.generate_react_hmr_tags()}{self.asset_loader.generate_ws_client_tags()}",
63
- )
64
-
65
- def get_asset_tag(
66
- self,
67
- path: str | list[str],
68
- scripts_attrs: dict[str, str] | None = None,
69
- **_: Any,
70
- ) -> markupsafe.Markup:
71
- """Generate all assets include tags for the file in argument.
72
-
73
- Generates all scripts tags for this file and all its dependencies
74
- (JS and CSS) by reading the manifest file (for production only).
75
- In development Vite imports all dependencies by itself.
76
- Place this tag in <head> section of your page.
77
-
78
- Args:
79
- path: Path to a Vite asset to include.
80
- scripts_attrs: Dictionary of attributes to add to script tags.
81
- **_: Additional keyword arguments (ignored).
82
-
83
- Returns:
84
- markupsafe.Markup: HTML markup containing all required asset tags.
85
- """
86
- if isinstance(path, str):
87
- path = [path]
88
- return markupsafe.Markup(
89
- "".join([self.asset_loader.generate_asset_tags(p, scripts_attrs=scripts_attrs) for p in path]),
90
- )
91
-
92
- @classmethod
93
- def from_environment(cls, config: ViteConfig, jinja_environment: Environment) -> ViteTemplateEngine: # type: ignore[override]
94
- """Create a JinjaTemplateEngine from an existing jinja Environment instance.
95
-
96
- Args:
97
- config: Vite config
98
- jinja_environment (jinja2.environment.Environment): A jinja Environment instance.
99
-
100
- Returns:
101
- JinjaTemplateEngine instance
102
- """
103
- return cls(directory=None, config=config, engine_instance=jinja_environment)