unplugin-https-reverse-proxy 0.0.11 → 0.0.13

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,4 +1,8 @@
1
1
  import { createServer } from 'node:net'
2
+ import ora from 'ora'
3
+ import { consola } from '../utils'
4
+
5
+ let spinner: ora.Ora
2
6
 
3
7
  /**
4
8
  * @returns whether the port is in use
@@ -23,3 +27,40 @@ export function tryPort(port: number) {
23
27
  }
24
28
  })
25
29
  }
30
+
31
+ function getNumber(number: number) {
32
+ if (number <= 0)
33
+ return '0%'
34
+ else if (number < 100)
35
+ return `${number.toFixed(2)}%`
36
+ else
37
+ return '100%'
38
+ }
39
+
40
+ export function logProgress(percent: number | string) {
41
+ if (!spinner) {
42
+ // empty a line before start
43
+ consola.log('')
44
+ spinner = ora({
45
+ text: 'Start Download Caddy: 0%',
46
+ indent: 2,
47
+ })
48
+ spinner.start()
49
+ }
50
+ else { spinner.text = `Download Caddy: ${getNumber(Number(percent) * 100)}` }
51
+ }
52
+
53
+ export function logProgressOver() {
54
+ if (!spinner) {
55
+ spinner = ora({
56
+ text: 'Start Download Caddy: 100%',
57
+ indent: 2,
58
+ })
59
+ spinner.start()
60
+ }
61
+ else {
62
+ spinner.succeed()
63
+ // empty a line after succeed
64
+ consola.log('')
65
+ }
66
+ }
package/src/index.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import process from 'node:process'
2
2
  import type { UnpluginFactory } from 'unplugin'
3
3
  import { createUnplugin } from 'unplugin'
4
- import type { ResolvedConfig } from 'vite'
4
+ import type { ResolvedConfig, ViteDevServer } from 'vite'
5
5
  import c from 'picocolors'
6
- import { consola } from './utils'
6
+ import { consola, once } from './utils'
7
7
  import type { Options } from './types'
8
8
  import { CaddyInstant } from './caddy'
9
9
 
@@ -11,21 +11,74 @@ let config: ResolvedConfig
11
11
 
12
12
  let caddy: CaddyInstant
13
13
 
14
+ let _stop: (callback?: () => any) => Promise<any>
15
+ let _servce: ViteDevServer
16
+
17
+ function registerExit(clear: (() => Promise<any>) | (() => any)) {
18
+ process.on('beforeExit', async (_code) => {
19
+ await clear()
20
+ })
21
+
22
+ process.on('uncaughtException', async (err) => {
23
+ console.error('An uncaught error occurred!', err.stack)
24
+ await clear()
25
+ process.nextTick(() => {
26
+ process.exit(1)
27
+ })
28
+ })
29
+
30
+ process.on('unhandledRejection', async (reason, promise) => {
31
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason)
32
+ await clear()
33
+ process.nextTick(() => {
34
+ process.exit(1)
35
+ })
36
+ })
37
+
38
+ process.once('SIGINT', async () => {
39
+ await clear()
40
+ process.emit('SIGINT')
41
+ })
42
+
43
+ process.once('SIGTERM', async () => {
44
+ await clear()
45
+ process.emit('SIGTERM')
46
+ })
47
+ }
48
+
14
49
  export const unpluginFactory: UnpluginFactory<Options> = options => ({
15
50
  name: 'unplugin-https-reverse-proxy',
16
- enforce: 'post',
51
+ enforce: 'pre',
17
52
  vite: {
18
53
  configResolved(_config) {
19
54
  config = _config
55
+ registerExit(async () => {
56
+ try {
57
+ _servce && _servce.close()
58
+ _servce.httpServer?.close(async () => {
59
+ _stop && await _stop()
60
+ })
61
+ _stop && await _stop()
62
+ }
63
+ catch (e) {
64
+ consola.error(e)
65
+ }
66
+ })
20
67
  },
21
68
  configureServer(server) {
22
69
  const {
70
+ enable = true,
23
71
  target = '',
24
72
  } = options
73
+ if (!enable)
74
+ return
25
75
  if (!target) {
26
76
  consola.fail('please provide target')
27
77
  return
28
78
  }
79
+
80
+ _servce = server
81
+
29
82
  const _printUrls = server.printUrls
30
83
  server.printUrls = () => {
31
84
  _printUrls()
@@ -37,19 +90,18 @@ export const unpluginFactory: UnpluginFactory<Options> = options => ({
37
90
  }
38
91
  const base = server.config.base || '/'
39
92
  try {
40
- const caddy = new CaddyInstant()
93
+ if (caddy)
94
+ return
95
+ caddy = new CaddyInstant()
41
96
  caddy.run(source, target, {
42
97
  base,
43
98
  showCaddyLog: options.showCaddyLog,
44
99
  }).then((stop) => {
45
100
  const colorUrl = (url: string) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`))
46
101
  consola.success(` ${c.green('➜')} ${c.bold('run caddy reverse proxy success')}: ${colorUrl(`https://${target}${base}`)}`)
47
-
48
- process.on('SIGINT', async () => {
49
- await stop()
50
- server.close()
51
- process.exit()
52
- })
102
+ !_stop && (_stop = once(stop))
103
+ }).catch((e) => {
104
+ throw e
53
105
  })
54
106
  }
55
107
  catch (e) {
@@ -57,23 +109,59 @@ export const unpluginFactory: UnpluginFactory<Options> = options => ({
57
109
  }
58
110
  }
59
111
  },
112
+ async buildEnd() {
113
+ // https://github.com/vitejs/vite/commit/4338d7d6f32c8e0e67ff58f0cb8c1a9120294756#diff-c0b6eb176448702b6325d2e1b2567c5ccf969f03eef1242950e0bfb18877022fR580
114
+ _stop && await _stop()
115
+ },
60
116
  },
61
117
  webpack(compiler) {
62
118
  const {
119
+ enable = true,
63
120
  target = '',
64
121
  } = options
122
+ if (!enable)
123
+ return
65
124
  if (!target) {
66
125
  consola.fail('please provide target')
67
126
  return
68
127
  }
128
+
69
129
  try {
70
- // @ts-expect-error vuecli
71
- const devServer = compiler.options.devServer || process.VUE_CLI_SERVICE.projectOptions.devServer
72
- const source = `${devServer?.host || '127.0.0.1'}:${devServer?.port || '8080'}`
130
+ registerExit(async () => {
131
+ try {
132
+ _stop && await _stop()
133
+ }
134
+ catch (e) {
135
+ consola.error(e)
136
+ }
137
+ })
138
+
139
+ const devServer = {
140
+ host: '127.0.0.1',
141
+ port: 8080,
142
+ ...compiler.options.devServer,
143
+ // @ts-expect-error vuecli
144
+ ...process.VUE_CLI_SERVICE.projectOptions.devServer,
145
+ }
146
+ const source = `${devServer.host}:${devServer.port}`
73
147
 
74
148
  if (caddy)
75
149
  return
76
150
 
151
+ // https://github.com/webpack/webpack-dev-server/blob/master/lib/Server.js#L1913
152
+ const _close = compiler.close.bind(compiler)
153
+ compiler.close = async (callback: Parameters<typeof _close>[0]) => {
154
+ try {
155
+ _stop && await _stop(() => {
156
+ _close && _close(callback)
157
+ })
158
+ }
159
+ catch (e) {
160
+ consola.error(e)
161
+ process.exit(1)
162
+ }
163
+ }
164
+
77
165
  caddy = new CaddyInstant()
78
166
 
79
167
  caddy.run(source, target, {
@@ -81,16 +169,10 @@ export const unpluginFactory: UnpluginFactory<Options> = options => ({
81
169
  }).then((stop) => {
82
170
  const colorUrl = (url: string) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`))
83
171
 
84
- compiler.hooks.done.tap('unplugin-https-reverse-proxy', (stats) => {
85
- if (stats.hasErrors())
86
- return
87
-
172
+ compiler.hooks.done.tap('unplugin-https-reverse-proxy', () => {
88
173
  consola.success(` ${c.green('➜')} ${c.bold('run caddy reverse proxy success')}: ${colorUrl(`https://${target}`)}`)
89
- })
90
174
 
91
- process.on('SIGINT', async () => {
92
- await stop()
93
- process.exit()
175
+ !_stop && (_stop = once(stop))
94
176
  })
95
177
  }).catch((e) => {
96
178
  throw e
package/src/types.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export interface Options {
2
2
  // define your plugin options here
3
+ enable?: boolean
3
4
  target: string
4
5
  showCaddyLog?: boolean
5
6
  }
package/src/utils.ts CHANGED
@@ -3,3 +3,13 @@ import { createConsola } from 'consola'
3
3
  export const consola = createConsola({
4
4
  level: 3,
5
5
  }).withTag('reverse-proxy')
6
+
7
+ export function once<T extends (...args: any[]) => any>(fn: T): (...args: Parameters<T>) => ReturnType<T> {
8
+ let called = false
9
+ return (...args: any[]) => {
10
+ if (called)
11
+ return
12
+ called = true
13
+ return fn(...args)
14
+ }
15
+ }
@@ -1,9 +0,0 @@
1
- // src/utils.ts
2
- import { createConsola } from "consola";
3
- var consola = createConsola({
4
- level: 3
5
- }).withTag("reverse-proxy");
6
-
7
- export {
8
- consola
9
- };