// ─── repairCodeBlocks.ts ────────────────────────────────────────────────────── // Fase 5 — ripara blocchi di codice malformati nel testo LLM. // Browser-safe, zero deps, iPhone compatible. // // Problemi gestiti: // 1. Code block aperto senza chiusura // 2. Code block senza label lingua (aggiunge "text" come default) // 3. Indentazione mista (tab + spazi) normalizzata a spazi // 4. Backtick singoli usati per blocchi multi-riga (→ tripli) export interface RepairCodeResult { text: string; changed: boolean; repairs: string[]; } // ── Linguaggi comuni (per rilevamento automatico) ───────────────────────────── const LANG_HINTS: Array<[RegExp, string]> = [ [/^(import|export|const|let|var|function|class|type|interface)\s/m, "typescript"], [/^(def |class |import |from |print\()/m, "python"], [/^( { const normalized = match.replace(/\t/g, " "); if (normalized !== match) repairs.push("normalizzati tab → spazi in code block"); return normalized; }); // 2. Aggiunge lingua mancante ai code block ``` senza label t = t.replace(/```(\s*\n)([\s\S]*?)```/g, (_m, nl, code) => { const lang = detectLang(code); if (lang !== "text") repairs.push(`rilevato linguaggio: ${lang}`); return "```" + lang + nl + code + "```"; }); // 3. Backtick singoli su testo multi-riga → triple backtick t = t.replace(/`([^`\n]{40,})`/g, (_, code) => { repairs.push("convertito backtick singolo → triplo (testo lungo)"); return "```\n" + code + "\n```"; }); // 4. Chiudi blocchi aperti (numero dispari di ```) const count = (t.match(/```/g) ?? []).length; if (count % 2 !== 0) { t += "\n```"; repairs.push("chiuso code block aperto finale"); } return { text: t, changed: repairs.length > 0, repairs }; } /** Versione semplice */ export function repairCode(raw: string): string { return repairCodeBlocks(raw).text; }