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

@@ -0,0 +1,9 @@
1
+ from __future__ import annotations
2
+
3
+ from litestar_vite import inertia
4
+ from litestar_vite.config import ViteConfig, ViteTemplateConfig
5
+ from litestar_vite.loader import ViteAssetLoader
6
+ from litestar_vite.plugin import VitePlugin
7
+ from litestar_vite.template_engine import ViteTemplateEngine
8
+
9
+ __all__ = ("ViteAssetLoader", "ViteConfig", "VitePlugin", "ViteTemplateConfig", "ViteTemplateEngine", "inertia")
@@ -0,0 +1,18 @@
1
+ """Metadata for the Project."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, metadata, version
6
+
7
+ __all__ = ("__project__", "__version__")
8
+
9
+ try:
10
+ __version__ = version("litestar_vite")
11
+ """Version of the project."""
12
+ __project__ = metadata("litestar_vite")["Name"]
13
+ """Name of the project."""
14
+ except PackageNotFoundError: # pragma: no cover
15
+ __version__ = "0.0.0"
16
+ __project__ = "Litestar Vite"
17
+ finally:
18
+ del version, PackageNotFoundError, metadata
litestar_vite/cli.py ADDED
@@ -0,0 +1,324 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import TYPE_CHECKING
5
+
6
+ from click import Context, group, option
7
+ from click import Path as ClickPath
8
+ from litestar.cli._utils import (
9
+ LitestarEnv,
10
+ LitestarGroup,
11
+ )
12
+
13
+ if TYPE_CHECKING:
14
+ from litestar import Litestar
15
+
16
+
17
+ @group(cls=LitestarGroup, name="assets")
18
+ def vite_group() -> None:
19
+ """Manage Vite Tasks."""
20
+
21
+
22
+ @vite_group.command(
23
+ name="init",
24
+ help="Initialize vite for your project.",
25
+ )
26
+ @option(
27
+ "--root-path",
28
+ type=ClickPath(dir_okay=True, file_okay=False, path_type=Path),
29
+ help="The path for the initial the Vite application. This is the equivalent to the top-level folder in a normal Vue or React application..",
30
+ default=None,
31
+ required=False,
32
+ )
33
+ @option(
34
+ "--bundle-path",
35
+ type=ClickPath(dir_okay=True, file_okay=False, path_type=Path),
36
+ help="The path for the built Vite assets. This is the where the output of `npm run build` will write files.",
37
+ default=None,
38
+ required=False,
39
+ )
40
+ @option(
41
+ "--resource-path",
42
+ type=ClickPath(dir_okay=True, file_okay=False, path_type=Path),
43
+ help="The path to your Javascript/Typescript source and associated assets. If this were a standalone Vue or React app, this would point to your `src/` folder.",
44
+ default=None,
45
+ required=False,
46
+ )
47
+ @option(
48
+ "--public-path",
49
+ type=ClickPath(dir_okay=True, file_okay=False, path_type=Path),
50
+ help="The optional path to your public/static JS assets. If this were a standalone Vue or React app, this would point to your `public/` folder.",
51
+ default=None,
52
+ required=False,
53
+ )
54
+ @option("--asset-url", type=str, help="Base url to serve assets from.", default=None, required=False)
55
+ @option(
56
+ "--vite-port",
57
+ type=int,
58
+ help="The port to run the vite server against.",
59
+ default=None,
60
+ is_flag=True,
61
+ required=False,
62
+ )
63
+ @option(
64
+ "--enable-ssr",
65
+ type=bool,
66
+ help="Enable SSR Support.",
67
+ required=False,
68
+ show_default=False,
69
+ is_flag=True,
70
+ )
71
+ @option("--overwrite", type=bool, help="Overwrite any files in place.", default=False, is_flag=True)
72
+ @option("--verbose", type=bool, help="Enable verbose output.", default=False, is_flag=True)
73
+ @option(
74
+ "--no-prompt",
75
+ help="Do not prompt for confirmation and use all defaults for initializing the project.",
76
+ type=bool,
77
+ default=False,
78
+ required=False,
79
+ show_default=True,
80
+ is_flag=True,
81
+ )
82
+ @option(
83
+ "--no-install",
84
+ help="Do not execute the installation commands after generating templates.",
85
+ type=bool,
86
+ default=False,
87
+ required=False,
88
+ show_default=True,
89
+ is_flag=True,
90
+ )
91
+ def vite_init(
92
+ ctx: Context,
93
+ vite_port: int | None,
94
+ enable_ssr: bool | None,
95
+ asset_url: str | None,
96
+ root_path: Path | None,
97
+ bundle_path: Path | None,
98
+ resource_path: Path | None,
99
+ public_path: Path | None,
100
+ overwrite: bool,
101
+ verbose: bool,
102
+ no_prompt: bool,
103
+ no_install: bool,
104
+ ) -> None: # sourcery skip: low-code-quality
105
+ """Run vite build."""
106
+ import os
107
+ import sys
108
+ from importlib.util import find_spec
109
+ from pathlib import Path
110
+
111
+ from litestar.cli._utils import (
112
+ console,
113
+ )
114
+ from rich.prompt import Confirm
115
+
116
+ from litestar_vite.commands import execute_command, init_vite
117
+ from litestar_vite.plugin import VitePlugin
118
+
119
+ if callable(ctx.obj):
120
+ ctx.obj = ctx.obj()
121
+ elif verbose:
122
+ ctx.obj.app.debug = True
123
+ env: LitestarEnv = ctx.obj
124
+ plugin = env.app.plugins.get(VitePlugin)
125
+ config = plugin._config # pyright: ignore[reportPrivateUsage]
126
+
127
+ console.rule("[yellow]Initializing Vite[/]", align="left")
128
+ resource_path = Path(resource_path or config.resource_dir)
129
+ public_path = Path(public_path or config.public_dir)
130
+ bundle_path = Path(bundle_path or config.bundle_dir)
131
+ enable_ssr = enable_ssr or config.ssr_enabled
132
+ asset_url = asset_url or config.asset_url
133
+ vite_port = vite_port or config.port
134
+ hot_file = Path(bundle_path / config.hot_file)
135
+ root_path = Path(root_path or config.root_dir or resource_path.parent)
136
+
137
+ if any(output_path.exists() for output_path in (bundle_path, resource_path)) and not any(
138
+ [overwrite, no_prompt],
139
+ ):
140
+ confirm_overwrite = Confirm.ask(
141
+ "Files were found in the paths specified. Are you sure you wish to overwrite the contents?",
142
+ )
143
+ if not confirm_overwrite:
144
+ console.print("Skipping Vite initialization")
145
+ sys.exit(2)
146
+ for output_path in (bundle_path, resource_path, root_path):
147
+ if output_path.exists():
148
+ console.print(f" * Creating {output_path!s}")
149
+ output_path.mkdir(parents=True, exist_ok=True)
150
+
151
+ enable_ssr = (
152
+ True
153
+ if enable_ssr
154
+ else False
155
+ if no_prompt
156
+ else Confirm.ask(
157
+ "Do you intend to use Litestar with any SSR framework?",
158
+ )
159
+ )
160
+ init_vite(
161
+ app=env.app,
162
+ root_path=root_path,
163
+ enable_ssr=enable_ssr,
164
+ vite_port=vite_port,
165
+ asset_url=asset_url,
166
+ resource_path=resource_path,
167
+ public_path=public_path,
168
+ bundle_path=bundle_path,
169
+ hot_file=hot_file,
170
+ litestar_port=env.port or 8000,
171
+ )
172
+ if not no_install:
173
+ if find_spec("nodeenv") is not None and plugin.config.detect_nodeenv:
174
+ """Detect nodeenv installed in the current python env before using a global version"""
175
+ nodeenv_command = (
176
+ str(Path(Path(sys.executable) / "nodeenv"))
177
+ if Path(Path(sys.executable) / "nodeenv").exists()
178
+ else "nodeenv"
179
+ )
180
+ install_dir = os.environ.get("VIRTUAL_ENV", sys.prefix)
181
+ console.rule("[yellow]Starting Nodeenv installation process[/]", align="left")
182
+ console.print(f"Installing Node environment into {install_dir}")
183
+ execute_command(command_to_run=[nodeenv_command, install_dir, "--force", "--quiet"], cwd=root_path)
184
+
185
+ console.rule("[yellow]Starting package installation process[/]", align="left")
186
+
187
+ execute_command(command_to_run=plugin.config.install_command, cwd=root_path)
188
+
189
+
190
+ @vite_group.command(
191
+ name="install",
192
+ help="Install frontend packages.",
193
+ )
194
+ @option("--verbose", type=bool, help="Enable verbose output.", default=False, is_flag=True)
195
+ def vite_install(app: Litestar, verbose: bool) -> None:
196
+ """Run vite build."""
197
+ import os
198
+ import sys
199
+ from importlib.util import find_spec
200
+ from pathlib import Path
201
+
202
+ from litestar.cli._utils import console
203
+
204
+ from litestar_vite.commands import execute_command
205
+ from litestar_vite.plugin import VitePlugin
206
+
207
+ if verbose:
208
+ app.debug = True
209
+ plugin = app.plugins.get(VitePlugin)
210
+
211
+ if find_spec("nodeenv") is not None and plugin.config.detect_nodeenv:
212
+ """Detect nodeenv installed in the current python env before using a global version"""
213
+ nodeenv_command = (
214
+ str(Path(Path(sys.executable) / "nodeenv"))
215
+ if Path(Path(sys.executable) / "nodeenv").exists()
216
+ else "nodeenv"
217
+ )
218
+ install_dir = os.environ.get("VIRTUAL_ENV", sys.prefix)
219
+ console.rule("[yellow]Starting Nodeenv installation process[/]", align="left")
220
+ console.print("Installing Node environment to %s:", install_dir)
221
+ execute_command(command_to_run=[nodeenv_command, install_dir, "--force", "--quiet"], cwd=plugin.config.root_dir)
222
+
223
+ console.rule("[yellow]Starting package installation process[/]", align="left")
224
+
225
+ execute_command(command_to_run=plugin.config.install_command, cwd=plugin.config.root_dir)
226
+
227
+
228
+ @vite_group.command(
229
+ name="build",
230
+ help="Building frontend assets with Vite.",
231
+ )
232
+ @option("--verbose", type=bool, help="Enable verbose output.", default=False, is_flag=True)
233
+ def vite_build(app: Litestar, verbose: bool) -> None:
234
+ """Run vite build."""
235
+ from litestar.cli._utils import (
236
+ console,
237
+ )
238
+
239
+ from litestar_vite.commands import execute_command
240
+ from litestar_vite.plugin import VitePlugin, set_environment
241
+
242
+ if verbose:
243
+ app.debug = True
244
+ console.rule("[yellow]Starting Vite build process[/]", align="left")
245
+ plugin = app.plugins.get(VitePlugin)
246
+ if plugin.config.set_environment:
247
+ set_environment(config=plugin.config)
248
+ p = execute_command(command_to_run=plugin.config.build_command, cwd=plugin.config.root_dir)
249
+ if p.returncode == 0:
250
+ console.print("[bold green] Assets built.[/]")
251
+ else:
252
+ console.print("[bold red] There was an error building the assets.[/]")
253
+
254
+
255
+ @vite_group.command(
256
+ name="serve",
257
+ help="Serving frontend assets with Vite.",
258
+ )
259
+ @option("--verbose", type=bool, help="Enable verbose output.", default=False, is_flag=True)
260
+ def vite_serve(app: Litestar, verbose: bool) -> None:
261
+ """Run vite serve."""
262
+ from litestar.cli._utils import (
263
+ console,
264
+ )
265
+
266
+ from litestar_vite.commands import execute_command
267
+ from litestar_vite.plugin import VitePlugin, set_environment
268
+
269
+ if verbose:
270
+ app.debug = True
271
+
272
+ plugin = app.plugins.get(VitePlugin)
273
+ if plugin.config.set_environment:
274
+ set_environment(config=plugin.config)
275
+ if plugin.config.hot_reload:
276
+ console.rule("[yellow]Starting Vite process with HMR Enabled[/]", align="left")
277
+ else:
278
+ console.rule("[yellow]Starting Vite watch and build process[/]", align="left")
279
+ command_to_run = plugin.config.run_command if plugin.config.hot_reload else plugin.config.build_watch_command
280
+ execute_command(command_to_run=command_to_run, cwd=plugin.config.root_dir)
281
+ console.print("[yellow]Vite process stopped.[/]")
282
+
283
+
284
+ @vite_group.command(
285
+ name="generate-routes",
286
+ help="Generate a JSON file with the route configuration",
287
+ )
288
+ @option(
289
+ "--output",
290
+ help="output file path",
291
+ type=ClickPath(dir_okay=False, path_type=Path),
292
+ default=Path("routes.json"),
293
+ show_default=True,
294
+ )
295
+ @option("--verbose", type=bool, help="Enable verbose output.", default=False, is_flag=True)
296
+ def generate_js_routes(app: Litestar, output: Path, verbose: bool) -> None:
297
+ """Run vite serve."""
298
+ import msgspec
299
+ from litestar.cli._utils import (
300
+ LitestarCLIException,
301
+ console,
302
+ )
303
+ from litestar.serialization import encode_json, get_serializer
304
+
305
+ from litestar_vite.plugin import VitePlugin, set_environment
306
+
307
+ if verbose:
308
+ app.debug = True
309
+ serializer = get_serializer(app.type_encoders)
310
+ plugin = app.plugins.get(VitePlugin)
311
+ if plugin.config.set_environment:
312
+ set_environment(config=plugin.config)
313
+ content = msgspec.json.format(
314
+ encode_json(app.openapi_schema.to_schema(), serializer=serializer),
315
+ indent=4,
316
+ )
317
+
318
+ try:
319
+ output.write_bytes(content)
320
+ except OSError as e: # pragma: no cover
321
+ msg = f"failed to write schema to path {output}"
322
+ raise LitestarCLIException(msg) from e
323
+
324
+ console.print("[yellow]Vite process stopped.[/]")
@@ -0,0 +1,131 @@
1
+ from __future__ import annotations
2
+
3
+ import platform
4
+ import subprocess
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, Any, MutableMapping
7
+
8
+ if TYPE_CHECKING:
9
+ from jinja2 import Environment, Template
10
+ from litestar import Litestar
11
+
12
+ VITE_INIT_TEMPLATES: set[str] = {"package.json.j2", "tsconfig.json.j2", "vite.config.ts.j2"}
13
+ DEFAULT_RESOURCES: set[str] = {"styles.css.j2", "main.ts.j2"}
14
+ DEFAULT_DEV_DEPENDENCIES: dict[str, str] = {
15
+ "typescript": "^5.3.3",
16
+ "vite": "^5.3.3",
17
+ "litestar-vite-plugin": "^0.6.2",
18
+ "@types/node": "^20.14.10",
19
+ }
20
+ DEFAULT_DEPENDENCIES: dict[str, str] = {"axios": "^1.7.2"}
21
+
22
+
23
+ def to_json(value: Any) -> str:
24
+ """Serialize JSON field values.
25
+
26
+ Args:
27
+ value: Any json serializable value.
28
+
29
+ Returns:
30
+ JSON string.
31
+ """
32
+ from litestar.serialization import encode_json
33
+
34
+ return encode_json(value).decode("utf-8")
35
+
36
+
37
+ def init_vite(
38
+ app: Litestar,
39
+ root_path: Path,
40
+ resource_path: Path,
41
+ asset_url: str,
42
+ public_path: Path,
43
+ bundle_path: Path,
44
+ enable_ssr: bool,
45
+ vite_port: int,
46
+ hot_file: Path,
47
+ litestar_port: int,
48
+ ) -> None:
49
+ """Initialize a new Vite project.
50
+
51
+ Args:
52
+ app: The Litestar application instance.
53
+ root_path: Root directory for the Vite project.
54
+ resource_path: Directory containing source files.
55
+ asset_url: Base URL for serving assets.
56
+ public_path: Directory for static files.
57
+ bundle_path: Output directory for built files.
58
+ enable_ssr: Enable server-side rendering.
59
+ vite_port: Port for Vite dev server.
60
+ hot_file: Path to hot reload manifest.
61
+ litestar_port: Port for Litestar server.
62
+ """
63
+ from jinja2 import Environment, FileSystemLoader, select_autoescape
64
+ from litestar.cli._utils import console
65
+ from litestar.utils import module_loader
66
+
67
+ template_path = module_loader.module_to_os_path("litestar_vite.templates")
68
+ vite_template_env = Environment(
69
+ loader=FileSystemLoader([template_path]),
70
+ autoescape=select_autoescape(),
71
+ )
72
+
73
+ enabled_templates: set[str] = VITE_INIT_TEMPLATES
74
+ enabled_resources: set[str] = DEFAULT_RESOURCES
75
+ dependencies: dict[str, str] = DEFAULT_DEPENDENCIES
76
+ dev_dependencies: dict[str, str] = DEFAULT_DEV_DEPENDENCIES
77
+ templates: dict[str, Template] = {
78
+ template_name: get_template(environment=vite_template_env, name=template_name)
79
+ for template_name in enabled_templates
80
+ }
81
+ for template_name, template in templates.items():
82
+ target_file_name = template_name[:-3] if template_name.endswith(".j2") else template_name
83
+ with Path(target_file_name).open(mode="w") as file:
84
+ console.print(f" * Writing {target_file_name} to {Path(target_file_name)!s}")
85
+
86
+ file.write(
87
+ template.render(
88
+ entry_point=[
89
+ f"{resource_path!s}/{resource_name[:-3] if resource_name.endswith('.j2') else resource_name}"
90
+ for resource_name in enabled_resources
91
+ ],
92
+ enable_ssr=enable_ssr,
93
+ asset_url=asset_url,
94
+ root_path=root_path,
95
+ resource_path=str(resource_path.relative_to(root_path)),
96
+ public_path=str(public_path.relative_to(root_path)),
97
+ bundle_path=str(bundle_path.relative_to(root_path)),
98
+ hot_file=str(hot_file.relative_to(root_path)),
99
+ vite_port=str(vite_port),
100
+ litestar_port=litestar_port,
101
+ dependencies=to_json(dependencies),
102
+ dev_dependencies=to_json(dev_dependencies),
103
+ ),
104
+ )
105
+
106
+ for resource_name in enabled_resources:
107
+ template = get_template(environment=vite_template_env, name=resource_name)
108
+ target_file_name = f"{resource_path}/{resource_name[:-3] if resource_name.endswith('.j2') else resource_name}"
109
+ with Path(target_file_name).open(mode="w") as file:
110
+ console.print(
111
+ f" * Writing {resource_name[:-3] if resource_name.endswith('.j2') else resource_name} to {Path(target_file_name)!s}",
112
+ )
113
+ file.write(template.render())
114
+ console.print("[yellow]Vite initialization completed.[/]")
115
+
116
+
117
+ def get_template(
118
+ environment: Environment,
119
+ name: str | Template,
120
+ parent: str | None = None,
121
+ globals: MutableMapping[str, Any] | None = None, # noqa: A002
122
+ ) -> Template:
123
+ return environment.get_template(name=name, parent=parent, globals=globals)
124
+
125
+
126
+ def execute_command(command_to_run: list[str], cwd: str | Path | None = None) -> subprocess.CompletedProcess[bytes]:
127
+ """Run Vite in a subprocess."""
128
+ kwargs = {}
129
+ if cwd is not None:
130
+ kwargs["cwd"] = Path(cwd)
131
+ return subprocess.run(command_to_run, check=False, shell=platform.system() == "Windows", **kwargs) # type: ignore[call-overload]
@@ -0,0 +1,173 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from dataclasses import dataclass, field
5
+ from functools import cached_property
6
+ from inspect import isclass
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, cast
9
+
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")
20
+ TRUE_VALUES = {"True", "true", "1", "yes", "Y", "T"}
21
+
22
+
23
+ @dataclass
24
+ class ViteConfig:
25
+ """Configuration for ViteJS support.
26
+
27
+ To enable Vite integration, pass an instance of this class to the
28
+ :class:`Litestar <litestar.app.Litestar>` constructor using the
29
+ 'plugins' key.
30
+ """
31
+
32
+ bundle_dir: Path | str = field(default="public")
33
+ """Location of the compiled assets from Vite.
34
+
35
+ The manifest file will also be found here.
36
+ """
37
+ resource_dir: Path | str = field(default="resources")
38
+ """The directory where all typescript/javascript source are written.
39
+
40
+ In a standalone Vue or React application, this would be equivalent to the ``./src`` directory.
41
+ """
42
+ template_dir: Path | str | None = field(default="templates")
43
+ """Location of the Jinja2 template file."""
44
+ public_dir: Path | str = field(default="public")
45
+ """The optional public directory Vite serves assets from.
46
+
47
+ In a standalone Vue or React application, this would be equivalent to the ``./public`` directory.
48
+ """
49
+ manifest_name: str = "manifest.json"
50
+ """Name of the manifest file."""
51
+ hot_file: str = "hot"
52
+ """Name of the hot file.
53
+
54
+ This file contains a single line containing the host, protocol, and port the Vite server is running.
55
+ """
56
+ hot_reload: bool = field(
57
+ default_factory=lambda: os.getenv("VITE_HOT_RELOAD", "True") in TRUE_VALUES,
58
+ )
59
+ """Enable HMR for Vite development server."""
60
+ ssr_enabled: bool = False
61
+ """Enable SSR."""
62
+ ssr_output_dir: Path | str | None = None
63
+ """SSR Output path"""
64
+ root_dir: Path | str | None = None
65
+ """The is the base path to your application.
66
+
67
+ In a standalone Vue or React application, this would be equivalent to the top-level project folder containing the ``./src`` directory.
68
+
69
+ """
70
+ is_react: bool = False
71
+ """Enable React components."""
72
+ asset_url: str = field(default_factory=lambda: os.getenv("ASSET_URL", "/static/"))
73
+ """Base URL to generate for static asset references.
74
+
75
+ This URL will be prepended to anything generated from Vite.
76
+ """
77
+ host: str = field(default_factory=lambda: os.getenv("VITE_HOST", "localhost"))
78
+ """Default host to use for Vite server."""
79
+ protocol: str = "http"
80
+ """Protocol to use for communication"""
81
+ port: int = field(default_factory=lambda: int(os.getenv("VITE_PORT", "5173")))
82
+ """Default port to use for Vite server."""
83
+ run_command: list[str] = field(default_factory=lambda: ["npm", "run", "dev"])
84
+ """Default command to use for running Vite."""
85
+ build_watch_command: list[str] = field(default_factory=lambda: ["npm", "run", "watch"])
86
+ """Default command to use for dev building with Vite."""
87
+ build_command: list[str] = field(default_factory=lambda: ["npm", "run", "build"])
88
+ """Default command to use for building with Vite."""
89
+ install_command: list[str] = field(default_factory=lambda: ["npm", "install"])
90
+ """Default command to use for installing Vite."""
91
+ use_server_lifespan: bool = field(
92
+ default_factory=lambda: os.getenv("VITE_USE_SERVER_LIFESPAN", "False") in TRUE_VALUES,
93
+ )
94
+ """Utilize the server lifespan hook to run Vite."""
95
+ dev_mode: bool = field(
96
+ default_factory=lambda: os.getenv("VITE_DEV_MODE", "False") in TRUE_VALUES,
97
+ )
98
+ """When True, Vite will run with HMR or watch build"""
99
+ detect_nodeenv: bool = True
100
+ """When True, The initializer will install and configure nodeenv if present"""
101
+ set_environment: bool = True
102
+ """When True, configuration in this class will be set into environment variables.
103
+
104
+ This can be useful to ensure Vite always uses the configuration supplied to the plugin
105
+ """
106
+ set_static_folders: bool = True
107
+ """When True, Litestar will automatically serve assets at the `ASSET_URL` path.
108
+ """
109
+
110
+ def __post_init__(self) -> None:
111
+ """Ensure that directory is set if engine is a class."""
112
+ if self.root_dir is not None and isinstance(self.root_dir, str):
113
+ self.root_dir = Path(self.root_dir)
114
+ if self.template_dir is not None and isinstance(self.template_dir, str):
115
+ self.template_dir = Path(self.template_dir)
116
+ if self.public_dir and isinstance(self.public_dir, str):
117
+ self.public_dir = Path(self.public_dir)
118
+ if isinstance(self.resource_dir, str):
119
+ self.resource_dir = Path(self.resource_dir)
120
+ if isinstance(self.bundle_dir, str):
121
+ self.bundle_dir = Path(self.bundle_dir)
122
+ if isinstance(self.ssr_output_dir, str):
123
+ self.ssr_output_dir = Path(self.ssr_output_dir)
124
+
125
+
126
+ @dataclass
127
+ class ViteTemplateConfig(TemplateConfig[EngineType]):
128
+ """Configuration for Templating.
129
+
130
+ To enable templating, pass an instance of this class to the
131
+ :class:`Litestar <litestar.app.Litestar>` constructor using the
132
+ 'template_config' key.
133
+ """
134
+
135
+ config: ViteConfig = field(default_factory=lambda: ViteConfig())
136
+ """A a config for the vite engine`."""
137
+ engine: type[EngineType] | EngineType | None = field(default=None)
138
+ """A template engine adhering to the :class:`TemplateEngineProtocol <litestar.template.TemplateEngineProtocol>`."""
139
+ directory: PathType | list[PathType] | None = field(default=None)
140
+ """A directory or list of directories from which to serve templates."""
141
+ engine_callback: Callable[[EngineType], None] | None = field(default=None)
142
+ """A callback function that allows modifying the instantiated templating
143
+ protocol."""
144
+
145
+ instance: EngineType | None = field(default=None)
146
+ """An instance of the templating protocol."""
147
+
148
+ def __post_init__(self) -> None:
149
+ """Ensure that directory is set if engine is a class."""
150
+ if isclass(self.engine) and not self.directory: # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
151
+ msg = "directory is a required kwarg when passing a template engine class"
152
+ raise ImproperlyConfiguredException(msg)
153
+ """Ensure that directory is not set if instance is."""
154
+ if self.instance is not None and self.directory is not None: # pyright: ignore[reportUnknownMemberType]
155
+ msg = "directory cannot be set if instance is"
156
+ raise ImproperlyConfiguredException(msg)
157
+
158
+ def to_engine(self) -> EngineType:
159
+ """Instantiate the template engine."""
160
+ template_engine = cast(
161
+ "EngineType",
162
+ self.engine(directory=self.directory, config=self.config, engine_instance=None) # pyright: ignore[reportUnknownMemberType,reportCallIssue]
163
+ if isclass(self.engine) # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
164
+ else self.engine, # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
165
+ )
166
+ if callable(self.engine_callback):
167
+ self.engine_callback(template_engine) # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
168
+ return template_engine
169
+
170
+ @cached_property
171
+ def engine_instance(self) -> EngineType:
172
+ """Return the template engine instance."""
173
+ return self.to_engine() if self.instance is None else self.instance
@@ -0,0 +1,34 @@
1
+ from .config import InertiaConfig
2
+ from .exception_handler import create_inertia_exception_response, exception_to_http_response
3
+ from .middleware import InertiaMiddleware
4
+ from .plugin import InertiaPlugin
5
+ from .request import InertiaDetails, InertiaHeaders, InertiaRequest
6
+ from .response import (
7
+ InertiaBack,
8
+ InertiaExternalRedirect,
9
+ InertiaRedirect,
10
+ InertiaResponse,
11
+ error,
12
+ get_shared_props,
13
+ share,
14
+ )
15
+ from .routes import generate_js_routes
16
+
17
+ __all__ = (
18
+ "InertiaBack",
19
+ "InertiaConfig",
20
+ "InertiaDetails",
21
+ "InertiaExternalRedirect",
22
+ "InertiaHeaders",
23
+ "InertiaMiddleware",
24
+ "InertiaPlugin",
25
+ "InertiaRedirect",
26
+ "InertiaRequest",
27
+ "InertiaResponse",
28
+ "create_inertia_exception_response",
29
+ "error",
30
+ "exception_to_http_response",
31
+ "generate_js_routes",
32
+ "get_shared_props",
33
+ "share",
34
+ )