// Le programme : sa forme, sa validation (la seule, partagée par l'app et le // serveur) et la lecture d'un exercice. Glossaire : docs/glossaire/programme.md import { EXERCISES } from "./exercises.js"; import { TRACKING_MODES, ZONES, INTENSITIES } from "./vocabulary.js"; import { validateFormat } from "./wod.js"; /** * Un exercice tel qu'écrit dans le programme : une référence à la bibliothèque * (`ref`), ou un exercice libre décrit par son nom et ses textes. * @typedef {object} ProgramExercise * @property {string} [ref] identifiant dans EXERCISES * @property {string} [name] obligatoire sans ref ; remplace le nom de la bibliothèque sinon * @property {string[]} [cues] le geste * @property {string[]} [mistakes] à éviter * @property {number} sets * @property {string} reps texte libre : « 8 », « 6–8 », « 10 / jambe », « 40 s » * @property {number} rest repos en secondes * @property {string} [group] superset : exercices consécutifs de même groupe * @property {import("./vocabulary.js").TrackingMode} [tracking] * @property {string} [note] remarque du coach * @property {string} [tutorial] lien de tutoriel précis (https), sinon recherche YouTube */ /** * Glossaire : docs/glossaire/seance.md * @typedef {object} ProgramSession * @property {string} key une ou deux lettres, « A » * @property {string} name * @property {string} [subtitle] * @property {string} [color] #RRGGBB * @property {string} [tag] * @property {ProgramExercise[]} exercises * @property {import("./wod.js").WodFormat} [format] séance WOD (AMRAP, EMOM…), ADR 0010 * @property {WarmupItem[]} [warmup] échauffement propre à la séance ; omis : * l'échauffement standard (warmup.js) ; liste vide : aucun */ /** * Une étape d'échauffement écrite dans le programme. Glossaire : * docs/glossaire/echauffement.md * @typedef {object} WarmupItem * @property {string} [ref] exercice de la bibliothèque (son nom et sa première consigne) * @property {string} [name] obligatoire sans ref * @property {string} [detail] la consigne * @property {number} [seconds] durée, pour lancer un minuteur */ /** * Glossaire : docs/glossaire/activite.md * @typedef {object} Activity * @property {string} id * @property {string} name * @property {string} [color] * @property {import("./vocabulary.js").Zone[]} zones * @property {import("./vocabulary.js").Intensity} intensity * @property {number} minutes */ /** * @typedef {object} CardioItem * @property {string} name * @property {boolean} inPlan occupe un jour du planning (sinon : extra en fin de séance) * @property {string} text */ /** @typedef {{name: string, text: string}} Rule */ /** * Glossaire : docs/glossaire/programme.md * @typedef {object} Program * @property {string} name * @property {string} [subtitle] * @property {ProgramSession[]} sessions * @property {Activity[]} [activities] * @property {CardioItem[]} [cardio] * @property {Rule[]} [rules] */ const isObject = (/** @type {unknown} */ x) => typeof x === "object" && x !== null && !Array.isArray(x); const isText = (/** @type {unknown} */ x) => typeof x === "string" && x.trim() !== ""; const isTextList = (/** @type {unknown} */ x) => Array.isArray(x) && x.every((s) => typeof s === "string"); /** * Vérifie un programme. Renvoie la liste des problèmes, en français, vide si le * programme est valide. Les messages s'adressent aussi à une IA : ils doivent * lui permettre de corriger sa proposition. * @param {unknown} program * @returns {string[]} */ export function validateProgram(program) { if (!isObject(program)) return ["Le programme doit être un objet."]; const p = /** @type {Record} */ (program); /** @type {string[]} */ const errors = []; if (!isText(p.name)) errors.push("Le programme n'a pas de nom ('name')."); if (!Array.isArray(p.sessions) || p.sessions.length === 0) { errors.push("Aucune séance dans 'sessions'."); return errors; } const keys = new Set(); p.sessions.forEach((/** @type {any} */ s, /** @type {number} */ i) => { const where = `séance ${isText(s?.key) ? s.key : "n° " + (i + 1)}`; if (!isObject(s)) return errors.push(`La séance n° ${i + 1} doit être un objet.`); if (!isText(s.key) || !/^[A-Za-z0-9]{1,3}$/.test(s.key)) errors.push(`${where} : 'key' doit faire 1 à 3 lettres ou chiffres.`); else if (keys.has(s.key)) errors.push(`Deux séances portent la clé « ${s.key} ».`); keys.add(s.key); if (!isText(s.name)) errors.push(`${where} : 'name' manquant.`); if (s.color !== undefined && !/^#[0-9A-Fa-f]{6}$/.test(s.color)) errors.push(`${where} : 'color' doit être de la forme #RRGGBB.`); if (!Array.isArray(s.exercises) || s.exercises.length === 0) return errors.push(`${where} : aucun exercice.`); s.exercises.forEach((/** @type {any} */ e, /** @type {number} */ j) => { const ex = `${where}, exercice n° ${j + 1}`; if (!isObject(e)) return errors.push(`${ex} : doit être un objet.`); if (e.ref !== undefined && !isRef(e.ref)) errors.push(`${ex} : 'ref' doit être un texte court (identifiant de la bibliothèque).`); if (e.ref === undefined && !isText(e.name)) errors.push(`${ex} : il faut 'ref' ou 'name'.`); if (e.name !== undefined && !isText(e.name)) errors.push(`${ex} : 'name' doit être un texte.`); if (!Number.isInteger(e.sets) || e.sets < 1 || e.sets > 12) errors.push(`${ex} : 'sets' doit être un entier de 1 à 12.`); if (!isText(e.reps)) errors.push(`${ex} : 'reps' manquant (texte libre, par exemple « 8 » ou « 40 s »).`); if (typeof e.rest !== "number" || e.rest < 0 || e.rest > 600) errors.push(`${ex} : 'rest' doit être un nombre de secondes de 0 à 600.`); if (e.group !== undefined && !isText(e.group)) errors.push(`${ex} : 'group' doit être un texte.`); if (e.tracking !== undefined && !TRACKING_MODES.includes(e.tracking)) errors.push(`${ex} : 'tracking' inconnu « ${e.tracking} » (attendu : ${TRACKING_MODES.join(", ")}).`); if (e.cues !== undefined && !isTextList(e.cues)) errors.push(`${ex} : 'cues' doit être une liste de phrases.`); if (e.mistakes !== undefined && !isTextList(e.mistakes)) errors.push(`${ex} : 'mistakes' doit être une liste de phrases.`); if (e.tutorial !== undefined && !/^https:\/\//.test(e.tutorial)) errors.push(`${ex} : 'tutorial' doit être une adresse https.`); }); if (s.format !== undefined) errors.push(...validateFormat(s.format, where)); if (s.warmup !== undefined) { if (!Array.isArray(s.warmup) || s.warmup.length > 12) errors.push(`${where} : 'warmup' doit être une liste de 0 à 12 étapes.`); else s.warmup.forEach((/** @type {any} */ w, /** @type {number} */ j) => { const st = `${where}, échauffement n° ${j + 1}`; if (!isObject(w)) return errors.push(`${st} : doit être un objet.`); if (w.ref !== undefined && !isRef(w.ref)) errors.push(`${st} : 'ref' doit être un texte court (identifiant de la bibliothèque).`); if (w.ref === undefined && !isText(w.name)) errors.push(`${st} : il faut 'ref' ou 'name'.`); if (w.name !== undefined && !isText(w.name)) errors.push(`${st} : 'name' doit être un texte.`); if (w.detail !== undefined && typeof w.detail !== "string") errors.push(`${st} : 'detail' doit être un texte.`); if (w.seconds !== undefined && (!Number.isInteger(w.seconds) || w.seconds < 5 || w.seconds > 900)) errors.push(`${st} : 'seconds' doit être un entier de 5 à 900.`); }); } }); if (p.activities !== undefined) { if (!Array.isArray(p.activities)) errors.push("'activities' doit être une liste."); else { const ids = new Set(); p.activities.forEach((/** @type {any} */ a, /** @type {number} */ i) => { const where = `activité ${isText(a?.name) ? "« " + a.name + " »" : "n° " + (i + 1)}`; if (!isText(a?.id) || !/^[a-z0-9-]{1,32}$/.test(a.id)) errors.push(`${where} : 'id' doit être en minuscules, chiffres et tirets.`); else if (ids.has(a.id)) errors.push(`Deux activités portent l'identifiant « ${a.id} ».`); ids.add(a?.id); if (!isText(a?.name)) errors.push(`${where} : 'name' manquant.`); if (!Array.isArray(a?.zones) || !a.zones.length || !a.zones.every((/** @type {any} */ z) => ZONES.includes(z))) errors.push(`${where} : 'zones' doit lister au moins une zone parmi ${ZONES.join(", ")}.`); if (!INTENSITIES.includes(a?.intensity)) errors.push(`${where} : 'intensity' doit valoir ${INTENSITIES.join(", ")}.`); if (typeof a?.minutes !== "number" || a.minutes < 5 || a.minutes > 600) errors.push(`${where} : 'minutes' doit être une durée de 5 à 600.`); }); } } if (p.cardio !== undefined) { if (!Array.isArray(p.cardio)) errors.push("'cardio' doit être une liste."); else p.cardio.forEach((/** @type {any} */ c, /** @type {number} */ i) => { if (!isText(c?.name) || typeof c?.inPlan !== "boolean" || typeof c?.text !== "string") errors.push(`cardio n° ${i + 1} : il faut 'name', 'inPlan' (vrai ou faux) et 'text'.`); }); } if (p.rules !== undefined) { if (!Array.isArray(p.rules)) errors.push("'rules' doit être une liste."); else p.rules.forEach((/** @type {any} */ r, /** @type {number} */ i) => { if (!isText(r?.name) || typeof r?.text !== "string") errors.push(`repère n° ${i + 1} : il faut 'name' et 'text'.`); }); } return errors; } /** * Met un programme valide au propre avant de l'enregistrer : une référence * absente de la bibliothèque devient un exercice générique (sans `ref`, nommé * par son `name` ou d'après la référence, avec la recherche de tutoriel par son * nom). Une séance d'étirements ne doit pas être refusée pour un exercice * inventé. Les remarques sont à transmettre à l'IA. * @param {Program} program programme valide (validateProgram) * @returns {{program: Program, notices: string[]}} une copie ; l'original n'est pas touché */ export function normalizeProgram(program) { const copy = structuredClone(program); /** @type {string[]} */ const notices = []; /** @param {{ref?: string, name?: string, cues?: string[]}} item @param {string} where */ const generic = (item, where) => { if (item.ref === undefined || EXERCISES[item.ref]) return; const ref = item.ref; item.name = item.name || nameFromRef(ref); delete item.ref; notices.push(`${where} : « ${ref} » n'est pas dans la bibliothèque${nearRefs(ref)} ; gardé comme exercice générique « ${item.name} »` + (item.cues ? "." : ", sans consignes (donne 'cues' et 'mistakes' la prochaine fois).")); }; for (const s of copy.sessions) { s.exercises.forEach((e, j) => generic(e, `séance ${s.key}, exercice n° ${j + 1}`)); (s.warmup ?? []).forEach((w, j) => generic(w, `séance ${s.key}, échauffement n° ${j + 1}`)); } return { program: copy, notices }; } /** Référence à la bibliothèque, connue ou non : un texte court. @param {unknown} x */ const isRef = (x) => isText(x) && /** @type {string} */ (x).length <= 64; /** Nom lisible tiré d'une référence hors bibliothèque : « pigeon-pose » → « Pigeon pose ». @param {string} ref */ export function nameFromRef(ref) { const words = ref.trim().replace(/[-_]+/g, " "); return words.charAt(0).toUpperCase() + words.slice(1); } /** * Références proches d'une référence inconnue (mots en commun), pour aider une IA * à corriger sans lui renvoyer toute la bibliothèque. * @param {string} ref */ function nearRefs(ref) { const words = ref.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2); const near = Object.keys(EXERCISES).filter((id) => words.some((w) => id.includes(w))).slice(0, 8); return near.length ? ` (références proches : ${near.join(", ")})` : ""; } /** * Un exercice prêt à afficher : textes de la bibliothèque complétés par le programme. * @typedef {object} ResolvedExercise * @property {string} id clé stable de l'exercice : sa ref, sinon son nom * @property {string} name * @property {string[]} cues * @property {string[]} mistakes * @property {number} sets * @property {string} reps * @property {number} rest * @property {string|null} group * @property {string|null} note * @property {import("./exercises.js").LibraryExercise|null} library * @property {string} tutorial lien de tutoriel (ADR 0004) */ /** * @param {ProgramExercise} item * @returns {ResolvedExercise} */ export function resolveExercise(item) { const library = item.ref ? EXERCISES[item.ref] ?? null : null; // Une ref inconnue ne devrait plus arriver ici (normalizeProgram) ; filet de sécurité. const name = item.name || library?.name || (item.ref ? nameFromRef(item.ref) : "Exercice"); return { id: item.ref || name, name, cues: item.cues ?? library?.cues ?? [], mistakes: item.mistakes ?? library?.mistakes ?? [], sets: item.sets, reps: item.reps, rest: item.rest, group: item.group ?? null, note: item.note ?? null, library, tutorial: tutorialFor(name, item.tutorial), }; } /** * @param {string} name * @param {string} [explicitUrl] */ function tutorialFor(name, explicitUrl) { if (explicitUrl && /^https:\/\//.test(explicitUrl)) return explicitUrl; return "https://www.youtube.com/results?search_query=" + encodeURIComponent("tuto mouvement gym : " + name); } /** * Découpe les exercices d'une séance en blocs : un exercice seul, ou un superset * d'exercices consécutifs partageant le même `group`. Glossaire : docs/glossaire/superset.md * @param {ProgramExercise[]} exercises * @returns {{group: string|null, items: ProgramExercise[]}[]} */ export function groupBlocks(exercises) { /** @type {{group: string|null, items: ProgramExercise[]}[]} */ const blocks = []; for (const item of exercises) { const last = blocks[blocks.length - 1]; if (item.group && last && last.group === item.group) last.items.push(item); else blocks.push({ group: item.group ?? null, items: [item] }); } return blocks; } /** * Clé de la charge de travail et du mode de suivi d'un exercice dans une séance : * « A-squat ». Glossaire : docs/glossaire/charge-de-travail.md * @param {string} sessionKey * @param {ProgramExercise} item */ export function exerciseKey(sessionKey, item) { return sessionKey + "-" + resolveExercise(item).id; } /** * Durée cible en secondes si les répétitions sont exprimées en temps (« 30–45 s » * donne 45 : sur une fourchette, on vise le haut ; « 1 min », « 45 sec » et * « 1 min 30 » sont compris), sinon null. * @param {string} reps */ export function targetSeconds(reps) { const m = /(\d+)\s*(?:[–-]\s*(\d+)\s*)?(s|sec|secondes?|min|minutes?)(?![a-zà-ÿ])(?:\s*(\d+)(?!\s*[–-]))?/i.exec(reps || ""); if (!m) return null; const n = Number(m[2] || m[1]); return m[3].toLowerCase().startsWith("m") ? n * 60 + Number(m[4] ?? 0) : n; } /** Matériel dont on note la charge en kg (barre, haltères, kettlebell, machine, poulie). */ const LOADED_EQUIPMENT = ["barbell", "dumbbell", "dumbbells", "kettlebell", "machine", "cable"]; /** * Mode de suivi effectif, par priorité : le choix de l'utilisateur, celui du * programme, puis une déduction (temps si les répétitions sont en secondes, * charge si l'exercice se fait avec un matériel chargeable : LOADED_EQUIPMENT). * @param {ProgramExercise} item * @param {import("./vocabulary.js").TrackingMode|undefined} override * @returns {import("./vocabulary.js").TrackingMode} */ export function trackingFor(item, override) { if (override && TRACKING_MODES.includes(override)) return override; if (item.tracking && TRACKING_MODES.includes(item.tracking)) return item.tracking; const library = item.ref ? EXERCISES[item.ref] : null; const loadable = !!library && LOADED_EQUIPMENT.includes(library.equipment); if (targetSeconds(item.reps) !== null) return loadable ? "time+load" : "time"; return loadable ? "load" : "none"; }