(text: string)
| 27 | * 4. Missing blank line before table |
| 28 | */ |
| 29 | export function fixMarkdownTables(text: string): string { |
| 30 | const lines = text.split('\n'); |
| 31 | const result: string[] = []; |
| 32 | |
| 33 | for (let i = 0; i < lines.length; i++) { |
| 34 | const trimmed = lines[i].trim(); |
| 35 | |
| 36 | // Detect crammed rows: multiple table rows on one line |
| 37 | if (trimmed.startsWith('|') && trimmed.endsWith('|') && (trimmed.match(/\|/g) || []).length > 8) { |
| 38 | const split = splitCrammedRows(trimmed); |
| 39 | if (split.length > 1) { |
| 40 | // Ensure blank line before table if needed |
| 41 | const prev = result[result.length - 1]?.trim() ?? ''; |
| 42 | if (prev && !prev.startsWith('|')) result.push(''); |
| 43 | result.push(...split); |
| 44 | continue; |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | result.push(lines[i]); |
| 49 | } |
| 50 | |
| 51 | // Second pass: fix separator rows to match header column count |
| 52 | const fixed: string[] = []; |
| 53 | for (let i = 0; i < result.length; i++) { |
| 54 | const line = result[i].trim(); |
| 55 | const nextLine = result[i + 1]?.trim() ?? ''; |
| 56 | const prevLine = fixed[fixed.length - 1]?.trim() ?? ''; |
| 57 | |
| 58 | // Case 1: Current line is header, next is separator with wrong col count → fix it |
| 59 | if (isTableRow(line) && isSeparatorRow(nextLine)) { |
| 60 | const headerCols = countColumns(line); |
| 61 | const sepCols = countColumns(nextLine); |
| 62 | fixed.push(result[i]); |
| 63 | if (headerCols !== sepCols) { |
| 64 | // Replace separator with correct column count |
| 65 | fixed.push('|' + Array(headerCols).fill('---').join('|') + '|'); |
| 66 | i++; // skip original separator |
| 67 | } |
| 68 | continue; |
| 69 | } |
| 70 | |
| 71 | // Case 2: Current line is header, next is data row (no separator) → inject |
| 72 | // Only if previous line is NOT part of a table (not a row and not a separator) |
| 73 | if ( |
| 74 | isTableRow(line) && |
| 75 | isTableRow(nextLine) && |
| 76 | !isSeparatorRow(nextLine) && |
| 77 | !isTableRow(prevLine) && |
| 78 | !isSeparatorRow(prevLine) && |
| 79 | !isSeparatorRow(line) |
| 80 | ) { |
| 81 | fixed.push(result[i]); |
| 82 | const headerCols = countColumns(line); |
| 83 | fixed.push('|' + Array(headerCols).fill('---').join('|') + '|'); |
| 84 | continue; |
| 85 | } |
| 86 |
no test coverage detected