angular/packages/language-service/testing/src/language_service_test_cache.ts
Paul Gschwendtner 2df8584619 refactor(compiler-cli): speed up compiler tests by caching Angular (#54650)
Currently the `makeProgram` utility from `ngtsc/testing` does not use
the test host by default- optimizing for source file caching.

Additionally, the host can be updated to attempt caching of the `.d.ts`
files from `@angular/core`— whether that's fake core, or the real core-
is irrelevant. We are never caching if these changes between tests, so
correctness is guaranteed.

This commit reduces the type check test times form 80s to just 11
seconds, faster than what it was before with `fake_core`. The ngtsc
tests also run significantly faster. From 40s to 30s

PR Close #54650
2024-03-06 12:34:39 +01:00

50 lines
1.8 KiB
TypeScript

/**
* @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.io/license
*/
import {getCachedSourceFile} from '@angular/compiler-cli/src/ngtsc/testing';
import ts from 'typescript';
interface TsProjectWithInternals {
// typescript/src/server/project.ts#ConfiguredProject
setCompilerHost?(host: ts.CompilerHost): void;
}
let patchedLanguageServiceProjectHost = false;
/**
* Updates `ts.server.Project` to use efficient test caching of source files
* that aren't expected to be changed. E.g. the default libs.
*/
export function patchLanguageServiceProjectsWithTestHost() {
if (patchedLanguageServiceProjectHost) {
return;
}
patchedLanguageServiceProjectHost = true;
(ts.server.Project.prototype as TsProjectWithInternals).setCompilerHost = (host) => {
const _originalHostGetSourceFile = host.getSourceFile;
const _originalHostGetSourceFileByPath = host.getSourceFileByPath;
host.getSourceFile =
(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) => {
return getCachedSourceFile(fileName, () => host.readFile(fileName)) ??
_originalHostGetSourceFile.call(
host, fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile);
};
if (_originalHostGetSourceFileByPath !== undefined) {
host.getSourceFileByPath =
(fileName, path, languageVersionOrOptions, onError, shouldCreateNewSourceFile) => {
return getCachedSourceFile(fileName, () => host.readFile(fileName)) ??
_originalHostGetSourceFileByPath.call(
host, fileName, path, languageVersionOrOptions, onError,
shouldCreateNewSourceFile);
};
}
};
}