logigate/server/utils/puzzles.ts

97 lines
3.7 KiB
TypeScript
Raw Normal View History

// Published puzzles and their scores, as JSON files under data/puzzles:
// specs:<id> holds the puzzle, scores:<id> the best score of each player.
// The puzzle of the week is generated, so only its scores are stored.
import type { H3Event } from 'h3'
import { cleanPuzzle, isWeekKey, weekKey, weeklyPuzzle } from '../../app/lib/logic/puzzles'
import type { PuzzleSpec } from '../../app/lib/logic/types'
export interface PuzzleRecord {
spec: PuzzleSpec
created: number
}
export interface Entry {
t: number
d: number | null
at: number
}
export type ScoreBoard = Record<string, Entry>
export const puzzleStorage = () => useStorage('puzzles')
export const isPlayer = (v: unknown): v is string => typeof v === 'string' && /^[A-Za-z0-9_-]{8,40}$/.test(v)
/** The puzzle behind an API id: a link id, or "week-2026-43" for a weekly one up to this week. */
export async function findPuzzle(id: string | undefined): Promise<PuzzleSpec | null> {
if (!id) return null
const week = /^week-(\d{4}-\d{2})$/.exec(id)?.[1]
if (week) return isWeekKey(week) && week <= weekKey() ? weeklyPuzzle(week) : null
if (!isShareId(id)) return null
const rec = await puzzleStorage().getItem<PuzzleRecord>(`specs:${id}`)
return rec ? cleanPuzzle(rec.spec, `pz:${id}`) : null
}
/** One write at a time per puzzle, so two scores arriving together both count. */
const queues = new Map<string, Promise<unknown>>()
export function locked<T>(key: string, fn: () => Promise<T>): Promise<T> {
const prev = queues.get(key) ?? Promise.resolve()
const next = prev.then(fn, fn)
queues.set(
key,
next.catch(() => {}),
)
return next
}
export interface Summary {
players: number
/** Transistor counts and how many players have each, fewest first. */
histogram: { t: number; n: number }[]
/** This player's best and place (1 = best), when they have a score. */
you?: { t: number; d: number | null; rank: number }
/** The best ten: fewest transistors, then shortest delay, then first to get there. */
top: { name: string; t: number; d: number | null; you?: true }[]
}
/** Names players chose for leaderboards, by player id. */
export async function playerNames(): Promise<Record<string, string>> {
return (await puzzleStorage().getItem<Record<string, string>>('players')) ?? {}
}
/** A leaderboard name: letters, digits, spaces and a little punctuation, at most 24 characters. */
export function cleanName(v: unknown): string {
if (typeof v !== 'string') return ''
return v
.normalize('NFC')
.replace(/[^\p{L}\p{N} ._\-'!?&+#]/gu, '')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 24)
}
export function summarize(board: ScoreBoard, player?: string, names: Record<string, string> = {}): Summary {
const entries = Object.values(board)
const counts = new Map<number, number>()
for (const e of entries) counts.set(e.t, (counts.get(e.t) ?? 0) + 1)
const histogram = [...counts.entries()].sort((a, b) => a[0] - b[0]).map(([t, n]) => ({ t, n }))
const mine = player ? board[player] : undefined
const top = Object.entries(board)
.sort(([, a], [, b]) => a.t - b.t || (a.d ?? Infinity) - (b.d ?? Infinity) || a.at - b.at)
.slice(0, 10)
.map(([id, e]) => ({ name: names[id] ?? '', t: e.t, d: e.d, ...(id === player ? { you: true as const } : {}) }))
const summary: Summary = { players: entries.length, histogram, top }
if (mine) summary.you = { t: mine.t, d: mine.d, rank: 1 + entries.filter(e => e.t < mine.t).length }
return summary
}
export async function board(id: string): Promise<ScoreBoard> {
return (await puzzleStorage().getItem<ScoreBoard>(`scores:${id}`)) ?? {}
}
export function playerParam(event: H3Event): string | undefined {
const p = getQuery(event).player
return isPlayer(p) ? p : undefined
}