import{Path}from"../utils/path";import{link}from"../utils/printstyle";import{formatUrl,withoutUrl}from"./utils";importlogfrom"../utils/log";typeOnRequestType=(cfg: {path: Path})=>any;typeOnSocketConnectedType=(ws: any)=>any;/** * Start a server at the provided URL and port. * Handle requests with the provided callback. */constcreateServer=({
url,
port,
websocketPath,
onRequest =()=>{},
onSocketConnected =()=>{},}: {url: string;port: number;websocketPath: string;onRequest: OnRequestType;onSocketConnected: OnSocketConnectedType;})=>{constfullUrl=formatUrl({ url, port });constlinkText=link(fullUrl).underline().color("blue");consthttpWebsocketUrl=formatUrl({
url,
port,path: websocketPath,});log.production(`Starting server at ${linkText}`);constserver=Bun.serve({
port,fetch(req,server){constpath=withoutUrl(req.url,fullUrl);log.network("FETCH",path);if(req.url===httpWebsocketUrl){log.network("websocket request");if(server.upgrade(req)){return;}}letreturnPath=Path.create(path);// 'sec-fetch-dest' header determines how the script will be used// on the website, so we assume it's a js file - and push that -// if it's used in a script.if(req.headers.get("sec-fetch-dest")==="script"){returnPath=returnPath.replaceExtension("js");}returnonRequest({// req,// server,path: returnPath,});},websocket: {// TODO: what does this field do?message(ws,message){log.network("Received message from client: ",message);},open(ws){onSocketConnected(ws);},},});returnserver;};export{createServer};