in ide/deploy/serve.js [101:218]
async function main() {
// Get command-line arguments
const args = Bun.argv.slice(2);
const flags = {
port: 8080,
host: "127.0.0.1",
dir: "./",
proxyHost: null,
cacheTime: null,
mimeType: null,
};
// Parse command-line flags
for (let i = 0; i < args.length; i++) {
switch (args[i]) {
case "-h":
flags.host = args[i + 1];
i++;
break;
case "-d":
flags.dir = args[i + 1];
i++;
break;
case "-P":
flags.proxyHost = args[i + 1];
i++;
break;
case "-c":
flags.cacheTime = parseInt(args[i + 1], 10) || null;
i++;
break;
case "--mimetype":
flags.mimeType = args[i + 1];
i++;
break;
}
}
const assetsDirectory = resolve(flags.dir);
const serverPort = await findAvailablePort(flags.host, flags.port);
Bun.serve({
port: serverPort,
hostname: flags.host,
async fetch(req) {
const {pathname} = parse(req.url);
const filePath = `${assetsDirectory}${pathname === "/" ? "/index.html" : pathname}`;
// Check if file exists locally
try {
// console.debug(`Asset dir: ${assetsDirectory} - Filepath is ${filePath}`);
const fileStats = statSync(filePath);
if (fileStats.isFile()) {
const mimeType = flags.mimeType || getMimeType(filePath);
const headers = {
"Content-Type": mimeType,
};
if (flags.cacheTime) {
headers["Cache-Control"] = `max-age=${flags.cacheTime}`;
}
console.log(`[200] - Serving file ${pathname} from filesystem`);
return new Response(readFileSync(filePath), {headers});
}
} catch (err) {
let shouldExclude = (excludedAssets.indexOf(pathname) !== -1);
// File not found, fall back to proxy
if (flags.proxyHost && !shouldExclude) {
const destProxyUrl = `${flags.proxyHost}${pathname}`;
console.log(`[ P ] - Proxying request ${req.method} to '${destProxyUrl}'`);
const newHeaders = JSON.parse(JSON.stringify(req.headers));
const excludedHeaders = [
'host', 'origin',
// 'accept-encoding',
'sec-fetch-mode', 'sec-fetch-dest', 'sec-ch-ua',
'sec-ch-ua-mobile', 'sec-ch-ua-platform', 'sec-fetch-site'
];
for (const header of excludedHeaders) {
delete newHeaders[header];
}
const init = {
method: req.method,
headers: newHeaders,
};
if (req.method.toLowerCase() !== 'get') {
let body = await toBuffer(req.body);
body = body.toString('utf8');
if (body !== undefined) {
init['body'] = body;
}
}
const respP = await fetch(destProxyUrl, init);
console.log(`[${respP.status}] - Sending response with status ${respP.statusText}`);
return respP;
} else {
console.log(`[404] - File ${pathname} not found`);
return new Response("File not found", {status: 404});
}
}
},
error(e) {
console.error("Error occurred:", e);
return new Response("Internal Server Error", {status: 500});
},
});
console.log(`Server running at http://${flags.host}:${serverPort}`);
if (flags.proxyHost) {
console.log(`Server proxying at ${flags.proxyHost}`);
}
}