UNPKG

refakts

Version:

TypeScript refactoring tool built for AI coding agents to perform precise refactoring operations via command line instead of requiring complete code regeneration.

80 lines 3.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.VariableDeclarationFinder = void 0; const ts_morph_1 = require("ts-morph"); class VariableDeclarationFinder { findVariableDeclaration(sourceFile, variableName, contextNode) { const declaration = contextNode ? this.findClosestDeclaration(contextNode, variableName) : this.searchForDeclaration(sourceFile, variableName); if (!declaration) { throw new Error(`Variable declaration for '${variableName}' not found`); } return declaration; } searchForDeclaration(sourceFile, variableName) { const variableDeclarations = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.VariableDeclaration); for (const decl of variableDeclarations) { if (this.matchesVariableName(decl, variableName)) { return decl; } } return undefined; } findClosestDeclaration(contextNode, variableName) { const allDeclarations = contextNode.getSourceFile().getDescendantsOfKind(ts_morph_1.SyntaxKind.VariableDeclaration); const matchingDeclarations = allDeclarations.filter(decl => this.matchesVariableName(decl, variableName)); if (matchingDeclarations.length === 1) { return matchingDeclarations[0]; } return this.findDeclarationInSameScope(contextNode, matchingDeclarations); } findDeclarationInSameScope(contextNode, declarations) { const contextMethod = this.findContainingMethod(contextNode); const sameScopeDeclaration = this.findDeclarationInMethod(declarations, contextMethod); return sameScopeDeclaration || declarations[0]; } findDeclarationInMethod(declarations, targetMethod) { for (const decl of declarations) { const declMethod = this.findContainingMethod(decl); if (declMethod === targetMethod) { return decl; } } return undefined; } findContainingMethod(node) { let current = node; while (current) { if (ts_morph_1.Node.isMethodDeclaration(current) || ts_morph_1.Node.isFunctionDeclaration(current)) { return current; } current = current.getParent(); } return undefined; } matchesVariableName(declaration, variableName) { if (declaration.getName() === variableName) { return true; } return this.matchesDestructuredVariable(declaration, variableName); } matchesDestructuredVariable(declaration, variableName) { const nameNode = declaration.getNameNode(); if (!ts_morph_1.Node.isObjectBindingPattern(nameNode)) { return false; } return this.hasMatchingElement(nameNode, variableName); } hasMatchingElement(nameNode, variableName) { const bindingPattern = nameNode.asKindOrThrow(ts_morph_1.SyntaxKind.ObjectBindingPattern); for (const element of bindingPattern.getElements()) { if (element.getName() === variableName) { return true; } } return false; } } exports.VariableDeclarationFinder = VariableDeclarationFinder; //# sourceMappingURL=variable-declaration-finder.js.map