1/* 2 * Copyright (c) 2022-2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import * as ts from 'typescript'; 17 18import { isVisitResultNode, visitVisitResult } from './utils/ASTHelpers'; 19 20export class Transformer { 21 private readonly context: ts.TransformationContext; 22 private readonly sourceFileMap: Map<string, ts.SourceFile>; 23 private readonly transformers: ts.Visitor[]; 24 25 constructor( 26 context: ts.TransformationContext, 27 customSourceFileMap: Map<string, ts.SourceFile>, 28 transformerCallbacks: ts.Visitor[] 29 ) { 30 this.context = context; 31 this.sourceFileMap = customSourceFileMap; 32 this.transformers = transformerCallbacks; 33 } 34 35 createCustomTransformer(): ts.CustomTransformer { 36 const visitor = <T extends ts.Node>(sourceFile: T): T => { 37 return ts.visitNode(sourceFile, this.visitNode.bind(this)); 38 }; 39 40 return { 41 transformSourceFile: visitor, 42 transformBundle: visitor 43 }; 44 } 45 46 visitNode(node: ts.Node): ts.VisitResult<ts.Node> { 47 48 /* Depth-first order */ 49 50 let visitResult: ts.VisitResult<ts.Node> = ts.visitEachChild(node, this.visitNode.bind(this), this.context); 51 52 for (const transformer of this.transformers) { 53 visitResult = visitVisitResult(visitResult, transformer); 54 } 55 56 /* Reverse order */ 57 /* 58 * let fixedNode: ts.VisitResult<ts.Node> = node; 59 * fixedNode = this.autofixer.fixNode(node); 60 * return ts.visitEachChild(fixedNode, this.visitNode.bind(this), this.context); 61 */ 62 63 /* 64 * Here we set custom source file map in order to later create custom compilerHost 65 * to traverse and typecheck modified files 66 */ 67 if (isVisitResultNode(visitResult) && ts.isSourceFile(visitResult)) { 68 this.sourceFileMap?.set( 69 visitResult.fileName, 70 ts.createSourceFile( 71 visitResult.fileName, 72 ts.createPrinter().printFile(visitResult), 73 visitResult.languageVersion 74 ) 75 ); 76 } 77 78 return visitResult; 79 } 80} 81