vite-plugin-backend-html 0.0.1

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) 2025- Dieter Oberkofler
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 ADDED
@@ -0,0 +1,91 @@
1
+ [![NPM Version][npm-image]][npm-url]
2
+ [![NPM Downloads][downloads-image]][downloads-url]
3
+ [![Node.js CI](https://github.com/doberkofler/vite-plugin-backend-html/actions/workflows/node.js.yml/badge.svg)](https://github.com/doberkofler/vite-plugin-backend-html/actions/workflows/node.js.yml)
4
+ [![Coverage Status](https://coveralls.io/repos/github/doberkofler/vite-plugin-backend-html/badge.svg?branch=main)](https://coveralls.io/github/doberkofler/vite-plugin-backend-html?branch=main)
5
+
6
+ # vite-plugin-backend-html
7
+
8
+ Vite plugin for proxying backend HTML responses with dynamic asset injection.
9
+
10
+ ## Key Features
11
+
12
+ - **Backend Proxying**: Filters and forwards requests to the Vite dev server to a backend.
13
+ - **Dynamic Asset Injection**: Automatically injects Vite dev assets (JS and CSS) into backend HTML responses.
14
+ - **Production Asset Stripping**: Automatically removes production asset tags (e.g., from `/assets/` or `/q/p/` paths) to prevent conflicts during development.
15
+ - **Module Extraction**: Helpers to extract module names from HTML meta tags or URL patterns for module-specific asset injection.
16
+ - **Flexible Handlers**: Support for custom backend handlers, including a built-in fetch-based handler.
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ npm install vite-plugin-backend-html --save-dev
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ ```typescript
27
+ import {defineConfig} from 'vite';
28
+ import {backendProxyPlugin, createFetchBackendHandler, extractModuleFromMeta} from 'vite-plugin-backend-html';
29
+
30
+ export default defineConfig({
31
+ plugins: [
32
+ backendProxyPlugin({
33
+ backendBaseUrl: 'http://localhost:8080',
34
+ bypass: (url) => url.startsWith('/api/v2/'),
35
+ backendHandler: createFetchBackendHandler({
36
+ extractModule: (_url, html) => extractModuleFromMeta(html, 'vite-module'),
37
+ }),
38
+ assetConfig: {
39
+ globalEntryPoints: {
40
+ js: '/src/main.ts',
41
+ },
42
+ getModuleEntryPoints: (module) => ({
43
+ js: `/src/modules/${module}/index.ts`,
44
+ }),
45
+ },
46
+ }),
47
+ ],
48
+ });
49
+ ```
50
+
51
+ ## API
52
+
53
+ ### `backendProxyPlugin(config: ProxyConfig)`
54
+
55
+ The main Vite plugin.
56
+
57
+ #### `ProxyConfig`
58
+
59
+ - `backendBaseUrl`: Base URL of the backend server.
60
+ - `bypass`: Function to skip proxying for specific URLs.
61
+ - `backendHandler`: Function to handle the actual backend request.
62
+ - `assetConfig`: Configuration for asset injection.
63
+ - `rewrites`: Optional URL path rewrites.
64
+ - `debug`: Optional logging level (`error`, `info`, `debug`).
65
+
66
+ ### `createFetchBackendHandler(options)`
67
+
68
+ A built-in handler using `fetch` to communicate with the backend.
69
+
70
+ ### `extractModuleFromMeta(html, metaName?)`
71
+
72
+ Extracts a module name from a `<meta name="vite-module" content="...">` tag.
73
+
74
+ ### `extractModuleFromUrl(url, pattern)`
75
+
76
+ Extracts a module name from the URL using a regular expression with a capture group.
77
+
78
+ ## Testing
79
+
80
+ The plugin includes a comprehensive test suite with >90% coverage.
81
+
82
+ ```bash
83
+ npm test
84
+ ```
85
+
86
+
87
+ [npm-image]: https://img.shields.io/npm/v/vite-plugin-backend-html.svg
88
+ [npm-url]: https://npmjs.org/package/vite-plugin-backend-html
89
+
90
+ [downloads-image]: https://img.shields.io/npm/dm/vite-plugin-backend-html.svg
91
+ [downloads-url]: https://npmjs.org/package/vite-plugin-backend-html
@@ -0,0 +1,182 @@
1
+ import { Plugin } from "vite";
2
+ import { IncomingMessage } from "node:http";
3
+
4
+ //#region src/backend-proxy.d.ts
5
+ /**
6
+ * Logging levels supported by the proxy
7
+ * @public
8
+ */
9
+ type LoggingLevel = 'error' | 'info' | 'debug';
10
+ /**
11
+ * Result from backend handler - only actual backend responses
12
+ * @public
13
+ */
14
+ type BackendResult = {
15
+ /** HTML response */type: 'html'; /** HTML content */
16
+ content: string; /** Optional module name for asset injection */
17
+ module: string | null; /** Optional headers to forward (e.g. set-cookie) */
18
+ headers?: Record<string, string | string[]>;
19
+ } | {
20
+ /** Binary response */type: 'binary'; /** Binary content */
21
+ content: Buffer; /** Content type */
22
+ contentType: string; /** HTTP status code */
23
+ status: number; /** Optional headers to forward (e.g. set-cookie) */
24
+ headers?: Record<string, string | string[]>;
25
+ } | {
26
+ /** Redirect response */type: 'redirect'; /** HTTP status code */
27
+ status: number; /** Redirect location */
28
+ location: string; /** Optional headers to forward (e.g. set-cookie) */
29
+ headers?: Record<string, string | string[]>;
30
+ };
31
+ /**
32
+ * Request handler - only invoked for non-Vite requests
33
+ * @public
34
+ */
35
+ type BackendHandler = (context: {
36
+ /** Request URL */url: string; /** Node request object */
37
+ req: IncomingMessage; /** HTTP method */
38
+ method: string; /** Request headers */
39
+ headers: Record<string, string | string[] | undefined>; /** Request body for POST requests */
40
+ body: Buffer | undefined; /** Backend base URL */
41
+ backendBaseUrl: string; /** Logging function */
42
+ logger: (level: LoggingLevel, message: string, data?: unknown) => void;
43
+ }) => Promise<BackendResult>;
44
+ type EntryPoints = {
45
+ js?: string;
46
+ css?: string;
47
+ };
48
+ /**
49
+ * Asset injection configuration
50
+ * @public
51
+ */
52
+ type AssetConfig = {
53
+ /**
54
+ * Global entry points (e.g. main.js, global.css)
55
+ */
56
+ globalEntryPoints: EntryPoints;
57
+ /**
58
+ * Get module-specific entry points
59
+ * @param module - Module name
60
+ * @returns Entry points
61
+ */
62
+ getModuleEntryPoints: (module: string) => EntryPoints;
63
+ };
64
+ /**
65
+ * Plugin configuration
66
+ * @public
67
+ */
68
+ type ProxyConfig = {
69
+ /**
70
+ * Backend base URL
71
+ */
72
+ backendBaseUrl: string;
73
+ /**
74
+ * Custom bypass function to skip proxying for specific URLs
75
+ * @param url - Request URL
76
+ * @returns True if the request should be skipped (handled by Vite), false otherwise
77
+ */
78
+ bypass: (url: string) => boolean;
79
+ /**
80
+ * Backend request handler
81
+ */
82
+ backendHandler: BackendHandler;
83
+ /**
84
+ * Asset injection configuration
85
+ */
86
+ assetConfig: AssetConfig;
87
+ /**
88
+ * URL path rewrites
89
+ * Map of URL prefix to new path prefix
90
+ * @example {'/legacy/path/': '/new/path/'}
91
+ */
92
+ rewrites?: Record<string, string>;
93
+ /**
94
+ * Enable debug logging level
95
+ */
96
+ debug?: LoggingLevel;
97
+ };
98
+ /**
99
+ * Helper: Create fetch-based backend handler
100
+ * @param options - Handler options
101
+ * @param options.extractModule - Optional module extraction function
102
+ * @param options.transformBackendUrl - Optional function to transform the backend URL
103
+ * @returns Backend handler
104
+ * @public
105
+ */
106
+ declare function createFetchBackendHandler(options: {
107
+ extractModule?: (url: string, html: string, headers: Headers) => string | null | Promise<string | null>;
108
+ transformBackendUrl?: (url: string, backendBaseUrl: string) => string;
109
+ }): BackendHandler;
110
+ /**
111
+ * Helper: Extract module from HTML meta tag
112
+ * @param html - HTML content
113
+ * @param metaName - Name of meta tag
114
+ * @returns Extracted module or null
115
+ * @public
116
+ */
117
+ declare function extractModuleFromMeta(html: string, metaName?: string): string | null;
118
+ /**
119
+ * Helper: Extract module from URL based on pattern
120
+ * @param url - Request URL
121
+ * @param pattern - Regex pattern with capture group
122
+ * @returns Extracted module or null
123
+ * @public
124
+ */
125
+ declare function extractModuleFromUrl(url: string, pattern: RegExp): string | null;
126
+ //#endregion
127
+ //#region src/path-utils.d.ts
128
+ /**
129
+ * Path normalization utilities for URL construction
130
+ */
131
+ /**
132
+ * Strips trailing slashes from path
133
+ * @param path - Path to normalize
134
+ * @returns Path without trailing slashes
135
+ * @public
136
+ */
137
+ declare const stripTrailingSlash: (path: string) => string;
138
+ /**
139
+ * Strips leading slashes from path
140
+ * @param path - Path to normalize
141
+ * @returns Path without leading slashes
142
+ * @public
143
+ */
144
+ declare const stripLeadingSlash: (path: string) => string;
145
+ /**
146
+ * Ensures path has exactly one leading slash
147
+ * @param path - Path to normalize
148
+ * @returns Path with single leading slash
149
+ * @public
150
+ */
151
+ declare const ensureLeadingSlash: (path: string) => string;
152
+ /**
153
+ * Joins URL parts, ensuring no double slashes
154
+ * @param base - Base URL (trailing slash removed)
155
+ * @param path - Path to append (leading slash removed)
156
+ * @returns Joined URL
157
+ * @public
158
+ */
159
+ declare const joinUrlParts: (base: string, path: string) => string;
160
+ /**
161
+ * Normalizes redirect location relative to base path
162
+ * Handles:
163
+ * - Fully qualified URLs (extracts path)
164
+ * - Absolute paths (strips base path if present)
165
+ * - Relative paths (ensures leading slash)
166
+ *
167
+ * @param location - Redirect location from backend
168
+ * @param basePath - Base path to strip (e.g. '/lj_unittest/')
169
+ * @returns Normalized location with single leading slash
170
+ * @public
171
+ */
172
+ declare const normalizeRedirectLocation: (location: string, basePath: string) => string;
173
+ //#endregion
174
+ //#region src/index.d.ts
175
+ /**
176
+ * Backend Proxy Plugin
177
+ * @param config - Plugin configuration
178
+ * @returns Vite plugin
179
+ */
180
+ declare function backendProxyPlugin(config: ProxyConfig): Plugin;
181
+ //#endregion
182
+ export { type AssetConfig, type BackendHandler, type BackendResult, type LoggingLevel, type ProxyConfig, backendProxyPlugin, createFetchBackendHandler, ensureLeadingSlash, extractModuleFromMeta, extractModuleFromUrl, joinUrlParts, normalizeRedirectLocation, stripLeadingSlash, stripTrailingSlash };
package/dist/index.mjs ADDED
@@ -0,0 +1,368 @@
1
+ //#region src/path-utils.ts
2
+ /**
3
+ * Path normalization utilities for URL construction
4
+ */
5
+ /**
6
+ * Strips trailing slashes from path
7
+ * @param path - Path to normalize
8
+ * @returns Path without trailing slashes
9
+ * @public
10
+ */
11
+ const stripTrailingSlash = (path) => {
12
+ return path.replace(/\/+$/u, "");
13
+ };
14
+ /**
15
+ * Strips leading slashes from path
16
+ * @param path - Path to normalize
17
+ * @returns Path without leading slashes
18
+ * @public
19
+ */
20
+ const stripLeadingSlash = (path) => {
21
+ return path.replace(/^\/+/u, "");
22
+ };
23
+ /**
24
+ * Ensures path has exactly one leading slash
25
+ * @param path - Path to normalize
26
+ * @returns Path with single leading slash
27
+ * @public
28
+ */
29
+ const ensureLeadingSlash = (path) => {
30
+ return "/" + stripLeadingSlash(path);
31
+ };
32
+ /**
33
+ * Joins URL parts, ensuring no double slashes
34
+ * @param base - Base URL (trailing slash removed)
35
+ * @param path - Path to append (leading slash removed)
36
+ * @returns Joined URL
37
+ * @public
38
+ */
39
+ const joinUrlParts = (base, path) => {
40
+ return `${stripTrailingSlash(base)}/${stripLeadingSlash(path)}`;
41
+ };
42
+ /**
43
+ * Normalizes redirect location relative to base path
44
+ * Handles:
45
+ * - Fully qualified URLs (extracts path)
46
+ * - Absolute paths (strips base path if present)
47
+ * - Relative paths (ensures leading slash)
48
+ *
49
+ * @param location - Redirect location from backend
50
+ * @param basePath - Base path to strip (e.g. '/lj_unittest/')
51
+ * @returns Normalized location with single leading slash
52
+ * @public
53
+ */
54
+ const normalizeRedirectLocation = (location, basePath) => {
55
+ let normalized = location;
56
+ if (location.startsWith("http://") || location.startsWith("https://")) {
57
+ const url = new URL(location);
58
+ normalized = url.pathname + url.search + url.hash;
59
+ }
60
+ if (normalized.startsWith(basePath)) normalized = normalized.slice(basePath.length);
61
+ return ensureLeadingSlash(normalized);
62
+ };
63
+
64
+ //#endregion
65
+ //#region src/backend-proxy.ts
66
+ /**
67
+ * Core backend proxy logic
68
+ * @public
69
+ */
70
+ var BackendProxy = class {
71
+ config;
72
+ /**
73
+ * Creates a new backend proxy instance
74
+ * @param config - Proxy configuration
75
+ */
76
+ constructor(config) {
77
+ this.config = config;
78
+ }
79
+ /**
80
+ * Logs a debug message
81
+ * @param level - Log level
82
+ * @param message - Message to log
83
+ * @param data - Optional data to log
84
+ */
85
+ log(level, message, data) {
86
+ if (!this.config.debug) return;
87
+ const configLevel = this.config.debug;
88
+ const levels = [
89
+ "error",
90
+ "info",
91
+ "debug"
92
+ ];
93
+ const configIndex = levels.indexOf(configLevel);
94
+ if (configIndex === -1) throw new Error(`Invalid configLevel ${configLevel}`);
95
+ const messageIndex = levels.indexOf(level);
96
+ if (messageIndex === -1) throw new Error(`Invalid messageIndex ${messageIndex}`);
97
+ if (messageIndex <= configIndex) if (message.length > 0) {
98
+ const prefix = `${nowUtcCompact()} [backend-proxy] ${level.toUpperCase().padEnd(5)} ${message}`;
99
+ if (level === "error") console.error(prefix, data ?? "");
100
+ else console.log(prefix, data ?? "");
101
+ } else console.log("");
102
+ }
103
+ /**
104
+ * Handles a request from Vite and proxies it to the backend if appropriate
105
+ * @param url - Request URL
106
+ * @param req - Node request object
107
+ * @param res - Node response object
108
+ * @param server - Vite dev server
109
+ * @returns True if the request was handled, false otherwise
110
+ */
111
+ async handleRequest(url, req, res, server) {
112
+ try {
113
+ let currentUrl = url;
114
+ if (this.config.rewrites) {
115
+ for (const [prefix, replacement] of Object.entries(this.config.rewrites)) if (currentUrl.startsWith(prefix)) {
116
+ const newUrl = currentUrl.replace(prefix, replacement);
117
+ this.log("debug", `Rewrite URL: ${currentUrl} -> ${newUrl}`);
118
+ currentUrl = newUrl;
119
+ req.url = newUrl;
120
+ break;
121
+ }
122
+ }
123
+ const { method, headers: reqHeaders } = req;
124
+ if (this.shouldSkipForVite(currentUrl)) {
125
+ this.log("debug", `Vite handles: ${currentUrl}`);
126
+ return false;
127
+ }
128
+ let body;
129
+ if (method === "POST") body = await new Promise((resolve, reject) => {
130
+ const chunks = [];
131
+ req.on("data", (chunk) => {
132
+ chunks.push(chunk);
133
+ });
134
+ req.on("end", () => {
135
+ resolve(Buffer.concat(chunks));
136
+ });
137
+ req.on("error", (err) => {
138
+ reject(err);
139
+ });
140
+ });
141
+ const result = await this.config.backendHandler({
142
+ url: currentUrl,
143
+ req,
144
+ method: method ?? "GET",
145
+ headers: reqHeaders,
146
+ body,
147
+ backendBaseUrl: this.config.backendBaseUrl,
148
+ logger: (level, message, data) => {
149
+ this.log(level, message, data);
150
+ }
151
+ });
152
+ this.log("info", `Proxying to backend [${method ?? "GET"}] ${currentUrl}`);
153
+ return await this.processResult(result, currentUrl, res, server);
154
+ } catch (error) {
155
+ this.log("error", `Proxy error for: ${url}`, error);
156
+ res.statusCode = 500;
157
+ res.setHeader("content-type", "text/plain");
158
+ const message = error instanceof Error ? error.message : String(error);
159
+ res.end(`Proxy error: ${message}`);
160
+ return true;
161
+ }
162
+ }
163
+ /**
164
+ * Processes the result and sends it to the response
165
+ * @param result - Result from backend handler
166
+ * @param url - Request URL
167
+ * @param res - Node response object
168
+ * @param server - Vite dev server
169
+ * @returns True if handled
170
+ */
171
+ async processResult(result, url, res, server) {
172
+ if (result.headers) for (const [key, value] of Object.entries(result.headers)) res.setHeader(key, value);
173
+ switch (result.type) {
174
+ case "html": {
175
+ this.log("info", `-> HTML response: length=${result.content.length}`);
176
+ if (this.config.debug === "debug") {
177
+ console.log("-".repeat(80));
178
+ console.log(result.content);
179
+ console.log("-".repeat(80));
180
+ }
181
+ let html = this.injectAssets(result.content, result.module);
182
+ res.statusCode = 200;
183
+ res.setHeader("content-type", "text/html; charset=utf-8");
184
+ html = await server.transformIndexHtml(url, html);
185
+ res.end(html);
186
+ return true;
187
+ }
188
+ case "binary":
189
+ this.log("info", `-> Binary response: status=${result.status}, contentType=${result.contentType}, length=${result.content.length}`);
190
+ res.statusCode = result.status;
191
+ res.setHeader("content-type", result.contentType);
192
+ res.end(result.content);
193
+ return true;
194
+ case "redirect":
195
+ this.log("info", `-> Redirect response: status=${result.status}, location=${result.location}`);
196
+ res.statusCode = result.status;
197
+ res.setHeader("location", result.location);
198
+ res.end();
199
+ return true;
200
+ default: {
201
+ const _exhaustive = result;
202
+ throw new Error(`Unhandled result type: ${JSON.stringify(_exhaustive)}`);
203
+ }
204
+ }
205
+ }
206
+ /**
207
+ * Injects assets into HTML
208
+ * @param html - HTML content
209
+ * @param module - Optional module name
210
+ * @returns Processed HTML
211
+ */
212
+ injectAssets(html, module) {
213
+ const injection = [];
214
+ const inject = (entryPoints) => {
215
+ if (entryPoints.css) injection.push(`<link rel="stylesheet" href="${entryPoints.css}">`);
216
+ if (entryPoints.js) injection.push(`<script type="module" src="${entryPoints.js}"><\/script>`);
217
+ };
218
+ const { globalEntryPoints, getModuleEntryPoints } = this.config.assetConfig;
219
+ inject({ js: "/@vite/client" });
220
+ inject(globalEntryPoints);
221
+ if (module) inject(getModuleEntryPoints(module));
222
+ let processedHtml = html.replaceAll(/<link [^>]*href="(?:\/assets\/|\/q\/p\/)[^"]+"[^>]*>/g, "");
223
+ processedHtml = processedHtml.replaceAll(/<script [^>]*src="(?:\/assets\/|\/q\/p\/)[^"]+"[^>]*><\/script>/g, "");
224
+ if (processedHtml.includes("</head>")) return processedHtml.replace("</head>", `${injection.join("\n")}\n</head>`);
225
+ if (processedHtml.includes("<body>")) return processedHtml.replace("<body>", `<body>\n${injection.join("\n")}`);
226
+ return injection.join("\n") + processedHtml;
227
+ }
228
+ /**
229
+ * Checks if the URL should be skipped (handled by Vite)
230
+ * @param url - Request URL
231
+ * @returns True if skipped
232
+ */
233
+ shouldSkipForVite(url) {
234
+ if (this.config.bypass(url)) return true;
235
+ if (url.startsWith("/@") || url.startsWith("/node_modules/")) return true;
236
+ if (/\.(?:ts|tsx|js|jsx|mjs)$/.test(url) || /\.css(?:\?|$)/.test(url)) return true;
237
+ return false;
238
+ }
239
+ };
240
+ /**
241
+ * Helper: Create fetch-based backend handler
242
+ * @param options - Handler options
243
+ * @param options.extractModule - Optional module extraction function
244
+ * @param options.transformBackendUrl - Optional function to transform the backend URL
245
+ * @returns Backend handler
246
+ * @public
247
+ */
248
+ function createFetchBackendHandler(options) {
249
+ return async ({ url, method, headers, body, backendBaseUrl, logger }) => {
250
+ const backendUrl = options.transformBackendUrl ? options.transformBackendUrl(url, backendBaseUrl) : `${backendBaseUrl}${url}`;
251
+ logger("debug", `backendBaseUrl="${backendBaseUrl}" args.url="${url}" url="${backendUrl}"`);
252
+ const fetchHeaders = new Headers();
253
+ for (const [key, value] of Object.entries(headers)) if (value !== void 0) if (Array.isArray(value)) for (const v of value) fetchHeaders.append(key, v);
254
+ else fetchHeaders.set(key, value);
255
+ const fetchOptions = {
256
+ method,
257
+ headers: fetchHeaders,
258
+ redirect: "manual"
259
+ };
260
+ if (method === "POST" && body !== void 0) fetchOptions.body = body;
261
+ const response = await fetch(backendUrl, fetchOptions);
262
+ logger("debug", "fetch results", {
263
+ ok: response.ok,
264
+ statusText: response.statusText,
265
+ redirected: response.redirected
266
+ });
267
+ const status = response.status;
268
+ const contentType = response.headers.get("content-type") ?? "application/octet-stream";
269
+ const responseHeaders = {};
270
+ const setCookie = response.headers.getSetCookie();
271
+ if (setCookie.length > 0) {
272
+ logger("debug", `setCookie="${setCookie.join(", ")}"`);
273
+ responseHeaders["set-cookie"] = setCookie;
274
+ }
275
+ if (status >= 300 && status < 400) {
276
+ const rawLocation = response.headers.get("location");
277
+ if (!rawLocation) throw new Error(`Redirect ${status} missing Location header`);
278
+ const location = normalizeRedirectLocation(rawLocation, new URL(backendBaseUrl).pathname);
279
+ logger("debug", `redirect="${location}"`);
280
+ return {
281
+ type: "redirect",
282
+ status,
283
+ location,
284
+ headers: responseHeaders
285
+ };
286
+ }
287
+ if (contentType.includes("text/html")) {
288
+ const html = await response.text();
289
+ let module = null;
290
+ if (response.ok) {
291
+ const result = options.extractModule?.(url, html, response.headers);
292
+ module = (result instanceof Promise ? await result : result) ?? null;
293
+ }
294
+ logger("debug", `extracted module "${module}"`);
295
+ return {
296
+ type: "html",
297
+ content: html,
298
+ module,
299
+ headers: responseHeaders
300
+ };
301
+ }
302
+ return {
303
+ type: "binary",
304
+ content: Buffer.from(await response.arrayBuffer()),
305
+ contentType,
306
+ status,
307
+ headers: responseHeaders
308
+ };
309
+ };
310
+ }
311
+ /**
312
+ * Helper: Extract module from HTML meta tag
313
+ * @param html - HTML content
314
+ * @param metaName - Name of meta tag
315
+ * @returns Extracted module or null
316
+ * @public
317
+ */
318
+ function extractModuleFromMeta(html, metaName = "vite-module") {
319
+ return new RegExp(`<meta name="${metaName}" content="([^"]+)">`).exec(html)?.[1] ?? null;
320
+ }
321
+ /**
322
+ * Helper: Extract module from URL based on pattern
323
+ * @param url - Request URL
324
+ * @param pattern - Regex pattern with capture group
325
+ * @returns Extracted module or null
326
+ * @public
327
+ */
328
+ function extractModuleFromUrl(url, pattern) {
329
+ return pattern.exec(url)?.[1] ?? null;
330
+ }
331
+ /**
332
+ * Returns current date-time in format: HH24:MI:SS.MS
333
+ * @returns Formatted timestamp.
334
+ */
335
+ function nowUtcCompact() {
336
+ const now = /* @__PURE__ */ new Date();
337
+ return `${now.getUTCHours().toString().padStart(2, "0")}:${now.getUTCMinutes().toString().padStart(2, "0")}:${now.getUTCSeconds().toString().padStart(2, "0")}.${now.getUTCMilliseconds().toString().padStart(3, "0")}`;
338
+ }
339
+
340
+ //#endregion
341
+ //#region src/index.ts
342
+ /**
343
+ * Backend Proxy Plugin
344
+ * @param config - Plugin configuration
345
+ * @returns Vite plugin
346
+ */
347
+ function backendProxyPlugin(config) {
348
+ const proxy = new BackendProxy(config);
349
+ return {
350
+ name: "backend-proxy-plugin",
351
+ configureServer(server) {
352
+ proxy.log("info", "Plugin vite-plugin-backend-htmlconfigured", { backendBaseUrl: config.backendBaseUrl });
353
+ server.middlewares.use((req, res, next) => {
354
+ const url = req.url;
355
+ if (!url) {
356
+ next();
357
+ return;
358
+ }
359
+ proxy.handleRequest(url, req, res, server).then((handled) => {
360
+ if (!handled) next();
361
+ });
362
+ });
363
+ }
364
+ };
365
+ }
366
+
367
+ //#endregion
368
+ export { backendProxyPlugin, createFetchBackendHandler, ensureLeadingSlash, extractModuleFromMeta, extractModuleFromUrl, joinUrlParts, normalizeRedirectLocation, stripLeadingSlash, stripTrailingSlash };
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "vite-plugin-backend-html",
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "author": "Dieter Oberkofler",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "keywords": [
11
+ "vite",
12
+ "vite-plugin",
13
+ "frontend",
14
+ "backend",
15
+ "html"
16
+ ],
17
+ "scripts": {
18
+ "dev": "tsdown --watch",
19
+ "build": "tsdown",
20
+ "lint": "eslint --no-cache . && tsc && prettier --check .",
21
+ "test": "vitest run --coverage",
22
+ "ci": "npm run lint && npm run build && npm run test",
23
+ "create-changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
24
+ "pack-local": "rm -f *.tgz && npm run build && npm pack",
25
+ "prepare": "husky"
26
+ },
27
+ "main": "./dist/index.mjs",
28
+ "module": "./dist/index.mjs",
29
+ "types": "./dist/index.d.ts",
30
+ "exports": {
31
+ ".": "./dist/index.mjs",
32
+ "./package.json": "./package.json"
33
+ },
34
+ "engines": {
35
+ "node": ">=22"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git://github.com/doberkofler/vite-plugin-merge-css.git"
40
+ },
41
+ "homepage": "https://github.com/doberkofler/vite-plugin-merge-css#readme",
42
+ "peerDependencies": {
43
+ "vite": "^7.0.0"
44
+ },
45
+ "devDependencies": {
46
+ "@commitlint/cli": "^20.4.2",
47
+ "@commitlint/config-conventional": "^20.4.2",
48
+ "@eslint/js": "^9.31.0",
49
+ "@types/debug": "^4.1.12",
50
+ "@types/node": "^25.3.0",
51
+ "@vitest/coverage-v8": "^4.0.18",
52
+ "@vitest/eslint-plugin": "^1.6.9",
53
+ "conventional-changelog": "^7.1.1",
54
+ "conventional-changelog-angular": "^8.1.0",
55
+ "conventional-changelog-cli": "^5.0.0",
56
+ "eslint": "^9.31.0",
57
+ "eslint-plugin-jsdoc": "^62.6.1",
58
+ "eslint-plugin-regexp": "^3.0.0",
59
+ "eslint-plugin-unicorn": "^63.0.0",
60
+ "globals": "^17.3.0",
61
+ "husky": "^9.1.7",
62
+ "prettier": "^3.8.1",
63
+ "tsdown": "^0.20.3",
64
+ "typescript": "^5.9.3",
65
+ "typescript-eslint": "^8.56.0",
66
+ "vitest": "^4.0.18"
67
+ },
68
+ "dependencies": {
69
+ "debug": "^4.4.3"
70
+ }
71
+ }