@gylautorun/dev-proxy-cookie 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,847 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ AutoProxyCookie: () => AutoProxyCookie,
34
+ CookieReader: () => CookieReader,
35
+ CookieWatcher: () => CookieWatcher,
36
+ createAutoProxyConfig: () => createAutoProxyConfig,
37
+ createAutoProxyCookie: () => createAutoProxyCookie,
38
+ createCookieGetter: () => createCookieGetter,
39
+ createDevProxyCookie: () => createDevProxyCookie,
40
+ createFileCookieGetter: () => createFileCookieGetter,
41
+ createVueProxyConfig: () => createVueProxyConfig,
42
+ detectProductionEnvironment: () => detectProductionEnvironment,
43
+ getViteMajorVersion: () => getViteMajorVersion,
44
+ getViteVersion: () => getViteVersion,
45
+ isProductionValue: () => isProductionValue,
46
+ shouldEnableWatch: () => shouldEnableWatch,
47
+ viteAutoProxyCookie: () => viteAutoProxyCookie,
48
+ viteDevProxyCookie: () => viteDevProxyCookie,
49
+ watchCookieFile: () => watchCookieFile
50
+ });
51
+ module.exports = __toCommonJS(index_exports);
52
+
53
+ // src/proxy/core.ts
54
+ var http = __toESM(require("http"));
55
+ var fs2 = __toESM(require("fs"));
56
+ var path3 = __toESM(require("path"));
57
+ var import_http_proxy = __toESM(require("http-proxy"));
58
+
59
+ // src/utils/cookie-reader.ts
60
+ var fs = __toESM(require("fs"));
61
+ var path = __toESM(require("path"));
62
+ var CookieReader = class {
63
+ constructor(options) {
64
+ this.options = {
65
+ encoding: "utf-8",
66
+ ...options
67
+ };
68
+ }
69
+ readCookie() {
70
+ try {
71
+ const filePath = path.resolve(this.options.cookieFile);
72
+ if (fs.existsSync(filePath)) {
73
+ const content = fs.readFileSync(filePath, this.options.encoding || "utf-8");
74
+ const lines = content.split("\n");
75
+ const cookieLines = lines.map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
76
+ return cookieLines.join("; ");
77
+ }
78
+ return "";
79
+ } catch {
80
+ return "";
81
+ }
82
+ }
83
+ ensureCookieFile() {
84
+ const filePath = path.resolve(this.options.cookieFile);
85
+ const dir = path.dirname(filePath);
86
+ if (!fs.existsSync(dir)) {
87
+ fs.mkdirSync(dir, { recursive: true });
88
+ }
89
+ if (!fs.existsSync(filePath)) {
90
+ fs.writeFileSync(filePath, "");
91
+ }
92
+ }
93
+ };
94
+ function createCookieGetter(cookieFile) {
95
+ const reader = new CookieReader({ cookieFile });
96
+ return () => reader.readCookie();
97
+ }
98
+
99
+ // src/utils/cookie-watcher.ts
100
+ var path2 = __toESM(require("path"));
101
+ var import_chokidar = __toESM(require("chokidar"));
102
+ var CookieWatcher = class {
103
+ constructor(options) {
104
+ this.watcher = null;
105
+ this.lastContent = "";
106
+ this.handleChange = () => {
107
+ const newContent = this.cookieReader.readCookie();
108
+ if (newContent !== this.lastContent) {
109
+ this.lastContent = newContent;
110
+ this.options.onCookieChange(newContent);
111
+ console.log(`[CookieWatcher] Cookie updated from file: ${this.options.cookieFile}`);
112
+ }
113
+ };
114
+ this.options = {
115
+ autoCreateFile: true,
116
+ ...options
117
+ };
118
+ this.cookieReader = new CookieReader({ cookieFile: options.cookieFile });
119
+ }
120
+ start() {
121
+ if (this.options.autoCreateFile) {
122
+ this.cookieReader.ensureCookieFile();
123
+ }
124
+ const watchPath = path2.resolve(this.options.cookieFile);
125
+ this.lastContent = this.cookieReader.readCookie();
126
+ console.log(`[CookieWatcher] Started watching: ${watchPath}`);
127
+ try {
128
+ this.watcher = import_chokidar.default.watch(watchPath, {
129
+ persistent: true,
130
+ ignoreInitial: true,
131
+ awaitWriteFinish: {
132
+ stabilityThreshold: 100,
133
+ pollInterval: 50
134
+ }
135
+ });
136
+ this.watcher.on("change", this.handleChange);
137
+ this.watcher.on("add", this.handleChange);
138
+ this.watcher.on("error", (error) => {
139
+ this.options.onError?.(error);
140
+ });
141
+ } catch (error) {
142
+ this.options.onError?.(error);
143
+ }
144
+ }
145
+ stop() {
146
+ if (this.watcher) {
147
+ this.watcher.close();
148
+ this.watcher = null;
149
+ console.log(`[CookieWatcher] Stopped watching: ${this.options.cookieFile}`);
150
+ }
151
+ }
152
+ getCurrentCookie() {
153
+ return this.lastContent;
154
+ }
155
+ };
156
+ function watchCookieFile(cookieFile, onCookieChange, onError) {
157
+ const watcher = new CookieWatcher({
158
+ cookieFile,
159
+ onCookieChange,
160
+ onError
161
+ });
162
+ watcher.start();
163
+ return watcher;
164
+ }
165
+
166
+ // src/utils/env-detector.ts
167
+ function isProductionValue(value) {
168
+ const productionValues = [
169
+ "production",
170
+ // 生产环境
171
+ "prod",
172
+ // 生产环境
173
+ "prd",
174
+ // 生产环境
175
+ "release",
176
+ // 发布环境
177
+ "staging",
178
+ // 预发布环境
179
+ "uat"
180
+ // 预发布环境
181
+ ];
182
+ return productionValues.includes(value.toLowerCase().trim());
183
+ }
184
+ function detectProductionEnvironment(customEnvs = [], debug = false, loggerPrefix = "[env-detector]") {
185
+ const env = process.env;
186
+ if (customEnvs.length > 0) {
187
+ for (const envName of customEnvs) {
188
+ const envValue = env[envName];
189
+ if (envValue && isProductionValue(envValue)) {
190
+ if (debug) {
191
+ console.log(`${loggerPrefix} Detected production via custom env: ${envName}=${envValue}`);
192
+ }
193
+ return true;
194
+ }
195
+ }
196
+ }
197
+ const commonEnvNames = [
198
+ "NODE_ENV",
199
+ "BUILD_MODE",
200
+ "VUE_APP_ENV",
201
+ "VITE_NODE_ENV",
202
+ "WEBPACK_MODE",
203
+ "CI_ENV",
204
+ "APP_ENV",
205
+ "ENV",
206
+ "DEPLOY_ENV",
207
+ "RUN_MODE"
208
+ ];
209
+ for (const envName of commonEnvNames) {
210
+ const envValue = env[envName];
211
+ if (envValue && isProductionValue(envValue)) {
212
+ if (debug) {
213
+ console.log(`${loggerPrefix} Detected production via env: ${envName}=${envValue}`);
214
+ }
215
+ return true;
216
+ }
217
+ }
218
+ if (env.CI === "true" || env.CI === "1" || env.CI === "yes") {
219
+ if (debug) {
220
+ console.log(`${loggerPrefix} Detected production via CI env`);
221
+ }
222
+ return true;
223
+ }
224
+ if (env.npm_lifecycle_event) {
225
+ const lifecycleEvent = env.npm_lifecycle_event.toLowerCase();
226
+ if (lifecycleEvent.includes("build") || lifecycleEvent.includes("prod") || lifecycleEvent.includes("prd") || lifecycleEvent.includes("release")) {
227
+ if (debug) {
228
+ console.log(`${loggerPrefix} Detected production via lifecycle event: ${env.npm_lifecycle_event}`);
229
+ }
230
+ return true;
231
+ }
232
+ }
233
+ const processArgs = process.argv.join("").toLowerCase();
234
+ if (processArgs.includes("build") || processArgs.includes("production") || processArgs.includes("--mode=production") || processArgs.includes("--prod") || processArgs.includes("--release")) {
235
+ if (debug) {
236
+ console.log(`${loggerPrefix} Detected production via process arguments`);
237
+ }
238
+ return true;
239
+ }
240
+ return false;
241
+ }
242
+ function shouldEnableWatch(watch, customEnvs = [], debug = false, loggerPrefix = "[env-detector]") {
243
+ if (typeof watch === "boolean") {
244
+ if (debug && !watch) {
245
+ console.log(`${loggerPrefix} Watch disabled by user setting`);
246
+ }
247
+ return watch;
248
+ }
249
+ const isProduction = detectProductionEnvironment(customEnvs, debug, loggerPrefix);
250
+ if (isProduction) {
251
+ if (debug) {
252
+ console.log(`${loggerPrefix} Auto-detected production mode - disabling watch`);
253
+ }
254
+ return false;
255
+ }
256
+ if (debug) {
257
+ console.log(`${loggerPrefix} Auto-detected development mode - enabling watch`);
258
+ }
259
+ return true;
260
+ }
261
+
262
+ // src/proxy/apply-dev-cookie-header.ts
263
+ function applyDevCookieHeader(proxyReq, cookie) {
264
+ if (!cookie) return;
265
+ proxyReq.removeHeader("cookie");
266
+ proxyReq.removeHeader("Cookie");
267
+ proxyReq.setHeader("Cookie", cookie);
268
+ }
269
+
270
+ // src/proxy/core.ts
271
+ var AutoProxyCookie = class {
272
+ constructor(options) {
273
+ this.currentCookie = "";
274
+ this.server = null;
275
+ this.proxyServer = null;
276
+ this.watcher = null;
277
+ this.handleCookieChange = (newCookie) => {
278
+ if (newCookie !== this.currentCookie) {
279
+ this.currentCookie = newCookie;
280
+ this.log("info", "[AutoProxyCookie] Cookie updated:", newCookie ? "(has cookie)" : "(empty)");
281
+ if (this.options.autoRestart && this.options.restartMarkerFile) {
282
+ const markerPath = path3.resolve(this.options.restartMarkerFile);
283
+ fs2.writeFileSync(markerPath, JSON.stringify({
284
+ timestamp: Date.now(),
285
+ cookie: newCookie
286
+ }, null, 2));
287
+ this.log("info", "[AutoProxyCookie] Restart marker written to:", markerPath);
288
+ this.log("info", "[AutoProxyCookie] Please restart the dev server for changes to take effect");
289
+ }
290
+ }
291
+ };
292
+ this.handleOnProxyReq = (proxyReq, req, res, _options) => {
293
+ if (this.currentCookie) {
294
+ applyDevCookieHeader(proxyReq, this.currentCookie);
295
+ }
296
+ this.log("debug", "[AutoProxyCookie] Proxy Request:", req.method, req.url);
297
+ if (this.options.hooks.onProxyReq) {
298
+ try {
299
+ this.options.hooks.onProxyReq(proxyReq, req, res);
300
+ } catch (err) {
301
+ this.log("error", "[AutoProxyCookie] onProxyReq hook error:", err.message);
302
+ }
303
+ }
304
+ };
305
+ this.handleOnProxyRes = (proxyRes, req, res) => {
306
+ const allowedHeaders = [
307
+ "Content-Type",
308
+ "Content-Length",
309
+ "Authorization",
310
+ "Set-Cookie",
311
+ "X-Requested-With",
312
+ "Access-Control-Allow-Origin",
313
+ "Access-Control-Allow-Credentials"
314
+ ];
315
+ res.setHeader("Access-Control-Allow-Origin", "*");
316
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
317
+ res.setHeader("Access-Control-Allow-Headers", allowedHeaders.join(","));
318
+ res.setHeader("Access-Control-Allow-Credentials", "true");
319
+ this.log("debug", "[AutoProxyCookie] Proxy Response:", req.url, proxyRes.statusCode);
320
+ if (this.options.hooks.onProxyRes) {
321
+ try {
322
+ this.options.hooks.onProxyRes(proxyRes, req, res);
323
+ } catch (err) {
324
+ this.log("error", "[AutoProxyCookie] onProxyRes hook error:", err.message);
325
+ }
326
+ }
327
+ };
328
+ this.handleOnError = (err, req, res) => {
329
+ this.log("error", "[AutoProxyCookie] Proxy Error:", err.message);
330
+ this.log("error", "[AutoProxyCookie] URL:", req.url);
331
+ if (res instanceof http.ServerResponse && !res.headersSent) {
332
+ res.writeHead(503, { "Content-Type": "application/json; charset=utf-8" });
333
+ res.end(JSON.stringify({
334
+ success: false,
335
+ message: "\u670D\u52A1\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",
336
+ error: err.message
337
+ }));
338
+ }
339
+ if (this.options.hooks.onError) {
340
+ try {
341
+ this.options.hooks.onError(err, req, res);
342
+ } catch (hookErr) {
343
+ this.log("error", "[AutoProxyCookie] onError hook error:", hookErr.message);
344
+ }
345
+ }
346
+ };
347
+ this.handleOnWsError = (err, req, socket) => {
348
+ this.log("error", "[AutoProxyCookie] WebSocket Proxy Error:", err.message);
349
+ this.log("error", "[AutoProxyCookie] WebSocket URL:", req.url);
350
+ if (socket) {
351
+ socket.close();
352
+ }
353
+ if (this.options.hooks.onWsError) {
354
+ try {
355
+ this.options.hooks.onWsError(err, req, socket);
356
+ } catch (hookErr) {
357
+ this.log("error", "[AutoProxyCookie] onWsError hook error:", hookErr.message);
358
+ }
359
+ }
360
+ };
361
+ const defaultHooks = {
362
+ onProxyReq: () => {
363
+ },
364
+ onProxyRes: () => {
365
+ },
366
+ onError: () => {
367
+ },
368
+ onWsError: () => {
369
+ }
370
+ };
371
+ const mergedOptions = {
372
+ ...options,
373
+ hooks: {
374
+ ...defaultHooks,
375
+ ...options.hooks || {}
376
+ }
377
+ };
378
+ this.options = {
379
+ debug: false,
380
+ autoRestart: false,
381
+ restartMarkerFile: ".cookie-restart-marker",
382
+ proxyMap: {},
383
+ ignorePaths: [],
384
+ ws: true,
385
+ changeOrigin: true,
386
+ secure: false,
387
+ followRedirects: true,
388
+ autoRewrite: false,
389
+ protocolRewrite: void 0,
390
+ logLevel: "info",
391
+ cookieDomainRewrite: "*",
392
+ cookiePathRewrite: false,
393
+ headers: {},
394
+ ...mergedOptions
395
+ };
396
+ this.cookieReader = new CookieReader({ cookieFile: options.cookieFile });
397
+ }
398
+ getProxyUrl(req) {
399
+ const pathname = req.url?.split("?")[0] || "/";
400
+ const proxyMap = this.options.proxyMap || {};
401
+ for (const [prefix, target] of Object.entries(proxyMap)) {
402
+ if (pathname.startsWith(prefix)) {
403
+ return target;
404
+ }
405
+ }
406
+ return this.options.target;
407
+ }
408
+ isIgnoredPath(pathname) {
409
+ const ignorePaths = this.options.ignorePaths || [];
410
+ return ignorePaths.some(
411
+ (ignored) => pathname.startsWith(ignored)
412
+ );
413
+ }
414
+ log(level, ...args) {
415
+ const levels = { debug: 0, info: 1, warn: 2, error: 3 };
416
+ const currentLevel = levels[this.options.logLevel || "info"];
417
+ const msgLevel = levels[level];
418
+ if (msgLevel >= currentLevel) {
419
+ if (level === "error") {
420
+ console.error(...args);
421
+ } else if (level === "warn") {
422
+ console.warn(...args);
423
+ } else {
424
+ console.log(...args);
425
+ }
426
+ }
427
+ }
428
+ createProxyOptions(target) {
429
+ const {
430
+ ws,
431
+ changeOrigin,
432
+ secure,
433
+ followRedirects,
434
+ autoRewrite,
435
+ protocolRewrite,
436
+ cookieDomainRewrite,
437
+ cookiePathRewrite,
438
+ headers
439
+ } = this.options;
440
+ return {
441
+ target,
442
+ ws,
443
+ changeOrigin,
444
+ secure,
445
+ followRedirects,
446
+ autoRewrite,
447
+ protocolRewrite,
448
+ cookieDomainRewrite,
449
+ cookiePathRewrite,
450
+ headers: {
451
+ ...headers
452
+ },
453
+ ignorePath: false
454
+ };
455
+ }
456
+ async setup(server) {
457
+ this.server = server;
458
+ this.currentCookie = this.cookieReader.readCookie();
459
+ try {
460
+ const baseOptions = {
461
+ target: this.options.target,
462
+ changeOrigin: this.options.changeOrigin,
463
+ secure: this.options.secure,
464
+ followRedirects: this.options.followRedirects,
465
+ autoRewrite: this.options.autoRewrite,
466
+ protocolRewrite: this.options.protocolRewrite,
467
+ cookieDomainRewrite: this.options.cookieDomainRewrite,
468
+ cookiePathRewrite: this.options.cookiePathRewrite,
469
+ ws: this.options.ws
470
+ };
471
+ this.proxyServer = import_http_proxy.default.createProxyServer(baseOptions);
472
+ this.proxyServer.on("proxyReq", this.handleOnProxyReq);
473
+ this.proxyServer.on("proxyRes", this.handleOnProxyRes);
474
+ this.proxyServer.on("error", this.handleOnError);
475
+ if (this.options.ws) {
476
+ this.proxyServer.on("wsError", this.handleOnWsError);
477
+ }
478
+ this.log("info", "[AutoProxyCookie] Proxy server created with WebSocket support");
479
+ } catch (err) {
480
+ this.log("warn", "[AutoProxyCookie] http-proxy create failed, using basic mode:", err.message);
481
+ }
482
+ server.middlewares.use((req, res, next) => {
483
+ const pathname = new URL(req.url || "/", "http://localhost").pathname;
484
+ if (this.isIgnoredPath(pathname)) {
485
+ next();
486
+ return;
487
+ }
488
+ this.currentCookie = this.cookieReader.readCookie();
489
+ if (this.proxyServer) {
490
+ const target = this.getProxyUrl(req);
491
+ if (this.options.debug || this.options.logLevel === "debug") {
492
+ this.log("info", `[AutoProxyCookie] ${pathname} -> ${target}`);
493
+ }
494
+ const proxyOptions = this.createProxyOptions(target);
495
+ try {
496
+ this.proxyServer.web(req, res, proxyOptions);
497
+ } catch (err) {
498
+ this.log("error", "[AutoProxyCookie] Proxy web error:", err.message);
499
+ next(err);
500
+ }
501
+ } else {
502
+ next();
503
+ }
504
+ });
505
+ if (this.options.ws && this.server.httpServer && this.proxyServer) {
506
+ this.server.httpServer.on("upgrade", (req, socket, head) => {
507
+ const pathname = new URL(req.url || "/", "http://localhost").pathname;
508
+ if (this.isIgnoredPath(pathname)) {
509
+ socket.destroy();
510
+ return;
511
+ }
512
+ const target = this.getProxyUrl(req);
513
+ this.proxyServer?.ws(req, socket, head, {
514
+ target,
515
+ ws: true,
516
+ changeOrigin: this.options.changeOrigin,
517
+ secure: this.options.secure
518
+ });
519
+ });
520
+ this.log("info", "[AutoProxyCookie] WebSocket upgrade handler registered");
521
+ }
522
+ this.startFileWatch();
523
+ this.log("info", "[AutoProxyCookie] Auto-proxy middleware enabled");
524
+ this.log("info", "[AutoProxyCookie] Target:", this.options.target);
525
+ this.log("info", "[AutoProxyCookie] Cookie file:", this.options.cookieFile);
526
+ if (this.options.autoRestart) {
527
+ this.log("info", "[AutoProxyCookie] Auto-restart enabled");
528
+ }
529
+ if (this.options.ws) {
530
+ this.log("info", "[AutoProxyCookie] WebSocket support enabled");
531
+ }
532
+ }
533
+ startFileWatch() {
534
+ let shouldWatch;
535
+ if (this.options.isDev !== void 0) {
536
+ shouldWatch = this.options.isDev;
537
+ if (this.options.debug) {
538
+ console.log(`[AutoProxyCookie] isDev=${this.options.isDev}, ${shouldWatch ? "enabling" : "disabling"} watch`);
539
+ }
540
+ } else {
541
+ shouldWatch = true;
542
+ if (this.options.debug) {
543
+ console.log("[AutoProxyCookie] Default behavior: enabling watch (dev mode)");
544
+ }
545
+ }
546
+ if (shouldWatch) {
547
+ this.watcher = watchCookieFile(
548
+ this.options.cookieFile,
549
+ this.handleCookieChange,
550
+ (error) => {
551
+ this.log("error", "[AutoProxyCookie] File watch error:", error.message);
552
+ }
553
+ );
554
+ } else if (this.options.debug) {
555
+ console.log("[AutoProxyCookie] File watch disabled");
556
+ }
557
+ }
558
+ stop() {
559
+ if (this.watcher) {
560
+ this.watcher.stop();
561
+ this.watcher = null;
562
+ }
563
+ if (this.proxyServer) {
564
+ this.proxyServer.close();
565
+ this.proxyServer = null;
566
+ }
567
+ this.log("info", "[AutoProxyCookie] Stopped");
568
+ }
569
+ getCurrentCookie() {
570
+ return this.currentCookie;
571
+ }
572
+ };
573
+ function createAutoProxyCookie(options) {
574
+ return new AutoProxyCookie(options);
575
+ }
576
+
577
+ // src/proxy/vite-plugin.ts
578
+ function viteAutoProxyCookie(options) {
579
+ const {
580
+ name = "vite-auto-proxy-cookie",
581
+ isDev,
582
+ ...autoProxyOptions
583
+ } = options;
584
+ let autoProxy = null;
585
+ return {
586
+ name,
587
+ apply: "serve",
588
+ async configureServer(server) {
589
+ autoProxy = createAutoProxyCookie({
590
+ ...autoProxyOptions,
591
+ debug: options.debug ?? false,
592
+ autoRestart: options.autoRestart ?? true,
593
+ isDev
594
+ });
595
+ try {
596
+ await autoProxy.setup(server);
597
+ } catch (error) {
598
+ console.error("[vite-auto-proxy-cookie] Failed to setup proxy:", error);
599
+ if (options.debug) {
600
+ console.log("[vite-auto-proxy-cookie] Falling back to middleware mode");
601
+ }
602
+ }
603
+ },
604
+ closeBundle() {
605
+ autoProxy?.stop();
606
+ }
607
+ };
608
+ }
609
+
610
+ // src/proxy/vite-cookie-plugin.ts
611
+ function viteDevProxyCookie(options) {
612
+ const { cookieFile, debug = false, onCookieChange, watch = "auto", isDev } = options;
613
+ let watcher = null;
614
+ let currentCookie = "";
615
+ const cookieReader = new CookieReader({ cookieFile });
616
+ return {
617
+ name: "vite-dev-proxy-cookie",
618
+ apply: "serve",
619
+ configureServer(server) {
620
+ currentCookie = cookieReader.readCookie();
621
+ if (debug) {
622
+ console.log("[vite-dev-proxy-cookie] Initial cookie loaded");
623
+ }
624
+ const middlewares = server.middlewares || server._middlewares || server.app;
625
+ if (middlewares && typeof middlewares.use === "function") {
626
+ middlewares.use((req, _res, next) => {
627
+ if (currentCookie && req.url?.startsWith("/")) {
628
+ req.headers = req.headers || {};
629
+ req.headers["cookie"] = currentCookie;
630
+ }
631
+ next();
632
+ });
633
+ } else {
634
+ console.warn("[vite-dev-proxy-cookie] Could not access middleware stack, cookie injection disabled");
635
+ }
636
+ let shouldWatch;
637
+ if (isDev !== void 0) {
638
+ shouldWatch = isDev;
639
+ if (debug) {
640
+ console.log(`[vite-dev-proxy-cookie] isDev=${isDev}, ${shouldWatch ? "enabling" : "disabling"} watch`);
641
+ }
642
+ } else {
643
+ shouldWatch = shouldEnableWatch(watch, [], debug, "[vite-dev-proxy-cookie]");
644
+ }
645
+ if (shouldWatch) {
646
+ watcher = watchCookieFile(
647
+ cookieFile,
648
+ (newCookie) => {
649
+ currentCookie = newCookie;
650
+ onCookieChange?.(newCookie);
651
+ console.log("[vite-dev-proxy-cookie] Cookie changed, please restart server for full effect");
652
+ },
653
+ (error) => {
654
+ console.error("[vite-dev-proxy-cookie] Watch error:", error.message);
655
+ }
656
+ );
657
+ } else if (debug) {
658
+ console.log("[vite-dev-proxy-cookie] File watch disabled");
659
+ }
660
+ },
661
+ closeBundle() {
662
+ watcher?.stop();
663
+ }
664
+ };
665
+ }
666
+
667
+ // src/proxy/vue-proxy-config.ts
668
+ var path4 = __toESM(require("path"));
669
+ function createVueProxyConfig(target, options = {}) {
670
+ const {
671
+ getCookie,
672
+ debug = false,
673
+ headers = {},
674
+ ws = false,
675
+ changeOrigin = true,
676
+ secure = false,
677
+ onError: customOnError
678
+ } = options;
679
+ const config = {
680
+ ws,
681
+ target,
682
+ changeOrigin,
683
+ secure,
684
+ headers,
685
+ onProxyReq: (proxyReq, req) => {
686
+ const cookie = getCookie ? getCookie() : "";
687
+ if (cookie) {
688
+ applyDevCookieHeader(proxyReq, cookie);
689
+ }
690
+ if (debug) {
691
+ const reqPath = req.url || "/";
692
+ console.log("[Proxy Request]", reqPath, req.method, cookie ? "(with cookie)" : "(no cookie)");
693
+ }
694
+ },
695
+ onError: customOnError || ((err) => {
696
+ console.error("\n[Proxy Error]", err.message);
697
+ })
698
+ };
699
+ return config;
700
+ }
701
+ function createFileCookieGetter(cookieFile, options = {}) {
702
+ const {
703
+ watch = "auto",
704
+ debug = false,
705
+ productionEnvs = [],
706
+ isDev
707
+ } = options;
708
+ const reader = new CookieReader({ cookieFile: path4.resolve(cookieFile) });
709
+ let shouldWatch;
710
+ if (isDev !== void 0) {
711
+ shouldWatch = isDev;
712
+ if (debug) {
713
+ console.log(`[CookieFile] isDev=${isDev}, ${shouldWatch ? "enabling" : "disabling"} watch`);
714
+ }
715
+ } else {
716
+ shouldWatch = shouldEnableWatch(watch, productionEnvs, debug, "[CookieFile]");
717
+ }
718
+ if (shouldWatch) {
719
+ watchCookieFile(
720
+ path4.resolve(cookieFile),
721
+ (newCookie) => {
722
+ if (debug) {
723
+ console.log("[CookieFile] Updated:", newCookie ? "(has cookie)" : "(empty)");
724
+ }
725
+ },
726
+ (error) => {
727
+ console.error("[CookieFile] Watch error:", error.message);
728
+ }
729
+ );
730
+ } else if (debug) {
731
+ console.log("[CookieFile] File watch disabled");
732
+ }
733
+ return () => reader.readCookie();
734
+ }
735
+ function createAutoProxyConfig(options) {
736
+ const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers } = options;
737
+ const result = {};
738
+ if (includePaths.length > 0) {
739
+ for (const proxyPath of includePaths) {
740
+ result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers });
741
+ }
742
+ } else {
743
+ const defaultProxy = {
744
+ ws: false,
745
+ target,
746
+ changeOrigin: true,
747
+ secure: false,
748
+ headers,
749
+ onProxyReq: (proxyReq, req) => {
750
+ const reqPath = req.url || "/";
751
+ if (ignorePaths.some((p) => reqPath.startsWith(p))) {
752
+ return;
753
+ }
754
+ const cookie = getCookie ? getCookie() : "";
755
+ if (cookie) {
756
+ applyDevCookieHeader(proxyReq, cookie);
757
+ }
758
+ if (debug) {
759
+ console.log("[Proxy Request]", reqPath, req.method, cookie ? "(with cookie)" : "(no cookie)");
760
+ }
761
+ },
762
+ onError: (err) => {
763
+ console.error("\n[Proxy Error]", err.message);
764
+ }
765
+ };
766
+ result["/"] = defaultProxy;
767
+ }
768
+ for (const [proxyPath, proxyTarget] of Object.entries(additionalProxies)) {
769
+ result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers });
770
+ }
771
+ return result;
772
+ }
773
+
774
+ // src/proxy/vite-adapter.ts
775
+ var viteVersion = "";
776
+ var majorVersion = null;
777
+ function detectViteVersion() {
778
+ if (majorVersion !== null) {
779
+ return majorVersion;
780
+ }
781
+ try {
782
+ const pkg = require("vite/package.json");
783
+ viteVersion = pkg.version;
784
+ majorVersion = parseInt(viteVersion.split(".")[0], 10);
785
+ } catch {
786
+ majorVersion = 5;
787
+ }
788
+ return majorVersion;
789
+ }
790
+ function createDevProxyCookie(options) {
791
+ const {
792
+ mode = "auto",
793
+ watch = "auto",
794
+ isDev,
795
+ ...restOptions
796
+ } = options;
797
+ const version = detectViteVersion();
798
+ if (options.debug) {
799
+ console.log(`[dev-proxy-cookie] Detected Vite ${version}.x`);
800
+ }
801
+ if (mode === "cookie" || mode === "auto" && !options.target) {
802
+ return viteDevProxyCookie({
803
+ cookieFile: options.cookieFile,
804
+ debug: options.debug,
805
+ onCookieChange: options.onCookieChange,
806
+ watch,
807
+ isDev
808
+ });
809
+ }
810
+ const pluginOptions = {
811
+ cookieFile: options.cookieFile,
812
+ target: options.target,
813
+ debug: options.debug,
814
+ autoRestart: options.autoRestart ?? true,
815
+ restartMarkerFile: options.restartMarkerFile,
816
+ proxyMap: options.proxyMap,
817
+ ignorePaths: options.ignorePaths
818
+ };
819
+ return viteAutoProxyCookie(pluginOptions);
820
+ }
821
+ function getViteVersion() {
822
+ detectViteVersion();
823
+ return viteVersion;
824
+ }
825
+ function getViteMajorVersion() {
826
+ return detectViteVersion();
827
+ }
828
+ // Annotate the CommonJS export names for ESM import in node:
829
+ 0 && (module.exports = {
830
+ AutoProxyCookie,
831
+ CookieReader,
832
+ CookieWatcher,
833
+ createAutoProxyConfig,
834
+ createAutoProxyCookie,
835
+ createCookieGetter,
836
+ createDevProxyCookie,
837
+ createFileCookieGetter,
838
+ createVueProxyConfig,
839
+ detectProductionEnvironment,
840
+ getViteMajorVersion,
841
+ getViteVersion,
842
+ isProductionValue,
843
+ shouldEnableWatch,
844
+ viteAutoProxyCookie,
845
+ viteDevProxyCookie,
846
+ watchCookieFile
847
+ });