71 lines
1.8 KiB
JavaScript
71 lines
1.8 KiB
JavaScript
import { unlinkSync } from 'node:fs';
|
|
import { resolve } from 'path';
|
|
const transpiler = Bun.Transpiler({
|
|
loader: 'cjs',
|
|
});
|
|
|
|
export default {
|
|
port: Bun.env.BUN_PORT || Bun.env.APP_PORT || 3000,
|
|
async fetch(req) {
|
|
const magicKey = Math.random().toString(36).substring(2, 10);
|
|
const url = new URL(req.url);
|
|
if (url.pathname == '/main.js') {
|
|
const path = resolve(__dirname, `./.cache/`);
|
|
const filename = `${magicKey}.js`;
|
|
const filePath = resolve(path, filename);
|
|
const file = Bun.file(filePath);
|
|
const result = await Bun.build({
|
|
entrypoints: ['./src/main.js'],
|
|
outdir: path,
|
|
target: 'browser',
|
|
splitting: true,
|
|
naming: `[dir]/${filename}`,
|
|
});
|
|
|
|
let content = await file.arrayBuffer();
|
|
let headers = {
|
|
'Cache-Control': 'no-cache',
|
|
'Content-Length': file.size,
|
|
'Content-Type': file.type,
|
|
};
|
|
|
|
if (req.headers.get('accept-encoding').includes('gzip')) {
|
|
headers['Content-Encoding'] = 'gzip';
|
|
headers['Vary'] = 'Accept-Encoding';
|
|
content = Bun.gzipSync(content);
|
|
}
|
|
|
|
const resp = new Response(content, {
|
|
headers,
|
|
});
|
|
|
|
setTimeout(() => {
|
|
unlinkSync(filePath);
|
|
}, 400);
|
|
|
|
return resp;
|
|
}
|
|
if (url.pathname == '/') {
|
|
const file = Bun.file(resolve('./index.html'));
|
|
let content = await file.arrayBuffer();
|
|
let headers = {
|
|
'Cache-Control': 'no-cache',
|
|
'Content-Length': file.size,
|
|
'Content-Type': file.type,
|
|
};
|
|
|
|
if (req.headers.get('accept-encoding').includes('gzip')) {
|
|
headers['Content-Encoding'] = 'gzip';
|
|
headers['Vary'] = 'Accept-Encoding';
|
|
content = Bun.gzipSync(content);
|
|
}
|
|
|
|
console.log(headers, req.headers.get('accept-encoding'));
|
|
return new Response(content, {
|
|
headers,
|
|
});
|
|
}
|
|
return new Response('ERR 404: Not Found', { status: 404 });
|
|
},
|
|
};
|