ast-utils.js 2.55 KB
const parser = require("@babel/parser");

function parseJavaScript(source, filePath) {
	return parser.parse(source, {
		sourceType: "unambiguous",
		sourceFilename: filePath,
		plugins: [
			"dynamicImport",
			"jsx",
			"objectRestSpread",
			"optionalCatchBinding",
			"optionalChaining",
			"nullishCoalescingOperator",
			"classProperties",
		],
	});
}

function propertyName(property) {
	if (!property || !property.key) {
		return null;
	}
	if (property.computed) {
		return null;
	}
	return property.key.name || property.key.value || null;
}

function findProperty(objectNode, name) {
	if (!objectNode || objectNode.type !== "ObjectExpression") {
		return null;
	}
	return objectNode.properties.find(property => String(propertyName(property)) === String(name)) || null;
}

function staticPrimitive(node, constants = new Map()) {
	if (!node) {
		return null;
	}
	if (["StringLiteral", "NumericLiteral", "BooleanLiteral"].includes(node.type)) {
		return node.value;
	}
	if (node.type === "Identifier" && constants.has(node.name)) {
		return constants.get(node.name);
	}
	if (node.type === "TemplateLiteral") {
		let value = "";
		for (let index = 0; index < node.quasis.length; index += 1) {
			value += node.quasis[index].value.cooked || "";
			if (index < node.expressions.length) {
				const expressionValue = staticPrimitive(node.expressions[index], constants);
				if (expressionValue === null) {
					return null;
				}
				value += String(expressionValue);
			}
		}
		return value;
	}
	if (node.type === "BinaryExpression" && node.operator === "+") {
		const left = staticPrimitive(node.left, constants);
		const right = staticPrimitive(node.right, constants);
		return left === null || right === null ? null : `${left}${right}`;
	}
	return null;
}

function locationOf(node, filePath) {
	return {
		path: filePath,
		line: node && node.loc ? node.loc.start.line : 1,
		column: node && node.loc ? node.loc.start.column : 0,
	};
}

function objectEntries(objectNode) {
	if (!objectNode || objectNode.type !== "ObjectExpression") {
		return [];
	}
	return objectNode.properties
		.map(property => ({
			name: propertyName(property),
			node: property,
			value: property.value || property,
		}))
		.filter(entry => entry.name !== null);
}

function arrayValues(node, constants = new Map()) {
	if (!node || node.type !== "ArrayExpression") {
		return [];
	}
	return node.elements.map(element => staticPrimitive(element, constants)).filter(value => value !== null);
}

module.exports = {
	arrayValues,
	findProperty,
	locationOf,
	objectEntries,
	parseJavaScript,
	propertyName,
	staticPrimitive,
};