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'; 17import type { CommandLineOptions } from '../CommandLineOptions'; 18import { createCompilerHost, readDeclareFiles } from './ResolveSdks'; 19 20function getTargetESVersionLib(optionsTarget: ts.ScriptTarget): string[] { 21 switch (optionsTarget) { 22 case ts.ScriptTarget.ES2017: 23 return ['lib.es2017.d.ts']; 24 case ts.ScriptTarget.ES2021: 25 return ['lib.es2021.d.ts']; 26 default: 27 return ['lib.es2021.d.ts']; 28 } 29} 30 31export function formTscOptions( 32 cmdOptions: CommandLineOptions, 33 overrideCompilerOptions: ts.CompilerOptions 34): ts.CreateProgramOptions { 35 if (cmdOptions.parsedConfigFile) { 36 const options: ts.CreateProgramOptions = { 37 rootNames: cmdOptions.parsedConfigFile.fileNames, 38 options: cmdOptions.parsedConfigFile.options, 39 projectReferences: cmdOptions.parsedConfigFile.projectReferences, 40 configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(cmdOptions.parsedConfigFile) 41 }; 42 options.options = Object.assign(options.options, overrideCompilerOptions); 43 return options; 44 } 45 const rootNames = cmdOptions.inputFiles.concat(readDeclareFiles(cmdOptions.sdkDefaultApiPath ?? '')); 46 const ESVersion = cmdOptions.followSdkSettings ? ts.ScriptTarget.ES2021 : ts.ScriptTarget.Latest; 47 const ESVersionLib = cmdOptions.followSdkSettings ? getTargetESVersionLib(ESVersion) : undefined; 48 const isCheckJs = !cmdOptions.followSdkSettings; 49 const options: ts.CreateProgramOptions = { 50 rootNames: rootNames, 51 options: { 52 target: ESVersion, 53 module: ts.ModuleKind.CommonJS, 54 allowJs: true, 55 checkJs: isCheckJs, 56 lib: ESVersionLib 57 } 58 }; 59 if (cmdOptions.sdkDefaultApiPath && cmdOptions.arktsWholeProjectPath && cmdOptions.sdkExternalApiPath) { 60 options.host = createCompilerHost( 61 cmdOptions.sdkDefaultApiPath, 62 cmdOptions.sdkExternalApiPath, 63 cmdOptions.arktsWholeProjectPath 64 ); 65 } 66 options.options = Object.assign(options.options, overrideCompilerOptions); 67 return options; 68} 69