unplugin-https-reverse-proxy 0.0.23 → 0.0.24

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.
@@ -22,15 +22,6 @@ import { createConsola } from "consola";
22
22
  var consola = createConsola({
23
23
  level: 3
24
24
  }).withTag("reverse-proxy");
25
- function once(fn) {
26
- let called = false;
27
- return (...args) => {
28
- if (called)
29
- return;
30
- called = true;
31
- return fn(...args);
32
- };
33
- }
34
25
  function isAdmin() {
35
26
  if (process.platform === "win32") {
36
27
  try {
@@ -47,6 +38,5 @@ function isAdmin() {
47
38
  export {
48
39
  __spreadValues,
49
40
  consola,
50
- once,
51
41
  isAdmin
52
42
  };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  unpluginFactory
3
- } from "./chunk-S4DC5XL4.js";
3
+ } from "./chunk-TVCN6ESH.js";
4
4
 
5
5
  // src/vite.ts
6
6
  import { createVitePlugin } from "unplugin";
@@ -1,32 +1,75 @@
1
1
  import {
2
2
  __spreadValues,
3
3
  consola,
4
- isAdmin,
5
- once
6
- } from "./chunk-NNO3ZUSU.js";
4
+ isAdmin
5
+ } from "./chunk-3RTK3FSZ.js";
7
6
 
8
7
  // src/index.ts
9
- import process3 from "process";
10
- import { chmodSync as chmodSync2, existsSync as existsSync2 } from "fs";
8
+ import process4 from "process";
9
+ import { chmodSync as chmodSync3, existsSync as existsSync2 } from "fs";
11
10
  import { createUnplugin } from "unplugin";
12
11
  import c from "picocolors";
13
12
 
14
13
  // src/caddy/index.ts
15
14
  import { platform } from "os";
16
- import process2 from "process";
17
- import { chmodSync, createWriteStream, existsSync, unlinkSync } from "fs";
15
+ import process3 from "process";
16
+ import { chmodSync as chmodSync2, createWriteStream, existsSync, unlinkSync } from "fs";
18
17
  import { spawn } from "child_process";
19
18
  import { got } from "got-cjs";
20
19
  import { HttpProxyAgent } from "http-proxy-agent";
21
20
  import { HttpsProxyAgent } from "https-proxy-agent";
22
- import _Hosts from "hosts-so-easy";
23
21
  import kill from "kill-port";
24
22
 
23
+ // src/host/index.ts
24
+ import process from "process";
25
+ import { exec } from "child_process";
26
+ import { chmodSync } from "fs";
27
+ import _Hosts from "hosts-so-easy";
28
+ var Hosts = _Hosts.default || _Hosts;
29
+ var hostInstance = new Hosts({
30
+ debounceTime: 50,
31
+ hostsFile: getPathOfSystemHostsPath()
32
+ });
33
+ function getPathOfSystemHostsPath() {
34
+ return process.platform === "win32" ? `${process.env.windir || "C:\\WINDOWS"}\\system32\\drivers\\etc\\hosts` : "/etc/hosts";
35
+ }
36
+ async function syncHost() {
37
+ return new Promise((resolve, reject) => {
38
+ exec(
39
+ process.platform === "win32" ? "ipconfig /flushdns" : "sudo -E killall -HUP mDNSResponder",
40
+ (error, stdout, stderr) => {
41
+ if (error) {
42
+ console.error(`exec error: ${error}`);
43
+ return resolve(false);
44
+ }
45
+ return resolve(true);
46
+ }
47
+ );
48
+ });
49
+ }
50
+ async function addHost(ip, host) {
51
+ if (process.platform !== "win32")
52
+ chmodSync(getPathOfSystemHostsPath(), 511);
53
+ hostInstance.add("127.0.0.1", "localhost");
54
+ hostInstance.add(ip, host);
55
+ await hostInstance.updateFinish();
56
+ return await syncHost();
57
+ }
58
+ async function removeHost(ip, host) {
59
+ if (process.platform !== "win32")
60
+ chmodSync(getPathOfSystemHostsPath(), 511);
61
+ hostInstance.remove(ip, host);
62
+ if (ip === "localhost")
63
+ hostInstance.remove("127.0.0.1", host);
64
+ await hostInstance.updateFinish();
65
+ return await syncHost();
66
+ }
67
+
25
68
  // src/caddy/constants.ts
26
69
  import { join } from "path";
27
- import process from "process";
28
- var TEMP_DIR = process.env.TEMP || process.env.TMPDIR || "/tmp";
29
- var caddyPath = join(TEMP_DIR, `caddy${process.platform === "win32" ? ".exe" : ""}`);
70
+ import process2 from "process";
71
+ var TEMP_DIR = process2.env.TEMP || process2.env.TMPDIR || "/tmp";
72
+ var caddyPath = join(TEMP_DIR, `caddy${process2.platform === "win32" ? ".exe" : ""}`);
30
73
  var caddyFilePath = join(TEMP_DIR, "CADDYFILE");
31
74
  var supportList = [
32
75
  {
@@ -195,7 +238,6 @@ function logProgressOver() {
195
238
  }
196
239
 
197
240
  // src/caddy/index.ts
198
- var Hosts = _Hosts.default || _Hosts;
199
241
  async function download() {
200
242
  if (await testCaddy())
201
243
  return caddyPath;
@@ -203,15 +245,15 @@ async function download() {
203
245
  const file = createWriteStream(caddyPath);
204
246
  let _platform = platform().toString();
205
247
  _platform === "win32" && (_platform = "windows");
206
- let _arch = process2.arch.toString();
248
+ let _arch = process3.arch.toString();
207
249
  _arch === "x64" && (_arch = "amd64");
208
250
  const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
209
251
  if (!support)
210
252
  return reject(new Error("not support"));
211
253
  const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}`;
212
254
  existsSync(caddyPath) && unlinkSync(caddyPath);
213
- const httpProxy = process2.env.HTTP_PROXY || process2.env.http_proxy;
214
- const httpsProxy = process2.env.HTTPS_PROXY || process2.env.https_proxy;
255
+ const httpProxy = process3.env.HTTP_PROXY || process3.env.http_proxy;
256
+ const httpsProxy = process3.env.HTTPS_PROXY || process3.env.https_proxy;
215
257
  const httpAgent = httpProxy ? new HttpProxyAgent(httpProxy) : void 0;
216
258
  const httpsAgent = httpsProxy ? new HttpsProxyAgent(httpsProxy) : void 0;
217
259
  got.stream(dowmloadLink, {
@@ -223,9 +265,9 @@ async function download() {
223
265
  logProgress(progress.percent);
224
266
  }).pipe(file).on("finish", () => {
225
267
  logProgressOver();
226
- if (process2.platform === "win32")
268
+ if (process3.platform === "win32")
227
269
  return resolve(caddyPath);
228
- chmodSync(caddyPath, 493);
270
+ chmodSync2(caddyPath, 493);
229
271
  resolve(caddyPath);
230
272
  }).on("error", (err) => {
231
273
  reject(err);
@@ -236,8 +278,8 @@ function testCaddy() {
236
278
  return new Promise((resolve, reject) => {
237
279
  if (!existsSync(caddyPath))
238
280
  return resolve(false);
239
- chmodSync(caddyPath, 493);
240
- const child = process2.platform === "win32" ? spawn(caddyPath, []) : spawn("sudo", ["-E", caddyPath]);
281
+ chmodSync2(caddyPath, 493);
282
+ const child = process3.platform === "win32" ? spawn(caddyPath, []) : spawn("sudo", ["-E", caddyPath]);
241
283
  child.on("close", () => {
242
284
  return resolve(false);
243
285
  });
@@ -253,7 +295,6 @@ var CaddyInstant = class {
253
295
  constructor() {
254
296
  this.inited = false;
255
297
  this.stoped = false;
256
- this.host = new Hosts();
257
298
  testCaddy().then(() => {
258
299
  this.inited = true;
259
300
  });
@@ -262,51 +303,6 @@ var CaddyInstant = class {
262
303
  await download();
263
304
  this.inited = true;
264
305
  }
265
- async updateHost(ip, host) {
266
- ["localhost", "0.0.0.0"].includes(ip) && (ip = "127.0.0.1");
267
- this.host.add("127.0.0.1", "localhost");
268
- this.host.add(ip, host);
269
- await this.host.updateFinish();
270
- return new Promise((resolve, reject) => {
271
- if (process2.platform === "win32") {
272
- spawn("ipconfig", ["/flushdns"]).on("error", (err) => {
273
- consola.error(err);
274
- return resolve(false);
275
- }).on("close", () => {
276
- resolve(true);
277
- });
278
- } else {
279
- spawn("sudo", ["-E", "killall", "-HUP", "mDNSResponder"]).on("error", (err) => {
280
- consola.error(err);
281
- return resolve(false);
282
- }).on("close", () => {
283
- resolve(true);
284
- });
285
- }
286
- });
287
- }
288
- async restoreHost(ip, host) {
289
- ["localhost", "0.0.0.0"].includes(ip) && (ip = "127.0.0.1");
290
- this.host.remove(ip, host);
291
- await this.host.updateFinish();
292
- return new Promise((resolve, reject) => {
293
- if (process2.platform === "win32") {
294
- spawn("ipconfig", ["/flushdns"]).on("error", (err) => {
295
- consola.error(err);
296
- return resolve(false);
297
- }).on("close", () => {
298
- resolve(true);
299
- });
300
- } else {
301
- spawn("sudo", ["-E", "killall", "-HUP", "mDNSResponder"]).on("error", (err) => {
302
- consola.error(err);
303
- return resolve(false);
304
- }).on("close", () => {
305
- resolve(true);
306
- });
307
- }
308
- });
309
- }
310
306
  /**
311
307
  * @param source like `127.0.0.1:8080`
312
308
  * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
@@ -324,16 +320,53 @@ var CaddyInstant = class {
324
320
  await this.init();
325
321
  if (https && await tryPort(443))
326
322
  await kill(443, "tcp");
327
- if ((process2.platform === "win32" || !https) && await tryPort(80))
323
+ if ((process3.platform === "win32" || !https) && await tryPort(80))
328
324
  await kill(80, "tcp");
329
- if (!await this.updateHost(source.split(":")[0], target.split(":")[0]))
325
+ if (!await addHost(source.split(":")[0], target.split(":")[0]))
330
326
  throw new Error("update host failed");
331
327
  consola.success("update host success\n");
332
328
  return new Promise((resolve, reject) => {
333
- const child = process2.platform !== "win32" ? spawn("sudo", ["-E", caddyPath, "reverse-proxy", "--from", `${target.split(":")[0]}${https ? "" : ":80"}`, "--to", `${source}`, "--internal-certs", "--insecure", "--disable-redirects"]) : spawn(caddyPath, ["reverse-proxy", "--from", `${target.split(":")[0]}`, "--to", `${source}`, "--internal-certs"]);
329
+ const child = process3.platform !== "win32" ? spawn("sudo", ["-E", caddyPath, "reverse-proxy", "--from", `${target.split(":")[0]}${https ? "" : ":80"}`, "--to", `${source}`, "--internal-certs", "--insecure", "--disable-redirects"]) : spawn(caddyPath, ["reverse-proxy", "--from", `${target.split(":")[0]}`, "--to", `${source}`, "--internal-certs"]);
334
330
  child.on("error", (err) => {
335
331
  return reject(err);
336
332
  });
333
+ process3.on("SIGINT", async () => {
334
+ if (!restore || this.stoped)
335
+ return;
336
+ try {
337
+ if (await removeHost(source.split(":")[0], target.split(":")[0]))
338
+ consola.success("restore host success\n");
339
+ else
340
+ consola.fail("restore host failed\n");
341
+ } catch (e) {
342
+ consola.error(e);
343
+ consola.fail("restore host failed\n");
344
+ } finally {
345
+ this.stoped = true;
346
+ process3.nextTick(() => {
347
+ process3.exit();
348
+ });
349
+ }
350
+ });
351
+ const originalExit = process3.exit;
352
+ process3.exit = async (code) => {
353
+ if (!restore || this.stoped)
354
+ return originalExit(code);
355
+ try {
356
+ if (await removeHost(source.split(":")[0], target.split(":")[0]))
357
+ consola.success("restore host success\n");
358
+ else
359
+ consola.fail("restore host failed\n");
360
+ } catch (e) {
361
+ consola.error(e);
362
+ consola.fail("restore host failed\n");
363
+ } finally {
364
+ this.stoped = true;
365
+ process3.nextTick(() => {
366
+ originalExit(code);
367
+ });
368
+ }
369
+ };
337
370
  child.stderr.on("data", (data) => {
338
371
  const lines = data.toString().split("\n").map((line) => line.trim());
339
372
  for (const line of lines) {
@@ -346,22 +379,7 @@ var CaddyInstant = class {
346
379
  });
347
380
  child.stdout.on("data", (_data) => {
348
381
  consola.info(_data.toString());
349
- resolve(async (callback) => {
350
- if (!restore || this.stoped)
351
- return;
352
- try {
353
- if (await this.restoreHost(source.split(":")[0], target.split(":")[0]))
354
- consola.success("restore host success\n");
355
- else
356
- consola.fail("restore host failed\n");
357
- } catch (e) {
358
- consola.error(e);
359
- consola.fail("restore host failed\n");
360
- }
361
- this.stoped = true;
362
- child.kill();
363
- callback && callback();
364
- });
382
+ resolve();
365
383
  });
366
384
  });
367
385
  }
@@ -370,55 +388,13 @@ var CaddyInstant = class {
370
388
  // src/index.ts
371
389
  var config;
372
390
  var caddy;
373
- var _stop;
374
391
  var _servce;
375
- function registerExit(clear) {
376
- process3.on("beforeExit", async (_code) => {
377
- await clear();
378
- });
379
- process3.on("uncaughtException", async (err) => {
380
- console.error("An uncaught error occurred!", err.stack);
381
- await clear();
382
- process3.nextTick(() => {
383
- process3.exit(1);
384
- });
385
- });
386
- process3.on("unhandledRejection", async (reason, promise) => {
387
- console.error("Unhandled Rejection at:", promise, "reason:", reason);
388
- await clear();
389
- process3.nextTick(() => {
390
- process3.exit(1);
391
- });
392
- });
393
- process3.once("SIGINT", async () => {
394
- await clear();
395
- process3.exit(0);
396
- });
397
- process3.once("SIGTERM", async () => {
398
- await clear();
399
- process3.exit(0);
400
- });
401
- }
402
392
  var unpluginFactory = (options) => ({
403
393
  name: "unplugin-https-reverse-proxy",
404
394
  enforce: "pre",
405
395
  vite: {
406
396
  configResolved(_config) {
407
397
  config = _config;
408
- registerExit(async () => {
409
- var _a;
410
- try {
411
- if (_servce) {
412
- (_a = _servce.httpServer) == null ? void 0 : _a.close(async () => {
413
- _stop && await _stop();
414
- });
415
- _servce.close();
416
- }
417
- _stop && await _stop();
418
- } catch (e) {
419
- consola.error(e);
420
- }
421
- });
422
398
  },
423
399
  configureServer(server) {
424
400
  if (!isAdmin()) {
@@ -442,10 +418,10 @@ var unpluginFactory = (options) => ({
442
418
  server.printUrls = () => {
443
419
  var _a;
444
420
  _printUrls();
445
- const pwd = process3.cwd();
421
+ const pwd = process4.cwd();
446
422
  const vireCacheDir = `${pwd}/node_modules/.vite`;
447
423
  if (existsSync2(vireCacheDir))
448
- chmodSync2(vireCacheDir, 511);
424
+ chmodSync3(vireCacheDir, 511);
449
425
  let source = `localhost:${config.server.port}`;
450
426
  const url = (_a = server.resolvedUrls) == null ? void 0 : _a.local[0];
451
427
  if (url) {
@@ -459,10 +435,9 @@ var unpluginFactory = (options) => ({
459
435
  caddy = new CaddyInstant();
460
436
  caddy.run(source, target, __spreadValues({
461
437
  base
462
- }, options)).then((stop) => {
438
+ }, options)).then(() => {
463
439
  const colorUrl = (url2) => c.green(url2.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
464
440
  consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
465
- !_stop && (_stop = once(stop));
466
441
  }).catch((e) => {
467
442
  throw e;
468
443
  });
@@ -478,7 +453,7 @@ var unpluginFactory = (options) => ({
478
453
  consola.warn("please run as administrator");
479
454
  return;
480
455
  }
481
- if (process3.env.NODE_ENV !== "development")
456
+ if (process4.env.NODE_ENV !== "development")
482
457
  return;
483
458
  const {
484
459
  enable = true,
@@ -494,38 +469,25 @@ var unpluginFactory = (options) => ({
494
469
  const devServer = __spreadValues(__spreadValues({
495
470
  host: "localhost",
496
471
  port: 8080
497
- }, compiler.options.devServer), process3.VUE_CLI_SERVICE.projectOptions.devServer);
472
+ }, compiler.options.devServer), process4.VUE_CLI_SERVICE.projectOptions.devServer);
498
473
  const source = `${devServer.host}:${devServer.port}`;
499
474
  if (caddy)
500
475
  return;
501
476
  const _close = (_a = compiler.close) == null ? void 0 : _a.bind(compiler);
502
477
  if (_close) {
503
478
  compiler.close = async (callback) => {
504
- try {
505
- _stop && await _stop(() => {
506
- _close && _close(callback);
507
- });
508
- } catch (e) {
509
- consola.error(e);
510
- process3.exit(1);
511
- }
479
+ process4.on("exit", () => {
480
+ _close && _close(callback);
481
+ });
512
482
  };
513
483
  } else {
514
484
  options.https = false;
515
- registerExit(async () => {
516
- try {
517
- _stop && await _stop();
518
- } catch (e) {
519
- consola.error(e);
520
- }
521
- });
522
485
  }
523
486
  caddy = new CaddyInstant();
524
- caddy.run(source, target, __spreadValues({}, options)).then((stop) => {
487
+ caddy.run(source, target, __spreadValues({}, options)).then(() => {
525
488
  const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
526
489
  compiler.hooks.done.tap("unplugin-https-reverse-proxy", () => {
527
490
  consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
528
- !_stop && (_stop = once(stop));
529
491
  });
530
492
  }).catch((e) => {
531
493
  throw e;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  unpluginFactory
3
- } from "./chunk-S4DC5XL4.js";
3
+ } from "./chunk-TVCN6ESH.js";
4
4
 
5
5
  // src/webpack.ts
6
6
  import { createWebpackPlugin } from "unplugin";