本文最后更新于 2025-08-14T01:08:34+08:00
AST 通用工具
框架
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| const fs = require('fs'); const types = require("@babel/types"); const parser = require("@babel/parser"); const template = require("@babel/template").default; const traverse = require("@babel/traverse").default; const generator = require("@babel/generator").default;
process.argv.length > 2 ? encodeFile = process.argv[2] : encodeFile = "./5s.js"; process.argv.length > 3 ? decodeFile = process.argv[3] : decodeFile = encodeFile.replace(".js", "") + "_ok.js";
let sourceCode = fs.readFileSync(encodeFile, { encoding: "utf-8" }); let ast = parser.parse(sourceCode); console.time("处理完毕,耗时");
console.timeEnd("处理完毕,耗时"); let { code } = generator(ast, opts = { "compact": false, "comments": false, "jsescOption": { "minimal": true }, });
fs.writeFile(decodeFile, code, (err) => { });
|
字符串合并
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| const AddObjPro = { BinaryExpression(path) { const { left, right, operator } = path.node;
if (operator === '+') { const leftValue = getStaticStringValue(left); const rightValue = getStaticStringValue(right);
if (leftValue !== null && rightValue !== null) { const combinedString = leftValue + rightValue;
const newStringLiteral = types.stringLiteral(combinedString);
path.replaceWith(newStringLiteral); } } }, };
function getStaticStringValue(node) { if (types.isStringLiteral(node)) { return node.value; } else if ( types.isBinaryExpression(node) && node.operator === '+' ) { const leftValue = getStaticStringValue(node.left); const rightValue = getStaticStringValue(node.right);
if (leftValue !== null && rightValue !== null) { return leftValue + rightValue; } } return null; }
traverse(ast, AddObjPro);
|
16进制转换为 数字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const hexadecimalToInt = { NumericLiteral(path) { const { value, extra } = path.node;
if (extra && extra.raw.startsWith('0x')) { const decimalValue = parseInt(extra.raw, 16);
const newNumericLiteral = types.numericLiteral(decimalValue);
path.replaceWith(newNumericLiteral); } }, };
traverse(ast, hexadecimalToInt);
|
花指令替换
AST_通用插件
https://hybpjx.cn/2024/08/31/AST-速记/