|
| 1 | +import { ServerUserConfig } from '../types.js'; |
| 2 | +import type Express from 'express'; |
| 3 | +import express from 'express'; |
| 4 | +import http from 'node:http'; |
| 5 | +import https from 'node:https'; |
| 6 | +import http2 from 'node:http2'; |
| 7 | +import path from 'node:path'; |
| 8 | +import fs from 'node:fs'; |
| 9 | +import { createProxyMiddleware } from 'http-proxy-middleware'; |
| 10 | +import { consola } from 'consola'; |
| 11 | +import pc from 'picocolors'; |
| 12 | +import cors from 'cors'; |
| 13 | +import { getAddressUrls } from './utils.js'; |
| 14 | + |
| 15 | +export const DEFAULT_PORT = 5138; |
| 16 | +export const DEFAULT_HOST = '0.0.0.0'; |
| 17 | + |
| 18 | +export interface PkgServer { |
| 19 | + app: Express.Application; |
| 20 | + httpServer: import('node:http').Server | import('node:https').Server | import('node:http2').Http2SecureServer | null; |
| 21 | + listen: () => Promise<{ |
| 22 | + port: number; |
| 23 | + urls: string[]; |
| 24 | + server: { |
| 25 | + close: () => Promise<void>; |
| 26 | + }; |
| 27 | + }>; |
| 28 | + port: number; |
| 29 | + close: () => Promise<void>; |
| 30 | + printUrls: () => void; |
| 31 | +} |
| 32 | + |
| 33 | +export function createServer(serverConfig: ServerUserConfig): PkgServer { |
| 34 | + const { |
| 35 | + port: configPort = DEFAULT_PORT, |
| 36 | + host = DEFAULT_HOST, |
| 37 | + publicDir: publicDirConfig, |
| 38 | + headers, |
| 39 | + cors: corsConfig, |
| 40 | + proxy, |
| 41 | + autoServeBundle = true, |
| 42 | + https: httpsConfig, |
| 43 | + } = serverConfig; |
| 44 | + const app = express(); |
| 45 | + |
| 46 | + if (headers) { |
| 47 | + app.use((req, res, next) => { |
| 48 | + Object.entries(headers).forEach(([key, value]) => { |
| 49 | + if (Array.isArray(value)) { |
| 50 | + value.forEach((v) => res.setHeader(key, v)); |
| 51 | + } else { |
| 52 | + res.setHeader(key, value); |
| 53 | + } |
| 54 | + }); |
| 55 | + next(); |
| 56 | + }); |
| 57 | + } |
| 58 | + |
| 59 | + if (proxy) { |
| 60 | + if (Array.isArray(proxy)) { |
| 61 | + proxy.forEach((p) => app.use(createProxyMiddleware(p))); |
| 62 | + } else { |
| 63 | + Object.entries(proxy).forEach(([context, options]) => { |
| 64 | + if (typeof options === 'string') { |
| 65 | + app.use(context, createProxyMiddleware({ target: options, changeOrigin: true })); |
| 66 | + } else { |
| 67 | + app.use(context, createProxyMiddleware(options)); |
| 68 | + } |
| 69 | + }); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + if (corsConfig !== false) { |
| 74 | + const options = corsConfig === true ? undefined : corsConfig; |
| 75 | + app.use(cors(options)); |
| 76 | + } |
| 77 | + |
| 78 | + if (autoServeBundle) { |
| 79 | + app.use(express.static(path.resolve(process.cwd(), 'dist'))); |
| 80 | + } |
| 81 | + |
| 82 | + if (publicDirConfig) { |
| 83 | + const dirs = Array.isArray(publicDirConfig) ? publicDirConfig : [publicDirConfig]; |
| 84 | + dirs.forEach((dir) => { |
| 85 | + let publicDir: string | undefined; |
| 86 | + if (typeof dir === 'string') { |
| 87 | + publicDir = dir; |
| 88 | + } else if (typeof dir === 'object') { |
| 89 | + publicDir = dir.name; |
| 90 | + } |
| 91 | + |
| 92 | + if (publicDir) { |
| 93 | + const staticPath = path.resolve(process.cwd(), publicDir); |
| 94 | + if (fs.existsSync(staticPath)) { |
| 95 | + app.use(express.static(staticPath)); |
| 96 | + } |
| 97 | + } |
| 98 | + }); |
| 99 | + } |
| 100 | + |
| 101 | + let httpServer: http.Server | https.Server | http2.Http2SecureServer; |
| 102 | + |
| 103 | + if (httpsConfig) { |
| 104 | + if (proxy) { |
| 105 | + // http-proxy-middleware is not compatible with HTTP/2 |
| 106 | + httpServer = https.createServer(httpsConfig as https.ServerOptions, app); |
| 107 | + } else { |
| 108 | + httpServer = http2.createSecureServer( |
| 109 | + { |
| 110 | + allowHTTP1: true, |
| 111 | + maxSessionMemory: 1024, |
| 112 | + ...httpsConfig, |
| 113 | + }, |
| 114 | + // @ts-expect-error req type mismatch |
| 115 | + app, |
| 116 | + ); |
| 117 | + } |
| 118 | + } else { |
| 119 | + httpServer = http.createServer(app); |
| 120 | + } |
| 121 | + |
| 122 | + let resolvedPort = configPort; |
| 123 | + |
| 124 | + const devServerAPI: PkgServer = { |
| 125 | + app: app, |
| 126 | + httpServer, |
| 127 | + get port() { |
| 128 | + return resolvedPort; |
| 129 | + }, |
| 130 | + listen: async () => { |
| 131 | + const findPort = async (startPort: number): Promise<number> => { |
| 132 | + return new Promise((resolve, reject) => { |
| 133 | + const s = http.createServer(); |
| 134 | + s.on('error', (err: any) => { |
| 135 | + if (err.code === 'EADDRINUSE') { |
| 136 | + s.close(); |
| 137 | + resolve(findPort(startPort + 1)); |
| 138 | + } else { |
| 139 | + reject(err); |
| 140 | + } |
| 141 | + }); |
| 142 | + s.listen(startPort, host, () => { |
| 143 | + s.close(() => resolve(startPort)); |
| 144 | + }); |
| 145 | + }); |
| 146 | + }; |
| 147 | + |
| 148 | + resolvedPort = await findPort(resolvedPort); |
| 149 | + |
| 150 | + return new Promise((resolve) => { |
| 151 | + httpServer.listen(resolvedPort, host, () => { |
| 152 | + const hostname = host === '0.0.0.0' ? 'localhost' : host; |
| 153 | + const protocol = httpsConfig ? 'https' : 'http'; |
| 154 | + const urls = [`${protocol}://${hostname}:${resolvedPort}`]; |
| 155 | + resolve({ |
| 156 | + port: resolvedPort, |
| 157 | + urls, |
| 158 | + server: { |
| 159 | + close: devServerAPI.close, |
| 160 | + }, |
| 161 | + }); |
| 162 | + }); |
| 163 | + }); |
| 164 | + }, |
| 165 | + close: async () => { |
| 166 | + if (httpServer.listening) { |
| 167 | + return new Promise<void>((resolve, reject) => { |
| 168 | + httpServer.close((err) => { |
| 169 | + if (err) reject(err); |
| 170 | + else resolve(); |
| 171 | + }); |
| 172 | + }); |
| 173 | + } |
| 174 | + }, |
| 175 | + printUrls: () => { |
| 176 | + const protocol = httpsConfig ? 'https' : 'http'; |
| 177 | + const urls = getAddressUrls(protocol, resolvedPort, host); |
| 178 | + // eslint-disable-next-line no-console |
| 179 | + console.log(); |
| 180 | + urls.forEach(({ label, url }) => { |
| 181 | + consola.log(`${label}${pc.cyan(url)}`); |
| 182 | + }); |
| 183 | + // eslint-disable-next-line no-console |
| 184 | + console.log(); |
| 185 | + }, |
| 186 | + }; |
| 187 | + |
| 188 | + return devServerAPI; |
| 189 | +} |
0 commit comments