litestar-vite-plugin 0.6.8 → 0.7.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Cody Fincher
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,15 +1,138 @@
1
- # Litestar Vite Plugin
1
+ # Litestar Vite
2
2
 
3
- **Notice** This is experimental software
3
+ > [!IMPORTANT]
4
+ > This plugin currently contains minimal features and is a work-in-progress
4
5
 
5
- ## What is this?
6
+ ## Installation
6
7
 
7
- This is a library for Litestar and Vite that makes integration between the the two easier.
8
+ ```shell
9
+ pip install litestar-vite
10
+ ```
8
11
 
9
- For details on usage, use the `litestar-vite` [plugin](https://github.com/cofin/litestar-vite)
12
+ ## Usage
10
13
 
11
- ## Credit
14
+ Here is a basic application that demonstrates how to use the plugin.
12
15
 
13
- The team at Laravel have done an incredible job at making it easier to use common JS/TS frameworks with the framework.
16
+ ```python
17
+ from __future__ import annotations
14
18
 
15
- This plugin is more than a little inspired by the worker here [Laravel's Vite Integration](https://github.com/laravel/vite-plugin)
19
+ from pathlib import Path
20
+
21
+ from litestar import Controller, get, Litestar
22
+ from litestar.response import Template
23
+ from litestar.status_codes import HTTP_200_OK
24
+ from litestar_vite import ViteConfig, VitePlugin
25
+
26
+ class WebController(Controller):
27
+
28
+ opt = {"exclude_from_auth": True}
29
+ include_in_schema = False
30
+
31
+ @get(["/", "/{path:str}"],status_code=HTTP_200_OK)
32
+ async def index(self) -> Template:
33
+ return Template(template_name="index.html.j2")
34
+
35
+
36
+ vite = VitePlugin(config=ViteConfig(template_dir='templates/'))
37
+ app = Litestar(plugins=[vite], route_handlers=[WebController])
38
+
39
+ ```
40
+
41
+ Create a template to serve the application in `./templates/index.html.h2`:
42
+
43
+ ```html
44
+ <!DOCTYPE html>
45
+ <html>
46
+ <head>
47
+ <meta charset="utf-8" />
48
+ <!--IE compatibility-->
49
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
50
+ <meta
51
+ name="viewport"
52
+ content="width=device-width, initial-scale=1.0, maximum-scale=1.0"
53
+ />
54
+ </head>
55
+
56
+ <body>
57
+ <div id="app"></div>
58
+ {{ vite_hmr() }} {{ vite('resources/main.ts') }}
59
+ </body>
60
+ </html>
61
+ ```
62
+
63
+ ### Template initialization (Optional)
64
+
65
+ This is a command to help initialize Vite for your project. This is generally only needed a single time. You may also manually configure Vite and skip this step.
66
+
67
+ to initialize a Vite configuration:
68
+
69
+ ```shell
70
+ ❯ litestar assets init
71
+ Using Litestar app from app:app
72
+ Initializing Vite ──────────────────────────────────────────────────────────────────────────────────────────
73
+ Do you intend to use Litestar with any SSR framework? [y/n]: n
74
+ INFO - 2023-12-11 12:33:41,455 - root - commands - Writing vite.config.ts
75
+ INFO - 2023-12-11 12:33:41,456 - root - commands - Writing package.json
76
+ INFO - 2023-12-11 12:33:41,456 - root - commands - Writing tsconfig.json
77
+ ```
78
+
79
+ ### Install Javascript/Typescript Packages
80
+
81
+ Install the packages required for development:
82
+
83
+ **Note** This is equivalent to the the `npm install` by default. This command is configurable.
84
+
85
+ ```shell
86
+ ❯ litestar assets install
87
+ Using Litestar app from app:app
88
+ Starting Vite package installation process ──────────────────────────────────────────────────────────────────────────────────────────
89
+
90
+ added 25 packages, and audited 26 packages in 1s
91
+
92
+
93
+ 5 packages are looking for funding
94
+ run `npm fund` for details
95
+
96
+
97
+ found 0 vulnerabilities
98
+ ```
99
+
100
+ ### Development
101
+
102
+ To automatically start and stop the Vite instance with the Litestar application, you can enable the `use_server_lifespan` hooks in the `ViteConfig`.
103
+
104
+ Alternately, to start the development server manually, you can run the following
105
+
106
+ ```shell
107
+ ❯ litestar assets serve
108
+ Using Litestar app from app:app
109
+ Starting Vite build process ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
110
+
111
+ > build
112
+ > vite build
113
+
114
+
115
+ vite v5.0.7 building for production...
116
+
117
+ ✓ 0 modules transformed.
118
+
119
+ ```
120
+
121
+ **Note** This is equivalent to the the `npm run dev` command when `hot_reload` is enabled. Otherwise it is equivalent to `npm run build -- --watch`. This command is configurable.
122
+
123
+ ### Building for Production
124
+
125
+ ```shell
126
+ ❯ litestar assets build
127
+ Using Litestar app from app:app
128
+ Starting Vite build process ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
129
+
130
+ > build
131
+ > vite build
132
+
133
+
134
+ vite v5.0.7 building for production...
135
+
136
+ ✓ 0 modules transformed.
137
+
138
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "litestar-vite-plugin",
3
- "version": "0.6.8",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "Litestar plugin for Vite.",
6
6
  "keywords": [
@@ -8,38 +8,38 @@
8
8
  "vite",
9
9
  "vite-plugin"
10
10
  ],
11
- "homepage": "https://github.com/litestar-org/vite-plugin",
11
+ "homepage": "https://github.com/litestar-org/litestar-vite",
12
12
  "repository": {
13
13
  "type": "git",
14
- "url": "git+https://github.com/litestar-org/vite-plugin.git"
14
+ "url": "git+https://github.com/litestar-org/litestar-vite.git"
15
15
  },
16
16
  "license": "MIT",
17
17
  "author": "Litestar",
18
18
  "exports": {
19
19
  ".": {
20
- "types": "./dist/index.d.ts",
21
- "default": "./dist/index.js"
20
+ "types": "./dist/js/index.d.ts",
21
+ "default": "./dist/js/index.js"
22
22
  },
23
23
  "./inertia-helpers": {
24
- "types": "./inertia-helpers/index.d.ts",
25
- "default": "./inertia-helpers/index.js"
24
+ "types": "./dist/js/inertia-helpers/index.d.ts",
25
+ "default": "./dist/js/inertia-helpers/index.js"
26
26
  }
27
27
  },
28
- "types": "./dist/index.d.ts",
28
+ "types": "./dist/js/index.d.ts",
29
29
  "files": [
30
- "/dist",
31
- "/inertia-helpers"
30
+ "/dist/js/",
31
+ "/dist/js/inertia-helpers"
32
32
  ],
33
33
  "bin": {
34
- "clean-orphaned-assets": "bin/clean.js"
34
+ "clean-orphaned-assets": "tools/clean.js"
35
35
  },
36
36
  "scripts": {
37
37
  "build": "npm run build-plugin && npm run build-inertia-helpers",
38
- "build-plugin": "rm -rf dist && npm run build-plugin-types && npm run build-plugin-esm && cp src/dev-server-index.html dist/",
39
- "build-plugin-types": "tsc --emitDeclarationOnly",
40
- "build-plugin-esm": "esbuild src/index.ts --platform=node --format=esm --outfile=dist/index.js",
41
- "build-inertia-helpers": "rm -rf inertia-helpers && tsc --project tsconfig.inertia-helpers.json",
42
- "lint": "eslint --ext .ts ./src ./tests",
38
+ "build-plugin": "rm -rf dist/js && npm run build-plugin-types && npm run build-plugin-esm && cp src/js/src/dev-server-index.html dist/js/",
39
+ "build-plugin-types": "tsc --project src/js/tsconfig.json --emitDeclarationOnly",
40
+ "build-plugin-esm": "esbuild src/js/src/index.ts --platform=node --format=esm --outfile=dist/js/index.js",
41
+ "build-inertia-helpers": "rm -rf dist/inertia-helpers && tsc --project src/js/tsconfig.inertia-helpers.json",
42
+ "lint": "eslint --ext .ts ./src/js/src ./src/js/tests",
43
43
  "test": "vitest run"
44
44
  },
45
45
  "devDependencies": {
File without changes
package/LICENSE.md DELETED
@@ -1,45 +0,0 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) 2021, 2022, 2023 Litestar Org.
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
22
-
23
- Code adapted from:
24
-
25
- The MIT License (MIT)
26
-
27
- Copyright (c) Taylor Otwell
28
-
29
- Permission is hereby granted, free of charge, to any person obtaining a copy
30
- of this software and associated documentation files (the "Software"), to deal
31
- in the Software without restriction, including without limitation the rights
32
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33
- copies of the Software, and to permit persons to whom the Software is
34
- furnished to do so, subject to the following conditions:
35
-
36
- The above copyright notice and this permission notice shall be included in
37
- all copies or substantial portions of the Software.
38
-
39
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
41
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
42
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
43
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
44
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
45
- THE SOFTWARE.
@@ -1,185 +0,0 @@
1
- <!DOCTYPE html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width, initial-scale=1" />
6
-
7
- <title>Litestar Vite</title>
8
-
9
- <!-- Fonts -->
10
- <link
11
- href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap"
12
- rel="stylesheet"
13
- />
14
-
15
- <script src="https://cdn.tailwindcss.com"></script>
16
- </head>
17
- <body class="antialiased">
18
- <div
19
- class="relative flex min-h-screen flex-col justify-center overflow-hidden bg-gray-100 text-gray-600 dark:text-gray-400 dark:bg-gray-900 py-6 sm:py-12"
20
- >
21
- <div
22
- class="relative bg-white dark:bg-gray-800 px-6 pt-10 pb-8 shadow-xl ring-1 ring-gray-900/5 sm:mx-auto sm:max-w-xl sm:rounded-lg sm:px-10"
23
- >
24
- <div class="mx-auto">
25
- <div class="flex items-center justify-center space-x-6">
26
- <a href="https://litestar.dev">
27
- <svg
28
- viewBox="0 52 410 250"
29
- xmlns="http://www.w3.org/2000/svg"
30
- class="h-16 w-auto"
31
- >
32
- <defs>
33
- <clipPath id="9eb7762d41">
34
- <path
35
- d="M 15.933594 105 L 328 105 L 328 259 L 15.933594 259 Z M 15.933594 105 "
36
- clip-rule="nonzero"
37
- />
38
- </clipPath>
39
- <clipPath id="183d3cc178">
40
- <path
41
- d="M 142 78.769531 L 359.433594 78.769531 L 359.433594 296.269531 L 142 296.269531 Z M 142 78.769531 "
42
- clip-rule="nonzero"
43
- />
44
- </clipPath>
45
- </defs>
46
- <g clip-path="url(#9eb7762d41)">
47
- <path
48
- fill="#edb641"
49
- d="M 147.625 240.3125 C 161.5 233.984375 173.554688 227.011719 183.425781 220.550781 C 202.304688 208.203125 226.4375 185.242188 227.761719 183.410156 L 218.917969 177.503906 L 211.257812 172.386719 L 235.503906 171.441406 L 243.296875 171.136719 L 245.414062 163.640625 L 252.007812 140.304688 L 260.402344 163.054688 L 263.097656 170.363281 L 270.890625 170.058594 L 295.136719 169.113281 L 276.078125 184.117188 L 269.953125 188.9375 L 272.652344 196.25 L 281.046875 218.996094 L 260.871094 205.523438 L 254.390625 201.195312 L 248.265625 206.015625 L 229.207031 221.023438 L 232.480469 209.425781 L 235.796875 197.691406 L 236.207031 196.234375 C 213.003906 213.585938 180.546875 230.304688 161.140625 236.488281 C 156.6875 237.90625 152.183594 239.179688 147.625 240.3125 Z M 101.992188 258.078125 C 136.382812 256.734375 177.355469 248 217.675781 222.363281 L 209.90625 249.867188 L 254.910156 214.4375 L 302.539062 246.246094 L 282.71875 192.539062 L 327.71875 157.109375 L 270.46875 159.34375 L 250.648438 105.636719 L 235.085938 160.726562 L 177.835938 162.964844 L 210.980469 185.097656 C 189.164062 204.921875 134.445312 247.195312 61.957031 250.03125 C 47.300781 250.601562 31.914062 249.558594 15.933594 246.394531 C 15.933594 246.394531 52.011719 260.035156 101.992188 258.078125 "
50
- fill-opacity="1"
51
- fill-rule="nonzero"
52
- />
53
- </g>
54
- <g clip-path="url(#183d3cc178)">
55
- <path
56
- fill="#edb641"
57
- d="M 250.789062 78.96875 C 190.78125 78.96875 142.140625 127.570312 142.140625 187.519531 C 142.140625 198.875 143.886719 209.816406 147.121094 220.101562 C 151.847656 217.75 156.363281 215.316406 160.660156 212.84375 C 158.394531 204.789062 157.183594 196.296875 157.183594 187.519531 C 157.183594 135.871094 199.089844 93.996094 250.789062 93.996094 C 302.484375 93.996094 344.390625 135.871094 344.390625 187.519531 C 344.390625 239.171875 302.484375 281.042969 250.789062 281.042969 C 222.75 281.042969 197.597656 268.722656 180.441406 249.210938 C 175.453125 251.152344 170.402344 252.917969 165.289062 254.511719 C 185.183594 279.816406 216.082031 296.070312 250.789062 296.070312 C 310.792969 296.070312 359.433594 247.472656 359.433594 187.519531 C 359.433594 127.570312 310.792969 78.96875 250.789062 78.96875 "
58
- fill-opacity="1"
59
- fill-rule="nonzero"
60
- />
61
- </g>
62
- <path
63
- fill="#edb641"
64
- d="M 92.292969 173.023438 L 98.289062 191.460938 L 117.691406 191.460938 L 101.992188 202.855469 L 107.988281 221.292969 L 92.292969 209.898438 L 76.59375 221.292969 L 82.589844 202.855469 L 66.894531 191.460938 L 86.296875 191.460938 L 92.292969 173.023438 "
65
- fill-opacity="1"
66
- fill-rule="nonzero"
67
- />
68
- <path
69
- fill="#edb641"
70
- d="M 120.214844 112.25 L 125.390625 128.167969 L 142.140625 128.167969 L 128.589844 138 L 133.765625 153.917969 L 120.214844 144.082031 L 106.664062 153.917969 L 111.839844 138 L 98.289062 128.167969 L 115.039062 128.167969 L 120.214844 112.25 "
71
- fill-opacity="1"
72
- fill-rule="nonzero"
73
- />
74
- <path
75
- fill="#edb641"
76
- d="M 34.695312 209.136719 L 37.71875 218.421875 L 47.492188 218.421875 L 39.585938 224.160156 L 42.605469 233.449219 L 34.695312 227.707031 L 26.792969 233.449219 L 29.8125 224.160156 L 21.90625 218.421875 L 31.679688 218.421875 L 34.695312 209.136719 "
77
- fill-opacity="1"
78
- fill-rule="nonzero"
79
- />
80
- </svg>
81
- </a>
82
- <svg
83
- xmlns="http://www.w3.org/2000/svg"
84
- class="h-6 w-6 text-gray-500"
85
- fill="none"
86
- viewBox="0 0 24 24"
87
- stroke="currentColor"
88
- stroke-width="2"
89
- >
90
- <path
91
- stroke-linecap="round"
92
- stroke-linejoin="round"
93
- d="M12 4v16m8-8H4"
94
- />
95
- </svg>
96
- <a href="https://vitejs.dev">
97
- <svg
98
- viewBox="0 0 410 404"
99
- fill="none"
100
- xmlns="http://www.w3.org/2000/svg"
101
- class="h-16 w-auto"
102
- >
103
- <path
104
- d="M399.641 59.5246L215.643 388.545C211.844 395.338 202.084 395.378 198.228 388.618L10.5817 59.5563C6.38087 52.1896 12.6802 43.2665 21.0281 44.7586L205.223 77.6824C206.398 77.8924 207.601 77.8904 208.776 77.6763L389.119 44.8058C397.439 43.2894 403.768 52.1434 399.641 59.5246Z"
105
- fill="url(#paint0_linear)"
106
- />
107
- <path
108
- d="M292.965 1.5744L156.801 28.2552C154.563 28.6937 152.906 30.5903 152.771 32.8664L144.395 174.33C144.198 177.662 147.258 180.248 150.51 179.498L188.42 170.749C191.967 169.931 195.172 173.055 194.443 176.622L183.18 231.775C182.422 235.487 185.907 238.661 189.532 237.56L212.947 230.446C216.577 229.344 220.065 232.527 219.297 236.242L201.398 322.875C200.278 328.294 207.486 331.249 210.492 326.603L212.5 323.5L323.454 102.072C325.312 98.3645 322.108 94.137 318.036 94.9228L279.014 102.454C275.347 103.161 272.227 99.746 273.262 96.1583L298.731 7.86689C299.767 4.27314 296.636 0.855181 292.965 1.5744Z"
109
- fill="url(#paint1_linear)"
110
- />
111
- <defs>
112
- <linearGradient
113
- id="paint0_linear"
114
- x1="6.00017"
115
- y1="32.9999"
116
- x2="235"
117
- y2="344"
118
- gradientUnits="userSpaceOnUse"
119
- >
120
- <stop stop-color="#41D1FF" />
121
- <stop offset="1" stop-color="#BD34FE" />
122
- </linearGradient>
123
- <linearGradient
124
- id="paint1_linear"
125
- x1="194.651"
126
- y1="8.81818"
127
- x2="236.076"
128
- y2="292.989"
129
- gradientUnits="userSpaceOnUse"
130
- >
131
- <stop stop-color="#FFEA83" />
132
- <stop
133
- offset="0.0833333"
134
- stop-color="#FFDD35"
135
- />
136
- <stop offset="1" stop-color="#FFA800" />
137
- </linearGradient>
138
- </defs>
139
- </svg>
140
- </a>
141
- </div>
142
- <div class="divide-y divide-gray-300 dark:divide-gray-700">
143
- <div class="py-8 text-base leading-7">
144
- <p>
145
- This is the Vite development server that
146
- provides Hot Module Replacement for your
147
- Litestar application.
148
- </p>
149
- <p class="mt-6">
150
- To access your Litestar application, you will
151
- need to run a local development server.
152
- </p>
153
- </div>
154
- <div class="pt-8 text-base leading-7">
155
- <p>
156
- Your Litestar application's configured
157
- <code
158
- class="text-sm font-bold text-gray-900 dark:text-gray-100"
159
- >APP_URL</code
160
- >
161
- is:<br />
162
- <a
163
- href="{{ APP_URL }}"
164
- class="font-semibold text-red-500 hover:text-red-600"
165
- >{{ APP_URL }}</a
166
- >
167
- </p>
168
- <p class="mt-6">
169
- Want more information on Litestar's Vite
170
- integration?
171
- </p>
172
- <p>
173
- <a
174
- href="https://litestar.dev/docs/vite"
175
- class="font-semibold text-red-500 hover:text-red-600"
176
- >Read the docs &rarr;</a
177
- >
178
- </p>
179
- </div>
180
- </div>
181
- </div>
182
- </div>
183
- </div>
184
- </body>
185
- </html>
package/dist/index.d.ts DELETED
@@ -1,75 +0,0 @@
1
- import { Plugin, UserConfig, ConfigEnv } from 'vite';
2
- import { Config as FullReloadConfig } from 'vite-plugin-full-reload';
3
- interface PluginConfig {
4
- /**
5
- * The path or paths of the entry points to compile.
6
- */
7
- input: string | string[];
8
- /**
9
- * The base path to use for all asset URLs.
10
- *
11
- * @default '/static/'
12
- */
13
- assetUrl?: string;
14
- /**
15
- * The public directory where all compiled/bundled assets should be written.
16
- *
17
- * @default 'public/dist'
18
- */
19
- bundleDirectory?: string;
20
- /**
21
- * Litestar's public assets directory. These are the assets that Vite will serve when developing.
22
- *
23
- * @default 'resources'
24
- */
25
- resourceDirectory?: string;
26
- /**
27
- * The path to the "hot" file.
28
- *
29
- * @default `${bundleDirectory}/hot`
30
- */
31
- hotFile?: string;
32
- /**
33
- * The path of the SSR entry point.
34
- */
35
- ssr?: string | string[];
36
- /**
37
- * The directory where the SSR bundle should be written.
38
- *
39
- * @default '${bundleDirectory}/bootstrap/ssr'
40
- */
41
- ssrOutputDirectory?: string;
42
- /**
43
- * Configuration for performing full page refresh on python (or other) file changes.
44
- *
45
- * {@link https://github.com/ElMassimo/vite-plugin-full-reload}
46
- * @default false
47
- */
48
- refresh?: boolean | string | string[] | RefreshConfig | RefreshConfig[];
49
- /**
50
- * Utilize TLS certificates.
51
- *
52
- * @default null
53
- */
54
- detectTls?: string | boolean | null;
55
- /**
56
- * Transform the code while serving.
57
- */
58
- transformOnServe?: (code: string, url: DevServerUrl) => string;
59
- }
60
- interface RefreshConfig {
61
- paths: string[];
62
- config?: FullReloadConfig;
63
- }
64
- interface LitestarPlugin extends Plugin {
65
- config: (config: UserConfig, env: ConfigEnv) => UserConfig;
66
- }
67
- type DevServerUrl = `${"http" | "https"}://${string}:${number}`;
68
- export declare const refreshPaths: string[];
69
- /**
70
- * Litestar plugin for Vite.
71
- *
72
- * @param config - A config object or relative path(s) of the scripts to be compiled.
73
- */
74
- export default function litestar(config: string | string[] | PluginConfig): [LitestarPlugin, ...Plugin[]];
75
- export {};
package/dist/index.js DELETED
@@ -1,401 +0,0 @@
1
- import fs from "fs";
2
- import { fileURLToPath } from "url";
3
- import path from "path";
4
- import colors from "picocolors";
5
- import { loadEnv } from "vite";
6
- import fullReload from "vite-plugin-full-reload";
7
- let exitHandlersBound = false;
8
- const refreshPaths = [
9
- "**/*.py",
10
- "**/*.j2",
11
- "**/*.html.j2",
12
- "**/*.html",
13
- "**/assets/**/*"
14
- ];
15
- function litestar(config) {
16
- const pluginConfig = resolvePluginConfig(config);
17
- return [
18
- resolveLitestarPlugin(pluginConfig),
19
- ...resolveFullReloadConfig(pluginConfig)
20
- ];
21
- }
22
- function resolveLitestarPlugin(pluginConfig) {
23
- let viteDevServerUrl;
24
- let resolvedConfig;
25
- let userConfig;
26
- const defaultAliases = {
27
- "@": pluginConfig.resourceDirectory || "/resources/"
28
- };
29
- return {
30
- name: "litestar",
31
- enforce: "post",
32
- config: (config, { command, mode }) => {
33
- userConfig = config;
34
- const ssr = !!userConfig.build?.ssr;
35
- const env = loadEnv(mode, userConfig.envDir || process.cwd(), "");
36
- const assetUrl = env.ASSET_URL || pluginConfig.assetUrl;
37
- const serverConfig = command === "serve" ? resolveDevelopmentEnvironmentServerConfig(
38
- pluginConfig.detectTls
39
- ) ?? resolveEnvironmentServerConfig(env) : void 0;
40
- ensureCommandShouldRunInEnvironment(command, env);
41
- return {
42
- base: userConfig.base ?? (command === "build" ? resolveBase(pluginConfig, assetUrl) : pluginConfig.assetUrl),
43
- publicDir: userConfig.publicDir ?? false,
44
- clearScreen: false,
45
- build: {
46
- manifest: userConfig.build?.manifest ?? (ssr ? false : "manifest.json"),
47
- ssrManifest: userConfig.build?.ssrManifest ?? (ssr ? "ssr-manifest.json" : false),
48
- outDir: userConfig.build?.outDir ?? resolveOutDir(pluginConfig, ssr),
49
- rollupOptions: {
50
- input: userConfig.build?.rollupOptions?.input ?? resolveInput(pluginConfig, ssr)
51
- },
52
- assetsInlineLimit: userConfig.build?.assetsInlineLimit ?? 0
53
- },
54
- server: {
55
- origin: userConfig.server?.origin ?? "__litestar_vite_placeholder__",
56
- ...process.env.VITE_ALLOW_REMOTE ? {
57
- host: userConfig.server?.host ?? "0.0.0.0",
58
- port: userConfig.server?.port ?? (env.VITE_PORT ? parseInt(env.VITE_PORT) : 5173),
59
- strictPort: userConfig.server?.strictPort ?? true
60
- } : void 0,
61
- ...serverConfig ? {
62
- host: userConfig.server?.host ?? serverConfig.host,
63
- hmr: userConfig.server?.hmr === false ? false : {
64
- ...serverConfig.hmr,
65
- ...userConfig.server?.hmr === true ? {} : userConfig.server?.hmr
66
- },
67
- https: userConfig.server?.https ?? serverConfig.https
68
- } : void 0
69
- },
70
- resolve: {
71
- alias: Array.isArray(userConfig.resolve?.alias) ? [
72
- ...userConfig.resolve?.alias ?? [],
73
- ...Object.keys(defaultAliases).map((alias) => ({
74
- find: alias,
75
- replacement: defaultAliases[alias]
76
- }))
77
- ] : {
78
- ...defaultAliases,
79
- ...userConfig.resolve?.alias
80
- }
81
- },
82
- ssr: {
83
- noExternal: noExternalInertiaHelpers(userConfig)
84
- }
85
- };
86
- },
87
- configResolved(config) {
88
- resolvedConfig = config;
89
- },
90
- transform(code) {
91
- if (resolvedConfig.command === "serve") {
92
- code = code.replace(
93
- /__litestar_vite_placeholder__/g,
94
- viteDevServerUrl
95
- );
96
- return pluginConfig.transformOnServe(code, viteDevServerUrl);
97
- }
98
- },
99
- configureServer(server) {
100
- const envDir = resolvedConfig.envDir || process.cwd();
101
- const appUrl = loadEnv(resolvedConfig.mode, envDir, "APP_URL").APP_URL ?? "undefined";
102
- server.httpServer?.once("listening", () => {
103
- const address = server.httpServer?.address();
104
- const isAddressInfo = (x) => typeof x === "object";
105
- if (isAddressInfo(address)) {
106
- viteDevServerUrl = userConfig.server?.origin ? userConfig.server.origin : resolveDevServerUrl(
107
- address,
108
- server.config,
109
- userConfig
110
- );
111
- fs.mkdirSync(path.dirname(pluginConfig.hotFile), { recursive: true });
112
- fs.writeFileSync(pluginConfig.hotFile, viteDevServerUrl);
113
- setTimeout(() => {
114
- server.config.logger.info(
115
- `
116
- ${colors.red(
117
- `${colors.bold(
118
- "LITESTAR"
119
- )} ${litestarVersion()}`
120
- )} ${colors.dim("plugin")} ${colors.bold(
121
- `v${pluginVersion()}`
122
- )}`
123
- );
124
- server.config.logger.info("");
125
- server.config.logger.info(
126
- ` ${colors.green("\u279C")} ${colors.bold(
127
- "APP_URL"
128
- )}: ${colors.cyan(
129
- appUrl.replace(
130
- /:(\d+)/,
131
- (_, port) => `:${colors.bold(port)}`
132
- )
133
- )}`
134
- );
135
- }, 100);
136
- }
137
- });
138
- if (!exitHandlersBound) {
139
- const clean = () => {
140
- if (fs.existsSync(pluginConfig.hotFile)) {
141
- fs.rmSync(pluginConfig.hotFile);
142
- }
143
- };
144
- process.on("exit", clean);
145
- process.on("SIGINT", () => process.exit());
146
- process.on("SIGTERM", () => process.exit());
147
- process.on("SIGHUP", () => process.exit());
148
- exitHandlersBound = true;
149
- }
150
- return () => server.middlewares.use((req, res, next) => {
151
- if (req.url === "/index.html") {
152
- res.statusCode = 404;
153
- res.end(
154
- fs.readFileSync(
155
- path.join(
156
- dirname(),
157
- "dev-server-index.html"
158
- )
159
- ).toString().replace(/{{ APP_URL }}/g, appUrl)
160
- );
161
- }
162
- next();
163
- });
164
- }
165
- };
166
- }
167
- function ensureCommandShouldRunInEnvironment(command, env) {
168
- const validEnvironmentNames = ["dev", "development", "local", "docker"];
169
- if (command === "build" || env.LITESTAR_BYPASS_ENV_CHECK === "1") {
170
- return;
171
- }
172
- if (typeof env.LITESTAR_MODE !== "undefined" && validEnvironmentNames.some((e) => e === env.LITESTAR_MODE)) {
173
- throw Error(
174
- "You should only run Vite dev server when Litestar is development mode. You should build your assets for production instead. To disable this ENV check you may set LITESTAR_BYPASS_ENV_CHECK=1"
175
- );
176
- }
177
- if (typeof env.CI !== "undefined") {
178
- throw Error(
179
- "You should not run the Vite HMR server in CI environments. You should build your assets for production instead. To disable this ENV check you may set LITESTAR_BYPASS_ENV_CHECK=1"
180
- );
181
- }
182
- }
183
- function litestarVersion() {
184
- return "";
185
- }
186
- function pluginVersion() {
187
- try {
188
- return JSON.parse(
189
- fs.readFileSync(path.join(dirname(), "../package.json")).toString()
190
- )?.version;
191
- } catch {
192
- return "";
193
- }
194
- }
195
- function resolvePluginConfig(config) {
196
- if (typeof config === "undefined") {
197
- throw new Error("litestar-vite-plugin: missing configuration.");
198
- }
199
- if (typeof config === "string" || Array.isArray(config)) {
200
- config = { input: config, ssr: config };
201
- }
202
- if (typeof config.input === "undefined") {
203
- throw new Error(
204
- 'litestar-vite-plugin: missing configuration for "input".'
205
- );
206
- }
207
- if (typeof config.resourceDirectory === "string") {
208
- config.resourceDirectory = config.resourceDirectory.trim().replace(/^\/+/, "");
209
- if (config.resourceDirectory === "") {
210
- throw new Error(
211
- "litestar-vite-plugin: resourceDirectory must be a subdirectory. E.g. 'resources'."
212
- );
213
- }
214
- }
215
- if (typeof config.bundleDirectory === "string") {
216
- config.bundleDirectory = config.bundleDirectory.trim().replace(/^\/+/, "").replace(/\/+$/, "");
217
- if (config.bundleDirectory === "") {
218
- throw new Error(
219
- "litestar-vite-plugin: bundleDirectory must be a subdirectory. E.g. 'public'."
220
- );
221
- }
222
- }
223
- if (typeof config.ssrOutputDirectory === "string") {
224
- config.ssrOutputDirectory = config.ssrOutputDirectory.trim().replace(/^\/+/, "").replace(/\/+$/, "");
225
- }
226
- if (config.refresh === true) {
227
- config.refresh = [{ paths: refreshPaths }];
228
- }
229
- return {
230
- input: config.input,
231
- assetUrl: config.assetUrl ?? "static",
232
- resourceDirectory: config.resourceDirectory ?? "/resources/",
233
- bundleDirectory: config.bundleDirectory || (config.bundleDirectory ?? "public"),
234
- ssr: config.ssr ?? config.input,
235
- ssrOutputDirectory: config.ssrOutputDirectory ?? path.join(config.resourceDirectory ?? "resources", "bootstrap/ssr"),
236
- refresh: config.refresh ?? false,
237
- hotFile: config.hotFile ?? path.join(config.bundleDirectory ?? "public", "hot"),
238
- detectTls: config.detectTls ?? false,
239
- transformOnServe: config.transformOnServe ?? ((code) => code)
240
- };
241
- }
242
- function resolveBase(config, assetUrl) {
243
- return assetUrl + (assetUrl.endsWith("/") ? "" : "/");
244
- }
245
- function resolveInput(config, ssr) {
246
- if (ssr) {
247
- return config.ssr;
248
- }
249
- return config.input;
250
- }
251
- function resolveOutDir(config, ssr) {
252
- if (ssr) {
253
- return config.ssrOutputDirectory;
254
- }
255
- return path.join(config.bundleDirectory);
256
- }
257
- function resolveFullReloadConfig({
258
- refresh: config
259
- }) {
260
- if (typeof config === "boolean") {
261
- return [];
262
- }
263
- if (typeof config === "string") {
264
- config = [{ paths: [config] }];
265
- }
266
- if (!Array.isArray(config)) {
267
- config = [config];
268
- }
269
- if (config.some((c) => typeof c === "string")) {
270
- config = [{ paths: config }];
271
- }
272
- return config.flatMap((c) => {
273
- const plugin = fullReload(c.paths, c.config);
274
- plugin.__litestar_plugin_config = c;
275
- return plugin;
276
- });
277
- }
278
- function resolveDevServerUrl(address, config, userConfig) {
279
- const configHmrProtocol = typeof config.server.hmr === "object" ? config.server.hmr.protocol : null;
280
- const clientProtocol = configHmrProtocol ? configHmrProtocol === "wss" ? "https" : "http" : null;
281
- const serverProtocol = config.server.https ? "https" : "http";
282
- const protocol = clientProtocol ?? serverProtocol;
283
- const configHmrHost = typeof config.server.hmr === "object" ? config.server.hmr.host : null;
284
- const configHost = typeof config.server.host === "string" ? config.server.host : null;
285
- const remoteHost = process.env.VITE_ALLOW_REMOTE && !userConfig.server?.host ? "localhost" : null;
286
- const serverAddress = isIpv6(address) ? `[${address.address}]` : address.address;
287
- const host = configHmrHost ?? remoteHost ?? configHost ?? serverAddress;
288
- const configHmrClientPort = typeof config.server.hmr === "object" ? config.server.hmr.clientPort : null;
289
- const port = configHmrClientPort ?? address.port;
290
- return `${protocol}://${host}:${port}`;
291
- }
292
- function isIpv6(address) {
293
- return address.family === "IPv6" || address.family === 6;
294
- }
295
- function noExternalInertiaHelpers(config) {
296
- const userNoExternal = config.ssr?.noExternal;
297
- const pluginNoExternal = ["litestar-vite-plugin"];
298
- if (userNoExternal === true) {
299
- return true;
300
- }
301
- if (typeof userNoExternal === "undefined") {
302
- return pluginNoExternal;
303
- }
304
- return [
305
- ...Array.isArray(userNoExternal) ? userNoExternal : [userNoExternal],
306
- ...pluginNoExternal
307
- ];
308
- }
309
- function resolveEnvironmentServerConfig(env) {
310
- if (!env.VITE_SERVER_KEY && !env.VITE_SERVER_CERT) {
311
- return;
312
- }
313
- if (!fs.existsSync(env.VITE_SERVER_KEY) || !fs.existsSync(env.VITE_SERVER_CERT)) {
314
- throw Error(
315
- `Unable to find the certificate files specified in your environment. Ensure you have correctly configured VITE_SERVER_KEY: [${env.VITE_SERVER_KEY}] and VITE_SERVER_CERT: [${env.VITE_SERVER_CERT}].`
316
- );
317
- }
318
- const host = resolveHostFromEnv(env);
319
- if (!host) {
320
- throw Error(
321
- `Unable to determine the host from the environment's APP_URL: [${env.APP_URL}].`
322
- );
323
- }
324
- return {
325
- hmr: { host },
326
- host,
327
- https: {
328
- key: fs.readFileSync(env.VITE_DEV_SERVER_KEY),
329
- cert: fs.readFileSync(env.VITE_DEV_SERVER_CERT)
330
- }
331
- };
332
- }
333
- function resolveHostFromEnv(env) {
334
- try {
335
- return new URL(env.APP_URL).host;
336
- } catch {
337
- return;
338
- }
339
- }
340
- function resolveDevelopmentEnvironmentServerConfig(host) {
341
- if (host === false) {
342
- return;
343
- }
344
- const configPath = determineDevelopmentEnvironmentConfigPath();
345
- if (typeof configPath === "undefined" && host === null) {
346
- return;
347
- }
348
- if (typeof configPath === "undefined") {
349
- throw Error(
350
- `Unable to find the Herd or Valet configuration directory. Please check they are correctly installed.`
351
- );
352
- }
353
- const resolvedHost = host === true || host === null ? path.basename(process.cwd()) + "." + resolveDevelopmentEnvironmentTld(configPath) : host;
354
- const keyPath = path.resolve(
355
- configPath,
356
- "certs",
357
- `${resolvedHost}.key`
358
- );
359
- const certPath = path.resolve(
360
- configPath,
361
- "certs",
362
- `${resolvedHost}.crt`
363
- );
364
- if ((!fs.existsSync(keyPath) || !fs.existsSync(certPath)) && host === null) {
365
- throw Error(
366
- `Unable to find certificate files for your host [${host}] in the [${configPath}/certs] directory.`
367
- );
368
- }
369
- return {
370
- hmr: { host: resolvedHost },
371
- host: resolvedHost,
372
- https: {
373
- key: keyPath,
374
- cert: certPath
375
- }
376
- };
377
- }
378
- function determineDevelopmentEnvironmentConfigPath() {
379
- const envConfigPath = path.resolve(process.cwd(), ".config");
380
- if (fs.existsSync(envConfigPath)) {
381
- return envConfigPath;
382
- }
383
- return path.resolve(process.cwd(), ".config");
384
- }
385
- function resolveDevelopmentEnvironmentTld(configPath) {
386
- const configFile = path.resolve(configPath, "config.json");
387
- if (!fs.existsSync(configFile)) {
388
- throw Error(`Unable to find the configuration file [${configFile}].`);
389
- }
390
- const config = JSON.parse(
391
- fs.readFileSync(configFile, "utf-8")
392
- );
393
- return config.tld;
394
- }
395
- function dirname() {
396
- return fileURLToPath(new URL(".", import.meta.url));
397
- }
398
- export {
399
- litestar as default,
400
- refreshPaths
401
- };
@@ -1,17 +0,0 @@
1
- export declare function resolvePageComponent<T>(path: string | string[], pages: Record<string, Promise<T> | (() => Promise<T>)>): Promise<T>;
2
- export declare function route(routeName: string, ...args: any[]): string;
3
- export declare function getRelativeUrlPath(url: string): string;
4
- export declare function toRoute(url: string): string | null;
5
- export declare function currentRoute(): string | null;
6
- export declare function isRoute(url: string, routeName: string): boolean;
7
- export declare function isCurrentRoute(routeName: string): boolean;
8
- declare global {
9
- var routes: {
10
- [key: string]: string;
11
- };
12
- function route(routeName: string, ...args: any[]): string;
13
- function toRoute(url: string): string | null;
14
- function currentRoute(): string | null;
15
- function isRoute(url: string, routeName: string): boolean;
16
- function isCurrentRoute(routeName: string): boolean;
17
- }
@@ -1,138 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
- export async function resolvePageComponent(path, pages) {
3
- for (const p of Array.isArray(path) ? path : [path]) {
4
- const page = pages[p];
5
- if (typeof page === "undefined") {
6
- continue;
7
- }
8
- return typeof page === "function" ? page() : page;
9
- }
10
- throw new Error(`Page not found: ${path}`);
11
- }
12
- export function route(routeName, ...args) {
13
- let url = globalThis.routes[routeName];
14
- if (!url) {
15
- console.error(`URL '${routeName}' not found in routes.`);
16
- return "#"; // Return "#" to indicate failure
17
- }
18
- const argTokens = url.match(/\{([^}]+):([^}]+)\}/g);
19
- if (!argTokens && args.length > 0) {
20
- console.error(`Invalid URL lookup: URL '${routeName}' does not expect arguments.`);
21
- return "#";
22
- }
23
- try {
24
- if (typeof args[0] === "object" && !Array.isArray(args[0])) {
25
- argTokens?.forEach((token) => {
26
- let argName = token.slice(1, -1);
27
- if (argName.includes(":")) {
28
- argName = argName.split(":")[1];
29
- }
30
- const argValue = args[0][argName];
31
- if (argValue === undefined) {
32
- throw new Error(`Invalid URL lookup: Argument '${argName}' was not provided.`);
33
- }
34
- url = url.replace(token, argValue.toString());
35
- });
36
- }
37
- else {
38
- const argsArray = Array.isArray(args[0])
39
- ? args[0]
40
- : Array.prototype.slice.call(args);
41
- if (argTokens && argTokens.length !== argsArray.length) {
42
- throw new Error(`Invalid URL lookup: Wrong number of arguments; expected ${argTokens.length.toString()} arguments.`);
43
- }
44
- argTokens?.forEach((token, i) => {
45
- const argValue = argsArray[i];
46
- url = url.replace(token, argValue.toString());
47
- });
48
- }
49
- }
50
- catch (error) {
51
- console.error(error.message);
52
- return "#";
53
- }
54
- const fullUrl = new URL(url, window.location.origin);
55
- return fullUrl.href;
56
- }
57
- export function getRelativeUrlPath(url) {
58
- try {
59
- const urlObject = new URL(url);
60
- return urlObject.pathname + urlObject.search + urlObject.hash;
61
- }
62
- catch (e) {
63
- // If the URL is invalid or already a relative path, just return it as is
64
- return url;
65
- }
66
- }
67
- function routePatternToRegex(pattern) {
68
- return new RegExp('^' + pattern.replace(/\*/g, '.*') + '$');
69
- }
70
- export function toRoute(url) {
71
- url = getRelativeUrlPath(url);
72
- url = url === '/' ? url : url.replace(/\/$/, '');
73
- for (const routeName in routes) {
74
- const routePattern = routes[routeName];
75
- const regexPattern = routePattern.replace(/\//g, '\\/').replace(/\{([^}]+):([^}]+)\}/g, (match, paramName, paramType) => {
76
- // Create a regex pattern based on the parameter type
77
- switch (paramType) {
78
- case 'str':
79
- case 'path':
80
- return '([^/]+)'; // Match any non-slash characters
81
- case 'uuid':
82
- return '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'; // Match a UUID pattern
83
- default:
84
- return '([^/]+)'; // Default to match any non-slash characters
85
- }
86
- });
87
- const regex = new RegExp(`^${regexPattern}$`);
88
- if (regex.test(url)) {
89
- return routeName;
90
- }
91
- }
92
- return null; // No matching route found
93
- }
94
- export function currentRoute() {
95
- const currentUrl = window.location.pathname;
96
- return toRoute(currentUrl);
97
- }
98
- export function isRoute(url, routeName) {
99
- url = getRelativeUrlPath(url);
100
- url = url === '/' ? url : url.replace(/\/$/, '');
101
- const routeNameRegex = routePatternToRegex(routeName);
102
- for (const routeName in routes) {
103
- if (routeNameRegex.test(routeName)) {
104
- const routePattern = routes[routeName];
105
- const regexPattern = routePattern.replace(/\//g, '\\/').replace(/\{([^}]+):([^}]+)\}/g, (match, paramName, paramType) => {
106
- switch (paramType) {
107
- case 'str':
108
- case 'path':
109
- return '([^/]+)';
110
- case 'uuid':
111
- return '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
112
- default:
113
- return '([^/]+)';
114
- }
115
- });
116
- const regex = new RegExp(`^${regexPattern}$`);
117
- if (regex.test(url)) {
118
- return true;
119
- }
120
- }
121
- }
122
- return false;
123
- }
124
- export function isCurrentRoute(routeName) {
125
- const currentRouteName = currentRoute();
126
- if (!currentRouteName) {
127
- console.error("Could not match current window location to a named route.");
128
- return false;
129
- }
130
- const routeNameRegex = routePatternToRegex(routeName);
131
- return routeNameRegex.test(currentRouteName);
132
- }
133
- globalThis.routes = globalThis.routes || {};
134
- globalThis.route = route;
135
- globalThis.toRoute = toRoute;
136
- globalThis.currentRoute = currentRoute;
137
- globalThis.isRoute = isRoute;
138
- globalThis.isCurrentRoute = isCurrentRoute;