| 1 | import { createServer } from 'node:http'; |
| 2 | import { createReadStream } from 'node:fs'; |
| 3 | import { stat } from 'node:fs/promises'; |
| 4 | import { extname, join, resolve } from 'node:path'; |
| 5 | import { fileURLToPath } from 'node:url'; |
| 6 | import { attachRooms } from './rooms.ts'; |
| 7 | |
| 8 | /** |
| 9 | * The whole production stack in one process: the built game out of dist/, and |
| 10 | * the room relay on /ws of the same origin. `npm run build && npm run serve`. |
| 11 | * In development this file is not involved — vite serves the game and |
| 12 | * vite.config.ts attaches the same relay to vite's own server. |
| 13 | */ |
| 14 | |
| 15 | const DIST = resolve(fileURLToPath(import.meta.url), '../../dist'); |
| 16 | const PORT = process.env.PORT ? Number(process.env.PORT) : 8080; |
| 17 | const HOST = process.env.HOST || '0.0.0.0'; |
| 18 | |
| 19 | const MIME: Record<string, string> = { |
| 20 | '.html': 'text/html; charset=utf-8', |
| 21 | '.js': 'text/javascript', |
| 22 | '.css': 'text/css', |
| 23 | '.svg': 'image/svg+xml', |
| 24 | '.png': 'image/png', |
| 25 | '.mp3': 'audio/mpeg', |
| 26 | '.json': 'application/json', |
| 27 | '.webmanifest': 'application/manifest+json', |
| 28 | '.ico': 'image/x-icon', |
| 29 | '.txt': 'text/plain; charset=utf-8', |
| 30 | '.map': 'application/json', |
| 31 | '.woff2': 'font/woff2', |
| 32 | }; |
| 33 | |
| 34 | const server = createServer(async (req, res) => { |
| 35 | const pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://localhost').pathname); |
| 36 | const file = resolve(join(DIST, pathname === '/' ? 'index.html' : pathname)); |
| 37 | if (!file.startsWith(DIST)) { |
| 38 | res.writeHead(403).end(); |
| 39 | return; |
| 40 | } |
| 41 | try { |
| 42 | const s = await stat(file); |
| 43 | if (!s.isFile()) throw new Error('not a file'); |
| 44 | const ext = extname(file); |
| 45 | res.writeHead(200, { |
| 46 | 'content-type': MIME[ext] ?? 'application/octet-stream', |
| 47 | 'content-length': s.size, |
| 48 | // Hashed assets may be kept forever; everything else asks again. |
| 49 | 'cache-control': pathname.startsWith('/assets/') |
| 50 | ? 'public, max-age=31536000, immutable' |
| 51 | : 'no-cache', |
| 52 | }); |
| 53 | createReadStream(file).pipe(res); |
| 54 | } catch { |
| 55 | res.writeHead(404, { 'content-type': 'text/plain' }).end('not found\n'); |
| 56 | } |
| 57 | }); |
| 58 | |
| 59 | attachRooms(server); |
| 60 | // Upgrades to anything but /ws have no other takers here — hang up. |
| 61 | server.on('upgrade', (req, socket) => { |
| 62 | if (new URL(req.url ?? '/', 'http://localhost').pathname !== '/ws') socket.destroy(); |
| 63 | }); |
| 64 | |
| 65 | server.listen(PORT, HOST, async () => { |
| 66 | const built = await stat(join(DIST, 'index.html')).catch(() => null); |
| 67 | console.log(`mahjong on http://${HOST}:${PORT} — rooms on /ws`); |
| 68 | if (!built) console.log('dist/ is empty — run `npm run build` first'); |
| 69 | }); |