forked from hashicorp/next-mdx-remote
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat-mdx-error.ts
66 lines (55 loc) · 1.72 KB
/
format-mdx-error.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: MPL-2.0
*/
import { codeFrameColumns } from '@babel/code-frame'
/**
* Attempt to parse position information from an error message originating from the MDX compiler.
* Only used if the error object doesn't contain
*/
function parsePositionInformationFromErrorMessage(
message: string
): { start: { line: number; column: number } } | undefined {
const positionInfoPattern = /\d+:\d+(-\d+:\d+)/g
const match = message.match(positionInfoPattern)
if (match) {
// take the last match, that seems to be the most reliable source of the error.
const lastMatch = match.slice(-1)[0]
const [line, column] = lastMatch.split('-')[0].split(':')
return {
start: {
line: Number.parseInt(line, 10),
column: Number.parseInt(column, 10),
},
}
}
}
/**
* Prints a nicely formatted error message from an error caught during MDX compilation.
*
* @param error - Error caught from the mdx compiler
* @param source - Raw MDX string
* @returns Error
*/
export function createFormattedMDXError(error: any, source: string) {
const position =
error?.position ?? parsePositionInformationFromErrorMessage(error?.message)
const codeFrames = position
? codeFrameColumns(
source,
{
start: {
line: position.start.line,
column: position.start.column ?? 0,
},
},
{ linesAbove: 2, linesBelow: 2 }
)
: ''
const formattedError = new Error(`[next-mdx-remote] error compiling MDX:
${error?.message}
${codeFrames ? '\n' + codeFrames + '\n' : ''}
More information: https://mdxjs.com/docs/troubleshooting-mdx`)
formattedError.stack = ''
return formattedError
}