-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
290 lines (240 loc) · 7.08 KB
/
index.ts
File metadata and controls
290 lines (240 loc) · 7.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import type { UnpluginFactory } from 'unplugin'
import type { ResolvedConfig } from 'vite'
import type { Options } from './types'
import process from 'node:process'
import { Table } from 'console-table-printer'
import c from 'picocolors'
import { createUnplugin } from 'unplugin'
import { CaddyInstant } from './caddy'
import { hmrSseBridgeClientScript, setupHmrSseBridge } from './hmr-sse-bridge'
import { consola, generateQrcode, getIpv4List, isAdmin, once } from './utils'
let config: ResolvedConfig
let caddy: CaddyInstant
let hmrSseBridgeActive = false
const cwd = process.cwd()
function colorUrl(url: string): string {
return c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`))
}
async function printForwardProxy(): Promise<void> {
const ipv4List = getIpv4List()
if (ipv4List.length) {
const ips = ipv4List.map(ip => c.cyan(ip)).join(', ')
consola.info(`${c.bold('Mobile device proxy access')}:\n`)
consola.info('1. Install certificate: scan the QR code and download the \`root.crt\` file,')
consola.info(' then install it on your mobile device')
const ipTable = await Promise.all(
ipv4List.map(async ip => ({
target: `http://${ip}:7601`,
certificate: await generateQrcode(`http://${ip}:7601`),
})),
)
const table = new Table({
columns: [
{ name: 'target', alignment: 'left' },
{ name: 'certificate', alignment: 'center', minLen: 28 },
],
})
ipTable.forEach((ip) => {
table.addRow(ip)
})
table.printTable()
consola.info(`2. Set proxy on mobile device (Available IPs: ${ips}):${c.bold(7600)}\n\n`)
}
}
export const vitePrintUrls = once((
options: Options,
source: string,
target: string,
base: string = '/',
_printUrls?: () => void,
) => {
_printUrls?.()
if (caddy)
return
caddy = new CaddyInstant()
caddy.run(source, target, {
base,
...options,
}).then(async () => {
await printForwardProxy()
consola.success(` ${c.green('➜')} ${c.bold('run caddy reverse proxy success')}: ${colorUrl(`${options.https ? 'https' : 'http'}://${target}${base}`)}`)
}).catch((e) => {
throw e
})
})
export const unpluginFactory: UnpluginFactory<Options> = options => ({
name: 'unplugin-https-reverse-proxy',
enforce: 'pre',
vite: {
configResolved(_config) {
config = _config
},
configureServer(server) {
if (config.command !== 'serve')
return
const {
enable = true,
target = '',
} = options
if (!enable)
return
if (!isAdmin()) {
consola.warn('please run as administrator')
return
}
if (!target) {
consola.fail('please provide target')
return
}
if (target.match(/^(?:https?)?:\/\//)) {
consola.fail('target must be a domain')
return
}
const _printUrls = server.printUrls.bind(server)
let source = `localhost:${config.server.port || 5173}`
const url = server.resolvedUrls?.local[0]
if (url) {
const u = new URL(url)
source = u.host
}
const base = server.config.base || '/'
server.printUrls = () => vitePrintUrls(options, source, target, base, _printUrls)
// Setup SSE bridge for iOS Safari WSS workaround
if (options.https) {
setupHmrSseBridge(server)
hmrSseBridgeActive = true
consola.info('HMR SSE bridge enabled for iOS Safari WSS workaround')
}
},
transformIndexHtml() {
if (!hmrSseBridgeActive)
return []
// Inject client-side script to patch WebSocket on iOS Safari
return [{
tag: 'script',
children: hmrSseBridgeClientScript,
injectTo: 'head-prepend',
}]
},
},
webpack(compiler) {
if (process.env.NODE_ENV !== 'development')
return
const {
enable = true,
target = '',
} = options
if (!enable)
return
if (!isAdmin()) {
consola.warn('please run as administrator')
return
}
if (!target) {
consola.fail('please provide target')
return
}
if (target.match(/^(?:https?)?:\/\//)) {
consola.fail('target must be a domain')
return
}
const devServer = {
host: 'localhost',
port: 8080,
...compiler.options.devServer,
// @ts-expect-error vuecli
...(process.VUE_CLI_SERVICE?.projectOptions.devServer),
}
const source = `${devServer.host}:${devServer.port}`
if (caddy)
return
let base = '/'
const publicPath = compiler.options.output?.publicPath as unknown
if (typeof publicPath === 'string' && publicPath) {
base = publicPath
}
if (!base.startsWith('/'))
base = `/${base}`
if (base !== '/' && !base.endsWith('/'))
base = `${base}/`
// https://github.com/webpack/webpack-dev-server/blob/master/lib/Server.js#L1913
const _close = compiler.close?.bind(compiler)
if (_close) {
compiler.close = async (callback: Parameters<typeof _close>[0]) => {
process.on('exit', () => {
_close && _close(callback)
})
}
}
else {
// webpack 4 not support yet
options.https = false
}
caddy = new CaddyInstant()
caddy.run(source, target, {
base,
...options,
}).then(() => {
compiler.hooks.done.tap('unplugin-https-reverse-proxy', async () => {
await printForwardProxy()
consola.success(` ${c.green('➜')} ${c.bold('run caddy reverse proxy success')}: ${colorUrl(`${options.https ? 'https' : 'http'}://${target}${base}`)}`)
})
}).catch((e) => {
throw e
})
},
async rspack(compiler) {
if (process.env.NODE_ENV !== 'development')
return
const {
enable = true,
target = '',
} = options
if (!enable)
return
if (!isAdmin()) {
consola.warn('please run as administrator')
return
}
if (!target) {
consola.fail('please provide target')
return
}
if (target.match(/^(?:https?)?:\/\//)) {
consola.fail('target must be a domain')
return
}
const devServer = {
host: 'localhost',
port: 8080,
...compiler.options.devServer,
...(await (await import('@rsbuild/core'))?.loadConfig({
cwd,
}))?.content?.server,
}
const source = `${devServer.host}:${devServer.port}`
if (caddy)
return
caddy = new CaddyInstant()
let base = '/'
const publicPath = compiler.options.output?.publicPath as unknown
if (typeof publicPath === 'string' && publicPath) {
base = publicPath
}
if (!base.startsWith('/'))
base = `/${base}`
if (base !== '/' && !base.endsWith('/'))
base = `${base}/`
caddy.run(source, target, {
base,
...options,
}).then(async () => {
await printForwardProxy()
consola.success(` ${c.green('➜')} ${c.bold('run caddy reverse proxy success')}: ${colorUrl(`${options.https ? 'https' : 'http'}://${target}${base}`)}`)
}).catch((e) => {
throw e
})
},
})
export const unplugin = /* #__PURE__ */ createUnplugin(unpluginFactory)
export default unplugin