CarboAny / scripts /hf-space-server.mjs
Esketch's picture
deploy: [P4] Strangler Pattern API Adapter Release (Orphan Clean Build v2)
daaf9d7
Raw
History Blame Contribute Delete
2.09 kB
import { existsSync } from 'node:fs';
import { join, resolve } from 'node:path';
const root = resolve(import.meta.dirname, '..');
const distDir = join(root, 'dist');
const port = Number(process.env.PORT || 7860);
if (!existsSync(join(distDir, 'index.html'))) {
const proc = Bun.spawnSync(['bun', 'run', 'build'], {
cwd: root,
stdout: 'inherit',
stderr: 'inherit',
env: process.env,
});
if (proc.exitCode !== 0) {
process.exit(proc.exitCode ?? 1);
}
}
const mimeByExt = {
'.css': 'text/css; charset=utf-8',
'.html': 'text/html; charset=utf-8',
'.ico': 'image/x-icon',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.map': 'application/json; charset=utf-8',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.webmanifest': 'application/manifest+json; charset=utf-8',
};
function contentType(pathname) {
const dot = pathname.lastIndexOf('.');
if (dot === -1) return 'application/octet-stream';
return mimeByExt[pathname.slice(dot)] ?? 'application/octet-stream';
}
function safePath(pathname) {
const decoded = decodeURIComponent(pathname.split('?')[0] || '/');
const normalized = decoded === '/' ? '/index.html' : decoded;
return join(distDir, normalized.replace(/^\/+/, ''));
}
Bun.serve({
hostname: '0.0.0.0',
port,
async fetch(request) {
const url = new URL(request.url);
const filePath = safePath(url.pathname);
const file = Bun.file(filePath);
if (await file.exists()) {
const isAsset = url.pathname.startsWith('/assets/');
return new Response(file, {
headers: {
'content-type': contentType(filePath),
'cache-control': isAsset
? 'public, max-age=31536000, immutable'
: 'no-cache',
},
});
}
const index = Bun.file(join(distDir, 'index.html'));
return new Response(index, {
headers: {
'content-type': 'text/html; charset=utf-8',
'cache-control': 'no-cache',
},
});
},
});
console.log(`CarboAny Space server listening on 0.0.0.0:${port}`);