unplugin-https-reverse-proxy 1.0.0-beta.9 → 2.0.0

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/rspack.cjs CHANGED
@@ -3,22 +3,8 @@ var __create = Object.create;
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
6
  var __getProtoOf = Object.getPrototypeOf;
8
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
- var __spreadValues = (a, b) => {
12
- for (var prop in b || (b = {}))
13
- if (__hasOwnProp.call(b, prop))
14
- __defNormalProp(a, prop, b[prop]);
15
- if (__getOwnPropSymbols)
16
- for (var prop of __getOwnPropSymbols(b)) {
17
- if (__propIsEnum.call(b, prop))
18
- __defNormalProp(a, prop, b[prop]);
19
- }
20
- return a;
21
- };
22
8
  var __export = (target, all) => {
23
9
  for (var name in all)
24
10
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -50,15 +36,38 @@ module.exports = __toCommonJS(rspack_exports);
50
36
 
51
37
  // src/index.ts
52
38
  var import_node_process5 = __toESM(require("process"), 1);
39
+ var import_console_table_printer = require("console-table-printer");
40
+ var import_picocolors2 = __toESM(require("picocolors"), 1);
53
41
  var import_unplugin = require("unplugin");
54
- var import_picocolors = __toESM(require("picocolors"), 1);
42
+
43
+ // src/caddy/index.ts
44
+ var import_node_child_process4 = require("child_process");
45
+ var import_node_fs2 = require("fs");
46
+ var import_promises2 = require("fs/promises");
47
+ var import_node_os3 = require("os");
48
+ var import_node_path3 = require("path");
49
+ var import_node_process4 = __toESM(require("process"), 1);
50
+ var import_got_cjs = require("got-cjs");
51
+ var import_http_proxy_agent = require("http-proxy-agent");
52
+ var import_https_proxy_agent = require("https-proxy-agent");
53
+ var lockfile = __toESM(require("proper-lockfile"), 1);
54
+
55
+ // src/host/index.ts
56
+ var import_node_child_process2 = require("child_process");
57
+ var import_node_fs = require("fs");
58
+ var import_node_process2 = __toESM(require("process"), 1);
59
+ var import_node_util = require("util");
60
+ var import_hostile = __toESM(require("hostile"), 1);
55
61
 
56
62
  // src/utils.ts
57
- var import_node_process = __toESM(require("process"), 1);
58
- var import_node_path = __toESM(require("path"), 1);
59
- var import_promises = require("fs/promises");
60
63
  var import_node_child_process = require("child_process");
64
+ var import_promises = require("fs/promises");
65
+ var import_node_os = require("os");
66
+ var import_node_path = __toESM(require("path"), 1);
67
+ var import_node_process = __toESM(require("process"), 1);
61
68
  var import_consola = require("consola");
69
+ var import_picocolors = __toESM(require("picocolors"), 1);
70
+ var import_qrcode_terminal = __toESM(require("qrcode-terminal"), 1);
62
71
  var consola = (0, import_consola.createConsola)({
63
72
  level: 3
64
73
  }).withTag("reverse-proxy");
@@ -84,42 +93,38 @@ function isAdmin() {
84
93
  try {
85
94
  (0, import_node_child_process.execSync)("net session", { stdio: "ignore" });
86
95
  return true;
87
- } catch (e) {
96
+ } catch {
88
97
  return false;
89
98
  }
90
99
  } else {
91
- return import_node_process.default.getuid && import_node_process.default.getuid() === 0;
100
+ return !!(import_node_process.default.getuid && import_node_process.default.getuid() === 0);
92
101
  }
93
102
  }
94
-
95
- // src/caddy/index.ts
96
- var import_node_os2 = require("os");
97
- var import_node_process4 = __toESM(require("process"), 1);
98
- var import_node_fs2 = require("fs");
99
- var import_node_child_process3 = require("child_process");
100
- var import_got_cjs = require("got-cjs");
101
- var import_http_proxy_agent = require("http-proxy-agent");
102
- var import_https_proxy_agent = require("https-proxy-agent");
103
- var import_kill_port = __toESM(require("kill-port"), 1);
103
+ function getIpv4List() {
104
+ const interfaces = (0, import_node_os.networkInterfaces)();
105
+ return Object.values(interfaces).flatMap((nInterface) => nInterface ?? []).filter(
106
+ (detail) => detail.address && (detail.family === "IPv4" || detail.family === 4)
107
+ ).filter((detail) => detail.family === "IPv4" && !detail.internal).map((detail) => detail.address);
108
+ }
109
+ async function generateQrcode(input) {
110
+ return new Promise((resolve) => {
111
+ import_qrcode_terminal.default.generate(input, { small: true }, (code) => {
112
+ resolve(code.split("\n").map((line) => import_picocolors.default.bgBlack(import_picocolors.default.white(line))).join("\n"));
113
+ });
114
+ });
115
+ }
104
116
 
105
117
  // src/host/index.ts
106
- var import_node_process2 = __toESM(require("process"), 1);
107
- var import_node_child_process2 = require("child_process");
108
- var import_node_fs = require("fs");
109
- var import_hosts_so_easy = __toESM(require("hosts-so-easy"), 1);
110
- var Hosts = import_hosts_so_easy.default.default || import_hosts_so_easy.default;
111
- var hostInstance = new Hosts({
112
- debounceTime: 50,
113
- hostsFile: getPathOfSystemHostsPath()
114
- });
118
+ var _setHost = (0, import_node_util.promisify)(import_hostile.default.set);
119
+ var _removeHost = (0, import_node_util.promisify)(import_hostile.default.remove);
115
120
  function getPathOfSystemHostsPath() {
116
121
  return import_node_process2.default.platform === "win32" ? `${import_node_process2.default.env.windir || "C:\\WINDOWS"}\\system32\\drivers\\etc\\hosts` : "/etc/hosts";
117
122
  }
118
123
  async function syncHost() {
119
- return new Promise((resolve, reject) => {
124
+ return new Promise((resolve, _reject) => {
120
125
  (0, import_node_child_process2.exec)(
121
126
  import_node_process2.default.platform === "win32" ? "ipconfig /flushdns" : "sudo -E killall -HUP mDNSResponder",
122
- (error, stdout, stderr) => {
127
+ (error, _stdout, _stderr) => {
123
128
  if (error) {
124
129
  consola.error(`exec error: ${error}`);
125
130
  return resolve(false);
@@ -132,26 +137,24 @@ async function syncHost() {
132
137
  async function addHost(ip, host) {
133
138
  if (import_node_process2.default.platform !== "win32")
134
139
  (0, import_node_fs.chmodSync)(getPathOfSystemHostsPath(), 511);
135
- hostInstance.add("127.0.0.1", "localhost");
136
- hostInstance.add(ip, host);
140
+ await _setHost("127.0.0.1", "localhost");
141
+ await _setHost(ip, host);
137
142
  if (ip === "localhost")
138
- hostInstance.add("127.0.0.1", host);
139
- await hostInstance.updateFinish();
143
+ await _setHost("127.0.0.1", host);
140
144
  return await syncHost();
141
145
  }
142
146
  async function removeHost(ip, host) {
143
147
  if (import_node_process2.default.platform !== "win32")
144
148
  (0, import_node_fs.chmodSync)(getPathOfSystemHostsPath(), 511);
145
- hostInstance.remove(ip, host);
149
+ await _removeHost(ip, host);
146
150
  if (ip === "localhost")
147
- hostInstance.remove("127.0.0.1", host);
148
- await hostInstance.updateFinish();
151
+ await _removeHost("127.0.0.1", host);
149
152
  return await syncHost();
150
153
  }
151
154
 
152
155
  // src/caddy/constants.ts
156
+ var import_node_os2 = __toESM(require("os"), 1);
153
157
  var import_node_path2 = require("path");
154
- var import_node_os = __toESM(require("os"), 1);
155
158
  var import_node_process3 = __toESM(require("process"), 1);
156
159
  var import_dotenv_flow = __toESM(require("dotenv-flow"), 1);
157
160
  import_dotenv_flow.default.config({
@@ -159,12 +162,13 @@ import_dotenv_flow.default.config({
159
162
  });
160
163
  function resolvePath(path2) {
161
164
  if (path2.startsWith("~"))
162
- return (0, import_node_path2.join)(import_node_os.default.homedir() || "", path2.slice(1));
165
+ return (0, import_node_path2.join)(import_node_os2.default.homedir() || "", path2.slice(1));
163
166
  return path2;
164
167
  }
165
168
  var TEMP_DIR = resolvePath(import_node_process3.default.env.UHRP_CADDY_PATH || import_node_process3.default.env.TEMP || import_node_process3.default.env.TMPDIR || "/tmp");
166
169
  var caddyPath = (0, import_node_path2.join)(TEMP_DIR, `caddy${import_node_process3.default.platform === "win32" ? ".exe" : ""}`);
167
170
  var caddyFilePath = (0, import_node_path2.join)(TEMP_DIR, "CADDYFILE");
171
+ var caddyLockFilePath = (0, import_node_path2.join)(TEMP_DIR, "caddylock");
168
172
  var supportList = [
169
173
  {
170
174
  platform: "dragonfly",
@@ -277,11 +281,12 @@ var supportList = [
277
281
  ];
278
282
 
279
283
  // src/caddy/utils.ts
284
+ var import_node_child_process3 = require("child_process");
280
285
  var import_node_net = require("net");
281
286
  var import_ora = __toESM(require("ora"), 1);
282
287
  var spinner;
283
288
  function tryPort(port) {
284
- return new Promise((resolve, reject) => {
289
+ return new Promise((resolve, _reject) => {
285
290
  try {
286
291
  const server = (0, import_node_net.createServer)().listen(port);
287
292
  server.on("listening", () => {
@@ -293,11 +298,23 @@ function tryPort(port) {
293
298
  resolve(true);
294
299
  server.close();
295
300
  });
296
- } catch (e) {
301
+ } catch {
297
302
  resolve(true);
298
303
  }
299
304
  });
300
305
  }
306
+ async function kill(port) {
307
+ return new Promise((resolve, reject) => {
308
+ (0, import_node_child_process3.exec)(`npx @maxbo/free-port ${port} -s`, (err, stdout, _stderr) => {
309
+ if (err) {
310
+ reject(err);
311
+ } else {
312
+ consola.log(stdout);
313
+ resolve();
314
+ }
315
+ });
316
+ });
317
+ }
301
318
  function getNumber(number) {
302
319
  if (number <= 0)
303
320
  return "0%";
@@ -341,14 +358,14 @@ async function download() {
341
358
  (0, import_node_fs2.chmodSync)(TEMP_DIR, 511);
342
359
  }
343
360
  const file = (0, import_node_fs2.createWriteStream)(caddyPath);
344
- let _platform = (0, import_node_os2.platform)().toString();
361
+ let _platform = (0, import_node_os3.platform)().toString();
345
362
  _platform === "win32" && (_platform = "windows");
346
363
  let _arch = import_node_process4.default.arch.toString();
347
364
  _arch === "x64" && (_arch = "amd64");
348
365
  const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
349
366
  if (!support)
350
367
  return reject(new Error("not support"));
351
- const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}`;
368
+ const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}&p=github.com%2Fcaddyserver%2Fforwardproxy`;
352
369
  (0, import_node_fs2.existsSync)(caddyPath) && (0, import_node_fs2.unlinkSync)(caddyPath);
353
370
  const httpProxy = import_node_process4.default.env.HTTP_PROXY || import_node_process4.default.env.http_proxy;
354
371
  const httpsProxy = import_node_process4.default.env.HTTPS_PROXY || import_node_process4.default.env.https_proxy;
@@ -381,7 +398,7 @@ function testCaddy() {
381
398
  if (!(0, import_node_fs2.existsSync)(caddyPath))
382
399
  return resolve(false);
383
400
  (0, import_node_fs2.chmodSync)(caddyPath, 511);
384
- const child = import_node_process4.default.platform === "win32" ? (0, import_node_child_process3.spawn)(caddyPath, []) : (0, import_node_child_process3.spawn)("sudo", ["-E", caddyPath]);
401
+ const child = import_node_process4.default.platform === "win32" ? (0, import_node_child_process4.spawn)(caddyPath, []) : (0, import_node_child_process4.spawn)("sudo", ["-E", caddyPath]);
385
402
  child.on("close", () => {
386
403
  return resolve(false);
387
404
  });
@@ -397,9 +414,61 @@ var CaddyInstant = class {
397
414
  constructor() {
398
415
  this.inited = false;
399
416
  this.stoped = false;
400
- testCaddy().then(() => {
417
+ /** has locked */
418
+ this.locked = false;
419
+ testCaddy().then(async () => {
420
+ await this.getCaddyfile();
401
421
  this.inited = true;
402
422
  });
423
+ this.locked = this.checkLock();
424
+ }
425
+ checkLock() {
426
+ if (!(0, import_node_fs2.existsSync)(caddyLockFilePath))
427
+ (0, import_node_fs2.writeFileSync)(caddyLockFilePath, "");
428
+ return lockfile.checkSync(caddyLockFilePath);
429
+ }
430
+ async getCaddyfile() {
431
+ if (!(0, import_node_fs2.existsSync)(caddyFilePath))
432
+ await this.initCaddyfile();
433
+ this.caddyfile = await (0, import_promises2.readFile)(caddyFilePath, "utf-8");
434
+ return this.caddyfile;
435
+ }
436
+ async initCaddyfile() {
437
+ const contet = `
438
+ {
439
+ debug
440
+ auto_https disable_redirects
441
+ }
442
+
443
+ :7601 {
444
+ root * "${(0, import_node_path3.join)(
445
+ import_node_process4.default.platform === "win32" ? `${import_node_process4.default.env.AppData}/Caddy` : `${import_node_process4.default.env.HOME}/Library/Application Support/Caddy`,
446
+ "./pki/authorities/local"
447
+ )}"
448
+ file_server browse
449
+ }
450
+
451
+ # \u6B63\u5411\u4EE3\u7406\u914D\u7F6E
452
+ :7600 {
453
+ bind 0.0.0.0
454
+
455
+ forward_proxy {
456
+ hide_ip
457
+ hide_via
458
+ acl {
459
+ allow all
460
+ }
461
+ }
462
+ }
463
+ `;
464
+ await (0, import_promises2.writeFile)(caddyFilePath, contet);
465
+ this.caddyfile = contet;
466
+ }
467
+ async writeCaddyfile() {
468
+ return await (0, import_promises2.writeFile)(caddyFilePath, this.caddyfile || "");
469
+ }
470
+ async deleteCaddyfile() {
471
+ return await (0, import_promises2.unlink)(caddyFilePath);
403
472
  }
404
473
  async init() {
405
474
  await download();
@@ -408,7 +477,6 @@ var CaddyInstant = class {
408
477
  /**
409
478
  * @param source like `127.0.0.1:8080`
410
479
  * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
411
- * @returns
412
480
  */
413
481
  async run(source, target, options) {
414
482
  source = source.replace("0.0.0.0", "127.0.0.1");
@@ -418,102 +486,217 @@ var CaddyInstant = class {
418
486
  showCaddyLog = false,
419
487
  https = false
420
488
  } = options || {};
489
+ this._source = source;
490
+ this._target = target;
421
491
  if (!this.inited)
422
492
  await this.init();
423
- if (https && await tryPort(443))
424
- await (0, import_kill_port.default)(443, "tcp");
425
- if ((import_node_process4.default.platform === "win32" || !https) && await tryPort(80))
426
- await (0, import_kill_port.default)(80, "tcp");
427
493
  if (!await addHost(source.split(":")[0], target.split(":")[0]))
428
494
  throw new Error("update host failed");
429
495
  consola.success("update host success\n");
496
+ await this.getCaddyfile();
497
+ if (!(this.caddyfile || "").includes(`${target.split(":")[0]}${https ? "" : ":80"}`)) {
498
+ this.caddyfile = `${this.caddyfile}
499
+ ${target.split(":")[0]}${https ? "" : ":80"} {
500
+ ${https ? "tls internal" : ""}
501
+ reverse_proxy http://${source} {
502
+ health_uri ${base}
503
+ health_interval 2s
504
+ health_timeout 5s
505
+ fail_duration 2s
506
+ unhealthy_status 502 503 504 404
507
+ lb_try_duration 3s
508
+ lb_try_interval 300ms
509
+ health_headers {
510
+ Accept text/html
511
+ Accept-Encoding gzip, deflate, br
512
+ User-Agent Caddy-Health-Check
513
+ }
514
+
515
+ @error status 502 503 504 404
516
+ handle_response @error {
517
+ respond * 503 {
518
+ body "Service Unavailable"
519
+ close
520
+ }
521
+ }
522
+ }
523
+ }
524
+ `;
525
+ await this.writeCaddyfile();
526
+ }
527
+ if (!(0, import_node_fs2.existsSync)(caddyLockFilePath))
528
+ (0, import_node_fs2.writeFileSync)(caddyLockFilePath, "");
529
+ if (!this.locked) {
530
+ if (await tryPort(443))
531
+ await kill(443);
532
+ if ((import_node_process4.default.platform === "win32" || !https) && await tryPort(80))
533
+ await kill(80);
534
+ }
430
535
  return new Promise((resolve, reject) => {
431
- const child = import_node_process4.default.platform !== "win32" ? (0, import_node_child_process3.spawn)("sudo", ["-E", caddyPath, "reverse-proxy", "--from", `${target.split(":")[0]}${https ? "" : ":80"}`, "--to", `${source}`, "--internal-certs", "--insecure", "--disable-redirects"]) : (0, import_node_child_process3.spawn)(caddyPath, ["reverse-proxy", "--from", `${target.split(":")[0]}`, "--to", `${source}`, "--internal-certs"]);
432
- child.on("error", (err) => {
433
- return reject(err);
434
- });
435
- import_node_process4.default.on("SIGINT", async () => {
436
- if (!restore || this.stoped)
437
- return;
438
- try {
439
- if (await removeHost(source.split(":")[0], target.split(":")[0]))
440
- consola.success("restore host success\n");
441
- else
442
- consola.fail("restore host failed\n");
443
- } catch (e) {
444
- consola.error(e);
445
- consola.fail("restore host failed\n");
446
- } finally {
447
- this.stoped = true;
448
- import_node_process4.default.nextTick(() => {
449
- import_node_process4.default.exit();
450
- });
451
- }
452
- });
453
- const originalExit = import_node_process4.default.exit.bind(import_node_process4.default);
454
- import_node_process4.default.exit = async (code) => {
455
- const port = Number(source.split(":")[1]);
456
- if (!Number.isNaN(port) && await tryPort(port))
457
- await (0, import_kill_port.default)(port, "tcp");
458
- const pwd = import_node_process4.default.cwd();
459
- const viteCacheDir = `${pwd}/node_modules/.vite`;
460
- if ((0, import_node_fs2.existsSync)(viteCacheDir))
461
- chmodRecursive(viteCacheDir, 511);
462
- const nuxtCacheDir = `${pwd}/.nuxt`;
463
- if ((0, import_node_fs2.existsSync)(nuxtCacheDir))
464
- await chmodRecursive(nuxtCacheDir, 511);
465
- const webpackCacheDir = `${pwd}/node_modules/.cache`;
466
- if ((0, import_node_fs2.existsSync)(webpackCacheDir))
467
- chmodRecursive(webpackCacheDir, 511);
468
- if (!restore || this.stoped)
469
- return originalExit(code);
470
- try {
471
- if (await removeHost(source.split(":")[0], target.split(":")[0]))
472
- consola.success("restore host success\n");
473
- else
474
- consola.fail("restore host failed\n");
475
- } catch (e) {
476
- consola.error(e);
477
- consola.fail("restore host failed\n");
478
- } finally {
479
- this.stoped = true;
480
- import_node_process4.default.nextTick(() => {
481
- originalExit(code);
482
- });
483
- }
536
+ var _a, _b;
537
+ const setupCleanup = () => {
538
+ import_node_process4.default.on("SIGINT", async () => {
539
+ if (this.stoped)
540
+ return;
541
+ import_node_process4.default.stdin.resume();
542
+ try {
543
+ await this.baseCleanup(restore);
544
+ } finally {
545
+ this.stoped = true;
546
+ import_node_process4.default.nextTick(() => {
547
+ import_node_process4.default.exit();
548
+ });
549
+ }
550
+ });
551
+ const originalExit = import_node_process4.default.exit.bind(import_node_process4.default);
552
+ import_node_process4.default.exit = async (code) => {
553
+ const port = Number(source.split(":")[1]);
554
+ if (!Number.isNaN(port) && await tryPort(port))
555
+ await kill(port);
556
+ const pwd = import_node_process4.default.cwd();
557
+ const viteCacheDir = `${pwd}/node_modules/.vite`;
558
+ if ((0, import_node_fs2.existsSync)(viteCacheDir))
559
+ await chmodRecursive(viteCacheDir, 511).catch(() => {
560
+ });
561
+ const nuxtCacheDir = `${pwd}/.nuxt`;
562
+ if ((0, import_node_fs2.existsSync)(nuxtCacheDir))
563
+ await chmodRecursive(nuxtCacheDir, 511).catch(() => {
564
+ });
565
+ const webpackCacheDir = `${pwd}/node_modules/.cache`;
566
+ if ((0, import_node_fs2.existsSync)(webpackCacheDir))
567
+ await chmodRecursive(webpackCacheDir, 511).catch(() => {
568
+ });
569
+ if (this.stoped)
570
+ return originalExit(code);
571
+ import_node_process4.default.stdin.resume();
572
+ try {
573
+ await this.baseCleanup();
574
+ } finally {
575
+ this.stoped = true;
576
+ import_node_process4.default.nextTick(() => {
577
+ originalExit(code);
578
+ });
579
+ }
580
+ };
484
581
  };
485
- child.stderr.on("data", (data) => {
486
- const lines = data.toString().split("\n").map((line) => line.trim());
487
- for (const line of lines) {
488
- showCaddyLog && line && console.info(line);
489
- if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
490
- consola.error(line);
491
- return reject(line);
582
+ if (!this.locked) {
583
+ this._caddyChild = import_node_process4.default.platform !== "win32" ? (0, import_node_child_process4.spawn)("sudo", ["-E", caddyPath, "run", "--config", caddyFilePath, "--watch"]) : (0, import_node_child_process4.spawn)(caddyPath, ["run", "--config", caddyFilePath, "--watch"]);
584
+ lockfile.lockSync(caddyLockFilePath);
585
+ this._caddyChild.on("error", (err) => {
586
+ return reject(err);
587
+ });
588
+ (_a = this._caddyChild.stderr) == null ? void 0 : _a.on("data", async (data) => {
589
+ const lines = data.toString().split("\n").map((line) => line.trim());
590
+ for (const line of lines) {
591
+ showCaddyLog && line && console.info(line);
592
+ if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
593
+ if (line.includes("parsing caddyfile tokens")) {
594
+ consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
595
+
596
+ ${line}
597
+ `);
598
+ await this.baseCleanup();
599
+ import_node_process4.default.exit();
600
+ } else {
601
+ consola.error(`${line}
602
+ `);
603
+ return reject(line);
604
+ }
605
+ }
606
+ if (line.includes("config file changed"))
607
+ consola.success("Detect added a new reverse proxy config, restarted.\n");
608
+ if (line.includes("caddy proxying") || line.includes("serving initial"))
609
+ return resolve();
492
610
  }
493
- }
494
- });
495
- child.stdout.on("data", (_data) => {
496
- consola.info(_data.toString());
497
- resolve();
498
- });
611
+ });
612
+ (_b = this._caddyChild.stdout) == null ? void 0 : _b.on("data", (_data) => {
613
+ consola.info(_data.toString());
614
+ resolve();
615
+ });
616
+ setupCleanup();
617
+ } else {
618
+ consola.info("Caddy is running in another process.");
619
+ setupCleanup();
620
+ return resolve();
621
+ }
499
622
  });
500
623
  }
624
+ async baseCleanup(restore = true) {
625
+ var _a;
626
+ try {
627
+ if (restore && this._source && this._target) {
628
+ if (await removeHost(this._source.split(":")[0], this._target.split(":")[0]))
629
+ consola.success("Restore host success.\n");
630
+ else
631
+ consola.fail("Restore host failed.\n");
632
+ }
633
+ } catch (e) {
634
+ consola.error(e);
635
+ consola.fail("Restore host failed.\n");
636
+ }
637
+ if (!this.locked && !this.stoped) {
638
+ (_a = this._caddyChild) == null ? void 0 : _a.kill();
639
+ try {
640
+ await lockfile.unlock(caddyLockFilePath).catch(() => {
641
+ });
642
+ await (0, import_promises2.unlink)(caddyFilePath).catch(() => {
643
+ });
644
+ await (0, import_promises2.unlink)(caddyLockFilePath).catch(() => {
645
+ });
646
+ } catch (e) {
647
+ consola.error(e);
648
+ }
649
+ }
650
+ }
501
651
  };
502
652
 
503
653
  // src/index.ts
504
654
  var config;
505
655
  var caddy;
506
656
  var cwd = import_node_process5.default.cwd();
657
+ function colorUrl(url) {
658
+ return import_picocolors2.default.green(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors2.default.bold(port)}/`));
659
+ }
660
+ async function printForwardProxy() {
661
+ const ipv4List = getIpv4List();
662
+ if (ipv4List.length) {
663
+ const ips = ipv4List.map((ip) => import_picocolors2.default.cyan(ip)).join(", ");
664
+ consola.info(`${import_picocolors2.default.bold("Mobile device proxy access")}:
665
+ `);
666
+ consola.info("1. Install certificate: scan the QR code and download the `root.crt` file,");
667
+ consola.info(" then install it on your mobile device");
668
+ const ipTable = await Promise.all(
669
+ ipv4List.map(async (ip) => ({
670
+ target: `http://${ip}:7601`,
671
+ certificate: await generateQrcode(`http://${ip}:7601`)
672
+ }))
673
+ );
674
+ const table = new import_console_table_printer.Table({
675
+ columns: [
676
+ { name: "target", alignment: "left" },
677
+ { name: "certificate", alignment: "center", minLen: 28 }
678
+ ]
679
+ });
680
+ ipTable.forEach((ip) => {
681
+ table.addRow(ip);
682
+ });
683
+ table.printTable();
684
+ consola.info(`2. Set proxy on mobile device (Available IPs: ${ips}):${import_picocolors2.default.bold(7600)}
685
+
686
+ `);
687
+ }
688
+ }
507
689
  var vitePrintUrls = once((options, source, target, base = "/", _printUrls) => {
508
690
  _printUrls == null ? void 0 : _printUrls();
509
691
  if (caddy)
510
692
  return;
511
693
  caddy = new CaddyInstant();
512
- caddy.run(source, target, __spreadValues({
513
- base
514
- }, options)).then(() => {
515
- const colorUrl = (url) => import_picocolors.default.green(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
516
- consola.success(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
694
+ caddy.run(source, target, {
695
+ base,
696
+ ...options
697
+ }).then(async () => {
698
+ await printForwardProxy();
699
+ consola.success(` ${import_picocolors2.default.green("\u279C")} ${import_picocolors2.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
517
700
  }).catch((e) => {
518
701
  throw e;
519
702
  });
@@ -529,16 +712,16 @@ var unpluginFactory = (options) => ({
529
712
  var _a;
530
713
  if (config.command !== "serve")
531
714
  return;
532
- if (!isAdmin()) {
533
- consola.warn("please run as administrator");
534
- return;
535
- }
536
715
  const {
537
716
  enable = true,
538
717
  target = ""
539
718
  } = options;
540
719
  if (!enable)
541
720
  return;
721
+ if (!isAdmin()) {
722
+ consola.warn("please run as administrator");
723
+ return;
724
+ }
542
725
  if (!target) {
543
726
  consola.fail("please provide target");
544
727
  return;
@@ -558,24 +741,27 @@ var unpluginFactory = (options) => ({
558
741
  var _a, _b;
559
742
  if (import_node_process5.default.env.NODE_ENV !== "development")
560
743
  return;
561
- if (!isAdmin()) {
562
- consola.warn("please run as administrator");
563
- return;
564
- }
565
744
  const {
566
745
  enable = true,
567
746
  target = ""
568
747
  } = options;
569
748
  if (!enable)
570
749
  return;
750
+ if (!isAdmin()) {
751
+ consola.warn("please run as administrator");
752
+ return;
753
+ }
571
754
  if (!target) {
572
755
  consola.fail("please provide target");
573
756
  return;
574
757
  }
575
- const devServer = __spreadValues(__spreadValues({
758
+ const devServer = {
576
759
  host: "localhost",
577
- port: 8080
578
- }, compiler.options.devServer), (_a = import_node_process5.default.VUE_CLI_SERVICE) == null ? void 0 : _a.projectOptions.devServer);
760
+ port: 8080,
761
+ ...compiler.options.devServer,
762
+ // @ts-expect-error vuecli
763
+ ...(_a = import_node_process5.default.VUE_CLI_SERVICE) == null ? void 0 : _a.projectOptions.devServer
764
+ };
579
765
  const source = `${devServer.host}:${devServer.port}`;
580
766
  if (caddy)
581
767
  return;
@@ -590,10 +776,12 @@ var unpluginFactory = (options) => ({
590
776
  options.https = false;
591
777
  }
592
778
  caddy = new CaddyInstant();
593
- caddy.run(source, target, __spreadValues({}, options)).then(() => {
594
- const colorUrl = (url) => import_picocolors.default.green(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
595
- compiler.hooks.done.tap("unplugin-https-reverse-proxy", () => {
596
- consola.success(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
779
+ caddy.run(source, target, {
780
+ ...options
781
+ }).then(() => {
782
+ compiler.hooks.done.tap("unplugin-https-reverse-proxy", async () => {
783
+ await printForwardProxy();
784
+ consola.success(` ${import_picocolors2.default.green("\u279C")} ${import_picocolors2.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
597
785
  });
598
786
  }).catch((e) => {
599
787
  throw e;
@@ -603,33 +791,37 @@ var unpluginFactory = (options) => ({
603
791
  var _a, _b, _c;
604
792
  if (import_node_process5.default.env.NODE_ENV !== "development")
605
793
  return;
606
- if (!isAdmin()) {
607
- consola.warn("please run as administrator");
608
- return;
609
- }
610
794
  const {
611
795
  enable = true,
612
796
  target = ""
613
797
  } = options;
614
798
  if (!enable)
615
799
  return;
800
+ if (!isAdmin()) {
801
+ consola.warn("please run as administrator");
802
+ return;
803
+ }
616
804
  if (!target) {
617
805
  consola.fail("please provide target");
618
806
  return;
619
807
  }
620
- const devServer = __spreadValues(__spreadValues({
808
+ const devServer = {
621
809
  host: "localhost",
622
- port: 8080
623
- }, compiler.options.devServer), (_c = (_b = await ((_a = await import("@rsbuild/core")) == null ? void 0 : _a.loadConfig({
624
- cwd
625
- }))) == null ? void 0 : _b.content) == null ? void 0 : _c.server);
810
+ port: 8080,
811
+ ...compiler.options.devServer,
812
+ ...(_c = (_b = await ((_a = await import("@rsbuild/core")) == null ? void 0 : _a.loadConfig({
813
+ cwd
814
+ }))) == null ? void 0 : _b.content) == null ? void 0 : _c.server
815
+ };
626
816
  const source = `${devServer.host}:${devServer.port}`;
627
817
  if (caddy)
628
818
  return;
629
819
  caddy = new CaddyInstant();
630
- caddy.run(source, target, __spreadValues({}, options)).then(() => {
631
- const colorUrl = (url) => import_picocolors.default.green(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
632
- consola.success(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
820
+ caddy.run(source, target, {
821
+ ...options
822
+ }).then(async () => {
823
+ await printForwardProxy();
824
+ consola.success(` ${import_picocolors2.default.green("\u279C")} ${import_picocolors2.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
633
825
  }).catch((e) => {
634
826
  throw e;
635
827
  });
@@ -640,4 +832,4 @@ var src_default = unplugin;
640
832
 
641
833
  // src/rspack.ts
642
834
  var rspack_default = src_default.rspack;
643
- exports.default = module.exports;
835
+ module.exports = module.exports;exports.default = module.exports;