unplugin-https-reverse-proxy 1.0.0-beta.13 → 1.0.0-beta.15

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.
@@ -1,567 +0,0 @@
1
- import {
2
- __spreadValues,
3
- chmodRecursive,
4
- consola,
5
- isAdmin,
6
- once
7
- } from "./chunk-RUJE3YFB.js";
8
-
9
- // src/index.ts
10
- import process4 from "process";
11
- import { createUnplugin } from "unplugin";
12
- import c from "picocolors";
13
-
14
- // src/caddy/index.ts
15
- import { platform } from "os";
16
- import process3 from "process";
17
- import { chmodSync as chmodSync2, createWriteStream, existsSync, mkdirSync, unlinkSync } from "fs";
18
- import { spawn } from "child_process";
19
- import { got } from "got-cjs";
20
- import { HttpProxyAgent } from "http-proxy-agent";
21
- import { HttpsProxyAgent } from "https-proxy-agent";
22
- import kill from "kill-port";
23
-
24
- // src/host/index.ts
25
- import process from "process";
26
- import { exec } from "child_process";
27
- import { chmodSync } from "fs";
28
- import _Hosts from "hosts-so-easy";
29
- var Hosts = _Hosts.default || _Hosts;
30
- var hostInstance = new Hosts({
31
- debounceTime: 50,
32
- hostsFile: getPathOfSystemHostsPath()
33
- });
34
- function getPathOfSystemHostsPath() {
35
- return process.platform === "win32" ? `${process.env.windir || "C:\\WINDOWS"}\\system32\\drivers\\etc\\hosts` : "/etc/hosts";
36
- }
37
- async function syncHost() {
38
- return new Promise((resolve, reject) => {
39
- exec(
40
- process.platform === "win32" ? "ipconfig /flushdns" : "sudo -E killall -HUP mDNSResponder",
41
- (error, stdout, stderr) => {
42
- if (error) {
43
- consola.error(`exec error: ${error}`);
44
- return resolve(false);
45
- }
46
- return resolve(true);
47
- }
48
- );
49
- });
50
- }
51
- async function addHost(ip, host) {
52
- if (process.platform !== "win32")
53
- chmodSync(getPathOfSystemHostsPath(), 511);
54
- hostInstance.add("127.0.0.1", "localhost");
55
- hostInstance.add(ip, host);
56
- if (ip === "localhost")
57
- hostInstance.add("127.0.0.1", host);
58
- await hostInstance.updateFinish();
59
- return await syncHost();
60
- }
61
- async function removeHost(ip, host) {
62
- if (process.platform !== "win32")
63
- chmodSync(getPathOfSystemHostsPath(), 511);
64
- hostInstance.remove(ip, host);
65
- if (ip === "localhost")
66
- hostInstance.remove("127.0.0.1", host);
67
- await hostInstance.updateFinish();
68
- return await syncHost();
69
- }
70
-
71
- // src/caddy/constants.ts
72
- import { join } from "path";
73
- import os from "os";
74
- import process2 from "process";
75
- import dotenvFlow from "dotenv-flow";
76
- dotenvFlow.config({
77
- silent: true
78
- });
79
- function resolvePath(path) {
80
- if (path.startsWith("~"))
81
- return join(os.homedir() || "", path.slice(1));
82
- return path;
83
- }
84
- var TEMP_DIR = resolvePath(process2.env.UHRP_CADDY_PATH || process2.env.TEMP || process2.env.TMPDIR || "/tmp");
85
- var caddyPath = join(TEMP_DIR, `caddy${process2.platform === "win32" ? ".exe" : ""}`);
86
- var caddyFilePath = join(TEMP_DIR, "CADDYFILE");
87
- var supportList = [
88
- {
89
- platform: "dragonfly",
90
- arch: "amd64"
91
- },
92
- {
93
- platform: "freebsd",
94
- arch: "amd64"
95
- },
96
- {
97
- platform: "freebsd",
98
- arch: "arm-6"
99
- },
100
- {
101
- platform: "freebsd",
102
- arch: "arm-7"
103
- },
104
- {
105
- platform: "freebsd",
106
- arch: "arm64"
107
- },
108
- {
109
- platform: "linux",
110
- arch: "amd64"
111
- },
112
- {
113
- platform: "linux",
114
- arch: "arm-5"
115
- },
116
- {
117
- platform: "linux",
118
- arch: "arm-6"
119
- },
120
- {
121
- platform: "linux",
122
- arch: "arm-7"
123
- },
124
- {
125
- platform: "linux",
126
- arch: "arm64"
127
- },
128
- {
129
- platform: "linux",
130
- arch: "mips"
131
- },
132
- {
133
- platform: "linux",
134
- arch: "mips64"
135
- },
136
- {
137
- platform: "linux",
138
- arch: "mips64le"
139
- },
140
- {
141
- platform: "linux",
142
- arch: "mipsle"
143
- },
144
- {
145
- platform: "linux",
146
- arch: "ppc64"
147
- },
148
- {
149
- platform: "linux",
150
- arch: "ppc64le"
151
- },
152
- {
153
- platform: "linux",
154
- arch: "s390x"
155
- },
156
- {
157
- platform: "darwin",
158
- arch: "amd64"
159
- },
160
- {
161
- platform: "darwin",
162
- arch: "arm64"
163
- },
164
- {
165
- platform: "openbsd",
166
- arch: "amd64"
167
- },
168
- {
169
- platform: "openbsd",
170
- arch: "arm-6"
171
- },
172
- {
173
- platform: "openbsd",
174
- arch: "arm-7"
175
- },
176
- {
177
- platform: "openbsd",
178
- arch: "arm64"
179
- },
180
- {
181
- platform: "windows",
182
- arch: "amd64"
183
- },
184
- {
185
- platform: "windows",
186
- arch: "arm-6"
187
- },
188
- {
189
- platform: "windows",
190
- arch: "arm-7"
191
- },
192
- {
193
- platform: "windows",
194
- arch: "arm64"
195
- }
196
- ];
197
-
198
- // src/caddy/utils.ts
199
- import { createServer } from "net";
200
- import ora from "ora";
201
- var spinner;
202
- function tryPort(port) {
203
- return new Promise((resolve, reject) => {
204
- try {
205
- const server = createServer().listen(port);
206
- server.on("listening", () => {
207
- server.close();
208
- resolve(false);
209
- });
210
- server.on("error", (err) => {
211
- if (err.code === "EADDRINUSE")
212
- resolve(true);
213
- server.close();
214
- });
215
- } catch (e) {
216
- resolve(true);
217
- }
218
- });
219
- }
220
- function getNumber(number) {
221
- if (number <= 0)
222
- return "0%";
223
- else if (number < 100)
224
- return `${number.toFixed(2)}%`;
225
- else
226
- return "100%";
227
- }
228
- function logProgress(percent) {
229
- if (!spinner) {
230
- consola.log("");
231
- spinner = ora({
232
- text: "Start Download Caddy: 0%",
233
- indent: 2
234
- });
235
- spinner.start();
236
- } else {
237
- spinner.text = `Download Caddy: ${getNumber(Number(percent) * 100)}`;
238
- }
239
- }
240
- function logProgressOver() {
241
- if (!spinner) {
242
- spinner = ora({
243
- text: "Start Download Caddy: 100%",
244
- indent: 2
245
- });
246
- spinner.start();
247
- } else {
248
- spinner.succeed();
249
- consola.log("");
250
- }
251
- }
252
-
253
- // src/caddy/index.ts
254
- async function download() {
255
- if (await testCaddy())
256
- return caddyPath;
257
- return new Promise((resolve, reject) => {
258
- if (!existsSync(TEMP_DIR)) {
259
- mkdirSync(TEMP_DIR, { recursive: true });
260
- chmodSync2(TEMP_DIR, 511);
261
- }
262
- const file = createWriteStream(caddyPath);
263
- let _platform = platform().toString();
264
- _platform === "win32" && (_platform = "windows");
265
- let _arch = process3.arch.toString();
266
- _arch === "x64" && (_arch = "amd64");
267
- const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
268
- if (!support)
269
- return reject(new Error("not support"));
270
- const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}`;
271
- existsSync(caddyPath) && unlinkSync(caddyPath);
272
- const httpProxy = process3.env.HTTP_PROXY || process3.env.http_proxy;
273
- const httpsProxy = process3.env.HTTPS_PROXY || process3.env.https_proxy;
274
- const httpAgent = httpProxy ? new HttpProxyAgent(httpProxy) : void 0;
275
- const httpsAgent = httpsProxy ? new HttpsProxyAgent(httpsProxy) : void 0;
276
- const chmodCaddyOnce = once(() => {
277
- chmodSync2(caddyPath, 511);
278
- });
279
- got.stream(dowmloadLink, {
280
- agent: {
281
- http: httpAgent,
282
- https: httpsAgent
283
- }
284
- }).on("downloadProgress", (progress) => {
285
- logProgress(progress.percent);
286
- chmodCaddyOnce();
287
- }).pipe(file).on("finish", () => {
288
- logProgressOver();
289
- if (process3.platform === "win32")
290
- return resolve(caddyPath);
291
- chmodSync2(caddyPath, 511);
292
- resolve(caddyPath);
293
- }).on("error", (err) => {
294
- reject(err);
295
- });
296
- });
297
- }
298
- function testCaddy() {
299
- return new Promise((resolve, reject) => {
300
- if (!existsSync(caddyPath))
301
- return resolve(false);
302
- chmodSync2(caddyPath, 511);
303
- const child = process3.platform === "win32" ? spawn(caddyPath, []) : spawn("sudo", ["-E", caddyPath]);
304
- child.on("close", () => {
305
- return resolve(false);
306
- });
307
- child.on("error", (err) => {
308
- return reject(err);
309
- });
310
- child.stdout.on("data", (_data) => {
311
- return resolve(true);
312
- });
313
- });
314
- }
315
- var CaddyInstant = class {
316
- constructor() {
317
- this.inited = false;
318
- this.stoped = false;
319
- testCaddy().then(() => {
320
- this.inited = true;
321
- });
322
- }
323
- async init() {
324
- await download();
325
- this.inited = true;
326
- }
327
- /**
328
- * @param source like `127.0.0.1:8080`
329
- * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
330
- * @returns
331
- */
332
- async run(source, target, options) {
333
- source = source.replace("0.0.0.0", "127.0.0.1");
334
- const {
335
- restore = true,
336
- base = "/",
337
- showCaddyLog = false,
338
- https = false
339
- } = options || {};
340
- if (!this.inited)
341
- await this.init();
342
- if (https && await tryPort(443))
343
- await kill(443, "tcp");
344
- if ((process3.platform === "win32" || !https) && await tryPort(80))
345
- await kill(80, "tcp");
346
- if (!await addHost(source.split(":")[0], target.split(":")[0]))
347
- throw new Error("update host failed");
348
- consola.success("update host success\n");
349
- return new Promise((resolve, reject) => {
350
- 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"]);
351
- child.on("error", (err) => {
352
- return reject(err);
353
- });
354
- child.stderr.on("data", (data) => {
355
- const lines = data.toString().split("\n").map((line) => line.trim());
356
- for (const line of lines) {
357
- showCaddyLog && line && console.info(line);
358
- if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
359
- consola.error(line);
360
- return reject(line);
361
- }
362
- if (line.includes("caddy proxying"))
363
- return resolve();
364
- }
365
- });
366
- child.stdout.on("data", (_data) => {
367
- consola.info(_data.toString());
368
- resolve();
369
- });
370
- process3.on("SIGINT", async () => {
371
- if (!restore || this.stoped)
372
- return;
373
- try {
374
- if (await removeHost(source.split(":")[0], target.split(":")[0]))
375
- consola.success("restore host success\n");
376
- else
377
- consola.fail("restore host failed\n");
378
- } catch (e) {
379
- consola.error(e);
380
- consola.fail("restore host failed\n");
381
- } finally {
382
- this.stoped = true;
383
- process3.nextTick(() => {
384
- process3.exit();
385
- });
386
- }
387
- });
388
- const originalExit = process3.exit.bind(process3);
389
- process3.exit = async (code) => {
390
- const port = Number(source.split(":")[1]);
391
- if (!Number.isNaN(port) && await tryPort(port))
392
- await kill(port, "tcp");
393
- const pwd = process3.cwd();
394
- const viteCacheDir = `${pwd}/node_modules/.vite`;
395
- if (existsSync(viteCacheDir))
396
- chmodRecursive(viteCacheDir, 511);
397
- const nuxtCacheDir = `${pwd}/.nuxt`;
398
- if (existsSync(nuxtCacheDir))
399
- await chmodRecursive(nuxtCacheDir, 511);
400
- const webpackCacheDir = `${pwd}/node_modules/.cache`;
401
- if (existsSync(webpackCacheDir))
402
- chmodRecursive(webpackCacheDir, 511);
403
- if (!restore || this.stoped)
404
- return originalExit(code);
405
- try {
406
- if (await removeHost(source.split(":")[0], target.split(":")[0]))
407
- consola.success("restore host success\n");
408
- else
409
- consola.fail("restore host failed\n");
410
- } catch (e) {
411
- consola.error(e);
412
- consola.fail("restore host failed\n");
413
- } finally {
414
- this.stoped = true;
415
- process3.nextTick(() => {
416
- originalExit(code);
417
- });
418
- }
419
- };
420
- });
421
- }
422
- };
423
-
424
- // src/index.ts
425
- var config;
426
- var caddy;
427
- var cwd = process4.cwd();
428
- var vitePrintUrls = once((options, source, target, base = "/", _printUrls) => {
429
- _printUrls == null ? void 0 : _printUrls();
430
- if (caddy)
431
- return;
432
- caddy = new CaddyInstant();
433
- caddy.run(source, target, __spreadValues({
434
- base
435
- }, options)).then(() => {
436
- const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
437
- consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
438
- }).catch((e) => {
439
- throw e;
440
- });
441
- });
442
- var unpluginFactory = (options) => ({
443
- name: "unplugin-https-reverse-proxy",
444
- enforce: "pre",
445
- vite: {
446
- configResolved(_config) {
447
- config = _config;
448
- },
449
- configureServer(server) {
450
- var _a;
451
- if (config.command !== "serve")
452
- return;
453
- const {
454
- enable = true,
455
- target = ""
456
- } = options;
457
- if (!enable)
458
- return;
459
- if (!isAdmin()) {
460
- consola.warn("please run as administrator");
461
- return;
462
- }
463
- if (!target) {
464
- consola.fail("please provide target");
465
- return;
466
- }
467
- const _printUrls = server.printUrls.bind(server);
468
- let source = `localhost:${config.server.port || 5173}`;
469
- const url = (_a = server.resolvedUrls) == null ? void 0 : _a.local[0];
470
- if (url) {
471
- const u = new URL(url);
472
- source = u.host;
473
- }
474
- const base = server.config.base || "/";
475
- server.printUrls = () => vitePrintUrls(options, source, target, base, _printUrls);
476
- }
477
- },
478
- webpack(compiler) {
479
- var _a, _b;
480
- if (process4.env.NODE_ENV !== "development")
481
- return;
482
- const {
483
- enable = true,
484
- target = ""
485
- } = options;
486
- if (!enable)
487
- return;
488
- if (!isAdmin()) {
489
- consola.warn("please run as administrator");
490
- return;
491
- }
492
- if (!target) {
493
- consola.fail("please provide target");
494
- return;
495
- }
496
- const devServer = __spreadValues(__spreadValues({
497
- host: "localhost",
498
- port: 8080
499
- }, compiler.options.devServer), (_a = process4.VUE_CLI_SERVICE) == null ? void 0 : _a.projectOptions.devServer);
500
- const source = `${devServer.host}:${devServer.port}`;
501
- if (caddy)
502
- return;
503
- const _close = (_b = compiler.close) == null ? void 0 : _b.bind(compiler);
504
- if (_close) {
505
- compiler.close = async (callback) => {
506
- process4.on("exit", () => {
507
- _close && _close(callback);
508
- });
509
- };
510
- } else {
511
- options.https = false;
512
- }
513
- caddy = new CaddyInstant();
514
- caddy.run(source, target, __spreadValues({}, options)).then(() => {
515
- const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
516
- compiler.hooks.done.tap("unplugin-https-reverse-proxy", () => {
517
- consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
518
- });
519
- }).catch((e) => {
520
- throw e;
521
- });
522
- },
523
- async rspack(compiler) {
524
- var _a, _b, _c;
525
- if (process4.env.NODE_ENV !== "development")
526
- return;
527
- const {
528
- enable = true,
529
- target = ""
530
- } = options;
531
- if (!enable)
532
- return;
533
- if (!isAdmin()) {
534
- consola.warn("please run as administrator");
535
- return;
536
- }
537
- if (!target) {
538
- consola.fail("please provide target");
539
- return;
540
- }
541
- const devServer = __spreadValues(__spreadValues({
542
- host: "localhost",
543
- port: 8080
544
- }, compiler.options.devServer), (_c = (_b = await ((_a = await import("@rsbuild/core")) == null ? void 0 : _a.loadConfig({
545
- cwd
546
- }))) == null ? void 0 : _b.content) == null ? void 0 : _c.server);
547
- const source = `${devServer.host}:${devServer.port}`;
548
- if (caddy)
549
- return;
550
- caddy = new CaddyInstant();
551
- caddy.run(source, target, __spreadValues({}, options)).then(() => {
552
- const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
553
- consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
554
- }).catch((e) => {
555
- throw e;
556
- });
557
- }
558
- });
559
- var unplugin = /* @__PURE__ */ createUnplugin(unpluginFactory);
560
- var src_default = unplugin;
561
-
562
- export {
563
- vitePrintUrls,
564
- unpluginFactory,
565
- unplugin,
566
- src_default
567
- };