@gylautorun/dev-proxy-cookie 1.0.2 → 1.0.3
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/README.md +212 -236
- package/dist/index.d.mts +24 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +57 -29
- package/dist/index.min.js +4 -4
- package/dist/index.min.mjs +4 -4
- package/dist/index.mjs +57 -29
- package/package.json +1 -1
- package/src/proxy/core.ts +23 -6
- package/src/proxy/vite-middleware-plugin.ts +30 -11
- package/src/proxy/vue-proxy-config.ts +34 -16
package/dist/index.d.ts
CHANGED
|
@@ -64,6 +64,14 @@ interface AutoProxyCookieOptions {
|
|
|
64
64
|
* 使用示例: isDev: process.env.NODE_ENV === 'development'
|
|
65
65
|
*/
|
|
66
66
|
isDev?: boolean;
|
|
67
|
+
/**
|
|
68
|
+
* 是否使用 Cookie 文件中的 Cookie 注入到请求中
|
|
69
|
+
* - true: 使用文件中的 Cookie(默认)
|
|
70
|
+
* - false: 不注入 Cookie,使用浏览器发送的 Cookie
|
|
71
|
+
*
|
|
72
|
+
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
73
|
+
*/
|
|
74
|
+
useCookie?: boolean;
|
|
67
75
|
}
|
|
68
76
|
/**
|
|
69
77
|
* 自动代理 Cookie 类
|
|
@@ -183,6 +191,14 @@ interface ViteMiddlewareProxyOptions {
|
|
|
183
191
|
target: string;
|
|
184
192
|
/** 是否启用调试日志 */
|
|
185
193
|
debug?: boolean;
|
|
194
|
+
/**
|
|
195
|
+
* 是否使用 Cookie 文件中的 Cookie 注入到请求中
|
|
196
|
+
* - true: 使用文件中的 Cookie(默认)
|
|
197
|
+
* - false: 不注入 Cookie,使用浏览器发送的 Cookie
|
|
198
|
+
*
|
|
199
|
+
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
200
|
+
*/
|
|
201
|
+
useCookie?: boolean;
|
|
186
202
|
/**
|
|
187
203
|
* 代理路径映射表
|
|
188
204
|
* 键:路径前缀,值:代理目标地址
|
|
@@ -252,6 +268,14 @@ interface VueProxyConfigOptions {
|
|
|
252
268
|
getCookie?: () => string;
|
|
253
269
|
/** 是否输出调试日志 */
|
|
254
270
|
debug?: boolean;
|
|
271
|
+
/**
|
|
272
|
+
* 是否使用 Cookie 文件中的 Cookie 注入到请求中
|
|
273
|
+
* - true: 使用文件中的 Cookie(默认)
|
|
274
|
+
* - false: 不注入 Cookie,使用浏览器发送的 Cookie
|
|
275
|
+
*
|
|
276
|
+
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
277
|
+
*/
|
|
278
|
+
useCookie?: boolean;
|
|
255
279
|
/** 自定义请求头 */
|
|
256
280
|
headers?: Record<string, string>;
|
|
257
281
|
/** 是否启用 WebSocket 代理 */
|
package/dist/index.js
CHANGED
|
@@ -380,11 +380,14 @@ var AutoProxyCookie = class {
|
|
|
380
380
|
this.handleOnProxyReq = (proxyReq, req, res, _options) => {
|
|
381
381
|
console.log("[AutoProxyCookie] === handleOnProxyReq START ===");
|
|
382
382
|
console.log("[AutoProxyCookie] Request URL:", req.method, req.url);
|
|
383
|
+
console.log("[AutoProxyCookie] useCookie:", this.options.useCookie);
|
|
383
384
|
console.log("[AutoProxyCookie] Current cookie:", this.currentCookie ? `(length: ${this.currentCookie.length})` : "(empty)");
|
|
384
|
-
if (this.currentCookie) {
|
|
385
|
+
if (this.options.useCookie && this.currentCookie) {
|
|
385
386
|
console.log("[AutoProxyCookie] Applying cookie header...");
|
|
386
387
|
applyDevCookieHeader(proxyReq, this.currentCookie);
|
|
387
388
|
console.log("[AutoProxyCookie] Cookie header applied successfully");
|
|
389
|
+
} else if (!this.options.useCookie) {
|
|
390
|
+
console.log("[AutoProxyCookie] useCookie is false, skipping cookie injection");
|
|
388
391
|
} else {
|
|
389
392
|
console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!");
|
|
390
393
|
}
|
|
@@ -506,6 +509,7 @@ var AutoProxyCookie = class {
|
|
|
506
509
|
cookieDomainRewrite: "*",
|
|
507
510
|
cookiePathRewrite: false,
|
|
508
511
|
headers: {},
|
|
512
|
+
useCookie: true,
|
|
509
513
|
...mergedOptions
|
|
510
514
|
};
|
|
511
515
|
this.cookieReader = new CookieReader({ cookieFile: options.cookieFile }, options.debug ?? false);
|
|
@@ -643,16 +647,21 @@ var AutoProxyCookie = class {
|
|
|
643
647
|
console.log("[AutoProxyCookie] Method:", req.method);
|
|
644
648
|
console.log("[AutoProxyCookie] Full URL:", fullUrl);
|
|
645
649
|
console.log("[AutoProxyCookie] Pathname:", pathname);
|
|
650
|
+
console.log("[AutoProxyCookie] useCookie:", this.options.useCookie);
|
|
646
651
|
console.log("[AutoProxyCookie] Headers:", JSON.stringify(req.headers, null, 2));
|
|
647
652
|
if (this.isIgnoredPath(pathname)) {
|
|
648
653
|
console.log("[AutoProxyCookie] Path ignored, passing to next middleware");
|
|
649
654
|
next();
|
|
650
655
|
return;
|
|
651
656
|
}
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
657
|
+
if (this.options.useCookie) {
|
|
658
|
+
this.currentCookie = this.cookieReader.readCookie();
|
|
659
|
+
console.log("[AutoProxyCookie] Current cookie:", this.currentCookie ? `(length: ${this.currentCookie.length})` : "(empty)");
|
|
660
|
+
if (this.currentCookie) {
|
|
661
|
+
console.log("[AutoProxyCookie] Cookie preview:", this.currentCookie);
|
|
662
|
+
}
|
|
663
|
+
} else {
|
|
664
|
+
console.log("[AutoProxyCookie] useCookie is false, skipping cookie reading");
|
|
656
665
|
}
|
|
657
666
|
const proxyMapKeys = Object.keys(this.options.proxyMap || {});
|
|
658
667
|
const proxyPaths = this.options.proxyPaths || [];
|
|
@@ -778,12 +787,16 @@ function viteMiddlewareProxy(options) {
|
|
|
778
787
|
cookieFile,
|
|
779
788
|
target,
|
|
780
789
|
debug = false,
|
|
790
|
+
useCookie = true,
|
|
781
791
|
proxyMap = {},
|
|
782
792
|
proxyPaths = [],
|
|
783
793
|
ignorePaths = []
|
|
784
794
|
} = options;
|
|
785
795
|
const cookieReader = new CookieReader({ cookieFile }, debug);
|
|
786
|
-
let currentCookie =
|
|
796
|
+
let currentCookie = "";
|
|
797
|
+
if (useCookie) {
|
|
798
|
+
currentCookie = cookieReader.readCookie();
|
|
799
|
+
}
|
|
787
800
|
const allProxyPrefixes = [
|
|
788
801
|
...Object.keys(proxyMap),
|
|
789
802
|
...proxyPaths
|
|
@@ -794,7 +807,7 @@ function viteMiddlewareProxy(options) {
|
|
|
794
807
|
configureServer(server) {
|
|
795
808
|
const httpProxy2 = require("http-proxy");
|
|
796
809
|
const proxyServer = httpProxy2.createProxyServer({});
|
|
797
|
-
if (debug) {
|
|
810
|
+
if (useCookie && debug) {
|
|
798
811
|
console.log("[ViteMiddlewareProxy] Watching cookie file:", cookieFile);
|
|
799
812
|
}
|
|
800
813
|
server.middlewares.use((req, res, next) => {
|
|
@@ -814,13 +827,19 @@ function viteMiddlewareProxy(options) {
|
|
|
814
827
|
if (debug) {
|
|
815
828
|
console.log("[ViteMiddlewareProxy] Proxying:", req.method, pathname, "->", proxyTarget);
|
|
816
829
|
}
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
if (
|
|
820
|
-
|
|
830
|
+
if (useCookie) {
|
|
831
|
+
currentCookie = cookieReader.readCookie();
|
|
832
|
+
if (currentCookie) {
|
|
833
|
+
if (debug) {
|
|
834
|
+
console.log("[ViteMiddlewareProxy] Injecting cookie:", `(length: ${currentCookie.length})`);
|
|
835
|
+
}
|
|
836
|
+
req.headers["cookie"] = currentCookie;
|
|
837
|
+
req.headers["Cookie"] = currentCookie;
|
|
838
|
+
} else if (debug) {
|
|
839
|
+
console.log("[ViteMiddlewareProxy] Cookie file is empty");
|
|
821
840
|
}
|
|
822
|
-
|
|
823
|
-
|
|
841
|
+
} else if (debug) {
|
|
842
|
+
console.log("[ViteMiddlewareProxy] useCookie is false, skipping cookie injection");
|
|
824
843
|
}
|
|
825
844
|
proxyServer.web(req, res, {
|
|
826
845
|
target: proxyTarget,
|
|
@@ -842,6 +861,7 @@ function createVueProxyConfig(target, options = {}) {
|
|
|
842
861
|
const {
|
|
843
862
|
getCookie,
|
|
844
863
|
debug = false,
|
|
864
|
+
useCookie = true,
|
|
845
865
|
headers = {},
|
|
846
866
|
ws = false,
|
|
847
867
|
changeOrigin = true,
|
|
@@ -855,13 +875,17 @@ function createVueProxyConfig(target, options = {}) {
|
|
|
855
875
|
secure,
|
|
856
876
|
headers,
|
|
857
877
|
onProxyReq: (proxyReq, req) => {
|
|
858
|
-
const
|
|
859
|
-
if (
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
878
|
+
const reqPath = req.url || "/";
|
|
879
|
+
if (useCookie) {
|
|
880
|
+
const cookie = getCookie ? getCookie() : "";
|
|
881
|
+
if (cookie) {
|
|
882
|
+
applyDevCookieHeader(proxyReq, cookie);
|
|
883
|
+
}
|
|
884
|
+
if (debug) {
|
|
885
|
+
console.log("[Proxy Request]", reqPath, req.method, cookie ? "(with cookie)" : "(no cookie)");
|
|
886
|
+
}
|
|
887
|
+
} else if (debug) {
|
|
888
|
+
console.log("[Proxy Request]", reqPath, req.method, "(useCookie is false, skipping cookie injection)");
|
|
865
889
|
}
|
|
866
890
|
},
|
|
867
891
|
onError: customOnError || ((err) => {
|
|
@@ -905,11 +929,11 @@ function createFileCookieGetter(cookieFile, options = {}) {
|
|
|
905
929
|
return () => reader.readCookie();
|
|
906
930
|
}
|
|
907
931
|
function createAutoProxyConfig(options) {
|
|
908
|
-
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers } = options;
|
|
932
|
+
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers, useCookie = true } = options;
|
|
909
933
|
const result = {};
|
|
910
934
|
if (includePaths.length > 0) {
|
|
911
935
|
for (const proxyPath of includePaths) {
|
|
912
|
-
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers });
|
|
936
|
+
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers, useCookie });
|
|
913
937
|
}
|
|
914
938
|
} else {
|
|
915
939
|
const defaultProxy = {
|
|
@@ -923,12 +947,16 @@ function createAutoProxyConfig(options) {
|
|
|
923
947
|
if (ignorePaths.some((p) => reqPath.startsWith(p))) {
|
|
924
948
|
return;
|
|
925
949
|
}
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
950
|
+
if (useCookie) {
|
|
951
|
+
const cookie = getCookie ? getCookie() : "";
|
|
952
|
+
if (cookie) {
|
|
953
|
+
applyDevCookieHeader(proxyReq, cookie);
|
|
954
|
+
}
|
|
955
|
+
if (debug) {
|
|
956
|
+
console.log("[Proxy Request]", reqPath, req.method, cookie ? "(with cookie)" : "(no cookie)");
|
|
957
|
+
}
|
|
958
|
+
} else if (debug) {
|
|
959
|
+
console.log("[Proxy Request]", reqPath, req.method, "(useCookie is false, skipping cookie injection)");
|
|
932
960
|
}
|
|
933
961
|
},
|
|
934
962
|
onError: (err) => {
|
|
@@ -938,7 +966,7 @@ function createAutoProxyConfig(options) {
|
|
|
938
966
|
result["/"] = defaultProxy;
|
|
939
967
|
}
|
|
940
968
|
for (const [proxyPath, proxyTarget] of Object.entries(additionalProxies)) {
|
|
941
|
-
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers });
|
|
969
|
+
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers, useCookie });
|
|
942
970
|
}
|
|
943
971
|
return result;
|
|
944
972
|
}
|
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);y.existsSync(e)||y.mkdirSync(e,{recursive:!0}),y.existsSync(o)||y.writeFileSync(o,"")}};function G(t){let o=new g({cookieFile:t});return()=>o.readCookie()}var F=f(require("path")),I=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 g({cookieFile:o.cookieFile})}start(){this.options.autoCreateFile&&this.cookieReader.ensureCookieFile();let o=F.resolve(this.options.cookieFile);this.lastContent=this.cookieReader.readCookie(),console.log(`[CookieWatcher] Started watching: ${o}`);try{this.watcher=I.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 b(t){return["production","prod","prd","release","staging","uat"].includes(t.toLowerCase().trim())}function W(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&&b(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&&b(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 A(t,o=[],e=!1,r="[env-detector]"){return typeof t=="boolean"?(e&&!t&&console.log(`${r} Watch disabled by user setting`),t):W(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=V.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] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.currentCookie?(console.log("[AutoProxyCookie] Applying cookie header..."),v(o,this.currentCookie),console.log("[AutoProxyCookie] Cookie header applied successfully")):console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!"),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 H.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:{},...r},this.cookieReader=new g({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:p,headers:h}=this.options;return{target:o,ws:e,changeOrigin:r,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=U.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] Headers:",JSON.stringify(e.headers,null,2)),this.isIgnoredPath(i)){console.log("[AutoProxyCookie] Path ignored, passing to next middleware"),s();return}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);let a=Object.keys(this.options.proxyMap||{}),l=this.options.proxyPaths||[],h=[...a,...l].some(d=>i.startsWith(d));if(console.log("[AutoProxyCookie] Path matches proxy rules:",h),this.proxyServer){let d=this.getProxyUrl(e);console.log(`[AutoProxyCookie] Proxying ${e.method} ${i} -> ${d}`);let u=this.createProxyOptions(d);try{console.log("[AutoProxyCookie] Calling proxyServer.web..."),this.proxyServer.web(e,r,u),console.log("[AutoProxyCookie] proxyServer.web called successfully")}catch(c){console.error("[AutoProxyCookie] Proxy web error:",c.message),s(c)}}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 J(t){return new R(t)}function K(t,o){return o.some(e=>t.startsWith(e))}function z(t,o){return o.some(e=>t.startsWith(e))}function X(t,o,e){for(let[r,s]of Object.entries(o))if(t.startsWith(r))return s;return e}function Y(t){let{cookieFile:o,target:e,debug:r=!1,proxyMap:s={},proxyPaths:n=[],ignorePaths:i=[]}=t,a=new g({cookieFile:o},r),l=a.readCookie(),p=[...Object.keys(s),...n];return{name:"vite-middleware-proxy",apply:"serve",configureServer(h){let u=require("http-proxy").createProxyServer({});r&&console.log("[ViteMiddlewareProxy] Watching cookie file:",o),h.middlewares.use((c,k,O)=>{let x=new URL(c.url||"/","http://localhost").pathname;if(K(x,i)){r&&console.log("[ViteMiddlewareProxy] Ignoring:",x),O();return}if(!z(x,p)){O();return}let M=X(x,s,e);r&&console.log("[ViteMiddlewareProxy] Proxying:",c.method,x,"->",M),l=a.readCookie(),l&&(r&&console.log("[ViteMiddlewareProxy] Injecting cookie:",`(length: ${l.length})`),c.headers.cookie=l,c.headers.Cookie=l),u.web(c,k,{target:M,changeOrigin:!0,secure:!1,ignorePath:!1})}),u.on("error",(c,k)=>{console.error("[ViteMiddlewareProxy] Proxy error:",c.message,"for",k.url)})}}}var E=f(require("path"));function S(t,o={}){let{getCookie:e,debug:r=!1,headers:s={},ws:n=!1,changeOrigin:i=!0,secure:a=!1,onError:l}=o;return{ws:n,target:t,changeOrigin:i,secure:a,headers:s,onProxyReq:(h,d)=>{let u=e?e():"";if(u&&v(h,u),r){let c=d.url||"/";console.log("[Proxy Request]",c,d.method,u?"(with cookie)":"(no cookie)")}},onError:l||(h=>{console.error(`
|
|
3
|
-
[Proxy Error]`,h.message)})}}function
|
|
4
|
-
[Proxy Error]`,h.message)}};
|
|
1
|
+
"use strict";var N=Object.create;var m=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var q=Object.getPrototypeOf,j=Object.prototype.hasOwnProperty;var B=(t,o)=>{for(var e in o)m(t,e,{get:o[e],enumerable:!0})},F=(t,o,e,r)=>{if(o&&typeof o=="object"||typeof o=="function")for(let s of T(o))!j.call(t,s)&&s!==e&&m(t,s,{get:()=>o[s],enumerable:!(r=_(o,s))||r.enumerable});return t};var f=(t,o,e)=>(e=t!=null?N(q(t)):{},F(o||!t||!t.__esModule?m(e,"default",{value:t,enumerable:!0}):e,t)),G=t=>F(m({},"__esModule",{value:!0}),t);var eo={};B(eo,{AutoProxyCookie:()=>R,CookieReader:()=>d,CookieWatcher:()=>w,createAutoProxyConfig:()=>oo,createAutoProxyCookie:()=>K,createCookieGetter:()=>J,createFileCookieGetter:()=>Z,createVueProxyConfig:()=>O,detectProductionEnvironment:()=>H,isProductionValue:()=>A,shouldEnableWatch:()=>E,viteMiddlewareProxy:()=>Q,watchCookieFile:()=>P});module.exports=G(eo);var V=f(require("http")),$=f(require("fs")),U=f(require("path")),L=f(require("http-proxy"));var k=f(require("fs")),C=f(require("path")),d=class{constructor(o,e=!1){this.options={encoding:"utf-8",...o},this.debug=e}readCookie(){try{let o=C.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=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]`,h.message)})}}function Z(t,o={}){let{watch:e="auto",debug:r=!0,productionEnvs:s=[],isDev:n}=o,i=new d({cookieFile:S.resolve(t)},r),a;return n!==void 0?(a=n,r&&console.log(`[CookieFile] isDev=${n}, ${a?"enabling":"disabling"} watch`)):a=E(e,s,r,"[CookieFile]"),a?P(S.resolve(t),l=>{r&&console.log("[CookieFile] Updated:",l?"(has cookie)":"(empty)")},l=>{console.error("[CookieFile] Watch error:",l.message)}):r&&console.log("[CookieFile] File watch disabled"),()=>i.readCookie()}function oo(t){let{target:o,ignorePaths:e=[],includePaths:r=[],additionalProxies:s={},getCookie:n,debug:i,headers:a,useCookie:l=!0}=t,g={};if(r.length>0)for(let p of r)g[p]=O(o,{getCookie:n,debug:i,headers:a,useCookie:l});else{let p={ws:!1,target:o,changeOrigin:!0,secure:!1,headers:a,onProxyReq:(h,y)=>{let u=y.url||"/";if(!e.some(c=>u.startsWith(c)))if(l){let c=n?n():"";c&&v(h,c),i&&console.log("[Proxy Request]",u,y.method,c?"(with cookie)":"(no cookie)")}else i&&console.log("[Proxy Request]",u,y.method,"(useCookie is false, skipping cookie injection)")},onError:h=>{console.error(`
|
|
4
|
+
[Proxy Error]`,h.message)}};g["/"]=p}for(let[p,h]of Object.entries(s))g[p]=O(h,{getCookie:n,debug:i,headers:a,useCookie:l});return g}0&&(module.exports={AutoProxyCookie,CookieReader,CookieWatcher,createAutoProxyConfig,createAutoProxyCookie,createCookieGetter,createFileCookieGetter,createVueProxyConfig,detectProductionEnvironment,isProductionValue,shouldEnableWatch,viteMiddlewareProxy,watchCookieFile});
|
package/dist/index.min.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).map(i=>i.trim()).filter(i=>i&&!i.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);u.existsSync(e)||u.mkdirSync(e,{recursive:!0}),u.existsSync(o)||u.writeFileSync(o,"")}};function _(t){let o=new y({cookieFile:t});return()=>o.readCookie()}import*as A from"path";import W from"chokidar";var v=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 y({cookieFile:o.cookieFile})}start(){this.options.autoCreateFile&&this.cookieReader.ensureCookieFile();let o=A.resolve(this.options.cookieFile);this.lastContent=this.cookieReader.readCookie(),console.log(`[CookieWatcher] Started watching: ${o}`);try{this.watcher=W.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 v({cookieFile:t,onCookieChange:o,onError:e});return r.start(),r}function E(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&&E(a))return o&&console.log(`${e} Detected production via custom env: ${i}=${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 i of n){let a=r[i];if(a&&E(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 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 S(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 C(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 m=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=D.resolve(this.options.restartMarkerFile);M.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] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.currentCookie?(console.log("[AutoProxyCookie] Applying cookie header..."),C(o,this.currentCookie),console.log("[AutoProxyCookie] Cookie header applied successfully")):console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!"),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 O.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:{},...r},this.cookieReader=new y({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[i,a]of Object.entries(n)){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 s){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},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:i,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:g,headers:h}=this.options;return{target:o,ws:e,changeOrigin:r,secure:n,followRedirects:s,autoRewrite:i,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:g,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=$.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||"/",i=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:",i),console.log("[AutoProxyCookie] Headers:",JSON.stringify(e.headers,null,2)),this.isIgnoredPath(i)){console.log("[AutoProxyCookie] Path ignored, passing to next middleware"),n();return}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);let a=Object.keys(this.options.proxyMap||{}),l=this.options.proxyPaths||[],h=[...a,...l].some(p=>i.startsWith(p));if(console.log("[AutoProxyCookie] Path matches proxy rules:",h),this.proxyServer){let p=this.getProxyUrl(e);console.log(`[AutoProxyCookie] Proxying ${e.method} ${i} -> ${p}`);let d=this.createProxyOptions(p);try{console.log("[AutoProxyCookie] Calling proxyServer.web..."),this.proxyServer.web(e,r,d),console.log("[AutoProxyCookie] proxyServer.web called successfully")}catch(c){console.error("[AutoProxyCookie] Proxy web error:",c.message),n(c)}}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 i=this.getProxyUrl(e);this.proxyServer?.ws(e,r,n,{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 to(t){return new m(t)}function V(t,o){return o.some(e=>t.startsWith(e))}function U(t,o){return o.some(e=>t.startsWith(e))}function L(t,o,e){for(let[r,n]of Object.entries(o))if(t.startsWith(r))return n;return e}function no(t){let{cookieFile:o,target:e,debug:r=!1,proxyMap:n={},proxyPaths:s=[],ignorePaths:i=[]}=t,a=new y({cookieFile:o},r),l=a.readCookie(),g=[...Object.keys(n),...s];return{name:"vite-middleware-proxy",apply:"serve",configureServer(h){let d=I("http-proxy").createProxyServer({});r&&console.log("[ViteMiddlewareProxy] Watching cookie file:",o),h.middlewares.use((c,f,R)=>{let k=new URL(c.url||"/","http://localhost").pathname;if(V(k,i)){r&&console.log("[ViteMiddlewareProxy] Ignoring:",k),R();return}if(!U(k,g)){R();return}let b=L(k,n,e);r&&console.log("[ViteMiddlewareProxy] Proxying:",c.method,k,"->",b),l=a.readCookie(),l&&(r&&console.log("[ViteMiddlewareProxy] Injecting cookie:",`(length: ${l.length})`),c.headers.cookie=l,c.headers.Cookie=l),d.web(c,f,{target:b,changeOrigin:!0,secure:!1,ignorePath:!1})}),d.on("error",(c,f)=>{console.error("[ViteMiddlewareProxy] Proxy error:",c.message,"for",f.url)})}}}import*as w from"path";function F(t,o={}){let{getCookie:e,debug:r=!1,headers:n={},ws:s=!1,changeOrigin:i=!0,secure:a=!1,onError:l}=o;return{ws:s,target:t,changeOrigin:i,secure:a,headers:n,onProxyReq:(h,p)=>{let d=e?e():"";if(d&&C(h,d),r){let c=p.url||"/";console.log("[Proxy Request]",c,p.method,d?"(with cookie)":"(no cookie)")}},onError:l||(h=>{console.error(`
|
|
3
|
-
[Proxy Error]`,h.message)})}}function ho(
|
|
4
|
-
[Proxy Error]`,h.message)}};
|
|
1
|
+
var W=(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 M from"http";import*as D from"fs";import*as F from"path";import $ from"http-proxy";import*as d from"fs";import*as x from"path";var k=class{constructor(o,e=!1){this.options={encoding:"utf-8",...o},this.debug=e}readCookie(){try{let o=x.resolve(this.options.cookieFile);if(this.debug&&(console.log("[CookieReader] Resolved cookie file path:",o),console.log("[CookieReader] File exists:",d.existsSync(o))),d.existsSync(o)){let e=d.readFileSync(o,this.options.encoding||"utf-8");this.debug&&console.log("[CookieReader] File content length:",e.length);let s=e.split(`
|
|
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]`,h.message)})}}function ho(i,o={}){let{watch:e="auto",debug:r=!0,productionEnvs:n=[],isDev:s}=o,t=new k({cookieFile:R.resolve(i)},r),a;return s!==void 0?(a=s,r&&console.log(`[CookieFile] isDev=${s}, ${a?"enabling":"disabling"} watch`)):a=O(e,n,r,"[CookieFile]"),a?P(R.resolve(i),l=>{r&&console.log("[CookieFile] Updated:",l?"(has cookie)":"(empty)")},l=>{console.error("[CookieFile] Watch error:",l.message)}):r&&console.log("[CookieFile] File watch disabled"),()=>t.readCookie()}function po(i){let{target:o,ignorePaths:e=[],includePaths:r=[],additionalProxies:n={},getCookie:s,debug:t,headers:a,useCookie:l=!0}=i,g={};if(r.length>0)for(let p of r)g[p]=I(o,{getCookie:s,debug:t,headers:a,useCookie:l});else{let p={ws:!1,target:o,changeOrigin:!0,secure:!1,headers:a,onProxyReq:(h,y)=>{let u=y.url||"/";if(!e.some(c=>u.startsWith(c)))if(l){let c=s?s():"";c&&C(h,c),t&&console.log("[Proxy Request]",u,y.method,c?"(with cookie)":"(no cookie)")}else t&&console.log("[Proxy Request]",u,y.method,"(useCookie is false, skipping cookie injection)")},onError:h=>{console.error(`
|
|
4
|
+
[Proxy Error]`,h.message)}};g["/"]=p}for(let[p,h]of Object.entries(n))g[p]=I(h,{getCookie:s,debug:t,headers:a,useCookie:l});return g}export{w as AutoProxyCookie,k as CookieReader,m as CookieWatcher,po as createAutoProxyConfig,io as createAutoProxyCookie,T as createCookieGetter,ho as createFileCookieGetter,I as createVueProxyConfig,V as detectProductionEnvironment,S as isProductionValue,O as shouldEnableWatch,ao as viteMiddlewareProxy,P as watchCookieFile};
|
package/dist/index.mjs
CHANGED
|
@@ -339,11 +339,14 @@ var AutoProxyCookie = class {
|
|
|
339
339
|
this.handleOnProxyReq = (proxyReq, req, res, _options) => {
|
|
340
340
|
console.log("[AutoProxyCookie] === handleOnProxyReq START ===");
|
|
341
341
|
console.log("[AutoProxyCookie] Request URL:", req.method, req.url);
|
|
342
|
+
console.log("[AutoProxyCookie] useCookie:", this.options.useCookie);
|
|
342
343
|
console.log("[AutoProxyCookie] Current cookie:", this.currentCookie ? `(length: ${this.currentCookie.length})` : "(empty)");
|
|
343
|
-
if (this.currentCookie) {
|
|
344
|
+
if (this.options.useCookie && this.currentCookie) {
|
|
344
345
|
console.log("[AutoProxyCookie] Applying cookie header...");
|
|
345
346
|
applyDevCookieHeader(proxyReq, this.currentCookie);
|
|
346
347
|
console.log("[AutoProxyCookie] Cookie header applied successfully");
|
|
348
|
+
} else if (!this.options.useCookie) {
|
|
349
|
+
console.log("[AutoProxyCookie] useCookie is false, skipping cookie injection");
|
|
347
350
|
} else {
|
|
348
351
|
console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!");
|
|
349
352
|
}
|
|
@@ -465,6 +468,7 @@ var AutoProxyCookie = class {
|
|
|
465
468
|
cookieDomainRewrite: "*",
|
|
466
469
|
cookiePathRewrite: false,
|
|
467
470
|
headers: {},
|
|
471
|
+
useCookie: true,
|
|
468
472
|
...mergedOptions
|
|
469
473
|
};
|
|
470
474
|
this.cookieReader = new CookieReader({ cookieFile: options.cookieFile }, options.debug ?? false);
|
|
@@ -602,16 +606,21 @@ var AutoProxyCookie = class {
|
|
|
602
606
|
console.log("[AutoProxyCookie] Method:", req.method);
|
|
603
607
|
console.log("[AutoProxyCookie] Full URL:", fullUrl);
|
|
604
608
|
console.log("[AutoProxyCookie] Pathname:", pathname);
|
|
609
|
+
console.log("[AutoProxyCookie] useCookie:", this.options.useCookie);
|
|
605
610
|
console.log("[AutoProxyCookie] Headers:", JSON.stringify(req.headers, null, 2));
|
|
606
611
|
if (this.isIgnoredPath(pathname)) {
|
|
607
612
|
console.log("[AutoProxyCookie] Path ignored, passing to next middleware");
|
|
608
613
|
next();
|
|
609
614
|
return;
|
|
610
615
|
}
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
616
|
+
if (this.options.useCookie) {
|
|
617
|
+
this.currentCookie = this.cookieReader.readCookie();
|
|
618
|
+
console.log("[AutoProxyCookie] Current cookie:", this.currentCookie ? `(length: ${this.currentCookie.length})` : "(empty)");
|
|
619
|
+
if (this.currentCookie) {
|
|
620
|
+
console.log("[AutoProxyCookie] Cookie preview:", this.currentCookie);
|
|
621
|
+
}
|
|
622
|
+
} else {
|
|
623
|
+
console.log("[AutoProxyCookie] useCookie is false, skipping cookie reading");
|
|
615
624
|
}
|
|
616
625
|
const proxyMapKeys = Object.keys(this.options.proxyMap || {});
|
|
617
626
|
const proxyPaths = this.options.proxyPaths || [];
|
|
@@ -737,12 +746,16 @@ function viteMiddlewareProxy(options) {
|
|
|
737
746
|
cookieFile,
|
|
738
747
|
target,
|
|
739
748
|
debug = false,
|
|
749
|
+
useCookie = true,
|
|
740
750
|
proxyMap = {},
|
|
741
751
|
proxyPaths = [],
|
|
742
752
|
ignorePaths = []
|
|
743
753
|
} = options;
|
|
744
754
|
const cookieReader = new CookieReader({ cookieFile }, debug);
|
|
745
|
-
let currentCookie =
|
|
755
|
+
let currentCookie = "";
|
|
756
|
+
if (useCookie) {
|
|
757
|
+
currentCookie = cookieReader.readCookie();
|
|
758
|
+
}
|
|
746
759
|
const allProxyPrefixes = [
|
|
747
760
|
...Object.keys(proxyMap),
|
|
748
761
|
...proxyPaths
|
|
@@ -753,7 +766,7 @@ function viteMiddlewareProxy(options) {
|
|
|
753
766
|
configureServer(server) {
|
|
754
767
|
const httpProxy2 = __require("http-proxy");
|
|
755
768
|
const proxyServer = httpProxy2.createProxyServer({});
|
|
756
|
-
if (debug) {
|
|
769
|
+
if (useCookie && debug) {
|
|
757
770
|
console.log("[ViteMiddlewareProxy] Watching cookie file:", cookieFile);
|
|
758
771
|
}
|
|
759
772
|
server.middlewares.use((req, res, next) => {
|
|
@@ -773,13 +786,19 @@ function viteMiddlewareProxy(options) {
|
|
|
773
786
|
if (debug) {
|
|
774
787
|
console.log("[ViteMiddlewareProxy] Proxying:", req.method, pathname, "->", proxyTarget);
|
|
775
788
|
}
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
if (
|
|
779
|
-
|
|
789
|
+
if (useCookie) {
|
|
790
|
+
currentCookie = cookieReader.readCookie();
|
|
791
|
+
if (currentCookie) {
|
|
792
|
+
if (debug) {
|
|
793
|
+
console.log("[ViteMiddlewareProxy] Injecting cookie:", `(length: ${currentCookie.length})`);
|
|
794
|
+
}
|
|
795
|
+
req.headers["cookie"] = currentCookie;
|
|
796
|
+
req.headers["Cookie"] = currentCookie;
|
|
797
|
+
} else if (debug) {
|
|
798
|
+
console.log("[ViteMiddlewareProxy] Cookie file is empty");
|
|
780
799
|
}
|
|
781
|
-
|
|
782
|
-
|
|
800
|
+
} else if (debug) {
|
|
801
|
+
console.log("[ViteMiddlewareProxy] useCookie is false, skipping cookie injection");
|
|
783
802
|
}
|
|
784
803
|
proxyServer.web(req, res, {
|
|
785
804
|
target: proxyTarget,
|
|
@@ -801,6 +820,7 @@ function createVueProxyConfig(target, options = {}) {
|
|
|
801
820
|
const {
|
|
802
821
|
getCookie,
|
|
803
822
|
debug = false,
|
|
823
|
+
useCookie = true,
|
|
804
824
|
headers = {},
|
|
805
825
|
ws = false,
|
|
806
826
|
changeOrigin = true,
|
|
@@ -814,13 +834,17 @@ function createVueProxyConfig(target, options = {}) {
|
|
|
814
834
|
secure,
|
|
815
835
|
headers,
|
|
816
836
|
onProxyReq: (proxyReq, req) => {
|
|
817
|
-
const
|
|
818
|
-
if (
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
837
|
+
const reqPath = req.url || "/";
|
|
838
|
+
if (useCookie) {
|
|
839
|
+
const cookie = getCookie ? getCookie() : "";
|
|
840
|
+
if (cookie) {
|
|
841
|
+
applyDevCookieHeader(proxyReq, cookie);
|
|
842
|
+
}
|
|
843
|
+
if (debug) {
|
|
844
|
+
console.log("[Proxy Request]", reqPath, req.method, cookie ? "(with cookie)" : "(no cookie)");
|
|
845
|
+
}
|
|
846
|
+
} else if (debug) {
|
|
847
|
+
console.log("[Proxy Request]", reqPath, req.method, "(useCookie is false, skipping cookie injection)");
|
|
824
848
|
}
|
|
825
849
|
},
|
|
826
850
|
onError: customOnError || ((err) => {
|
|
@@ -864,11 +888,11 @@ function createFileCookieGetter(cookieFile, options = {}) {
|
|
|
864
888
|
return () => reader.readCookie();
|
|
865
889
|
}
|
|
866
890
|
function createAutoProxyConfig(options) {
|
|
867
|
-
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers } = options;
|
|
891
|
+
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers, useCookie = true } = options;
|
|
868
892
|
const result = {};
|
|
869
893
|
if (includePaths.length > 0) {
|
|
870
894
|
for (const proxyPath of includePaths) {
|
|
871
|
-
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers });
|
|
895
|
+
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers, useCookie });
|
|
872
896
|
}
|
|
873
897
|
} else {
|
|
874
898
|
const defaultProxy = {
|
|
@@ -882,12 +906,16 @@ function createAutoProxyConfig(options) {
|
|
|
882
906
|
if (ignorePaths.some((p) => reqPath.startsWith(p))) {
|
|
883
907
|
return;
|
|
884
908
|
}
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
909
|
+
if (useCookie) {
|
|
910
|
+
const cookie = getCookie ? getCookie() : "";
|
|
911
|
+
if (cookie) {
|
|
912
|
+
applyDevCookieHeader(proxyReq, cookie);
|
|
913
|
+
}
|
|
914
|
+
if (debug) {
|
|
915
|
+
console.log("[Proxy Request]", reqPath, req.method, cookie ? "(with cookie)" : "(no cookie)");
|
|
916
|
+
}
|
|
917
|
+
} else if (debug) {
|
|
918
|
+
console.log("[Proxy Request]", reqPath, req.method, "(useCookie is false, skipping cookie injection)");
|
|
891
919
|
}
|
|
892
920
|
},
|
|
893
921
|
onError: (err) => {
|
|
@@ -897,7 +925,7 @@ function createAutoProxyConfig(options) {
|
|
|
897
925
|
result["/"] = defaultProxy;
|
|
898
926
|
}
|
|
899
927
|
for (const [proxyPath, proxyTarget] of Object.entries(additionalProxies)) {
|
|
900
|
-
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers });
|
|
928
|
+
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers, useCookie });
|
|
901
929
|
}
|
|
902
930
|
return result;
|
|
903
931
|
}
|