/** * Сборка пака из таблицы Excel / Google Sheets. * * npx tsx scripts/import-pack.ts вопросы.csv --id novy-god --title "Квиз" * npx tsx scripts/import-pack.ts вопросы.csv --final финал.csv * npx tsx scripts/import-pack.ts вопросы.csv --check # только проверить * * В PowerShell npm съедает «--» вместе с флагами, поэтому там нужен npx tsx. * В cmd.exe и bash работает и короткая форма: npm run import -- файл.csv * * CSV может быть в UTF-8 или Windows-1251 (так сохраняет русский Excel), * с запятыми, точками с запятой или табуляцией — разделитель определяется сам. */ import { existsSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { decodeTable, parseFinal, parsePack, tableToPack } from '../packages/shared/src/index' const root = fileURLToPath(new URL('../', import.meta.url)) const packsDir = path.join(root, 'content', 'packs') interface Args { input?: string id?: string title?: string final?: string out?: string check: boolean help: boolean } function parseArgs(argv: string[]): Args { const args: Args = { check: false, help: false } const positional: string[] = [] for (let index = 0; index < argv.length; index += 1) { const current = argv[index] if (!current) continue if (current === '--check') { args.check = true continue } if (current === '--help' || current === '-h') { args.help = true continue } if (current.startsWith('--')) { const [rawName, inline] = current.slice(2).split('=') const name = rawName as keyof Args const value = inline ?? argv[index + 1] if (inline === undefined) index += 1 if (typeof value === 'string') { if (name === 'id' || name === 'title' || name === 'final' || name === 'out') args[name] = value } continue } positional.push(current) } args.input = positional[0] return args } function usage(): void { console.log( [ '', 'Сборка пака из таблицы', '', ' npx tsx scripts/import-pack.ts <файл.csv> [ключи]', ' npm run import -- <файл.csv> [ключи] (cmd.exe и bash)', '', 'В PowerShell используйте npx: он съедает «--», и флаги до скрипта не доходят.', '', ' --id=<идентификатор> латиницей, по умолчанию из имени файла', ' --title="Название" заголовок пака, по умолчанию равен id', ' --final=<файл.csv> финальный вопрос: вопрос, ответ, комментарий', ' --out=<путь> куда положить пак, по умолчанию content/packs/.json', ' --check только проверить таблицу, ничего не писать', '', 'Колонки: Раунд, Тема, Стоимость, Вопрос, Ответ, Комментарий, Тип, Медиа.', 'Обязательны Тема, Стоимость, Вопрос, Ответ (или Медиа вместо Вопроса).', '', ].join('\n'), ) } function slug(input: string): string { return input .replace(/\.(csv|tsv|txt)$/i, '') .toLowerCase() .replace(/[^a-z0-9-]+/g, '-') .replace(/^-+|-+$/g, '') } function fail(message: string, details: string[] = []): never { console.error(`\n✖ ${message}`) for (const detail of details) console.error(` ${detail}`) console.error('') process.exit(1) } const args = parseArgs(process.argv.slice(2)) if (args.help || !args.input) { usage() process.exit(args.help ? 0 : 1) } const inputPath = path.resolve(args.input) if (!existsSync(inputPath)) fail(`файл не найден: ${inputPath}`) // Без --id берём его из блока метаданных в самой таблице, иначе из имени файла. const idFromArgs = args.id ?? slug(path.basename(inputPath)) if (args.id && !/^[a-z0-9][a-z0-9-]*$/.test(args.id)) { fail(`идентификатор «${args.id}» не подходит`, [ 'нужны строчные латинские буквы, цифры и дефис', 'пример: --id=novy-god', ]) } const decoded = decodeTable(readFileSync(inputPath)) console.log(`\nчитаю ${path.relative(root, inputPath)} (${decoded.encoding})`) let final: { question: string; answer: string; comment?: string } | undefined if (args.final) { const finalPath = path.resolve(args.final) if (!existsSync(finalPath)) fail(`файл финала не найден: ${finalPath}`) const parsedFinal = parseFinal(decodeTable(readFileSync(finalPath)).text) if (!parsedFinal.ok) { fail('финальный вопрос не разобрался', parsedFinal.errors.map((e) => `строка ${e.line}: ${e.message}`)) } final = parsedFinal.final } const result = tableToPack(decoded.text, { id: idFromArgs, ...(args.title ? { title: args.title } : {}), ...(final ? { final } : {}), }) if (!result.ok) { fail('в таблице есть ошибки', result.errors.map((error) => `строка ${error.line}: ${error.message}`)) } // Импортёр старается, но последнее слово — за схемой, с которой живёт игра. const validated = parsePack(result.pack) if (!validated.ok) { fail('пак не прошёл схему (это баг импортёра, напишите о нём)', validated.errors) } const { stats } = result console.log(`раундов: ${stats.rounds}, тем: ${stats.themes}, клеток: ${stats.cells}`) if (args.check) { console.log('проверка пройдена, файл не записан (--check)\n') process.exit(0) } const outPath = args.out ? path.resolve(args.out) : path.join(packsDir, `${validated.pack.id}.json`) writeFileSync(outPath, `${JSON.stringify(validated.pack, null, 2)}\n`, 'utf8') console.log(`записано: ${path.relative(root, outPath)}`) console.log('сервер подхватит пак при следующем запуске\n')