/** * Валидация контента. * * Пак — это данные, которые пишет человек руками, поэтому схема обязана * ловить опечатки до игры, а не в момент показа вопроса на проекторе. */ import { existsSync, readFileSync, readdirSync } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' import type { Pack } from '../src/index' import { cellKey, effectiveValue, findCell, isRoundComplete, parseCellKey, parsePack } from '../src/index' const CONTENT_DIR = fileURLToPath(new URL('../../../content/', import.meta.url)) const PACKS_DIR = path.join(CONTENT_DIR, 'packs') function loadDemo(): unknown { return JSON.parse(readFileSync(path.join(PACKS_DIR, 'demo.json'), 'utf8')) } function packFiles(): string[] { return readdirSync(PACKS_DIR).filter((file) => file.endsWith('.json')) } function mediaSources(pack: Pack): string[] { const sources: string[] = [] for (const round of pack.rounds) { for (const theme of round.themes) { for (const cell of theme.cells) { if (cell.question.media) sources.push(cell.question.media.src) } } } if (pack.final?.question.media) sources.push(pack.final.question.media.src) return sources } function errorsOf(input: unknown): string[] { const result = parsePack(input) if (result.ok) throw new Error('ожидалась ошибка валидации, а пак прошёл') return result.errors } function validPack(): Record { return { id: 'demo', title: 'Демо', settings: {}, rounds: [ { id: 'r1', title: 'Раунд 1', themes: [ { id: 't1', title: 'Тема 1', cells: [{ value: 100, question: { text: 'Вопрос', answer: 'Ответ' } }], }, ], }, ], } } describe('все паки в репозитории', () => { const files = packFiles() it('их вообще есть', () => { expect(files.length).toBeGreaterThan(0) }) for (const file of files) { it(`${file}: проходит схему`, () => { const raw: unknown = JSON.parse(readFileSync(path.join(PACKS_DIR, file), 'utf8')) const result = parsePack(raw) if (!result.ok) throw new Error(`${file}:\n${result.errors.join('\n')}`) for (const round of result.pack.rounds) { const sizes = new Set(round.themes.map((theme) => theme.cells.length)) expect(sizes.size).toBe(1) } }) it(`${file}: все медиафайлы лежат на диске`, () => { // Самый обидный баг вечера — вопрос с музыкой, у которого нет файла. const raw: unknown = JSON.parse(readFileSync(path.join(PACKS_DIR, file), 'utf8')) const result = parsePack(raw) if (!result.ok) throw new Error(`${file}:\n${result.errors.join('\n')}`) for (const source of mediaSources(result.pack)) { const relative = source.replace(/^\/media\//, '') const full = path.join(CONTENT_DIR, 'media', relative) expect(existsSync(full), `нет файла для ${source} (${file})`).toBe(true) } }) } }) describe('демо-пак', () => { it('проходит валидацию и готов к игре', () => { const result = parsePack(loadDemo()) if (!result.ok) throw new Error(result.errors.join('\n')) const pack = result.pack expect(pack.rounds.length).toBeGreaterThan(0) expect(pack.final).toBeDefined() for (const round of pack.rounds) { const sizes = new Set(round.themes.map((t) => t.cells.length)) expect(sizes.size).toBe(1) for (const theme of round.themes) { for (const cell of theme.cells) { expect(cell.question.answer.length).toBeGreaterThan(0) expect(Boolean(cell.question.text || cell.question.media)).toBe(true) } } } }) it('заполняет значения по умолчанию', () => { const result = parsePack(loadDemo()) if (!result.ok) throw new Error(result.errors.join('\n')) expect(result.pack.settings.defaultTimeLimit).toBe(30) expect(result.pack.settings.buzzers).toBe(true) const firstCell = result.pack.rounds[0]?.themes[0]?.cells[0] expect(firstCell?.kind).toBe('normal') }) }) describe('схема ловит ошибки автора', () => { it('повторяющийся номинал в теме', () => { const pack = validPack() const round = (pack.rounds as any[])[0] round.themes[0].cells.push({ value: 100, question: { text: 'Ещё', answer: 'Ответ' } }) expect(errorsOf(pack).join(' ')).toMatch(/повторяется номинал 100/) }) it('разное число клеток у тем', () => { const pack = validPack() const round = (pack.rounds as any[])[0] round.themes.push({ id: 't2', title: 'Тема 2', cells: [ { value: 100, question: { text: 'Вопрос', answer: 'Ответ' } }, { value: 200, question: { text: 'Вопрос', answer: 'Ответ' } }, ], }) expect(errorsOf(pack).join(' ')).toMatch(/одинаковое число клеток/) }) it('вопрос без текста и без медиа', () => { const pack = validPack() const round = (pack.rounds as any[])[0] round.themes[0].cells[0].question = { answer: 'Ответ' } expect(errorsOf(pack).join(' ')).toMatch(/text или media/) }) it('медиа вне /media/', () => { const pack = validPack() const round = (pack.rounds as any[])[0] round.themes[0].cells[0].question = { media: { kind: 'audio', src: 'https://example.com/song.mp3' }, answer: 'Ответ', } expect(errorsOf(pack).join(' ')).toMatch(/\/media\//) }) it('финал задан, но выключен', () => { const pack = validPack() pack.settings = { finalEnabled: false } pack.final = { question: { text: 'Финал', answer: 'Ответ' } } expect(errorsOf(pack).join(' ')).toMatch(/finalEnabled/) }) it('неизвестный тип клетки', () => { const pack = validPack() const round = (pack.rounds as any[])[0] round.themes[0].cells[0].kind = 'bonus' expect(errorsOf(pack).length).toBeGreaterThan(0) }) }) describe('навигация по сетке', () => { it('ключ клетки переживает разбор', () => { const key = cellKey('r1', 't1', 2) expect(key).toBe('r1/t1/2') expect(parseCellKey(key)).toEqual({ roundId: 'r1', themeId: 't1', index: 2 }) expect(parseCellKey('мусор')).toBeNull() expect(parseCellKey('r1/t1/нет')).toBeNull() }) it('findCell находит клетку и стоимость с учётом супер-вопроса', () => { const result = parsePack(loadDemo()) if (!result.ok) throw new Error(result.errors.join('\n')) const pack = result.pack const found = findCell(pack, 'r1/cinema/2') expect(found?.cell.kind).toBe('super') expect(found && effectiveValue(found.cell)).toBe(600) expect(findCell(pack, 'r1/нет-такой/0')).toBeNull() expect(findCell(pack, 'r1/cinema/99')).toBeNull() }) it('раунд считается сыгранным только когда закрыты все клетки', () => { const result = parsePack(loadDemo()) if (!result.ok) throw new Error(result.errors.join('\n')) const round = result.pack.rounds[0] if (!round) throw new Error('нет раунда') const keys = round.themes.flatMap((theme) => theme.cells.map((_, index) => cellKey(round.id, theme.id, index)), ) expect(isRoundComplete(round, keys.slice(0, -1))).toBe(false) expect(isRoundComplete(round, keys)).toBe(true) }) })