Skip to content

Commit f2943c4

Browse files
committed
Add improved error messages
1 parent 731eb5e commit f2943c4

File tree

4 files changed

+27
-12
lines changed

4 files changed

+27
-12
lines changed

lib/index.js

+14-10
Original file line numberDiff line numberDiff line change
@@ -96,18 +96,22 @@ export function fromJs(value, options) {
9696
onComment: comments
9797
})
9898
} catch (error) {
99-
const exception = /** @type {AcornError} */ (error)
100-
exception.message = exception.message.replace(/ \((\d+):(\d+)\)$/, '')
99+
const cause = /** @type {AcornError} */ (error)
101100

102-
throw new VFileMessage(
103-
exception,
104-
{
105-
line: exception.loc.line,
106-
column: exception.loc.column + 1,
107-
offset: exception.pos
101+
const message = new VFileMessage('Could not parse JavaScript with Acorn', {
102+
cause,
103+
place: {
104+
line: cause.loc.line,
105+
column: cause.loc.column + 1,
106+
offset: cause.pos
108107
},
109-
'esast-util-from-js:acorn'
110-
)
108+
ruleId: 'acorn',
109+
source: 'esast-util-from-js'
110+
})
111+
112+
message.url = 'https://github.com/syntax-tree/esast-util-from-js#throws'
113+
114+
throw message
111115
}
112116

113117
tree.comments = comments

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
"@types/estree-jsx": "^1.0.0",
4040
"acorn": "^8.0.0",
4141
"esast-util-from-estree": "^1.0.0",
42-
"vfile-message": "^3.0.0"
42+
"vfile-message": "^4.0.0"
4343
},
4444
"devDependencies": {
4545
"@types/node": "^20.0.0",

readme.md

+11
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,15 @@ Parse JavaScript to an esast.
135135

136136
Tree ([`Node`][node]).
137137

138+
###### Throws
139+
140+
When the JavaScript cannot be parsed with `acorn`, a
141+
[`VFileMessage`][vfile-message] is thrown.
142+
143+
This can for example happen when passing modern syntax (you could maybe use a
144+
newer `version`, or it might be that the syntax is not yet supported), or just
145+
otherwise invalid JavaScript (you might need a plugin).
146+
138147
### `Options`
139148

140149
Configuration (TypeScript type).
@@ -309,6 +318,8 @@ abide by its terms.
309318
310319
[estree-util-to-js]: https://github.com/syntax-tree/estree-util-to-js
311320
321+
[vfile-message]: https://github.com/vfile/vfile-message
322+
312323
[fromjs]: #fromjsvalue-options
313324
314325
[options]: #options

test/index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ test('fromJs', () => {
6969
function () {
7070
fromJs('import "a"')
7171
},
72-
/'import' and 'export' may appear only with 'sourceType: module'/,
72+
/Could not parse JavaScript with Acorn/,
7373
'should fail on an import w/o `module: true`'
7474
)
7575

0 commit comments

Comments
 (0)