feat: add HTTP and WebSocket development proxy
This commit is contained in:
@@ -10,6 +10,7 @@ import chokidar, {type FSWatcher} from 'chokidar';
|
||||
import {WebSocketServer, type WebSocket} from 'ws';
|
||||
import {loadConfig, type IcebergConfig, type ResolvedIcebergConfig} from '../core/config.js';
|
||||
import {DEV_CLIENT} from './client.js';
|
||||
import {DevProxy} from './proxy.js';
|
||||
import {logger} from '../core/logger.js';
|
||||
|
||||
const assetPattern = /\.(png|jpe?g|gif|svg|webp|avif|woff2?|ttf|otf|ico)$/i;
|
||||
@@ -36,8 +37,10 @@ class IcebergDevServer implements DevServer {
|
||||
private watcher?: FSWatcher;
|
||||
private ws?: WebSocketServer;
|
||||
private boundPort?: number;
|
||||
private readonly proxy: DevProxy;
|
||||
|
||||
constructor(public readonly config: ResolvedIcebergConfig) {
|
||||
this.proxy = new DevProxy(config);
|
||||
}
|
||||
|
||||
get url() {
|
||||
@@ -59,11 +62,13 @@ class IcebergDevServer implements DevServer {
|
||||
});
|
||||
this.server.on('upgrade', (request, socket, head) => {
|
||||
const pathname = new URL(request.url ?? '/', `http://${request.headers.host ?? 'localhost'}`).pathname;
|
||||
if (pathname !== `${this.config.base}__iceberg_ws` && pathname !== '/__iceberg_ws') {
|
||||
socket.destroy();
|
||||
if (pathname === `${this.config.base}__iceberg_ws` || pathname === '/__iceberg_ws') {
|
||||
this.ws!.handleUpgrade(request, socket, head, client => this.ws!.emit('connection', client, request));
|
||||
return;
|
||||
}
|
||||
this.ws!.handleUpgrade(request, socket, head, client => this.ws!.emit('connection', client, request));
|
||||
const match = this.proxy.match(pathname);
|
||||
if (match?.options.ws) return this.proxy.forwardWebSocket(request, socket, head, match);
|
||||
socket.destroy();
|
||||
});
|
||||
this.boundPort = await listenOnAvailablePort(this.server, this.config.server.host, this.config.server.port, this.config.server.strictPort);
|
||||
this.watcher = chokidar.watch(this.config.root, {
|
||||
@@ -75,17 +80,21 @@ class IcebergDevServer implements DevServer {
|
||||
this.watcher!.once('ready', () => resolve());
|
||||
this.watcher!.once('error', reject);
|
||||
});
|
||||
logger.info(`ICEBERG v0.2.0\n\n Local: ${this.url}\n Network: use --host to expose\n\n Ready`);
|
||||
logger.info(`ICEBERG v0.2.1\n\n Local: ${this.url}\n Network: use --host to expose\n\n Ready`);
|
||||
if (this.config.server.open && this.url) openBrowser(this.url);
|
||||
}
|
||||
|
||||
async close() {
|
||||
await this.watcher?.close();
|
||||
this.watcher = undefined;
|
||||
for (const socket of this.sockets) socket.close();
|
||||
for (const socket of this.sockets) {
|
||||
socket.close();
|
||||
socket.terminate();
|
||||
}
|
||||
this.sockets.clear();
|
||||
this.ws?.close();
|
||||
if (this.ws) await new Promise<void>(resolve => this.ws!.close(() => resolve()));
|
||||
this.ws = undefined;
|
||||
this.proxy.close();
|
||||
if (this.server) await new Promise<void>(resolve => this.server!.close(() => resolve()));
|
||||
this.server = undefined;
|
||||
this.boundPort = undefined;
|
||||
@@ -93,7 +102,7 @@ class IcebergDevServer implements DevServer {
|
||||
|
||||
private async handle(request: http.IncomingMessage, response: http.ServerResponse) {
|
||||
try {
|
||||
if (request.method !== 'GET' && request.method !== 'HEAD') return send(response, 405, 'Method Not Allowed', 'text/plain');
|
||||
if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].includes(request.method ?? '')) return send(response, 405, 'Method Not Allowed', 'text/plain');
|
||||
const url = new URL(request.url ?? '/', `http://${request.headers.host ?? 'localhost'}`);
|
||||
const pathname = decodeURIComponent(url.pathname);
|
||||
if (pathname === `${this.config.base}@iceberg/client.js` || pathname === '/@iceberg/client.js') return send(response, 200, DEV_CLIENT, 'application/javascript');
|
||||
@@ -101,6 +110,8 @@ class IcebergDevServer implements DevServer {
|
||||
if (pathname === `${this.config.base}@iceberg/module` || pathname === '/@iceberg/module') return this.serveModule(url, response);
|
||||
if (pathname === `${this.config.base}@iceberg/asset-module` || pathname === '/@iceberg/asset-module') return this.serveAssetModule(url, response);
|
||||
if (pathname === `${this.config.base}@iceberg/asset` || pathname === '/@iceberg/asset') return this.serveAsset(url, response);
|
||||
const proxyMatch = this.proxy.match(pathname);
|
||||
if (proxyMatch) return this.proxy.forwardHttp(request, response, proxyMatch);
|
||||
const relative = pathname.replace(new RegExp(`^${escapeRegExp(this.config.base)}`), '').replace(/^\//, '');
|
||||
if (sensitivePattern.test(relative)) return send(response, 404, 'Not Found', 'text/plain');
|
||||
const publicFile = await this.safeFile(path.join(this.config.root, 'public', relative));
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import type http from 'node:http';
|
||||
import httpProxy from 'http-proxy';
|
||||
import type {ResolvedIcebergConfig, ResolvedProxyOptions} from '../core/config.js';
|
||||
import {logger} from '../core/logger.js';
|
||||
|
||||
export interface ProxyMatch {
|
||||
route: string;
|
||||
options: ResolvedProxyOptions;
|
||||
}
|
||||
|
||||
export class DevProxy {
|
||||
private readonly proxy = httpProxy.createProxyServer({});
|
||||
|
||||
constructor(private readonly config: ResolvedIcebergConfig) {
|
||||
this.proxy.on('error', (error, request) => {
|
||||
logger.error(`Proxy error: ${request?.url ?? '<unknown>'}`);
|
||||
logger.error(`Target: ${this.targetFor(request)}`);
|
||||
logger.error(error.message);
|
||||
});
|
||||
}
|
||||
|
||||
match(pathname: string): ProxyMatch | undefined {
|
||||
return Object.entries(this.config.server.proxy)
|
||||
.filter(([route]) => matchesRoute(route, pathname))
|
||||
.sort(([left], [right]) => right.length - left.length)
|
||||
.map(([route, options]) => ({route, options}))[0];
|
||||
}
|
||||
|
||||
forwardHttp(request: http.IncomingMessage, response: http.ServerResponse, match: ProxyMatch) {
|
||||
const originalUrl = request.url ?? '/';
|
||||
try {
|
||||
request.url = forwardedUrl(originalUrl, match.options, match.route);
|
||||
} catch (error) {
|
||||
request.url = originalUrl;
|
||||
this.sendRewriteError(response, error);
|
||||
return;
|
||||
}
|
||||
this.proxy.web(request, response, {target: match.options.target, changeOrigin: match.options.changeOrigin, secure: match.options.secure}, error => {
|
||||
request.url = originalUrl;
|
||||
if (error) this.sendProxyError(response, error, match);
|
||||
});
|
||||
}
|
||||
|
||||
forwardWebSocket(request: http.IncomingMessage, socket: import('node:stream').Duplex, head: Buffer, match: ProxyMatch) {
|
||||
const originalUrl = request.url ?? '/';
|
||||
try {
|
||||
request.url = forwardedUrl(originalUrl, match.options, match.route);
|
||||
} catch (error) {
|
||||
request.url = originalUrl;
|
||||
socket.destroy();
|
||||
logger.error(`Proxy rewrite error: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
this.proxy.ws(request, socket, head, {target: match.options.target, changeOrigin: match.options.changeOrigin, secure: match.options.secure}, error => {
|
||||
request.url = originalUrl;
|
||||
if (error) {
|
||||
logger.error(`Proxy WebSocket error: ${request.url}`);
|
||||
logger.error(`Target: ${match.options.target}`);
|
||||
logger.error(error.message);
|
||||
socket.destroy();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
close() {
|
||||
this.proxy.close();
|
||||
}
|
||||
|
||||
private sendRewriteError(response: http.ServerResponse, error: unknown) {
|
||||
if (response.headersSent) return response.destroy();
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logger.error(`Proxy rewrite error: ${message}`);
|
||||
response.statusCode = 500;
|
||||
response.setHeader('content-type', 'application/json; charset=utf-8');
|
||||
response.end(JSON.stringify({error: 'Proxy Rewrite Error', message: 'The configured proxy path rewrite failed.'}));
|
||||
}
|
||||
|
||||
private sendProxyError(response: http.ServerResponse, error: Error, match: ProxyMatch) {
|
||||
const networkError = error as NodeJS.ErrnoException;
|
||||
logger.error(`Proxy error: ${match.route}`);
|
||||
logger.error(`Target: ${match.options.target}`);
|
||||
logger.error(networkError.code ? `${networkError.code}: ${error.message}` : error.message);
|
||||
if (response.headersSent) return response.destroy();
|
||||
response.statusCode = networkError.code === 'ETIMEDOUT' ? 504 : 502;
|
||||
response.setHeader('content-type', 'application/json; charset=utf-8');
|
||||
response.end(JSON.stringify({error: response.statusCode === 504 ? 'Gateway Timeout' : 'Bad Gateway', message: 'The configured proxy target is unavailable.'}));
|
||||
}
|
||||
|
||||
private targetFor(request?: http.IncomingMessage) {
|
||||
const match = request?.url ? this.match(new URL(request.url, 'http://iceberg.local').pathname) : undefined;
|
||||
return match?.options.target ?? '<unknown>';
|
||||
}
|
||||
}
|
||||
|
||||
function matchesRoute(route: string, pathname: string) {
|
||||
return route === '/' ? pathname.startsWith('/') : pathname === route || pathname.startsWith(`${route}/`);
|
||||
}
|
||||
|
||||
function forwardedUrl(originalUrl: string, options: ResolvedProxyOptions, route: string) {
|
||||
const parsed = new URL(originalUrl, 'http://iceberg.local');
|
||||
let rewrittenPath = parsed.pathname;
|
||||
if (options.rewrite) {
|
||||
rewrittenPath = options.rewrite(parsed.pathname);
|
||||
if (typeof rewrittenPath !== 'string' || !rewrittenPath.startsWith('/') || rewrittenPath.includes('://') || rewrittenPath.includes('\r') || rewrittenPath.includes('\n')) throw new Error(`Proxy rewrite for '${route}' must return a safe absolute path beginning with '/'.`);
|
||||
}
|
||||
return `${rewrittenPath || '/'}${parsed.search}`;
|
||||
}
|
||||
Reference in New Issue
Block a user