Skip to content

gitflarePublicPartly agent-ready40

neon-drift

Real-time multiplayer arcade racer on Cloudflare Workers and Durable Objects.

Add the Apache-2.0 licence3efe3da
TypeScript43 lines1.6 KB
import { Room } from './room.ts';import { Lobby } from './lobby.ts';import { topScores } from './leaderboard.ts';import { isValidCode, makeCode } from './room-logic.ts'; export { Room, Lobby }; interface Env { ROOM: any; LOBBY: any; DB?: any; ASSETS: any } const json = (body: unknown, status = 200) => Response.json(body, { status }); export default {  async fetch(request: Request, env: Env): Promise<Response> {    const url = new URL(request.url);    const lobby = env.LOBBY.get(env.LOBBY.idFromName('global'));    if (url.pathname === '/health') {      const s = await lobby.stats();      return json({ ok: true, rooms: s.rooms, players: s.players });    }    if (url.pathname === '/api/rooms' && request.method === 'POST') {      return json({ code: makeCodeSecure() });    }    if (url.pathname === '/api/quickplay') return json({ code: await lobby.quickplay() });    if (url.pathname === '/api/leaderboard') {      return json(await topScores(env.DB, url.searchParams.get('mode') ?? 'arena'));    }    if (url.pathname.startsWith('/ws/')) {      const code = url.pathname.slice(4).toUpperCase();      if (!isValidCode(code)) return new Response('bad code', { status: 400 });      if (request.headers.get('Upgrade') !== 'websocket') return new Response('upgrade required', { status: 426 });      return env.ROOM.get(env.ROOM.idFromName(code)).fetch(request);    }    return env.ASSETS.fetch(request);  },}; function makeCodeSecure(): string {  const a = new Uint32Array(6);  crypto.getRandomValues(a);  let i = 0;  return makeCode((n) => a[i++ % 6] % n);}