litestar-vite-plugin 0.8.2 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,185 @@
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>
@@ -0,0 +1,75 @@
1
+ import { type ConfigEnv, type Plugin, type UserConfig } from "vite";
2
+ import { type 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 {};
@@ -0,0 +1,335 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
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 = ["**/*.py", "**/*.j2", "**/*.html.j2", "**/*.html", "**/assets/**/*"];
9
+ function litestar(config) {
10
+ const pluginConfig = resolvePluginConfig(config);
11
+ return [resolveLitestarPlugin(pluginConfig), ...resolveFullReloadConfig(pluginConfig)];
12
+ }
13
+ function resolveLitestarPlugin(pluginConfig) {
14
+ let viteDevServerUrl;
15
+ let resolvedConfig;
16
+ let userConfig;
17
+ const defaultAliases = {
18
+ "@": pluginConfig.resourceDirectory || "/resources/"
19
+ };
20
+ return {
21
+ name: "litestar",
22
+ enforce: "post",
23
+ config: (config, { command, mode }) => {
24
+ userConfig = config;
25
+ const ssr = !!userConfig.build?.ssr;
26
+ const env = loadEnv(mode, userConfig.envDir || process.cwd(), "");
27
+ const assetUrl = env.ASSET_URL || pluginConfig.assetUrl;
28
+ const serverConfig = command === "serve" ? resolveDevelopmentEnvironmentServerConfig(pluginConfig.detectTls) ?? resolveEnvironmentServerConfig(env) : void 0;
29
+ ensureCommandShouldRunInEnvironment(command, env);
30
+ return {
31
+ base: userConfig.base ?? (command === "build" ? resolveBase(pluginConfig, assetUrl) : pluginConfig.assetUrl),
32
+ publicDir: userConfig.publicDir ?? false,
33
+ clearScreen: false,
34
+ build: {
35
+ manifest: userConfig.build?.manifest ?? (ssr ? false : "manifest.json"),
36
+ ssrManifest: userConfig.build?.ssrManifest ?? (ssr ? "ssr-manifest.json" : false),
37
+ outDir: userConfig.build?.outDir ?? resolveOutDir(pluginConfig, ssr),
38
+ rollupOptions: {
39
+ input: userConfig.build?.rollupOptions?.input ?? resolveInput(pluginConfig, ssr)
40
+ },
41
+ assetsInlineLimit: userConfig.build?.assetsInlineLimit ?? 0
42
+ },
43
+ server: {
44
+ origin: userConfig.server?.origin ?? "__litestar_vite_placeholder__",
45
+ ...process.env.VITE_ALLOW_REMOTE ? {
46
+ host: userConfig.server?.host ?? "0.0.0.0",
47
+ port: userConfig.server?.port ?? (env.VITE_PORT ? Number.parseInt(env.VITE_PORT) : 5173),
48
+ strictPort: userConfig.server?.strictPort ?? true
49
+ } : void 0,
50
+ ...serverConfig ? {
51
+ host: userConfig.server?.host ?? serverConfig.host,
52
+ hmr: userConfig.server?.hmr === false ? false : {
53
+ ...serverConfig.hmr,
54
+ ...userConfig.server?.hmr === true ? {} : userConfig.server?.hmr
55
+ },
56
+ https: userConfig.server?.https ?? serverConfig.https
57
+ } : void 0
58
+ },
59
+ resolve: {
60
+ alias: Array.isArray(userConfig.resolve?.alias) ? [
61
+ ...userConfig.resolve?.alias ?? [],
62
+ ...Object.keys(defaultAliases).map((alias) => ({
63
+ find: alias,
64
+ replacement: defaultAliases[alias]
65
+ }))
66
+ ] : {
67
+ ...defaultAliases,
68
+ ...userConfig.resolve?.alias
69
+ }
70
+ },
71
+ ssr: {
72
+ noExternal: noExternalInertiaHelpers(userConfig)
73
+ }
74
+ };
75
+ },
76
+ configResolved(config) {
77
+ resolvedConfig = config;
78
+ },
79
+ transform(code) {
80
+ if (resolvedConfig.command === "serve") {
81
+ const transformedCode = code.replace(/__litestar_vite_placeholder__/g, viteDevServerUrl);
82
+ return pluginConfig.transformOnServe(transformedCode, viteDevServerUrl);
83
+ }
84
+ return void 0;
85
+ },
86
+ configureServer(server) {
87
+ const envDir = resolvedConfig.envDir || process.cwd();
88
+ const appUrl = loadEnv(resolvedConfig.mode, envDir, "APP_URL").APP_URL ?? "undefined";
89
+ server.httpServer?.once("listening", () => {
90
+ const address = server.httpServer?.address();
91
+ const isAddressInfo = (x) => typeof x === "object";
92
+ if (isAddressInfo(address)) {
93
+ viteDevServerUrl = userConfig.server?.origin ? userConfig.server.origin : resolveDevServerUrl(address, server.config, userConfig);
94
+ fs.mkdirSync(path.dirname(pluginConfig.hotFile), { recursive: true });
95
+ fs.writeFileSync(pluginConfig.hotFile, viteDevServerUrl);
96
+ setTimeout(() => {
97
+ server.config.logger.info(`
98
+ ${colors.red(`${colors.bold("LITESTAR")} ${litestarVersion()}`)} ${colors.dim("plugin")} ${colors.bold(`v${pluginVersion()}`)}`);
99
+ server.config.logger.info("");
100
+ server.config.logger.info(` ${colors.green("\u279C")} ${colors.bold("APP_URL")}: ${colors.cyan(appUrl.replace(/:(\d+)/, (_, port) => `:${colors.bold(port)}`))}`);
101
+ }, 100);
102
+ }
103
+ });
104
+ if (!exitHandlersBound) {
105
+ const clean = () => {
106
+ if (fs.existsSync(pluginConfig.hotFile)) {
107
+ fs.rmSync(pluginConfig.hotFile);
108
+ }
109
+ };
110
+ process.on("exit", clean);
111
+ process.on("SIGINT", () => process.exit());
112
+ process.on("SIGTERM", () => process.exit());
113
+ process.on("SIGHUP", () => process.exit());
114
+ exitHandlersBound = true;
115
+ }
116
+ return () => server.middlewares.use((req, res, next) => {
117
+ if (req.url === "/index.html") {
118
+ res.statusCode = 404;
119
+ res.end(
120
+ fs.readFileSync(path.join(dirname(), "dev-server-index.html")).toString().replace(/{{ APP_URL }}/g, appUrl)
121
+ );
122
+ }
123
+ next();
124
+ });
125
+ }
126
+ };
127
+ }
128
+ function ensureCommandShouldRunInEnvironment(command, env) {
129
+ const validEnvironmentNames = ["dev", "development", "local", "docker"];
130
+ if (command === "build" || env.LITESTAR_BYPASS_ENV_CHECK === "1") {
131
+ return;
132
+ }
133
+ if (typeof env.LITESTAR_MODE !== "undefined" && validEnvironmentNames.some((e) => e === env.LITESTAR_MODE)) {
134
+ throw Error(
135
+ "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"
136
+ );
137
+ }
138
+ if (typeof env.CI !== "undefined") {
139
+ throw Error(
140
+ "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"
141
+ );
142
+ }
143
+ }
144
+ function litestarVersion() {
145
+ return "";
146
+ }
147
+ function pluginVersion() {
148
+ try {
149
+ return JSON.parse(fs.readFileSync(path.join(dirname(), "../package.json")).toString())?.version;
150
+ } catch {
151
+ return "";
152
+ }
153
+ }
154
+ function resolvePluginConfig(config) {
155
+ if (typeof config === "undefined") {
156
+ throw new Error("litestar-vite-plugin: missing configuration.");
157
+ }
158
+ const resolvedConfig = typeof config === "string" || Array.isArray(config) ? { input: config, ssr: config } : config;
159
+ if (typeof resolvedConfig.input === "undefined") {
160
+ throw new Error('litestar-vite-plugin: missing configuration for "input".');
161
+ }
162
+ if (typeof resolvedConfig.resourceDirectory === "string") {
163
+ resolvedConfig.resourceDirectory = resolvedConfig.resourceDirectory.trim().replace(/^\/+/, "");
164
+ if (resolvedConfig.resourceDirectory === "") {
165
+ throw new Error("litestar-vite-plugin: resourceDirectory must be a subdirectory. E.g. 'resources'.");
166
+ }
167
+ }
168
+ if (typeof resolvedConfig.bundleDirectory === "string") {
169
+ resolvedConfig.bundleDirectory = resolvedConfig.bundleDirectory.trim().replace(/^\/+/, "").replace(/\/+$/, "");
170
+ if (resolvedConfig.bundleDirectory === "") {
171
+ throw new Error("litestar-vite-plugin: bundleDirectory must be a subdirectory. E.g. 'public'.");
172
+ }
173
+ }
174
+ if (typeof resolvedConfig.ssrOutputDirectory === "string") {
175
+ resolvedConfig.ssrOutputDirectory = resolvedConfig.ssrOutputDirectory.trim().replace(/^\/+/, "").replace(/\/+$/, "");
176
+ }
177
+ if (resolvedConfig.refresh === true) {
178
+ resolvedConfig.refresh = [{ paths: refreshPaths }];
179
+ }
180
+ return {
181
+ input: resolvedConfig.input,
182
+ assetUrl: resolvedConfig.assetUrl ?? "static",
183
+ resourceDirectory: resolvedConfig.resourceDirectory ?? "/resources/",
184
+ bundleDirectory: resolvedConfig.bundleDirectory || (resolvedConfig.bundleDirectory ?? "public"),
185
+ ssr: resolvedConfig.ssr ?? resolvedConfig.input,
186
+ ssrOutputDirectory: resolvedConfig.ssrOutputDirectory ?? path.join(resolvedConfig.resourceDirectory ?? "resources", "bootstrap/ssr"),
187
+ refresh: resolvedConfig.refresh ?? false,
188
+ hotFile: resolvedConfig.hotFile ?? path.join(resolvedConfig.bundleDirectory ?? "public", "hot"),
189
+ detectTls: resolvedConfig.detectTls ?? false,
190
+ transformOnServe: resolvedConfig.transformOnServe ?? ((code) => code)
191
+ };
192
+ }
193
+ function resolveBase(config, assetUrl) {
194
+ return assetUrl + (assetUrl.endsWith("/") ? "" : "/");
195
+ }
196
+ function resolveInput(config, ssr) {
197
+ if (ssr) {
198
+ return config.ssr;
199
+ }
200
+ return config.input;
201
+ }
202
+ function resolveOutDir(config, ssr) {
203
+ if (ssr) {
204
+ return config.ssrOutputDirectory;
205
+ }
206
+ return path.join(config.bundleDirectory);
207
+ }
208
+ function resolveFullReloadConfig({ refresh: config }) {
209
+ if (typeof config === "boolean") {
210
+ return [];
211
+ }
212
+ if (typeof config === "string") {
213
+ config = [{ paths: [config] }];
214
+ }
215
+ if (!Array.isArray(config)) {
216
+ config = [config];
217
+ }
218
+ if (config.some((c) => typeof c === "string")) {
219
+ config = [{ paths: config }];
220
+ }
221
+ return config.flatMap((c) => {
222
+ const plugin = fullReload(c.paths, c.config);
223
+ plugin.__litestar_plugin_config = c;
224
+ return plugin;
225
+ });
226
+ }
227
+ function resolveDevServerUrl(address, config, userConfig) {
228
+ const configHmrProtocol = typeof config.server.hmr === "object" ? config.server.hmr.protocol : null;
229
+ const clientProtocol = configHmrProtocol ? configHmrProtocol === "wss" ? "https" : "http" : null;
230
+ const serverProtocol = config.server.https ? "https" : "http";
231
+ const protocol = clientProtocol ?? serverProtocol;
232
+ const configHmrHost = typeof config.server.hmr === "object" ? config.server.hmr.host : null;
233
+ const configHost = typeof config.server.host === "string" ? config.server.host : null;
234
+ const remoteHost = process.env.VITE_ALLOW_REMOTE && !userConfig.server?.host ? "localhost" : null;
235
+ const serverAddress = isIpv6(address) ? `[${address.address}]` : address.address;
236
+ const host = configHmrHost ?? remoteHost ?? configHost ?? serverAddress;
237
+ const configHmrClientPort = typeof config.server.hmr === "object" ? config.server.hmr.clientPort : null;
238
+ const port = configHmrClientPort ?? address.port;
239
+ return `${protocol}://${host}:${port}`;
240
+ }
241
+ function isIpv6(address) {
242
+ return address.family === "IPv6" || // In node >=18.0 <18.4 this was an integer value. This was changed in a minor version.
243
+ // See: https://github.com/laravel/vite-plugin/issues/103
244
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
245
+ // @ts-ignore-next-line
246
+ address.family === 6;
247
+ }
248
+ function noExternalInertiaHelpers(config) {
249
+ const userNoExternal = config.ssr?.noExternal;
250
+ const pluginNoExternal = ["litestar-vite-plugin"];
251
+ if (userNoExternal === true) {
252
+ return true;
253
+ }
254
+ if (typeof userNoExternal === "undefined") {
255
+ return pluginNoExternal;
256
+ }
257
+ return [...Array.isArray(userNoExternal) ? userNoExternal : [userNoExternal], ...pluginNoExternal];
258
+ }
259
+ function resolveEnvironmentServerConfig(env) {
260
+ if (!env.VITE_SERVER_KEY && !env.VITE_SERVER_CERT) {
261
+ return;
262
+ }
263
+ if (!fs.existsSync(env.VITE_SERVER_KEY) || !fs.existsSync(env.VITE_SERVER_CERT)) {
264
+ throw Error(
265
+ `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}].`
266
+ );
267
+ }
268
+ const host = resolveHostFromEnv(env);
269
+ if (!host) {
270
+ throw Error(`Unable to determine the host from the environment's APP_URL: [${env.APP_URL}].`);
271
+ }
272
+ return {
273
+ hmr: { host },
274
+ host,
275
+ https: {
276
+ key: fs.readFileSync(env.VITE_DEV_SERVER_KEY),
277
+ cert: fs.readFileSync(env.VITE_DEV_SERVER_CERT)
278
+ }
279
+ };
280
+ }
281
+ function resolveHostFromEnv(env) {
282
+ try {
283
+ return new URL(env.APP_URL).host;
284
+ } catch {
285
+ return;
286
+ }
287
+ }
288
+ function resolveDevelopmentEnvironmentServerConfig(host) {
289
+ if (host === false) {
290
+ return;
291
+ }
292
+ const configPath = determineDevelopmentEnvironmentConfigPath();
293
+ if (typeof configPath === "undefined" && host === null) {
294
+ return;
295
+ }
296
+ if (typeof configPath === "undefined") {
297
+ throw Error("Unable to find the Herd or Valet configuration directory. Please check they are correctly installed.");
298
+ }
299
+ const resolvedHost = host === true || host === null ? `${path.basename(process.cwd())}.${resolveDevelopmentEnvironmentTld(configPath)}` : host;
300
+ const keyPath = path.resolve(configPath, "certs", `${resolvedHost}.key`);
301
+ const certPath = path.resolve(configPath, "certs", `${resolvedHost}.crt`);
302
+ if ((!fs.existsSync(keyPath) || !fs.existsSync(certPath)) && host === null) {
303
+ throw Error(`Unable to find certificate files for your host [${host}] in the [${configPath}/certs] directory.`);
304
+ }
305
+ return {
306
+ hmr: { host: resolvedHost },
307
+ host: resolvedHost,
308
+ https: {
309
+ key: keyPath,
310
+ cert: certPath
311
+ }
312
+ };
313
+ }
314
+ function determineDevelopmentEnvironmentConfigPath() {
315
+ const envConfigPath = path.resolve(process.cwd(), ".config");
316
+ if (fs.existsSync(envConfigPath)) {
317
+ return envConfigPath;
318
+ }
319
+ return path.resolve(process.cwd(), ".config");
320
+ }
321
+ function resolveDevelopmentEnvironmentTld(configPath) {
322
+ const configFile = path.resolve(configPath, "config.json");
323
+ if (!fs.existsSync(configFile)) {
324
+ throw Error(`Unable to find the configuration file [${configFile}].`);
325
+ }
326
+ const config = JSON.parse(fs.readFileSync(configFile, "utf-8"));
327
+ return config.tld;
328
+ }
329
+ function dirname() {
330
+ return fileURLToPath(new URL(".", import.meta.url));
331
+ }
332
+ export {
333
+ litestar as default,
334
+ refreshPaths
335
+ };
@@ -0,0 +1,20 @@
1
+ export declare function resolvePageComponent<T>(path: string | string[], pages: Record<string, Promise<T> | (() => Promise<T>)>): Promise<T>;
2
+ type RouteArg = string | number | boolean;
3
+ type RouteArgs = Record<string, RouteArg> | RouteArg[];
4
+ export declare function route(routeName: string, ...args: [RouteArgs?]): string;
5
+ export declare function getRelativeUrlPath(url: string): string;
6
+ export declare function toRoute(url: string): string | null;
7
+ export declare function currentRoute(): string | null;
8
+ export declare function isRoute(url: string, routeName: string): boolean;
9
+ export declare function isCurrentRoute(routeName: string): boolean;
10
+ declare global {
11
+ var routes: {
12
+ [key: string]: string;
13
+ };
14
+ function route(routeName: string, ...args: [RouteArgs?]): string;
15
+ function toRoute(url: string): string | null;
16
+ function currentRoute(): string | null;
17
+ function isRoute(url: string, routeName: string): boolean;
18
+ function isCurrentRoute(routeName: string): boolean;
19
+ }
20
+ export {};
@@ -0,0 +1,137 @@
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
+ for (const token of argTokens ?? []) {
26
+ let argName = token.slice(1, -1);
27
+ if (argName.includes(":")) {
28
+ argName = argName.split(":")[0];
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, String(argValue));
35
+ }
36
+ }
37
+ else {
38
+ const argsArray = Array.isArray(args[0]) ? args[0] : Array.from(args);
39
+ if (argTokens && argTokens.length !== argsArray.length) {
40
+ throw new Error(`Invalid URL lookup: Wrong number of arguments; expected ${argTokens.length.toString()} arguments.`);
41
+ }
42
+ argTokens?.forEach((token, i) => {
43
+ const argValue = argsArray[i];
44
+ if (argValue === undefined) {
45
+ throw new Error(`Missing argument at position ${i}`);
46
+ }
47
+ url = url.replace(token, argValue.toString());
48
+ });
49
+ }
50
+ }
51
+ catch (error) {
52
+ console.error(error instanceof Error ? error.message : String(error));
53
+ return "#";
54
+ }
55
+ const fullUrl = new URL(url, window.location.origin);
56
+ return fullUrl.href;
57
+ }
58
+ export function getRelativeUrlPath(url) {
59
+ try {
60
+ const urlObject = new URL(url);
61
+ return urlObject.pathname + urlObject.search + urlObject.hash;
62
+ }
63
+ catch (e) {
64
+ // If the URL is invalid or already a relative path, just return it as is
65
+ return url;
66
+ }
67
+ }
68
+ function routePatternToRegex(pattern) {
69
+ return new RegExp(`^${pattern.replace(/\*/g, ".*")}$`);
70
+ }
71
+ export function toRoute(url) {
72
+ const processedUrl = getRelativeUrlPath(url);
73
+ const normalizedUrl = processedUrl === "/" ? processedUrl : processedUrl.replace(/\/$/, "");
74
+ for (const [routeName, routePattern] of Object.entries(routes)) {
75
+ const regexPattern = routePattern.replace(/\//g, "\\/").replace(/\{([^}]+):([^}]+)\}/g, (_, __, paramType) => {
76
+ switch (paramType) {
77
+ case "uuid":
78
+ return "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
79
+ case "path":
80
+ return ".*"; // Matches any characters including forward slashes
81
+ default:
82
+ return "[^/]+"; // Matches any characters except forward slashes
83
+ }
84
+ });
85
+ const regex = new RegExp(`^${regexPattern}$`);
86
+ if (regex.test(normalizedUrl)) {
87
+ return routeName;
88
+ }
89
+ }
90
+ return null;
91
+ }
92
+ export function currentRoute() {
93
+ const currentUrl = window.location.pathname;
94
+ return toRoute(currentUrl);
95
+ }
96
+ export function isRoute(url, routeName) {
97
+ const processedUrl = getRelativeUrlPath(url);
98
+ const normalizedUrl = processedUrl === "/" ? processedUrl : processedUrl.replace(/\/$/, "");
99
+ const routeNameRegex = routePatternToRegex(routeName);
100
+ // Find all matching route names based on the pattern
101
+ const matchingRouteNames = Object.keys(routes).filter((name) => routeNameRegex.test(name));
102
+ // For each matching route name, check if the URL matches its pattern
103
+ for (const name of matchingRouteNames) {
104
+ const routePattern = routes[name];
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(normalizedUrl)) {
118
+ return true;
119
+ }
120
+ }
121
+ return false;
122
+ }
123
+ export function isCurrentRoute(routeName) {
124
+ const currentRouteName = currentRoute();
125
+ if (!currentRouteName) {
126
+ console.error("Could not match current window location to a named route.");
127
+ return false;
128
+ }
129
+ const routeNameRegex = routePatternToRegex(routeName);
130
+ return routeNameRegex.test(currentRouteName);
131
+ }
132
+ globalThis.routes = globalThis.routes || {};
133
+ globalThis.route = route;
134
+ globalThis.toRoute = toRoute;
135
+ globalThis.currentRoute = currentRoute;
136
+ globalThis.isRoute = isRoute;
137
+ globalThis.isCurrentRoute = isCurrentRoute;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "litestar-vite-plugin",
3
- "version": "0.8.2",
3
+ "version": "0.8.3",
4
4
  "type": "module",
5
5
  "description": "Litestar plugin for Vite.",
6
6
  "keywords": ["litestar", "vite", "vite-plugin"],