File tree 2 files changed +35
-6
lines changed
2 files changed +35
-6
lines changed Original file line number Diff line number Diff line change @@ -43,13 +43,21 @@ const getErrorLocation = (string, message) => {
43
43
return ;
44
44
}
45
45
46
- const { index, line, column} = match . groups ;
46
+ let { index, line, column} = match . groups ;
47
47
48
48
if ( line && column ) {
49
49
return { line : Number ( line ) , column : Number ( column ) } ;
50
50
}
51
51
52
- return indexToPosition ( string , Number ( index ) , { oneBased : true } ) ;
52
+ index = Number ( index ) ;
53
+
54
+ // The error location can be out of bounds.
55
+ if ( index === string . length ) {
56
+ const { line, column} = indexToPosition ( string , string . length - 1 , { oneBased : true } ) ;
57
+ return { line, column : column + 1 } ;
58
+ }
59
+
60
+ return indexToPosition ( string , index , { oneBased : true } ) ;
53
61
} ;
54
62
55
63
export default function parseJson ( string , reviver , filename ) {
Original file line number Diff line number Diff line change @@ -4,14 +4,14 @@ import {outdent} from 'outdent';
4
4
import stripAnsi from 'strip-ansi' ;
5
5
import parseJson , { JSONError } from './index.js' ;
6
6
7
- const errorMessageRegex = ( ( ) => {
8
- const version = Number ( process . versions . node . split ( '.' ) [ 0 ] ) ;
7
+ const NODE_JS_VERSION = Number ( process . versions . node . split ( '.' ) [ 0 ] ) ;
9
8
10
- if ( version < 20 ) {
9
+ const errorMessageRegex = ( ( ) => {
10
+ if ( NODE_JS_VERSION < 20 ) {
11
11
return / U n e x p e c t e d t o k e n " } " / ;
12
12
}
13
13
14
- if ( version < 21 ) {
14
+ if ( NODE_JS_VERSION < 21 ) {
15
15
return / E x p e c t e d d o u b l e - q u o t e d p r o p e r t y n a m e i n J S O N a t p o s i t i o n 1 6 w h i l e p a r s i n g / ;
16
16
}
17
17
@@ -85,3 +85,24 @@ test('has error frame properties', t => {
85
85
t . is ( stripAnsi ( error . codeFrame ) , EXPECTED_CODE_FRAME ) ;
86
86
}
87
87
} ) ;
88
+
89
+ test ( 'allow error location out of bounds' , t => {
90
+ try {
91
+ parseJson ( '{' ) ;
92
+ } catch ( error ) {
93
+ t . true ( error instanceof JSONError ) ;
94
+ t . is ( error . rawCodeFrame , NODE_JS_VERSION === 18 ? undefined : outdent `
95
+ > 1 | {
96
+ | ^
97
+ ` ) ;
98
+ }
99
+ } ) ;
100
+
101
+ test ( 'empty string' , t => {
102
+ try {
103
+ parseJson ( '' ) ;
104
+ } catch ( error ) {
105
+ t . true ( error instanceof JSONError ) ;
106
+ t . is ( error . rawCodeFrame , undefined ) ;
107
+ }
108
+ } ) ;
You can’t perform that action at this time.
0 commit comments