blobgulp / arena.js
CyberMax-tools's picture
Deploy blobgulp
9d1d0d5 verified
Raw History Blame Contribute Delete
16.5 kB
// CyberMax Arena: the cheap social layer of the CyberMax games (31 Oct 2026). Copied into each game by
// scripts/games/sync_kit.py (web/arena.js, or src/arena.js for bundled games), so every game stays self-contained.
// Goal: a game can go viral without breaking anything or running up Worker requests (docs/ceo/games-scale-2026-10-31.md).
// * counts: summed on the device, ONE beacon per session (on hide/close), sampled 1-in-w in high-traffic modes
// with the weight sent along, so the totals stay right
// * boards: read at most once per 5/15/60 minutes per device (normal/high/surge), else from this device's copy,
// else from the static snapshot on cybermaxtools.com (free), else "offline"; the game never waits on it
// * posts: skipped on the device when the score can't reach the top 20 (and no friend group needs it), queued on the
// device in surge mode or when the board is busy, and sent later by drain(); never an error for the player
// * friend groups (6-letter code, no accounts), weekly cups (ISO week, the week's Monday course), head-to-head records
// Nothing personal: a random device tag (for friend boards), the name the player typed, scores. (c) 2026 CyberMax.
export const ARENA_API = 'https://toys.cybermaxtools.com';
export const POLICY = {
normal: { w: 1, board: 5 * 60e3 },
high: { w: 10, board: 15 * 60e3 },
surge: { w: 100, board: 60 * 60e3 },
};
export const BOARD_SIZE = 20;
const G = globalThis;
const CODE_RX = /^[A-HJ-NP-Z2-9]{6}$/;
const CODE_ABC = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
// ------------------------------------------------------------------ storage (never throws: private mode, blocked storage)
export function ls(key, val) {
try {
if (val === undefined) return JSON.parse(G.localStorage.getItem(key) || 'null');
if (val === null) G.localStorage.removeItem(key); else G.localStorage.setItem(key, JSON.stringify(val));
} catch { /* private mode */ }
return val;
}
const now = () => Date.now();
const host = () => { try { return G.location.hostname || ''; } catch { return ''; } };
/** Our own test runs and local copies send nothing (tests opt in with window.__cmxBeaconTest). */
export function quiet() {
if (G.__cmxBeaconTest) return false;
if (G.__cmxNoBeacon) return true; // portals that allow no outside analytics (set by the platform adapter)
return /^(localhost|127\.|0\.0\.0\.0|\[::1\])/.test(host()) || !!(G.navigator && G.navigator.webdriver);
}
// ------------------------------------------------------------------ traffic mode hint
/** The mode this device last heard (from a board answer or the static /games/traffic.json), else normal. */
export function traffic() {
const h = ls('cmx-traffic');
return h && h.until > now() && POLICY[h.mode] ? h.mode : 'normal';
}
export function noteMode(mode, ttl = 30 * 60e3) {
if (!POLICY[mode]) return;
const h = ls('cmx-traffic');
if (h && h.forced && h.until > now()) return; // a forced mode from the static file wins until it expires
ls('cmx-traffic', { mode, until: now() + ttl });
}
/** Reads /games/traffic.json at most every 6 hours (a free static file; the owner or an agent can force a mode there). */
export async function loadTraffic(base = '') {
try {
if (!G.__cmxTrafficBase && !/(^|\.)cybermaxtools\.com$/.test(host())) return traffic();
const seen = ls('cmx-traffic-file');
if (seen && now() - seen < 6 * 3600e3) return traffic();
ls('cmx-traffic-file', now());
const r = await G.fetch(`${G.__cmxTrafficBase || base || ''}/games/traffic.json`, { cache: 'no-cache', signal: timeout(3000) });
const j = r.ok ? await r.json() : null;
if (j && POLICY[j.mode]) ls('cmx-traffic', { mode: j.mode, until: now() + 6 * 3600e3, forced: true });
} catch { /* offline: keep what we had */ }
return traffic();
}
const timeout = (ms) => (G.AbortSignal && G.AbortSignal.timeout ? G.AbortSignal.timeout(ms) : undefined);
// ------------------------------------------------------------------ counts: one beacon per session
const pend = new Map(); // game -> { "ev:ch": n }
let pendN = 0, hooked = false;
export const sent = []; // beacons sent by this page (tests read it)
const cleanCh = (c) => String(c || '').toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 40);
/** Count one event. Free: nothing leaves the device until the page is hidden or closed (or 60 events pile up). */
export function tally(game, ev, ch = '') {
const c = cleanCh(ch);
try { G.dispatchEvent && G.dispatchEvent(new G.CustomEvent('cmx:count', { detail: { game, ev, ch: c } })); } catch { /* old browser */ }
if (quiet()) return;
const k = `${ev}:${cleanCh((G.__cmxChPrefix || '') + c)}`;
const m = pend.get(game) || {};
m[k] = (m[k] || 0) + 1;
pend.set(game, m);
pendN++;
if (!hooked && G.addEventListener) {
hooked = true;
G.addEventListener('pagehide', () => flush('pagehide'));
if (G.document) G.document.addEventListener('visibilitychange', () => { if (G.document.visibilityState === 'hidden') flush('hidden'); });
}
if (pendN >= 60) flush('full');
}
export const pending = () => Object.fromEntries([...pend].map(([g, m]) => [g, { ...m }]));
/** Send what is pending: one beacon per game, kept with probability 1/w and weighted by w (unbiased totals). */
export function flush(why = '') {
let n = 0;
const w = POLICY[traffic()].w;
for (const [game, m] of pend) {
if (!Object.keys(m).length) continue;
if ((G.__cmxRandom || Math.random)() * w < 1) {
const body = JSON.stringify({ t: game, n: m, w });
try {
const ok = G.navigator && G.navigator.sendBeacon && G.navigator.sendBeacon(`${ARENA_API}/eb`, new G.Blob([body], { type: 'text/plain' }));
if (!ok) G.fetch(`${ARENA_API}/eb`, { method: 'POST', body, keepalive: true, mode: 'no-cors', headers: { 'content-type': 'text/plain' } }).catch(() => {});
} catch { /* never break the game */ }
sent.push({ game, n: { ...m }, w, why });
n++;
}
}
pend.clear();
pendN = 0;
return n;
}
// ------------------------------------------------------------------ weeks (same maths as the toys Worker, social.js)
export function weekOf(iso) {
const [y, m, d] = iso.split('-').map(Number);
const t = new Date(Date.UTC(y, m - 1, d));
t.setUTCDate(t.getUTCDate() - ((t.getUTCDay() + 6) % 7) + 3);
const wy = t.getUTCFullYear();
return `${wy}-W${String(Math.floor((t - Date.UTC(wy, 0, 1)) / 864e5 / 7) + 1).padStart(2, '0')}`;
}
export function mondayOf(wk) {
const y = +wk.slice(0, 4), w = +wk.slice(6);
const jan4 = Date.UTC(y, 0, 4), dow = (new Date(jan4).getUTCDay() + 6) % 7;
return new Date(jan4 - dow * 864e5 + (w - 1) * 7 * 864e5).toISOString().slice(0, 10);
}
/** Cup number: #1 = the week of 2 Nov 2026 (the first full week after launch). */
export const cupNumber = (wk) => Math.round((Date.parse(mondayOf(wk)) - Date.parse('2026-11-02')) / (7 * 864e5)) + 1;
function stillOpen(d, today) {
const t = Date.parse(today);
if (/^\d{4}-\d{2}-\d{2}$/.test(d)) return Math.abs(Date.parse(d) - t) <= 864e5;
const day = (o) => new Date(t + o * 864e5).toISOString().slice(0, 10);
return [day(-1), day(0), day(1)].some((x) => weekOf(x) === d);
}
// ------------------------------------------------------------------ boards (read through this device's copy)
const slim = (j) => ({ top: (j.top || []).slice(0, BOARD_SIZE).map((e) => ({ name: e.name, score: e.score })), cut: j.cut || 0,
ghost: j.ghost && typeof j.ghost.taps === 'string' && j.ghost.taps.length <= 12000 ? j.ghost : null, mode: j.mode || '' });
const cutOf = (j) => (j && j.top && j.top.length >= BOARD_SIZE ? (j.cut || j.top[j.top.length - 1].score) : 0);
export function cachedBoard(game, d) { const c = ls(`cmx-board:${game}:${d}`); return c ? { ...c.j, at: c.at } : null; }
function keepBoard(game, d, j) {
ls(`cmx-board:${game}:${d}`, { at: now(), j: slim(j) });
// keep at most 8 board copies on the device
try {
const keys = []; for (let i = 0; i < G.localStorage.length; i++) { const k = G.localStorage.key(i); if (k && k.startsWith('cmx-board:')) keys.push(k); }
if (keys.length > 8) keys.map((k) => [k, (ls(k) || {}).at || 0]).sort((a, b) => a[1] - b[1]).slice(0, keys.length - 8).forEach(([k]) => ls(k, null));
} catch { /* storage blocked */ }
}
/** A board: { top, cut, ghost, mode, src: live|cache|snapshot|stale } or null when nothing is reachable. */
export async function board(game, d, { fresh = false, wait = 4500 } = {}) {
const c = ls(`cmx-board:${game}:${d}`);
if (!fresh && c && now() - c.at < POLICY[traffic()].board) return { ...c.j, src: 'cache' };
try {
const r = await G.fetch(`${ARENA_API}/api/board?g=${encodeURIComponent(game)}&d=${encodeURIComponent(d)}`, { signal: timeout(wait) });
if (r.ok) {
const j = await r.json();
if (j.mode) noteMode(j.mode);
keepBoard(game, d, j);
return { ...slim(j), src: 'live' };
}
} catch { /* offline or capped: fall through */ }
const snap = await snapshot(game, d);
if (snap) return { ...snap, src: 'snapshot' };
return c ? { ...c.j, src: 'stale' } : null;
}
/** The static board snapshot written at site build (scripts/games/board_snapshot.py), free to read. */
async function snapshot(game, d) {
try {
if (!G.__cmxSnapshotBase && !/(^|\.)cybermaxtools\.com$/.test(host())) return null;
const r = await G.fetch(`${G.__cmxSnapshotBase || ''}/games/boards/${game}.json`, { signal: timeout(3000) });
const j = r.ok ? await r.json() : null;
const b = j && j.boards && j.boards[d];
return b ? slim(b) : null;
} catch { return null; }
}
// ------------------------------------------------------------------ device tag, friend groups
export function tag() {
let p = ls('cmx-p');
if (!/^[a-z0-9]{8}$/.test(p || '')) { p = ''; for (let i = 0; i < 8; i++) p += 'abcdefghijkmnpqrstuvwxyz23456789'[Math.floor(Math.random() * 32)]; ls('cmx-p', p); }
return p;
}
export const cleanNick = (n) => String(n || '').replace(/[^A-Za-z0-9 ]/g, '').replace(/\s+/g, ' ').trim().slice(0, 10);
export const myGroups = () => (Array.isArray(ls('cmx-groups')) ? ls('cmx-groups').filter((g) => CODE_RX.test(g.code)) : []);
export function joinGroup(code) {
code = String(code || '').toUpperCase();
if (!CODE_RX.test(code)) return false;
const gs = myGroups().filter((g) => g.code !== code);
gs.unshift({ code, at: now() });
ls('cmx-groups', gs.slice(0, 3)); // at most 3 groups per device
return true;
}
export function leaveGroup(code) { ls('cmx-groups', myGroups().filter((g) => g.code !== code)); }
export function newGroup() {
let c = ''; for (let i = 0; i < 6; i++) c += CODE_ABC[Math.floor(Math.random() * CODE_ABC.length)];
joinGroup(c);
return c;
}
/** ?fg=CODE in the link joins that group (returns the code, or ''). */
export function groupFromUrl(search) {
try { const c = new URLSearchParams(search ?? G.location.search).get('fg'); return c && joinGroup(c) ? c.toUpperCase() : ''; } catch { return ''; }
}
export function groupLink(url, code) { const u = new URL(url); u.searchParams.set('fg', code); return u.toString(); }
export async function groupBoard(game, code, d, { fresh = false } = {}) {
const key = `cmx-group:${game}:${code}:${d}`, c = ls(key);
if (!fresh && c && now() - c.at < POLICY[traffic()].board) return { ...c.j, src: 'cache' };
try {
const r = await G.fetch(`${ARENA_API}/api/group?g=${encodeURIComponent(game)}&d=${encodeURIComponent(d)}&code=${code}`, { signal: timeout(4500) });
if (r.ok) { const j = await r.json(); if (j.mode) noteMode(j.mode); const v = { top: (j.top || []).slice(0, 50) }; ls(key, { at: now(), j: v }); return { ...v, src: 'live' }; }
} catch { /* offline */ }
return c ? { ...c.j, src: 'stale' } : null;
}
const gbestKey = (game, code, d) => `${game}|${code}|${d}`;
function gbest(game, code, d, score) {
const m = ls('cmx-gbest') || {};
if (score === undefined) return m[gbestKey(game, code, d)] || 0;
m[gbestKey(game, code, d)] = score;
const ks = Object.keys(m); if (ks.length > 60) for (const k of ks.slice(0, ks.length - 60)) delete m[k];
ls('cmx-gbest', m);
return score;
}
// ------------------------------------------------------------------ posting (gated, queued, never an error)
/**
* Post a run to the daily (d = YYYY-MM-DD) or weekly (d = YYYY-Www) board and the player's friend groups.
* Returns { state: posted|skipped|queued|refused, rank, score, message, groups }.
*/
export async function post(game, d, { name, taps, score, nick = '', groups = true, today = '' } = {}) {
const gs = groups ? myGroups().map((g) => g.code).filter((code) => score > gbest(game, code, d)) : [];
const c = cachedBoard(game, d);
const cut = cutOf(c);
if (cut && score <= cut && !gs.length) return { state: 'skipped', rank: 0, score, cut, message: `Saved on this device. The top 20 starts at ${cut.toLocaleString('en-US')}.` };
const item = { game, d, name, taps, score, nick: cleanNick(nick) || name, gs, at: now(), today };
if (traffic() === 'surge') return queue(item, 'Busy moment on the board: saved, and it posts on its own later.');
return send(item);
}
async function send(item) {
let r;
try {
r = await G.fetch(`${ARENA_API}/api/board`, { method: 'POST', headers: { 'content-type': 'application/json' }, signal: timeout(8000),
body: JSON.stringify({ g: item.game, d: item.d, name: item.name, taps: item.taps, s: item.score, groups: item.gs, p: item.gs.length ? tag() : undefined, nick: item.nick }) });
} catch { return queue(item, 'Offline for now: saved, and it posts on its own later.'); }
let j = null; try { j = await r.json(); } catch { /* not JSON */ }
if (r.ok && j && j.ok) {
if (j.mode) noteMode(j.mode);
if (Array.isArray(j.top)) keepBoard(item.game, item.d, j);
for (const g of j.groups || []) if (g && g.best) gbest(item.game, g.code, item.d, g.best);
return { state: 'posted', rank: j.rank || 0, score: j.score ?? item.score, groups: j.groups || [], checked: j.checked !== false,
message: j.rank ? `Posted! You're #${j.rank}.` : 'Posted! Not in the top 20 yet. Keep going.' };
}
if (r.status === 422 || r.status === 400) return { state: 'refused', rank: 0, score: item.score, message: (j && j.message) || 'That run could not be posted.' };
return queue(item, 'The board is busy: saved, and it posts on its own later.');
}
function queue(item, message) {
const q = (ls('cmx-q') || []).filter((x) => !(x.game === item.game && x.d === item.d && x.score >= item.score));
if (!q.some((x) => x.game === item.game && x.d === item.d)) q.push(item);
else for (let i = 0; i < q.length; i++) if (q[i].game === item.game && q[i].d === item.d) q[i] = item;
ls('cmx-q', q.slice(-10));
return { state: 'queued', rank: 0, score: item.score, message };
}
export const queued = (game) => (ls('cmx-q') || []).filter((x) => !game || x.game === game);
/** Send at most ONE queued post for this game (call once at boot); drops posts whose day or week has closed. */
export async function drain(game, today) {
if (traffic() === 'surge') return null;
const q = ls('cmx-q') || [];
const keep = q.filter((x) => stillOpen(x.d, today || new Date().toISOString().slice(0, 10)));
const i = keep.findIndex((x) => x.game === game);
if (i < 0) { ls('cmx-q', keep); return null; }
const [item] = keep.splice(i, 1);
ls('cmx-q', keep);
return send(item);
}
// ------------------------------------------------------------------ head-to-head records (challenge links, on the device)
/** Record one finished challenge (id = the challenge link's run id); returns the record against that rival. */
export function h2hRecord(game, rival, id, mine, theirs) {
const all = ls('cmx-h2h') || {};
const g = all[game] || (all[game] = {});
const key = cleanNick(rival).toLowerCase() || 'friend';
const r = g[key] || (g[key] = { name: cleanNick(rival) || 'Friend', c: {} });
const prev = r.c[id];
if (!prev || mine > prev.mine) r.c[id] = { mine, theirs };
const ids = Object.keys(r.c); if (ids.length > 50) for (const k of ids.slice(0, ids.length - 50)) delete r.c[k];
ls('cmx-h2h', all);
return h2h(game, rival);
}
export function h2h(game, rival) {
const r = ((ls('cmx-h2h') || {})[game] || {})[cleanNick(rival).toLowerCase() || 'friend'];
const out = { name: r ? r.name : cleanNick(rival), w: 0, l: 0, t: 0 };
if (r) for (const { mine, theirs } of Object.values(r.c)) { if (mine > theirs) out.w++; else if (mine < theirs) out.l++; else out.t++; }
return out;
}