@gylautorun/dev-proxy-cookie 1.0.3 → 1.0.4
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 +37 -2
- package/dist/index.d.ts +37 -2
- package/dist/index.js +59 -11
- package/dist/index.min.js +4 -4
- package/dist/index.min.mjs +4 -4
- package/dist/index.mjs +58 -11
- package/package.json +1 -1
- package/src/proxy/apply-dev-authentications.ts +40 -0
- package/src/proxy/core.ts +14 -0
- package/src/proxy/index.ts +1 -0
- package/src/proxy/vite-middleware-plugin.ts +27 -11
- package/src/proxy/vue-proxy-config.ts +24 -3
package/dist/index.d.mts
CHANGED
|
@@ -2,6 +2,26 @@ import * as net from 'net';
|
|
|
2
2
|
import { IncomingMessage, ServerResponse } from 'http';
|
|
3
3
|
import { ViteDevServer } from 'vite';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* 应用开发环境自定义鉴权信息到代理请求头
|
|
7
|
+
*
|
|
8
|
+
* 将自定义鉴权信息数组展开为请求头键值对,注入到代理请求中。
|
|
9
|
+
* 支持多种鉴权方式,如 ticket、token、Authorization 等。
|
|
10
|
+
*
|
|
11
|
+
* @module apply-dev-authentications
|
|
12
|
+
*/
|
|
13
|
+
type AuthenticationItem = Record<string, string>;
|
|
14
|
+
/**
|
|
15
|
+
* 将自定义鉴权信息数组应用到代理请求头
|
|
16
|
+
*
|
|
17
|
+
* @param proxyReq - 代理请求对象
|
|
18
|
+
* @param authentications - 鉴权信息数组,每个元素是一个键值对对象
|
|
19
|
+
*/
|
|
20
|
+
declare function applyDevAuthentications(proxyReq: {
|
|
21
|
+
setHeader(name: string, value: string): void;
|
|
22
|
+
getHeader?(name: string): string | string[] | undefined;
|
|
23
|
+
}, authentications: AuthenticationItem[]): void;
|
|
24
|
+
|
|
5
25
|
/**
|
|
6
26
|
* 错误回调函数类型
|
|
7
27
|
* @param err - 错误对象
|
|
@@ -72,6 +92,11 @@ interface AutoProxyCookieOptions {
|
|
|
72
92
|
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
73
93
|
*/
|
|
74
94
|
useCookie?: boolean;
|
|
95
|
+
/**
|
|
96
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
97
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
98
|
+
*/
|
|
99
|
+
authentications?: AuthenticationItem[];
|
|
75
100
|
}
|
|
76
101
|
/**
|
|
77
102
|
* 自动代理 Cookie 类
|
|
@@ -185,7 +210,7 @@ declare function createAutoProxyCookie(options: AutoProxyCookieOptions): AutoPro
|
|
|
185
210
|
* Vite 中间件代理 Cookie 插件配置选项
|
|
186
211
|
*/
|
|
187
212
|
interface ViteMiddlewareProxyOptions {
|
|
188
|
-
/** Cookie
|
|
213
|
+
/** Cookie 文件路径, 使用文件方便监听cookie 变化,避免手动启动更新 */
|
|
189
214
|
cookieFile: string;
|
|
190
215
|
/** 默认代理目标地址 */
|
|
191
216
|
target: string;
|
|
@@ -199,6 +224,11 @@ interface ViteMiddlewareProxyOptions {
|
|
|
199
224
|
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
200
225
|
*/
|
|
201
226
|
useCookie?: boolean;
|
|
227
|
+
/**
|
|
228
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
229
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
230
|
+
*/
|
|
231
|
+
authentications?: AuthenticationItem[];
|
|
202
232
|
/**
|
|
203
233
|
* 代理路径映射表
|
|
204
234
|
* 键:路径前缀,值:代理目标地址
|
|
@@ -276,6 +306,11 @@ interface VueProxyConfigOptions {
|
|
|
276
306
|
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
277
307
|
*/
|
|
278
308
|
useCookie?: boolean;
|
|
309
|
+
/**
|
|
310
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
311
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
312
|
+
*/
|
|
313
|
+
authentications?: AuthenticationItem[];
|
|
279
314
|
/** 自定义请求头 */
|
|
280
315
|
headers?: Record<string, string>;
|
|
281
316
|
/** 是否启用 WebSocket 代理 */
|
|
@@ -498,4 +533,4 @@ declare function detectProductionEnvironment(customEnvs?: string[], debug?: bool
|
|
|
498
533
|
*/
|
|
499
534
|
declare function shouldEnableWatch(watch: boolean | 'auto', customEnvs?: string[], debug?: boolean, loggerPrefix?: string): boolean;
|
|
500
535
|
|
|
501
|
-
export { type AutoProxyConfigOptions, AutoProxyCookie, type AutoProxyCookieOptions, CookieReader, type CookieReaderOptions, CookieWatcher, type CookieWatcherOptions, type CreateFileCookieGetterOptions, type ErrorCallback, type ProxyConfig, type ProxyHooks, type ViteMiddlewareProxyOptions, type VueProxyConfigOptions, createAutoProxyConfig, createAutoProxyCookie, createCookieGetter, createFileCookieGetter, createVueProxyConfig, detectProductionEnvironment, isProductionValue, shouldEnableWatch, viteMiddlewareProxy, watchCookieFile };
|
|
536
|
+
export { type AuthenticationItem, type AutoProxyConfigOptions, AutoProxyCookie, type AutoProxyCookieOptions, CookieReader, type CookieReaderOptions, CookieWatcher, type CookieWatcherOptions, type CreateFileCookieGetterOptions, type ErrorCallback, type ProxyConfig, type ProxyHooks, type ViteMiddlewareProxyOptions, type VueProxyConfigOptions, applyDevAuthentications, createAutoProxyConfig, createAutoProxyCookie, createCookieGetter, createFileCookieGetter, createVueProxyConfig, detectProductionEnvironment, isProductionValue, shouldEnableWatch, viteMiddlewareProxy, watchCookieFile };
|
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,26 @@ import * as net from 'net';
|
|
|
2
2
|
import { IncomingMessage, ServerResponse } from 'http';
|
|
3
3
|
import { ViteDevServer } from 'vite';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* 应用开发环境自定义鉴权信息到代理请求头
|
|
7
|
+
*
|
|
8
|
+
* 将自定义鉴权信息数组展开为请求头键值对,注入到代理请求中。
|
|
9
|
+
* 支持多种鉴权方式,如 ticket、token、Authorization 等。
|
|
10
|
+
*
|
|
11
|
+
* @module apply-dev-authentications
|
|
12
|
+
*/
|
|
13
|
+
type AuthenticationItem = Record<string, string>;
|
|
14
|
+
/**
|
|
15
|
+
* 将自定义鉴权信息数组应用到代理请求头
|
|
16
|
+
*
|
|
17
|
+
* @param proxyReq - 代理请求对象
|
|
18
|
+
* @param authentications - 鉴权信息数组,每个元素是一个键值对对象
|
|
19
|
+
*/
|
|
20
|
+
declare function applyDevAuthentications(proxyReq: {
|
|
21
|
+
setHeader(name: string, value: string): void;
|
|
22
|
+
getHeader?(name: string): string | string[] | undefined;
|
|
23
|
+
}, authentications: AuthenticationItem[]): void;
|
|
24
|
+
|
|
5
25
|
/**
|
|
6
26
|
* 错误回调函数类型
|
|
7
27
|
* @param err - 错误对象
|
|
@@ -72,6 +92,11 @@ interface AutoProxyCookieOptions {
|
|
|
72
92
|
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
73
93
|
*/
|
|
74
94
|
useCookie?: boolean;
|
|
95
|
+
/**
|
|
96
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
97
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
98
|
+
*/
|
|
99
|
+
authentications?: AuthenticationItem[];
|
|
75
100
|
}
|
|
76
101
|
/**
|
|
77
102
|
* 自动代理 Cookie 类
|
|
@@ -185,7 +210,7 @@ declare function createAutoProxyCookie(options: AutoProxyCookieOptions): AutoPro
|
|
|
185
210
|
* Vite 中间件代理 Cookie 插件配置选项
|
|
186
211
|
*/
|
|
187
212
|
interface ViteMiddlewareProxyOptions {
|
|
188
|
-
/** Cookie
|
|
213
|
+
/** Cookie 文件路径, 使用文件方便监听cookie 变化,避免手动启动更新 */
|
|
189
214
|
cookieFile: string;
|
|
190
215
|
/** 默认代理目标地址 */
|
|
191
216
|
target: string;
|
|
@@ -199,6 +224,11 @@ interface ViteMiddlewareProxyOptions {
|
|
|
199
224
|
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
200
225
|
*/
|
|
201
226
|
useCookie?: boolean;
|
|
227
|
+
/**
|
|
228
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
229
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
230
|
+
*/
|
|
231
|
+
authentications?: AuthenticationItem[];
|
|
202
232
|
/**
|
|
203
233
|
* 代理路径映射表
|
|
204
234
|
* 键:路径前缀,值:代理目标地址
|
|
@@ -276,6 +306,11 @@ interface VueProxyConfigOptions {
|
|
|
276
306
|
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
277
307
|
*/
|
|
278
308
|
useCookie?: boolean;
|
|
309
|
+
/**
|
|
310
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
311
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
312
|
+
*/
|
|
313
|
+
authentications?: AuthenticationItem[];
|
|
279
314
|
/** 自定义请求头 */
|
|
280
315
|
headers?: Record<string, string>;
|
|
281
316
|
/** 是否启用 WebSocket 代理 */
|
|
@@ -498,4 +533,4 @@ declare function detectProductionEnvironment(customEnvs?: string[], debug?: bool
|
|
|
498
533
|
*/
|
|
499
534
|
declare function shouldEnableWatch(watch: boolean | 'auto', customEnvs?: string[], debug?: boolean, loggerPrefix?: string): boolean;
|
|
500
535
|
|
|
501
|
-
export { type AutoProxyConfigOptions, AutoProxyCookie, type AutoProxyCookieOptions, CookieReader, type CookieReaderOptions, CookieWatcher, type CookieWatcherOptions, type CreateFileCookieGetterOptions, type ErrorCallback, type ProxyConfig, type ProxyHooks, type ViteMiddlewareProxyOptions, type VueProxyConfigOptions, createAutoProxyConfig, createAutoProxyCookie, createCookieGetter, createFileCookieGetter, createVueProxyConfig, detectProductionEnvironment, isProductionValue, shouldEnableWatch, viteMiddlewareProxy, watchCookieFile };
|
|
536
|
+
export { type AuthenticationItem, type AutoProxyConfigOptions, AutoProxyCookie, type AutoProxyCookieOptions, CookieReader, type CookieReaderOptions, CookieWatcher, type CookieWatcherOptions, type CreateFileCookieGetterOptions, type ErrorCallback, type ProxyConfig, type ProxyHooks, type ViteMiddlewareProxyOptions, type VueProxyConfigOptions, applyDevAuthentications, createAutoProxyConfig, createAutoProxyCookie, createCookieGetter, createFileCookieGetter, createVueProxyConfig, detectProductionEnvironment, isProductionValue, shouldEnableWatch, viteMiddlewareProxy, watchCookieFile };
|
package/dist/index.js
CHANGED
|
@@ -33,6 +33,7 @@ __export(index_exports, {
|
|
|
33
33
|
AutoProxyCookie: () => AutoProxyCookie,
|
|
34
34
|
CookieReader: () => CookieReader,
|
|
35
35
|
CookieWatcher: () => CookieWatcher,
|
|
36
|
+
applyDevAuthentications: () => applyDevAuthentications,
|
|
36
37
|
createAutoProxyConfig: () => createAutoProxyConfig,
|
|
37
38
|
createAutoProxyCookie: () => createAutoProxyCookie,
|
|
38
39
|
createCookieGetter: () => createCookieGetter,
|
|
@@ -336,6 +337,24 @@ function applyDevCookieHeader(proxyReq, cookie) {
|
|
|
336
337
|
console.log("[applyDevCookieHeader] === END ===");
|
|
337
338
|
}
|
|
338
339
|
|
|
340
|
+
// src/proxy/apply-dev-authentications.ts
|
|
341
|
+
function applyDevAuthentications(proxyReq, authentications) {
|
|
342
|
+
console.log("[applyDevAuthentications] === START ===");
|
|
343
|
+
if (!authentications || authentications.length === 0) {
|
|
344
|
+
console.log("[applyDevAuthentications] Authentications is empty, returning");
|
|
345
|
+
console.log("[applyDevAuthentications] === END ===");
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
console.log("[applyDevAuthentications] Applying authentications:", JSON.stringify(authentications));
|
|
349
|
+
for (const authItem of authentications) {
|
|
350
|
+
for (const [key, value] of Object.entries(authItem)) {
|
|
351
|
+
proxyReq.setHeader(key, value);
|
|
352
|
+
console.log("[applyDevAuthentications] Set header:", key, "->", value);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
console.log("[applyDevAuthentications] === END ===");
|
|
356
|
+
}
|
|
357
|
+
|
|
339
358
|
// src/proxy/core.ts
|
|
340
359
|
var AutoProxyCookie = class {
|
|
341
360
|
/**
|
|
@@ -391,6 +410,12 @@ var AutoProxyCookie = class {
|
|
|
391
410
|
} else {
|
|
392
411
|
console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!");
|
|
393
412
|
}
|
|
413
|
+
const authentications = this.options.authentications || [];
|
|
414
|
+
if (authentications.length > 0) {
|
|
415
|
+
console.log("[AutoProxyCookie] Applying authentications headers...");
|
|
416
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
417
|
+
console.log("[AutoProxyCookie] Authentications headers applied successfully");
|
|
418
|
+
}
|
|
394
419
|
this.log("debug", "[AutoProxyCookie] Proxy Request:", req.method, req.url);
|
|
395
420
|
if (this.options.hooks.onProxyReq) {
|
|
396
421
|
try {
|
|
@@ -510,6 +535,7 @@ var AutoProxyCookie = class {
|
|
|
510
535
|
cookiePathRewrite: false,
|
|
511
536
|
headers: {},
|
|
512
537
|
useCookie: true,
|
|
538
|
+
authentications: [],
|
|
513
539
|
...mergedOptions
|
|
514
540
|
};
|
|
515
541
|
this.cookieReader = new CookieReader({ cookieFile: options.cookieFile }, options.debug ?? false);
|
|
@@ -788,6 +814,7 @@ function viteMiddlewareProxy(options) {
|
|
|
788
814
|
target,
|
|
789
815
|
debug = false,
|
|
790
816
|
useCookie = true,
|
|
817
|
+
authentications = [],
|
|
791
818
|
proxyMap = {},
|
|
792
819
|
proxyPaths = [],
|
|
793
820
|
ignorePaths = []
|
|
@@ -827,26 +854,33 @@ function viteMiddlewareProxy(options) {
|
|
|
827
854
|
if (debug) {
|
|
828
855
|
console.log("[ViteMiddlewareProxy] Proxying:", req.method, pathname, "->", proxyTarget);
|
|
829
856
|
}
|
|
857
|
+
proxyServer.web(req, res, {
|
|
858
|
+
target: proxyTarget,
|
|
859
|
+
changeOrigin: true,
|
|
860
|
+
secure: false,
|
|
861
|
+
ignorePath: false
|
|
862
|
+
});
|
|
863
|
+
});
|
|
864
|
+
proxyServer.on("proxyReq", (proxyReq, req) => {
|
|
830
865
|
if (useCookie) {
|
|
831
866
|
currentCookie = cookieReader.readCookie();
|
|
832
867
|
if (currentCookie) {
|
|
833
868
|
if (debug) {
|
|
834
869
|
console.log("[ViteMiddlewareProxy] Injecting cookie:", `(length: ${currentCookie.length})`);
|
|
835
870
|
}
|
|
836
|
-
|
|
837
|
-
req.headers["Cookie"] = currentCookie;
|
|
871
|
+
applyDevCookieHeader(proxyReq, currentCookie);
|
|
838
872
|
} else if (debug) {
|
|
839
873
|
console.log("[ViteMiddlewareProxy] Cookie file is empty");
|
|
840
874
|
}
|
|
841
875
|
} else if (debug) {
|
|
842
876
|
console.log("[ViteMiddlewareProxy] useCookie is false, skipping cookie injection");
|
|
843
877
|
}
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
}
|
|
878
|
+
if (authentications && authentications.length > 0) {
|
|
879
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
880
|
+
if (debug) {
|
|
881
|
+
console.log("[ViteMiddlewareProxy] Injecting authentications:", JSON.stringify(authentications));
|
|
882
|
+
}
|
|
883
|
+
}
|
|
850
884
|
});
|
|
851
885
|
proxyServer.on("error", (err, req) => {
|
|
852
886
|
console.error("[ViteMiddlewareProxy] Proxy error:", err.message, "for", req.url);
|
|
@@ -862,6 +896,7 @@ function createVueProxyConfig(target, options = {}) {
|
|
|
862
896
|
getCookie,
|
|
863
897
|
debug = false,
|
|
864
898
|
useCookie = true,
|
|
899
|
+
authentications = [],
|
|
865
900
|
headers = {},
|
|
866
901
|
ws = false,
|
|
867
902
|
changeOrigin = true,
|
|
@@ -887,6 +922,12 @@ function createVueProxyConfig(target, options = {}) {
|
|
|
887
922
|
} else if (debug) {
|
|
888
923
|
console.log("[Proxy Request]", reqPath, req.method, "(useCookie is false, skipping cookie injection)");
|
|
889
924
|
}
|
|
925
|
+
if (authentications && authentications.length > 0) {
|
|
926
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
927
|
+
if (debug) {
|
|
928
|
+
console.log("[Proxy Request]", reqPath, req.method, "(with authentications)");
|
|
929
|
+
}
|
|
930
|
+
}
|
|
890
931
|
},
|
|
891
932
|
onError: customOnError || ((err) => {
|
|
892
933
|
console.error("\n[Proxy Error]", err.message);
|
|
@@ -929,11 +970,11 @@ function createFileCookieGetter(cookieFile, options = {}) {
|
|
|
929
970
|
return () => reader.readCookie();
|
|
930
971
|
}
|
|
931
972
|
function createAutoProxyConfig(options) {
|
|
932
|
-
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers, useCookie = true } = options;
|
|
973
|
+
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers, useCookie = true, authentications = [] } = options;
|
|
933
974
|
const result = {};
|
|
934
975
|
if (includePaths.length > 0) {
|
|
935
976
|
for (const proxyPath of includePaths) {
|
|
936
|
-
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers, useCookie });
|
|
977
|
+
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers, useCookie, authentications });
|
|
937
978
|
}
|
|
938
979
|
} else {
|
|
939
980
|
const defaultProxy = {
|
|
@@ -958,6 +999,12 @@ function createAutoProxyConfig(options) {
|
|
|
958
999
|
} else if (debug) {
|
|
959
1000
|
console.log("[Proxy Request]", reqPath, req.method, "(useCookie is false, skipping cookie injection)");
|
|
960
1001
|
}
|
|
1002
|
+
if (authentications && authentications.length > 0) {
|
|
1003
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
1004
|
+
if (debug) {
|
|
1005
|
+
console.log("[Proxy Request]", reqPath, req.method, "(with authentications)");
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
961
1008
|
},
|
|
962
1009
|
onError: (err) => {
|
|
963
1010
|
console.error("\n[Proxy Error]", err.message);
|
|
@@ -966,7 +1013,7 @@ function createAutoProxyConfig(options) {
|
|
|
966
1013
|
result["/"] = defaultProxy;
|
|
967
1014
|
}
|
|
968
1015
|
for (const [proxyPath, proxyTarget] of Object.entries(additionalProxies)) {
|
|
969
|
-
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers, useCookie });
|
|
1016
|
+
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers, useCookie, authentications });
|
|
970
1017
|
}
|
|
971
1018
|
return result;
|
|
972
1019
|
}
|
|
@@ -975,6 +1022,7 @@ function createAutoProxyConfig(options) {
|
|
|
975
1022
|
AutoProxyCookie,
|
|
976
1023
|
CookieReader,
|
|
977
1024
|
CookieWatcher,
|
|
1025
|
+
applyDevAuthentications,
|
|
978
1026
|
createAutoProxyConfig,
|
|
979
1027
|
createAutoProxyCookie,
|
|
980
1028
|
createCookieGetter,
|
package/dist/index.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")).join("; ");return this.debug&&console.log("[CookieReader] Parsed cookie:",n?"(has cookie)":"(empty)"),n}return this.debug&&console.log("[CookieReader] Cookie file not found:",o),""}catch(o){return this.debug&&console.error("[CookieReader] Error reading cookie file:",o.message),""}}ensureCookieFile(){let o=C.resolve(this.options.cookieFile),e=C.dirname(o);k.existsSync(e)||k.mkdirSync(e,{recursive:!0}),k.existsSync(o)||k.writeFileSync(o,"")}};function J(t){let o=new d({cookieFile:t});return()=>o.readCookie()}var I=f(require("path")),W=f(require("chokidar"));var w=class{constructor(o){this.watcher=null;this.lastContent="";this.handleChange=()=>{let o=this.cookieReader.readCookie();o!==this.lastContent&&(this.lastContent=o,this.options.onCookieChange(o),console.log(`[CookieWatcher] Cookie updated from file: ${this.options.cookieFile}`))};this.options={autoCreateFile:!0,...o},this.cookieReader=new d({cookieFile:o.cookieFile})}start(){this.options.autoCreateFile&&this.cookieReader.ensureCookieFile();let o=I.resolve(this.options.cookieFile);this.lastContent=this.cookieReader.readCookie(),console.log(`[CookieWatcher] Started watching: ${o}`);try{this.watcher=W.default.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}}),this.watcher.on("change",this.handleChange),this.watcher.on("add",this.handleChange),this.watcher.on("error",e=>{this.options.onError?.(e)})}catch(e){this.options.onError?.(e)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,console.log(`[CookieWatcher] Stopped watching: ${this.options.cookieFile}`))}getCurrentCookie(){return this.lastContent}};function P(t,o,e){let r=new w({cookieFile:t,onCookieChange:o,onError:e});return r.start(),r}function A(t){return["production","prod","prd","release","staging","uat"].includes(t.toLowerCase().trim())}function H(t=[],o=!1,e="[env-detector]"){let r=process.env;if(t.length>0)for(let i of t){let a=r[i];if(a&&A(a))return o&&console.log(`${e} Detected production via custom env: ${i}=${a}`),!0}let s=["NODE_ENV","BUILD_MODE","VUE_APP_ENV","VITE_NODE_ENV","WEBPACK_MODE","CI_ENV","APP_ENV","ENV","DEPLOY_ENV","RUN_MODE"];for(let i of s){let a=r[i];if(a&&A(a))return o&&console.log(`${e} Detected production via env: ${i}=${a}`),!0}if(r.CI==="true"||r.CI==="1"||r.CI==="yes")return o&&console.log(`${e} Detected production via CI env`),!0;if(r.npm_lifecycle_event){let i=r.npm_lifecycle_event.toLowerCase();if(i.includes("build")||i.includes("prod")||i.includes("prd")||i.includes("release"))return o&&console.log(`${e} Detected production via lifecycle event: ${r.npm_lifecycle_event}`),!0}let n=process.argv.join("").toLowerCase();return n.includes("build")||n.includes("production")||n.includes("--mode=production")||n.includes("--prod")||n.includes("--release")?(o&&console.log(`${e} Detected production via process arguments`),!0):!1}function E(t,o=[],e=!1,r="[env-detector]"){return typeof t=="boolean"?(e&&!t&&console.log(`${r} Watch disabled by user setting`),t):H(o,e,r)?(e&&console.log(`${r} Auto-detected production mode - disabling watch`),!1):(e&&console.log(`${r} Auto-detected development mode - enabling watch`),!0)}function v(t,o){if(console.log("[applyDevCookieHeader] === START ==="),console.log("[applyDevCookieHeader] Cookie to apply:",o?`(length: ${o.length})`:"(empty)"),!o){console.log("[applyDevCookieHeader] Cookie is empty, returning"),console.log("[applyDevCookieHeader] === END ===");return}let e=t.getHeader?.("Cookie");if(console.log("[applyDevCookieHeader] Cookie current:",e?`(length: ${String(e).length})`:"(none)"),e===o){console.log("[applyDevCookieHeader] Cookie is already set, skipping"),console.log("[applyDevCookieHeader] === END ===");return}t.removeHeader("cookie"),t.removeHeader("Cookie"),t.setHeader("Cookie",o);let r=t.getHeader?.("Cookie");console.log("[applyDevCookieHeader] Cookie new:",r?`(length: ${String(r).length})`:"(failed)"),console.log("[applyDevCookieHeader] === END ===")}var R=class{constructor(o){this.currentCookie="";this.server=null;this.proxyServer=null;this.watcher=null;this.handleCookieChange=o=>{if(o!==this.currentCookie&&(this.currentCookie=o,this.log("info","[AutoProxyCookie] Cookie updated:",o?"(has cookie)":"(empty)"),this.options.autoRestart&&this.options.restartMarkerFile)){let e=U.resolve(this.options.restartMarkerFile);$.writeFileSync(e,JSON.stringify({timestamp:Date.now(),cookie:o},null,2)),this.log("info","[AutoProxyCookie] Restart marker written to:",e),this.log("info","[AutoProxyCookie] Please restart the dev server for changes to take effect")}};this.handleOnProxyReq=(o,e,r,s)=>{if(console.log("[AutoProxyCookie] === handleOnProxyReq START ==="),console.log("[AutoProxyCookie] Request URL:",e.method,e.url),console.log("[AutoProxyCookie] useCookie:",this.options.useCookie),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.options.useCookie&&this.currentCookie?(console.log("[AutoProxyCookie] Applying cookie header..."),v(o,this.currentCookie),console.log("[AutoProxyCookie] Cookie header applied successfully")):this.options.useCookie?console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!"):console.log("[AutoProxyCookie] useCookie is false, skipping cookie injection"),this.log("debug","[AutoProxyCookie] Proxy Request:",e.method,e.url),this.options.hooks.onProxyReq)try{this.options.hooks.onProxyReq(o,e,r)}catch(n){this.log("error","[AutoProxyCookie] onProxyReq hook error:",n.message)}console.log("[AutoProxyCookie] === handleOnProxyReq END ===")};this.handleOnProxyRes=(o,e,r)=>{let s=["Content-Type","Content-Length","Authorization","Set-Cookie","X-Requested-With","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"];if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),r.setHeader("Access-Control-Allow-Headers",s.join(",")),r.setHeader("Access-Control-Allow-Credentials","true"),this.log("debug","[AutoProxyCookie] Proxy Response:",e.url,o.statusCode),this.options.hooks.onProxyRes)try{this.options.hooks.onProxyRes(o,e,r)}catch(n){this.log("error","[AutoProxyCookie] onProxyRes hook error:",n.message)}};this.handleOnError=(o,e,r)=>{if(this.log("error","[AutoProxyCookie] Proxy Error:",o.message),this.log("error","[AutoProxyCookie] URL:",e.url),r instanceof V.ServerResponse&&!r.headersSent&&(r.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),r.end(JSON.stringify({success:!1,message:"\u670D\u52A1\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",error:o.message}))),this.options.hooks.onError)try{this.options.hooks.onError(o,e,r)}catch(s){this.log("error","[AutoProxyCookie] onError hook error:",s.message)}};this.handleOnWsError=(o,e,r)=>{if(this.log("error","[AutoProxyCookie] WebSocket Proxy Error:",o.message),this.log("error","[AutoProxyCookie] WebSocket URL:",e.url),r&&r.close(),this.options.hooks.onWsError)try{this.options.hooks.onWsError(o,e,r)}catch(s){this.log("error","[AutoProxyCookie] onWsError hook error:",s.message)}};let r={...o,hooks:{...{onProxyReq:()=>{},onProxyRes:()=>{},onError:()=>{},onWsError:()=>{}},...o.hooks||{}}};this.options={debug:!1,autoRestart:!1,restartMarkerFile:".cookie-restart-marker",proxyMap:{},proxyPaths:[],ignorePaths:[],ws:!0,changeOrigin:!0,secure:!1,followRedirects:!0,autoRewrite:!1,protocolRewrite:void 0,logLevel:"info",cookieDomainRewrite:"*",cookiePathRewrite:!1,headers:{},useCookie:!0,...r},this.cookieReader=new d({cookieFile:o.cookieFile},o.debug??!1)}getProxyUrl(o){let e=o.url||"/",r=new URL(e,"http://localhost").pathname,s=this.options.proxyMap||{},n=this.options.proxyPaths||[];this.log("debug","[AutoProxyCookie] getProxyUrl - Request path:",r),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyMap paths:",Object.keys(s)),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyPaths:",n);for(let[i,a]of Object.entries(s)){let l=r.startsWith(i);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyMap:",i,"- matches:",l),l)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyMap:",i,"->",a),a}for(let i of n){let a=r.startsWith(i);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyPaths:",i,"- matches:",a),a)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyPaths:",i,"->",this.options.target),this.options.target}return this.log("debug","[AutoProxyCookie] getProxyUrl - No match found, using default target:",this.options.target),this.options.target}isIgnoredPath(o){return(this.options.ignorePaths||[]).some(r=>o.startsWith(r))}log(o,...e){let r={debug:0,info:1,warn:2,error:3},s=this.options.debug?"debug":this.options.logLevel||"info",n=r[s];r[o]>=n&&(o==="error"?console.error(...e):o==="warn"?console.warn(...e):console.log(...e))}createProxyOptions(o){let{ws:e,changeOrigin:r,secure:s,followRedirects:n,autoRewrite:i,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:g,headers:p}=this.options;return{target:o,ws:e,changeOrigin:r,secure:s,followRedirects:n,autoRewrite:i,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:g,headers:{...p},ignorePath:!1}}async setup(o){this.server=o,this.currentCookie=this.cookieReader.readCookie();try{let e={target:this.options.target,changeOrigin:this.options.changeOrigin,secure:this.options.secure,followRedirects:this.options.followRedirects,autoRewrite:this.options.autoRewrite,protocolRewrite:this.options.protocolRewrite,cookieDomainRewrite:this.options.cookieDomainRewrite,cookiePathRewrite:this.options.cookiePathRewrite,ws:this.options.ws};this.proxyServer=L.default.createProxyServer(e),this.proxyServer.on("proxyReq",this.handleOnProxyReq),this.proxyServer.on("proxyRes",this.handleOnProxyRes),this.proxyServer.on("error",this.handleOnError),this.options.ws&&this.proxyServer.on("wsError",this.handleOnWsError),this.log("info","[AutoProxyCookie] Proxy server created with WebSocket support")}catch(e){this.log("warn","[AutoProxyCookie] http-proxy create failed, using basic mode:",e.message)}o.middlewares.use((e,r,s)=>{let n=e.url||"/",i=new URL(n,"http://localhost").pathname;if(console.log("[AutoProxyCookie] === Incoming Request ==="),console.log("[AutoProxyCookie] Method:",e.method),console.log("[AutoProxyCookie] Full URL:",n),console.log("[AutoProxyCookie] Pathname:",i),console.log("[AutoProxyCookie] useCookie:",this.options.useCookie),console.log("[AutoProxyCookie] Headers:",JSON.stringify(e.headers,null,2)),this.isIgnoredPath(i)){console.log("[AutoProxyCookie] Path ignored, passing to next middleware"),s();return}this.options.useCookie?(this.currentCookie=this.cookieReader.readCookie(),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.currentCookie&&console.log("[AutoProxyCookie] Cookie preview:",this.currentCookie)):console.log("[AutoProxyCookie] useCookie is false, skipping cookie reading");let a=Object.keys(this.options.proxyMap||{}),l=this.options.proxyPaths||[],p=[...a,...l].some(h=>i.startsWith(h));if(console.log("[AutoProxyCookie] Path matches proxy rules:",p),this.proxyServer){let h=this.getProxyUrl(e);console.log(`[AutoProxyCookie] Proxying ${e.method} ${i} -> ${h}`);let y=this.createProxyOptions(h);try{console.log("[AutoProxyCookie] Calling proxyServer.web..."),this.proxyServer.web(e,r,y),console.log("[AutoProxyCookie] proxyServer.web called successfully")}catch(u){console.error("[AutoProxyCookie] Proxy web error:",u.message),s(u)}}else console.log("[AutoProxyCookie] No proxy server, passing to next middleware"),s()}),this.options.ws&&this.server.httpServer&&this.proxyServer&&(this.server.httpServer.on("upgrade",(e,r,s)=>{let n=new URL(e.url||"/","http://localhost").pathname;if(this.isIgnoredPath(n)){r.destroy();return}let i=this.getProxyUrl(e);this.proxyServer?.ws(e,r,s,{target:i,ws:!0,changeOrigin:this.options.changeOrigin,secure:this.options.secure})}),this.log("info","[AutoProxyCookie] WebSocket upgrade handler registered")),this.startFileWatch(),this.log("info","[AutoProxyCookie] Auto-proxy middleware enabled"),this.log("info","[AutoProxyCookie] Target:",this.options.target),this.log("info","[AutoProxyCookie] Cookie file:",this.options.cookieFile),this.options.autoRestart&&this.log("info","[AutoProxyCookie] Auto-restart enabled"),this.options.ws&&this.log("info","[AutoProxyCookie] WebSocket support enabled")}startFileWatch(){let o;this.options.isDev!==void 0?(o=this.options.isDev,this.options.debug&&console.log(`[AutoProxyCookie] isDev=${this.options.isDev}, ${o?"enabling":"disabling"} watch`)):(o=!0,this.options.debug&&console.log("[AutoProxyCookie] Default behavior: enabling watch (dev mode)")),o?this.watcher=P(this.options.cookieFile,this.handleCookieChange,e=>{this.log("error","[AutoProxyCookie] File watch error:",e.message)}):this.options.debug&&console.log("[AutoProxyCookie] File watch disabled")}stop(){this.watcher&&(this.watcher.stop(),this.watcher=null),this.proxyServer&&(this.proxyServer.close(),this.proxyServer=null),this.log("info","[AutoProxyCookie] Stopped")}getCurrentCookie(){return this.currentCookie}};function K(t){return new R(t)}function z(t,o){return o.some(e=>t.startsWith(e))}function X(t,o){return o.some(e=>t.startsWith(e))}function Y(t,o,e){for(let[r,s]of Object.entries(o))if(t.startsWith(r))return s;return e}function Q(t){let{cookieFile:o,target:e,debug:r=!1,useCookie:s=!0,proxyMap:n={},proxyPaths:i=[],ignorePaths:a=[]}=t,l=new d({cookieFile:o},r),g="";s&&(g=l.readCookie());let p=[...Object.keys(n),...i];return{name:"vite-middleware-proxy",apply:"serve",configureServer(h){let u=require("http-proxy").createProxyServer({});s&&r&&console.log("[ViteMiddlewareProxy] Watching cookie file:",o),h.middlewares.use((c,b,M)=>{let x=new URL(c.url||"/","http://localhost").pathname;if(z(x,a)){r&&console.log("[ViteMiddlewareProxy] Ignoring:",x),M();return}if(!X(x,p)){M();return}let D=Y(x,n,e);r&&console.log("[ViteMiddlewareProxy] Proxying:",c.method,x,"->",D),s?(g=l.readCookie(),g?(r&&console.log("[ViteMiddlewareProxy] Injecting cookie:",`(length: ${g.length})`),c.headers.cookie=g,c.headers.Cookie=g):r&&console.log("[ViteMiddlewareProxy] Cookie file is empty")):r&&console.log("[ViteMiddlewareProxy] useCookie is false, skipping cookie injection"),u.web(c,b,{target:D,changeOrigin:!0,secure:!1,ignorePath:!1})}),u.on("error",(c,b)=>{console.error("[ViteMiddlewareProxy] Proxy error:",c.message,"for",b.url)})}}}var S=f(require("path"));function O(t,o={}){let{getCookie:e,debug:r=!1,useCookie:s=!0,headers:n={},ws:i=!1,changeOrigin:a=!0,secure:l=!1,onError:g}=o;return{ws:i,target:t,changeOrigin:a,secure:l,headers:n,onProxyReq:(h,y)=>{let u=y.url||"/";if(s){let c=e?e():"";c&&v(h,c),r&&console.log("[Proxy Request]",u,y.method,c?"(with cookie)":"(no cookie)")}else r&&console.log("[Proxy Request]",u,y.method,"(useCookie is false, skipping cookie injection)")},onError:g||(h=>{console.error(`
|
|
3
|
-
[Proxy Error]`,
|
|
4
|
-
[Proxy Error]`,
|
|
1
|
+
"use strict";var _=Object.create;var A=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var B=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var J=(r,o)=>{for(var e in o)A(r,e,{get:o[e],enumerable:!0})},W=(r,o,e,t)=>{if(o&&typeof o=="object"||typeof o=="function")for(let s of q(o))!G.call(r,s)&&s!==e&&A(r,s,{get:()=>o[s],enumerable:!(t=j(o,s))||t.enumerable});return r};var x=(r,o,e)=>(e=r!=null?_(B(r)):{},W(o||!r||!r.__esModule?A(e,"default",{value:r,enumerable:!0}):e,r)),K=r=>W(A({},"__esModule",{value:!0}),r);var ro={};J(ro,{AutoProxyCookie:()=>E,CookieReader:()=>f,CookieWatcher:()=>b,applyDevAuthentications:()=>C,createAutoProxyConfig:()=>to,createAutoProxyCookie:()=>X,createCookieGetter:()=>z,createFileCookieGetter:()=>eo,createVueProxyConfig:()=>M,detectProductionEnvironment:()=>$,isProductionValue:()=>S,shouldEnableWatch:()=>O,viteMiddlewareProxy:()=>oo,watchCookieFile:()=>w});module.exports=K(ro);var N=x(require("http")),U=x(require("fs")),L=x(require("path")),T=x(require("http-proxy"));var k=x(require("fs")),m=x(require("path")),f=class{constructor(o,e=!1){this.options={encoding:"utf-8",...o},this.debug=e}readCookie(){try{let o=m.resolve(this.options.cookieFile);if(this.debug&&(console.log("[CookieReader] Resolved cookie file path:",o),console.log("[CookieReader] File exists:",k.existsSync(o))),k.existsSync(o)){let e=k.readFileSync(o,this.options.encoding||"utf-8");this.debug&&console.log("[CookieReader] File content length:",e.length);let n=e.split(`
|
|
2
|
+
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")).join("; ");return this.debug&&console.log("[CookieReader] Parsed cookie:",n?"(has cookie)":"(empty)"),n}return this.debug&&console.log("[CookieReader] Cookie file not found:",o),""}catch(o){return this.debug&&console.error("[CookieReader] Error reading cookie file:",o.message),""}}ensureCookieFile(){let o=m.resolve(this.options.cookieFile),e=m.dirname(o);k.existsSync(e)||k.mkdirSync(e,{recursive:!0}),k.existsSync(o)||k.writeFileSync(o,"")}};function z(r){let o=new f({cookieFile:r});return()=>o.readCookie()}var H=x(require("path")),V=x(require("chokidar"));var b=class{constructor(o){this.watcher=null;this.lastContent="";this.handleChange=()=>{let o=this.cookieReader.readCookie();o!==this.lastContent&&(this.lastContent=o,this.options.onCookieChange(o),console.log(`[CookieWatcher] Cookie updated from file: ${this.options.cookieFile}`))};this.options={autoCreateFile:!0,...o},this.cookieReader=new f({cookieFile:o.cookieFile})}start(){this.options.autoCreateFile&&this.cookieReader.ensureCookieFile();let o=H.resolve(this.options.cookieFile);this.lastContent=this.cookieReader.readCookie(),console.log(`[CookieWatcher] Started watching: ${o}`);try{this.watcher=V.default.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}}),this.watcher.on("change",this.handleChange),this.watcher.on("add",this.handleChange),this.watcher.on("error",e=>{this.options.onError?.(e)})}catch(e){this.options.onError?.(e)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,console.log(`[CookieWatcher] Stopped watching: ${this.options.cookieFile}`))}getCurrentCookie(){return this.lastContent}};function w(r,o,e){let t=new b({cookieFile:r,onCookieChange:o,onError:e});return t.start(),t}function S(r){return["production","prod","prd","release","staging","uat"].includes(r.toLowerCase().trim())}function $(r=[],o=!1,e="[env-detector]"){let t=process.env;if(r.length>0)for(let i of r){let a=t[i];if(a&&S(a))return o&&console.log(`${e} Detected production via custom env: ${i}=${a}`),!0}let s=["NODE_ENV","BUILD_MODE","VUE_APP_ENV","VITE_NODE_ENV","WEBPACK_MODE","CI_ENV","APP_ENV","ENV","DEPLOY_ENV","RUN_MODE"];for(let i of s){let a=t[i];if(a&&S(a))return o&&console.log(`${e} Detected production via env: ${i}=${a}`),!0}if(t.CI==="true"||t.CI==="1"||t.CI==="yes")return o&&console.log(`${e} Detected production via CI env`),!0;if(t.npm_lifecycle_event){let i=t.npm_lifecycle_event.toLowerCase();if(i.includes("build")||i.includes("prod")||i.includes("prd")||i.includes("release"))return o&&console.log(`${e} Detected production via lifecycle event: ${t.npm_lifecycle_event}`),!0}let n=process.argv.join("").toLowerCase();return n.includes("build")||n.includes("production")||n.includes("--mode=production")||n.includes("--prod")||n.includes("--release")?(o&&console.log(`${e} Detected production via process arguments`),!0):!1}function O(r,o=[],e=!1,t="[env-detector]"){return typeof r=="boolean"?(e&&!r&&console.log(`${t} Watch disabled by user setting`),r):$(o,e,t)?(e&&console.log(`${t} Auto-detected production mode - disabling watch`),!1):(e&&console.log(`${t} Auto-detected development mode - enabling watch`),!0)}function P(r,o){if(console.log("[applyDevCookieHeader] === START ==="),console.log("[applyDevCookieHeader] Cookie to apply:",o?`(length: ${o.length})`:"(empty)"),!o){console.log("[applyDevCookieHeader] Cookie is empty, returning"),console.log("[applyDevCookieHeader] === END ===");return}let e=r.getHeader?.("Cookie");if(console.log("[applyDevCookieHeader] Cookie current:",e?`(length: ${String(e).length})`:"(none)"),e===o){console.log("[applyDevCookieHeader] Cookie is already set, skipping"),console.log("[applyDevCookieHeader] === END ===");return}r.removeHeader("cookie"),r.removeHeader("Cookie"),r.setHeader("Cookie",o);let t=r.getHeader?.("Cookie");console.log("[applyDevCookieHeader] Cookie new:",t?`(length: ${String(t).length})`:"(failed)"),console.log("[applyDevCookieHeader] === END ===")}function C(r,o){if(console.log("[applyDevAuthentications] === START ==="),!o||o.length===0){console.log("[applyDevAuthentications] Authentications is empty, returning"),console.log("[applyDevAuthentications] === END ===");return}console.log("[applyDevAuthentications] Applying authentications:",JSON.stringify(o));for(let e of o)for(let[t,s]of Object.entries(e))r.setHeader(t,s),console.log("[applyDevAuthentications] Set header:",t,"->",s);console.log("[applyDevAuthentications] === END ===")}var E=class{constructor(o){this.currentCookie="";this.server=null;this.proxyServer=null;this.watcher=null;this.handleCookieChange=o=>{if(o!==this.currentCookie&&(this.currentCookie=o,this.log("info","[AutoProxyCookie] Cookie updated:",o?"(has cookie)":"(empty)"),this.options.autoRestart&&this.options.restartMarkerFile)){let e=L.resolve(this.options.restartMarkerFile);U.writeFileSync(e,JSON.stringify({timestamp:Date.now(),cookie:o},null,2)),this.log("info","[AutoProxyCookie] Restart marker written to:",e),this.log("info","[AutoProxyCookie] Please restart the dev server for changes to take effect")}};this.handleOnProxyReq=(o,e,t,s)=>{console.log("[AutoProxyCookie] === handleOnProxyReq START ==="),console.log("[AutoProxyCookie] Request URL:",e.method,e.url),console.log("[AutoProxyCookie] useCookie:",this.options.useCookie),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.options.useCookie&&this.currentCookie?(console.log("[AutoProxyCookie] Applying cookie header..."),P(o,this.currentCookie),console.log("[AutoProxyCookie] Cookie header applied successfully")):this.options.useCookie?console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!"):console.log("[AutoProxyCookie] useCookie is false, skipping cookie injection");let n=this.options.authentications||[];if(n.length>0&&(console.log("[AutoProxyCookie] Applying authentications headers..."),C(o,n),console.log("[AutoProxyCookie] Authentications headers applied successfully")),this.log("debug","[AutoProxyCookie] Proxy Request:",e.method,e.url),this.options.hooks.onProxyReq)try{this.options.hooks.onProxyReq(o,e,t)}catch(i){this.log("error","[AutoProxyCookie] onProxyReq hook error:",i.message)}console.log("[AutoProxyCookie] === handleOnProxyReq END ===")};this.handleOnProxyRes=(o,e,t)=>{let s=["Content-Type","Content-Length","Authorization","Set-Cookie","X-Requested-With","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"];if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers",s.join(",")),t.setHeader("Access-Control-Allow-Credentials","true"),this.log("debug","[AutoProxyCookie] Proxy Response:",e.url,o.statusCode),this.options.hooks.onProxyRes)try{this.options.hooks.onProxyRes(o,e,t)}catch(n){this.log("error","[AutoProxyCookie] onProxyRes hook error:",n.message)}};this.handleOnError=(o,e,t)=>{if(this.log("error","[AutoProxyCookie] Proxy Error:",o.message),this.log("error","[AutoProxyCookie] URL:",e.url),t instanceof N.ServerResponse&&!t.headersSent&&(t.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),t.end(JSON.stringify({success:!1,message:"\u670D\u52A1\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",error:o.message}))),this.options.hooks.onError)try{this.options.hooks.onError(o,e,t)}catch(s){this.log("error","[AutoProxyCookie] onError hook error:",s.message)}};this.handleOnWsError=(o,e,t)=>{if(this.log("error","[AutoProxyCookie] WebSocket Proxy Error:",o.message),this.log("error","[AutoProxyCookie] WebSocket URL:",e.url),t&&t.close(),this.options.hooks.onWsError)try{this.options.hooks.onWsError(o,e,t)}catch(s){this.log("error","[AutoProxyCookie] onWsError hook error:",s.message)}};let t={...o,hooks:{...{onProxyReq:()=>{},onProxyRes:()=>{},onError:()=>{},onWsError:()=>{}},...o.hooks||{}}};this.options={debug:!1,autoRestart:!1,restartMarkerFile:".cookie-restart-marker",proxyMap:{},proxyPaths:[],ignorePaths:[],ws:!0,changeOrigin:!0,secure:!1,followRedirects:!0,autoRewrite:!1,protocolRewrite:void 0,logLevel:"info",cookieDomainRewrite:"*",cookiePathRewrite:!1,headers:{},useCookie:!0,authentications:[],...t},this.cookieReader=new f({cookieFile:o.cookieFile},o.debug??!1)}getProxyUrl(o){let e=o.url||"/",t=new URL(e,"http://localhost").pathname,s=this.options.proxyMap||{},n=this.options.proxyPaths||[];this.log("debug","[AutoProxyCookie] getProxyUrl - Request path:",t),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyMap paths:",Object.keys(s)),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyPaths:",n);for(let[i,a]of Object.entries(s)){let l=t.startsWith(i);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyMap:",i,"- matches:",l),l)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyMap:",i,"->",a),a}for(let i of n){let a=t.startsWith(i);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyPaths:",i,"- matches:",a),a)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyPaths:",i,"->",this.options.target),this.options.target}return this.log("debug","[AutoProxyCookie] getProxyUrl - No match found, using default target:",this.options.target),this.options.target}isIgnoredPath(o){return(this.options.ignorePaths||[]).some(t=>o.startsWith(t))}log(o,...e){let t={debug:0,info:1,warn:2,error:3},s=this.options.debug?"debug":this.options.logLevel||"info",n=t[s];t[o]>=n&&(o==="error"?console.error(...e):o==="warn"?console.warn(...e):console.log(...e))}createProxyOptions(o){let{ws:e,changeOrigin:t,secure:s,followRedirects:n,autoRewrite:i,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:p,headers:h}=this.options;return{target:o,ws:e,changeOrigin:t,secure:s,followRedirects:n,autoRewrite:i,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:p,headers:{...h},ignorePath:!1}}async setup(o){this.server=o,this.currentCookie=this.cookieReader.readCookie();try{let e={target:this.options.target,changeOrigin:this.options.changeOrigin,secure:this.options.secure,followRedirects:this.options.followRedirects,autoRewrite:this.options.autoRewrite,protocolRewrite:this.options.protocolRewrite,cookieDomainRewrite:this.options.cookieDomainRewrite,cookiePathRewrite:this.options.cookiePathRewrite,ws:this.options.ws};this.proxyServer=T.default.createProxyServer(e),this.proxyServer.on("proxyReq",this.handleOnProxyReq),this.proxyServer.on("proxyRes",this.handleOnProxyRes),this.proxyServer.on("error",this.handleOnError),this.options.ws&&this.proxyServer.on("wsError",this.handleOnWsError),this.log("info","[AutoProxyCookie] Proxy server created with WebSocket support")}catch(e){this.log("warn","[AutoProxyCookie] http-proxy create failed, using basic mode:",e.message)}o.middlewares.use((e,t,s)=>{let n=e.url||"/",i=new URL(n,"http://localhost").pathname;if(console.log("[AutoProxyCookie] === Incoming Request ==="),console.log("[AutoProxyCookie] Method:",e.method),console.log("[AutoProxyCookie] Full URL:",n),console.log("[AutoProxyCookie] Pathname:",i),console.log("[AutoProxyCookie] useCookie:",this.options.useCookie),console.log("[AutoProxyCookie] Headers:",JSON.stringify(e.headers,null,2)),this.isIgnoredPath(i)){console.log("[AutoProxyCookie] Path ignored, passing to next middleware"),s();return}this.options.useCookie?(this.currentCookie=this.cookieReader.readCookie(),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.currentCookie&&console.log("[AutoProxyCookie] Cookie preview:",this.currentCookie)):console.log("[AutoProxyCookie] useCookie is false, skipping cookie reading");let a=Object.keys(this.options.proxyMap||{}),l=this.options.proxyPaths||[],h=[...a,...l].some(u=>i.startsWith(u));if(console.log("[AutoProxyCookie] Path matches proxy rules:",h),this.proxyServer){let u=this.getProxyUrl(e);console.log(`[AutoProxyCookie] Proxying ${e.method} ${i} -> ${u}`);let g=this.createProxyOptions(u);try{console.log("[AutoProxyCookie] Calling proxyServer.web..."),this.proxyServer.web(e,t,g),console.log("[AutoProxyCookie] proxyServer.web called successfully")}catch(d){console.error("[AutoProxyCookie] Proxy web error:",d.message),s(d)}}else console.log("[AutoProxyCookie] No proxy server, passing to next middleware"),s()}),this.options.ws&&this.server.httpServer&&this.proxyServer&&(this.server.httpServer.on("upgrade",(e,t,s)=>{let n=new URL(e.url||"/","http://localhost").pathname;if(this.isIgnoredPath(n)){t.destroy();return}let i=this.getProxyUrl(e);this.proxyServer?.ws(e,t,s,{target:i,ws:!0,changeOrigin:this.options.changeOrigin,secure:this.options.secure})}),this.log("info","[AutoProxyCookie] WebSocket upgrade handler registered")),this.startFileWatch(),this.log("info","[AutoProxyCookie] Auto-proxy middleware enabled"),this.log("info","[AutoProxyCookie] Target:",this.options.target),this.log("info","[AutoProxyCookie] Cookie file:",this.options.cookieFile),this.options.autoRestart&&this.log("info","[AutoProxyCookie] Auto-restart enabled"),this.options.ws&&this.log("info","[AutoProxyCookie] WebSocket support enabled")}startFileWatch(){let o;this.options.isDev!==void 0?(o=this.options.isDev,this.options.debug&&console.log(`[AutoProxyCookie] isDev=${this.options.isDev}, ${o?"enabling":"disabling"} watch`)):(o=!0,this.options.debug&&console.log("[AutoProxyCookie] Default behavior: enabling watch (dev mode)")),o?this.watcher=w(this.options.cookieFile,this.handleCookieChange,e=>{this.log("error","[AutoProxyCookie] File watch error:",e.message)}):this.options.debug&&console.log("[AutoProxyCookie] File watch disabled")}stop(){this.watcher&&(this.watcher.stop(),this.watcher=null),this.proxyServer&&(this.proxyServer.close(),this.proxyServer=null),this.log("info","[AutoProxyCookie] Stopped")}getCurrentCookie(){return this.currentCookie}};function X(r){return new E(r)}function Y(r,o){return o.some(e=>r.startsWith(e))}function Q(r,o){return o.some(e=>r.startsWith(e))}function Z(r,o,e){for(let[t,s]of Object.entries(o))if(r.startsWith(t))return s;return e}function oo(r){let{cookieFile:o,target:e,debug:t=!1,useCookie:s=!0,authentications:n=[],proxyMap:i={},proxyPaths:a=[],ignorePaths:l=[]}=r,p=new f({cookieFile:o},t),h="";s&&(h=p.readCookie());let u=[...Object.keys(i),...a];return{name:"vite-middleware-proxy",apply:"serve",configureServer(g){let y=require("http-proxy").createProxyServer({});s&&t&&console.log("[ViteMiddlewareProxy] Watching cookie file:",o),g.middlewares.use((c,R,I)=>{let v=new URL(c.url||"/","http://localhost").pathname;if(Y(v,l)){t&&console.log("[ViteMiddlewareProxy] Ignoring:",v),I();return}if(!Q(v,u)){I();return}let F=Z(v,i,e);t&&console.log("[ViteMiddlewareProxy] Proxying:",c.method,v,"->",F),y.web(c,R,{target:F,changeOrigin:!0,secure:!1,ignorePath:!1})}),y.on("proxyReq",(c,R)=>{s?(h=p.readCookie(),h?(t&&console.log("[ViteMiddlewareProxy] Injecting cookie:",`(length: ${h.length})`),P(c,h)):t&&console.log("[ViteMiddlewareProxy] Cookie file is empty")):t&&console.log("[ViteMiddlewareProxy] useCookie is false, skipping cookie injection"),n&&n.length>0&&(C(c,n),t&&console.log("[ViteMiddlewareProxy] Injecting authentications:",JSON.stringify(n)))}),y.on("error",(c,R)=>{console.error("[ViteMiddlewareProxy] Proxy error:",c.message,"for",R.url)})}}}var D=x(require("path"));function M(r,o={}){let{getCookie:e,debug:t=!1,useCookie:s=!0,authentications:n=[],headers:i={},ws:a=!1,changeOrigin:l=!0,secure:p=!1,onError:h}=o;return{ws:a,target:r,changeOrigin:l,secure:p,headers:i,onProxyReq:(g,d)=>{let y=d.url||"/";if(s){let c=e?e():"";c&&P(g,c),t&&console.log("[Proxy Request]",y,d.method,c?"(with cookie)":"(no cookie)")}else t&&console.log("[Proxy Request]",y,d.method,"(useCookie is false, skipping cookie injection)");n&&n.length>0&&(C(g,n),t&&console.log("[Proxy Request]",y,d.method,"(with authentications)"))},onError:h||(g=>{console.error(`
|
|
3
|
+
[Proxy Error]`,g.message)})}}function eo(r,o={}){let{watch:e="auto",debug:t=!0,productionEnvs:s=[],isDev:n}=o,i=new f({cookieFile:D.resolve(r)},t),a;return n!==void 0?(a=n,t&&console.log(`[CookieFile] isDev=${n}, ${a?"enabling":"disabling"} watch`)):a=O(e,s,t,"[CookieFile]"),a?w(D.resolve(r),l=>{t&&console.log("[CookieFile] Updated:",l?"(has cookie)":"(empty)")},l=>{console.error("[CookieFile] Watch error:",l.message)}):t&&console.log("[CookieFile] File watch disabled"),()=>i.readCookie()}function to(r){let{target:o,ignorePaths:e=[],includePaths:t=[],additionalProxies:s={},getCookie:n,debug:i,headers:a,useCookie:l=!0,authentications:p=[]}=r,h={};if(t.length>0)for(let u of t)h[u]=M(o,{getCookie:n,debug:i,headers:a,useCookie:l,authentications:p});else{let u={ws:!1,target:o,changeOrigin:!0,secure:!1,headers:a,onProxyReq:(g,d)=>{let y=d.url||"/";if(!e.some(c=>y.startsWith(c))){if(l){let c=n?n():"";c&&P(g,c),i&&console.log("[Proxy Request]",y,d.method,c?"(with cookie)":"(no cookie)")}else i&&console.log("[Proxy Request]",y,d.method,"(useCookie is false, skipping cookie injection)");p&&p.length>0&&(C(g,p),i&&console.log("[Proxy Request]",y,d.method,"(with authentications)"))}},onError:g=>{console.error(`
|
|
4
|
+
[Proxy Error]`,g.message)}};h["/"]=u}for(let[u,g]of Object.entries(s))h[u]=M(g,{getCookie:n,debug:i,headers:a,useCookie:l,authentications:p});return h}0&&(module.exports={AutoProxyCookie,CookieReader,CookieWatcher,applyDevAuthentications,createAutoProxyConfig,createAutoProxyCookie,createCookieGetter,createFileCookieGetter,createVueProxyConfig,detectProductionEnvironment,isProductionValue,shouldEnableWatch,viteMiddlewareProxy,watchCookieFile});
|
package/dist/index.min.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).map(t=>t.trim()).filter(t=>t&&!t.startsWith("#")).join("; ");return this.debug&&console.log("[CookieReader] Parsed cookie:",s?"(has cookie)":"(empty)"),s}return this.debug&&console.log("[CookieReader] Cookie file not found:",o),""}catch(o){return this.debug&&console.error("[CookieReader] Error reading cookie file:",o.message),""}}ensureCookieFile(){let o=x.resolve(this.options.cookieFile),e=x.dirname(o);d.existsSync(e)||d.mkdirSync(e,{recursive:!0}),d.existsSync(o)||d.writeFileSync(o,"")}};function T(i){let o=new k({cookieFile:i});return()=>o.readCookie()}import*as E from"path";import H from"chokidar";var m=class{constructor(o){this.watcher=null;this.lastContent="";this.handleChange=()=>{let o=this.cookieReader.readCookie();o!==this.lastContent&&(this.lastContent=o,this.options.onCookieChange(o),console.log(`[CookieWatcher] Cookie updated from file: ${this.options.cookieFile}`))};this.options={autoCreateFile:!0,...o},this.cookieReader=new k({cookieFile:o.cookieFile})}start(){this.options.autoCreateFile&&this.cookieReader.ensureCookieFile();let o=E.resolve(this.options.cookieFile);this.lastContent=this.cookieReader.readCookie(),console.log(`[CookieWatcher] Started watching: ${o}`);try{this.watcher=H.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}}),this.watcher.on("change",this.handleChange),this.watcher.on("add",this.handleChange),this.watcher.on("error",e=>{this.options.onError?.(e)})}catch(e){this.options.onError?.(e)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,console.log(`[CookieWatcher] Stopped watching: ${this.options.cookieFile}`))}getCurrentCookie(){return this.lastContent}};function P(i,o,e){let r=new m({cookieFile:i,onCookieChange:o,onError:e});return r.start(),r}function S(i){return["production","prod","prd","release","staging","uat"].includes(i.toLowerCase().trim())}function V(i=[],o=!1,e="[env-detector]"){let r=process.env;if(i.length>0)for(let t of i){let a=r[t];if(a&&S(a))return o&&console.log(`${e} Detected production via custom env: ${t}=${a}`),!0}let n=["NODE_ENV","BUILD_MODE","VUE_APP_ENV","VITE_NODE_ENV","WEBPACK_MODE","CI_ENV","APP_ENV","ENV","DEPLOY_ENV","RUN_MODE"];for(let t of n){let a=r[t];if(a&&S(a))return o&&console.log(`${e} Detected production via env: ${t}=${a}`),!0}if(r.CI==="true"||r.CI==="1"||r.CI==="yes")return o&&console.log(`${e} Detected production via CI env`),!0;if(r.npm_lifecycle_event){let t=r.npm_lifecycle_event.toLowerCase();if(t.includes("build")||t.includes("prod")||t.includes("prd")||t.includes("release"))return o&&console.log(`${e} Detected production via lifecycle event: ${r.npm_lifecycle_event}`),!0}let s=process.argv.join("").toLowerCase();return s.includes("build")||s.includes("production")||s.includes("--mode=production")||s.includes("--prod")||s.includes("--release")?(o&&console.log(`${e} Detected production via process arguments`),!0):!1}function O(i,o=[],e=!1,r="[env-detector]"){return typeof i=="boolean"?(e&&!i&&console.log(`${r} Watch disabled by user setting`),i):V(o,e,r)?(e&&console.log(`${r} Auto-detected production mode - disabling watch`),!1):(e&&console.log(`${r} Auto-detected development mode - enabling watch`),!0)}function C(i,o){if(console.log("[applyDevCookieHeader] === START ==="),console.log("[applyDevCookieHeader] Cookie to apply:",o?`(length: ${o.length})`:"(empty)"),!o){console.log("[applyDevCookieHeader] Cookie is empty, returning"),console.log("[applyDevCookieHeader] === END ===");return}let e=i.getHeader?.("Cookie");if(console.log("[applyDevCookieHeader] Cookie current:",e?`(length: ${String(e).length})`:"(none)"),e===o){console.log("[applyDevCookieHeader] Cookie is already set, skipping"),console.log("[applyDevCookieHeader] === END ===");return}i.removeHeader("cookie"),i.removeHeader("Cookie"),i.setHeader("Cookie",o);let r=i.getHeader?.("Cookie");console.log("[applyDevCookieHeader] Cookie new:",r?`(length: ${String(r).length})`:"(failed)"),console.log("[applyDevCookieHeader] === END ===")}var w=class{constructor(o){this.currentCookie="";this.server=null;this.proxyServer=null;this.watcher=null;this.handleCookieChange=o=>{if(o!==this.currentCookie&&(this.currentCookie=o,this.log("info","[AutoProxyCookie] Cookie updated:",o?"(has cookie)":"(empty)"),this.options.autoRestart&&this.options.restartMarkerFile)){let e=F.resolve(this.options.restartMarkerFile);D.writeFileSync(e,JSON.stringify({timestamp:Date.now(),cookie:o},null,2)),this.log("info","[AutoProxyCookie] Restart marker written to:",e),this.log("info","[AutoProxyCookie] Please restart the dev server for changes to take effect")}};this.handleOnProxyReq=(o,e,r,n)=>{if(console.log("[AutoProxyCookie] === handleOnProxyReq START ==="),console.log("[AutoProxyCookie] Request URL:",e.method,e.url),console.log("[AutoProxyCookie] useCookie:",this.options.useCookie),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.options.useCookie&&this.currentCookie?(console.log("[AutoProxyCookie] Applying cookie header..."),C(o,this.currentCookie),console.log("[AutoProxyCookie] Cookie header applied successfully")):this.options.useCookie?console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!"):console.log("[AutoProxyCookie] useCookie is false, skipping cookie injection"),this.log("debug","[AutoProxyCookie] Proxy Request:",e.method,e.url),this.options.hooks.onProxyReq)try{this.options.hooks.onProxyReq(o,e,r)}catch(s){this.log("error","[AutoProxyCookie] onProxyReq hook error:",s.message)}console.log("[AutoProxyCookie] === handleOnProxyReq END ===")};this.handleOnProxyRes=(o,e,r)=>{let n=["Content-Type","Content-Length","Authorization","Set-Cookie","X-Requested-With","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"];if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),r.setHeader("Access-Control-Allow-Headers",n.join(",")),r.setHeader("Access-Control-Allow-Credentials","true"),this.log("debug","[AutoProxyCookie] Proxy Response:",e.url,o.statusCode),this.options.hooks.onProxyRes)try{this.options.hooks.onProxyRes(o,e,r)}catch(s){this.log("error","[AutoProxyCookie] onProxyRes hook error:",s.message)}};this.handleOnError=(o,e,r)=>{if(this.log("error","[AutoProxyCookie] Proxy Error:",o.message),this.log("error","[AutoProxyCookie] URL:",e.url),r instanceof M.ServerResponse&&!r.headersSent&&(r.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),r.end(JSON.stringify({success:!1,message:"\u670D\u52A1\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",error:o.message}))),this.options.hooks.onError)try{this.options.hooks.onError(o,e,r)}catch(n){this.log("error","[AutoProxyCookie] onError hook error:",n.message)}};this.handleOnWsError=(o,e,r)=>{if(this.log("error","[AutoProxyCookie] WebSocket Proxy Error:",o.message),this.log("error","[AutoProxyCookie] WebSocket URL:",e.url),r&&r.close(),this.options.hooks.onWsError)try{this.options.hooks.onWsError(o,e,r)}catch(n){this.log("error","[AutoProxyCookie] onWsError hook error:",n.message)}};let r={...o,hooks:{...{onProxyReq:()=>{},onProxyRes:()=>{},onError:()=>{},onWsError:()=>{}},...o.hooks||{}}};this.options={debug:!1,autoRestart:!1,restartMarkerFile:".cookie-restart-marker",proxyMap:{},proxyPaths:[],ignorePaths:[],ws:!0,changeOrigin:!0,secure:!1,followRedirects:!0,autoRewrite:!1,protocolRewrite:void 0,logLevel:"info",cookieDomainRewrite:"*",cookiePathRewrite:!1,headers:{},useCookie:!0,...r},this.cookieReader=new k({cookieFile:o.cookieFile},o.debug??!1)}getProxyUrl(o){let e=o.url||"/",r=new URL(e,"http://localhost").pathname,n=this.options.proxyMap||{},s=this.options.proxyPaths||[];this.log("debug","[AutoProxyCookie] getProxyUrl - Request path:",r),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyMap paths:",Object.keys(n)),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyPaths:",s);for(let[t,a]of Object.entries(n)){let l=r.startsWith(t);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyMap:",t,"- matches:",l),l)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyMap:",t,"->",a),a}for(let t of s){let a=r.startsWith(t);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyPaths:",t,"- matches:",a),a)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyPaths:",t,"->",this.options.target),this.options.target}return this.log("debug","[AutoProxyCookie] getProxyUrl - No match found, using default target:",this.options.target),this.options.target}isIgnoredPath(o){return(this.options.ignorePaths||[]).some(r=>o.startsWith(r))}log(o,...e){let r={debug:0,info:1,warn:2,error:3},n=this.options.debug?"debug":this.options.logLevel||"info",s=r[n];r[o]>=s&&(o==="error"?console.error(...e):o==="warn"?console.warn(...e):console.log(...e))}createProxyOptions(o){let{ws:e,changeOrigin:r,secure:n,followRedirects:s,autoRewrite:t,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:g,headers:p}=this.options;return{target:o,ws:e,changeOrigin:r,secure:n,followRedirects:s,autoRewrite:t,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:g,headers:{...p},ignorePath:!1}}async setup(o){this.server=o,this.currentCookie=this.cookieReader.readCookie();try{let e={target:this.options.target,changeOrigin:this.options.changeOrigin,secure:this.options.secure,followRedirects:this.options.followRedirects,autoRewrite:this.options.autoRewrite,protocolRewrite:this.options.protocolRewrite,cookieDomainRewrite:this.options.cookieDomainRewrite,cookiePathRewrite:this.options.cookiePathRewrite,ws:this.options.ws};this.proxyServer=$.createProxyServer(e),this.proxyServer.on("proxyReq",this.handleOnProxyReq),this.proxyServer.on("proxyRes",this.handleOnProxyRes),this.proxyServer.on("error",this.handleOnError),this.options.ws&&this.proxyServer.on("wsError",this.handleOnWsError),this.log("info","[AutoProxyCookie] Proxy server created with WebSocket support")}catch(e){this.log("warn","[AutoProxyCookie] http-proxy create failed, using basic mode:",e.message)}o.middlewares.use((e,r,n)=>{let s=e.url||"/",t=new URL(s,"http://localhost").pathname;if(console.log("[AutoProxyCookie] === Incoming Request ==="),console.log("[AutoProxyCookie] Method:",e.method),console.log("[AutoProxyCookie] Full URL:",s),console.log("[AutoProxyCookie] Pathname:",t),console.log("[AutoProxyCookie] useCookie:",this.options.useCookie),console.log("[AutoProxyCookie] Headers:",JSON.stringify(e.headers,null,2)),this.isIgnoredPath(t)){console.log("[AutoProxyCookie] Path ignored, passing to next middleware"),n();return}this.options.useCookie?(this.currentCookie=this.cookieReader.readCookie(),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.currentCookie&&console.log("[AutoProxyCookie] Cookie preview:",this.currentCookie)):console.log("[AutoProxyCookie] useCookie is false, skipping cookie reading");let a=Object.keys(this.options.proxyMap||{}),l=this.options.proxyPaths||[],p=[...a,...l].some(h=>t.startsWith(h));if(console.log("[AutoProxyCookie] Path matches proxy rules:",p),this.proxyServer){let h=this.getProxyUrl(e);console.log(`[AutoProxyCookie] Proxying ${e.method} ${t} -> ${h}`);let y=this.createProxyOptions(h);try{console.log("[AutoProxyCookie] Calling proxyServer.web..."),this.proxyServer.web(e,r,y),console.log("[AutoProxyCookie] proxyServer.web called successfully")}catch(u){console.error("[AutoProxyCookie] Proxy web error:",u.message),n(u)}}else console.log("[AutoProxyCookie] No proxy server, passing to next middleware"),n()}),this.options.ws&&this.server.httpServer&&this.proxyServer&&(this.server.httpServer.on("upgrade",(e,r,n)=>{let s=new URL(e.url||"/","http://localhost").pathname;if(this.isIgnoredPath(s)){r.destroy();return}let t=this.getProxyUrl(e);this.proxyServer?.ws(e,r,n,{target:t,ws:!0,changeOrigin:this.options.changeOrigin,secure:this.options.secure})}),this.log("info","[AutoProxyCookie] WebSocket upgrade handler registered")),this.startFileWatch(),this.log("info","[AutoProxyCookie] Auto-proxy middleware enabled"),this.log("info","[AutoProxyCookie] Target:",this.options.target),this.log("info","[AutoProxyCookie] Cookie file:",this.options.cookieFile),this.options.autoRestart&&this.log("info","[AutoProxyCookie] Auto-restart enabled"),this.options.ws&&this.log("info","[AutoProxyCookie] WebSocket support enabled")}startFileWatch(){let o;this.options.isDev!==void 0?(o=this.options.isDev,this.options.debug&&console.log(`[AutoProxyCookie] isDev=${this.options.isDev}, ${o?"enabling":"disabling"} watch`)):(o=!0,this.options.debug&&console.log("[AutoProxyCookie] Default behavior: enabling watch (dev mode)")),o?this.watcher=P(this.options.cookieFile,this.handleCookieChange,e=>{this.log("error","[AutoProxyCookie] File watch error:",e.message)}):this.options.debug&&console.log("[AutoProxyCookie] File watch disabled")}stop(){this.watcher&&(this.watcher.stop(),this.watcher=null),this.proxyServer&&(this.proxyServer.close(),this.proxyServer=null),this.log("info","[AutoProxyCookie] Stopped")}getCurrentCookie(){return this.currentCookie}};function io(i){return new w(i)}function U(i,o){return o.some(e=>i.startsWith(e))}function L(i,o){return o.some(e=>i.startsWith(e))}function N(i,o,e){for(let[r,n]of Object.entries(o))if(i.startsWith(r))return n;return e}function ao(i){let{cookieFile:o,target:e,debug:r=!1,useCookie:n=!0,proxyMap:s={},proxyPaths:t=[],ignorePaths:a=[]}=i,l=new k({cookieFile:o},r),g="";n&&(g=l.readCookie());let p=[...Object.keys(s),...t];return{name:"vite-middleware-proxy",apply:"serve",configureServer(h){let u=W("http-proxy").createProxyServer({});n&&r&&console.log("[ViteMiddlewareProxy] Watching cookie file:",o),h.middlewares.use((c,v,b)=>{let f=new URL(c.url||"/","http://localhost").pathname;if(U(f,a)){r&&console.log("[ViteMiddlewareProxy] Ignoring:",f),b();return}if(!L(f,p)){b();return}let A=N(f,s,e);r&&console.log("[ViteMiddlewareProxy] Proxying:",c.method,f,"->",A),n?(g=l.readCookie(),g?(r&&console.log("[ViteMiddlewareProxy] Injecting cookie:",`(length: ${g.length})`),c.headers.cookie=g,c.headers.Cookie=g):r&&console.log("[ViteMiddlewareProxy] Cookie file is empty")):r&&console.log("[ViteMiddlewareProxy] useCookie is false, skipping cookie injection"),u.web(c,v,{target:A,changeOrigin:!0,secure:!1,ignorePath:!1})}),u.on("error",(c,v)=>{console.error("[ViteMiddlewareProxy] Proxy error:",c.message,"for",v.url)})}}}import*as R from"path";function I(i,o={}){let{getCookie:e,debug:r=!1,useCookie:n=!0,headers:s={},ws:t=!1,changeOrigin:a=!0,secure:l=!1,onError:g}=o;return{ws:t,target:i,changeOrigin:a,secure:l,headers:s,onProxyReq:(h,y)=>{let u=y.url||"/";if(n){let c=e?e():"";c&&C(h,c),r&&console.log("[Proxy Request]",u,y.method,c?"(with cookie)":"(no cookie)")}else r&&console.log("[Proxy Request]",u,y.method,"(useCookie is false, skipping cookie injection)")},onError:g||(h=>{console.error(`
|
|
3
|
-
[Proxy Error]`,
|
|
4
|
-
[Proxy Error]`,
|
|
1
|
+
var V=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(o,e)=>(typeof require<"u"?require:o)[e]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});import*as I from"http";import*as F from"fs";import*as W from"path";import U from"http-proxy";import*as f from"fs";import*as v from"path";var k=class{constructor(o,e=!1){this.options={encoding:"utf-8",...o},this.debug=e}readCookie(){try{let o=v.resolve(this.options.cookieFile);if(this.debug&&(console.log("[CookieReader] Resolved cookie file path:",o),console.log("[CookieReader] File exists:",f.existsSync(o))),f.existsSync(o)){let e=f.readFileSync(o,this.options.encoding||"utf-8");this.debug&&console.log("[CookieReader] File content length:",e.length);let s=e.split(`
|
|
2
|
+
`).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")).join("; ");return this.debug&&console.log("[CookieReader] Parsed cookie:",s?"(has cookie)":"(empty)"),s}return this.debug&&console.log("[CookieReader] Cookie file not found:",o),""}catch(o){return this.debug&&console.error("[CookieReader] Error reading cookie file:",o.message),""}}ensureCookieFile(){let o=v.resolve(this.options.cookieFile),e=v.dirname(o);f.existsSync(e)||f.mkdirSync(e,{recursive:!0}),f.existsSync(o)||f.writeFileSync(o,"")}};function q(i){let o=new k({cookieFile:i});return()=>o.readCookie()}import*as O from"path";import $ from"chokidar";var R=class{constructor(o){this.watcher=null;this.lastContent="";this.handleChange=()=>{let o=this.cookieReader.readCookie();o!==this.lastContent&&(this.lastContent=o,this.options.onCookieChange(o),console.log(`[CookieWatcher] Cookie updated from file: ${this.options.cookieFile}`))};this.options={autoCreateFile:!0,...o},this.cookieReader=new k({cookieFile:o.cookieFile})}start(){this.options.autoCreateFile&&this.cookieReader.ensureCookieFile();let o=O.resolve(this.options.cookieFile);this.lastContent=this.cookieReader.readCookie(),console.log(`[CookieWatcher] Started watching: ${o}`);try{this.watcher=$.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}}),this.watcher.on("change",this.handleChange),this.watcher.on("add",this.handleChange),this.watcher.on("error",e=>{this.options.onError?.(e)})}catch(e){this.options.onError?.(e)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,console.log(`[CookieWatcher] Stopped watching: ${this.options.cookieFile}`))}getCurrentCookie(){return this.lastContent}};function w(i,o,e){let t=new R({cookieFile:i,onCookieChange:o,onError:e});return t.start(),t}function D(i){return["production","prod","prd","release","staging","uat"].includes(i.toLowerCase().trim())}function N(i=[],o=!1,e="[env-detector]"){let t=process.env;if(i.length>0)for(let r of i){let a=t[r];if(a&&D(a))return o&&console.log(`${e} Detected production via custom env: ${r}=${a}`),!0}let n=["NODE_ENV","BUILD_MODE","VUE_APP_ENV","VITE_NODE_ENV","WEBPACK_MODE","CI_ENV","APP_ENV","ENV","DEPLOY_ENV","RUN_MODE"];for(let r of n){let a=t[r];if(a&&D(a))return o&&console.log(`${e} Detected production via env: ${r}=${a}`),!0}if(t.CI==="true"||t.CI==="1"||t.CI==="yes")return o&&console.log(`${e} Detected production via CI env`),!0;if(t.npm_lifecycle_event){let r=t.npm_lifecycle_event.toLowerCase();if(r.includes("build")||r.includes("prod")||r.includes("prd")||r.includes("release"))return o&&console.log(`${e} Detected production via lifecycle event: ${t.npm_lifecycle_event}`),!0}let s=process.argv.join("").toLowerCase();return s.includes("build")||s.includes("production")||s.includes("--mode=production")||s.includes("--prod")||s.includes("--release")?(o&&console.log(`${e} Detected production via process arguments`),!0):!1}function M(i,o=[],e=!1,t="[env-detector]"){return typeof i=="boolean"?(e&&!i&&console.log(`${t} Watch disabled by user setting`),i):N(o,e,t)?(e&&console.log(`${t} Auto-detected production mode - disabling watch`),!1):(e&&console.log(`${t} Auto-detected development mode - enabling watch`),!0)}function x(i,o){if(console.log("[applyDevCookieHeader] === START ==="),console.log("[applyDevCookieHeader] Cookie to apply:",o?`(length: ${o.length})`:"(empty)"),!o){console.log("[applyDevCookieHeader] Cookie is empty, returning"),console.log("[applyDevCookieHeader] === END ===");return}let e=i.getHeader?.("Cookie");if(console.log("[applyDevCookieHeader] Cookie current:",e?`(length: ${String(e).length})`:"(none)"),e===o){console.log("[applyDevCookieHeader] Cookie is already set, skipping"),console.log("[applyDevCookieHeader] === END ===");return}i.removeHeader("cookie"),i.removeHeader("Cookie"),i.setHeader("Cookie",o);let t=i.getHeader?.("Cookie");console.log("[applyDevCookieHeader] Cookie new:",t?`(length: ${String(t).length})`:"(failed)"),console.log("[applyDevCookieHeader] === END ===")}function C(i,o){if(console.log("[applyDevAuthentications] === START ==="),!o||o.length===0){console.log("[applyDevAuthentications] Authentications is empty, returning"),console.log("[applyDevAuthentications] === END ===");return}console.log("[applyDevAuthentications] Applying authentications:",JSON.stringify(o));for(let e of o)for(let[t,n]of Object.entries(e))i.setHeader(t,n),console.log("[applyDevAuthentications] Set header:",t,"->",n);console.log("[applyDevAuthentications] === END ===")}var A=class{constructor(o){this.currentCookie="";this.server=null;this.proxyServer=null;this.watcher=null;this.handleCookieChange=o=>{if(o!==this.currentCookie&&(this.currentCookie=o,this.log("info","[AutoProxyCookie] Cookie updated:",o?"(has cookie)":"(empty)"),this.options.autoRestart&&this.options.restartMarkerFile)){let e=W.resolve(this.options.restartMarkerFile);F.writeFileSync(e,JSON.stringify({timestamp:Date.now(),cookie:o},null,2)),this.log("info","[AutoProxyCookie] Restart marker written to:",e),this.log("info","[AutoProxyCookie] Please restart the dev server for changes to take effect")}};this.handleOnProxyReq=(o,e,t,n)=>{console.log("[AutoProxyCookie] === handleOnProxyReq START ==="),console.log("[AutoProxyCookie] Request URL:",e.method,e.url),console.log("[AutoProxyCookie] useCookie:",this.options.useCookie),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.options.useCookie&&this.currentCookie?(console.log("[AutoProxyCookie] Applying cookie header..."),x(o,this.currentCookie),console.log("[AutoProxyCookie] Cookie header applied successfully")):this.options.useCookie?console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!"):console.log("[AutoProxyCookie] useCookie is false, skipping cookie injection");let s=this.options.authentications||[];if(s.length>0&&(console.log("[AutoProxyCookie] Applying authentications headers..."),C(o,s),console.log("[AutoProxyCookie] Authentications headers applied successfully")),this.log("debug","[AutoProxyCookie] Proxy Request:",e.method,e.url),this.options.hooks.onProxyReq)try{this.options.hooks.onProxyReq(o,e,t)}catch(r){this.log("error","[AutoProxyCookie] onProxyReq hook error:",r.message)}console.log("[AutoProxyCookie] === handleOnProxyReq END ===")};this.handleOnProxyRes=(o,e,t)=>{let n=["Content-Type","Content-Length","Authorization","Set-Cookie","X-Requested-With","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"];if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers",n.join(",")),t.setHeader("Access-Control-Allow-Credentials","true"),this.log("debug","[AutoProxyCookie] Proxy Response:",e.url,o.statusCode),this.options.hooks.onProxyRes)try{this.options.hooks.onProxyRes(o,e,t)}catch(s){this.log("error","[AutoProxyCookie] onProxyRes hook error:",s.message)}};this.handleOnError=(o,e,t)=>{if(this.log("error","[AutoProxyCookie] Proxy Error:",o.message),this.log("error","[AutoProxyCookie] URL:",e.url),t instanceof I.ServerResponse&&!t.headersSent&&(t.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),t.end(JSON.stringify({success:!1,message:"\u670D\u52A1\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",error:o.message}))),this.options.hooks.onError)try{this.options.hooks.onError(o,e,t)}catch(n){this.log("error","[AutoProxyCookie] onError hook error:",n.message)}};this.handleOnWsError=(o,e,t)=>{if(this.log("error","[AutoProxyCookie] WebSocket Proxy Error:",o.message),this.log("error","[AutoProxyCookie] WebSocket URL:",e.url),t&&t.close(),this.options.hooks.onWsError)try{this.options.hooks.onWsError(o,e,t)}catch(n){this.log("error","[AutoProxyCookie] onWsError hook error:",n.message)}};let t={...o,hooks:{...{onProxyReq:()=>{},onProxyRes:()=>{},onError:()=>{},onWsError:()=>{}},...o.hooks||{}}};this.options={debug:!1,autoRestart:!1,restartMarkerFile:".cookie-restart-marker",proxyMap:{},proxyPaths:[],ignorePaths:[],ws:!0,changeOrigin:!0,secure:!1,followRedirects:!0,autoRewrite:!1,protocolRewrite:void 0,logLevel:"info",cookieDomainRewrite:"*",cookiePathRewrite:!1,headers:{},useCookie:!0,authentications:[],...t},this.cookieReader=new k({cookieFile:o.cookieFile},o.debug??!1)}getProxyUrl(o){let e=o.url||"/",t=new URL(e,"http://localhost").pathname,n=this.options.proxyMap||{},s=this.options.proxyPaths||[];this.log("debug","[AutoProxyCookie] getProxyUrl - Request path:",t),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyMap paths:",Object.keys(n)),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyPaths:",s);for(let[r,a]of Object.entries(n)){let l=t.startsWith(r);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyMap:",r,"- matches:",l),l)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyMap:",r,"->",a),a}for(let r of s){let a=t.startsWith(r);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyPaths:",r,"- matches:",a),a)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyPaths:",r,"->",this.options.target),this.options.target}return this.log("debug","[AutoProxyCookie] getProxyUrl - No match found, using default target:",this.options.target),this.options.target}isIgnoredPath(o){return(this.options.ignorePaths||[]).some(t=>o.startsWith(t))}log(o,...e){let t={debug:0,info:1,warn:2,error:3},n=this.options.debug?"debug":this.options.logLevel||"info",s=t[n];t[o]>=s&&(o==="error"?console.error(...e):o==="warn"?console.warn(...e):console.log(...e))}createProxyOptions(o){let{ws:e,changeOrigin:t,secure:n,followRedirects:s,autoRewrite:r,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:p,headers:h}=this.options;return{target:o,ws:e,changeOrigin:t,secure:n,followRedirects:s,autoRewrite:r,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:p,headers:{...h},ignorePath:!1}}async setup(o){this.server=o,this.currentCookie=this.cookieReader.readCookie();try{let e={target:this.options.target,changeOrigin:this.options.changeOrigin,secure:this.options.secure,followRedirects:this.options.followRedirects,autoRewrite:this.options.autoRewrite,protocolRewrite:this.options.protocolRewrite,cookieDomainRewrite:this.options.cookieDomainRewrite,cookiePathRewrite:this.options.cookiePathRewrite,ws:this.options.ws};this.proxyServer=U.createProxyServer(e),this.proxyServer.on("proxyReq",this.handleOnProxyReq),this.proxyServer.on("proxyRes",this.handleOnProxyRes),this.proxyServer.on("error",this.handleOnError),this.options.ws&&this.proxyServer.on("wsError",this.handleOnWsError),this.log("info","[AutoProxyCookie] Proxy server created with WebSocket support")}catch(e){this.log("warn","[AutoProxyCookie] http-proxy create failed, using basic mode:",e.message)}o.middlewares.use((e,t,n)=>{let s=e.url||"/",r=new URL(s,"http://localhost").pathname;if(console.log("[AutoProxyCookie] === Incoming Request ==="),console.log("[AutoProxyCookie] Method:",e.method),console.log("[AutoProxyCookie] Full URL:",s),console.log("[AutoProxyCookie] Pathname:",r),console.log("[AutoProxyCookie] useCookie:",this.options.useCookie),console.log("[AutoProxyCookie] Headers:",JSON.stringify(e.headers,null,2)),this.isIgnoredPath(r)){console.log("[AutoProxyCookie] Path ignored, passing to next middleware"),n();return}this.options.useCookie?(this.currentCookie=this.cookieReader.readCookie(),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.currentCookie&&console.log("[AutoProxyCookie] Cookie preview:",this.currentCookie)):console.log("[AutoProxyCookie] useCookie is false, skipping cookie reading");let a=Object.keys(this.options.proxyMap||{}),l=this.options.proxyPaths||[],h=[...a,...l].some(u=>r.startsWith(u));if(console.log("[AutoProxyCookie] Path matches proxy rules:",h),this.proxyServer){let u=this.getProxyUrl(e);console.log(`[AutoProxyCookie] Proxying ${e.method} ${r} -> ${u}`);let g=this.createProxyOptions(u);try{console.log("[AutoProxyCookie] Calling proxyServer.web..."),this.proxyServer.web(e,t,g),console.log("[AutoProxyCookie] proxyServer.web called successfully")}catch(d){console.error("[AutoProxyCookie] Proxy web error:",d.message),n(d)}}else console.log("[AutoProxyCookie] No proxy server, passing to next middleware"),n()}),this.options.ws&&this.server.httpServer&&this.proxyServer&&(this.server.httpServer.on("upgrade",(e,t,n)=>{let s=new URL(e.url||"/","http://localhost").pathname;if(this.isIgnoredPath(s)){t.destroy();return}let r=this.getProxyUrl(e);this.proxyServer?.ws(e,t,n,{target:r,ws:!0,changeOrigin:this.options.changeOrigin,secure:this.options.secure})}),this.log("info","[AutoProxyCookie] WebSocket upgrade handler registered")),this.startFileWatch(),this.log("info","[AutoProxyCookie] Auto-proxy middleware enabled"),this.log("info","[AutoProxyCookie] Target:",this.options.target),this.log("info","[AutoProxyCookie] Cookie file:",this.options.cookieFile),this.options.autoRestart&&this.log("info","[AutoProxyCookie] Auto-restart enabled"),this.options.ws&&this.log("info","[AutoProxyCookie] WebSocket support enabled")}startFileWatch(){let o;this.options.isDev!==void 0?(o=this.options.isDev,this.options.debug&&console.log(`[AutoProxyCookie] isDev=${this.options.isDev}, ${o?"enabling":"disabling"} watch`)):(o=!0,this.options.debug&&console.log("[AutoProxyCookie] Default behavior: enabling watch (dev mode)")),o?this.watcher=w(this.options.cookieFile,this.handleCookieChange,e=>{this.log("error","[AutoProxyCookie] File watch error:",e.message)}):this.options.debug&&console.log("[AutoProxyCookie] File watch disabled")}stop(){this.watcher&&(this.watcher.stop(),this.watcher=null),this.proxyServer&&(this.proxyServer.close(),this.proxyServer=null),this.log("info","[AutoProxyCookie] Stopped")}getCurrentCookie(){return this.currentCookie}};function lo(i){return new A(i)}function L(i,o){return o.some(e=>i.startsWith(e))}function T(i,o){return o.some(e=>i.startsWith(e))}function _(i,o,e){for(let[t,n]of Object.entries(o))if(i.startsWith(t))return n;return e}function uo(i){let{cookieFile:o,target:e,debug:t=!1,useCookie:n=!0,authentications:s=[],proxyMap:r={},proxyPaths:a=[],ignorePaths:l=[]}=i,p=new k({cookieFile:o},t),h="";n&&(h=p.readCookie());let u=[...Object.keys(r),...a];return{name:"vite-middleware-proxy",apply:"serve",configureServer(g){let y=V("http-proxy").createProxyServer({});n&&t&&console.log("[ViteMiddlewareProxy] Watching cookie file:",o),g.middlewares.use((c,m,E)=>{let P=new URL(c.url||"/","http://localhost").pathname;if(L(P,l)){t&&console.log("[ViteMiddlewareProxy] Ignoring:",P),E();return}if(!T(P,u)){E();return}let S=_(P,r,e);t&&console.log("[ViteMiddlewareProxy] Proxying:",c.method,P,"->",S),y.web(c,m,{target:S,changeOrigin:!0,secure:!1,ignorePath:!1})}),y.on("proxyReq",(c,m)=>{n?(h=p.readCookie(),h?(t&&console.log("[ViteMiddlewareProxy] Injecting cookie:",`(length: ${h.length})`),x(c,h)):t&&console.log("[ViteMiddlewareProxy] Cookie file is empty")):t&&console.log("[ViteMiddlewareProxy] useCookie is false, skipping cookie injection"),s&&s.length>0&&(C(c,s),t&&console.log("[ViteMiddlewareProxy] Injecting authentications:",JSON.stringify(s)))}),y.on("error",(c,m)=>{console.error("[ViteMiddlewareProxy] Proxy error:",c.message,"for",m.url)})}}}import*as b from"path";function H(i,o={}){let{getCookie:e,debug:t=!1,useCookie:n=!0,authentications:s=[],headers:r={},ws:a=!1,changeOrigin:l=!0,secure:p=!1,onError:h}=o;return{ws:a,target:i,changeOrigin:l,secure:p,headers:r,onProxyReq:(g,d)=>{let y=d.url||"/";if(n){let c=e?e():"";c&&x(g,c),t&&console.log("[Proxy Request]",y,d.method,c?"(with cookie)":"(no cookie)")}else t&&console.log("[Proxy Request]",y,d.method,"(useCookie is false, skipping cookie injection)");s&&s.length>0&&(C(g,s),t&&console.log("[Proxy Request]",y,d.method,"(with authentications)"))},onError:h||(g=>{console.error(`
|
|
3
|
+
[Proxy Error]`,g.message)})}}function Co(i,o={}){let{watch:e="auto",debug:t=!0,productionEnvs:n=[],isDev:s}=o,r=new k({cookieFile:b.resolve(i)},t),a;return s!==void 0?(a=s,t&&console.log(`[CookieFile] isDev=${s}, ${a?"enabling":"disabling"} watch`)):a=M(e,n,t,"[CookieFile]"),a?w(b.resolve(i),l=>{t&&console.log("[CookieFile] Updated:",l?"(has cookie)":"(empty)")},l=>{console.error("[CookieFile] Watch error:",l.message)}):t&&console.log("[CookieFile] File watch disabled"),()=>r.readCookie()}function Po(i){let{target:o,ignorePaths:e=[],includePaths:t=[],additionalProxies:n={},getCookie:s,debug:r,headers:a,useCookie:l=!0,authentications:p=[]}=i,h={};if(t.length>0)for(let u of t)h[u]=H(o,{getCookie:s,debug:r,headers:a,useCookie:l,authentications:p});else{let u={ws:!1,target:o,changeOrigin:!0,secure:!1,headers:a,onProxyReq:(g,d)=>{let y=d.url||"/";if(!e.some(c=>y.startsWith(c))){if(l){let c=s?s():"";c&&x(g,c),r&&console.log("[Proxy Request]",y,d.method,c?"(with cookie)":"(no cookie)")}else r&&console.log("[Proxy Request]",y,d.method,"(useCookie is false, skipping cookie injection)");p&&p.length>0&&(C(g,p),r&&console.log("[Proxy Request]",y,d.method,"(with authentications)"))}},onError:g=>{console.error(`
|
|
4
|
+
[Proxy Error]`,g.message)}};h["/"]=u}for(let[u,g]of Object.entries(n))h[u]=H(g,{getCookie:s,debug:r,headers:a,useCookie:l,authentications:p});return h}export{A as AutoProxyCookie,k as CookieReader,R as CookieWatcher,C as applyDevAuthentications,Po as createAutoProxyConfig,lo as createAutoProxyCookie,q as createCookieGetter,Co as createFileCookieGetter,H as createVueProxyConfig,N as detectProductionEnvironment,D as isProductionValue,M as shouldEnableWatch,uo as viteMiddlewareProxy,w as watchCookieFile};
|
package/dist/index.mjs
CHANGED
|
@@ -295,6 +295,24 @@ function applyDevCookieHeader(proxyReq, cookie) {
|
|
|
295
295
|
console.log("[applyDevCookieHeader] === END ===");
|
|
296
296
|
}
|
|
297
297
|
|
|
298
|
+
// src/proxy/apply-dev-authentications.ts
|
|
299
|
+
function applyDevAuthentications(proxyReq, authentications) {
|
|
300
|
+
console.log("[applyDevAuthentications] === START ===");
|
|
301
|
+
if (!authentications || authentications.length === 0) {
|
|
302
|
+
console.log("[applyDevAuthentications] Authentications is empty, returning");
|
|
303
|
+
console.log("[applyDevAuthentications] === END ===");
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
console.log("[applyDevAuthentications] Applying authentications:", JSON.stringify(authentications));
|
|
307
|
+
for (const authItem of authentications) {
|
|
308
|
+
for (const [key, value] of Object.entries(authItem)) {
|
|
309
|
+
proxyReq.setHeader(key, value);
|
|
310
|
+
console.log("[applyDevAuthentications] Set header:", key, "->", value);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
console.log("[applyDevAuthentications] === END ===");
|
|
314
|
+
}
|
|
315
|
+
|
|
298
316
|
// src/proxy/core.ts
|
|
299
317
|
var AutoProxyCookie = class {
|
|
300
318
|
/**
|
|
@@ -350,6 +368,12 @@ var AutoProxyCookie = class {
|
|
|
350
368
|
} else {
|
|
351
369
|
console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!");
|
|
352
370
|
}
|
|
371
|
+
const authentications = this.options.authentications || [];
|
|
372
|
+
if (authentications.length > 0) {
|
|
373
|
+
console.log("[AutoProxyCookie] Applying authentications headers...");
|
|
374
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
375
|
+
console.log("[AutoProxyCookie] Authentications headers applied successfully");
|
|
376
|
+
}
|
|
353
377
|
this.log("debug", "[AutoProxyCookie] Proxy Request:", req.method, req.url);
|
|
354
378
|
if (this.options.hooks.onProxyReq) {
|
|
355
379
|
try {
|
|
@@ -469,6 +493,7 @@ var AutoProxyCookie = class {
|
|
|
469
493
|
cookiePathRewrite: false,
|
|
470
494
|
headers: {},
|
|
471
495
|
useCookie: true,
|
|
496
|
+
authentications: [],
|
|
472
497
|
...mergedOptions
|
|
473
498
|
};
|
|
474
499
|
this.cookieReader = new CookieReader({ cookieFile: options.cookieFile }, options.debug ?? false);
|
|
@@ -747,6 +772,7 @@ function viteMiddlewareProxy(options) {
|
|
|
747
772
|
target,
|
|
748
773
|
debug = false,
|
|
749
774
|
useCookie = true,
|
|
775
|
+
authentications = [],
|
|
750
776
|
proxyMap = {},
|
|
751
777
|
proxyPaths = [],
|
|
752
778
|
ignorePaths = []
|
|
@@ -786,26 +812,33 @@ function viteMiddlewareProxy(options) {
|
|
|
786
812
|
if (debug) {
|
|
787
813
|
console.log("[ViteMiddlewareProxy] Proxying:", req.method, pathname, "->", proxyTarget);
|
|
788
814
|
}
|
|
815
|
+
proxyServer.web(req, res, {
|
|
816
|
+
target: proxyTarget,
|
|
817
|
+
changeOrigin: true,
|
|
818
|
+
secure: false,
|
|
819
|
+
ignorePath: false
|
|
820
|
+
});
|
|
821
|
+
});
|
|
822
|
+
proxyServer.on("proxyReq", (proxyReq, req) => {
|
|
789
823
|
if (useCookie) {
|
|
790
824
|
currentCookie = cookieReader.readCookie();
|
|
791
825
|
if (currentCookie) {
|
|
792
826
|
if (debug) {
|
|
793
827
|
console.log("[ViteMiddlewareProxy] Injecting cookie:", `(length: ${currentCookie.length})`);
|
|
794
828
|
}
|
|
795
|
-
|
|
796
|
-
req.headers["Cookie"] = currentCookie;
|
|
829
|
+
applyDevCookieHeader(proxyReq, currentCookie);
|
|
797
830
|
} else if (debug) {
|
|
798
831
|
console.log("[ViteMiddlewareProxy] Cookie file is empty");
|
|
799
832
|
}
|
|
800
833
|
} else if (debug) {
|
|
801
834
|
console.log("[ViteMiddlewareProxy] useCookie is false, skipping cookie injection");
|
|
802
835
|
}
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
}
|
|
836
|
+
if (authentications && authentications.length > 0) {
|
|
837
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
838
|
+
if (debug) {
|
|
839
|
+
console.log("[ViteMiddlewareProxy] Injecting authentications:", JSON.stringify(authentications));
|
|
840
|
+
}
|
|
841
|
+
}
|
|
809
842
|
});
|
|
810
843
|
proxyServer.on("error", (err, req) => {
|
|
811
844
|
console.error("[ViteMiddlewareProxy] Proxy error:", err.message, "for", req.url);
|
|
@@ -821,6 +854,7 @@ function createVueProxyConfig(target, options = {}) {
|
|
|
821
854
|
getCookie,
|
|
822
855
|
debug = false,
|
|
823
856
|
useCookie = true,
|
|
857
|
+
authentications = [],
|
|
824
858
|
headers = {},
|
|
825
859
|
ws = false,
|
|
826
860
|
changeOrigin = true,
|
|
@@ -846,6 +880,12 @@ function createVueProxyConfig(target, options = {}) {
|
|
|
846
880
|
} else if (debug) {
|
|
847
881
|
console.log("[Proxy Request]", reqPath, req.method, "(useCookie is false, skipping cookie injection)");
|
|
848
882
|
}
|
|
883
|
+
if (authentications && authentications.length > 0) {
|
|
884
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
885
|
+
if (debug) {
|
|
886
|
+
console.log("[Proxy Request]", reqPath, req.method, "(with authentications)");
|
|
887
|
+
}
|
|
888
|
+
}
|
|
849
889
|
},
|
|
850
890
|
onError: customOnError || ((err) => {
|
|
851
891
|
console.error("\n[Proxy Error]", err.message);
|
|
@@ -888,11 +928,11 @@ function createFileCookieGetter(cookieFile, options = {}) {
|
|
|
888
928
|
return () => reader.readCookie();
|
|
889
929
|
}
|
|
890
930
|
function createAutoProxyConfig(options) {
|
|
891
|
-
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers, useCookie = true } = options;
|
|
931
|
+
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers, useCookie = true, authentications = [] } = options;
|
|
892
932
|
const result = {};
|
|
893
933
|
if (includePaths.length > 0) {
|
|
894
934
|
for (const proxyPath of includePaths) {
|
|
895
|
-
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers, useCookie });
|
|
935
|
+
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers, useCookie, authentications });
|
|
896
936
|
}
|
|
897
937
|
} else {
|
|
898
938
|
const defaultProxy = {
|
|
@@ -917,6 +957,12 @@ function createAutoProxyConfig(options) {
|
|
|
917
957
|
} else if (debug) {
|
|
918
958
|
console.log("[Proxy Request]", reqPath, req.method, "(useCookie is false, skipping cookie injection)");
|
|
919
959
|
}
|
|
960
|
+
if (authentications && authentications.length > 0) {
|
|
961
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
962
|
+
if (debug) {
|
|
963
|
+
console.log("[Proxy Request]", reqPath, req.method, "(with authentications)");
|
|
964
|
+
}
|
|
965
|
+
}
|
|
920
966
|
},
|
|
921
967
|
onError: (err) => {
|
|
922
968
|
console.error("\n[Proxy Error]", err.message);
|
|
@@ -925,7 +971,7 @@ function createAutoProxyConfig(options) {
|
|
|
925
971
|
result["/"] = defaultProxy;
|
|
926
972
|
}
|
|
927
973
|
for (const [proxyPath, proxyTarget] of Object.entries(additionalProxies)) {
|
|
928
|
-
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers, useCookie });
|
|
974
|
+
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers, useCookie, authentications });
|
|
929
975
|
}
|
|
930
976
|
return result;
|
|
931
977
|
}
|
|
@@ -933,6 +979,7 @@ export {
|
|
|
933
979
|
AutoProxyCookie,
|
|
934
980
|
CookieReader,
|
|
935
981
|
CookieWatcher,
|
|
982
|
+
applyDevAuthentications,
|
|
936
983
|
createAutoProxyConfig,
|
|
937
984
|
createAutoProxyCookie,
|
|
938
985
|
createCookieGetter,
|
package/package.json
CHANGED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 应用开发环境自定义鉴权信息到代理请求头
|
|
3
|
+
*
|
|
4
|
+
* 将自定义鉴权信息数组展开为请求头键值对,注入到代理请求中。
|
|
5
|
+
* 支持多种鉴权方式,如 ticket、token、Authorization 等。
|
|
6
|
+
*
|
|
7
|
+
* @module apply-dev-authentications
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export type AuthenticationItem = Record<string, string>;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 将自定义鉴权信息数组应用到代理请求头
|
|
14
|
+
*
|
|
15
|
+
* @param proxyReq - 代理请求对象
|
|
16
|
+
* @param authentications - 鉴权信息数组,每个元素是一个键值对对象
|
|
17
|
+
*/
|
|
18
|
+
export function applyDevAuthentications(
|
|
19
|
+
proxyReq: { setHeader(name: string, value: string): void; getHeader?(name: string): string | string[] | undefined },
|
|
20
|
+
authentications: AuthenticationItem[]
|
|
21
|
+
): void {
|
|
22
|
+
console.log('[applyDevAuthentications] === START ===');
|
|
23
|
+
|
|
24
|
+
if (!authentications || authentications.length === 0) {
|
|
25
|
+
console.log('[applyDevAuthentications] Authentications is empty, returning');
|
|
26
|
+
console.log('[applyDevAuthentications] === END ===');
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
console.log('[applyDevAuthentications] Applying authentications:', JSON.stringify(authentications));
|
|
31
|
+
|
|
32
|
+
for (const authItem of authentications) {
|
|
33
|
+
for (const [key, value] of Object.entries(authItem)) {
|
|
34
|
+
proxyReq.setHeader(key, value);
|
|
35
|
+
console.log('[applyDevAuthentications] Set header:', key, '->', value);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
console.log('[applyDevAuthentications] === END ===');
|
|
40
|
+
}
|
package/src/proxy/core.ts
CHANGED
|
@@ -15,6 +15,7 @@ import type { ViteDevServer } from 'vite';
|
|
|
15
15
|
import httpProxy from 'http-proxy';
|
|
16
16
|
import { CookieReader, CookieWatcher, watchCookieFile } from '../utils';
|
|
17
17
|
import { applyDevCookieHeader } from './apply-dev-cookie-header';
|
|
18
|
+
import { applyDevAuthentications, type AuthenticationItem } from './apply-dev-authentications';
|
|
18
19
|
|
|
19
20
|
/**
|
|
20
21
|
* 错误回调函数类型
|
|
@@ -106,6 +107,11 @@ export interface AutoProxyCookieOptions {
|
|
|
106
107
|
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
107
108
|
*/
|
|
108
109
|
useCookie?: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
112
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
113
|
+
*/
|
|
114
|
+
authentications?: AuthenticationItem[];
|
|
109
115
|
}
|
|
110
116
|
|
|
111
117
|
/**
|
|
@@ -166,6 +172,7 @@ export class AutoProxyCookie {
|
|
|
166
172
|
cookiePathRewrite: false,
|
|
167
173
|
headers: {},
|
|
168
174
|
useCookie: true,
|
|
175
|
+
authentications: [],
|
|
169
176
|
...mergedOptions,
|
|
170
177
|
};
|
|
171
178
|
this.cookieReader = new CookieReader({ cookieFile: options.cookieFile }, options.debug ?? false);
|
|
@@ -324,6 +331,13 @@ export class AutoProxyCookie {
|
|
|
324
331
|
console.log('[AutoProxyCookie] No cookie to apply - currentCookie is empty!');
|
|
325
332
|
}
|
|
326
333
|
|
|
334
|
+
const authentications = this.options.authentications || [];
|
|
335
|
+
if (authentications.length > 0) {
|
|
336
|
+
console.log('[AutoProxyCookie] Applying authentications headers...');
|
|
337
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
338
|
+
console.log('[AutoProxyCookie] Authentications headers applied successfully');
|
|
339
|
+
}
|
|
340
|
+
|
|
327
341
|
this.log('debug', '[AutoProxyCookie] Proxy Request:', req.method, req.url);
|
|
328
342
|
|
|
329
343
|
if (this.options.hooks.onProxyReq) {
|
package/src/proxy/index.ts
CHANGED
|
@@ -8,12 +8,14 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import type { IncomingMessage, ServerResponse } from 'http';
|
|
10
10
|
import { CookieReader } from '../utils/cookie-reader';
|
|
11
|
+
import { applyDevCookieHeader } from './apply-dev-cookie-header';
|
|
12
|
+
import { applyDevAuthentications, type AuthenticationItem } from './apply-dev-authentications';
|
|
11
13
|
|
|
12
14
|
/**
|
|
13
15
|
* Vite 中间件代理 Cookie 插件配置选项
|
|
14
16
|
*/
|
|
15
17
|
export interface ViteMiddlewareProxyOptions {
|
|
16
|
-
/** Cookie
|
|
18
|
+
/** Cookie 文件路径, 使用文件方便监听cookie 变化,避免手动启动更新 */
|
|
17
19
|
cookieFile: string;
|
|
18
20
|
/** 默认代理目标地址 */
|
|
19
21
|
target: string;
|
|
@@ -27,6 +29,11 @@ export interface ViteMiddlewareProxyOptions {
|
|
|
27
29
|
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
28
30
|
*/
|
|
29
31
|
useCookie?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
34
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
35
|
+
*/
|
|
36
|
+
authentications?: AuthenticationItem[];
|
|
30
37
|
/**
|
|
31
38
|
* 代理路径映射表
|
|
32
39
|
* 键:路径前缀,值:代理目标地址
|
|
@@ -80,6 +87,7 @@ export function viteMiddlewareProxy(options: ViteMiddlewareProxyOptions): any {
|
|
|
80
87
|
target,
|
|
81
88
|
debug = false,
|
|
82
89
|
useCookie = true,
|
|
90
|
+
authentications = [],
|
|
83
91
|
proxyMap = {},
|
|
84
92
|
proxyPaths = [],
|
|
85
93
|
ignorePaths = [],
|
|
@@ -140,7 +148,17 @@ export function viteMiddlewareProxy(options: ViteMiddlewareProxyOptions): any {
|
|
|
140
148
|
console.log('[ViteMiddlewareProxy] Proxying:', req.method, pathname, '->', proxyTarget);
|
|
141
149
|
}
|
|
142
150
|
|
|
143
|
-
//
|
|
151
|
+
// 代理请求
|
|
152
|
+
proxyServer.web(req, res, {
|
|
153
|
+
target: proxyTarget,
|
|
154
|
+
changeOrigin: true,
|
|
155
|
+
secure: false,
|
|
156
|
+
ignorePath: false,
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// 代理请求前的回调 - 注入 Cookie 和自定义鉴权信息
|
|
161
|
+
proxyServer.on('proxyReq', (proxyReq: any, req: IncomingMessage) => {
|
|
144
162
|
if (useCookie) {
|
|
145
163
|
currentCookie = cookieReader.readCookie();
|
|
146
164
|
|
|
@@ -148,8 +166,7 @@ export function viteMiddlewareProxy(options: ViteMiddlewareProxyOptions): any {
|
|
|
148
166
|
if (debug) {
|
|
149
167
|
console.log('[ViteMiddlewareProxy] Injecting cookie:', `(length: ${currentCookie.length})`);
|
|
150
168
|
}
|
|
151
|
-
(
|
|
152
|
-
(req as any).headers['Cookie'] = currentCookie;
|
|
169
|
+
applyDevCookieHeader(proxyReq, currentCookie);
|
|
153
170
|
} else if (debug) {
|
|
154
171
|
console.log('[ViteMiddlewareProxy] Cookie file is empty');
|
|
155
172
|
}
|
|
@@ -157,13 +174,12 @@ export function viteMiddlewareProxy(options: ViteMiddlewareProxyOptions): any {
|
|
|
157
174
|
console.log('[ViteMiddlewareProxy] useCookie is false, skipping cookie injection');
|
|
158
175
|
}
|
|
159
176
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
});
|
|
177
|
+
if (authentications && authentications.length > 0) {
|
|
178
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
179
|
+
if (debug) {
|
|
180
|
+
console.log('[ViteMiddlewareProxy] Injecting authentications:', JSON.stringify(authentications));
|
|
181
|
+
}
|
|
182
|
+
}
|
|
167
183
|
});
|
|
168
184
|
|
|
169
185
|
// 错误处理
|
|
@@ -10,6 +10,7 @@ import type { IncomingMessage } from 'http';
|
|
|
10
10
|
import * as path from 'path';
|
|
11
11
|
import { CookieReader, watchCookieFile, shouldEnableWatch } from '../utils';
|
|
12
12
|
import { applyDevCookieHeader } from './apply-dev-cookie-header';
|
|
13
|
+
import { applyDevAuthentications, type AuthenticationItem } from './apply-dev-authentications';
|
|
13
14
|
|
|
14
15
|
/** Options for {@link createFileCookieGetter}. */
|
|
15
16
|
export interface CreateFileCookieGetterOptions {
|
|
@@ -58,6 +59,11 @@ export interface VueProxyConfigOptions {
|
|
|
58
59
|
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
59
60
|
*/
|
|
60
61
|
useCookie?: boolean;
|
|
62
|
+
/**
|
|
63
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
64
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
65
|
+
*/
|
|
66
|
+
authentications?: AuthenticationItem[];
|
|
61
67
|
/** 自定义请求头 */
|
|
62
68
|
headers?: Record<string, string>;
|
|
63
69
|
/** 是否启用 WebSocket 代理 */
|
|
@@ -109,6 +115,7 @@ export function createVueProxyConfig(
|
|
|
109
115
|
getCookie,
|
|
110
116
|
debug = false,
|
|
111
117
|
useCookie = true,
|
|
118
|
+
authentications = [],
|
|
112
119
|
headers = {},
|
|
113
120
|
ws = false,
|
|
114
121
|
changeOrigin = true,
|
|
@@ -136,6 +143,13 @@ export function createVueProxyConfig(
|
|
|
136
143
|
} else if (debug) {
|
|
137
144
|
console.log('[Proxy Request]', reqPath, req.method, '(useCookie is false, skipping cookie injection)');
|
|
138
145
|
}
|
|
146
|
+
|
|
147
|
+
if (authentications && authentications.length > 0) {
|
|
148
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
149
|
+
if (debug) {
|
|
150
|
+
console.log('[Proxy Request]', reqPath, req.method, '(with authentications)');
|
|
151
|
+
}
|
|
152
|
+
}
|
|
139
153
|
},
|
|
140
154
|
onError: customOnError || ((err: Error) => {
|
|
141
155
|
console.error('\n[Proxy Error]', err.message);
|
|
@@ -223,13 +237,13 @@ export interface AutoProxyConfigOptions extends VueProxyConfigOptions {
|
|
|
223
237
|
* @returns Vue CLI 代理配置对象映射
|
|
224
238
|
*/
|
|
225
239
|
export function createAutoProxyConfig(options: AutoProxyConfigOptions): Record<string, ProxyConfig> {
|
|
226
|
-
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers, useCookie = true } = options;
|
|
240
|
+
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers, useCookie = true, authentications = [] } = options;
|
|
227
241
|
|
|
228
242
|
const result: Record<string, ProxyConfig> = {};
|
|
229
243
|
|
|
230
244
|
if (includePaths.length > 0) {
|
|
231
245
|
for (const proxyPath of includePaths) {
|
|
232
|
-
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers, useCookie });
|
|
246
|
+
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers, useCookie, authentications });
|
|
233
247
|
}
|
|
234
248
|
} else {
|
|
235
249
|
const defaultProxy: ProxyConfig = {
|
|
@@ -256,6 +270,13 @@ export function createAutoProxyConfig(options: AutoProxyConfigOptions): Record<s
|
|
|
256
270
|
} else if (debug) {
|
|
257
271
|
console.log('[Proxy Request]', reqPath, req.method, '(useCookie is false, skipping cookie injection)');
|
|
258
272
|
}
|
|
273
|
+
|
|
274
|
+
if (authentications && authentications.length > 0) {
|
|
275
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
276
|
+
if (debug) {
|
|
277
|
+
console.log('[Proxy Request]', reqPath, req.method, '(with authentications)');
|
|
278
|
+
}
|
|
279
|
+
}
|
|
259
280
|
},
|
|
260
281
|
onError: (err: Error) => {
|
|
261
282
|
console.error('\n[Proxy Error]', err.message);
|
|
@@ -265,7 +286,7 @@ export function createAutoProxyConfig(options: AutoProxyConfigOptions): Record<s
|
|
|
265
286
|
}
|
|
266
287
|
|
|
267
288
|
for (const [proxyPath, proxyTarget] of Object.entries(additionalProxies)) {
|
|
268
|
-
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers, useCookie });
|
|
289
|
+
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers, useCookie, authentications });
|
|
269
290
|
}
|
|
270
291
|
|
|
271
292
|
return result;
|