From 3003eda8a2f0181765ded602a976726314a84a30 Mon Sep 17 00:00:00 2001 From: denis Date: Fri, 16 Oct 2026 16:46:03 +0200 Subject: [PATCH] Add author editor data model (LevelDraft) with exact round-trip and YAML export; validate_levels --file Co-Authored-By: Claude Sonnet 5.5 --- app/js/author/LevelDraft.js | 240 ++++++++++++++++++ .../validate_levels.cpython-313.pyc | Bin 0 -> 8528 bytes scripts/validate_levels.py | 12 +- tests/js/level-draft.test.mjs | 81 ++++++ 4 files changed, 331 insertions(+), 2 deletions(-) create mode 100644 app/js/author/LevelDraft.js create mode 100644 scripts/__pycache__/validate_levels.cpython-313.pyc create mode 100644 tests/js/level-draft.test.mjs diff --git a/app/js/author/LevelDraft.js b/app/js/author/LevelDraft.js new file mode 100644 index 0000000..4b2c2d0 --- /dev/null +++ b/app/js/author/LevelDraft.js @@ -0,0 +1,240 @@ +// Modèle de formulaire de l'éditeur de niveaux ⇄ niveau au format du schéma. +// Le formulaire manipule des champs « complets » (textes fr/en, indices sur des lignes, valeurs en texte) ; +// toLevel() produit l'objet propre du schéma (champs facultatifs vides omis, ordre des clés stable) et +// fromLevel() fait l'inverse. toLevel(fromLevel(niveau)) redonne le niveau d'origine (testé sur tous les niveaux). + +import yaml from '../lib/js-yaml/js-yaml.mjs'; + +export const REWARD_SOUNDS = ['success_small', 'success_big', 'level_unlocked']; +export const PYTHON_TYPES = ['str', 'int', 'float', 'bool', 'list', 'dict']; + +/** Kinds éditables et champs qu'ils utilisent. */ +export const TEST_KINDS = { + no_syntax_error: { name: false, value: false }, + stdout_equals: { name: false, value: 'text' }, + stdout_contains: { name: false, value: 'text' }, + stdout_matches_regex: { name: false, value: 'text' }, + code_contains: { name: false, value: 'text' }, + var_equals: { name: true, value: 'typed' }, + var_type_is: { name: true, value: 'type' }, +}; + +const i18n = (fr = '', en = '') => ({ fr, en }); + +export function emptyLevelModel() { + return { + id: '', + title: i18n(), + difficulty: 1, + xp: 30, + requires: [], + steps: [], + mission: { title: i18n(), goal: i18n(), starter: '', tests: [], solution: '', rewardSound: 'success_small' }, + }; +} + +export function newTestModel(kind = 'stdout_equals') { + return { kind, name: '', value: '', valueType: 'text', inputs: '', message: i18n() }; +} + +export function newStepModel(type) { + return type === 'explain' + ? { type: 'explain', text: i18n(), voice: true, image: '' } + : { type: 'code', instruction: i18n(), starter: '', tests: [newTestModel()], hints: i18n(), solution: '' }; +} + +// ---- modèle -> niveau ------------------------------------------------------------------------------------ + +const text = ({ fr, en }) => (en ? { fr, en } : { fr }); +const lines = (value) => value.split('\n').map((line) => line.trim()).filter(Boolean); + +/** Saisies scriptées : une par ligne, les lignes vides finales sont ignorées (celles du milieu sont des saisies vides). */ +function inputLines(value) { + const all = value.split('\n'); + while (all.length > 0 && all.at(-1) === '') { + all.pop(); + } + return all; +} + +function testToLevel(test) { + const spec = TEST_KINDS[test.kind]; + const out = { kind: test.kind }; + if (spec.name) { + out.name = test.name; + } + if (spec.value === 'typed') { + out.value = test.valueType === 'number' && test.value.trim() !== '' && !Number.isNaN(Number(test.value)) ? Number(test.value) : test.valueType === 'boolean' ? test.value === 'true' : test.value; + } else if (spec.value) { + out.value = test.value; + } + const inputs = inputLines(test.inputs); + if (inputs.length > 0) { + out.inputs = inputs; + } + if (test.message.fr || test.message.en) { + out.message = text(test.message); + } + return out; +} + +function stepToLevel(step) { + if (step.type === 'explain') { + const out = { type: 'explain' }; + if (step.voice) { + out.voice = true; + } + out.text = text(step.text); + if (step.image.trim()) { + out.image = step.image.trim(); + } + return out; + } + const out = { type: 'code', starter: step.starter, instruction: text(step.instruction), tests: step.tests.map(testToLevel) }; + const hints = {}; + for (const lang of ['fr', 'en']) { + const list = lines(step.hints[lang]); + if (list.length > 0) { + hints[lang] = list; + } + } + if (Object.keys(hints).length > 0) { + out.hints = hints; + } + if (step.solution.trim()) { + out.solution = step.solution; + } + return out; +} + +/** Modèle de formulaire -> niveau au format du schéma. */ +export function toLevel(model) { + const { mission } = model; + const outMission = { title: text(mission.title), goal: text(mission.goal) }; + if (mission.starter.trim()) { + outMission.starter = mission.starter; + } + if (mission.tests.length > 0) { + outMission.tests = mission.tests.map(testToLevel); + } + if (mission.solution.trim()) { + outMission.solution = mission.solution; + } + if (mission.rewardSound) { + outMission.reward_sound = mission.rewardSound; + } + return { + id: model.id, + title: text(model.title), + difficulty: model.difficulty, + xp: model.xp, + requires: [...model.requires], + steps: model.steps.map(stepToLevel), + mission: outMission, + }; +} + +// ---- niveau -> modèle ------------------------------------------------------------------------------------ + +const fromText = (value) => i18n(value?.fr ?? '', value?.en ?? ''); +const fromHints = (hints) => i18n((hints?.fr ?? []).join('\n'), (hints?.en ?? []).join('\n')); + +function testFromLevel(test) { + const model = newTestModel(test.kind); + model.name = test.name ?? ''; + const { value } = test; + if (typeof value === 'number') { + model.valueType = 'number'; + model.value = String(value); + } else if (typeof value === 'boolean') { + model.valueType = 'boolean'; + model.value = String(value); + } else { + model.value = value ?? ''; + } + model.inputs = (test.inputs ?? []).join('\n'); + model.message = fromText(test.message); + return model; +} + +function stepFromLevel(step) { + if (step.type === 'explain') { + return { type: 'explain', text: fromText(step.text), voice: Boolean(step.voice), image: step.image ?? '' }; + } + return { + type: 'code', + instruction: fromText(step.instruction), + starter: step.starter ?? '', + tests: (step.tests ?? []).map(testFromLevel), + hints: fromHints(step.hints), + solution: step.solution ?? '', + }; +} + +/** Niveau au format du schéma -> modèle de formulaire (tolère les champs absents). */ +export function fromLevel(level) { + const mission = level.mission ?? {}; + return { + id: level.id ?? '', + title: fromText(level.title), + difficulty: level.difficulty ?? 1, + xp: level.xp ?? 0, + requires: [...(level.requires ?? [])], + steps: (level.steps ?? []).map(stepFromLevel), + mission: { + title: fromText(mission.title), + goal: fromText(mission.goal), + starter: mission.starter ?? '', + tests: (mission.tests ?? []).map(testFromLevel), + solution: mission.solution ?? '', + rewardSound: mission.reward_sound ?? '', + }, + }; +} + +// ---- YAML ------------------------------------------------------------------------------------------------ + +/** + * js-yaml écrit chaque élément de liste sur deux lignes (« - » seul puis le contenu indenté de 4 espaces). + * On le ramène au style des niveaux écrits à la main : « - clé: valeur » avec le reste aligné deux colonnes + * à droite du tiret. + */ +function compactListItems(source) { + const input = source.split('\n'); + const output = []; + const indentOf = (line) => line.length - line.trimStart().length; + for (let i = 0; i < input.length; i++) { + const line = input[i]; + if (/(^|\s)\|[-+]?$/.test(line)) { + // Bloc littéral (code, texte multiligne) : copié tel quel, même s'il contient une ligne « - ». + output.push(line); + while (i + 1 < input.length && (input[i + 1] === '' || indentOf(input[i + 1]) > indentOf(line))) { + output.push(input[++i]); + } + continue; + } + if (!/^\s*-$/.test(line)) { + output.push(line); + continue; + } + const base = indentOf(line); + const block = []; + while (i + 1 < input.length && (input[i + 1] === '' || indentOf(input[i + 1]) > base)) { + block.push(input[++i]); + } + // Récursion : les listes imbriquées sont d'abord compactées, puis tout le bloc recule de deux colonnes. + const inner = compactListItems(block.join('\n')).split('\n').map((blockLine) => (blockLine === '' ? '' : blockLine.slice(2))); + const [first, ...rest] = inner; + output.push(`${' '.repeat(base)}- ${first.trimStart()}`, ...rest); + } + return output.join('\n'); +} + +/** Sérialise un niveau en YAML conforme aux conventions du projet (4 espaces, pas de repli de ligne). */ +export function levelToYaml(level) { + return compactListItems(yaml.dump(level, { indent: 4, lineWidth: -1, noRefs: true, noCompatMode: true, quotingType: '"' })); +} + +export function levelFromYaml(source) { + return yaml.load(source); +} diff --git a/scripts/__pycache__/validate_levels.cpython-313.pyc b/scripts/__pycache__/validate_levels.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82937658bd9d23ccfee3bfa13176b4ea12ecf224 GIT binary patch literal 8528 zcmbt3eQXm~o^R|Kd;D$Znym_C$_j|wh`}Sj-&5WP~x*lBFUW(8cq@xu&+n^qIQ3$<>c!Uv8@w(&G zkPhoO($*i>W4-#NF|B?X%)pmEZWuCRqq>GU&JLNdDYxE?&FVS}wp=i7Ll>-_0GkwV zP4-({cjh|Y+Tzh{d!sSzxZvOo%@%~P^MaE%k`~XZeHZWGoxG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YFNLM!|s~Z!WUP#!RR@mn6JpOZ6W!mMw-LYu++5XoJU)zwY;)xTLHGI^WYB=_* z&buA&U48dzddHrX9eY0NOg0=_EghOO!bKP8g)9nK{h;_@GG!PG5h@!Q9xGo z`!V=A2!}~U1QI;Z8?s^~xvEg`QdVdUpi3ZGmc6eknTNUfJ0$!U+V%xpF literal 0 HcmV?d00001 diff --git a/scripts/validate_levels.py b/scripts/validate_levels.py index 3b83238..8102e24 100644 --- a/scripts/validate_levels.py +++ b/scripts/validate_levels.py @@ -45,7 +45,7 @@ def code_snippets(level: dict[str, Any]) -> list[tuple[str, str]]: return snippets -def validate_level(path: Path, schema: dict[str, Any], require_en: bool) -> list[str]: +def validate_level(path: Path, schema: dict[str, Any], require_en: bool, check_folder: bool = True) -> list[str]: errors: list[str] = [] try: level = yaml.safe_load(path.read_text(encoding="utf-8")) @@ -59,7 +59,7 @@ def validate_level(path: Path, schema: dict[str, Any], require_en: bool) -> list if errors: return errors - if level["id"] != path.parent.name: + if check_folder and level["id"] != path.parent.name: errors.append(f"id '{level['id']}' différent du dossier '{path.parent.name}'") if require_en: errors.extend(f"traduction `en` manquante : {where}" for where in missing_english(level)) @@ -90,11 +90,19 @@ def validate_manifest(known_ids: set[str]) -> list[str]: def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--allow-missing-en", action="store_true", help="n'exige pas les traductions en") + parser.add_argument("--file", type=Path, help="valide un seul fichier level.yaml (ex. exporté par l'éditeur), hors manifeste") args = parser.parse_args() schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8")) jsonschema.Draft202012Validator.check_schema(schema) + if args.file is not None: + errors = validate_level(args.file, schema, require_en=not args.allow_missing_en, check_folder=False) + print(f"{'OK ' if not errors else 'KO '} {args.file}") + for message in errors: + print(f" - {message}") + return 1 if errors else 0 + files = sorted(LEVELS_DIR.glob("*/level.yaml")) failed = False for path in files: diff --git a/tests/js/level-draft.test.mjs b/tests/js/level-draft.test.mjs new file mode 100644 index 0000000..08337d2 --- /dev/null +++ b/tests/js/level-draft.test.mjs @@ -0,0 +1,81 @@ +// Modèle de l'éditeur : aller-retour exact sur tous les niveaux, nettoyage des champs vides, YAML valide +// (rechargeable, conforme au schéma, et accepté par scripts/validate_levels.py). +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import assert from 'node:assert'; +import yaml from '../../app/js/lib/js-yaml/js-yaml.mjs'; +import { LevelLinter } from '../../app/js/core/LevelLinter.js'; +import { emptyLevelModel, fromLevel, levelFromYaml, levelToYaml, newStepModel, newTestModel, toLevel } from '../../app/js/author/LevelDraft.js'; + +const root = new URL('../../', import.meta.url).pathname; +const ids = readdirSync(`${root}levels`).filter((name) => /^\d\d-/.test(name)); +const load = (id) => yaml.load(readFileSync(`${root}levels/${id}/level.yaml`, 'utf8')); +const linter = new LevelLinter(JSON.parse(readFileSync(`${root}levels/schema/level.schema.json`, 'utf8'))); +const tmp = mkdtempSync(join(tmpdir(), 'pyquest-draft-')); + +// --- Aller-retour exact sur tous les niveaux, et YAML exporté rechargeable à l'identique. +for (const id of ids) { + const level = load(id); + assert.deepEqual(toLevel(fromLevel(level)), level, `${id} : aller-retour modèle`); + const source = levelToYaml(toLevel(fromLevel(level))); + assert.deepEqual(levelFromYaml(source), level, `${id} : aller-retour YAML`); + assert.ok(!/\t/.test(source), `${id} : pas de tabulation`); + const file = join(tmp, `${id}.yaml`); + writeFileSync(file, source); + // Le validateur Python de la CI accepte exactement ce que l'éditeur exporte. + const output = execFileSync('python3', ['-I', '-c', ` +import sys, json +sys.path.insert(0, ${JSON.stringify(`${root}scripts`)}) +import validate_levels as v +schema = json.load(open(${JSON.stringify(`${root}levels/schema/level.schema.json`)})) +print(v.validate_level(__import__('pathlib').Path(${JSON.stringify(file)}), schema, True, check_folder=False))`], { encoding: 'utf8' }); + assert.equal(output.trim(), '[]', `${id} : validate_levels.py`); +} + +// --- Un niveau vide, une fois rempli à minima, est conforme (sauf traductions et solutions à compléter). +const model = emptyLevelModel(); +model.id = '99-essai'; +model.title = { fr: 'Essai', en: 'Test' }; +model.steps = [newStepModel('explain'), newStepModel('code')]; +model.steps[0].text = { fr: 'Texte', en: 'Text' }; +model.steps[1].instruction = { fr: 'Fais ceci', en: 'Do this' }; +model.steps[1].solution = 'print("x")'; +model.steps[1].tests = [{ ...newTestModel('stdout_equals'), value: 'x\n' }]; +model.steps[1].hints = { fr: 'Un indice\n\n Deux \n', en: 'A hint\nTwo' }; +model.mission.title = { fr: 'M', en: 'M' }; +model.mission.goal = { fr: 'But', en: 'Goal' }; +const level = toLevel(model); +assert.deepEqual(linter.lint(level, { knownLevelIds: ids }).filter((p) => p.severity === 'error'), []); + +// --- Nettoyage : champs facultatifs vides omis, ordre des clés stable. +assert.deepEqual(Object.keys(level), ['id', 'title', 'difficulty', 'xp', 'requires', 'steps', 'mission']); +assert.deepEqual(Object.keys(level.steps[0]), ['type', 'voice', 'text']); +assert.deepEqual(Object.keys(level.steps[1]), ['type', 'starter', 'instruction', 'tests', 'hints', 'solution']); +assert.deepEqual(level.steps[1].hints, { fr: ['Un indice', 'Deux'], en: ['A hint', 'Two'] }, 'lignes vides retirées, espaces rognés'); +assert.deepEqual(Object.keys(level.mission), ['title', 'goal', 'reward_sound']); +model.steps[1].hints = { fr: '', en: '' }; +assert.equal('hints' in toLevel(model).steps[1], false); +model.steps[0].voice = false; model.steps[0].image = ' img.png '; +assert.deepEqual(toLevel(model).steps[0], { type: 'explain', text: { fr: 'Texte', en: 'Text' }, image: 'img.png' }); +model.steps[0].text.en = ''; +assert.deepEqual(toLevel(model).steps[0].text, { fr: 'Texte' }, 'en vide omis (signalé ensuite par le linter)'); + +// --- Tests typés et saisies scriptées. +const typed = (valueType, value) => toLevel({ ...model, steps: [{ ...model.steps[1], tests: [{ ...newTestModel('var_equals'), name: 'x', valueType, value }] }] }).steps[0].tests[0].value; +assert.equal(typed('number', '2.5'), 2.5); +assert.equal(typed('number', 'abc'), 'abc', 'nombre invalide conservé tel quel (le linter/validation le signalera)'); +assert.equal(typed('boolean', 'true'), true); +assert.equal(typed('text', '12'), '12'); +const withInputs = toLevel({ ...model, steps: [{ ...model.steps[1], tests: [{ ...newTestModel('stdout_contains'), value: 'a', inputs: 'x\n\ny\n\n' }] }] }).steps[0].tests[0]; +assert.deepEqual(withInputs.inputs, ['x', '', 'y'], 'ligne vide du milieu conservée, finales ignorées'); +assert.deepEqual(Object.keys(toLevel({ ...model, steps: [{ ...model.steps[1], tests: [newTestModel('no_syntax_error')] }] }).steps[0].tests[0]), ['kind']); + +// --- Le compactage des listes ne touche jamais au contenu des blocs littéraux (code avec une ligne « - »). +model.steps[1].starter = 'x = 1\n-\n- item\n -\n'; +model.steps[1].solution = '-\nprint("ok")'; +const exported = toLevel(model); +assert.deepEqual(levelFromYaml(levelToYaml(exported)), exported, 'blocs littéraux préservés'); + +console.log('level draft ok');