Skip to content

Commit c5aea89

Browse files
authored
Add alias ResolutionMode for ModuleKind.ESNext | ModuleKind.CommonJs | undefined (#51482)
* Add alias ResolutionMode for ModuleKind.ESNext | ModuleKind.CommonJs | undefined * ResolutionMode | undefined = ResolutionMode * More
1 parent 3eafb64 commit c5aea89

18 files changed

+151
-145
lines changed

src/compiler/builderState.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {
33
ExportedModulesFromDeclarationEmit, GetCanonicalFileName, getDirectoryPath, getSourceFileOfNode,
44
isDeclarationFileName, isExternalOrCommonJsModule, isGlobalScopeAugmentation, isJsonSourceFile,
55
isModuleWithStringLiteralName, isStringLiteral, mapDefined, mapDefinedIterator, ModuleDeclaration,
6-
ModuleKind, outFile, OutputFile, Path, Program, some, SourceFile, StringLiteralLike, Symbol,
6+
ModuleKind, outFile, OutputFile, Path, Program, ResolutionMode, some, SourceFile, StringLiteralLike, Symbol,
77
toPath, TypeChecker,
88
} from "./_namespaces/ts";
99

@@ -75,7 +75,7 @@ export namespace BuilderState {
7575
readonly version: string;
7676
signature: string | undefined;
7777
affectsGlobalScope: true | undefined;
78-
impliedFormat: SourceFile["impliedNodeFormat"];
78+
impliedFormat: ResolutionMode;
7979
}
8080

8181
export interface ReadonlyManyToManyPathMap {

src/compiler/checker.ts

+10-10
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ import {
195195
usingSingleLineStringWriter, VariableDeclaration, VariableDeclarationList, VariableLikeDeclaration,
196196
VariableStatement, VarianceFlags, visitEachChild, visitNode, visitNodes, Visitor, VisitResult, VoidExpression,
197197
walkUpBindingElementsAndPatterns, walkUpParenthesizedExpressions, walkUpParenthesizedTypes,
198-
walkUpParenthesizedTypesAndGetParentAndChild, WhileStatement, WideningContext, WithStatement, YieldExpression,
198+
walkUpParenthesizedTypesAndGetParentAndChild, WhileStatement, WideningContext, WithStatement, YieldExpression, ResolutionMode,
199199
} from "./_namespaces/ts";
200200
import * as performance from "./_namespaces/ts.performance";
201201
import * as moduleSpecifiers from "./_namespaces/ts.moduleSpecifiers";
@@ -2969,7 +2969,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
29692969
return isStringLiteralLike(usage) ? getModeForUsageLocation(getSourceFileOfNode(usage), usage) : undefined;
29702970
}
29712971

2972-
function isESMFormatImportImportingCommonjsFormatFile(usageMode: SourceFile["impliedNodeFormat"], targetMode: SourceFile["impliedNodeFormat"]) {
2972+
function isESMFormatImportImportingCommonjsFormatFile(usageMode: ResolutionMode, targetMode: ResolutionMode) {
29732973
return usageMode === ModuleKind.ESNext && targetMode === ModuleKind.CommonJS;
29742974
}
29752975

@@ -6559,7 +6559,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
65596559
return top;
65606560
}
65616561

6562-
function getSpecifierForModuleSymbol(symbol: Symbol, context: NodeBuilderContext, overrideImportMode?: SourceFile["impliedNodeFormat"]) {
6562+
function getSpecifierForModuleSymbol(symbol: Symbol, context: NodeBuilderContext, overrideImportMode?: ResolutionMode) {
65636563
let file = getDeclarationOfKind<SourceFile>(symbol, SyntaxKind.SourceFile);
65646564
if (!file) {
65656565
const equivalentFileSymbol = firstDefined(symbol.declarations, d => getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol));
@@ -6623,7 +6623,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
66236623
}
66246624
return specifier;
66256625

6626-
function getSpecifierCacheKey(path: string, mode: SourceFile["impliedNodeFormat"] | undefined) {
6626+
function getSpecifierCacheKey(path: string, mode: ResolutionMode | undefined) {
66276627
return mode === undefined ? path : `${mode}|${path}`;
66286628
}
66296629
}
@@ -44091,10 +44091,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
4409144091
// this variable and functions that use it are deliberately moved here from the outer scope
4409244092
// to avoid scope pollution
4409344093
const resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
44094-
let fileToDirective: Map<string, [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined]>;
44094+
let fileToDirective: Map<string, [specifier: string, mode: ResolutionMode | undefined]>;
4409544095
if (resolvedTypeReferenceDirectives) {
4409644096
// populate reverse mapping: file path -> type reference directive that was resolved to this file
44097-
fileToDirective = new Map<string, [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined]>();
44097+
fileToDirective = new Map<string, [specifier: string, mode: ResolutionMode | undefined]>();
4409844098
resolvedTypeReferenceDirectives.forEach((resolvedDirective, key, mode) => {
4409944099
if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
4410044100
return;
@@ -44226,7 +44226,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
4422644226
}
4422744227

4422844228
// defined here to avoid outer scope pollution
44229-
function getTypeReferenceDirectivesForEntityName(node: EntityNameOrEntityNameExpression): [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined][] | undefined {
44229+
function getTypeReferenceDirectivesForEntityName(node: EntityNameOrEntityNameExpression): [specifier: string, mode: ResolutionMode | undefined][] | undefined {
4423044230
// program does not have any files with type reference directives - bail out
4423144231
if (!fileToDirective) {
4423244232
return undefined;
@@ -44251,13 +44251,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
4425144251
}
4425244252

4425344253
// defined here to avoid outer scope pollution
44254-
function getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined][] | undefined {
44254+
function getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): [specifier: string, mode: ResolutionMode | undefined][] | undefined {
4425544255
// program does not have any files with type reference directives - bail out
4425644256
if (!fileToDirective || !isSymbolFromTypeDeclarationFile(symbol)) {
4425744257
return undefined;
4425844258
}
4425944259
// check what declarations in the symbol can contribute to the target meaning
44260-
let typeReferenceDirectives: [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined][] | undefined;
44260+
let typeReferenceDirectives: [specifier: string, mode: ResolutionMode | undefined][] | undefined;
4426144261
for (const decl of symbol.declarations!) {
4426244262
// check meaning of the local symbol to see if declaration needs to be analyzed further
4426344263
if (decl.symbol && decl.symbol.flags & meaning!) {
@@ -44308,7 +44308,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
4430844308
return false;
4430944309
}
4431044310

44311-
function addReferencedFilesToTypeDirective(file: SourceFile, key: string, mode: SourceFile["impliedNodeFormat"] | undefined) {
44311+
function addReferencedFilesToTypeDirective(file: SourceFile, key: string, mode: ResolutionMode | undefined) {
4431244312
if (fileToDirective.has(file.path)) return;
4431344313
fileToDirective.set(file.path, [key, mode]);
4431444314
for (const { fileName, resolutionMode } of file.referencedFiles) {

src/compiler/moduleNameResolver.ts

+16-15
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
ModuleKind, ModuleResolutionHost, ModuleResolutionKind, noop, noopPush, normalizePath, normalizeSlashes,
1414
optionsHaveModuleResolutionChanges, PackageId, packageIdToString, ParsedCommandLine, Path, pathIsRelative, Pattern,
1515
patternText, perfLogger, Push, readJson, removeExtension, removeFileExtension, removePrefix,
16+
ResolutionMode,
1617
ResolvedModuleWithFailedLookupLocations, ResolvedProjectReference, ResolvedTypeReferenceDirective,
1718
ResolvedTypeReferenceDirectiveWithFailedLookupLocations, some, sort, SourceFile, startsWith, stringContains,
1819
StringLiteralLike, supportedTSExtensionsFlat, toFileNameLowerCase, toPath, tryExtractTSExtension, tryGetExtensionFromPath,
@@ -333,7 +334,7 @@ function arePathsEqual(path1: string, path2: string, host: ModuleResolutionHost)
333334
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
334335
* is assumed to be the same as root directory of the project.
335336
*/
336-
export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache, resolutionMode?: SourceFile["impliedNodeFormat"]): ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
337+
export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache, resolutionMode?: ResolutionMode): ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
337338
Debug.assert(typeof typeReferenceDirectiveName === "string", "Non-string value passed to `ts.resolveTypeReferenceDirective`, likely by a wrapping package working with an outdated `resolveTypeReferenceDirectives` signature. This is probably not a problem in TS itself.");
338339
const traceEnabled = isTraceEnabled(options, host);
339340
if (redirectedReference) {
@@ -571,11 +572,11 @@ export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResol
571572
}
572573

573574
export interface ModeAwareCache<T> {
574-
get(key: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined): T | undefined;
575-
set(key: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined, value: T): this;
576-
delete(key: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined): this;
577-
has(key: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined): boolean;
578-
forEach(cb: (elem: T, key: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined) => void): void;
575+
get(key: string, mode: ResolutionMode): T | undefined;
576+
set(key: string, mode: ResolutionMode, value: T): this;
577+
delete(key: string, mode: ResolutionMode): this;
578+
has(key: string, mode: ResolutionMode): boolean;
579+
forEach(cb: (elem: T, key: string, mode: ResolutionMode) => void): void;
579580
size(): number;
580581
}
581582

@@ -603,7 +604,7 @@ export interface ModuleResolutionCache extends PerDirectoryResolutionCache<Resol
603604
* We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive.
604605
*/
605606
export interface NonRelativeModuleNameResolutionCache extends PackageJsonInfoCache {
606-
getOrCreateCacheForModuleName(nonRelativeModuleName: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined, redirectedReference?: ResolvedProjectReference): PerModuleNameCache;
607+
getOrCreateCacheForModuleName(nonRelativeModuleName: string, mode: ResolutionMode, redirectedReference?: ResolvedProjectReference): PerModuleNameCache;
607608
}
608609

609610
export interface PackageJsonInfoCache {
@@ -758,7 +759,7 @@ function createPerDirectoryResolutionCache<T>(currentDirectory: string, getCanon
758759
export function createModeAwareCache<T>(): ModeAwareCache<T> {
759760
const underlying = new Map<ModeAwareCacheKey, T>();
760761
type ModeAwareCacheKey = string & { __modeAwareCacheKey: any; };
761-
const memoizedReverseKeys = new Map<ModeAwareCacheKey, [specifier: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined]>();
762+
const memoizedReverseKeys = new Map<ModeAwareCacheKey, [specifier: string, mode: ResolutionMode]>();
762763

763764
const cache: ModeAwareCache<T> = {
764765
get(specifier, mode) {
@@ -787,7 +788,7 @@ export function createModeAwareCache<T>(): ModeAwareCache<T> {
787788
};
788789
return cache;
789790

790-
function getUnderlyingCacheKey(specifier: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined) {
791+
function getUnderlyingCacheKey(specifier: string, mode: ResolutionMode) {
791792
const result = (mode === undefined ? specifier : `${mode}|${specifier}`) as ModeAwareCacheKey;
792793
memoizedReverseKeys.set(result, [specifier, mode]);
793794
return result;
@@ -864,7 +865,7 @@ export function createModuleResolutionCache(
864865
updateRedirectsMap(options, directoryToModuleNameMap!, moduleNameToDirectoryMap);
865866
}
866867

867-
function getOrCreateCacheForModuleName(nonRelativeModuleName: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined, redirectedReference?: ResolvedProjectReference): PerModuleNameCache {
868+
function getOrCreateCacheForModuleName(nonRelativeModuleName: string, mode: ResolutionMode, redirectedReference?: ResolvedProjectReference): PerModuleNameCache {
868869
Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName));
869870
return getOrCreateCache(moduleNameToDirectoryMap!, redirectedReference, mode === undefined ? nonRelativeModuleName : `${mode}|${nonRelativeModuleName}`, createPerModuleNameCache);
870871
}
@@ -983,14 +984,14 @@ export function createTypeReferenceDirectiveResolutionCache(
983984
}
984985
}
985986

986-
export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache, mode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations | undefined {
987+
export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache, mode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations | undefined {
987988
const containingDirectory = getDirectoryPath(containingFile);
988989
const perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
989990
if (!perFolderCache) return undefined;
990991
return perFolderCache.get(moduleName, mode);
991992
}
992993

993-
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations {
994+
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations {
994995
const traceEnabled = isTraceEnabled(compilerOptions, host);
995996
if (redirectedReference) {
996997
compilerOptions = redirectedReference.commandLine.options;
@@ -1312,7 +1313,7 @@ export enum NodeResolutionFeatures {
13121313

13131314
function node16ModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions,
13141315
host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference,
1315-
resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations {
1316+
resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations {
13161317
return nodeNextModuleNameResolverWorker(
13171318
NodeResolutionFeatures.Node16Default,
13181319
moduleName,
@@ -1327,7 +1328,7 @@ function node16ModuleNameResolver(moduleName: string, containingFile: string, co
13271328

13281329
function nodeNextModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions,
13291330
host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference,
1330-
resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations {
1331+
resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations {
13311332
return nodeNextModuleNameResolverWorker(
13321333
NodeResolutionFeatures.NodeNextDefault,
13331334
moduleName,
@@ -1344,7 +1345,7 @@ const jsOnlyExtensions = [Extensions.JavaScript];
13441345
const tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
13451346
const tsPlusJsonExtensions = [...tsExtensions, Extensions.Json];
13461347
const tsconfigExtensions = [Extensions.TSConfig];
1347-
function nodeNextModuleNameResolverWorker(features: NodeResolutionFeatures, moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations {
1348+
function nodeNextModuleNameResolverWorker(features: NodeResolutionFeatures, moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, resolutionMode?: ResolutionMode): ResolvedModuleWithFailedLookupLocations {
13481349
const containingDirectory = getDirectoryPath(containingFile);
13491350

13501351
// es module file or cjs-like input file, use a variant of the legacy cjs resolver that supports the selected modern features

src/compiler/moduleSpecifiers.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import {
1616
ModuleSpecifierResolutionHost, NodeFlags, NodeModulePathParts, normalizePath, Path, pathContainsNodeModules,
1717
pathIsBareSpecifier, pathIsRelative, PropertyAccessExpression, removeFileExtension, removeSuffix, resolvePath,
1818
ScriptKind, some, SourceFile, startsWith, startsWithDirectory, stringContains, StringLiteral, Symbol, SymbolFlags,
19-
toPath, tryGetExtensionFromPath, tryParsePatterns, TypeChecker, UserPreferences,
19+
toPath, tryGetExtensionFromPath, tryParsePatterns, TypeChecker, UserPreferences, ResolutionMode,
2020
} from "./_namespaces/ts";
2121

2222
// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
@@ -322,7 +322,7 @@ function getInfo(importingSourceFileName: Path, host: ModuleSpecifierResolutionH
322322
return { getCanonicalFileName, importingSourceFileName, sourceDirectory };
323323
}
324324

325-
function getLocalModuleSpecifier(moduleFileName: string, info: Info, compilerOptions: CompilerOptions, host: ModuleSpecifierResolutionHost, importMode: SourceFile["impliedNodeFormat"], { ending, relativePreference }: Preferences): string {
325+
function getLocalModuleSpecifier(moduleFileName: string, info: Info, compilerOptions: CompilerOptions, host: ModuleSpecifierResolutionHost, importMode: ResolutionMode, { ending, relativePreference }: Preferences): string {
326326
const { baseUrl, paths, rootDirs } = compilerOptions;
327327
const { sourceDirectory, getCanonicalFileName } = info;
328328
const relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
@@ -589,7 +589,7 @@ function tryGetModuleNameFromAmbientModule(moduleSymbol: Symbol, checker: TypeCh
589589
}
590590
}
591591

592-
function getAllowedEndings(preferredEnding: Ending, compilerOptions: CompilerOptions, importMode: SourceFile["impliedNodeFormat"]) {
592+
function getAllowedEndings(preferredEnding: Ending, compilerOptions: CompilerOptions, importMode: ResolutionMode) {
593593
if (getEmitModuleResolutionKind(compilerOptions) >= ModuleResolutionKind.Node16 && importMode === ModuleKind.ESNext) {
594594
return [Ending.JsExtension];
595595
}
@@ -776,7 +776,7 @@ function tryGetModuleNameFromRootDirs(rootDirs: readonly string[], moduleFileNam
776776
: removeFileExtension(shortest);
777777
}
778778

779-
function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCanonicalFileName, sourceDirectory }: Info, importingSourceFile: SourceFile, host: ModuleSpecifierResolutionHost, options: CompilerOptions, userPreferences: UserPreferences, packageNameOnly?: boolean, overrideMode?: ModuleKind.ESNext | ModuleKind.CommonJS): string | undefined {
779+
function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCanonicalFileName, sourceDirectory }: Info, importingSourceFile: SourceFile, host: ModuleSpecifierResolutionHost, options: CompilerOptions, userPreferences: UserPreferences, packageNameOnly?: boolean, overrideMode?: ResolutionMode): string | undefined {
780780
if (!host.fileExists || !host.readFile) {
781781
return undefined;
782782
}

0 commit comments

Comments
 (0)