Skip to content

Commit 13cf9c1

Browse files
authoredNov 9, 2023
Fix code frame for parsing { (#44)
1 parent 7230975 commit 13cf9c1

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed
 

‎index.js

+10-2
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,21 @@ const getErrorLocation = (string, message) => {
4343
return;
4444
}
4545

46-
const {index, line, column} = match.groups;
46+
let {index, line, column} = match.groups;
4747

4848
if (line && column) {
4949
return {line: Number(line), column: Number(column)};
5050
}
5151

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});
5361
};
5462

5563
export default function parseJson(string, reviver, filename) {

‎test.js

+25-4
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@ import {outdent} from 'outdent';
44
import stripAnsi from 'strip-ansi';
55
import parseJson, {JSONError} from './index.js';
66

7-
const errorMessageRegex = (() => {
8-
const version = Number(process.versions.node.split('.')[0]);
7+
const NODE_JS_VERSION = Number(process.versions.node.split('.')[0]);
98

10-
if (version < 20) {
9+
const errorMessageRegex = (() => {
10+
if (NODE_JS_VERSION < 20) {
1111
return /Unexpected token "}"/;
1212
}
1313

14-
if (version < 21) {
14+
if (NODE_JS_VERSION < 21) {
1515
return /Expected double-quoted property name in JSON at position 16 while parsing/;
1616
}
1717

@@ -85,3 +85,24 @@ test('has error frame properties', t => {
8585
t.is(stripAnsi(error.codeFrame), EXPECTED_CODE_FRAME);
8686
}
8787
});
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+
});

0 commit comments

Comments
 (0)
Please sign in to comment.