diff --git a/src/server/dev-server.ts b/src/server/dev-server.ts index e80bb1a..3d82b92 100644 --- a/src/server/dev-server.ts +++ b/src/server/dev-server.ts @@ -1,117 +1,318 @@ import http from 'node:http'; -import { spawn } from 'node:child_process'; +import {spawn} from 'node:child_process'; import path from 'node:path'; -import { createRequire } from 'node:module'; -import { readFile, stat } from 'node:fs/promises'; -import { pathToFileURL } from 'node:url'; -import { transform } from 'rolldown/utils'; -import { bundleAsync } from 'lightningcss'; -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 { logger } from '../core/logger.js'; +import {createRequire} from 'node:module'; +import {readFile, stat} from 'node:fs/promises'; +import {pathToFileURL} from 'node:url'; +import {transform} from 'rolldown/utils'; +import {bundleAsync} from 'lightningcss'; +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 {logger} from '../core/logger.js'; const assetPattern = /\.(png|jpe?g|gif|svg|webp|avif|woff2?|ttf|otf|ico)$/i; const sourcePattern = /\.(js|mjs|ts|jsx|tsx)$/i; const sensitivePattern = /(^|[\\/])(?:\.git|\.env(?:\.|$)|node_modules[\\/]\.bin)(?:[\\/]|$)/i; export interface DevServer { - listen(): Promise; - close(): Promise; - readonly url: string | undefined; - readonly port: number | undefined; - readonly config: ResolvedIcebergConfig; + listen(): Promise; + + close(): Promise; + + readonly url: string | undefined; + readonly port: number | undefined; + readonly config: ResolvedIcebergConfig; } export async function createServer(inline?: IcebergConfig): Promise { - return new IcebergDevServer(await loadConfig(process.cwd(), inline)); + return new IcebergDevServer(await loadConfig(process.cwd(), inline)); } class IcebergDevServer implements DevServer { - private server?: http.Server; - private sockets = new Set(); - private watcher?: FSWatcher; - private ws?: WebSocketServer; - private boundPort?: number; - constructor(public readonly config: ResolvedIcebergConfig) {} - get url() { return this.boundPort === undefined ? undefined : `http://${displayHost(this.config.server.host)}:${this.boundPort}${this.config.base}`; } - get port() { return this.boundPort; } + private server?: http.Server; + private sockets = new Set(); + private watcher?: FSWatcher; + private ws?: WebSocketServer; + private boundPort?: number; - async listen() { - if (this.server) return; - this.server = http.createServer((request, response) => void this.handle(request, response)); - this.ws = new WebSocketServer({ noServer: true }); - this.ws.on('connection', socket => { this.sockets.add(socket); socket.send(JSON.stringify({ type: 'connected' })); socket.on('close', () => this.sockets.delete(socket)); }); - 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(); return; } this.ws!.handleUpgrade(request, socket, head, client => this.ws!.emit('connection', client, request)); }); - 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, { ignored: file => /[\\/]node_modules[\\/]|[\\/]\.git[\\/]|[\\/]dist[\\/]|[\\/]build[\\/]/.test(file), ignoreInitial: true }); - this.watcher.on('all', (event, file) => this.onFileChange(event, path.resolve(file))); - await new Promise((resolve, reject) => { 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`); - if (this.config.server.open && this.url) openBrowser(this.url); - } + constructor(public readonly config: ResolvedIcebergConfig) { + } - async close() { - await this.watcher?.close(); this.watcher = undefined; - for (const socket of this.sockets) socket.close(); this.sockets.clear(); - this.ws?.close(); this.ws = undefined; - if (this.server) await new Promise(resolve => this.server!.close(() => resolve())); - this.server = undefined; this.boundPort = undefined; - } + get url() { + return this.boundPort === undefined ? undefined : `http://${displayHost(this.config.server.host)}:${this.boundPort}${this.config.base}`; + } - 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'); - 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'); - if (pathname === `${this.config.base}@iceberg/css-proxy` || pathname === '/@iceberg/css-proxy') return this.serveCssProxy(url, response); - 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 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)); - if (publicFile && await isFile(publicFile)) return this.serveFile(publicFile, response); - const sourceFile = await this.safeFile(path.join(this.config.root, relative)); - if (sourceFile && await isFile(sourceFile)) { - if (sourceFile.endsWith('.html')) return this.serveHtml(sourceFile, response); - if (sourcePattern.test(sourceFile)) return this.serveModuleFile(sourceFile, response); - if (sourceFile.endsWith('.css')) return this.serveCss(sourceFile, response); - return this.serveFile(sourceFile, response); - } - if (!path.extname(relative)) return this.serveHtml(path.join(this.config.root, 'index.html'), response); - return send(response, 404, 'Not Found', 'text/plain'); - } catch (error) { const message = error instanceof Error ? error.message : String(error); logger.error(message); return send(response, 500, message, 'text/plain'); } - } + get port() { + return this.boundPort; + } - private async serveHtml(file: string, response: http.ServerResponse) { const html = await readFile(file, 'utf8'); const client = `${this.config.base}@iceberg/client.js`; const injected = html.includes('') ? html.replace(/<\/body>/i, ``) : `${html}\n`; send(response, 200, injected, 'text/html'); } - private async serveModuleFile(file: string, response: http.ServerResponse) { const source = await readFile(file, 'utf8'); const result = await transform(file, source, { lang: languageFor(file), sourceType: 'module', sourcemap: true }); if (result.errors.length) throw new Error(result.errors.map(error => error.message).join('\n')); let code = rewriteImports(String(result.code), file, this.config); if (result.map) code += `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(result.map)).toString('base64')}`; send(response, 200, code, 'application/javascript'); } - private async serveModule(url: URL, response: http.ServerResponse) { const file = this.requestedFile(url); if (!file) return send(response, 400, 'Missing module file', 'text/plain'); return this.serveModuleFile(file, response); } - private async serveCss(file: string, response: http.ServerResponse) { const result = await bundleAsync({ filename: file, minify: false, sourceMap: true }); const sourceMap = result.map ? `\n/*# sourceMappingURL=data:application/json;base64,${Buffer.from(result.map).toString('base64')} */` : ''; send(response, 200, Buffer.concat([result.code, Buffer.from(sourceMap)]), 'text/css'); } - private async serveCssProxy(url: URL, response: http.ServerResponse) { const file = this.requestedFile(url); if (!file) return send(response, 400, 'Missing CSS file', 'text/plain'); const cssUrl = this.browserUrl(file); const code = `const href = ${JSON.stringify(cssUrl)}; let link = document.querySelector('link[data-iceberg-css="' + href + '"]'); if (!link) { link = document.createElement('link'); link.rel = 'stylesheet'; link.dataset.icebergCss = href; link.href = href; document.head.append(link); } export default link;`; send(response, 200, code, 'application/javascript'); } - private async serveAssetModule(url: URL, response: http.ServerResponse) { const file = this.requestedFile(url); if (!file) return send(response, 400, 'Missing asset file', 'text/plain'); send(response, 200, `export default ${JSON.stringify(this.browserUrl(file))};`, 'application/javascript'); } - private async serveAsset(url: URL, response: http.ServerResponse) { const file = this.requestedFile(url); if (!file) return send(response, 400, 'Missing asset file', 'text/plain'); return this.serveFile(file, response); } - private async serveFile(file: string, response: http.ServerResponse) { const content = await readFile(file); send(response, 200, content, contentType(file)); } - private requestedFile(url: URL) { const raw = url.searchParams.get('file'); if (!raw) return undefined; const file = path.resolve(raw); return this.isAllowed(file) ? file : undefined; } - private async safeFile(file: string) { const resolved = path.resolve(file); return this.isAllowed(resolved) ? resolved : undefined; } - private isAllowed(file: string) { const root = path.resolve(this.config.root); return isWithin(root, file) && !sensitivePattern.test(path.relative(root, file)); } - private browserUrl(file: string) { const relative = `/${path.relative(this.config.root, file).replace(/\\/g, '/')}`; return `${this.config.base === '/' ? '' : this.config.base.slice(0, -1)}${relative}`; } - private onFileChange(event: string, file: string) { if (event === 'unlink') { this.broadcast({ type: 'reload' }); return; } if (file.endsWith('.css')) this.broadcast({ type: 'css-update', path: this.browserUrl(file) }); else this.broadcast({ type: 'reload' }); } - private broadcast(message: object) { const data = JSON.stringify(message); for (const socket of this.sockets) if (socket.readyState === 1) socket.send(data); } + async listen() { + if (this.server) return; + this.server = http.createServer((request, response) => void this.handle(request, response)); + this.ws = new WebSocketServer({noServer: true}); + this.ws.on('connection', socket => { + this.sockets.add(socket); + socket.send(JSON.stringify({type: 'connected'})); + socket.on('close', () => this.sockets.delete(socket)); + }); + 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(); + return; + } + this.ws!.handleUpgrade(request, socket, head, client => this.ws!.emit('connection', client, request)); + }); + 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, { + ignored: file => /[\\/]node_modules[\\/]|[\\/]\.git[\\/]|[\\/]dist[\\/]|[\\/]build[\\/]/.test(file), + ignoreInitial: true + }); + this.watcher.on('all', (event, file) => this.onFileChange(event, path.resolve(file))); + await new Promise((resolve, reject) => { + 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`); + 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(); + this.sockets.clear(); + this.ws?.close(); + this.ws = undefined; + if (this.server) await new Promise(resolve => this.server!.close(() => resolve())); + this.server = undefined; + this.boundPort = undefined; + } + + 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'); + 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'); + if (pathname === `${this.config.base}@iceberg/css-proxy` || pathname === '/@iceberg/css-proxy') return this.serveCssProxy(url, response); + 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 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)); + if (publicFile && await isFile(publicFile)) return this.serveFile(publicFile, response); + const sourceFile = await this.safeFile(path.join(this.config.root, relative)); + if (sourceFile && await isFile(sourceFile)) { + if (sourceFile.endsWith('.html')) return this.serveHtml(sourceFile, response); + if (sourcePattern.test(sourceFile)) return this.serveModuleFile(sourceFile, response); + if (sourceFile.endsWith('.css')) return this.serveCss(sourceFile, response); + return this.serveFile(sourceFile, response); + } + if (!path.extname(relative)) return this.serveHtml(path.join(this.config.root, 'index.html'), response); + return send(response, 404, 'Not Found', 'text/plain'); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + logger.error(message); + return send(response, 500, message, 'text/plain'); + } + } + + private async serveHtml(file: string, response: http.ServerResponse) { + const html = await readFile(file, 'utf8'); + const client = `${this.config.base}@iceberg/client.js`; + const injected = html.includes('') ? html.replace(/<\/body>/i, ``) : `${html}\n`; + send(response, 200, injected, 'text/html'); + } + + private async serveModuleFile(file: string, response: http.ServerResponse) { + const source = await readFile(file, 'utf8'); + const result = await transform(file, source, {lang: languageFor(file), sourceType: 'module', sourcemap: true}); + if (result.errors.length) throw new Error(result.errors.map(error => error.message).join('\n')); + let code = rewriteImports(String(result.code), file, this.config); + if (result.map) code += `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(result.map)).toString('base64')}`; + send(response, 200, code, 'application/javascript'); + } + + private async serveModule(url: URL, response: http.ServerResponse) { + const file = this.requestedFile(url); + if (!file) return send(response, 400, 'Missing module file', 'text/plain'); + return this.serveModuleFile(file, response); + } + + private async serveCss(file: string, response: http.ServerResponse) { + const result = await bundleAsync({filename: file, minify: false, sourceMap: true}); + const sourceMap = result.map ? `\n/*# sourceMappingURL=data:application/json;base64,${Buffer.from(result.map).toString('base64')} */` : ''; + send(response, 200, Buffer.concat([result.code, Buffer.from(sourceMap)]), 'text/css'); + } + + private async serveCssProxy(url: URL, response: http.ServerResponse) { + const file = this.requestedFile(url); + if (!file) return send(response, 400, 'Missing CSS file', 'text/plain'); + const cssUrl = this.browserUrl(file); + const code = `const href = ${JSON.stringify(cssUrl)}; let link = document.querySelector('link[data-iceberg-css="' + href + '"]'); if (!link) { link = document.createElement('link'); link.rel = 'stylesheet'; link.dataset.icebergCss = href; link.href = href; document.head.append(link); } export default link;`; + send(response, 200, code, 'application/javascript'); + } + + private async serveAssetModule(url: URL, response: http.ServerResponse) { + const file = this.requestedFile(url); + if (!file) return send(response, 400, 'Missing asset file', 'text/plain'); + send(response, 200, `export default ${JSON.stringify(this.browserUrl(file))};`, 'application/javascript'); + } + + private async serveAsset(url: URL, response: http.ServerResponse) { + const file = this.requestedFile(url); + if (!file) return send(response, 400, 'Missing asset file', 'text/plain'); + return this.serveFile(file, response); + } + + private async serveFile(file: string, response: http.ServerResponse) { + const content = await readFile(file); + send(response, 200, content, contentType(file)); + } + + private requestedFile(url: URL) { + const raw = url.searchParams.get('file'); + if (!raw) return undefined; + const file = path.resolve(raw); + return this.isAllowed(file) ? file : undefined; + } + + private async safeFile(file: string) { + const resolved = path.resolve(file); + return this.isAllowed(resolved) ? resolved : undefined; + } + + private isAllowed(file: string) { + const root = path.resolve(this.config.root); + return isWithin(root, file) && !sensitivePattern.test(path.relative(root, file)); + } + + private browserUrl(file: string) { + const relative = `/${path.relative(this.config.root, file).replace(/\\/g, '/')}`; + return `${this.config.base === '/' ? '' : this.config.base.slice(0, -1)}${relative}`; + } + + private onFileChange(event: string, file: string) { + if (event === 'unlink') { + this.broadcast({type: 'reload'}); + return; + } + if (file.endsWith('.css')) this.broadcast({ + type: 'css-update', + path: this.browserUrl(file) + }); else this.broadcast({type: 'reload'}); + } + + private broadcast(message: object) { + const data = JSON.stringify(message); + for (const socket of this.sockets) if (socket.readyState === 1) socket.send(data); + } } -function rewriteImports(code: string, importer: string, config: ResolvedIcebergConfig) { return code.replace(/(\b(?:import|export)\s*(?:[^'"`]*?\sfrom\s*)?|\bimport\s*\()(["'`])([^"'`]+)\2/g, (_match, prefix: string, quote: string, specifier: string) => `${prefix}${quote}${browserImport(specifier, importer, config)}${quote}`); } -function browserImport(specifier: string, importer: string, config: ResolvedIcebergConfig) { if (/^(node:|https?:|data:|\/\/)/.test(specifier)) return specifier; const file = resolveImport(specifier, importer, config.root); if (file.endsWith('.css')) return internalUrl('css-proxy', file, config); if (assetPattern.test(file)) return internalUrl('asset-module', file, config); return internalUrl('module', file, config); } -function resolveImport(specifier: string, importer: string, root: string) { const require = createRequire(pathToFileURL(importer)); try { const resolved = require.resolve(specifier); if (!isWithin(path.resolve(root), path.resolve(resolved))) throw new Error(`Dependency is outside the project root: ${specifier}`); return resolved; } catch (error) { throw new Error(`Could not resolve '${specifier}' from ${importer}: ${error instanceof Error ? error.message : String(error)}`); } } -function internalUrl(kind: string, file: string, config: ResolvedIcebergConfig) { return `${config.base}@iceberg/${kind}?file=${encodeURIComponent(file)}`; } -function languageFor(file: string): 'js' | 'jsx' | 'ts' | 'tsx' { if (file.endsWith('.tsx')) return 'tsx'; if (file.endsWith('.jsx')) return 'jsx'; if (file.endsWith('.ts')) return 'ts'; return 'js'; } -function contentType(file: string) { if (file.endsWith('.css')) return 'text/css'; if (file.endsWith('.html')) return 'text/html'; if (file.endsWith('.js') || file.endsWith('.ts')) return 'application/javascript'; if (file.endsWith('.json')) return 'application/json'; if (file.endsWith('.svg')) return 'image/svg+xml'; if (file.endsWith('.png')) return 'image/png'; if (file.endsWith('.jpg') || file.endsWith('.jpeg')) return 'image/jpeg'; if (file.endsWith('.woff2')) return 'font/woff2'; return 'application/octet-stream'; } -function send(response: http.ServerResponse, status: number, body: string | Uint8Array, type: string) { response.statusCode = status; response.setHeader('content-type', `${type}; charset=utf-8`); response.end(body); } -function isWithin(root: string, file: string) { const relative = path.relative(root, file); return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); } -async function isFile(file: string) { try { return (await stat(file)).isFile(); } catch { return false; } } -function escapeRegExp(value: string) { return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } -function displayHost(host: string) { return host === '0.0.0.0' ? 'localhost' : host; } -function openBrowser(url: string) { const command = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open'; const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url]; spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: true }).unref(); } -async function listenOnAvailablePort(server: http.Server, host: string, start: number, strict: boolean) { let port = start; while (true) { try { await new Promise((resolve, reject) => { const onError = (error: NodeJS.ErrnoException) => { server.off('listening', onListen); reject(error); }; const onListen = () => { server.off('error', onError); resolve(); }; server.once('error', onError); server.once('listening', onListen); server.listen(port, host); }); return (server.address() as { port: number }).port; } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE' || strict) throw new Error(`Could not start server on ${host}:${port}. ${(error as Error).message}`); port++; } } } +function rewriteImports(code: string, importer: string, config: ResolvedIcebergConfig) { + return code.replace(/(\b(?:import|export)\s*(?:[^'"`]*?\sfrom\s*)?|\bimport\s*\()(["'`])([^"'`]+)\2/g, (_match, prefix: string, quote: string, specifier: string) => `${prefix}${quote}${browserImport(specifier, importer, config)}${quote}`); +} + +function browserImport(specifier: string, importer: string, config: ResolvedIcebergConfig) { + if (/^(node:|https?:|data:|\/\/)/.test(specifier)) return specifier; + const file = resolveImport(specifier, importer, config.root); + if (file.endsWith('.css')) return internalUrl('css-proxy', file, config); + if (assetPattern.test(file)) return internalUrl('asset-module', file, config); + return internalUrl('module', file, config); +} + +function resolveImport(specifier: string, importer: string, root: string) { + const require = createRequire(pathToFileURL(importer)); + try { + const resolved = require.resolve(specifier); + if (!isWithin(path.resolve(root), path.resolve(resolved))) throw new Error(`Dependency is outside the project root: ${specifier}`); + return resolved; + } catch (error) { + throw new Error(`Could not resolve '${specifier}' from ${importer}: ${error instanceof Error ? error.message : String(error)}`); + } +} + +function internalUrl(kind: string, file: string, config: ResolvedIcebergConfig) { + return `${config.base}@iceberg/${kind}?file=${encodeURIComponent(file)}`; +} + +function languageFor(file: string): 'js' | 'jsx' | 'ts' | 'tsx' { + if (file.endsWith('.tsx')) return 'tsx'; + if (file.endsWith('.jsx')) return 'jsx'; + if (file.endsWith('.ts')) return 'ts'; + return 'js'; +} + +function contentType(file: string) { + if (file.endsWith('.css')) return 'text/css'; + if (file.endsWith('.html')) return 'text/html'; + if (file.endsWith('.js') || file.endsWith('.ts')) return 'application/javascript'; + if (file.endsWith('.json')) return 'application/json'; + if (file.endsWith('.svg')) return 'image/svg+xml'; + if (file.endsWith('.png')) return 'image/png'; + if (file.endsWith('.jpg') || file.endsWith('.jpeg')) return 'image/jpeg'; + if (file.endsWith('.woff2')) return 'font/woff2'; + return 'application/octet-stream'; +} + +function send(response: http.ServerResponse, status: number, body: string | Uint8Array, type: string) { + response.statusCode = status; + response.setHeader('content-type', `${type}; charset=utf-8`); + response.end(body); +} + +function isWithin(root: string, file: string) { + const relative = path.relative(root, file); + return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); +} + +async function isFile(file: string) { + try { + return (await stat(file)).isFile(); + } catch { + return false; + } +} + +function escapeRegExp(value: string) { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function displayHost(host: string) { + return host === '0.0.0.0' ? 'localhost' : host; +} + +function openBrowser(url: string) { + const command = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open'; + const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url]; + spawn(command, args, {detached: true, stdio: 'ignore', windowsHide: true}).unref(); +} + +async function listenOnAvailablePort(server: http.Server, host: string, start: number, strict: boolean) { + let port = start; + while (true) { + try { + await new Promise((resolve, reject) => { + const onError = (error: NodeJS.ErrnoException) => { + server.off('listening', onListen); + reject(error); + }; + const onListen = () => { + server.off('error', onError); + resolve(); + }; + server.once('error', onError); + server.once('listening', onListen); + server.listen(port, host); + }); + return (server.address() as { port: number }).port; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE' || strict) throw new Error(`Could not start server on ${host}:${port}. ${(error as Error).message}`); + port++; + } + } +}