Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hacking "check ast" into node_modules/prettier/bin/prettier.js at the bottom of `function format(argv, input, opt) {`
//
// at the bottom of `function format(argv, input, opt) {`, near line 20367
const pp = prettier$3.format(input, opt);
const ast = cleanAST(prettier$3.__debug.parse(input, opt));
const past = cleanAST(prettier$3.__debug.parse(pp, opt));
if (ast !== past) {
const MAX_AST_SIZE = 2097152; // 2MB
const astDiff =
ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE
? "AST diff too large to render"
: diff(ast, past);
const safeJsxChanges = [
'"children": []',
'"children": [',
'{',
'"type": "JSXExpressionContainer",',
'"expression": {',
'"type": "StringLiteral",',
'"value": " "',
'},',
'}',
']',
'],',
]
const safeNameRegex = /"name": "(\w+)",?/
const minusLines = astDiff
.split('\n')
.filter(l => l.match(/^\-\s+\S/))
.map(l => l.replace(/^\-\s+/, ''));
const plusLines = astDiff
.split('\n')
.filter(l => l.match(/^\+\s+\S/))
.map(l => l.replace(/^\+\s+/, ''));
const unsafePlusLines = plusLines.filter(l => {
if (safeJsxChanges.includes(l)) return false;
if (l.match(/"type": "Identifier",?/)) return false;
if (
l.match(safeNameRegex) &&
minusLines.join('').includes(`"value": "${l.match(safeNameRegex)[1]}"`)
) return false;
return true;
});
const unsafeMinusLines = minusLines.filter(l => {
if (safeJsxChanges.includes(l)) return false;
if (l.match(/"type": "StringLiteral",?/)) return false;
if (l.match(/"value": "\w+",?/)) return false;
return true;
});
if (unsafePlusLines.length === 0 && unsafeMinusLines.length === 0) {
console.log()
console.warn('Safe diff:')
console.warn(astDiff)
} else {
throw new errors.DebugError(
"ast(input) !== ast(prettier(input))\n" +
astDiff +
"\n" //+
// diff(input, pp)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment