vite-plugin-backend-html 0.2.0 → 0.2.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.
Files changed (3) hide show
  1. package/dist/index.d.mts +33 -33
  2. package/dist/index.mjs +141 -149
  3. package/package.json +77 -65
package/dist/index.d.mts CHANGED
@@ -56,8 +56,8 @@ type AssetConfig = {
56
56
  globalEntryPoints: EntryPoints;
57
57
  /**
58
58
  * Get module-specific entry points
59
- * @param module - Module name
60
- * @returns Entry points
59
+ * @param {string} module - Module name
60
+ * @returns {EntryPoints} Entry points
61
61
  */
62
62
  getModuleEntryPoints: (module: string) => EntryPoints;
63
63
  };
@@ -72,8 +72,8 @@ type ProxyConfig = {
72
72
  backendBaseUrl: string;
73
73
  /**
74
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
75
+ * @param {string} url - Request URL
76
+ * @returns {boolean} True if the request should be skipped (handled by Vite), false otherwise
77
77
  */
78
78
  bypass: (url: string) => boolean;
79
79
  /**
@@ -97,32 +97,32 @@ type ProxyConfig = {
97
97
  };
98
98
  /**
99
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
100
+ * @param {{ extractModule?: (url: string, html: string, headers: Headers) => string | null | Promise<string | null>; transformBackendUrl?: (url: string, backendBaseUrl: string) => string; }} options - Handler options
101
+ * @param {(url: string, html: string, headers: Headers) => string | null | Promise<string | null>} options.extractModule - Optional module extraction function
102
+ * @param {(url: string, backendBaseUrl: string) => string} options.transformBackendUrl - Optional function to transform the backend URL
103
+ * @returns {BackendHandler} Backend handler
104
104
  * @public
105
105
  */
106
- declare function createFetchBackendHandler(options: {
106
+ declare const createFetchBackendHandler: (options: {
107
107
  extractModule?: (url: string, html: string, headers: Headers) => string | null | Promise<string | null>;
108
108
  transformBackendUrl?: (url: string, backendBaseUrl: string) => string;
109
- }): BackendHandler;
109
+ }) => BackendHandler;
110
110
  /**
111
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
112
+ * @param {string} html - HTML content
113
+ * @param {string} metaName - Name of meta tag
114
+ * @returns {string | null} Extracted module or null
115
115
  * @public
116
116
  */
117
- declare function extractModuleFromMeta(html: string, metaName?: string): string | null;
117
+ declare const extractModuleFromMeta: (html: string, metaName?: string) => string | null;
118
118
  /**
119
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
120
+ * @param {string} url - Request URL
121
+ * @param {RegExp} pattern - Regex pattern with capture group
122
+ * @returns {string | null} Extracted module or null
123
123
  * @public
124
124
  */
125
- declare function extractModuleFromUrl(url: string, pattern: RegExp): string | null;
125
+ declare const extractModuleFromUrl: (url: string, pattern: RegExp) => string | null;
126
126
  //#endregion
127
127
  //#region src/path-utils.d.ts
128
128
  /**
@@ -130,30 +130,30 @@ declare function extractModuleFromUrl(url: string, pattern: RegExp): string | nu
130
130
  */
131
131
  /**
132
132
  * Strips trailing slashes from path
133
- * @param path - Path to normalize
134
- * @returns Path without trailing slashes
133
+ * @param {string} path - Path to normalize
134
+ * @returns {string} Path without trailing slashes
135
135
  * @public
136
136
  */
137
137
  declare const stripTrailingSlash: (path: string) => string;
138
138
  /**
139
139
  * Strips leading slashes from path
140
- * @param path - Path to normalize
141
- * @returns Path without leading slashes
140
+ * @param {string} path - Path to normalize
141
+ * @returns {string} Path without leading slashes
142
142
  * @public
143
143
  */
144
144
  declare const stripLeadingSlash: (path: string) => string;
145
145
  /**
146
146
  * Ensures path has exactly one leading slash
147
- * @param path - Path to normalize
148
- * @returns Path with single leading slash
147
+ * @param {string} path - Path to normalize
148
+ * @returns {string} Path with single leading slash
149
149
  * @public
150
150
  */
151
151
  declare const ensureLeadingSlash: (path: string) => string;
152
152
  /**
153
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
154
+ * @param {string} base - Base URL (trailing slash removed)
155
+ * @param {string} path - Path to append (leading slash removed)
156
+ * @returns {string} Joined URL
157
157
  * @public
158
158
  */
159
159
  declare const joinUrlParts: (base: string, path: string) => string;
@@ -164,9 +164,9 @@ declare const joinUrlParts: (base: string, path: string) => string;
164
164
  * - Absolute paths (strips base path if present)
165
165
  * - Relative paths (ensures leading slash)
166
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
167
+ * @param {string} location - Redirect location from backend
168
+ * @param {string} basePath - Base path to strip (e.g. '/lj_unittest/')
169
+ * @returns {string} Normalized location with single leading slash
170
170
  * @public
171
171
  */
172
172
  declare const normalizeRedirectLocation: (location: string, basePath: string) => string;
@@ -174,9 +174,9 @@ declare const normalizeRedirectLocation: (location: string, basePath: string) =>
174
174
  //#region src/index.d.ts
175
175
  /**
176
176
  * Backend Proxy Plugin
177
- * @param config - Plugin configuration
178
- * @returns Vite plugin
177
+ * @param {ProxyConfig} config - Plugin configuration
178
+ * @returns {Plugin} Vite plugin
179
179
  */
180
- declare function backendProxyPlugin(config: ProxyConfig): Plugin;
180
+ declare const backendProxyPlugin: (config: ProxyConfig) => Plugin;
181
181
  //#endregion
182
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 CHANGED
@@ -4,41 +4,33 @@
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) => {
@@ -63,6 +55,14 @@ const normalizeRedirectLocation = (location, basePath) => {
63
55
  //#endregion
64
56
  //#region src/backend-proxy.ts
65
57
  /**
58
+ * Returns current date-time in format: HH24:MI:SS.MS
59
+ * @returns {string} Formatted timestamp.
60
+ */
61
+ const nowUtcCompact = () => {
62
+ const now = /* @__PURE__ */ new Date();
63
+ 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")}`;
64
+ };
65
+ /**
66
66
  * Core backend proxy logic
67
67
  * @public
68
68
  */
@@ -70,16 +70,16 @@ var BackendProxy = class {
70
70
  config;
71
71
  /**
72
72
  * Creates a new backend proxy instance
73
- * @param config - Proxy configuration
73
+ * @param {ProxyConfig} config - Proxy configuration
74
74
  */
75
75
  constructor(config) {
76
76
  this.config = config;
77
77
  }
78
78
  /**
79
79
  * Logs a debug message
80
- * @param level - Log level
81
- * @param message - Message to log
82
- * @param data - Optional data to log
80
+ * @param {LoggingLevel} level - Log level
81
+ * @param {string} message - Message to log
82
+ * @param {unknown} data - Optional data to log
83
83
  */
84
84
  log(level, message, data) {
85
85
  if (!this.config.debug) return;
@@ -101,16 +101,16 @@ var BackendProxy = class {
101
101
  }
102
102
  /**
103
103
  * 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
104
+ * @param {string} url - Request URL
105
+ * @param {IncomingMessage} req - Node request object
106
+ * @param {ServerResponse} res - Node response object
107
+ * @param {ViteDevServer} server - Vite dev server
108
+ * @returns {Promise<boolean>} True if the request was handled, false otherwise
109
109
  */
110
110
  async handleRequest(url, req, res, server) {
111
111
  try {
112
112
  let currentUrl = url;
113
- if (this.config.rewrites) {
113
+ if (typeof this.config.rewrites !== "undefined") {
114
114
  for (const [prefix, replacement] of Object.entries(this.config.rewrites)) if (currentUrl.startsWith(prefix)) {
115
115
  const newUrl = currentUrl.replace(prefix, replacement);
116
116
  this.log("debug", `Rewrite URL: ${currentUrl} -> ${newUrl}`);
@@ -125,18 +125,12 @@ var BackendProxy = class {
125
125
  return false;
126
126
  }
127
127
  let body;
128
- if (method === "POST") body = await new Promise((resolve, reject) => {
128
+ if (method === "POST") {
129
129
  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
- });
130
+ for await (const chunk of req) if (Buffer.isBuffer(chunk)) chunks.push(chunk);
131
+ else chunks.push(Buffer.from(String(chunk)));
132
+ body = Buffer.concat(chunks);
133
+ }
140
134
  const result = await this.config.backendHandler({
141
135
  url: currentUrl,
142
136
  req,
@@ -161,14 +155,14 @@ var BackendProxy = class {
161
155
  }
162
156
  /**
163
157
  * 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
158
+ * @param {BackendResult} result - Result from backend handler
159
+ * @param {string} url - Request URL
160
+ * @param {ServerResponse} res - Node response object
161
+ * @param {ViteDevServer} server - Vite dev server
162
+ * @returns {Promise<boolean>} True if handled
169
163
  */
170
164
  async processResult(result, url, res, server) {
171
- if (result.headers) for (const [key, value] of Object.entries(result.headers)) res.setHeader(key, value);
165
+ if (typeof result.headers !== "undefined") for (const [key, value] of Object.entries(result.headers)) res.setHeader(key, value);
172
166
  switch (result.type) {
173
167
  case "html": {
174
168
  this.log("info", `-> HTML response: length=${result.content.length}`);
@@ -201,20 +195,20 @@ var BackendProxy = class {
201
195
  }
202
196
  /**
203
197
  * Injects assets into HTML
204
- * @param html - HTML content
205
- * @param module - Optional module name
206
- * @returns Processed HTML
198
+ * @param {string} html - HTML content
199
+ * @param {string | null} module - Optional module name
200
+ * @returns {string} Processed HTML
207
201
  */
208
202
  injectAssets(html, module) {
209
203
  const injection = [];
210
204
  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>`);
205
+ if (typeof entryPoints.css === "string" && entryPoints.css.length > 0) injection.push(`<link rel="stylesheet" href="${entryPoints.css}">`);
206
+ if (typeof entryPoints.js === "string" && entryPoints.js.length > 0) injection.push(`<script type="module" src="${entryPoints.js}"><\/script>`);
213
207
  };
214
208
  const { globalEntryPoints, getModuleEntryPoints } = this.config.assetConfig;
215
209
  inject({ js: "/@vite/client" });
216
210
  inject(globalEntryPoints);
217
- if (module) inject(getModuleEntryPoints(module));
211
+ if (typeof module === "string") inject(getModuleEntryPoints(module));
218
212
  let processedHtml = html.replaceAll(/<link [^>]*href="(?:\/assets\/|\/q\/p\/)[^"]+"[^>]*>/g, "");
219
213
  processedHtml = processedHtml.replaceAll(/<script [^>]*src="(?:\/assets\/|\/q\/p\/)[^"]+"[^>]*><\/script>/g, "");
220
214
  if (processedHtml.includes("</head>")) return processedHtml.replace("</head>", `${injection.join("\n")}\n</head>`);
@@ -223,8 +217,8 @@ var BackendProxy = class {
223
217
  }
224
218
  /**
225
219
  * Checks if the URL should be skipped (handled by Vite)
226
- * @param url - Request URL
227
- * @returns True if skipped
220
+ * @param {string} url - Request URL
221
+ * @returns {boolean} True if skipped
228
222
  */
229
223
  shouldSkipForVite(url) {
230
224
  if (this.config.bypass(url)) return true;
@@ -235,128 +229,126 @@ var BackendProxy = class {
235
229
  };
236
230
  /**
237
231
  * 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
232
+ * @param {{ extractModule?: (url: string, html: string, headers: Headers) => string | null | Promise<string | null>; transformBackendUrl?: (url: string, backendBaseUrl: string) => string; }} options - Handler options
233
+ * @param {(url: string, html: string, headers: Headers) => string | null | Promise<string | null>} options.extractModule - Optional module extraction function
234
+ * @param {(url: string, backendBaseUrl: string) => string} options.transformBackendUrl - Optional function to transform the backend URL
235
+ * @returns {BackendHandler} Backend handler
242
236
  * @public
243
237
  */
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);
250
- else fetchHeaders.set(key, value);
251
- const fetchOptions = {
252
- method,
253
- headers: fetchHeaders,
254
- redirect: "manual"
238
+ const createFetchBackendHandler = (options) => async ({ url, method, headers, body, backendBaseUrl, logger }) => {
239
+ const backendUrl = options.transformBackendUrl ? options.transformBackendUrl(url, backendBaseUrl) : `${backendBaseUrl}${url}`;
240
+ logger("debug", `backendBaseUrl="${backendBaseUrl}" args.url="${url}" url="${backendUrl}"`);
241
+ const fetchHeaders = new Headers();
242
+ 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);
243
+ else fetchHeaders.set(key, value);
244
+ const fetchOptions = {
245
+ method,
246
+ headers: fetchHeaders,
247
+ redirect: "manual"
248
+ };
249
+ if (method === "POST" && body !== void 0) fetchOptions.body = body;
250
+ const response = await fetch(backendUrl, fetchOptions);
251
+ logger("debug", "fetch results", {
252
+ ok: response.ok,
253
+ statusText: response.statusText,
254
+ redirected: response.redirected
255
+ });
256
+ const { status } = response;
257
+ const contentType = response.headers.get("content-type") ?? "application/octet-stream";
258
+ const responseHeaders = {};
259
+ const setCookie = response.headers.getSetCookie();
260
+ if (setCookie.length > 0) {
261
+ logger("debug", `setCookie="${setCookie.join(", ")}"`);
262
+ responseHeaders["set-cookie"] = setCookie;
263
+ }
264
+ if (status >= 300 && status < 400) {
265
+ const rawLocation = response.headers.get("location");
266
+ if (rawLocation === null || rawLocation.length === 0) throw new Error(`Redirect ${status} missing Location header`);
267
+ const location = normalizeRedirectLocation(rawLocation, new URL(backendBaseUrl).pathname);
268
+ logger("debug", `redirect="${location}"`);
269
+ return {
270
+ type: "redirect",
271
+ status,
272
+ location,
273
+ headers: responseHeaders
255
274
  };
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
- };
275
+ }
276
+ if (contentType.includes("text/html")) {
277
+ const html = await response.text();
278
+ let module = null;
279
+ const { extractModule } = options;
280
+ if (response.ok && typeof extractModule === "function") {
281
+ const result = extractModule(url, html, response.headers);
282
+ module = (result instanceof Promise ? await result : result) ?? null;
297
283
  }
284
+ logger("debug", `extracted module "${module}"`);
298
285
  return {
299
- type: "binary",
300
- content: Buffer.from(await response.arrayBuffer()),
301
- contentType,
302
- status,
286
+ type: "html",
287
+ content: html,
288
+ module,
303
289
  headers: responseHeaders
304
290
  };
291
+ }
292
+ return {
293
+ type: "binary",
294
+ content: Buffer.from(await response.arrayBuffer()),
295
+ contentType,
296
+ status,
297
+ headers: responseHeaders
305
298
  };
306
- }
299
+ };
307
300
  /**
308
301
  * 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
302
+ * @param {string} html - HTML content
303
+ * @param {string} metaName - Name of meta tag
304
+ * @returns {string | null} Extracted module or null
312
305
  * @public
313
306
  */
314
- function extractModuleFromMeta(html, metaName = "vite-module") {
315
- return new RegExp(`<meta name="${metaName}" content="([^"]+)">`).exec(html)?.[1] ?? null;
316
- }
307
+ const extractModuleFromMeta = (html, metaName = "vite-module") => {
308
+ const match = new RegExp(`<meta name="${metaName}" content="([^"]+)">`).exec(html);
309
+ return Array.isArray(match) && typeof match[1] === "string" ? match[1] : null;
310
+ };
317
311
  /**
318
312
  * 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
313
+ * @param {string} url - Request URL
314
+ * @param {RegExp} pattern - Regex pattern with capture group
315
+ * @returns {string | null} Extracted module or null
322
316
  * @public
323
317
  */
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
- }
318
+ const extractModuleFromUrl = (url, pattern) => {
319
+ const match = pattern.exec(url);
320
+ return Array.isArray(match) && typeof match[1] === "string" ? match[1] : null;
321
+ };
335
322
  //#endregion
336
323
  //#region src/index.ts
337
324
  /**
338
325
  * Backend Proxy Plugin
339
- * @param config - Plugin configuration
340
- * @returns Vite plugin
326
+ * @param {ProxyConfig} config - Plugin configuration
327
+ * @returns {Plugin} Vite plugin
341
328
  */
342
- function backendProxyPlugin(config) {
329
+ const backendProxyPlugin = (config) => {
343
330
  const proxy = new BackendProxy(config);
331
+ const handleRequest = async (url, req, res, server, next) => {
332
+ try {
333
+ if (!await proxy.handleRequest(url, req, res, server)) next();
334
+ } catch (error) {
335
+ next(error instanceof Error ? error : new Error(String(error)));
336
+ }
337
+ };
344
338
  return {
345
339
  name: "backend-proxy-plugin",
346
340
  configureServer(server) {
347
341
  proxy.log("info", "Plugin vite-plugin-backend-htmlconfigured", { backendBaseUrl: config.backendBaseUrl });
348
342
  server.middlewares.use((req, res, next) => {
349
- const url = req.url;
350
- if (!url) {
343
+ const { url } = req;
344
+ if (typeof url !== "string") {
351
345
  next();
352
346
  return;
353
347
  }
354
- proxy.handleRequest(url, req, res, server).then((handled) => {
355
- if (!handled) next();
356
- });
348
+ handleRequest(url, req, res, server, next);
357
349
  });
358
350
  }
359
351
  };
360
- }
352
+ };
361
353
  //#endregion
362
354
  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.1",
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": "^20.5.0",
35
+ "@commitlint/config-conventional": "^20.5.0",
36
+ "@types/debug": "^4.1.12",
37
+ "@types/node": "^25.6.0",
38
+ "@vitest/coverage-v8": "^4.1.4",
39
+ "conventional-changelog": "^7.2.0",
40
+ "conventional-changelog-angular": "^8.3.1",
41
+ "eslint-plugin-regexp": "3.1.0",
42
+ "husky": "^9.1.7",
43
+ "oxfmt": "^0.45.0",
44
+ "oxlint": "^1.60.0",
45
+ "oxlint-tsgolint": "^0.20.0",
46
+ "release-it": "^19.2.4",
47
+ "tsdown": "^0.21.8",
48
+ "typescript": "^6.0.2",
49
+ "vite": "^7.0.0 || ^8.0.0",
50
+ "vitest": "^4.1.4"
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
+ }