vite-plugin-backend-html 0.2.0 → 0.2.2

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.
Files changed (3) hide show
  1. package/dist/index.d.mts +75 -62
  2. package/dist/index.mjs +156 -162
  3. package/package.json +77 -65
package/dist/index.d.mts CHANGED
@@ -1,7 +1,5 @@
1
1
  import { Plugin } from "vite";
2
2
  import { IncomingMessage } from "node:http";
3
-
4
- //#region src/backend-proxy.d.ts
5
3
  /**
6
4
  * Logging levels supported by the proxy
7
5
  * @public
@@ -12,20 +10,33 @@ type LoggingLevel = 'error' | 'info' | 'debug';
12
10
  * @public
13
11
  */
14
12
  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) */
13
+ /** HTML response */
14
+ type: 'html';
15
+ /** HTML content */
16
+ content: string;
17
+ /** Optional module name for asset injection */
18
+ module: string | null;
19
+ /** Optional headers to forward (e.g. set-cookie) */
18
20
  headers?: Record<string, string | string[]>;
19
21
  } | {
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) */
22
+ /** Binary response */
23
+ type: 'binary';
24
+ /** Binary content */
25
+ content: Buffer;
26
+ /** Content type */
27
+ contentType: string;
28
+ /** HTTP status code */
29
+ status: number;
30
+ /** Optional headers to forward (e.g. set-cookie) */
24
31
  headers?: Record<string, string | string[]>;
25
32
  } | {
26
- /** Redirect response */type: 'redirect'; /** HTTP status code */
27
- status: number; /** Redirect location */
28
- location: string; /** Optional headers to forward (e.g. set-cookie) */
33
+ /** Redirect response */
34
+ type: 'redirect';
35
+ /** HTTP status code */
36
+ status: number;
37
+ /** Redirect location */
38
+ location: string;
39
+ /** Optional headers to forward (e.g. set-cookie) */
29
40
  headers?: Record<string, string | string[]>;
30
41
  };
31
42
  /**
@@ -33,12 +44,19 @@ type BackendResult = {
33
44
  * @public
34
45
  */
35
46
  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 */
47
+ /** Request URL */
48
+ url: string;
49
+ /** Node request object */
50
+ req: IncomingMessage;
51
+ /** HTTP method */
52
+ method: string;
53
+ /** Request headers */
54
+ headers: Record<string, string | string[] | undefined>;
55
+ /** Request body for POST requests */
56
+ body: Buffer | undefined;
57
+ /** Backend base URL */
58
+ backendBaseUrl: string;
59
+ /** Logging function */
42
60
  logger: (level: LoggingLevel, message: string, data?: unknown) => void;
43
61
  }) => Promise<BackendResult>;
44
62
  type EntryPoints = {
@@ -56,8 +74,8 @@ type AssetConfig = {
56
74
  globalEntryPoints: EntryPoints;
57
75
  /**
58
76
  * Get module-specific entry points
59
- * @param module - Module name
60
- * @returns Entry points
77
+ * @param {string} module - Module name
78
+ * @returns {EntryPoints} Entry points
61
79
  */
62
80
  getModuleEntryPoints: (module: string) => EntryPoints;
63
81
  };
@@ -72,8 +90,8 @@ type ProxyConfig = {
72
90
  backendBaseUrl: string;
73
91
  /**
74
92
  * 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
93
+ * @param {string} url - Request URL
94
+ * @returns {boolean} True if the request should be skipped (handled by Vite), false otherwise
77
95
  */
78
96
  bypass: (url: string) => boolean;
79
97
  /**
@@ -97,66 +115,64 @@ type ProxyConfig = {
97
115
  };
98
116
  /**
99
117
  * 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
118
+ * @param {{ extractModule?: (url: string, html: string, headers: Headers) => string | null | Promise<string | null>; transformBackendUrl?: (url: string, backendBaseUrl: string) => string; }} options - Handler options
119
+ * @param {(url: string, html: string, headers: Headers) => string | null | Promise<string | null>} options.extractModule - Optional module extraction function
120
+ * @param {(url: string, backendBaseUrl: string) => string} options.transformBackendUrl - Optional function to transform the backend URL
121
+ * @returns {BackendHandler} Backend handler
104
122
  * @public
105
123
  */
106
- declare function createFetchBackendHandler(options: {
124
+ export declare const createFetchBackendHandler: (options: {
107
125
  extractModule?: (url: string, html: string, headers: Headers) => string | null | Promise<string | null>;
108
126
  transformBackendUrl?: (url: string, backendBaseUrl: string) => string;
109
- }): BackendHandler;
127
+ }) => BackendHandler;
110
128
  /**
111
129
  * 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
130
+ * @param {string} html - HTML content
131
+ * @param {string} metaName - Name of meta tag
132
+ * @returns {string | null} Extracted module or null
115
133
  * @public
116
134
  */
117
- declare function extractModuleFromMeta(html: string, metaName?: string): string | null;
135
+ export declare const extractModuleFromMeta: (html: string, metaName?: string) => string | null;
118
136
  /**
119
137
  * 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
138
+ * @param {string} url - Request URL
139
+ * @param {RegExp} pattern - Regex pattern with capture group
140
+ * @returns {string | null} Extracted module or null
123
141
  * @public
124
142
  */
125
- declare function extractModuleFromUrl(url: string, pattern: RegExp): string | null;
126
- //#endregion
127
- //#region src/path-utils.d.ts
143
+ export declare const extractModuleFromUrl: (url: string, pattern: RegExp) => string | null;
128
144
  /**
129
145
  * Path normalization utilities for URL construction
130
146
  */
131
147
  /**
132
148
  * Strips trailing slashes from path
133
- * @param path - Path to normalize
134
- * @returns Path without trailing slashes
149
+ * @param {string} path - Path to normalize
150
+ * @returns {string} Path without trailing slashes
135
151
  * @public
136
152
  */
137
- declare const stripTrailingSlash: (path: string) => string;
153
+ export declare const stripTrailingSlash: (path: string) => string;
138
154
  /**
139
155
  * Strips leading slashes from path
140
- * @param path - Path to normalize
141
- * @returns Path without leading slashes
156
+ * @param {string} path - Path to normalize
157
+ * @returns {string} Path without leading slashes
142
158
  * @public
143
159
  */
144
- declare const stripLeadingSlash: (path: string) => string;
160
+ export declare const stripLeadingSlash: (path: string) => string;
145
161
  /**
146
162
  * Ensures path has exactly one leading slash
147
- * @param path - Path to normalize
148
- * @returns Path with single leading slash
163
+ * @param {string} path - Path to normalize
164
+ * @returns {string} Path with single leading slash
149
165
  * @public
150
166
  */
151
- declare const ensureLeadingSlash: (path: string) => string;
167
+ export declare const ensureLeadingSlash: (path: string) => string;
152
168
  /**
153
169
  * 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
170
+ * @param {string} base - Base URL (trailing slash removed)
171
+ * @param {string} path - Path to append (leading slash removed)
172
+ * @returns {string} Joined URL
157
173
  * @public
158
174
  */
159
- declare const joinUrlParts: (base: string, path: string) => string;
175
+ export declare const joinUrlParts: (base: string, path: string) => string;
160
176
  /**
161
177
  * Normalizes redirect location relative to base path
162
178
  * Handles:
@@ -164,19 +180,16 @@ declare const joinUrlParts: (base: string, path: string) => string;
164
180
  * - Absolute paths (strips base path if present)
165
181
  * - Relative paths (ensures leading slash)
166
182
  *
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
183
+ * @param {string} location - Redirect location from backend
184
+ * @param {string} basePath - Base path to strip (e.g. '/lj_unittest/')
185
+ * @returns {string} Normalized location with single leading slash
170
186
  * @public
171
187
  */
172
- declare const normalizeRedirectLocation: (location: string, basePath: string) => string;
173
- //#endregion
174
- //#region src/index.d.ts
188
+ export declare const normalizeRedirectLocation: (location: string, basePath: string) => string;
175
189
  /**
176
190
  * Backend Proxy Plugin
177
- * @param config - Plugin configuration
178
- * @returns Vite plugin
191
+ * @param {ProxyConfig} config - Plugin configuration
192
+ * @returns {Plugin} Vite plugin
179
193
  */
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 };
194
+ export declare const backendProxyPlugin: (config: ProxyConfig) => Plugin;
195
+ export type { AssetConfig, BackendHandler, BackendResult, LoggingLevel, ProxyConfig };
package/dist/index.mjs CHANGED
@@ -1,44 +1,36 @@
1
- //#region src/path-utils.ts
1
+ // src/path-utils.ts
2
2
  /**
3
3
  * Path normalization utilities for URL construction
4
4
  */
5
5
  /**
6
6
  * Strips trailing slashes from path
7
- * @param path - Path to normalize
8
- * @returns Path without trailing slashes
7
+ * @param {string} path - Path to normalize
8
+ * @returns {string} Path without trailing slashes
9
9
  * @public
10
10
  */
11
- const stripTrailingSlash = (path) => {
12
- return path.replace(/\/+$/u, "");
13
- };
11
+ const stripTrailingSlash = (path) => path.replace(/\/+$/u, "");
14
12
  /**
15
13
  * Strips leading slashes from path
16
- * @param path - Path to normalize
17
- * @returns Path without leading slashes
14
+ * @param {string} path - Path to normalize
15
+ * @returns {string} Path without leading slashes
18
16
  * @public
19
17
  */
20
- const stripLeadingSlash = (path) => {
21
- return path.replace(/^\/+/u, "");
22
- };
18
+ const stripLeadingSlash = (path) => path.replace(/^\/+/u, "");
23
19
  /**
24
20
  * Ensures path has exactly one leading slash
25
- * @param path - Path to normalize
26
- * @returns Path with single leading slash
21
+ * @param {string} path - Path to normalize
22
+ * @returns {string} Path with single leading slash
27
23
  * @public
28
24
  */
29
- const ensureLeadingSlash = (path) => {
30
- return "/" + stripLeadingSlash(path);
31
- };
25
+ const ensureLeadingSlash = (path) => `/${stripLeadingSlash(path)}`;
32
26
  /**
33
27
  * 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
28
+ * @param {string} base - Base URL (trailing slash removed)
29
+ * @param {string} path - Path to append (leading slash removed)
30
+ * @returns {string} Joined URL
37
31
  * @public
38
32
  */
39
- const joinUrlParts = (base, path) => {
40
- return `${stripTrailingSlash(base)}/${stripLeadingSlash(path)}`;
41
- };
33
+ const joinUrlParts = (base, path) => `${stripTrailingSlash(base)}/${stripLeadingSlash(path)}`;
42
34
  /**
43
35
  * Normalizes redirect location relative to base path
44
36
  * Handles:
@@ -46,9 +38,9 @@ const joinUrlParts = (base, path) => {
46
38
  * - Absolute paths (strips base path if present)
47
39
  * - Relative paths (ensures leading slash)
48
40
  *
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
41
+ * @param {string} location - Redirect location from backend
42
+ * @param {string} basePath - Base path to strip (e.g. '/lj_unittest/')
43
+ * @returns {string} Normalized location with single leading slash
52
44
  * @public
53
45
  */
54
46
  const normalizeRedirectLocation = (location, basePath) => {
@@ -60,8 +52,15 @@ const normalizeRedirectLocation = (location, basePath) => {
60
52
  if (normalized.startsWith(basePath)) normalized = normalized.slice(basePath.length);
61
53
  return ensureLeadingSlash(normalized);
62
54
  };
63
- //#endregion
64
- //#region src/backend-proxy.ts
55
+ // src/backend-proxy.ts
56
+ /**
57
+ * Returns current date-time in format: HH24:MI:SS.MS
58
+ * @returns {string} Formatted timestamp.
59
+ */
60
+ const nowUtcCompact = () => {
61
+ const now = /* @__PURE__ */ new Date();
62
+ 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")}`;
63
+ };
65
64
  /**
66
65
  * Core backend proxy logic
67
66
  * @public
@@ -70,16 +69,16 @@ var BackendProxy = class {
70
69
  config;
71
70
  /**
72
71
  * Creates a new backend proxy instance
73
- * @param config - Proxy configuration
72
+ * @param {ProxyConfig} config - Proxy configuration
74
73
  */
75
74
  constructor(config) {
76
75
  this.config = config;
77
76
  }
78
77
  /**
79
78
  * Logs a debug message
80
- * @param level - Log level
81
- * @param message - Message to log
82
- * @param data - Optional data to log
79
+ * @param {LoggingLevel} level - Log level
80
+ * @param {string} message - Message to log
81
+ * @param {unknown} data - Optional data to log
83
82
  */
84
83
  log(level, message, data) {
85
84
  if (!this.config.debug) return;
@@ -93,24 +92,26 @@ var BackendProxy = class {
93
92
  if (configIndex === -1) throw new Error(`Invalid configLevel ${configLevel}`);
94
93
  const messageIndex = levels.indexOf(level);
95
94
  if (messageIndex === -1) throw new Error(`Invalid messageIndex ${messageIndex}`);
96
- if (messageIndex <= configIndex) if (message.length > 0) {
97
- const prefix = `${nowUtcCompact()} [backend-proxy] ${level.toUpperCase().padEnd(5)} ${message}`;
98
- if (level === "error") console.error(prefix, data ?? "");
99
- else console.log(prefix, data ?? "");
100
- } else console.log("");
95
+ if (messageIndex <= configIndex) {
96
+ if (message.length > 0) {
97
+ const prefix = `${nowUtcCompact()} [backend-proxy] ${level.toUpperCase().padEnd(5)} ${message}`;
98
+ if (level === "error") console.error(prefix, data ?? "");
99
+ else console.log(prefix, data ?? "");
100
+ } else console.log("");
101
+ }
101
102
  }
102
103
  /**
103
104
  * Handles a request from Vite and proxies it to the backend if appropriate
104
- * @param url - Request URL
105
- * @param req - Node request object
106
- * @param res - Node response object
107
- * @param server - Vite dev server
108
- * @returns True if the request was handled, false otherwise
105
+ * @param {string} url - Request URL
106
+ * @param {IncomingMessage} req - Node request object
107
+ * @param {ServerResponse} res - Node response object
108
+ * @param {ViteDevServer} server - Vite dev server
109
+ * @returns {Promise<boolean>} True if the request was handled, false otherwise
109
110
  */
110
111
  async handleRequest(url, req, res, server) {
111
112
  try {
112
113
  let currentUrl = url;
113
- if (this.config.rewrites) {
114
+ if (typeof this.config.rewrites !== "undefined") {
114
115
  for (const [prefix, replacement] of Object.entries(this.config.rewrites)) if (currentUrl.startsWith(prefix)) {
115
116
  const newUrl = currentUrl.replace(prefix, replacement);
116
117
  this.log("debug", `Rewrite URL: ${currentUrl} -> ${newUrl}`);
@@ -125,18 +126,12 @@ var BackendProxy = class {
125
126
  return false;
126
127
  }
127
128
  let body;
128
- if (method === "POST") body = await new Promise((resolve, reject) => {
129
+ if (method === "POST") {
129
130
  const chunks = [];
130
- req.on("data", (chunk) => {
131
- chunks.push(chunk);
132
- });
133
- req.on("end", () => {
134
- resolve(Buffer.concat(chunks));
135
- });
136
- req.on("error", (err) => {
137
- reject(err);
138
- });
139
- });
131
+ for await (const chunk of req) if (Buffer.isBuffer(chunk)) chunks.push(chunk);
132
+ else chunks.push(Buffer.from(String(chunk)));
133
+ body = Buffer.concat(chunks);
134
+ }
140
135
  const result = await this.config.backendHandler({
141
136
  url: currentUrl,
142
137
  req,
@@ -161,14 +156,14 @@ var BackendProxy = class {
161
156
  }
162
157
  /**
163
158
  * Processes the result and sends it to the response
164
- * @param result - Result from backend handler
165
- * @param url - Request URL
166
- * @param res - Node response object
167
- * @param server - Vite dev server
168
- * @returns True if handled
159
+ * @param {BackendResult} result - Result from backend handler
160
+ * @param {string} url - Request URL
161
+ * @param {ServerResponse} res - Node response object
162
+ * @param {ViteDevServer} server - Vite dev server
163
+ * @returns {Promise<boolean>} True if handled
169
164
  */
170
165
  async processResult(result, url, res, server) {
171
- if (result.headers) for (const [key, value] of Object.entries(result.headers)) res.setHeader(key, value);
166
+ if (typeof result.headers !== "undefined") for (const [key, value] of Object.entries(result.headers)) res.setHeader(key, value);
172
167
  switch (result.type) {
173
168
  case "html": {
174
169
  this.log("info", `-> HTML response: length=${result.content.length}`);
@@ -201,162 +196,161 @@ var BackendProxy = class {
201
196
  }
202
197
  /**
203
198
  * Injects assets into HTML
204
- * @param html - HTML content
205
- * @param module - Optional module name
206
- * @returns Processed HTML
199
+ * @param {string} html - HTML content
200
+ * @param {string | null} module - Optional module name
201
+ * @returns {string} Processed HTML
207
202
  */
208
203
  injectAssets(html, module) {
209
204
  const injection = [];
210
205
  const inject = (entryPoints) => {
211
- if (entryPoints.css) injection.push(`<link rel="stylesheet" href="${entryPoints.css}">`);
212
- if (entryPoints.js) injection.push(`<script type="module" src="${entryPoints.js}"><\/script>`);
206
+ if (typeof entryPoints.css === "string" && entryPoints.css.length > 0) injection.push(`<link rel="stylesheet" href="${entryPoints.css}">`);
207
+ if (typeof entryPoints.js === "string" && entryPoints.js.length > 0) injection.push(`<script type="module" src="${entryPoints.js}"><\/script>`);
213
208
  };
214
209
  const { globalEntryPoints, getModuleEntryPoints } = this.config.assetConfig;
215
210
  inject({ js: "/@vite/client" });
216
211
  inject(globalEntryPoints);
217
- if (module) inject(getModuleEntryPoints(module));
218
- let processedHtml = html.replaceAll(/<link [^>]*href="(?:\/assets\/|\/q\/p\/)[^"]+"[^>]*>/g, "");
219
- processedHtml = processedHtml.replaceAll(/<script [^>]*src="(?:\/assets\/|\/q\/p\/)[^"]+"[^>]*><\/script>/g, "");
212
+ if (typeof module === "string") inject(getModuleEntryPoints(module));
213
+ let processedHtml = html.replaceAll(/<link [^>]*href="(?:\/assets\/|\/q\/p\/)[^"]+"[^>]*>/gu, "");
214
+ processedHtml = processedHtml.replaceAll(/<script [^>]*src="(?:\/assets\/|\/q\/p\/)[^"]+"[^>]*><\/script>/gu, "");
220
215
  if (processedHtml.includes("</head>")) return processedHtml.replace("</head>", `${injection.join("\n")}\n</head>`);
221
216
  if (processedHtml.includes("<body>")) return processedHtml.replace("<body>", `<body>\n${injection.join("\n")}`);
222
217
  return injection.join("\n") + processedHtml;
223
218
  }
224
219
  /**
225
220
  * Checks if the URL should be skipped (handled by Vite)
226
- * @param url - Request URL
227
- * @returns True if skipped
221
+ * @param {string} url - Request URL
222
+ * @returns {boolean} True if skipped
228
223
  */
229
224
  shouldSkipForVite(url) {
230
225
  if (this.config.bypass(url)) return true;
231
226
  if (url.startsWith("/@") || url.startsWith("/node_modules/")) return true;
232
- if (/\.(?:ts|tsx|js|jsx|mjs)$/.test(url) || /\.css(?:\?|$)/.test(url)) return true;
227
+ if (/\.(?:ts|tsx|js|jsx|mjs)$/u.test(url) || /\.css(?:\?|$)/u.test(url)) return true;
233
228
  return false;
234
229
  }
235
230
  };
236
231
  /**
237
232
  * Helper: Create fetch-based backend handler
238
- * @param options - Handler options
239
- * @param options.extractModule - Optional module extraction function
240
- * @param options.transformBackendUrl - Optional function to transform the backend URL
241
- * @returns Backend handler
233
+ * @param {{ extractModule?: (url: string, html: string, headers: Headers) => string | null | Promise<string | null>; transformBackendUrl?: (url: string, backendBaseUrl: string) => string; }} options - Handler options
234
+ * @param {(url: string, html: string, headers: Headers) => string | null | Promise<string | null>} options.extractModule - Optional module extraction function
235
+ * @param {(url: string, backendBaseUrl: string) => string} options.transformBackendUrl - Optional function to transform the backend URL
236
+ * @returns {BackendHandler} Backend handler
242
237
  * @public
243
238
  */
244
- function createFetchBackendHandler(options) {
245
- return async ({ url, method, headers, body, backendBaseUrl, logger }) => {
246
- const backendUrl = options.transformBackendUrl ? options.transformBackendUrl(url, backendBaseUrl) : `${backendBaseUrl}${url}`;
247
- logger("debug", `backendBaseUrl="${backendBaseUrl}" args.url="${url}" url="${backendUrl}"`);
248
- const fetchHeaders = new Headers();
249
- 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);
239
+ const createFetchBackendHandler = (options) => async ({ url, method, headers, body, backendBaseUrl, logger }) => {
240
+ const backendUrl = options.transformBackendUrl ? options.transformBackendUrl(url, backendBaseUrl) : `${backendBaseUrl}${url}`;
241
+ logger("debug", `backendBaseUrl="${backendBaseUrl}" args.url="${url}" url="${backendUrl}"`);
242
+ const fetchHeaders = new Headers();
243
+ for (const [key, value] of Object.entries(headers)) if (value !== void 0) {
244
+ if (Array.isArray(value)) for (const v of value) fetchHeaders.append(key, v);
250
245
  else fetchHeaders.set(key, value);
251
- const fetchOptions = {
252
- method,
253
- headers: fetchHeaders,
254
- redirect: "manual"
246
+ }
247
+ const fetchOptions = {
248
+ method,
249
+ headers: fetchHeaders,
250
+ redirect: "manual"
251
+ };
252
+ if (method === "POST" && body !== void 0) fetchOptions.body = body;
253
+ const response = await fetch(backendUrl, fetchOptions);
254
+ logger("debug", "fetch results", {
255
+ ok: response.ok,
256
+ statusText: response.statusText,
257
+ redirected: response.redirected
258
+ });
259
+ const { status } = response;
260
+ const contentType = response.headers.get("content-type") ?? "application/octet-stream";
261
+ const responseHeaders = {};
262
+ const setCookie = response.headers.getSetCookie();
263
+ if (setCookie.length > 0) {
264
+ logger("debug", `setCookie="${setCookie.join(", ")}"`);
265
+ responseHeaders["set-cookie"] = setCookie;
266
+ }
267
+ if (status >= 300 && status < 400) {
268
+ const rawLocation = response.headers.get("location");
269
+ if (rawLocation === null || rawLocation.length === 0) throw new Error(`Redirect ${status} missing Location header`);
270
+ const baseUrlObj = new URL(backendBaseUrl);
271
+ const location = normalizeRedirectLocation(rawLocation, baseUrlObj.pathname);
272
+ logger("debug", `redirect="${location}"`);
273
+ return {
274
+ type: "redirect",
275
+ status,
276
+ location,
277
+ headers: responseHeaders
255
278
  };
256
- if (method === "POST" && body !== void 0) fetchOptions.body = body;
257
- const response = await fetch(backendUrl, fetchOptions);
258
- logger("debug", "fetch results", {
259
- ok: response.ok,
260
- statusText: response.statusText,
261
- redirected: response.redirected
262
- });
263
- const status = response.status;
264
- const contentType = response.headers.get("content-type") ?? "application/octet-stream";
265
- const responseHeaders = {};
266
- const setCookie = response.headers.getSetCookie();
267
- if (setCookie.length > 0) {
268
- logger("debug", `setCookie="${setCookie.join(", ")}"`);
269
- responseHeaders["set-cookie"] = setCookie;
270
- }
271
- if (status >= 300 && status < 400) {
272
- const rawLocation = response.headers.get("location");
273
- if (!rawLocation) throw new Error(`Redirect ${status} missing Location header`);
274
- const location = normalizeRedirectLocation(rawLocation, new URL(backendBaseUrl).pathname);
275
- logger("debug", `redirect="${location}"`);
276
- return {
277
- type: "redirect",
278
- status,
279
- location,
280
- headers: responseHeaders
281
- };
282
- }
283
- if (contentType.includes("text/html")) {
284
- const html = await response.text();
285
- let module = null;
286
- if (response.ok) {
287
- const result = options.extractModule?.(url, html, response.headers);
288
- module = (result instanceof Promise ? await result : result) ?? null;
289
- }
290
- logger("debug", `extracted module "${module}"`);
291
- return {
292
- type: "html",
293
- content: html,
294
- module,
295
- headers: responseHeaders
296
- };
279
+ }
280
+ if (contentType.includes("text/html")) {
281
+ const html = await response.text();
282
+ let module = null;
283
+ const { extractModule } = options;
284
+ if (response.ok && typeof extractModule === "function") {
285
+ const result = extractModule(url, html, response.headers);
286
+ module = (result instanceof Promise ? await result : result) ?? null;
297
287
  }
288
+ logger("debug", `extracted module "${module}"`);
298
289
  return {
299
- type: "binary",
300
- content: Buffer.from(await response.arrayBuffer()),
301
- contentType,
302
- status,
290
+ type: "html",
291
+ content: html,
292
+ module,
303
293
  headers: responseHeaders
304
294
  };
295
+ }
296
+ return {
297
+ type: "binary",
298
+ content: Buffer.from(await response.arrayBuffer()),
299
+ contentType,
300
+ status,
301
+ headers: responseHeaders
305
302
  };
306
- }
303
+ };
307
304
  /**
308
305
  * Helper: Extract module from HTML meta tag
309
- * @param html - HTML content
310
- * @param metaName - Name of meta tag
311
- * @returns Extracted module or null
306
+ * @param {string} html - HTML content
307
+ * @param {string} metaName - Name of meta tag
308
+ * @returns {string | null} Extracted module or null
312
309
  * @public
313
310
  */
314
- function extractModuleFromMeta(html, metaName = "vite-module") {
315
- return new RegExp(`<meta name="${metaName}" content="([^"]+)">`).exec(html)?.[1] ?? null;
316
- }
311
+ const extractModuleFromMeta = (html, metaName = "vite-module") => {
312
+ const match = new RegExp(`<meta name="${metaName}" content="([^"]+)">`, "u").exec(html);
313
+ return Array.isArray(match) && typeof match[1] === "string" ? match[1] : null;
314
+ };
317
315
  /**
318
316
  * Helper: Extract module from URL based on pattern
319
- * @param url - Request URL
320
- * @param pattern - Regex pattern with capture group
321
- * @returns Extracted module or null
317
+ * @param {string} url - Request URL
318
+ * @param {RegExp} pattern - Regex pattern with capture group
319
+ * @returns {string | null} Extracted module or null
322
320
  * @public
323
321
  */
324
- function extractModuleFromUrl(url, pattern) {
325
- return pattern.exec(url)?.[1] ?? null;
326
- }
327
- /**
328
- * Returns current date-time in format: HH24:MI:SS.MS
329
- * @returns Formatted timestamp.
330
- */
331
- function nowUtcCompact() {
332
- const now = /* @__PURE__ */ new Date();
333
- 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")}`;
334
- }
335
- //#endregion
336
- //#region src/index.ts
322
+ const extractModuleFromUrl = (url, pattern) => {
323
+ const match = pattern.exec(url);
324
+ return Array.isArray(match) && typeof match[1] === "string" ? match[1] : null;
325
+ };
326
+ // src/index.ts
337
327
  /**
338
328
  * Backend Proxy Plugin
339
- * @param config - Plugin configuration
340
- * @returns Vite plugin
329
+ * @param {ProxyConfig} config - Plugin configuration
330
+ * @returns {Plugin} Vite plugin
341
331
  */
342
- function backendProxyPlugin(config) {
332
+ const backendProxyPlugin = (config) => {
343
333
  const proxy = new BackendProxy(config);
334
+ const handleRequest = async (url, req, res, server, next) => {
335
+ try {
336
+ if (!await proxy.handleRequest(url, req, res, server)) next();
337
+ } catch (error) {
338
+ next(error instanceof Error ? error : new Error(String(error)));
339
+ }
340
+ };
344
341
  return {
345
342
  name: "backend-proxy-plugin",
346
343
  configureServer(server) {
347
344
  proxy.log("info", "Plugin vite-plugin-backend-htmlconfigured", { backendBaseUrl: config.backendBaseUrl });
348
345
  server.middlewares.use((req, res, next) => {
349
- const url = req.url;
350
- if (!url) {
346
+ const { url } = req;
347
+ if (typeof url !== "string") {
351
348
  next();
352
349
  return;
353
350
  }
354
- proxy.handleRequest(url, req, res, server).then((handled) => {
355
- if (!handled) next();
356
- });
351
+ handleRequest(url, req, res, server, next);
357
352
  });
358
353
  }
359
354
  };
360
- }
361
- //#endregion
355
+ };
362
356
  export { backendProxyPlugin, createFetchBackendHandler, ensureLeadingSlash, extractModuleFromMeta, extractModuleFromUrl, joinUrlParts, normalizeRedirectLocation, stripLeadingSlash, stripTrailingSlash };
package/package.json CHANGED
@@ -1,66 +1,78 @@
1
1
  {
2
- "name": "vite-plugin-backend-html",
3
- "version": "0.2.0",
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": "prettier --check . && oxlint --type-aware --type-check && tsc",
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
- "devDependencies": {
43
- "@commitlint/cli": "^20.5.0",
44
- "@commitlint/config-conventional": "^20.5.0",
45
- "@types/debug": "^4.1.12",
46
- "@types/node": "^25.5.0",
47
- "@vitest/coverage-v8": "^4.1.0",
48
- "conventional-changelog": "^7.2.0",
49
- "conventional-changelog-angular": "^8.3.1",
50
- "eslint-plugin-regexp": "3.1.0",
51
- "husky": "^9.1.7",
52
- "oxlint": "^1.56.0",
53
- "oxlint-tsgolint": "^0.20.0",
54
- "prettier": "^3.8.1",
55
- "tsdown": "^0.21.4",
56
- "typescript": "^6.0.2",
57
- "vite": "^7.0.0 || ^8.0.0",
58
- "vitest": "^4.1.0"
59
- },
60
- "dependencies": {
61
- "debug": "^4.4.3"
62
- },
63
- "peerDependencies": {
64
- "vite": "^7.0.0 || ^8.0.0"
65
- }
66
- }
2
+ "$schema": "https://raw.githubusercontent.com/vitejs/vite-plugin-registry/refs/heads/main/data/schema/extended-package-json.schema.json",
3
+ "name": "vite-plugin-backend-html",
4
+ "version": "0.2.2",
5
+ "keywords": [
6
+ "backend",
7
+ "frontend",
8
+ "html",
9
+ "vite",
10
+ "vite-plugin"
11
+ ],
12
+ "homepage": "https://github.com/doberkofler/vite-plugin-merge-css#readme",
13
+ "license": "MIT",
14
+ "author": "Dieter Oberkofler",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git://github.com/doberkofler/vite-plugin-merge-css.git"
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "type": "module",
23
+ "main": "./dist/index.mjs",
24
+ "module": "./dist/index.mjs",
25
+ "types": "./dist/index.d.ts",
26
+ "exports": {
27
+ ".": "./dist/index.mjs",
28
+ "./package.json": "./package.json"
29
+ },
30
+ "dependencies": {
31
+ "debug": "^4.4.3"
32
+ },
33
+ "devDependencies": {
34
+ "@commitlint/cli": "^21.2.4",
35
+ "@commitlint/config-conventional": "^21.2.4",
36
+ "@types/debug": "^4.1.13",
37
+ "@types/node": "^26.6.6",
38
+ "@vitest/coverage-v8": "^5.1.1",
39
+ "conventional-changelog": "^8.1.3",
40
+ "conventional-changelog-angular": "^9.4.0",
41
+ "eslint-plugin-regexp": "3.3.3",
42
+ "husky": "^9.1.7",
43
+ "oxfmt": "^0.79.0",
44
+ "oxlint": "^1.94.0",
45
+ "oxlint-tsgolint": "^7.0.2007",
46
+ "release-it": "^21.1.2",
47
+ "tsdown": "^0.23.7",
48
+ "typescript": "^7.0.2",
49
+ "vite": "^7.0.0 || ^8.0.0",
50
+ "vitest": "^5.1.1"
51
+ },
52
+ "peerDependencies": {
53
+ "vite": "^7.0.0 || ^8.0.0"
54
+ },
55
+ "engines": {
56
+ "node": ">=22"
57
+ },
58
+ "compatiblePackages": {
59
+ "schemaVersion": 1,
60
+ "vite": {
61
+ "type": "compatible",
62
+ "versions": "^7.0.0 || ^8.0.0"
63
+ }
64
+ },
65
+ "scripts": {
66
+ "typecheck": "tsc --noEmit",
67
+ "lint": "oxlint",
68
+ "format": "oxfmt --write",
69
+ "format:check": "oxfmt --check",
70
+ "ci": "pnpm run typecheck && pnpm run lint && pnpm run format:check && pnpm run build && pnpm run test",
71
+ "dev": "tsdown --watch",
72
+ "build": "tsdown",
73
+ "test": "vitest run --coverage",
74
+ "create-changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
75
+ "pack-local": "rm -f *.tgz && npm run build && npm pack",
76
+ "release": "release-it"
77
+ }
78
+ }