vite-plugin-backend-html 0.1.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.
- package/dist/index.d.mts +33 -33
- package/dist/index.mjs +142 -153
- package/package.json +77 -66
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
|
|
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
|
-
})
|
|
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
|
|
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
|
|
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
|
|
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")
|
|
128
|
+
if (method === "POST") {
|
|
129
129
|
const chunks = [];
|
|
130
|
-
req.
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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}`);
|
|
@@ -196,28 +190,25 @@ var BackendProxy = class {
|
|
|
196
190
|
res.setHeader("location", result.location);
|
|
197
191
|
res.end();
|
|
198
192
|
return true;
|
|
199
|
-
default: {
|
|
200
|
-
const _exhaustive = result;
|
|
201
|
-
throw new Error(`Unhandled result type: ${JSON.stringify(_exhaustive)}`);
|
|
202
|
-
}
|
|
193
|
+
default: throw new Error(`Unhandled result type: ${JSON.stringify(result)}`);
|
|
203
194
|
}
|
|
204
195
|
}
|
|
205
196
|
/**
|
|
206
197
|
* Injects assets into HTML
|
|
207
|
-
* @param html - HTML content
|
|
208
|
-
* @param module - Optional module name
|
|
209
|
-
* @returns Processed HTML
|
|
198
|
+
* @param {string} html - HTML content
|
|
199
|
+
* @param {string | null} module - Optional module name
|
|
200
|
+
* @returns {string} Processed HTML
|
|
210
201
|
*/
|
|
211
202
|
injectAssets(html, module) {
|
|
212
203
|
const injection = [];
|
|
213
204
|
const inject = (entryPoints) => {
|
|
214
|
-
if (entryPoints.css) injection.push(`<link rel="stylesheet" href="${entryPoints.css}">`);
|
|
215
|
-
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>`);
|
|
216
207
|
};
|
|
217
208
|
const { globalEntryPoints, getModuleEntryPoints } = this.config.assetConfig;
|
|
218
209
|
inject({ js: "/@vite/client" });
|
|
219
210
|
inject(globalEntryPoints);
|
|
220
|
-
if (module) inject(getModuleEntryPoints(module));
|
|
211
|
+
if (typeof module === "string") inject(getModuleEntryPoints(module));
|
|
221
212
|
let processedHtml = html.replaceAll(/<link [^>]*href="(?:\/assets\/|\/q\/p\/)[^"]+"[^>]*>/g, "");
|
|
222
213
|
processedHtml = processedHtml.replaceAll(/<script [^>]*src="(?:\/assets\/|\/q\/p\/)[^"]+"[^>]*><\/script>/g, "");
|
|
223
214
|
if (processedHtml.includes("</head>")) return processedHtml.replace("</head>", `${injection.join("\n")}\n</head>`);
|
|
@@ -226,8 +217,8 @@ var BackendProxy = class {
|
|
|
226
217
|
}
|
|
227
218
|
/**
|
|
228
219
|
* Checks if the URL should be skipped (handled by Vite)
|
|
229
|
-
* @param url - Request URL
|
|
230
|
-
* @returns True if skipped
|
|
220
|
+
* @param {string} url - Request URL
|
|
221
|
+
* @returns {boolean} True if skipped
|
|
231
222
|
*/
|
|
232
223
|
shouldSkipForVite(url) {
|
|
233
224
|
if (this.config.bypass(url)) return true;
|
|
@@ -238,128 +229,126 @@ var BackendProxy = class {
|
|
|
238
229
|
};
|
|
239
230
|
/**
|
|
240
231
|
* Helper: Create fetch-based backend handler
|
|
241
|
-
* @param options - Handler options
|
|
242
|
-
* @param options.extractModule - Optional module extraction function
|
|
243
|
-
* @param options.transformBackendUrl - Optional function to transform the backend URL
|
|
244
|
-
* @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
|
|
245
236
|
* @public
|
|
246
237
|
*/
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
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
|
|
258
274
|
};
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
const contentType = response.headers.get("content-type") ?? "application/octet-stream";
|
|
268
|
-
const responseHeaders = {};
|
|
269
|
-
const setCookie = response.headers.getSetCookie();
|
|
270
|
-
if (setCookie.length > 0) {
|
|
271
|
-
logger("debug", `setCookie="${setCookie.join(", ")}"`);
|
|
272
|
-
responseHeaders["set-cookie"] = setCookie;
|
|
273
|
-
}
|
|
274
|
-
if (status >= 300 && status < 400) {
|
|
275
|
-
const rawLocation = response.headers.get("location");
|
|
276
|
-
if (!rawLocation) throw new Error(`Redirect ${status} missing Location header`);
|
|
277
|
-
const location = normalizeRedirectLocation(rawLocation, new URL(backendBaseUrl).pathname);
|
|
278
|
-
logger("debug", `redirect="${location}"`);
|
|
279
|
-
return {
|
|
280
|
-
type: "redirect",
|
|
281
|
-
status,
|
|
282
|
-
location,
|
|
283
|
-
headers: responseHeaders
|
|
284
|
-
};
|
|
285
|
-
}
|
|
286
|
-
if (contentType.includes("text/html")) {
|
|
287
|
-
const html = await response.text();
|
|
288
|
-
let module = null;
|
|
289
|
-
if (response.ok) {
|
|
290
|
-
const result = options.extractModule?.(url, html, response.headers);
|
|
291
|
-
module = (result instanceof Promise ? await result : result) ?? null;
|
|
292
|
-
}
|
|
293
|
-
logger("debug", `extracted module "${module}"`);
|
|
294
|
-
return {
|
|
295
|
-
type: "html",
|
|
296
|
-
content: html,
|
|
297
|
-
module,
|
|
298
|
-
headers: responseHeaders
|
|
299
|
-
};
|
|
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;
|
|
300
283
|
}
|
|
284
|
+
logger("debug", `extracted module "${module}"`);
|
|
301
285
|
return {
|
|
302
|
-
type: "
|
|
303
|
-
content:
|
|
304
|
-
|
|
305
|
-
status,
|
|
286
|
+
type: "html",
|
|
287
|
+
content: html,
|
|
288
|
+
module,
|
|
306
289
|
headers: responseHeaders
|
|
307
290
|
};
|
|
291
|
+
}
|
|
292
|
+
return {
|
|
293
|
+
type: "binary",
|
|
294
|
+
content: Buffer.from(await response.arrayBuffer()),
|
|
295
|
+
contentType,
|
|
296
|
+
status,
|
|
297
|
+
headers: responseHeaders
|
|
308
298
|
};
|
|
309
|
-
}
|
|
299
|
+
};
|
|
310
300
|
/**
|
|
311
301
|
* Helper: Extract module from HTML meta tag
|
|
312
|
-
* @param html - HTML content
|
|
313
|
-
* @param metaName - Name of meta tag
|
|
314
|
-
* @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
|
|
315
305
|
* @public
|
|
316
306
|
*/
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
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
|
+
};
|
|
320
311
|
/**
|
|
321
312
|
* Helper: Extract module from URL based on pattern
|
|
322
|
-
* @param url - Request URL
|
|
323
|
-
* @param pattern - Regex pattern with capture group
|
|
324
|
-
* @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
|
|
325
316
|
* @public
|
|
326
317
|
*/
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
* Returns current date-time in format: HH24:MI:SS.MS
|
|
332
|
-
* @returns Formatted timestamp.
|
|
333
|
-
*/
|
|
334
|
-
function nowUtcCompact() {
|
|
335
|
-
const now = /* @__PURE__ */ new Date();
|
|
336
|
-
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")}`;
|
|
337
|
-
}
|
|
318
|
+
const extractModuleFromUrl = (url, pattern) => {
|
|
319
|
+
const match = pattern.exec(url);
|
|
320
|
+
return Array.isArray(match) && typeof match[1] === "string" ? match[1] : null;
|
|
321
|
+
};
|
|
338
322
|
//#endregion
|
|
339
323
|
//#region src/index.ts
|
|
340
324
|
/**
|
|
341
325
|
* Backend Proxy Plugin
|
|
342
|
-
* @param config - Plugin configuration
|
|
343
|
-
* @returns Vite plugin
|
|
326
|
+
* @param {ProxyConfig} config - Plugin configuration
|
|
327
|
+
* @returns {Plugin} Vite plugin
|
|
344
328
|
*/
|
|
345
|
-
|
|
329
|
+
const backendProxyPlugin = (config) => {
|
|
346
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
|
+
};
|
|
347
338
|
return {
|
|
348
339
|
name: "backend-proxy-plugin",
|
|
349
340
|
configureServer(server) {
|
|
350
341
|
proxy.log("info", "Plugin vite-plugin-backend-htmlconfigured", { backendBaseUrl: config.backendBaseUrl });
|
|
351
342
|
server.middlewares.use((req, res, next) => {
|
|
352
|
-
const url = req
|
|
353
|
-
if (
|
|
343
|
+
const { url } = req;
|
|
344
|
+
if (typeof url !== "string") {
|
|
354
345
|
next();
|
|
355
346
|
return;
|
|
356
347
|
}
|
|
357
|
-
|
|
358
|
-
if (!handled) next();
|
|
359
|
-
});
|
|
348
|
+
handleRequest(url, req, res, server, next);
|
|
360
349
|
});
|
|
361
350
|
}
|
|
362
351
|
};
|
|
363
|
-
}
|
|
352
|
+
};
|
|
364
353
|
//#endregion
|
|
365
354
|
export { backendProxyPlugin, createFetchBackendHandler, ensureLeadingSlash, extractModuleFromMeta, extractModuleFromUrl, joinUrlParts, normalizeRedirectLocation, stripLeadingSlash, stripTrailingSlash };
|
package/package.json
CHANGED
|
@@ -1,67 +1,78 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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
|
+
}
|