TypeError: state.generator[node.type] is not a function
florentin-soubrand opened this issue · comments
Motivation
I was trying to translate a JSON AST to JS code through 'json-to-ast' library and Astring but the error in the title occured.
Expected behavior
After importing generate like this :
const { generate } = require('astring')
Calling generate with an AST as parameter like this :
const code = generate(ast)
should not trigger an error
Actual behavior
Here is the complete error with "my_file.js" being the source code:
`/home/[...]/node_modules/astring/dist/astring.js:1209
state.generator[node.type](node, state);
^
TypeError: state.generator[node.type] is not a function
at generate (/home/[...]/node_modules/astring/dist/astring.js:1209:29)
at Object. (/home/[...]/my_file.js:977:14)
at Module._compile (node:internal/modules/cjs/loader:1241:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
at Module.load (node:internal/modules/cjs/loader:1091:32)
at Module._load (node:internal/modules/cjs/loader:938:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47
Node.js v20.6.0`
Thanks for raising this @florentin-soubrand. The error is most likely due to a node type being unknown to the Estree
specification, and thus to Astring as well (my hunch is that json-to-ast
outputs object nodes with "Object"
as its type instead of "ObjectExpression"
).
An easy fix would be to normalize the AST
output by json-to-ast
to an Estree
compatible one.