refakts
Version:
TypeScript refactoring tool built for AI coding agents to perform precise refactoring operations via command line instead of requiring complete code regeneration.
61 lines • 2.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TSQueryHandler = void 0;
const ts_morph_1 = require("ts-morph");
const tsquery_1 = require("@phenomnomnominal/tsquery");
class TSQueryHandler {
findNodeByQuery(sourceFile, query) {
const matches = this.executeQuery(sourceFile, query);
this.validateMatches(matches, query);
if (matches.length > 1) {
return this.handleMultipleMatches(sourceFile, matches, query);
}
return this.convertToMorphNode(sourceFile, matches[0]);
}
findNodesByQuery(sourceFile, query) {
const matches = this.executeQuery(sourceFile, query);
return matches.map(match => this.convertToMorphNode(sourceFile, match));
}
executeQuery(sourceFile, query) {
return (0, tsquery_1.tsquery)(sourceFile.compilerNode, query);
}
validateMatches(matches, query) {
if (matches.length === 0) {
throw new Error(`No matches found for query: ${query}`);
}
}
handleMultipleMatches(sourceFile, matches, query) {
const firstNode = this.convertToMorphNode(sourceFile, matches[0]);
if (!ts_morph_1.Node.isIdentifier(firstNode)) {
throw new Error(`Multiple matches found for query: ${query}. Please be more specific.`);
}
this.validateSameVariable(sourceFile, matches, firstNode.getText(), query);
return firstNode;
}
validateSameVariable(sourceFile, matches, variableName, query) {
for (let i = 1; i < matches.length; i++) {
const node = this.convertToMorphNode(sourceFile, matches[i]);
if (!ts_morph_1.Node.isIdentifier(node) || node.getText() !== variableName) {
throw new Error(`Multiple matches found for query: ${query}. Please be more specific.`);
}
}
}
convertToMorphNode(sourceFile, match) {
const start = match.getStart();
const end = match.getEnd();
const width = end - start;
return this.findExactNode(sourceFile, start, width) || this.findFallbackNode(sourceFile, start);
}
findExactNode(sourceFile, start, width) {
return sourceFile.getDescendantAtStartWithWidth(start, width);
}
findFallbackNode(sourceFile, start) {
const fallback = sourceFile.getDescendantAtPos(start);
if (!fallback) {
throw new Error(`Could not find ts-morph node for query match`);
}
return fallback;
}
}
exports.TSQueryHandler = TSQueryHandler;
//# sourceMappingURL=tsquery-handler.js.map