1/* 2 * Copyright (c) 2022 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 fs from 'fs'; 17import path from 'path'; 18import * as ts from 'typescript'; 19import * as crypto from 'crypto'; 20const fse = require('fs-extra'); 21 22import { 23 projectConfig, 24 systemModules, 25 globalProgram, 26 sdkConfigs, 27 sdkConfigPrefix, 28 partialUpdateConfig, 29 resetProjectConfig, 30 resetGlobalProgram 31} from '../main'; 32import { 33 preprocessExtend, 34 preprocessNewExtend 35} from './validate_ui_syntax'; 36import { 37 INNER_COMPONENT_MEMBER_DECORATORS, 38 COMPONENT_DECORATORS_PARAMS, 39 COMPONENT_BUILD_FUNCTION, 40 STYLE_ADD_DOUBLE_DOLLAR, 41 $$, 42 PROPERTIES_ADD_DOUBLE_DOLLAR, 43 DOLLAR_BLOCK_INTERFACE, 44 COMPONENT_EXTEND_DECORATOR, 45 COMPONENT_BUILDER_DECORATOR, 46 ESMODULE, 47 EXTNAME_D_ETS, 48 EXTNAME_JS, 49 FOREACH_LAZYFOREACH, 50 COMPONENT_IF, 51 TS_WATCH_END_MSG, 52 TS_BUILD_INFO_SUFFIX, 53 HOT_RELOAD_BUILD_INFO_SUFFIX, 54 WATCH_COMPILER_BUILD_INFO_SUFFIX, 55 COMPONENT_STYLES_DECORATOR 56} from './pre_define'; 57import { 58 INNER_COMPONENT_NAMES, 59 JS_BIND_COMPONENTS, 60 BUILDIN_STYLE_NAMES 61} from './component_map'; 62import { logger } from './compile_info'; 63import { 64 hasDecorator, 65 isString, 66 generateSourceFilesInHar, 67 startTimeStatisticsLocation, 68 stopTimeStatisticsLocation, 69 resolveModuleNamesTime, 70 CompilationTimeStatistics, 71 storedFileInfo, 72 toUnixPath, 73 isWindows, 74 isMac, 75 tryToLowerCasePath, 76 getRollupCache, 77 setRollupCache 78} from './utils'; 79import { 80 isExtendFunction, 81 isOriginalExtend 82} from './process_ui_syntax'; 83import { visualTransform } from './process_visual'; 84import { tsWatchEmitter } from './fast_build/ets_ui/rollup-plugin-ets-checker'; 85import { 86 doArkTSLinter, 87 ArkTSLinterMode, 88 ArkTSVersion, 89} from './do_arkTS_linter'; 90import { 91 getJsDocNodeCheckConfig, 92 isCardFile, 93 getRealModulePath, 94 getJsDocNodeConditionCheckResult 95} from './fast_build/system_api/api_check_utils'; 96 97export interface LanguageServiceCache { 98 service?: ts.LanguageService; 99 pkgJsonFileHash?: string; 100 targetESVersion?: ts.ScriptTarget; 101 preTsImportSendable?: boolean; 102} 103 104export const SOURCE_FILES: Map<string, ts.SourceFile> = new Map(); 105export let localPackageSet: Set<string> = new Set(); 106 107export function readDeaclareFiles(): string[] { 108 const declarationsFileNames: string[] = []; 109 fs.readdirSync(path.resolve(__dirname, '../declarations')) 110 .forEach((fileName: string) => { 111 if (/\.d\.ts$/.test(fileName)) { 112 declarationsFileNames.push(path.resolve(__dirname, '../declarations', fileName)); 113 } 114 }); 115 return declarationsFileNames; 116} 117 118const buildInfoWriteFile: ts.WriteFileCallback = (fileName: string, data: string) => { 119 if (fileName.includes(TS_BUILD_INFO_SUFFIX)) { 120 const fd: number = fs.openSync(fileName, 'w'); 121 fs.writeSync(fd, data, undefined, 'utf8'); 122 fs.closeSync(fd); 123 } 124}; 125 126// The collection records the file name and the corresponding version, where the version is the hash value of the text in last compilation. 127const filesBuildInfo: Map<string, string> = new Map(); 128 129export const compilerOptions: ts.CompilerOptions = ts.readConfigFile( 130 path.resolve(__dirname, '../tsconfig.json'), ts.sys.readFile).config.compilerOptions; 131function setCompilerOptions(resolveModulePaths: string[]): void { 132 const allPath: Array<string> = ['*']; 133 const basePath: string = path.resolve(projectConfig.projectPath); 134 if (process.env.compileTool === 'rollup' && resolveModulePaths && resolveModulePaths.length) { 135 resolveModulePaths.forEach((item: string) => { 136 if (!(/oh_modules$/.test(item) || /node_modules$/.test(item))) { 137 allPath.push(path.join(path.relative(basePath, item), '*')); 138 } 139 }); 140 } else { 141 if (!projectConfig.aceModuleJsonPath) { 142 allPath.push('../../../../../*'); 143 allPath.push('../../*'); 144 } else { 145 allPath.push('../../../../*'); 146 allPath.push('../*'); 147 } 148 } 149 const suffix: string = projectConfig.hotReload ? HOT_RELOAD_BUILD_INFO_SUFFIX : TS_BUILD_INFO_SUFFIX; 150 const buildInfoPath: string = path.resolve(projectConfig.cachePath, '..', suffix); 151 checkArkTSVersion(); 152 Object.assign(compilerOptions, { 153 'allowJs': getArkTSLinterMode() !== ArkTSLinterMode.NOT_USE ? true : false, 154 'checkJs': getArkTSLinterMode() !== ArkTSLinterMode.NOT_USE ? false : undefined, 155 'emitNodeModulesFiles': true, 156 'importsNotUsedAsValues': ts.ImportsNotUsedAsValues.Preserve, 157 'module': ts.ModuleKind.CommonJS, 158 'moduleResolution': ts.ModuleResolutionKind.NodeJs, 159 'noEmit': true, 160 'target': convertConfigTarget(getTargetESVersion()), 161 'baseUrl': basePath, 162 'paths': { 163 '*': allPath 164 }, 165 'lib': convertConfigLib(getTargetESVersionLib()), 166 'types': projectConfig.compilerTypes, 167 'etsLoaderPath': projectConfig.etsLoaderPath, 168 'needDoArkTsLinter': getArkTSLinterMode() !== ArkTSLinterMode.NOT_USE, 169 'isCompatibleVersion': getArkTSLinterMode() === ArkTSLinterMode.COMPATIBLE_MODE, 170 'skipTscOhModuleCheck': partialUpdateConfig.skipTscOhModuleCheck, 171 'skipArkTSStaticBlocksCheck': partialUpdateConfig.skipArkTSStaticBlocksCheck, 172 // options incremental && tsBuildInfoFile are required for applying incremental ability of typescript 173 'incremental': true, 174 'tsBuildInfoFile': buildInfoPath, 175 'tsImportSendableEnable': tsImportSendable, 176 'skipPathsInKeyForCompilationSettings': reuseLanguageServiceForDepChange, 177 'compatibleSdkVersionStage': projectConfig.compatibleSdkVersionStage, 178 'compatibleSdkVersion': projectConfig.compatibleSdkVersion 179 }); 180 if (projectConfig.compileMode === ESMODULE) { 181 Object.assign(compilerOptions, { 182 'importsNotUsedAsValues': ts.ImportsNotUsedAsValues.Remove, 183 'module': ts.ModuleKind.ES2020 184 }); 185 } 186 if (projectConfig.packageDir === 'oh_modules') { 187 Object.assign(compilerOptions, {'packageManagerType': 'ohpm'}); 188 } 189 readTsBuildInfoFileInCrementalMode(buildInfoPath, projectConfig); 190} 191 192function checkArkTSVersion(): void { 193 const etsCheckerLogger = fastBuildLogger || logger; 194 if (getArkTSVersion() === ArkTSVersion.ArkTS_1_0 && tsImportSendable) { 195 const logMessage: string = 'ArkTS: ArkTSVersion1.0 does not support tsImportSendable in any condition'; 196 etsCheckerLogger.error('\u001b[31m' + logMessage); 197 tsImportSendable = false; 198 } 199} 200 201// Change target to enum's value,e.g: "es2021" => ts.ScriptTarget.ES2021 202function convertConfigTarget(target: number | string): number | string { 203 if ((typeof target === 'number') && (target in ts.ScriptTarget)) { 204 return target; 205 } 206 return ts.convertCompilerOptionsFromJson({ 'target': target }, '').options.target; 207} 208 209// Change lib to libMap's value,e.g: "es2021" => "lib.es2021.d.ts" 210function convertConfigLib(libs: string[]): string[] { 211 let converted: boolean = true; 212 let libMapValues: string[] = Array.from(ts.libMap.values()); 213 for (let i = 0; i < libs.length; i++) { 214 if (!libMapValues.includes(libs[i])) { 215 converted = false; 216 break; 217 } 218 } 219 if (converted) { 220 return libs; 221 } 222 return ts.convertCompilerOptionsFromJson({ 'lib': libs }, '').options.lib; 223} 224 225/** 226 * Read the source code information in the project of the last compilation process, and then use it 227 * to determine whether the file has been modified during this compilation process. 228 */ 229function readTsBuildInfoFileInCrementalMode(buildInfoPath: string, projectConfig: Object): void { 230 if (!fs.existsSync(buildInfoPath) || !(projectConfig.compileHar || projectConfig.compileShared)) { 231 return; 232 } 233 234 type FileInfoType = { 235 version: string; 236 affectsGlobalScope: boolean; 237 }; 238 type ProgramType = { 239 fileNames: string[]; 240 fileInfos: (FileInfoType | string)[]; 241 }; 242 let buildInfoProgram: ProgramType; 243 try { 244 const content: {program: ProgramType} = JSON.parse(fs.readFileSync(buildInfoPath, 'utf-8')); 245 buildInfoProgram = content.program; 246 if (!buildInfoProgram || !buildInfoProgram.fileNames || !buildInfoProgram.fileInfos) { 247 throw new Error('.tsbuildinfo content is invalid'); 248 } 249 } catch (err) { 250 fastBuildLogger.warn('\u001b[33m' + 'ArkTS: Failed to parse .tsbuildinfo file. Error message: ' + err.message.toString()); 251 return; 252 } 253 const buildInfoDirectory: string = path.dirname(buildInfoPath); 254 /** 255 * For the windos and mac platform, the file path in tsbuildinfo is in lowercase, while buildInfoDirectory is the original path (including uppercase). 256 * Therefore, the path needs to be converted to lowercase, and then perform path comparison. 257 */ 258 const isMacOrWin = isWindows() || isMac(); 259 const fileNames: string[] = buildInfoProgram.fileNames; 260 const fileInfos: (FileInfoType | string)[] = buildInfoProgram.fileInfos; 261 fileInfos.forEach((fileInfo, index) => { 262 const version: string = typeof fileInfo === 'string' ? fileInfo : fileInfo.version; 263 const absPath: string = path.resolve(buildInfoDirectory, fileNames[index]); 264 filesBuildInfo.set(isMacOrWin ? tryToLowerCasePath(absPath) : absPath, version); 265 }); 266} 267 268interface extendInfo { 269 start: number, 270 end: number, 271 compName: string 272} 273 274function createHash(str: string): string { 275 const hash = crypto.createHash('sha256'); 276 hash.update(str); 277 return hash.digest('hex'); 278} 279 280export const fileHashScriptVersion: (fileName: string) => string = (fileName: string) => { 281 if (!fs.existsSync(fileName)) { 282 return '0'; 283 } 284 285 let fileContent: string = fs.readFileSync(fileName).toString(); 286 let cacheInfo: CacheFileName = cache[path.resolve(fileName)]; 287 288 // Error code corresponding to message `Cannot find module xx or its corresponding type declarations` 289 const errorCodeRequireRecheck: number = 2307; 290 291 if (cacheInfo && cacheInfo.error === true && cacheInfo.errorCodes && cacheInfo.errorCodes.includes(errorCodeRequireRecheck)) { 292 // If this file had errors that require recheck in the last compilation, 293 // mark the file as modified by modifying its hash value, thereby triggering tsc to recheck. 294 fileContent += Date.now().toString(); 295 } 296 return createHash(fileContent); 297}; 298 299// Reuse the last language service when dependency in oh-package.json5 changes to enhance performance in incremental building. 300// Setting this to false will create a new language service on dependency changes, like a full rebuild. 301const reuseLanguageServiceForDepChange: boolean = true; 302// When dependency changes and reusing the last language service, enable this flag to recheck code dependent on those dependencies. 303export let needReCheckForChangedDepUsers: boolean = false; 304 305export function createLanguageService(rootFileNames: string[], resolveModulePaths: string[], 306 compilationTime: CompilationTimeStatistics = null, rollupShareObject?: any): ts.LanguageService { 307 setCompilerOptions(resolveModulePaths); 308 const servicesHost: ts.LanguageServiceHost = { 309 getScriptFileNames: () => [...rootFileNames, ...readDeaclareFiles()], 310 getScriptVersion: fileHashScriptVersion, 311 getScriptSnapshot: function(fileName) { 312 if (!fs.existsSync(fileName)) { 313 return undefined; 314 } 315 if (/(?<!\.d)\.(ets|ts)$/.test(fileName)) { 316 startTimeStatisticsLocation(compilationTime ? compilationTime.scriptSnapshotTime : undefined); 317 appComponentCollection.set(path.join(fileName), new Set()); 318 let content: string = processContent(fs.readFileSync(fileName).toString(), fileName); 319 const extendFunctionInfo: extendInfo[] = []; 320 content = instanceInsteadThis(content, fileName, extendFunctionInfo, this.uiProps); 321 stopTimeStatisticsLocation(compilationTime ? compilationTime.scriptSnapshotTime : undefined); 322 return ts.ScriptSnapshot.fromString(content); 323 } 324 return ts.ScriptSnapshot.fromString(fs.readFileSync(fileName).toString()); 325 }, 326 getCurrentDirectory: () => process.cwd(), 327 getCompilationSettings: () => compilerOptions, 328 getDefaultLibFileName: options => ts.getDefaultLibFilePath(options), 329 fileExists: ts.sys.fileExists, 330 readFile: ts.sys.readFile, 331 readDirectory: ts.sys.readDirectory, 332 resolveModuleNames: resolveModuleNames, 333 resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, 334 directoryExists: ts.sys.directoryExists, 335 getDirectories: ts.sys.getDirectories, 336 getJsDocNodeCheckedConfig: (fileCheckedInfo: ts.FileCheckModuleInfo, sourceFileName: string) => { 337 return getJsDocNodeCheckConfig(fileCheckedInfo.currentFileName, sourceFileName); 338 }, 339 getFileCheckedModuleInfo: (containFilePath: string) => { 340 return { 341 fileNeedCheck: true, 342 checkPayload: undefined, 343 currentFileName: containFilePath 344 }; 345 }, 346 getJsDocNodeConditionCheckedResult: (jsDocFileCheckedInfo: ts.FileCheckModuleInfo, jsDocs: ts.JsDocTagInfo[]) => { 347 return getJsDocNodeConditionCheckResult(jsDocFileCheckedInfo, jsDocs); 348 }, 349 uiProps: [], 350 clearProps: function() { 351 dollarCollection.clear(); 352 extendCollection.clear(); 353 this.uiProps.length = 0; 354 }, 355 // TSC will re-do resolution if this callback return true. 356 hasInvalidatedResolutions: (filePath: string): boolean => { 357 return reuseLanguageServiceForDepChange && needReCheckForChangedDepUsers; 358 } 359 }; 360 361 if (process.env.watchMode === 'true') { 362 return ts.createLanguageService(servicesHost, ts.createDocumentRegistry()); 363 } 364 365 return getOrCreateLanguageService(servicesHost, rootFileNames, rollupShareObject); 366} 367 368export let targetESVersionChanged: boolean = false; 369 370function getOrCreateLanguageService(servicesHost: ts.LanguageServiceHost, rootFileNames: string[], 371 rollupShareObject?: any): ts.LanguageService { 372 let cacheKey: string = 'service'; 373 let cache: LanguageServiceCache | undefined = getRollupCache(rollupShareObject, projectConfig, cacheKey); 374 375 let service: ts.LanguageService | undefined = cache?.service; 376 const currentHash: string | undefined = rollupShareObject?.projectConfig?.pkgJsonFileHash; 377 const currentTargetESVersion: ts.ScriptTarget = compilerOptions.target; 378 const lastHash: string | undefined = cache?.pkgJsonFileHash; 379 const lastTargetESVersion: ts.ScriptTarget | undefined = cache?.targetESVersion; 380 const hashDiffers: boolean | undefined = currentHash && lastHash && currentHash !== lastHash; 381 const shouldRebuildForDepDiffers: boolean | undefined = reuseLanguageServiceForDepChange ? 382 (hashDiffers && !rollupShareObject?.depInfo?.enableIncre) : hashDiffers; 383 const targetESVersionDiffers: boolean | undefined = lastTargetESVersion && currentTargetESVersion && lastTargetESVersion !== currentTargetESVersion; 384 const tsImportSendableDiff: boolean = (cache?.preTsImportSendable === undefined && !tsImportSendable) ? 385 false : 386 cache?.preTsImportSendable !== tsImportSendable; 387 const shouldRebuild: boolean | undefined = shouldRebuildForDepDiffers || targetESVersionDiffers || tsImportSendableDiff; 388 if (reuseLanguageServiceForDepChange && hashDiffers && rollupShareObject?.depInfo?.enableIncre) { 389 needReCheckForChangedDepUsers = true; 390 } 391 392 if (!service || shouldRebuild) { 393 rebuiuldProgram(targetESVersionDiffers, tsImportSendableDiff); 394 service = ts.createLanguageService(servicesHost, ts.createDocumentRegistry()); 395 } else { 396 // Found language service from cache, update root files 397 const updateRootFileNames = [...rootFileNames, ...readDeaclareFiles()]; 398 service.updateRootFiles(updateRootFileNames); 399 } 400 401 const newCache: LanguageServiceCache = { 402 service: service, 403 pkgJsonFileHash: currentHash, 404 targetESVersion: currentTargetESVersion, 405 preTsImportSendable: tsImportSendable 406 }; 407 setRollupCache(rollupShareObject, projectConfig, cacheKey, newCache); 408 return service; 409} 410 411function rebuiuldProgram(targetESVersionDiffers: boolean | undefined, tsImportSendableDiff: boolean): void { 412 if (targetESVersionDiffers) { 413 // If the targetESVersion is changed, we need to delete the build info cahce files 414 deleteBuildInfoCache(compilerOptions.tsBuildInfoFile); 415 targetESVersionChanged = true; 416 } else if (tsImportSendableDiff) { 417 // When tsImportSendable is changed, we need to delete the build info cahce files 418 deleteBuildInfoCache(compilerOptions.tsBuildInfoFile); 419 } 420} 421 422function deleteBuildInfoCache(tsBuildInfoFilePath: string): void { 423 // The file name of tsBuildInfoLinterFile is '.tsbuildinfo.linter', so we need to add '.linter' after tsBuildInfoFilePath 424 const tsBuildInfoLinterFilePath: string = tsBuildInfoFilePath + '.linter'; 425 deleteFile(tsBuildInfoFilePath); 426 deleteFile(tsBuildInfoLinterFilePath); 427} 428 429function deleteFile(filePath: string): void { 430 if (fs.existsSync(filePath)) { 431 fs.unlinkSync(filePath); 432 } 433} 434 435interface CacheFileName { 436 mtimeMs: number, 437 children: string[], 438 parent: string[], 439 error: boolean, 440 errorCodes?: number[] 441} 442interface NeedUpdateFlag { 443 flag: boolean; 444} 445interface CheckerResult { 446 count: number 447} 448 449interface WarnCheckerResult { 450 count: number 451} 452 453interface WholeCache { 454 runtimeOS: string, 455 sdkInfo: string, 456 fileList: Cache 457} 458type Cache = Record<string, CacheFileName>; 459export let cache: Cache = {}; 460export const hotReloadSupportFiles: Set<string> = new Set(); 461export const shouldResolvedFiles: Set<string> = new Set(); 462export const appComponentCollection: Map<string, Set<string>> = new Map(); 463const allResolvedModules: Set<string> = new Set(); 464// all files of tsc and rollup for obfuscation scanning. 465export const allSourceFilePaths: Set<string> = new Set(); 466// Used to collect file paths that have not been converted toUnixPath. 467export const allModuleIds: Set<string> = new Set(); 468export let props: string[] = []; 469 470export let fastBuildLogger = null; 471 472export const checkerResult: CheckerResult = { count: 0 }; 473export const warnCheckerResult: WarnCheckerResult = { count: 0 }; 474export let languageService: ts.LanguageService = null; 475let tsImportSendable: boolean = false; 476export function serviceChecker(rootFileNames: string[], newLogger: Object = null, resolveModulePaths: string[] = null, 477 compilationTime: CompilationTimeStatistics = null, rollupShareObject?: Object): void { 478 fastBuildLogger = newLogger; 479 let cacheFile: string = null; 480 tsImportSendable = rollupShareObject?.projectConfig.tsImportSendable; 481 if (projectConfig.xtsMode || process.env.watchMode === 'true') { 482 if (projectConfig.hotReload) { 483 rootFileNames.forEach(fileName => { 484 hotReloadSupportFiles.add(fileName); 485 }); 486 } 487 languageService = createLanguageService(rootFileNames, resolveModulePaths, compilationTime); 488 props = languageService.getProps(); 489 } else { 490 cacheFile = path.resolve(projectConfig.cachePath, '../.ts_checker_cache'); 491 const [isJsonObject, cacheJsonObject]: [boolean, WholeCache | undefined] = isJsonString(cacheFile); 492 const wholeCache: WholeCache = isJsonObject ? cacheJsonObject : { 'runtimeOS': projectConfig.runtimeOS, 'sdkInfo': projectConfig.sdkInfo, 'fileList': {} }; 493 if (wholeCache.runtimeOS === projectConfig.runtimeOS && wholeCache.sdkInfo === projectConfig.sdkInfo) { 494 cache = wholeCache.fileList; 495 } else { 496 cache = {}; 497 } 498 languageService = createLanguageService(rootFileNames, resolveModulePaths, compilationTime, rollupShareObject); 499 } 500 501 const timePrinterInstance = ts.ArkTSLinterTimePrinter.getInstance(); 502 timePrinterInstance.setArkTSTimePrintSwitch(false); 503 timePrinterInstance.appendTime(ts.TimePhase.START); 504 startTimeStatisticsLocation(compilationTime ? compilationTime.createProgramTime : undefined); 505 506 globalProgram.builderProgram = languageService.getBuilderProgram(/*withLinterProgram*/ true); 507 globalProgram.program = globalProgram.builderProgram.getProgram(); 508 props = languageService.getProps(); 509 timePrinterInstance.appendTime(ts.TimePhase.GET_PROGRAM); 510 stopTimeStatisticsLocation(compilationTime ? compilationTime.createProgramTime : undefined); 511 512 collectAllFiles(globalProgram.program); 513 collectFileToIgnoreDiagnostics(rootFileNames); 514 startTimeStatisticsLocation(compilationTime ? compilationTime.runArkTSLinterTime : undefined); 515 runArkTSLinter(); 516 stopTimeStatisticsLocation(compilationTime ? compilationTime.runArkTSLinterTime : undefined); 517 518 if (process.env.watchMode !== 'true') { 519 processBuildHap(cacheFile, rootFileNames, compilationTime, rollupShareObject); 520 } 521} 522// collect the compiled files of tsc and rollup for obfuscation scanning. 523export function collectAllFiles(program?: ts.Program, rollupFileList?: IterableIterator<string>, 524 rollupObject?: Object): void { 525 if (program) { 526 collectTscFiles(program); 527 return; 528 } 529 mergeRollUpFiles(rollupFileList, rollupObject); 530} 531 532function isJsonString(cacheFile: string): [boolean, WholeCache | undefined] { 533 if (fs.existsSync(cacheFile)) { 534 try { 535 return [true, JSON.parse(fs.readFileSync(cacheFile).toString())]; 536 } catch(e) { 537 return [false, undefined]; 538 } 539 } else { 540 return [false, undefined]; 541 } 542} 543 544export function collectTscFiles(program: ts.Program): void { 545 const programAllFiles: readonly ts.SourceFile[] = program.getSourceFiles(); 546 let projectRootPath: string = projectConfig.projectRootPath; 547 if (!projectRootPath) { 548 return; 549 } 550 projectRootPath = toUnixPath(projectRootPath); 551 const isMacOrWin = isWindows() || isMac(); 552 programAllFiles.forEach(sourceFile => { 553 const fileName = toUnixPath(sourceFile.fileName); 554 if (!fileName.startsWith(projectRootPath)) { 555 return; 556 } 557 allSourceFilePaths.add(fileName); 558 allModuleIds.add(sourceFile.fileName); 559 // For the windos and mac platform, the file path in filesBuildInfo is in lowercase, 560 // while fileName of sourceFile is the original path (including uppercase). 561 if (filesBuildInfo.size > 0 && 562 Reflect.get(sourceFile, 'version') !== filesBuildInfo.get(isMacOrWin ? tryToLowerCasePath(fileName) : fileName)) { 563 allResolvedModules.add(fileName); 564 } 565 }); 566} 567 568export function mergeRollUpFiles(rollupFileList: IterableIterator<string>, rollupObject: Object) { 569 for (const moduleId of rollupFileList) { 570 if (fs.existsSync(moduleId)) { 571 allSourceFilePaths.add(toUnixPath(moduleId)); 572 allModuleIds.add(moduleId); 573 addLocalPackageSet(moduleId, rollupObject); 574 } 575 } 576} 577 578// collect the modulename or pkgname of all local modules. 579export function addLocalPackageSet(moduleId: string, rollupObject: Object): void { 580 const moduleInfo: Object = rollupObject.getModuleInfo(moduleId); 581 const metaInfo: Object = moduleInfo.meta; 582 if (metaInfo.isLocalDependency) { 583 if (projectConfig.useNormalizedOHMUrl && metaInfo.pkgName) { 584 localPackageSet.add(metaInfo.pkgName); 585 } 586 if (!projectConfig.useNormalizedOHMUrl && metaInfo.moduleName) { 587 localPackageSet.add(metaInfo.moduleName); 588 } 589 } 590} 591 592export function emitBuildInfo(): void { 593 globalProgram.builderProgram.emitBuildInfo(buildInfoWriteFile); 594} 595 596function processBuildHap(cacheFile: string, rootFileNames: string[], compilationTime: CompilationTimeStatistics, 597 rollupShareObject: Object): void { 598 startTimeStatisticsLocation(compilationTime ? compilationTime.diagnosticTime : undefined); 599 const allDiagnostics: ts.Diagnostic[] = globalProgram.builderProgram 600 .getSyntacticDiagnostics() 601 .concat(globalProgram.builderProgram.getSemanticDiagnostics()); 602 stopTimeStatisticsLocation(compilationTime ? compilationTime.diagnosticTime : undefined); 603 emitBuildInfo(); 604 allDiagnostics.forEach((diagnostic: ts.Diagnostic) => { 605 printDiagnostic(diagnostic); 606 }); 607 if (!projectConfig.xtsMode) { 608 fse.ensureDirSync(projectConfig.cachePath); 609 fs.writeFileSync(cacheFile, JSON.stringify({ 610 'runtimeOS': projectConfig.runtimeOS, 611 'sdkInfo': projectConfig.sdkInfo, 612 'fileList': cache 613 }, null, 2)); 614 } 615 if (projectConfig.compileHar || projectConfig.compileShared) { 616 let emit: string | undefined = undefined; 617 let writeFile = (fileName: string, text: string, writeByteOrderMark: boolean): void => { 618 emit = text; 619 }; 620 [...allResolvedModules, ...rootFileNames].forEach(moduleFile => { 621 if (!(moduleFile.match(new RegExp(projectConfig.packageDir)) && projectConfig.compileHar)) { 622 try { 623 if ((/\.d\.e?ts$/).test(moduleFile)) { 624 generateSourceFilesInHar(moduleFile, fs.readFileSync(moduleFile, 'utf-8'), path.extname(moduleFile), 625 projectConfig, projectConfig.modulePathMap); 626 } else if ((/\.e?ts$/).test(moduleFile)) { 627 emit = undefined; 628 let sourcefile = globalProgram.program.getSourceFile(moduleFile); 629 if (sourcefile) { 630 globalProgram.program.emit(sourcefile, writeFile, undefined, true, undefined, true); 631 } 632 if (emit) { 633 generateSourceFilesInHar(moduleFile, emit, '.d' + path.extname(moduleFile), projectConfig, projectConfig.modulePathMap); 634 } 635 } 636 } catch (err) { } 637 } 638 }); 639 printDeclarationDiagnostics(); 640 } 641} 642 643function printDeclarationDiagnostics(): void { 644 globalProgram.builderProgram.getDeclarationDiagnostics().forEach((diagnostic: ts.Diagnostic) => { 645 printDiagnostic(diagnostic); 646 }); 647} 648 649function containFormError(message: string): boolean { 650 if (/can't support form application./.test(message)) { 651 return true; 652 } 653 return false; 654} 655 656let fileToIgnoreDiagnostics: Set<string> | undefined = undefined; 657 658function collectFileToThrowDiagnostics(file: string, fileToThrowDiagnostics: Set<string>): void { 659 const normalizedFilePath: string = path.resolve(file); 660 const unixFilePath: string = toUnixPath(file); 661 if (fileToThrowDiagnostics.has(unixFilePath)) { 662 return; 663 } 664 665 fileToThrowDiagnostics.add(unixFilePath); 666 // Although the cache object filters JavaScript files when collecting dependency relationships, we still include the 667 // filtering of JavaScript files here to avoid potential omissions. 668 if ((/\.(c|m)?js$/).test(file) || 669 !cache[normalizedFilePath] || cache[normalizedFilePath].children.length === 0) { 670 return; 671 } 672 cache[normalizedFilePath].children.forEach(file => { 673 collectFileToThrowDiagnostics(file, fileToThrowDiagnostics); 674 }); 675} 676 677export function collectFileToIgnoreDiagnostics(rootFileNames: string[]): void { 678 if (getArkTSLinterMode() === ArkTSLinterMode.NOT_USE) { 679 return; 680 } 681 682 // In watch mode, the `beforeBuild` phase will clear the parent and children fields in the cache. For files that have 683 // not been modified, the information needs to be restored using the `resolvedModuleNames` variable. 684 if (process.env.watchMode === 'true') { 685 for (let [file, resolvedModules] of resolvedModulesCache) { 686 createOrUpdateCache(resolvedModules, file); 687 } 688 } 689 690 // With arkts linter enabled, `allowJs` option is set to true, resulting JavaScript files themselves and 691 // JavaScript-referenced files are included in the tsc program and checking process, 692 // potentially introducing new errors. For instance, in scenarios where an ets file imports js file imports ts file, 693 // it’s necessary to filter out errors from ts files. 694 let fileToThrowDiagnostics: Set<string> = new Set<string>(); 695 rootFileNames.forEach(file => { 696 if (!(/\.(c|m)?js$/).test(file)) { 697 collectFileToThrowDiagnostics(file, fileToThrowDiagnostics); 698 } 699 }); 700 701 let resolvedTypeReferenceDirectivesFiles: Set<string> = new Set<string>(); 702 globalProgram.program.getResolvedTypeReferenceDirectives().forEach( 703 (elem: ts.ResolvedTypeReferenceDirective | undefined) => { 704 elem && elem.resolvedFileName && resolvedTypeReferenceDirectivesFiles.add(elem.resolvedFileName); 705 }); 706 707 fileToIgnoreDiagnostics = new Set<string>(); 708 globalProgram.program.getSourceFiles().forEach(sourceFile => { 709 // Previous projects had js libraries that were available through SDK, so need to filter js-file in SDK, 710 // like: hypium library 711 sourceFile.fileName && 712 (!isInSDK(sourceFile.fileName) || (/\.(c|m)?js$/).test(sourceFile.fileName)) && 713 !resolvedTypeReferenceDirectivesFiles.has(sourceFile.fileName) && 714 fileToIgnoreDiagnostics.add(toUnixPath(sourceFile.fileName)); 715 }); 716 717 fileToThrowDiagnostics.forEach(file => { 718 fileToIgnoreDiagnostics.delete(file); 719 }); 720} 721 722export function printDiagnostic(diagnostic: ts.Diagnostic): void { 723 if (projectConfig.ignoreWarning) { 724 return; 725 } 726 727 if (fileToIgnoreDiagnostics && diagnostic.file && diagnostic.file.fileName && 728 fileToIgnoreDiagnostics.has(toUnixPath(diagnostic.file.fileName))) { 729 return; 730 } 731 732 const message: string = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); 733 if (validateError(message)) { 734 if (process.env.watchMode !== 'true' && !projectConfig.xtsMode) { 735 updateErrorFileCache(diagnostic); 736 } 737 738 if (containFormError(message) && !isCardFile(diagnostic.file.fileName)) { 739 return; 740 } 741 742 const logPrefix: string = diagnostic.category === ts.DiagnosticCategory.Error ? 'ERROR' : 'WARN'; 743 const etsCheckerLogger = fastBuildLogger || logger; 744 let logMessage: string; 745 if (logPrefix === 'ERROR') { 746 checkerResult.count += 1; 747 } else { 748 warnCheckerResult.count += 1; 749 } 750 if (diagnostic.file) { 751 const { line, character }: ts.LineAndCharacter = 752 diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!); 753 logMessage = `ArkTS:${logPrefix} File: ${diagnostic.file.fileName}:${line + 1}:${character + 1}\n ${message}\n`; 754 } else { 755 logMessage = `ArkTS:${logPrefix}: ${message}`; 756 } 757 758 if (diagnostic.category === ts.DiagnosticCategory.Error) { 759 etsCheckerLogger.error('\u001b[31m' + logMessage); 760 } else { 761 etsCheckerLogger.warn('\u001b[33m' + logMessage); 762 } 763 } 764} 765 766function validateError(message: string): boolean { 767 const propInfoReg: RegExp = /Cannot find name\s*'(\$?\$?[_a-zA-Z0-9]+)'/; 768 const stateInfoReg: RegExp = /Property\s*'(\$?[_a-zA-Z0-9]+)' does not exist on type/; 769 if (matchMessage(message, props, propInfoReg) || 770 matchMessage(message, props, stateInfoReg)) { 771 return false; 772 } 773 return true; 774} 775function matchMessage(message: string, nameArr: any, reg: RegExp): boolean { 776 if (reg.test(message)) { 777 const match: string[] = message.match(reg); 778 if (match[1] && nameArr.includes(match[1])) { 779 return true; 780 } 781 } 782 return false; 783} 784 785function updateErrorFileCache(diagnostic: ts.Diagnostic): void { 786 if (!diagnostic.file) { 787 return; 788 } 789 790 let cacheInfo: CacheFileName = cache[path.resolve(diagnostic.file.fileName)]; 791 if (cacheInfo) { 792 cacheInfo.error = true; 793 if (!cacheInfo.errorCodes) { 794 cacheInfo.errorCodes = []; 795 } 796 cacheInfo.errorCodes.includes(diagnostic.code) || cacheInfo.errorCodes.push(diagnostic.code); 797 } 798} 799 800function filterInput(rootFileNames: string[]): string[] { 801 return rootFileNames.filter((file: string) => { 802 const needUpdate: NeedUpdateFlag = { flag: false }; 803 const alreadyCheckedFiles: Set<string> = new Set(); 804 checkNeedUpdateFiles(path.resolve(file), needUpdate, alreadyCheckedFiles); 805 if (!needUpdate.flag) { 806 storedFileInfo.changeFiles.push(path.resolve(file)); 807 } 808 return needUpdate.flag; 809 }); 810} 811 812function checkNeedUpdateFiles(file: string, needUpdate: NeedUpdateFlag, alreadyCheckedFiles: Set<string>): void { 813 if (alreadyCheckedFiles.has(file)) { 814 return; 815 } else { 816 alreadyCheckedFiles.add(file); 817 } 818 819 if (needUpdate.flag) { 820 return; 821 } 822 823 const value: CacheFileName = cache[file]; 824 const mtimeMs: number = fs.statSync(file).mtimeMs; 825 if (value) { 826 if (value.error || value.mtimeMs !== mtimeMs) { 827 needUpdate.flag = true; 828 return; 829 } 830 for (let i = 0; i < value.children.length; ++i) { 831 if (fs.existsSync(value.children[i])) { 832 checkNeedUpdateFiles(value.children[i], needUpdate, alreadyCheckedFiles); 833 } else { 834 needUpdate.flag = true; 835 } 836 } 837 } else { 838 cache[file] = { mtimeMs, children: [], parent: [], error: false }; 839 needUpdate.flag = true; 840 } 841} 842 843const fileExistsCache: Map<string, boolean> = new Map<string, boolean>(); 844const dirExistsCache: Map<string, boolean> = new Map<string, boolean>(); 845const moduleResolutionHost: ts.ModuleResolutionHost = { 846 fileExists: (fileName: string): boolean => { 847 let exists = fileExistsCache.get(fileName); 848 if (exists === undefined) { 849 exists = ts.sys.fileExists(fileName); 850 fileExistsCache.set(fileName, exists); 851 } 852 return exists; 853 }, 854 directoryExists: (directoryName: string): boolean => { 855 let exists = dirExistsCache.get(directoryName); 856 if (exists === undefined) { 857 exists = ts.sys.directoryExists(directoryName); 858 dirExistsCache.set(directoryName, exists); 859 } 860 return exists; 861 }, 862 readFile(fileName: string): string | undefined { 863 return ts.sys.readFile(fileName); 864 }, 865 realpath(path: string): string { 866 return ts.sys.realpath(path); 867 }, 868 trace(s: string): void { 869 console.info(s); 870 } 871}; 872 873//This is only for test 874export const moduleResolutionHostTest = moduleResolutionHost; 875 876export function resolveTypeReferenceDirectives(typeDirectiveNames: string[] | ts.FileReference[]): ts.ResolvedTypeReferenceDirective[] { 877 if (typeDirectiveNames.length === 0) { 878 return []; 879 } 880 881 const resolvedTypeReferenceCache: ts.ResolvedTypeReferenceDirective[] = []; 882 const cache: Map<string, ts.ResolvedTypeReferenceDirective> = new Map<string, ts.ResolvedTypeReferenceDirective>(); 883 const containingFile: string = path.join(projectConfig.modulePath, 'build-profile.json5'); 884 885 for (const entry of typeDirectiveNames) { 886 const typeName = isString(entry) ? entry : entry.fileName.toLowerCase(); 887 if (!cache.has(typeName)) { 888 const resolvedFile = ts.resolveTypeReferenceDirective(typeName, containingFile, compilerOptions, moduleResolutionHost); 889 if (!resolvedFile || !resolvedFile.resolvedTypeReferenceDirective) { 890 logger.error('\u001b[31m', `ArkTS:Cannot find type definition file for: ${typeName}\n`); 891 } 892 const result: ts.ResolvedTypeReferenceDirective = resolvedFile.resolvedTypeReferenceDirective; 893 cache.set(typeName, result); 894 resolvedTypeReferenceCache.push(result); 895 } 896 } 897 return resolvedTypeReferenceCache; 898} 899 900// resolvedModulesCache records the files and their dependencies of program. 901export const resolvedModulesCache: Map<string, ts.ResolvedModuleFull[]> = new Map(); 902 903export function resolveModuleNames(moduleNames: string[], containingFile: string): ts.ResolvedModuleFull[] { 904 startTimeStatisticsLocation(resolveModuleNamesTime); 905 const resolvedModules: ts.ResolvedModuleFull[] = []; 906 const cacheFileContent: ts.ResolvedModuleFull[] = resolvedModulesCache.get(path.resolve(containingFile)); 907 if (![...shouldResolvedFiles].length || shouldResolvedFiles.has(path.resolve(containingFile)) || 908 !(cacheFileContent && cacheFileContent.length === moduleNames.length)) { 909 for (const moduleName of moduleNames) { 910 const result = ts.resolveModuleName(moduleName, containingFile, compilerOptions, moduleResolutionHost); 911 if (result.resolvedModule) { 912 if (result.resolvedModule.resolvedFileName && 913 path.extname(result.resolvedModule.resolvedFileName) === EXTNAME_JS) { 914 const resultDETSPath: string = 915 result.resolvedModule.resolvedFileName.replace(EXTNAME_JS, EXTNAME_D_ETS); 916 if (ts.sys.fileExists(resultDETSPath)) { 917 resolvedModules.push(getResolveModule(resultDETSPath, EXTNAME_D_ETS)); 918 } else { 919 resolvedModules.push(result.resolvedModule); 920 } 921 } else { 922 resolvedModules.push(result.resolvedModule); 923 } 924 } else if (new RegExp(`^@(${sdkConfigPrefix})\\.`, 'i').test(moduleName.trim())) { 925 let apiFileExist: boolean = false; 926 for (let i = 0; i < sdkConfigs.length; i++) { 927 const sdkConfig = sdkConfigs[i]; 928 const resolveModuleInfo: ResolveModuleInfo = getRealModulePath(sdkConfig.apiPath, moduleName, ['.d.ts', '.d.ets']); 929 const modulePath: string = resolveModuleInfo.modulePath; 930 const isDETS: boolean = resolveModuleInfo.isEts; 931 if (systemModules.includes(moduleName + (isDETS ? '.d.ets' : '.d.ts')) && ts.sys.fileExists(modulePath)) { 932 resolvedModules.push(getResolveModule(modulePath, isDETS ? '.d.ets' : '.d.ts')); 933 apiFileExist = true; 934 break; 935 } 936 } 937 if (!apiFileExist) { 938 resolvedModules.push(null); 939 } 940 } else if (/\.ets$/.test(moduleName) && !/\.d\.ets$/.test(moduleName)) { 941 const modulePath: string = path.resolve(path.dirname(containingFile), moduleName); 942 if (ts.sys.fileExists(modulePath)) { 943 resolvedModules.push(getResolveModule(modulePath, '.ets')); 944 } else { 945 resolvedModules.push(null); 946 } 947 } else if (/\.ts$/.test(moduleName)) { 948 const modulePath: string = path.resolve(path.dirname(containingFile), moduleName); 949 if (ts.sys.fileExists(modulePath)) { 950 resolvedModules.push(getResolveModule(modulePath, '.ts')); 951 } else { 952 resolvedModules.push(null); 953 } 954 } else { 955 const modulePath: string = path.resolve(__dirname, '../../../api', moduleName + '.d.ts'); 956 const systemDETSModulePath: string = path.resolve(__dirname, '../../../api', moduleName + '.d.ets'); 957 const kitModulePath: string = path.resolve(__dirname, '../../../kits', moduleName + '.d.ts'); 958 const kitSystemDETSModulePath: string = path.resolve(__dirname, '../../../kits', moduleName + '.d.ets'); 959 const suffix: string = /\.js$/.test(moduleName) ? '' : '.js'; 960 const jsModulePath: string = path.resolve(__dirname, '../node_modules', moduleName + suffix); 961 const fileModulePath: string = 962 path.resolve(__dirname, '../node_modules', moduleName + '/index.js'); 963 const DETSModulePath: string = path.resolve(path.dirname(containingFile), 964 /\.d\.ets$/.test(moduleName) ? moduleName : moduleName + EXTNAME_D_ETS); 965 if (ts.sys.fileExists(modulePath)) { 966 resolvedModules.push(getResolveModule(modulePath, '.d.ts')); 967 } else if (ts.sys.fileExists(systemDETSModulePath)) { 968 resolvedModules.push(getResolveModule(systemDETSModulePath, '.d.ets')); 969 } else if (ts.sys.fileExists(kitModulePath)) { 970 resolvedModules.push(getResolveModule(kitModulePath, '.d.ts')); 971 } else if (ts.sys.fileExists(kitSystemDETSModulePath)) { 972 resolvedModules.push(getResolveModule(kitSystemDETSModulePath, '.d.ets')); 973 } else if (ts.sys.fileExists(jsModulePath)) { 974 resolvedModules.push(getResolveModule(jsModulePath, '.js')); 975 } else if (ts.sys.fileExists(fileModulePath)) { 976 resolvedModules.push(getResolveModule(fileModulePath, '.js')); 977 } else if (ts.sys.fileExists(DETSModulePath)) { 978 resolvedModules.push(getResolveModule(DETSModulePath, '.d.ets')); 979 } else { 980 const srcIndex: number = projectConfig.projectPath.indexOf('src' + path.sep + 'main'); 981 let DETSModulePathFromModule: string; 982 if (srcIndex > 0) { 983 DETSModulePathFromModule = path.resolve( 984 projectConfig.projectPath.substring(0, srcIndex), moduleName + path.sep + 'index' + EXTNAME_D_ETS); 985 if (DETSModulePathFromModule && ts.sys.fileExists(DETSModulePathFromModule)) { 986 resolvedModules.push(getResolveModule(DETSModulePathFromModule, '.d.ets')); 987 } else { 988 resolvedModules.push(null); 989 } 990 } else { 991 resolvedModules.push(null); 992 } 993 } 994 } 995 if (projectConfig.hotReload && resolvedModules.length && 996 resolvedModules[resolvedModules.length - 1]) { 997 hotReloadSupportFiles.add(path.resolve(resolvedModules[resolvedModules.length - 1].resolvedFileName)); 998 } 999 if (collectShouldPackedFiles(resolvedModules)) { 1000 allResolvedModules.add(resolvedModules[resolvedModules.length - 1].resolvedFileName); 1001 } 1002 } 1003 if (!projectConfig.xtsMode) { 1004 createOrUpdateCache(resolvedModules, path.resolve(containingFile)); 1005 } 1006 resolvedModulesCache.set(path.resolve(containingFile), resolvedModules); 1007 stopTimeStatisticsLocation(resolveModuleNamesTime); 1008 return resolvedModules; 1009 } 1010 stopTimeStatisticsLocation(resolveModuleNamesTime); 1011 return resolvedModulesCache.get(path.resolve(containingFile)); 1012} 1013 1014export interface ResolveModuleInfo { 1015 modulePath: string; 1016 isEts: boolean; 1017} 1018 1019function collectShouldPackedFiles(resolvedModules: ts.ResolvedModuleFull[]): boolean | RegExpMatchArray { 1020 return (projectConfig.compileHar || projectConfig.compileShared) && resolvedModules[resolvedModules.length - 1] && 1021 resolvedModules[resolvedModules.length - 1].resolvedFileName && 1022 (path.resolve(resolvedModules[resolvedModules.length - 1].resolvedFileName).match(/(\.[^d]|[^\.]d|[^\.][^d])\.e?ts$/) || 1023 path.resolve(resolvedModules[resolvedModules.length - 1].resolvedFileName).match(/\.d\.e?ts$/) && 1024 path.resolve(resolvedModules[resolvedModules.length - 1].resolvedFileName).match( 1025 new RegExp('\\' + path.sep + 'src' + '\\' + path.sep + 'main' + '\\' + path.sep))); 1026} 1027 1028function createOrUpdateCache(resolvedModules: ts.ResolvedModuleFull[], containingFile: string): void { 1029 const children: string[] = []; 1030 const error: boolean = false; 1031 resolvedModules.forEach(moduleObj => { 1032 if (moduleObj && moduleObj.resolvedFileName && /\.(ets|ts)$/.test(moduleObj.resolvedFileName)) { 1033 const file: string = path.resolve(moduleObj.resolvedFileName); 1034 const mtimeMs: number = fs.statSync(file).mtimeMs; 1035 children.push(file); 1036 const value: CacheFileName = cache[file]; 1037 if (value) { 1038 value.mtimeMs = mtimeMs; 1039 value.error = error; 1040 value.parent = value.parent || []; 1041 value.parent.push(path.resolve(containingFile)); 1042 value.parent = [...new Set(value.parent)]; 1043 } else { 1044 cache[file] = { mtimeMs, children: [], parent: [containingFile], error }; 1045 } 1046 } 1047 }); 1048 cache[path.resolve(containingFile)] = { 1049 mtimeMs: fs.statSync(containingFile).mtimeMs, children, 1050 parent: cache[path.resolve(containingFile)] && cache[path.resolve(containingFile)].parent ? 1051 cache[path.resolve(containingFile)].parent : [], error 1052 }; 1053} 1054 1055export function createWatchCompilerHost(rootFileNames: string[], 1056 reportDiagnostic: ts.DiagnosticReporter, delayPrintLogCount: Function, resetErrorCount: Function, 1057 isPipe: boolean = false, resolveModulePaths: string[] = null): ts.WatchCompilerHostOfFilesAndCompilerOptions<ts.BuilderProgram> { 1058 if (projectConfig.hotReload) { 1059 rootFileNames.forEach(fileName => { 1060 hotReloadSupportFiles.add(fileName); 1061 }); 1062 } 1063 if (!(isPipe && process.env.compileTool === 'rollup')) { 1064 setCompilerOptions(resolveModulePaths); 1065 } 1066 // Change the buildInfo file path, or it will cover the buildInfo file created before. 1067 const buildInfoPath: string = path.resolve(projectConfig.cachePath, '..', WATCH_COMPILER_BUILD_INFO_SUFFIX); 1068 const watchCompilerOptions = {...compilerOptions, tsBuildInfoFile: buildInfoPath}; 1069 const createProgram = ts.createSemanticDiagnosticsBuilderProgram; 1070 const host = ts.createWatchCompilerHost( 1071 [...rootFileNames, ...readDeaclareFiles()], watchCompilerOptions, 1072 ts.sys, createProgram, reportDiagnostic, 1073 (diagnostic: ts.Diagnostic) => { 1074 if ([6031, 6032].includes(diagnostic.code)) { 1075 if (!isPipe) { 1076 process.env.watchTs = 'start'; 1077 resetErrorCount(); 1078 } 1079 } 1080 // End of compilation in watch mode flag. 1081 if ([6193, 6194].includes(diagnostic.code)) { 1082 if (!isPipe) { 1083 process.env.watchTs = 'end'; 1084 if (fastBuildLogger) { 1085 fastBuildLogger.debug(TS_WATCH_END_MSG); 1086 tsWatchEmitter.emit(TS_WATCH_END_MSG); 1087 } 1088 } 1089 delayPrintLogCount(); 1090 } 1091 }); 1092 host.readFile = (fileName: string) => { 1093 if (!fs.existsSync(fileName)) { 1094 return undefined; 1095 } 1096 if (/(?<!\.d)\.(ets|ts)$/.test(fileName)) { 1097 let content: string = processContent(fs.readFileSync(fileName).toString(), fileName); 1098 const extendFunctionInfo: extendInfo[] = []; 1099 content = instanceInsteadThis(content, fileName, extendFunctionInfo, props); 1100 return content; 1101 } 1102 return fs.readFileSync(fileName).toString(); 1103 }; 1104 host.resolveModuleNames = resolveModuleNames; 1105 host.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives; 1106 return host; 1107} 1108 1109export function watchChecker(rootFileNames: string[], newLogger: any = null, resolveModulePaths: string[] = null): void { 1110 fastBuildLogger = newLogger; 1111 globalProgram.watchProgram = ts.createWatchProgram( 1112 createWatchCompilerHost(rootFileNames, printDiagnostic, () => { }, () => { }, false, resolveModulePaths)); 1113} 1114 1115export function instanceInsteadThis(content: string, fileName: string, extendFunctionInfo: extendInfo[], 1116 props: string[]): string { 1117 checkUISyntax(content, fileName, extendFunctionInfo, props); 1118 extendFunctionInfo.reverse().forEach((item) => { 1119 const subStr: string = content.substring(item.start, item.end); 1120 const insert: string = subStr.replace(/(\s)\$(\.)/g, (origin, item1, item2) => { 1121 return item1 + item.compName + 'Instance' + item2; 1122 }); 1123 content = content.slice(0, item.start) + insert + content.slice(item.end); 1124 }); 1125 return content; 1126} 1127 1128function getResolveModule(modulePath: string, type): ts.ResolvedModuleFull { 1129 return { 1130 resolvedFileName: modulePath, 1131 isExternalLibraryImport: false, 1132 extension: type 1133 }; 1134} 1135 1136export const dollarCollection: Set<string> = new Set(); 1137export const extendCollection: Set<string> = new Set(); 1138export const importModuleCollection: Set<string> = new Set(); 1139 1140function checkUISyntax(source: string, fileName: string, extendFunctionInfo: extendInfo[], props: string[]): void { 1141 if (/\.ets$/.test(fileName)) { 1142 if (process.env.compileMode === 'moduleJson' || 1143 path.resolve(fileName) !== path.resolve(projectConfig.projectPath, 'app.ets')) { 1144 const sourceFile: ts.SourceFile = ts.createSourceFile(fileName, source, 1145 ts.ScriptTarget.Latest, true, ts.ScriptKind.ETS, compilerOptions); 1146 collectComponents(sourceFile); 1147 collectionCustomizeStyles(sourceFile); 1148 parseAllNode(sourceFile, sourceFile, extendFunctionInfo); 1149 props.push(...dollarCollection, ...extendCollection); 1150 } 1151 } 1152} 1153 1154function collectionCustomizeStyles(node: ts.Node): void { 1155 if ((ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) && 1156 (isUIDecorator(node, COMPONENT_STYLES_DECORATOR) || isUIDecorator(node, COMPONENT_EXTEND_DECORATOR)) && 1157 node.name && ts.isIdentifier(node.name)) { 1158 BUILDIN_STYLE_NAMES.add(node.name.escapedText.toString()); 1159 } 1160 if (ts.isSourceFile(node)) { 1161 node.statements.forEach((item: ts.Node) => { 1162 return collectionCustomizeStyles(item); 1163 }); 1164 } else if (ts.isStructDeclaration(node)) { 1165 node.members.forEach((item: ts.Node) => { 1166 return collectionCustomizeStyles(item); 1167 }); 1168 } 1169} 1170 1171function isUIDecorator(node: ts.MethodDeclaration | ts.FunctionDeclaration | 1172 ts.StructDeclaration | ts.ClassDeclaration, decortorName: string): boolean { 1173 const decorators: readonly ts.Decorator[] = ts.getAllDecorators(node); 1174 if (decorators && decorators.length) { 1175 for (let i = 0; i < decorators.length; i++) { 1176 const originalDecortor: string = decorators[i].getText().replace(/\(.*\)$/, '').trim(); 1177 if (originalDecortor === decortorName) { 1178 return true; 1179 } else { 1180 return false; 1181 } 1182 } 1183 } 1184 return false; 1185} 1186function collectComponents(node: ts.SourceFile): void { 1187 // @ts-ignore 1188 if (process.env.watchMode !== 'true' && node.identifiers && node.identifiers.size) { 1189 // @ts-ignore 1190 for (const key of node.identifiers.keys()) { 1191 if (JS_BIND_COMPONENTS.has(key)) { 1192 appComponentCollection.get(path.join(node.fileName)).add(key); 1193 } 1194 } 1195 } 1196} 1197 1198function parseAllNode(node: ts.Node, sourceFileNode: ts.SourceFile, extendFunctionInfo: extendInfo[]): void { 1199 if (ts.isStructDeclaration(node)) { 1200 if (node.members) { 1201 node.members.forEach(item => { 1202 if (ts.isPropertyDeclaration(item) && ts.isIdentifier(item.name)) { 1203 const propertyName: string = item.name.getText(); 1204 const decorators: readonly ts.Decorator[] = ts.getAllDecorators(item); 1205 if (decorators && decorators.length) { 1206 for (let i = 0; i < decorators.length; i++) { 1207 const decoratorName: string = decorators[i].getText().replace(/\(.*\)$/, '').trim(); 1208 if (INNER_COMPONENT_MEMBER_DECORATORS.has(decoratorName)) { 1209 dollarCollection.add('$' + propertyName); 1210 } 1211 } 1212 } 1213 } 1214 }); 1215 } 1216 } 1217 if (process.env.watchMode !== 'true' && ts.isIfStatement(node)) { 1218 appComponentCollection.get(path.join(sourceFileNode.fileName)).add(COMPONENT_IF); 1219 } 1220 if (ts.isMethodDeclaration(node) && node.name.getText() === COMPONENT_BUILD_FUNCTION || 1221 (ts.isMethodDeclaration(node) || ts.isFunctionDeclaration(node)) && 1222 hasDecorator(node, COMPONENT_BUILDER_DECORATOR)) { 1223 if (node.body && node.body.statements && node.body.statements.length) { 1224 const checkProp: ts.NodeArray<ts.Statement> = node.body.statements; 1225 checkProp.forEach((item, index) => { 1226 traverseBuild(item, index); 1227 }); 1228 } 1229 } 1230 if (ts.isFunctionDeclaration(node) && hasDecorator(node, COMPONENT_EXTEND_DECORATOR)) { 1231 if (node.body && node.body.statements && node.body.statements.length && 1232 !isOriginalExtend(node.body)) { 1233 extendFunctionInfo.push({ 1234 start: node.pos, 1235 end: node.end, 1236 compName: isExtendFunction(node, { decoratorName: '', componentName: '' }) 1237 }); 1238 } 1239 } 1240 node.getChildren().forEach((item: ts.Node) => parseAllNode(item, sourceFileNode, extendFunctionInfo)); 1241} 1242 1243function isForeachAndLzayForEach(node: ts.Node): boolean { 1244 return ts.isCallExpression(node) && node.expression && ts.isIdentifier(node.expression) && 1245 FOREACH_LAZYFOREACH.has(node.expression.escapedText.toString()) && node.arguments && node.arguments[1] && 1246 ts.isArrowFunction(node.arguments[1]) && node.arguments[1].body && ts.isBlock(node.arguments[1].body); 1247} 1248 1249function getComponentName(node: ts.Node): string { 1250 let temp = node.expression; 1251 let name: string; 1252 while (temp) { 1253 if (ts.isIdentifier(temp) && temp.parent && (ts.isCallExpression(temp.parent) || 1254 ts.isEtsComponentExpression(temp.parent))) { 1255 name = temp.escapedText.toString(); 1256 break; 1257 } 1258 temp = temp.expression; 1259 } 1260 return name; 1261} 1262 1263function traverseBuild(node: ts.Node, index: number): void { 1264 if (ts.isExpressionStatement(node)) { 1265 const parentComponentName: string = getComponentName(node); 1266 node = node.expression; 1267 while (node) { 1268 if (ts.isEtsComponentExpression(node) && node.body && ts.isBlock(node.body) && 1269 ts.isIdentifier(node.expression) && !DOLLAR_BLOCK_INTERFACE.has(node.expression.escapedText.toString())) { 1270 node.body.statements.forEach((item: ts.Statement, indexBlock: number) => { 1271 traverseBuild(item, indexBlock); 1272 }); 1273 break; 1274 } else if (isForeachAndLzayForEach(node)) { 1275 node.arguments[1].body.statements.forEach((item: ts.Statement, indexBlock: number) => { 1276 traverseBuild(item, indexBlock); 1277 }); 1278 break; 1279 } else { 1280 loopNodeFindDoubleDollar(node, parentComponentName); 1281 if (ts.isEtsComponentExpression(node) && node.body && ts.isBlock(node.body) && 1282 ts.isIdentifier(node.expression)) { 1283 node.body.statements.forEach((item: ts.Statement, indexBlock: number) => { 1284 traverseBuild(item, indexBlock); 1285 }); 1286 break; 1287 } 1288 } 1289 node = node.expression; 1290 } 1291 } else if (ts.isIfStatement(node)) { 1292 ifInnerDollarAttribute(node); 1293 } 1294} 1295 1296function ifInnerDollarAttribute(node: ts.IfStatement): void { 1297 if (node.thenStatement && ts.isBlock(node.thenStatement) && node.thenStatement.statements) { 1298 node.thenStatement.statements.forEach((item, indexIfBlock) => { 1299 traverseBuild(item, indexIfBlock); 1300 }); 1301 } 1302 if (node.elseStatement) { 1303 elseInnerDollarAttribute(node); 1304 } 1305} 1306 1307function elseInnerDollarAttribute(node: ts.IfStatement): void { 1308 if (ts.isIfStatement(node.elseStatement) && node.elseStatement.thenStatement && ts.isBlock(node.elseStatement.thenStatement)) { 1309 traverseBuild(node.elseStatement, 0); 1310 } else if (ts.isBlock(node.elseStatement) && node.elseStatement.statements) { 1311 node.elseStatement.statements.forEach((item, indexElseBlock) => { 1312 traverseBuild(item, indexElseBlock); 1313 }); 1314 } 1315} 1316 1317function isPropertiesAddDoubleDollar(node: ts.Node): boolean { 1318 if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.arguments && node.arguments.length) { 1319 return true; 1320 } else if (ts.isEtsComponentExpression(node) && ts.isIdentifier(node.expression) && 1321 DOLLAR_BLOCK_INTERFACE.has(node.expression.escapedText.toString())) { 1322 return true; 1323 } else { 1324 return false; 1325 } 1326} 1327function loopNodeFindDoubleDollar(node: ts.Node, parentComponentName: string): void { 1328 if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) { 1329 const argument: ts.NodeArray<ts.Node> = node.arguments; 1330 const propertyName: ts.Identifier | ts.PrivateIdentifier = node.expression.name; 1331 if (isCanAddDoubleDollar(propertyName.getText(), parentComponentName)) { 1332 argument.forEach((item: ts.Node) => { 1333 doubleDollarCollection(item); 1334 }); 1335 } 1336 } else if (isPropertiesAddDoubleDollar(node)) { 1337 node.arguments.forEach((item: ts.Node) => { 1338 if (ts.isObjectLiteralExpression(item) && item.properties && item.properties.length) { 1339 item.properties.forEach((param: ts.Node) => { 1340 if (isObjectPram(param, parentComponentName)) { 1341 doubleDollarCollection(param.initializer); 1342 } 1343 }); 1344 } else if (ts.isPropertyAccessExpression(item) && (handleComponentDollarBlock(node as ts.CallExpression, parentComponentName) || 1345 STYLE_ADD_DOUBLE_DOLLAR.has(node.expression.getText()))) { 1346 doubleDollarCollection(item); 1347 } 1348 }); 1349 } 1350} 1351 1352function handleComponentDollarBlock(node: ts.CallExpression, parentComponentName: string): boolean { 1353 return ts.isCallExpression(node) && ts.isIdentifier(node.expression) && 1354 DOLLAR_BLOCK_INTERFACE.has(parentComponentName) && PROPERTIES_ADD_DOUBLE_DOLLAR.has(parentComponentName) && 1355 PROPERTIES_ADD_DOUBLE_DOLLAR.get(parentComponentName).has(node.expression.escapedText.toString()); 1356} 1357 1358function doubleDollarCollection(item: ts.Node): void { 1359 if (item.getText().startsWith($$)) { 1360 while (item.expression) { 1361 item = item.expression; 1362 } 1363 dollarCollection.add(item.getText()); 1364 } 1365} 1366 1367function isObjectPram(param: ts.Node, parentComponentName: string): boolean { 1368 return ts.isPropertyAssignment(param) && param.name && ts.isIdentifier(param.name) && 1369 param.initializer && PROPERTIES_ADD_DOUBLE_DOLLAR.has(parentComponentName) && 1370 PROPERTIES_ADD_DOUBLE_DOLLAR.get(parentComponentName).has(param.name.getText()); 1371} 1372 1373function isCanAddDoubleDollar(propertyName: string, parentComponentName: string): boolean { 1374 return PROPERTIES_ADD_DOUBLE_DOLLAR.has(parentComponentName) && 1375 PROPERTIES_ADD_DOUBLE_DOLLAR.get(parentComponentName).has(propertyName) || 1376 STYLE_ADD_DOUBLE_DOLLAR.has(propertyName); 1377} 1378 1379function processContent(source: string, id: string): string { 1380 if (fastBuildLogger) { 1381 source = visualTransform(source, id, fastBuildLogger); 1382 } 1383 source = preprocessExtend(source, extendCollection); 1384 source = preprocessNewExtend(source, extendCollection); 1385 return source; 1386} 1387 1388function judgeFileShouldResolved(file: string, shouldResolvedFiles: Set<string>): void { 1389 if (shouldResolvedFiles.has(file)) { 1390 return; 1391 } 1392 shouldResolvedFiles.add(file); 1393 if (cache && cache[file] && cache[file].parent) { 1394 cache[file].parent.forEach((item) => { 1395 judgeFileShouldResolved(item, shouldResolvedFiles); 1396 }); 1397 cache[file].parent = []; 1398 } 1399 if (cache && cache[file] && cache[file].children) { 1400 cache[file].children.forEach((item) => { 1401 judgeFileShouldResolved(item, shouldResolvedFiles); 1402 }); 1403 cache[file].children = []; 1404 } 1405} 1406 1407export function incrementWatchFile(watchModifiedFiles: string[], 1408 watchRemovedFiles: string[]): void { 1409 const changedFiles: string[] = [...watchModifiedFiles, ...watchRemovedFiles]; 1410 if (changedFiles.length) { 1411 shouldResolvedFiles.clear(); 1412 } 1413 changedFiles.forEach((file) => { 1414 judgeFileShouldResolved(file, shouldResolvedFiles); 1415 }); 1416} 1417 1418export function runArkTSLinter(): void { 1419 const originProgram: ts.BuilderProgram = globalProgram.builderProgram; 1420 1421 const timePrinterInstance = ts.ArkTSLinterTimePrinter.getInstance(); 1422 1423 const arkTSLinterDiagnostics = doArkTSLinter(getArkTSVersion(), 1424 getArkTSLinterMode(), 1425 originProgram, 1426 printArkTSLinterDiagnostic, 1427 !projectConfig.xtsMode, 1428 buildInfoWriteFile); 1429 1430 if (process.env.watchMode !== 'true' && !projectConfig.xtsMode) { 1431 arkTSLinterDiagnostics.forEach((diagnostic: ts.Diagnostic) => { 1432 updateErrorFileCache(diagnostic); 1433 }); 1434 timePrinterInstance.appendTime(ts.TimePhase.UPDATE_ERROR_FILE); 1435 } 1436 timePrinterInstance.printTimes(); 1437 ts.ArkTSLinterTimePrinter.destroyInstance(); 1438} 1439 1440function printArkTSLinterDiagnostic(diagnostic: ts.Diagnostic): void { 1441 if (diagnostic.category === ts.DiagnosticCategory.Error && (isInOhModuleFile(diagnostic) || isEtsDeclFileInSdk(diagnostic))) { 1442 const originalCategory = diagnostic.category; 1443 diagnostic.category = ts.DiagnosticCategory.Warning; 1444 printDiagnostic(diagnostic); 1445 diagnostic.category = originalCategory; 1446 return; 1447 } 1448 printDiagnostic(diagnostic); 1449} 1450 1451function isEtsDeclFileInSdk(diagnostics: ts.Diagnostic): boolean { 1452 if (diagnostics.file?.fileName === undefined) { 1453 return false; 1454 } 1455 return isInSDK(diagnostics.file.fileName) && diagnostics.file.fileName.endsWith('.ets'); 1456} 1457 1458function isInOhModuleFile(diagnostics: ts.Diagnostic): boolean { 1459 return (diagnostics.file !== undefined) && 1460 ((diagnostics.file.fileName.indexOf('/oh_modules/') !== -1) || diagnostics.file.fileName.indexOf('\\oh_modules\\') !== -1); 1461} 1462 1463function isInSDK(fileName: string | undefined): boolean { 1464 if (projectConfig.etsLoaderPath === undefined || fileName === undefined) { 1465 return false; 1466 } 1467 const sdkPath = path.resolve(projectConfig.etsLoaderPath, '../../../'); 1468 return path.resolve(fileName).startsWith(sdkPath); 1469} 1470 1471export function getArkTSLinterMode(): ArkTSLinterMode { 1472 if (!partialUpdateConfig.executeArkTSLinter) { 1473 return ArkTSLinterMode.NOT_USE; 1474 } 1475 1476 if (!partialUpdateConfig.standardArkTSLinter) { 1477 return ArkTSLinterMode.COMPATIBLE_MODE; 1478 } 1479 1480 if (isStandardMode()) { 1481 return ArkTSLinterMode.STANDARD_MODE; 1482 } 1483 return ArkTSLinterMode.COMPATIBLE_MODE; 1484} 1485 1486export function isStandardMode(): boolean { 1487 const STANDARD_MODE_COMPATIBLE_SDK_VERSION = 10; 1488 if (projectConfig && 1489 projectConfig.compatibleSdkVersion && 1490 projectConfig.compatibleSdkVersion >= STANDARD_MODE_COMPATIBLE_SDK_VERSION) { 1491 return true; 1492 } 1493 return false; 1494} 1495 1496function getArkTSVersion(): ArkTSVersion { 1497 if (projectConfig.arkTSVersion === '1.0') { 1498 return ArkTSVersion.ArkTS_1_0; 1499 } else if (projectConfig.arkTSVersion === '1.1') { 1500 return ArkTSVersion.ArkTS_1_1; 1501 } else if (projectConfig.arkTSVersion !== undefined) { 1502 const arkTSVersionLogger = fastBuildLogger || logger; 1503 arkTSVersionLogger.warn('\u001b[33m' + 'ArkTS: Invalid ArkTS version\n'); 1504 } 1505 1506 if (partialUpdateConfig.arkTSVersion === '1.0') { 1507 return ArkTSVersion.ArkTS_1_0; 1508 } else if (partialUpdateConfig.arkTSVersion === '1.1') { 1509 return ArkTSVersion.ArkTS_1_1; 1510 } else if (partialUpdateConfig.arkTSVersion !== undefined) { 1511 const arkTSVersionLogger = fastBuildLogger || logger; 1512 arkTSVersionLogger.warn('\u001b[33m' + 'ArkTS: Invalid ArkTS version in metadata\n'); 1513 } 1514 1515 return ArkTSVersion.ArkTS_1_1; 1516} 1517 1518enum TargetESVersion { 1519 ES2017 = 'ES2017', 1520 ES2021 = 'ES2021', 1521} 1522 1523function getTargetESVersion(): TargetESVersion { 1524 const targetESVersion = projectConfig?.projectArkOption?.tscConfig?.targetESVersion; 1525 if (targetESVersion === 'ES2017') { 1526 return TargetESVersion.ES2017; 1527 } else if (targetESVersion === 'ES2021') { 1528 return TargetESVersion.ES2021; 1529 } else if (targetESVersion !== undefined) { 1530 const targetESVersionLogger = fastBuildLogger || logger; 1531 targetESVersionLogger.warn('\u001b[33m' + 'ArkTS: Invalid Target ES version\n'); 1532 } 1533 return TargetESVersion.ES2021; 1534} 1535 1536interface TargetESVersionLib { 1537 ES2017: string[], 1538 ES2021: string[], 1539} 1540 1541const targetESVersionLib: TargetESVersionLib = { 1542 // When target is es2017, the lib is es2020. 1543 ES2017: ['ES2020'], 1544 ES2021: ['ES2021'], 1545}; 1546 1547function getTargetESVersionLib(): string[] { 1548 const targetESVersion = projectConfig?.projectArkOption?.tscConfig?.targetESVersion; 1549 if (targetESVersion === 'ES2017') { 1550 return targetESVersionLib.ES2017; 1551 } else if (targetESVersion === 'ES2021') { 1552 return targetESVersionLib.ES2021; 1553 } else if (targetESVersion !== undefined) { 1554 const targetESVersionLogger = fastBuildLogger || logger; 1555 targetESVersionLogger.warn('\u001b[33m' + 'ArkTS: Invalid Target ES version\n'); 1556 } 1557 return targetESVersionLib.ES2021; 1558} 1559 1560function initEtsStandaloneCheckerConfig(logger, config): void { 1561 fastBuildLogger = logger; 1562 if (config.packageManagerType === 'ohpm') { 1563 config.packageDir = 'oh_modules'; 1564 config.packageJson = 'oh-package.json5'; 1565 } else { 1566 config.packageDir = 'node_modules'; 1567 config.packageJson = 'package.json'; 1568 } 1569 if (config.aceModuleJsonPath && fs.existsSync(config.aceModuleJsonPath)) { 1570 process.env.compileMode = 'moduleJson'; 1571 } 1572 Object.assign(projectConfig, config); 1573} 1574 1575function resetEtsStandaloneCheckerConfig(beforeInitFastBuildLogger, beforeInitCompileMode: string): void { 1576 resetProjectConfig(); 1577 resetEtsCheck(); 1578 fastBuildLogger = beforeInitFastBuildLogger; 1579 process.env.compileMode = beforeInitCompileMode; 1580} 1581 1582export function etsStandaloneChecker(entryObj, logger, projectConfig): void { 1583 const beforeInitFastBuildLogger = fastBuildLogger; 1584 const beforeInitCompileMode = process.env.compileMode; 1585 initEtsStandaloneCheckerConfig(logger, projectConfig); 1586 const rootFileNames: string[] = []; 1587 const resolveModulePaths: string[] = []; 1588 Object.values(entryObj).forEach((fileName: string) => { 1589 rootFileNames.push(path.resolve(fileName)); 1590 }); 1591 if (projectConfig.resolveModulePaths && Array.isArray(projectConfig.resolveModulePaths)) { 1592 resolveModulePaths.push(...projectConfig.resolveModulePaths); 1593 } 1594 const filterFiles: string[] = filterInput(rootFileNames); 1595 languageService = createLanguageService(filterFiles, resolveModulePaths); 1596 const timePrinterInstance = ts.ArkTSLinterTimePrinter.getInstance(); 1597 timePrinterInstance.setArkTSTimePrintSwitch(false); 1598 timePrinterInstance.appendTime(ts.TimePhase.START); 1599 globalProgram.builderProgram = languageService.getBuilderProgram(/*withLinterProgram*/ true); 1600 globalProgram.program = globalProgram.builderProgram.getProgram(); 1601 props = languageService.getProps(); 1602 timePrinterInstance.appendTime(ts.TimePhase.GET_PROGRAM); 1603 collectFileToIgnoreDiagnostics(filterFiles); 1604 runArkTSLinter(); 1605 const allDiagnostics: ts.Diagnostic[] = globalProgram.builderProgram 1606 .getSyntacticDiagnostics() 1607 .concat(globalProgram.builderProgram.getSemanticDiagnostics()); 1608 globalProgram.builderProgram.emitBuildInfo(buildInfoWriteFile); 1609 1610 allDiagnostics.forEach((diagnostic: ts.Diagnostic) => { 1611 printDiagnostic(diagnostic); 1612 }); 1613 resetEtsStandaloneCheckerConfig(beforeInitFastBuildLogger, beforeInitCompileMode); 1614} 1615 1616export function resetEtsCheckTypeScript(): void { 1617 if (globalProgram.program) { 1618 globalProgram.program.releaseTypeChecker(); 1619 } else if (languageService) { 1620 languageService.getProgram().releaseTypeChecker(); 1621 } 1622 resetGlobalProgram(); 1623 languageService = null; 1624} 1625 1626export function resetEtsCheck(): void { 1627 cache = {}; 1628 props = []; 1629 needReCheckForChangedDepUsers = false; 1630 resetEtsCheckTypeScript(); 1631 allResolvedModules.clear(); 1632 checkerResult.count = 0; 1633 warnCheckerResult.count = 0; 1634 resolvedModulesCache.clear(); 1635 dollarCollection.clear(); 1636 extendCollection.clear(); 1637 allSourceFilePaths.clear(); 1638 allModuleIds.clear(); 1639 filesBuildInfo.clear(); 1640 fileExistsCache.clear(); 1641 dirExistsCache.clear(); 1642 targetESVersionChanged = false; 1643 fileToIgnoreDiagnostics = undefined; 1644} 1645