import { Emitter } from "./emitter.js";
import { TokenBucket, WindowCounter } from "./limits.js";
import { cleanText, MAX_NAME, nameKey } from "./names.js";
import { deepEqual, diffAt, isObject, StateBox, toJson } from "./sync.js";
export const PROTOCOL = 1;
export const BYE = {
protocol: 4002,
"bad-key": 4003,
"no-room": 4004,
"no-player": 4005,
"name-taken": 4006,
"name-invalid": 4007,
"rate-limited": 4008,
replaced: 4009,
kicked: 4010,
"room-closed": 4011,
slow: 4013,
full: 4029,
locked: 4029,
"in-progress": 4030,
};
export const LATE_JOIN = ["closed", "wait", "open"];
export class PartyError extends Error {
code;
constructor(code, message = code) {
super(message);
this.name = "PartyError";
this.code = code;
}
}
function randomBytes(n) {
return crypto.getRandomValues(new Uint8Array(n));
}
const B64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
export function base64url(bytes) {
let out = "";
for (let i = 0; i < bytes.length; i += 3) {
const n = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
out += B64URL[(n >> 18) & 63] + B64URL[(n >> 12) & 63];
if (i + 1 < bytes.length)
out += B64URL[(n >> 6) & 63];
if (i + 2 < bytes.length)
out += B64URL[n & 63];
}
return out;
}
export function token() {
return base64url(randomBytes(16));
}
export function sameToken(a, b) {
if (typeof a !== "string" || a.length !== b.length)
return false;
let diff = 0;
for (let i = 0; i < a.length; i++)
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
return diff === 0;
}
const CODE_LETTERS = "BCDFGHJKLMNPQRSTVWXZ";
export function roomCode() {
return [...randomBytes(4)].map((x) => CODE_LETTERS[x % CODE_LETTERS.length]).join("");
}
export const HELLO_TIMEOUT = 5000;
const FAILED_HELLOS = 20;
function utf8Length(s) {
let n = 0;
for (let i = 0; i < s.length; i++) {
const c = s.charCodeAt(i);
if (c < 0x80)
n += 1;
else if (c < 0x800)
n += 2;
else if (c >= 0xd800 && c <= 0xdbff) {
n += 4;
i++;
}
else
n += 3;
}
return n;
}
const ACK_CACHE = 32;
const MAX_CONTROL_MESSAGE = 16 * 1024;
const MAX_INPUT = 4 * 1024;
export class Player {
role = "player";
id;
name;
vip = false;
waitingFlag = false;
state;
data = {};
joinedAt = Date.now();
resume;
lastAct = 0;
results = new Map();
client;
input;
constructor(id, name, changed) {
this.id = id;
this.name = name;
this.resume = token();
this.state = new StateBox(changed);
}
get connected() {
return this.client !== undefined;
}
get waiting() {
return this.waitingFlag;
}
toJSON() {
const o = { id: this.id, name: this.name, vip: this.vip, connected: this.connected };
if (this.waitingFlag)
o["waiting"] = true;
return o;
}
}
export class Client {
conn;
role;
id;
address;
player;
sent;
have = new Map();
rev = 0;
waiting = false;
bucket;
lastAct = 0;
inSeq = 0;
constructor(conn, role, id, address, rate, burst) {
this.conn = conn;
this.role = role;
this.id = id;
this.address = address;
this.bucket = new TokenBucket(rate, burst);
}
send(msg) {
return this.sendText(JSON.stringify(msg));
}
sendText(text) {
if (this.conn.closed)
return false;
this.conn.send(text);
return true;
}
bye(reason, message) {
bye(this.conn, reason, message);
}
}
let partySeq = 0;
export class Party extends Emitter {
code;
joinKey = token();
screenKey = token();
watchKey = token();
room;
screen;
maxPlayers;
grace;
uid = ++partySeq;
#join;
#players = [];
#clients = new Set();
#handlers = new Map();
#locked = false;
#lateJoin;
#inProgress = false;
#closed = false;
#seq = 0;
#screenSeq = 0;
#flushQueued = false;
#stats = { flushes: 0, states: 0, stateBytes: 0, flushMs: 0 };
#screenView;
#rosterSection = { version: 0, value: [] };
#joinSection = { version: 0, value: null };
#moderate;
#limits;
#log;
#failed = new WindowCounter(FAILED_HELLOS, 60_000);
onClose;
constructor(options = {}) {
super();
this.code = options.code ?? roomCode();
this.maxPlayers = options.maxPlayers ?? 8;
this.grace = options.grace ?? 500;
this.#moderate = options.moderate;
this.#limits = { rate: 20, burst: 50, screens: 16, ...options.limits };
this.#log = options.log ?? (() => { });
this.#lateJoin = options.lateJoin ?? "wait";
if (!LATE_JOIN.includes(this.#lateJoin))
throw new TypeError(`lateJoin: ${String(options.lateJoin)}`);
this.room = new StateBox(() => this.#changed());
this.screen = new StateBox(() => this.#changed());
this.#join = { code: this.code, url: "", qr: null };
}
now() {
return Date.now();
}
get players() {
return this.#players;
}
get connectedPlayers() {
return this.#players.filter((p) => p.connected);
}
get vip() {
return this.#players.find((p) => p.vip);
}
get locked() {
return this.#locked;
}
get closed() {
return this.#closed;
}
get joinInfo() {
return this.#join;
}
set joinInfo(info) {
this.#join = info;
this.#joinChanged();
}
get lateJoin() {
return this.#lateJoin;
}
set lateJoin(mode) {
if (!LATE_JOIN.includes(mode))
throw new TypeError(`lateJoin: ${String(mode)}`);
if (mode === this.#lateJoin)
return;
this.#lateJoin = mode;
this.#joinChanged();
}
get inProgress() {
return this.#inProgress;
}
set inProgress(on) {
if (on === this.#inProgress)
return;
this.#inProgress = on;
this.#joinChanged();
}
activate(p) {
if (!p.waitingFlag || !this.#players.includes(p))
return false;
p.waitingFlag = false;
this.emit("active", p);
this.#changed();
return true;
}
#joinValue() {
return toJson({ ...this.#join, lateJoin: this.#lateJoin, inProgress: this.#inProgress });
}
#joinChanged() {
this.#joinSection = { version: this.#joinSection.version + 1, value: this.#joinValue() };
this.#changed();
}
get stats() {
return { ...this.#stats };
}
player(id) {
return this.#players.find((p) => p.id === id);
}
screenView() {
this.#screenView ??= {
roster: this.#roster(),
screen: this.screen.peek(),
join: this.#joinValue(),
};
return this.#screenView;
}
playerView(p) {
return { roster: this.#roster(), room: this.room.peek(), me: p.state.peek() };
}
#roster() {
return this.#players.map((p) => p.toJSON());
}
lock() {
this.#locked = true;
}
unlock() {
this.#locked = false;
}
handle(type, handler) {
this.#handlers.set(type, handler);
return () => {
if (this.#handlers.get(type) === handler)
this.#handlers.delete(type);
};
}
moderate(text, kind, player) {
const r = this.#moderate?.(text, { kind, player });
if (r === false)
return false;
return typeof r === "string" ? r : text;
}
send(to, type, data = null) {
to.client?.send({ t: "msg", type, data: toJson(data) });
}
broadcast(type, data = null, role = "player") {
const msg = { t: "msg", type, data: toJson(data) };
for (const c of this.#clients)
if (role === "all" || c.role === role)
c.send(msg);
}
kick(player, reason = "kicked") {
player.client?.bye("kicked", reason);
this.#remove(player, "kicked");
}
makeVip(player) {
if (player.vip || !this.#players.includes(player))
return;
for (const p of this.#players)
p.vip = false;
player.vip = true;
this.#log("info", `party ${this.code}: ${player.name} is the VIP`);
this.emit("vip", player);
this.#changed();
}
close() {
if (this.#closed)
return;
this.#closed = true;
for (const c of this.#clients)
c.bye("room-closed");
this.#clients.clear();
this.onClose?.();
}
collect(type, options = {}) {
const from = new Set(options.from ?? this.#players);
const answers = new Map();
const grace = options.grace ?? this.grace;
return new Promise((resolve) => {
let done = false;
let timer;
const finish = () => {
if (done)
return;
done = true;
if (timer)
clearTimeout(timer);
off();
this.off("away", check);
this.off("leave", onLeave);
options.signal?.removeEventListener("abort", finish);
resolve(answers);
};
const check = () => {
if (from.size === 0)
return finish();
const all = [...from];
if (options.until !== undefined && !options.skipAway) {
if (all.every((p) => answers.has(p)))
finish();
return;
}
if (!all.some((p) => p.connected))
return;
if (all.every((p) => answers.has(p) || !p.connected))
finish();
};
const onLeave = (p) => {
from.delete(p);
check();
};
const off = this.handle(type, (data, sender) => {
if (sender.role !== "player" || !from.has(sender))
throw new PartyError("not-asked", "Not your turn");
if (answers.has(sender) && !options.replace)
throw new PartyError("already-answered", "Already sent");
const value = options.validate ? options.validate(data, sender) : data;
answers.set(sender, value);
options.onAnswer?.(sender, value, answers);
queueMicrotask(check);
return options.reply ? options.reply(value, sender) : null;
});
this.on("away", check);
this.on("leave", onLeave);
options.signal?.addEventListener("abort", finish, { once: true });
if (options.signal?.aborted)
return finish();
if (options.until !== undefined) {
timer = setTimeout(finish, Math.max(0, options.until + grace - this.now()));
}
check();
});
}
listen(relay) {
relay.onopen = (conn) => this.accept(conn);
relay.onclosing = () => this.close();
return this;
}
accept(conn) {
const address = conn.address;
if (this.#closed)
return bye(conn, "room-closed");
if (this.#failed.over(address)) {
this.#log("warn", `party ${this.code}: too many failed joins from ${address}`);
return bye(conn, "rate-limited");
}
const fail = (reason, message) => {
this.#failed.hit(address);
bye(conn, reason, message);
};
const timer = setTimeout(() => fail("protocol", "no hello"), HELLO_TIMEOUT);
conn.onclose = () => clearTimeout(timer);
conn.onmessage = (data) => {
clearTimeout(timer);
conn.onmessage = undefined;
conn.onclose = undefined;
let hello;
try {
hello = typeof data === "string" ? JSON.parse(data) : undefined;
}
catch {
hello = undefined;
}
if (!isObject(hello) || hello["t"] !== "hello" || hello["v"] !== PROTOCOL) {
return fail("protocol", "expected hello, version 1");
}
const code = typeof hello["room"] === "string" ? hello["room"].toUpperCase() : "";
if (code !== this.code) {
this.#log("warn", `party ${this.code}: hello for room ${JSON.stringify(code.slice(0, 8))} from ${address}`);
return fail("no-room");
}
this.attach(conn, hello, address, () => this.#failed.hit(address));
};
}
attach(ws, hello, address, failed = () => { }) {
if (this.#closed) {
bye(ws, "room-closed");
return;
}
const role = hello.role;
if (role === "screen" || role === "watch") {
const key = role === "screen" ? this.screenKey : this.watchKey;
if (!sameToken(hello.key, key)) {
this.#log("warn", `party ${this.code}: ${role} with a wrong key from ${address}`);
failed();
return bye(ws, "bad-key");
}
const screens = [...this.#clients].filter((c) => c.role !== "player").length;
if (screens >= this.#limits.screens)
return bye(ws, "full");
const c = new Client(ws, role, `s${++this.#screenSeq}`, address, this.#limits.rate, this.#limits.burst);
this.#adopt(c);
this.#welcome(c);
this.emit("screen", { role, id: c.id }, true);
return;
}
if (role !== "player")
return bye(ws, "protocol");
if (typeof hello.resume === "string") {
const p = this.#players.find((x) => sameToken(hello.resume, x.resume));
if (p) {
const old = p.client;
const c = new Client(ws, "player", p.id, address, this.#limits.rate, this.#limits.burst);
c.player = p;
p.client = c;
if (old) {
old.player = undefined;
old.bye("replaced");
this.#clients.delete(old);
}
this.#adopt(c);
this.#welcome(c);
this.#log("info", `party ${this.code}: ${p.name} is back`);
this.emit("reconnect", p);
this.#changed();
return;
}
}
if (!sameToken(hello.key, this.joinKey)) {
this.#log("warn", `party ${this.code}: a join with a wrong key from ${address}`);
failed();
return bye(ws, "bad-key");
}
if (hello.name === undefined || hello.name === null)
return bye(ws, "no-player");
if (this.#locked)
return bye(ws, "locked");
if (this.#inProgress && this.#lateJoin === "closed")
return bye(ws, "in-progress", "A game is in progress");
if (this.#players.length >= this.maxPlayers)
return bye(ws, "full");
let name = cleanText(hello.name, MAX_NAME);
if (!name)
return bye(ws, "name-invalid", "Pick a name");
const moderated = this.moderate(name, "name");
if (moderated === false)
return bye(ws, "name-invalid", "Pick another name");
name = cleanText(moderated, MAX_NAME);
if (!name)
return bye(ws, "name-invalid", "Pick a name");
const key = nameKey(name);
if (this.#players.some((p) => nameKey(p.name) === key))
return bye(ws, "name-taken", "Someone has that name");
const p = new Player(`p${++this.#seq}`, name, () => this.#changed());
p.waitingFlag = this.#inProgress;
const c = new Client(ws, "player", p.id, address, this.#limits.rate, this.#limits.burst);
c.player = p;
p.client = c;
this.#players.push(p);
if (!this.vip) {
p.vip = true;
}
this.#adopt(c);
this.#welcome(c);
this.#log("info", `party ${this.code}: ${name} joined (${address})`);
this.emit("join", p);
if (p.vip)
this.emit("vip", p);
this.#changed();
}
#adopt(c) {
this.#clients.add(c);
c.conn.onmessage = (data) => this.#onMessage(c, data);
c.conn.onclose = () => this.#onClose(c);
c.conn.ondrain = () => {
if (c.waiting) {
this.#refreshRoster();
this.#flushClient(c, new Map());
}
};
}
#refreshRoster() {
const roster = this.#roster();
if (!deepEqual(roster, this.#rosterSection.value))
this.#rosterSection = { version: this.#rosterSection.version + 1, value: roster };
}
#sections(c) {
const roster = { key: "roster", id: "roster", ...this.#rosterSection };
if (c.player) {
const p = c.player;
return [
roster,
{ key: "room", id: "room", version: this.room.version, value: this.room.snapshot() },
{ key: "me", id: `me:${p.id}`, version: p.state.version, value: p.state.snapshot() },
];
}
if (this.#joinSection.version === 0)
this.#joinSection = { version: 1, value: this.#joinValue() };
return [
roster,
{ key: "screen", id: "screen", version: this.screen.version, value: this.screen.snapshot() },
{ key: "join", id: "join", ...this.#joinSection },
];
}
#fullView(c) {
this.#refreshRoster();
const view = {};
c.have = new Map();
for (const s of this.#sections(c)) {
view[s.key] = s.value;
c.have.set(s.id, s.version);
}
c.sent = view;
return view;
}
#welcome(c) {
const view = this.#fullView(c);
c.rev = 0;
const you = { id: c.id, role: c.role };
if (c.player) {
you["name"] = c.player.name;
you["vip"] = c.player.vip;
you["resume"] = c.player.resume;
you["lastAct"] = c.player.lastAct;
}
c.send({ t: "welcome", v: PROTOCOL, room: { code: this.code }, you, now: this.now(), view, rev: 0 });
}
#onClose(c) {
this.#clients.delete(c);
const p = c.player;
if (p && p.client === c) {
p.client = undefined;
this.#log("info", `party ${this.code}: ${p.name} is away`);
this.emit("away", p);
this.#changed();
}
else if (c.role !== "player") {
this.emit("screen", { role: c.role, id: c.id }, false);
}
}
#remove(p, reason) {
const i = this.#players.indexOf(p);
if (i < 0)
return;
this.#players.splice(i, 1);
if (p.client) {
p.client.player = undefined;
p.client = undefined;
}
const wasVip = p.vip;
p.vip = false;
this.#log("info", `party ${this.code}: ${p.name} left (${reason})`);
this.emit("leave", p, reason);
if (wasVip) {
const next = this.#players.find((x) => x.connected) ?? this.#players[0];
if (next)
next.vip = true;
this.emit("vip", next);
}
this.#changed();
}
#onMessage(c, data) {
if (c.conn.closed)
return;
if (!c.bucket.take())
return c.bye("rate-limited");
if (typeof data !== "string")
return c.bye("protocol", "binary messages are not used");
let msg;
try {
msg = JSON.parse(data);
}
catch {
return c.bye("protocol", "not JSON");
}
if (!isObject(msg))
return c.bye("protocol", "not an object");
if (msg["t"] === "in" && data.length > MAX_INPUT)
return;
if (msg["t"] !== "act" && data.length > MAX_CONTROL_MESSAGE)
return c.bye("protocol", "too big");
switch (msg["t"]) {
case "act":
return void this.#onAct(c, msg);
case "ping":
c.send({ t: "pong", c: typeof msg["c"] === "number" ? msg["c"] : 0, now: this.now() });
return;
case "resync": {
const view = this.#fullView(c);
c.send({ t: "state", rev: ++c.rev, full: view });
return;
}
case "in": {
const seq = msg["s"];
const p = c.player;
if (!p || typeof seq !== "number" || !Number.isSafeInteger(seq) || seq <= c.inSeq)
return;
c.inSeq = seq;
p.input = msg["data"] ?? null;
this.emit("input", p, p.input);
return;
}
case "leave":
if (c.player) {
const p = c.player;
this.#remove(p, "left");
}
c.conn.close(1000, "left");
return;
default:
return; }
}
async #onAct(c, msg) {
const id = msg["id"];
const type = msg["type"];
if (typeof id !== "number" || !Number.isSafeInteger(id) || id <= 0 || typeof type !== "string") {
return c.bye("protocol", "bad act");
}
const data = msg["data"] ?? null;
if (c.role === "watch") {
c.send({ t: "ack", id, ok: false, error: { code: "read-only", message: "Watchers cannot act" } });
return;
}
const p = c.player;
if (!p) {
if (id <= c.lastAct)
return;
c.lastAct = id;
const ack = await this.#run(id, type, data, { role: c.role, id: c.id });
c.send(ack);
return;
}
if (id <= p.lastAct) {
const cached = p.results.get(id);
const ack = cached ? await cached : { t: "ack", id, ok: true, dup: true };
p.client?.send(ack);
return;
}
p.lastAct = id;
const pending = this.#run(id, type, data, p);
p.results.set(id, pending);
const ack = await pending;
p.results.set(id, ack);
while (p.results.size > ACK_CACHE)
p.results.delete(p.results.keys().next().value);
p.client?.send(ack);
}
async #run(id, type, data, from) {
const handler = this.#handlers.get(type);
if (!handler)
return { t: "ack", id, ok: false, error: { code: "unknown-action", message: `No ${type} now` } };
try {
const result = await handler(data, from);
const ack = { t: "ack", id, ok: true };
if (result !== undefined && result !== null)
ack.result = toJson(result);
return ack;
}
catch (err) {
if (err instanceof PartyError)
return { t: "ack", id, ok: false, error: { code: err.code, message: err.message } };
this.#log("error", `party ${this.code}: action ${type}: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`);
return { t: "ack", id, ok: false, error: { code: "internal", message: "Something went wrong" } };
}
}
#changed() {
this.#screenView = undefined;
if (this.#flushQueued)
return;
this.#flushQueued = true;
queueMicrotask(() => {
this.#flushQueued = false;
const t0 = performance.now();
this.#refreshRoster();
const diffs = new Map();
for (const c of this.#clients)
this.#flushClient(c, diffs);
this.#stats.flushes++;
this.#stats.flushMs += performance.now() - t0;
if (this.listenerCount("screen-view") > 0)
this.emit("screen-view", this.screenView());
});
}
#flushClient(c, diffs) {
if (c.conn.closed || !c.sent || (c.role === "player" && !c.player))
return;
if (c.conn.busy) {
c.waiting = true;
return;
}
c.waiting = false;
const sent = c.sent;
const set = [];
const del = [];
for (const s of this.#sections(c)) {
const had = c.have.get(s.id);
if (had === s.version)
continue;
const cacheKey = had === undefined ? undefined : `${s.id}:${had}`;
let d = cacheKey ? diffs.get(cacheKey) : undefined;
if (!d) {
const old = sent[s.key];
if (old !== undefined && isObject(old) && isObject(s.value)) {
const at = diffAt(old, s.value, [s.key]);
d = { del: at.del.map((p) => JSON.stringify(p)) };
if (Object.keys(at.set).length > 0)
d.set = `${JSON.stringify(s.key)}:${JSON.stringify(at.set)}`;
}
else if (old === undefined || !deepEqual(old, s.value)) {
d = { set: `${JSON.stringify(s.key)}:${JSON.stringify(s.value)}`, del: [] };
}
else {
d = { del: [] };
}
if (cacheKey)
diffs.set(cacheKey, d);
}
if (d.set)
set.push(d.set);
del.push(...d.del);
sent[s.key] = s.value;
c.have.set(s.id, s.version);
}
if (set.length === 0 && del.length === 0)
return;
let text = `{"t":"state","rev":${++c.rev}`;
if (set.length > 0)
text += `,"set":{${set.join(",")}}`;
if (del.length > 0)
text += `,"del":[${del.join(",")}]`;
text += "}";
this.#stats.states++;
this.#stats.stateBytes += utf8Length(text);
c.sendText(text);
}
}
function bye(conn, reason, message) {
if (conn.closed)
return;
const msg = { t: "bye", reason };
if (message)
msg["message"] = message;
conn.send(JSON.stringify(msg));
conn.close(BYE[reason], reason);
}
export { bye as sendBye };