react/scripts/error-codes/transform-error-messages.js
Sebastian Markbåge 151cce3740
Track Stack of JSX Calls (#29032)
This is the first step to experimenting with a new type of stack traces
behind the `enableOwnerStacks` flag - in DEV only.

The idea is to generate stacks that are more like if the JSX was a
direct call even though it's actually a lazy call. Not only can you see
which exact JSX call line number generated the erroring component but if
that's inside an abstraction function, which function called that
function and if it's a component, which component generated that
component. For this to make sense it really need to be the "owner" stack
rather than the parent stack like we do for other component stacks. On
one hand it has more precise information but on the other hand it also
loses context. For most types of problems the owner stack is the most
useful though since it tells you which component rendered this
component.

The problem with the platform in its current state is that there's two
ways to deal with stacks:

1) `new Error().stack` 
2) `console.createTask()`

The nice thing about `new Error().stack` is that we can extract the
frames and piece them together in whatever way we want. That is great
for constructing custom UIs like error dialogs. Unfortunately, we can't
take custom stacks and set them in the native UIs like Chrome DevTools.

The nice thing about `console.createTask()` is that the resulting stacks
are natively integrated into the Chrome DevTools in the console and the
breakpoint debugger. They also automatically follow source mapping and
ignoreLists. The downside is that there's no way to extract the async
stack outside the native UI itself so this information cannot be used
for custom UIs like errors dialogs. It also means we can't collect this
on the server and then pass it to the client for server components.

The solution here is that we use both techniques and collect both an
`Error` object and a `Task` object for every JSX call.

The main concern about this approach is the performance so that's the
main thing to test. It's certainly too slow for production but it might
also be too slow even for DEV.

This first PR doesn't actually use the stacks yet. It just collects them
as the first step. The next step is to start utilizing this information
in error printing etc.

For RSC we pass the stack along across over the wire. This can be
concatenated on the client following the owner path to create an owner
stack leading back into the server. We'll later use this information to
restore fake frames on the client for native integration. Since this
information quickly gets pretty heavy if we include all frames, we strip
out the top frame. We also strip out everything below the functions that
call into user space in the Flight runtime. To do this we need to figure
out the frames that represents calling out into user space. The
resulting stack is typically just the one frame inside the owner
component's JSX callsite. I also eagerly strip out things we expect to
be ignoreList:ed anyway - such as `node_modules` and Node.js internals.
2024-05-09 12:23:05 -04:00

155 lines
4.5 KiB
JavaScript

/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'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) {
// Turns this code:
//
// new Error(`A ${adj} message that contains ${noun}`);
//
// or this code (no constructor):
//
// Error(`A ${adj} message that contains ${noun}`);
//
// into this:
//
// Error(formatProdErrorMessage(ERR_CODE, adj, noun));
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
);
if (errorMsgLiteral === 'react-stack-top-frame') {
// This is a special case for generating stack traces.
return;
}
let prodErrorId = errorMap[errorMsgLiteral];
if (prodErrorId === undefined) {
// There is no error code for this message. Add an inline comment
// that flags this as an unminified error. This allows the build
// to proceed, while also allowing a post-build linter to detect it.
//
// Outputs:
// /* FIXME (minify-errors-in-prod): Unminified error message in production build! */
// /* <expected-error-format>"A % message that contains %"</expected-error-format> */
// if (!condition) {
// throw Error(`A ${adj} message that contains ${noun}`);
// }
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++) {
// TODO: Since this only detects one of many ways to disable a lint
// rule, we should instead search for a custom directive (like
// no-minify-errors) instead of ESLint. Will need to update our lint
// rule to recognize the same directive.
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);
// Import formatProdErrorMessage
const formatProdErrorMessageIdentifier = helperModuleImports.addDefault(
path,
'shared/formatProdErrorMessage',
{nameHint: 'formatProdErrorMessage'}
);
// Outputs:
// formatProdErrorMessage(ERR_CODE, adj, noun);
const prodMessage = t.callExpression(formatProdErrorMessageIdentifier, [
t.numericLiteral(prodErrorId),
...errorMsgExpressions,
]);
// Outputs:
// Error(formatProdErrorMessage(ERR_CODE, adj, noun));
const newErrorCall = t.callExpression(t.identifier('Error'), [
prodMessage,
...node.arguments.slice(1),
]);
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;
}
},
},
};
};