| 13 | const ELLIPSIS = '...'; |
| 14 | |
| 15 | export function getCodeFrame(source: string, line: number, column: number): string { |
| 16 | let lines = source.split('\n'); |
| 17 | // Needed if a plugin did not generate correct sourcemaps |
| 18 | if (line > lines.length) return ''; |
| 19 | const maxLineLength = Math.max( |
| 20 | tabsToSpaces(lines[line - 1].slice(0, column)).length + |
| 21 | MIN_CHARACTERS_SHOWN_AFTER_LOCATION + |
| 22 | ELLIPSIS.length, |
| 23 | LINE_TRUNCATE_LENGTH, |
| 24 | ); |
| 25 | |
| 26 | const frameStart = Math.max(0, line - 3); |
| 27 | let frameEnd = Math.min(line + 2, lines.length); |
| 28 | |
| 29 | lines = lines.slice(frameStart, frameEnd); |
| 30 | while (!/\S/.test(lines[lines.length - 1])) { |
| 31 | lines.pop(); |
| 32 | frameEnd -= 1; |
| 33 | } |
| 34 | |
| 35 | const digits = String(frameEnd).length; |
| 36 | |
| 37 | return lines |
| 38 | .map((sourceLine, index) => { |
| 39 | const isErrorLine = frameStart + index + 1 === line; |
| 40 | |
| 41 | let lineNumber = String(index + frameStart + 1); |
| 42 | while (lineNumber.length < digits) lineNumber = ` ${lineNumber}`; |
| 43 | |
| 44 | let displayedLine = tabsToSpaces(sourceLine); |
| 45 | if (displayedLine.length > maxLineLength) { |
| 46 | displayedLine = `${displayedLine.slice(0, maxLineLength - ELLIPSIS.length)}${ELLIPSIS}`; |
| 47 | } |
| 48 | if (isErrorLine) { |
| 49 | const indicator = |
| 50 | spaces(digits + 2 + tabsToSpaces(sourceLine.slice(0, column)).length) + '^'; |
| 51 | return `${lineNumber}: ${displayedLine}\n${indicator}`; |
| 52 | } |
| 53 | |
| 54 | return `${lineNumber}: ${displayedLine}`; |
| 55 | }) |
| 56 | .join('\n'); |
| 57 | } |