unplugin-https-reverse-proxy 1.0.0-beta.0 → 1.0.0-beta.10

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/README.md CHANGED
@@ -2,10 +2,19 @@
2
2
 
3
3
  [![NPM version](https://img.shields.io/npm/v/unplugin-https-reverse-proxy?color=a1b858&label=)](https://www.npmjs.com/package/unplugin-https-reverse-proxy)
4
4
 
5
- A plugin for https reverse proxy, support `vite` and `webpack`.
5
+ A plugin for https reverse proxy, support `vite`、`webpack` and `rspack`.
6
6
 
7
7
  ## Install
8
8
 
9
+
10
+ Support set caddy file path by environment variable `UHRP_CADDY_PATH`, default is system cache folder.
11
+
12
+ ```env
13
+ #.env.local
14
+ UHRP_CADDY_PATH=~/tmp/.uhrp
15
+ ```
16
+
17
+
9
18
  ```bash
10
19
  # not auto install caddy when postinstall
11
20
  npm i unplugin-https-reverse-proxy --save-dev
@@ -115,6 +124,90 @@ module.exports = {
115
124
 
116
125
  <br></details>
117
126
 
127
+ <details>
128
+ <summary>Rspack</summary><br>
129
+
130
+ ```js
131
+ // rspack.config.js
132
+
133
+ /** @type {Parameters<import('unplugin-https-reverse-proxy/webpack')['default']>[0]} */
134
+ const reverseProxyOptions = {
135
+ enable: false,
136
+ target: 'xxx',
137
+ https: false,
138
+ }
139
+
140
+ module.exports = {
141
+ /* ... */
142
+ devServer: {
143
+ client: {
144
+ // ↓ for HMR
145
+ webSocketURL: {
146
+ ...(reverseProxyOptions.enable
147
+ ? {
148
+ hostname: reverseProxyOptions.target,
149
+ }
150
+ : {}),
151
+ ...(reverseProxyOptions.enable && reverseProxyOptions.https
152
+ ? {
153
+ protocol: 'wss',
154
+ port: 443,
155
+ }
156
+ : {})
157
+ }
158
+ },
159
+ },
160
+ plugins: [
161
+ require('unplugin-https-reverse-proxy/rspack')(reverseProxyOptions)
162
+ ]
163
+ }
164
+ ```
165
+
166
+ <br></details>
167
+
168
+ <details>
169
+ <summary>Rsbuild</summary><br>
170
+
171
+ ```js
172
+ // rsbuild.config.js
173
+
174
+ /** @type {Parameters<import('unplugin-https-reverse-proxy/webpack')['default']>[0]} */
175
+ const reverseProxyOptions = {
176
+ enable: false,
177
+ target: 'xxx',
178
+ https: false,
179
+ }
180
+
181
+ module.exports = {
182
+ /* ... */
183
+ dev: {
184
+ client: {
185
+ // ↓ for HMR
186
+ ...(reverseProxyOptions.enable
187
+ ? {
188
+ host: reverseProxyOptions.target,
189
+ }
190
+ : {}),
191
+ ...(reverseProxyOptions.enable && reverseProxyOptions.https
192
+ ? {
193
+ protocol: 'wss',
194
+ port: '443',
195
+ }
196
+ : {})
197
+ },
198
+ },
199
+ tools: {
200
+ rspack: {
201
+ plugins: [
202
+ require('unplugin-https-reverse-proxy/rspack')(reverseProxyOptions)
203
+ ]
204
+ },
205
+ },
206
+ }
207
+ ```
208
+
209
+ <br></details>
210
+
118
211
  <details>
119
212
  <summary>Nuxt</summary><br>
120
213
 
@@ -17,11 +17,30 @@ var __spreadValues = (a, b) => {
17
17
 
18
18
  // src/utils.ts
19
19
  import process from "process";
20
+ import path from "path";
21
+ import { chmod, readdir, stat } from "fs/promises";
20
22
  import { execSync } from "child_process";
21
23
  import { createConsola } from "consola";
22
24
  var consola = createConsola({
23
25
  level: 3
24
26
  }).withTag("reverse-proxy");
27
+ async function chmodRecursive(_path, mode) {
28
+ await chmod(_path, mode);
29
+ if ((await stat(_path)).isDirectory()) {
30
+ const children = await readdir(_path);
31
+ for (const child of children)
32
+ await chmodRecursive(path.join(_path, child), mode);
33
+ }
34
+ }
35
+ function once(fn) {
36
+ let called = false;
37
+ return (...args) => {
38
+ if (called)
39
+ return;
40
+ called = true;
41
+ return fn(...args);
42
+ };
43
+ }
25
44
  function isAdmin() {
26
45
  if (process.platform === "win32") {
27
46
  try {
@@ -38,5 +57,7 @@ function isAdmin() {
38
57
  export {
39
58
  __spreadValues,
40
59
  consola,
60
+ chmodRecursive,
61
+ once,
41
62
  isAdmin
42
63
  };
@@ -1,19 +1,20 @@
1
1
  import {
2
2
  __spreadValues,
3
+ chmodRecursive,
3
4
  consola,
4
- isAdmin
5
- } from "./chunk-3RTK3FSZ.js";
5
+ isAdmin,
6
+ once
7
+ } from "./chunk-RUJE3YFB.js";
6
8
 
7
9
  // src/index.ts
8
10
  import process4 from "process";
9
- import { chmodSync as chmodSync3, existsSync as existsSync2 } from "fs";
10
11
  import { createUnplugin } from "unplugin";
11
12
  import c from "picocolors";
12
13
 
13
14
  // src/caddy/index.ts
14
15
  import { platform } from "os";
15
16
  import process3 from "process";
16
- import { chmodSync as chmodSync2, createWriteStream, existsSync, unlinkSync } from "fs";
17
+ import { chmodSync as chmodSync2, createWriteStream, existsSync, mkdirSync, unlinkSync } from "fs";
17
18
  import { spawn } from "child_process";
18
19
  import { got } from "got-cjs";
19
20
  import { HttpProxyAgent } from "http-proxy-agent";
@@ -39,7 +40,7 @@ async function syncHost() {
39
40
  process.platform === "win32" ? "ipconfig /flushdns" : "sudo -E killall -HUP mDNSResponder",
40
41
  (error, stdout, stderr) => {
41
42
  if (error) {
42
- console.error(`exec error: ${error}`);
43
+ consola.error(`exec error: ${error}`);
43
44
  return resolve(false);
44
45
  }
45
46
  return resolve(true);
@@ -52,6 +53,8 @@ async function addHost(ip, host) {
52
53
  chmodSync(getPathOfSystemHostsPath(), 511);
53
54
  hostInstance.add("127.0.0.1", "localhost");
54
55
  hostInstance.add(ip, host);
56
+ if (ip === "localhost")
57
+ hostInstance.add("127.0.0.1", host);
55
58
  await hostInstance.updateFinish();
56
59
  return await syncHost();
57
60
  }
@@ -67,8 +70,18 @@ async function removeHost(ip, host) {
67
70
 
68
71
  // src/caddy/constants.ts
69
72
  import { join } from "path";
73
+ import os from "os";
70
74
  import process2 from "process";
71
- var TEMP_DIR = process2.env.TEMP || process2.env.TMPDIR || "/tmp";
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");
72
85
  var caddyPath = join(TEMP_DIR, `caddy${process2.platform === "win32" ? ".exe" : ""}`);
73
86
  var caddyFilePath = join(TEMP_DIR, "CADDYFILE");
74
87
  var supportList = [
@@ -242,6 +255,10 @@ async function download() {
242
255
  if (await testCaddy())
243
256
  return caddyPath;
244
257
  return new Promise((resolve, reject) => {
258
+ if (!existsSync(TEMP_DIR)) {
259
+ mkdirSync(TEMP_DIR, { recursive: true });
260
+ chmodSync2(TEMP_DIR, 511);
261
+ }
245
262
  const file = createWriteStream(caddyPath);
246
263
  let _platform = platform().toString();
247
264
  _platform === "win32" && (_platform = "windows");
@@ -256,6 +273,9 @@ async function download() {
256
273
  const httpsProxy = process3.env.HTTPS_PROXY || process3.env.https_proxy;
257
274
  const httpAgent = httpProxy ? new HttpProxyAgent(httpProxy) : void 0;
258
275
  const httpsAgent = httpsProxy ? new HttpsProxyAgent(httpsProxy) : void 0;
276
+ const chmodCaddyOnce = once(() => {
277
+ chmodSync2(caddyPath, 511);
278
+ });
259
279
  got.stream(dowmloadLink, {
260
280
  agent: {
261
281
  http: httpAgent,
@@ -263,11 +283,12 @@ async function download() {
263
283
  }
264
284
  }).on("downloadProgress", (progress) => {
265
285
  logProgress(progress.percent);
286
+ chmodCaddyOnce();
266
287
  }).pipe(file).on("finish", () => {
267
288
  logProgressOver();
268
289
  if (process3.platform === "win32")
269
290
  return resolve(caddyPath);
270
- chmodSync2(caddyPath, 493);
291
+ chmodSync2(caddyPath, 511);
271
292
  resolve(caddyPath);
272
293
  }).on("error", (err) => {
273
294
  reject(err);
@@ -278,7 +299,7 @@ function testCaddy() {
278
299
  return new Promise((resolve, reject) => {
279
300
  if (!existsSync(caddyPath))
280
301
  return resolve(false);
281
- chmodSync2(caddyPath, 493);
302
+ chmodSync2(caddyPath, 511);
282
303
  const child = process3.platform === "win32" ? spawn(caddyPath, []) : spawn("sudo", ["-E", caddyPath]);
283
304
  child.on("close", () => {
284
305
  return resolve(false);
@@ -350,6 +371,19 @@ var CaddyInstant = class {
350
371
  });
351
372
  const originalExit = process3.exit.bind(process3);
352
373
  process3.exit = async (code) => {
374
+ const port = Number(source.split(":")[1]);
375
+ if (!Number.isNaN(port) && await tryPort(port))
376
+ await kill(port, "tcp");
377
+ const pwd = process3.cwd();
378
+ const viteCacheDir = `${pwd}/node_modules/.vite`;
379
+ if (existsSync(viteCacheDir))
380
+ chmodRecursive(viteCacheDir, 511);
381
+ const nuxtCacheDir = `${pwd}/.nuxt`;
382
+ if (existsSync(nuxtCacheDir))
383
+ await chmodRecursive(nuxtCacheDir, 511);
384
+ const webpackCacheDir = `${pwd}/node_modules/.cache`;
385
+ if (existsSync(webpackCacheDir))
386
+ chmodRecursive(webpackCacheDir, 511);
353
387
  if (!restore || this.stoped)
354
388
  return originalExit(code);
355
389
  try {
@@ -388,7 +422,21 @@ var CaddyInstant = class {
388
422
  // src/index.ts
389
423
  var config;
390
424
  var caddy;
391
- var _servce;
425
+ var cwd = process4.cwd();
426
+ var vitePrintUrls = once((options, source, target, base = "/", _printUrls) => {
427
+ _printUrls == null ? void 0 : _printUrls();
428
+ if (caddy)
429
+ return;
430
+ caddy = new CaddyInstant();
431
+ caddy.run(source, target, __spreadValues({
432
+ base
433
+ }, options)).then(() => {
434
+ const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
435
+ consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
436
+ }).catch((e) => {
437
+ throw e;
438
+ });
439
+ });
392
440
  var unpluginFactory = (options) => ({
393
441
  name: "unplugin-https-reverse-proxy",
394
442
  enforce: "pre",
@@ -397,11 +445,8 @@ var unpluginFactory = (options) => ({
397
445
  config = _config;
398
446
  },
399
447
  configureServer(server) {
400
- if (!isAdmin()) {
401
- consola.warn("please run as administrator");
402
- return;
403
- }
404
- if (config.command === "build")
448
+ var _a;
449
+ if (config.command !== "serve")
405
450
  return;
406
451
  const {
407
452
  enable = true,
@@ -409,50 +454,72 @@ var unpluginFactory = (options) => ({
409
454
  } = options;
410
455
  if (!enable)
411
456
  return;
457
+ if (!isAdmin()) {
458
+ consola.warn("please run as administrator");
459
+ return;
460
+ }
412
461
  if (!target) {
413
462
  consola.fail("please provide target");
414
463
  return;
415
464
  }
416
- _servce = server;
417
- const _printUrls = server.printUrls;
418
- server.printUrls = () => {
419
- var _a;
420
- _printUrls();
421
- const pwd = process4.cwd();
422
- const vireCacheDir = `${pwd}/node_modules/.vite`;
423
- if (existsSync2(vireCacheDir))
424
- chmodSync3(vireCacheDir, 511);
425
- let source = `localhost:${config.server.port}`;
426
- const url = (_a = server.resolvedUrls) == null ? void 0 : _a.local[0];
427
- if (url) {
428
- const u = new URL(url);
429
- source = u.host;
430
- }
431
- const base = server.config.base || "/";
432
- try {
433
- if (caddy)
434
- return;
435
- caddy = new CaddyInstant();
436
- caddy.run(source, target, __spreadValues({
437
- base
438
- }, options)).then(() => {
439
- const colorUrl = (url2) => c.green(url2.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
440
- consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
441
- }).catch((e) => {
442
- throw e;
443
- });
444
- } catch (e) {
445
- consola.error(e);
446
- }
447
- };
465
+ const _printUrls = server.printUrls.bind(server);
466
+ let source = `localhost:${config.server.port || 5173}`;
467
+ const url = (_a = server.resolvedUrls) == null ? void 0 : _a.local[0];
468
+ if (url) {
469
+ const u = new URL(url);
470
+ source = u.host;
471
+ }
472
+ const base = server.config.base || "/";
473
+ server.printUrls = () => vitePrintUrls(options, source, target, base, _printUrls);
448
474
  }
449
475
  },
450
476
  webpack(compiler) {
451
- var _a;
477
+ var _a, _b;
478
+ if (process4.env.NODE_ENV !== "development")
479
+ return;
480
+ const {
481
+ enable = true,
482
+ target = ""
483
+ } = options;
484
+ if (!enable)
485
+ return;
452
486
  if (!isAdmin()) {
453
487
  consola.warn("please run as administrator");
454
488
  return;
455
489
  }
490
+ if (!target) {
491
+ consola.fail("please provide target");
492
+ return;
493
+ }
494
+ const devServer = __spreadValues(__spreadValues({
495
+ host: "localhost",
496
+ port: 8080
497
+ }, compiler.options.devServer), (_a = process4.VUE_CLI_SERVICE) == null ? void 0 : _a.projectOptions.devServer);
498
+ const source = `${devServer.host}:${devServer.port}`;
499
+ if (caddy)
500
+ return;
501
+ const _close = (_b = compiler.close) == null ? void 0 : _b.bind(compiler);
502
+ if (_close) {
503
+ compiler.close = async (callback) => {
504
+ process4.on("exit", () => {
505
+ _close && _close(callback);
506
+ });
507
+ };
508
+ } else {
509
+ options.https = false;
510
+ }
511
+ caddy = new CaddyInstant();
512
+ caddy.run(source, target, __spreadValues({}, options)).then(() => {
513
+ const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
514
+ compiler.hooks.done.tap("unplugin-https-reverse-proxy", () => {
515
+ consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
516
+ });
517
+ }).catch((e) => {
518
+ throw e;
519
+ });
520
+ },
521
+ async rspack(compiler) {
522
+ var _a, _b, _c;
456
523
  if (process4.env.NODE_ENV !== "development")
457
524
  return;
458
525
  const {
@@ -461,46 +528,37 @@ var unpluginFactory = (options) => ({
461
528
  } = options;
462
529
  if (!enable)
463
530
  return;
531
+ if (!isAdmin()) {
532
+ consola.warn("please run as administrator");
533
+ return;
534
+ }
464
535
  if (!target) {
465
536
  consola.fail("please provide target");
466
537
  return;
467
538
  }
468
- try {
469
- const devServer = __spreadValues(__spreadValues({
470
- host: "localhost",
471
- port: 8080
472
- }, compiler.options.devServer), process4.VUE_CLI_SERVICE.projectOptions.devServer);
473
- const source = `${devServer.host}:${devServer.port}`;
474
- if (caddy)
475
- return;
476
- const _close = (_a = compiler.close) == null ? void 0 : _a.bind(compiler);
477
- if (_close) {
478
- compiler.close = async (callback) => {
479
- process4.on("exit", () => {
480
- _close && _close(callback);
481
- });
482
- };
483
- } else {
484
- options.https = false;
485
- }
486
- caddy = new CaddyInstant();
487
- caddy.run(source, target, __spreadValues({}, options)).then(() => {
488
- const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
489
- compiler.hooks.done.tap("unplugin-https-reverse-proxy", () => {
490
- consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
491
- });
492
- }).catch((e) => {
493
- throw e;
494
- });
495
- } catch (e) {
496
- consola.error(e);
497
- }
539
+ const devServer = __spreadValues(__spreadValues({
540
+ host: "localhost",
541
+ port: 8080
542
+ }, compiler.options.devServer), (_c = (_b = await ((_a = await import("@rsbuild/core")) == null ? void 0 : _a.loadConfig({
543
+ cwd
544
+ }))) == null ? void 0 : _b.content) == null ? void 0 : _c.server);
545
+ const source = `${devServer.host}:${devServer.port}`;
546
+ if (caddy)
547
+ return;
548
+ caddy = new CaddyInstant();
549
+ caddy.run(source, target, __spreadValues({}, options)).then(() => {
550
+ const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
551
+ consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
552
+ }).catch((e) => {
553
+ throw e;
554
+ });
498
555
  }
499
556
  });
500
557
  var unplugin = /* @__PURE__ */ createUnplugin(unpluginFactory);
501
558
  var src_default = unplugin;
502
559
 
503
560
  export {
561
+ vitePrintUrls,
504
562
  unpluginFactory,
505
563
  unplugin,
506
564
  src_default