/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import ts from 'typescript'; import { absoluteFrom, AbsoluteFsPath, createFileSystemTsReadDirectoryFn, FileSystem, getFileSystem, ReadonlyFileSystem, } from '../src/ngtsc/file_system'; import {NgCompilerOptions} from './ngtsc/core/api'; import {replaceTsWithNgInErrors} from './ngtsc/diagnostics'; import * as api from './transformers/api'; import * as ng from './transformers/entry_points'; import {createMessageDiagnostic} from './transformers/util'; const defaultFormatHost: ts.FormatDiagnosticsHost = { getCurrentDirectory: () => ts.sys.getCurrentDirectory(), getCanonicalFileName: (fileName) => fileName, getNewLine: () => ts.sys.newLine, }; export function formatDiagnostics( diags: ReadonlyArray, host: ts.FormatDiagnosticsHost = defaultFormatHost, ): string { if (diags && diags.length) { return diags .map((diagnostic) => replaceTsWithNgInErrors(ts.formatDiagnosticsWithColorAndContext([diagnostic], host)), ) .join(''); } else { return ''; } } /** Used to read configuration files. */ export type ConfigurationHost = Pick< ReadonlyFileSystem, 'readFile' | 'exists' | 'lstat' | 'resolve' | 'join' | 'dirname' | 'extname' | 'pwd' | 'readdir' >; export interface ParsedConfiguration { project: string; options: api.CompilerOptions; rootNames: string[]; projectReferences?: readonly ts.ProjectReference[] | undefined; emitFlags: api.EmitFlags; errors: ts.Diagnostic[]; } export function calcProjectFileAndBasePath( project: string, host: ConfigurationHost = getFileSystem(), ): {projectFile: AbsoluteFsPath; basePath: AbsoluteFsPath} { const absProject = host.resolve(project); const projectIsDir = host.lstat(absProject).isDirectory(); const projectFile = projectIsDir ? host.join(absProject, 'tsconfig.json') : absProject; const projectDir = projectIsDir ? absProject : host.dirname(absProject); const basePath = host.resolve(projectDir); return {projectFile, basePath}; } export function readConfiguration( project: string, existingOptions?: api.CompilerOptions, host: ConfigurationHost = getFileSystem(), extendedConfigCache = new Map(), ): ParsedConfiguration { try { const fs = getFileSystem(); const {projectFile, basePath} = calcProjectFileAndBasePath(project, host); const parseConfigHost = createParseConfigHost(host, fs); const {config, error} = readConfigFile(projectFile, host, fs, extendedConfigCache); if (error) { return { project, errors: [error], rootNames: [], options: {}, emitFlags: api.EmitFlags.Default, }; } const existingCompilerOptions: api.CompilerOptions = { genDir: basePath, basePath, ...existingOptions, }; const { options, errors, fileNames: rootNames, projectReferences, } = ts.parseJsonConfigFileContent( /* json */ config, /* host */ parseConfigHost, /* basePath */ basePath, /* existingOptions */ existingCompilerOptions, /* configFileName */ projectFile, /* resolutionStack */ undefined, /* extraFileExtensions */ undefined, /* extendedConfigCache */ extendedConfigCache, ); const angularCompilerOptions = readAngularCompilerOptions( projectFile, config, host, fs, parseConfigHost, extendedConfigCache, ); Object.assign(options, angularCompilerOptions, existingOptions); let emitFlags = api.EmitFlags.Default; if (!options['skipMetadataEmit'] && !options['flatModuleOutFile']) { emitFlags |= api.EmitFlags.Metadata; } if (options['skipTemplateCodegen']) { emitFlags = emitFlags & ~api.EmitFlags.Codegen; } return {project: projectFile, rootNames, projectReferences, options, errors, emitFlags}; } catch (e) { const errors: ts.Diagnostic[] = [ { category: ts.DiagnosticCategory.Error, messageText: (e as Error).stack ?? (e as Error).message, file: undefined, start: undefined, length: undefined, source: 'angular', code: api.UNKNOWN_ERROR_CODE, }, ]; return {project: '', errors, rootNames: [], options: {}, emitFlags: api.EmitFlags.Default}; } } function readConfigFile( configFile: string, host: ConfigurationHost, fs: FileSystem, extendedConfigCache?: Map, ): {config?: any; error?: ts.Diagnostic} { const cacheKey = fs.isCaseSensitive() ? configFile : configFile.toLowerCase(); const cacheEntry = extendedConfigCache?.get(cacheKey); if (cacheEntry) { return { config: cacheEntry.extendedConfig?.raw, error: (cacheEntry.extendedResult as {parseDiagnostics?: ts.Diagnostic[]}) .parseDiagnostics?.[0], }; } return ts.readConfigFile(configFile, (file) => host.readFile(host.resolve(file))); } function readAngularCompilerOptions( configFile: string, config: any, host: ConfigurationHost, fs: FileSystem, parseConfigHost: ts.ParseConfigHost, extendedConfigCache: Map, ): NgCompilerOptions { const cacheKey = fs.isCaseSensitive() ? configFile : configFile.toLowerCase(); const cacheEntry = extendedConfigCache.get(cacheKey); const cachedExtendedConfig = cacheEntry?.extendedConfig as | (ts.ExtendedConfigCacheEntry['extendedConfig'] & { angularCompilerOptions?: NgCompilerOptions; }) | undefined; // If the merged angularCompilerOptions for this config are already cached, reuse them. if (cachedExtendedConfig?.angularCompilerOptions) { return cachedExtendedConfig.angularCompilerOptions; } // Note: In Google, `angularCompilerOptions` are stored in `bazelOptions`. // This function typically doesn't run for actual Angular compilations, but // tooling like Tsurge, or schematics may leverage this helper, so we account // for this here. const angularCompilerOptions = config.angularCompilerOptions ?? config.bazelOptions?.angularCompilerOptions ?? {}; if (!config.extends) { if (cachedExtendedConfig) { cachedExtendedConfig.angularCompilerOptions = angularCompilerOptions; } return angularCompilerOptions; } const resolvedExtendedConfigPath = cachedExtendedConfig?.extendedConfigPath; const extendsPaths: string[] = resolvedExtendedConfigPath ? typeof resolvedExtendedConfigPath === 'string' ? [resolvedExtendedConfigPath] : resolvedExtendedConfigPath : typeof config.extends === 'string' ? [config.extends] : Array.isArray(config.extends) ? config.extends : []; // Recursively merge extended configurations from base to leaf (left-to-right). const inheritedOptions = extendsPaths.reduce((prevOptions, extendsPath) => { const extendedConfigPath = resolvedExtendedConfigPath ? absoluteFrom(extendsPath) : getExtendedConfigPath(configFile, extendsPath, host, fs, parseConfigHost); if (extendedConfigPath === null) { return prevOptions; } const {config: extendedConfig, error} = readConfigFile( extendedConfigPath, host, fs, extendedConfigCache, ); if (error || !extendedConfig) { return prevOptions; } const options = readAngularCompilerOptions( extendedConfigPath, extendedConfig, host, fs, parseConfigHost, extendedConfigCache, ); return {...prevOptions, ...options}; }, {} as NgCompilerOptions); const mergedOptions = {...inheritedOptions, ...angularCompilerOptions}; if (cachedExtendedConfig) { cachedExtendedConfig.angularCompilerOptions = mergedOptions; } return mergedOptions; } function createParseConfigHost(host: ConfigurationHost, fs = getFileSystem()): ts.ParseConfigHost { return { fileExists: host.exists.bind(host), readDirectory: createFileSystemTsReadDirectoryFn(fs), readFile: host.readFile.bind(host), useCaseSensitiveFileNames: fs.isCaseSensitive(), }; } function getExtendedConfigPath( configFile: string, extendsValue: string, host: ConfigurationHost, fs: FileSystem, parseConfigHost: ts.ParseConfigHost, ): AbsoluteFsPath | null { for (const candidate of [extendsValue, `${extendsValue}.json`]) { if (candidate[0] === '.' || fs.isRooted(candidate)) { const extendedConfigPath = host.resolve(host.dirname(configFile), candidate); if (host.exists(extendedConfigPath)) { return extendedConfigPath; } } else { // Path isn't a rooted or relative path, resolve like a module. const {resolvedModule} = ts.nodeModuleNameResolver( candidate, configFile, {moduleResolution: ts.ModuleResolutionKind.NodeNext, resolveJsonModule: true}, parseConfigHost, ); if (resolvedModule) { return absoluteFrom(resolvedModule.resolvedFileName); } } } return null; } export interface PerformCompilationResult { diagnostics: ReadonlyArray; program?: api.Program; emitResult?: ts.EmitResult; } export function exitCodeFromResult(diags: ReadonlyArray | undefined): number { if (!diags) return 0; if (diags.every((diag) => diag.category !== ts.DiagnosticCategory.Error)) { // If we have a result and didn't get any errors, we succeeded. return 0; } // Return 2 if any of the errors were unknown. return diags.some((d) => d.source === 'angular' && d.code === api.UNKNOWN_ERROR_CODE) ? 2 : 1; } export function performCompilation({ rootNames, options, host, oldProgram, emitCallback, mergeEmitResultsCallback, gatherDiagnostics = defaultGatherDiagnostics, customTransformers, emitFlags = api.EmitFlags.Default, forceEmit = false, modifiedResourceFiles = null, }: { rootNames: string[]; options: api.CompilerOptions; host?: api.CompilerHost; oldProgram?: api.Program; emitCallback?: api.TsEmitCallback; mergeEmitResultsCallback?: api.TsMergeEmitResultsCallback; gatherDiagnostics?: (program: api.Program) => ReadonlyArray; customTransformers?: api.CustomTransformers; emitFlags?: api.EmitFlags; forceEmit?: boolean; modifiedResourceFiles?: Set | null; }): PerformCompilationResult { let program: api.Program | undefined; let emitResult: ts.EmitResult | undefined; let allDiagnostics: Array = []; try { if (!host) { host = ng.createCompilerHost({options}); } if (modifiedResourceFiles) { host.getModifiedResourceFiles = () => modifiedResourceFiles; } program = ng.createProgram({rootNames, host, options, oldProgram}); const beforeDiags = Date.now(); allDiagnostics.push(...gatherDiagnostics(program!)); if (options.diagnostics) { const afterDiags = Date.now(); allDiagnostics.push( createMessageDiagnostic(`Time for diagnostics: ${afterDiags - beforeDiags}ms.`), ); } if (!hasErrors(allDiagnostics)) { emitResult = program!.emit({ emitCallback, mergeEmitResultsCallback, customTransformers, emitFlags, forceEmit, }); allDiagnostics.push(...emitResult.diagnostics); return {diagnostics: allDiagnostics, program, emitResult}; } return {diagnostics: allDiagnostics, program}; } catch (e) { // We might have a program with unknown state, discard it. program = undefined; allDiagnostics.push({ category: ts.DiagnosticCategory.Error, messageText: (e as Error).stack ?? (e as Error).message, code: api.UNKNOWN_ERROR_CODE, file: undefined, start: undefined, length: undefined, }); return {diagnostics: allDiagnostics, program}; } } export function defaultGatherDiagnostics(program: api.Program): ReadonlyArray { const allDiagnostics: Array = []; function checkDiagnostics(diags: ReadonlyArray | undefined) { if (diags) { allDiagnostics.push(...diags); return !hasErrors(diags); } return true; } let checkOtherDiagnostics = true; // Check parameter diagnostics checkOtherDiagnostics = checkOtherDiagnostics && checkDiagnostics([...program.getTsOptionDiagnostics(), ...program.getNgOptionDiagnostics()]); // Check syntactic diagnostics checkOtherDiagnostics = checkOtherDiagnostics && checkDiagnostics(program.getTsSyntacticDiagnostics()); // Check TypeScript semantic and Angular structure diagnostics checkOtherDiagnostics = checkOtherDiagnostics && checkDiagnostics([ ...program.getTsSemanticDiagnostics(), ...program.getNgStructuralDiagnostics(), ]); // Check Angular semantic diagnostics checkOtherDiagnostics = checkOtherDiagnostics && checkDiagnostics(program.getNgSemanticDiagnostics()); return allDiagnostics; } function hasErrors(diags: ReadonlyArray) { return diags.some((d) => d.category === ts.DiagnosticCategory.Error); }