// Submit a solution. The server runs the puzzle's checks on it and counts // its transistors itself, so a score can't be made up. Each player keeps // their best: fewer transistors, then shorter delay. import { toProject } from '../../../../app/lib/logic/project' import { scoreSolution } from '../../../../app/lib/logic/puzzles' export default defineEventHandler(async event => { rateLimit(event, 'score', 60, 10 * 60_000) const id = getRouterParam(event, 'id') const spec = await findPuzzle(id) if (!spec || !id) throw createError({ statusCode: 404, message: 'Puzzle not found' }) const raw = await readRawBody(event, 'utf8') if (!raw) throw createError({ statusCode: 400, message: 'Empty request' }) if (raw.length > 2_000_000) throw createError({ statusCode: 413, message: 'Solution too large' }) let body: { player?: unknown; defId?: unknown; components?: unknown } try { body = JSON.parse(raw) } catch { throw createError({ statusCode: 400, message: 'Not valid JSON' }) } if (!isPlayer(body.player) || typeof body.defId !== 'string') throw createError({ statusCode: 400, message: 'Missing player or circuit' }) let components try { components = toProject({ components: body.components, name: 'solution' }).components } catch (e) { throw createError({ statusCode: 400, message: (e as Error).message }) } const score = scoreSolution(components, body.defId, spec) if (!score.pass) return { score, summary: summarize(await board(id), body.player) } const player = body.player const summary = await locked(id, async () => { const scores = await board(id) const old = scores[player] const better = !old || score.transistors < old.t || (score.transistors === old.t && (score.delay ?? Infinity) < (old.d ?? Infinity)) if (better) { scores[player] = { t: score.transistors, d: score.delay, at: Date.now() } await puzzleStorage().setItem(`scores:${id}`, scores) } return summarize(scores, player) }) return { score, summary } })