Skip to content
1        10        20        30        40        50        60        70        80        90        100       1101// Thin wrappers around the server API. Actions are POSTs; state and log2// messages come back over one Server-Sent Events stream.3import { emit } from './bus.js';45let playerId = null;67export const myId = () => playerId;89async function post(path, body) {10  const res = await fetch(path, {11    method: 'POST',12    headers: { 'content-type': 'application/json' },13    body: JSON.stringify(body),14  });15  if (res.status === 404) emit('lost');16  return res;17}1819export async function fetchMap() {20  const res = await fetch('/api/map');21  return res.json();22}2324export async function join(name, look) {25  const res = await post('/api/join', { name, look });26  if (!res.ok) throw new Error(await res.text());27  playerId = (await res.json()).id;28  return playerId;29}3031export function sendInput(dx, dy) {32  return post('/api/input', { id: playerId, dx, dy });33}3435export function sendAction() {36  return post('/api/action', { id: playerId });37}3839// Used on page hide: sendBeacon survives the page going away.40export function sendLeave() {41  if (!playerId) return;42  navigator.sendBeacon('/api/leave', new Blob([JSON.stringify({ id: playerId })], { type: 'application/json' }));43}4445export function connectEvents() {46  const source = new EventSource('/api/events');47  source.addEventListener('state', (e) => emit('state', JSON.parse(e.data)));48  source.addEventListener('log', (e) => emit('log', JSON.parse(e.data)));49  return source;50}