This repository has been archived by the owner on Dec 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
module.ts
224 lines (191 loc) · 7.58 KB
/
module.ts
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
import { addServerHandler, addTemplate, addPluginTemplate, createResolver, defineNuxtModule } from '@nuxt/kit'
import { name, version } from '../package.json'
import { ModuleOptions, ProxyOptions } from './types'
import { defu } from 'defu'
const CONFIG_KEY = 'proxy'
export default defineNuxtModule({
meta: {
name,
version,
configKey: CONFIG_KEY,
compatibility: {
nuxt: '^3.0.0'
}
},
defaults: {
enableProxy: true,
fetch: false
},
setup(options, nuxt) {
const config = (nuxt.options.runtimeConfig.proxy = defu(nuxt.options.runtimeConfig.proxy, options)) as ModuleOptions
const resolver = createResolver(import.meta.url)
const defaultHost = process.env.NITRO_HOST || process.env.HOST || 'localhost'
const defaultPort = process.env.NITRO_PORT || process.env.PORT || 3000
if (config.enableProxy) {
// Create Proxy
addTemplate({
filename: 'nuxt-proxy.ts',
write: true,
getContents: () => proxyMiddlewareContent(config.proxies ?? {})
})
addServerHandler({
handler: resolver.resolve(nuxt.options.buildDir, 'nuxt-proxy.ts'),
middleware: true
})
}
if (config.fetch) {
// Create Interceptor
addPluginTemplate({
src: resolver.resolve('runtime/fetch.interceptor.mjs'),
filename: 'fetch.interceptor.mjs',
options: config
})
nuxt.options.build.transpile.push(resolver.resolve('runtime'))
}
// Don't know if it runs on windows still.
if (config.fetch && process.platform !== "win32") {
// create nitro plugin
addTemplate({
getContents: () => nitroFetchProxy(defaultHost, defaultPort),
filename: 'nitro-fetch.mjs',
write: true
})
nuxt.hook('nitro:config', (nitro) => {
nitro.plugins = nitro.plugins || []
nitro.plugins.push(resolver.resolve(nuxt.options.buildDir, 'nitro-fetch.mjs'))
})
}
}
})
function nitroFetchProxy(host: string, port: number | string): string {
return `import { createFetch, Headers } from 'ofetch'
export default function (nitroApp) {
// the proxy module needs the host and port of the nitro server in order for it to proxy it properly.
// By default only a path is being submitted so this will chnage it to the host and port
globalThis.$fetch = createFetch({ fetch: nitroApp.localFetch, Headers, defaults: { baseURL: 'http://${host}:${port}' } })
}
`
}
function converter(key: string, val: any) {
if (typeof val === 'function' || val && val.constructor === RegExp) {
return String(val)
}
return val
}
function proxyMiddlewareContent(options: ProxyOptions): string {
return `import * as http from 'node:http'
import * as net from 'node:net'
import { createProxyServer, ProxyServer, Server } from '@refactorjs/http-proxy'
import { defineEventHandler } from 'h3'
interface ProxyOptions extends Server.ServerOptions {
/**
* rewrite path
*/
rewrite?: (path: string) => string | null | undefined | false
/**
* configure the proxy server (e.g. listen to events)
*/
configure?: (proxy: ProxyServer, options: ProxyOptions) => void | null | undefined | false
/**
* webpack-dev-server style bypass function
*/
bypass?: (
req: http.IncomingMessage,
res: http.ServerResponse,
options: ProxyOptions
) => void | null | undefined | false | string
}
// lazy require only when proxy is used
const proxies: Record<string, [ProxyServer, ProxyOptions]> = {}
const options: { [key: string]: string | ProxyOptions } | undefined = ${JSON.stringify(options, converter)};
Object.keys(options!).forEach((context) => {
let opts = options![context]
if (!opts) return
if (typeof opts === 'string') {
opts = { target: opts, changeOrigin: true } as ProxyOptions
}
if (isObject(opts)) {
opts = { changeOrigin: true, ...opts } as ProxyOptions
opts.rewrite = opts.rewrite ? new Function("return (" + opts.rewrite + ")")() : false
opts.configure = opts.configure ? new Function("return (" + opts.configure + ")")() : false
opts.bypass = opts.bypass ? new Function("return (" + opts.bypass + ")")() : false
}
const proxy = createProxyServer(opts)
proxy.on('error', (err, req, originalRes) => {
// When it is ws proxy, res is net.Socket
const res = originalRes as http.ServerResponse | net.Socket
if ('req' in res) {
console.error('http proxy error:' + err.stack, {
timestamp: true,
error: err
})
if (!res.headersSent && !res.writableEnded) {
res.writeHead(500, {
'Content-Type': 'text/plain'
})
.end()
}
} else {
console.error('ws proxy error:' + err.stack, {
timestamp: true,
error: err
})
res.end()
}
})
if (opts.configure) {
opts.configure(proxy, opts)
}
// clone before saving because http-proxy mutates the options
proxies[context] = [proxy, { ...opts }]
})
export default defineEventHandler(async (event) => {
await new Promise<void>((resolve, reject) => {
const next = (err?: unknown) => {
if (err) {
reject(err)
} else {
resolve()
}
}
const url = event.req.url!
for (const context in proxies) {
if (doesProxyContextMatchUrl(context, url)) {
const [proxy, opts] = proxies[context]
const options: Server.ServerOptions = {}
if (opts.bypass) {
const bypassResult = opts.bypass(event.req, event.res, opts)
if (typeof bypassResult === 'string') {
event.req.url = bypassResult
console.debug('bypass: ' + event.req.url + ' -> ' + bypassResult)
return next()
} else if (isObject(bypassResult)) {
Object.assign(options, bypassResult)
console.debug('bypass: ' + event.req.url + ' use modified options: %O', options)
return next()
} else if (bypassResult === false) {
console.debug('bypass: ' + event.req.url + ' -> 404')
return event.res.end(404)
}
}
console.debug(event.req.url + ' -> ' + opts.target || opts.forward)
if (opts.rewrite) {
event.req.url = opts.rewrite(event.req.url!) as string
}
proxy.web(event.req, event.res, options)
return
}
}
next()
})
})
function isObject(value: unknown): value is Record<string, any> {
return Object.prototype.toString.call(value) === '[object Object]'
}
function doesProxyContextMatchUrl(context: string, url: string): boolean {
return (
(context.startsWith('^') && new RegExp(context).test(url)) || url.startsWith(context)
)
}
`
}