'use strict';
const fs = require('fs');
const {evalStringAndTemplateConcat} = require('../shared/evalToString');
const invertObject = require('./invertObject');
const helperModuleImports = require('@babel/helper-module-imports');
const errorMap = invertObject(
JSON.parse(fs.readFileSync(__dirname + '/codes.json', 'utf-8'))
);
const SEEN_SYMBOL = Symbol('transform-error-messages.seen');
module.exports = function(babel) {
const t = babel.types;
function ErrorCallExpression(path, file) {
const node = path.node;
if (node[SEEN_SYMBOL]) {
return;
}
node[SEEN_SYMBOL] = true;
const errorMsgNode = node.arguments[0];
if (errorMsgNode === undefined) {
return;
}
const errorMsgExpressions = [];
const errorMsgLiteral = evalStringAndTemplateConcat(
errorMsgNode,
errorMsgExpressions
);
let prodErrorId = errorMap[errorMsgLiteral];
if (prodErrorId === undefined) {
let leadingComments = [];
const statementParent = path.getStatementParent();
let nextPath = path;
while (true) {
let nextNode = nextPath.node;
if (nextNode.leadingComments) {
leadingComments.push(...nextNode.leadingComments);
}
if (nextPath === statementParent) {
break;
}
nextPath = nextPath.parentPath;
}
if (leadingComments !== undefined) {
for (let i = 0; i < leadingComments.length; i++) {
const commentText = leadingComments[i].value;
if (
commentText.includes(
'eslint-disable-next-line react-internal/prod-error-codes'
)
) {
return;
}
}
}
statementParent.addComment(
'leading',
`! <expected-error-format>"${errorMsgLiteral}"</expected-error-format>`
);
statementParent.addComment(
'leading',
'! FIXME (minify-errors-in-prod): Unminified error message in production build!'
);
return;
}
prodErrorId = parseInt(prodErrorId, 10);
const formatProdErrorMessageIdentifier = helperModuleImports.addDefault(
path,
'shared/formatProdErrorMessage',
{nameHint: 'formatProdErrorMessage'}
);
const prodMessage = t.callExpression(formatProdErrorMessageIdentifier, [
t.numericLiteral(prodErrorId),
...errorMsgExpressions,
]);
const newErrorCall = t.callExpression(t.identifier('Error'), [prodMessage]);
newErrorCall[SEEN_SYMBOL] = true;
path.replaceWith(newErrorCall);
}
return {
visitor: {
NewExpression(path, file) {
if (path.get('callee').isIdentifier({name: 'Error'})) {
ErrorCallExpression(path, file);
}
},
CallExpression(path, file) {
if (path.get('callee').isIdentifier({name: 'Error'})) {
ErrorCallExpression(path, file);
return;
}
},
},
};
};