import * as ts from "typescript" ; import * as Lint from "tslint" ; import * as utils from "tsutils/typeguard/2.8" ; import * as Ignore from "./shared/ignore" ; import { createInvalidNode , CheckNodeResult , createCheckNodeRule } from "./shared/check-node" ; type Options = Ignore . IgnoreLocalOption & Ignore . IgnoreOption ; export const Rule = createCheckNodeRule ( Ignore . checkNodeWithIgnore ( checkNode ) , "Unexpected let, use const instead." ) ; function checkNode ( node , ctx ) { const results = [ checkVariableStatement ( node , ctx ) , checkForStatements ( node , ctx ) ] ; return { invalidNodes : results . reduce ( ( merged , result ) => [ ... merged , ... result . invalidNodes ] , [ ] ) , skipChildren : results . some ( result => result . skipChildren === true ) } ; } function checkVariableStatement ( node , ctx ) { if ( utils . isVariableStatement ( node ) ) { return checkDeclarationList ( node . declarationList , ctx ) ; } return { invalidNodes : [ ] } ; } function checkForStatements ( node , ctx ) { if ( ( utils . isForStatement ( node ) || utils . isForInStatement ( node ) || utils . isForOfStatement ( node ) ) && node . initializer && utils . isVariableDeclarationList ( node . initializer ) && Lint . isNodeFlagSet ( node . initializer , ts . NodeFlags . Let ) ) { return checkDeclarationList ( node . initializer , ctx ) ; } return { invalidNodes : [ ] } ; } function checkDeclarationList ( declarationList , ctx ) { if ( Lint . isNodeFlagSet ( declarationList , ts . NodeFlags . Let ) ) { const invalidVariableDeclarationNodes = [ ] ; let addFix = true ; for ( const variableDeclarationNode of declarationList . declarations ) { if ( ! Ignore . shouldIgnore ( variableDeclarationNode , ctx . options , ctx . sourceFile ) ) { invalidVariableDeclarationNodes . push ( createInvalidNode ( variableDeclarationNode , addFix ? [ new Lint . Replacement ( declarationList . getStart ( ctx . sourceFile ) , "let" . length , "const" ) ] : [ ] ) ) ; addFix = false ; } } return { invalidNodes : invalidVariableDeclarationNodes } ; } return { invalidNodes : [ ] } ; }