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