-
Notifications
You must be signed in to change notification settings - Fork 12.6k
/
moduleNameResolver.ts
3413 lines (3145 loc) · 176 KB
/
moduleNameResolver.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
append,
appendIfUnique,
arrayIsEqualTo,
changeAnyExtension,
changeFullExtension,
CharacterCodes,
combinePaths,
CommandLineOption,
comparePaths,
Comparison,
CompilerHost,
CompilerOptions,
concatenate,
contains,
containsPath,
createCompilerDiagnostic,
Debug,
deduplicate,
Diagnostic,
DiagnosticMessage,
DiagnosticReporter,
Diagnostics,
directoryProbablyExists,
directorySeparator,
emptyArray,
endsWith,
ensureTrailingDirectorySeparator,
every,
Extension,
extensionIsTS,
fileExtensionIs,
fileExtensionIsOneOf,
filter,
firstDefined,
forEach,
forEachAncestorDirectory,
formatMessage,
getAllowImportingTsExtensions,
getAllowJSCompilerOption,
getAnyExtensionFromPath,
getBaseFileName,
GetCanonicalFileName,
getCommonSourceDirectory,
getCompilerOptionValue,
getDirectoryPath,
GetEffectiveTypeRootsHost,
getEmitModuleResolutionKind,
getNormalizedAbsolutePath,
getOwnKeys,
getPathComponents,
getPathFromPathComponents,
getPathsBasePath,
getPossibleOriginalInputExtensionForExtension,
getRelativePathFromDirectory,
getResolveJsonModule,
getRootLength,
hasProperty,
hasTrailingDirectorySeparator,
hostGetCanonicalFileName,
inferredTypesContainingFile,
isArray,
isDeclarationFileName,
isExternalModuleNameRelative,
isRootedDiskPath,
isString,
lastOrUndefined,
length,
MapLike,
matchedText,
MatchingKeys,
matchPatternOrExact,
ModuleKind,
ModuleResolutionHost,
ModuleResolutionKind,
moduleResolutionOptionDeclarations,
moduleResolutionSupportsPackageJsonExportsAndImports,
ModuleSpecifierResolutionHost,
noop,
normalizePath,
normalizeSlashes,
PackageId,
packageIdToString,
ParsedPatterns,
Path,
pathIsRelative,
patternText,
readJson,
removeExtension,
removeFileExtension,
removePrefix,
replaceFirstStar,
ResolutionMode,
ResolvedModuleWithFailedLookupLocations,
ResolvedProjectReference,
ResolvedTypeReferenceDirective,
ResolvedTypeReferenceDirectiveWithFailedLookupLocations,
some,
startsWith,
supportedDeclarationExtensions,
supportedJSExtensionsFlat,
supportedTSImplementationExtensions,
toPath,
toSorted,
tryExtractTSExtension,
tryGetExtensionFromPath,
tryParsePatterns,
Version,
version,
versionMajorMinor,
VersionRange,
} from "./_namespaces/ts.js";
/** @internal */
export function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void {
host.trace!(formatMessage(message, ...args));
}
/** @internal */
export function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean {
return !!compilerOptions.traceResolution && host.trace !== undefined;
}
function withPackageId(packageInfo: PackageJsonInfo | undefined, r: PathAndExtension | undefined, state: ModuleResolutionState): Resolved | undefined {
let packageId: PackageId | undefined;
if (r && packageInfo) {
const packageJsonContent = packageInfo.contents.packageJsonContent as PackageJson;
if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
packageId = {
name: packageJsonContent.name,
subModuleName: r.path.slice(packageInfo.packageDirectory.length + directorySeparator.length),
version: packageJsonContent.version,
peerDependencies: getPeerDependenciesOfPackageJsonInfo(packageInfo, state),
};
}
}
return r && { path: r.path, extension: r.ext, packageId, resolvedUsingTsExtension: r.resolvedUsingTsExtension };
}
function noPackageId(r: PathAndExtension | undefined): Resolved | undefined {
return withPackageId(/*packageInfo*/ undefined, r, /*state*/ undefined!); // State will not be used so no need to pass
}
function removeIgnoredPackageId(r: Resolved | undefined): PathAndExtension | undefined {
if (r) {
Debug.assert(r.packageId === undefined);
return { path: r.path, ext: r.extension, resolvedUsingTsExtension: r.resolvedUsingTsExtension };
}
}
/** Result of trying to resolve a module. */
interface Resolved {
path: string;
extension: string;
packageId: PackageId | undefined;
/**
* When the resolved is not created from cache, the value is
* - string if it is symbolic link to the resolved `path`
* - undefined if `path` is not a symbolic link
* When the resolved is created using value from cache of ResolvedModuleWithFailedLookupLocations, the value is:
* - string if it is symbolic link to the resolved `path`
* - true if `path` is not a symbolic link - this indicates that the `originalPath` calculation is already done and needs to be skipped
* Note: This is a file name with preserved original casing, not a normalized `Path`.
*/
originalPath?: string | true;
resolvedUsingTsExtension: boolean | undefined;
}
/** Result of trying to resolve a module at a file. Needs to have 'packageId' added later. */
interface PathAndExtension {
path: string;
// (Use a different name than `extension` to make sure Resolved isn't assignable to PathAndExtension.)
ext: string;
resolvedUsingTsExtension: boolean | undefined;
}
// dprint-ignore
/**
* Kinds of file that we are currently looking for.
*/
const enum Extensions {
TypeScript = 1 << 0, // '.ts', '.tsx', '.mts', '.cts'
JavaScript = 1 << 1, // '.js', '.jsx', '.mjs', '.cjs'
Declaration = 1 << 2, // '.d.ts', etc.
Json = 1 << 3, // '.json'
ImplementationFiles = TypeScript | JavaScript,
}
function formatExtensions(extensions: Extensions) {
const result: string[] = [];
if (extensions & Extensions.TypeScript) result.push("TypeScript");
if (extensions & Extensions.JavaScript) result.push("JavaScript");
if (extensions & Extensions.Declaration) result.push("Declaration");
if (extensions & Extensions.Json) result.push("JSON");
return result.join(", ");
}
function extensionsToExtensionsArray(extensions: Extensions) {
const result: Extension[] = [];
if (extensions & Extensions.TypeScript) result.push(...supportedTSImplementationExtensions);
if (extensions & Extensions.JavaScript) result.push(...supportedJSExtensionsFlat);
if (extensions & Extensions.Declaration) result.push(...supportedDeclarationExtensions);
if (extensions & Extensions.Json) result.push(Extension.Json);
return result;
}
interface PathAndPackageId {
readonly fileName: string;
readonly packageId: PackageId | undefined;
}
/** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
function resolvedTypeScriptOnly(resolved: Resolved | undefined): PathAndPackageId | undefined {
if (!resolved) {
return undefined;
}
Debug.assert(extensionIsTS(resolved.extension));
return { fileName: resolved.path, packageId: resolved.packageId };
}
function createResolvedModuleWithFailedLookupLocationsHandlingSymlink(
moduleName: string,
resolved: Resolved | undefined,
isExternalLibraryImport: boolean | undefined,
failedLookupLocations: string[],
affectingLocations: string[],
diagnostics: Diagnostic[],
state: ModuleResolutionState,
cache: ModuleResolutionCache | NonRelativeModuleNameResolutionCache | undefined,
alternateResult?: string,
): ResolvedModuleWithFailedLookupLocations {
// If this is from node_modules for non relative name, always respect preserveSymlinks
if (
!state.resultFromCache &&
!state.compilerOptions.preserveSymlinks &&
resolved &&
isExternalLibraryImport &&
!resolved.originalPath &&
!isExternalModuleNameRelative(moduleName)
) {
const { resolvedFileName, originalPath } = getOriginalAndResolvedFileName(resolved.path, state.host, state.traceEnabled);
if (originalPath) resolved = { ...resolved, path: resolvedFileName, originalPath };
}
return createResolvedModuleWithFailedLookupLocations(
resolved,
isExternalLibraryImport,
failedLookupLocations,
affectingLocations,
diagnostics,
state.resultFromCache,
cache,
alternateResult,
);
}
function createResolvedModuleWithFailedLookupLocations(
resolved: Resolved | undefined,
isExternalLibraryImport: boolean | undefined,
failedLookupLocations: string[],
affectingLocations: string[],
diagnostics: Diagnostic[],
resultFromCache: ResolvedModuleWithFailedLookupLocations | undefined,
cache: ModuleResolutionCache | NonRelativeModuleNameResolutionCache | undefined,
alternateResult?: string,
): ResolvedModuleWithFailedLookupLocations {
if (resultFromCache) {
if (!cache?.isReadonly) {
resultFromCache.failedLookupLocations = updateResolutionField(resultFromCache.failedLookupLocations, failedLookupLocations);
resultFromCache.affectingLocations = updateResolutionField(resultFromCache.affectingLocations, affectingLocations);
resultFromCache.resolutionDiagnostics = updateResolutionField(resultFromCache.resolutionDiagnostics, diagnostics);
return resultFromCache;
}
else {
return {
...resultFromCache,
failedLookupLocations: initializeResolutionFieldForReadonlyCache(resultFromCache.failedLookupLocations, failedLookupLocations),
affectingLocations: initializeResolutionFieldForReadonlyCache(resultFromCache.affectingLocations, affectingLocations),
resolutionDiagnostics: initializeResolutionFieldForReadonlyCache(resultFromCache.resolutionDiagnostics, diagnostics),
};
}
}
return {
resolvedModule: resolved && {
resolvedFileName: resolved.path,
originalPath: resolved.originalPath === true ? undefined : resolved.originalPath,
extension: resolved.extension,
isExternalLibraryImport,
packageId: resolved.packageId,
resolvedUsingTsExtension: !!resolved.resolvedUsingTsExtension,
},
failedLookupLocations: initializeResolutionField(failedLookupLocations),
affectingLocations: initializeResolutionField(affectingLocations),
resolutionDiagnostics: initializeResolutionField(diagnostics),
alternateResult,
};
}
function initializeResolutionField<T>(value: T[]): T[] | undefined {
return value.length ? value : undefined;
}
/** @internal */
export function updateResolutionField<T>(to: T[] | undefined, value: T[] | undefined): T[] | undefined {
if (!value?.length) return to;
if (!to?.length) return value;
to.push(...value);
return to;
}
function initializeResolutionFieldForReadonlyCache<T>(fromCache: T[] | undefined, value: T[]): T[] | undefined {
if (!fromCache?.length) return initializeResolutionField(value);
if (!value.length) return fromCache.slice();
return [...fromCache, ...value];
}
/** @internal */
export interface ModuleResolutionState {
host: ModuleResolutionHost;
compilerOptions: CompilerOptions;
traceEnabled: boolean;
failedLookupLocations: string[] | undefined;
affectingLocations: string[] | undefined;
resultFromCache?: ResolvedModuleWithFailedLookupLocations;
packageJsonInfoCache: PackageJsonInfoCache | undefined;
features: NodeResolutionFeatures;
conditions: readonly string[];
requestContainingDirectory: string | undefined;
reportDiagnostic: DiagnosticReporter;
isConfigLookup: boolean;
candidateIsFromPackageJsonField: boolean;
resolvedPackageDirectory: boolean;
}
/** Just the fields that we use for module resolution.
*
* @internal
*/
export interface PackageJsonPathFields {
typings?: string;
types?: string;
typesVersions?: MapLike<MapLike<string[]>>;
main?: string;
tsconfig?: string;
type?: string;
imports?: object;
exports?: object;
name?: string;
dependencies?: MapLike<string>;
peerDependencies?: MapLike<string>;
optionalDependencies?: MapLike<string>;
}
interface PackageJson extends PackageJsonPathFields {
name?: string;
version?: string;
}
function readPackageJsonField<K extends MatchingKeys<PackageJson, string | undefined>>(jsonContent: PackageJson, fieldName: K, typeOfTag: "string", state: ModuleResolutionState): PackageJson[K] | undefined;
function readPackageJsonField<K extends MatchingKeys<PackageJson, object | undefined>>(jsonContent: PackageJson, fieldName: K, typeOfTag: "object", state: ModuleResolutionState): PackageJson[K] | undefined; // eslint-disable-line @typescript-eslint/unified-signatures
function readPackageJsonField<K extends keyof PackageJson>(jsonContent: PackageJson, fieldName: K, typeOfTag: "string" | "object", state: ModuleResolutionState): PackageJson[K] | undefined {
if (!hasProperty(jsonContent, fieldName)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName);
}
return;
}
const value = jsonContent[fieldName];
if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-restricted-syntax
if (state.traceEnabled) {
// eslint-disable-next-line no-restricted-syntax
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value);
}
return;
}
return value;
}
function readPackageJsonPathField<K extends "typings" | "types" | "main" | "tsconfig">(jsonContent: PackageJson, fieldName: K, baseDirectory: string, state: ModuleResolutionState): PackageJson[K] | undefined {
const fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
if (fileName === undefined) {
return;
}
if (!fileName) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_had_a_falsy_0_field, fieldName);
}
return;
}
const path = normalizePath(combinePaths(baseDirectory, fileName));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
}
return path;
}
function readPackageJsonTypesFields(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) {
return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
|| readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
}
function readPackageJsonTSConfigField(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) {
return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
}
function readPackageJsonMainField(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) {
return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
}
function readPackageJsonTypesVersionsField(jsonContent: PackageJson, state: ModuleResolutionState) {
const typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
if (typesVersions === undefined) return;
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
}
return typesVersions;
}
/** @internal */
export interface VersionPaths {
version: string;
paths: MapLike<string[]>;
}
function readPackageJsonTypesVersionPaths(jsonContent: PackageJson, state: ModuleResolutionState): VersionPaths | undefined {
const typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
if (typesVersions === undefined) return;
if (state.traceEnabled) {
for (const key in typesVersions) {
if (hasProperty(typesVersions, key) && !VersionRange.tryParse(key)) {
trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
}
}
}
const result = getPackageJsonTypesVersionsPaths(typesVersions);
if (!result) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, versionMajorMinor);
}
return;
}
const { version: bestVersionKey, paths: bestVersionPaths } = result;
if (typeof bestVersionPaths !== "object") {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersions['${bestVersionKey}']`, "object", typeof bestVersionPaths);
}
return;
}
return result;
}
let typeScriptVersion: Version | undefined;
/** @internal */
export function getPackageJsonTypesVersionsPaths(typesVersions: MapLike<MapLike<string[]>>): VersionPaths | undefined {
if (!typeScriptVersion) typeScriptVersion = new Version(version);
for (const key in typesVersions) {
if (!hasProperty(typesVersions, key)) continue;
const keyRange = VersionRange.tryParse(key);
if (keyRange === undefined) {
continue;
}
// return the first entry whose range matches the current compiler version.
if (keyRange.test(typeScriptVersion)) {
return { version: key, paths: typesVersions[key] };
}
}
}
export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined {
if (options.typeRoots) {
return options.typeRoots;
}
let currentDirectory: string | undefined;
if (options.configFilePath) {
currentDirectory = getDirectoryPath(options.configFilePath);
}
else if (host.getCurrentDirectory) {
currentDirectory = host.getCurrentDirectory();
}
if (currentDirectory !== undefined) {
return getDefaultTypeRoots(currentDirectory);
}
}
/**
* Returns the path to every node_modules/@types directory from some ancestor directory.
* Returns undefined if there are none.
*/
function getDefaultTypeRoots(currentDirectory: string): string[] | undefined {
let typeRoots: string[] | undefined;
forEachAncestorDirectory(normalizePath(currentDirectory), directory => {
const atTypes = combinePaths(directory, nodeModulesAtTypes);
(typeRoots ??= []).push(atTypes);
});
return typeRoots;
}
const nodeModulesAtTypes = combinePaths("node_modules", "@types");
function arePathsEqual(path1: string, path2: string, host: ModuleResolutionHost): boolean {
const useCaseSensitiveFileNames = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames;
return comparePaths(path1, path2, !useCaseSensitiveFileNames) === Comparison.EqualTo;
}
function getOriginalAndResolvedFileName(fileName: string, host: ModuleResolutionHost, traceEnabled: boolean) {
const resolvedFileName = realPath(fileName, host, traceEnabled);
const pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host);
return {
// If the fileName and realpath are differing only in casing prefer fileName so that we can issue correct errors for casing under forceConsistentCasingInFileNames
resolvedFileName: pathsAreEqual ? fileName : resolvedFileName,
originalPath: pathsAreEqual ? undefined : fileName,
};
}
function getCandidateFromTypeRoot(typeRoot: string, typeReferenceDirectiveName: string, moduleResolutionState: ModuleResolutionState) {
const nameForLookup = endsWith(typeRoot, "/node_modules/@types") || endsWith(typeRoot, "/node_modules/@types/") ?
mangleScopedPackageNameWithTrace(typeReferenceDirectiveName, moduleResolutionState) :
typeReferenceDirectiveName;
return combinePaths(typeRoot, nameForLookup);
}
/**
* @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
* is assumed to be the same as root directory of the project.
*/
export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, cache?: TypeReferenceDirectiveResolutionCache, resolutionMode?: ResolutionMode): ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
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.");
const traceEnabled = isTraceEnabled(options, host);
if (redirectedReference) {
options = redirectedReference.commandLine.options;
}
const containingDirectory = containingFile ? getDirectoryPath(containingFile) : undefined;
let result = containingDirectory ? cache?.getFromDirectoryCache(typeReferenceDirectiveName, resolutionMode, containingDirectory, redirectedReference) : undefined;
if (!result && containingDirectory && !isExternalModuleNameRelative(typeReferenceDirectiveName)) {
result = cache?.getFromNonRelativeNameCache(typeReferenceDirectiveName, resolutionMode, containingDirectory, redirectedReference);
}
if (result) {
if (traceEnabled) {
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile);
if (redirectedReference) trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
trace(host, Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory);
traceResult(result);
}
return result;
}
const typeRoots = getEffectiveTypeRoots(options, host);
if (traceEnabled) {
if (containingFile === undefined) {
if (typeRoots === undefined) {
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
}
else {
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
}
}
else {
if (typeRoots === undefined) {
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
}
else {
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
}
}
if (redirectedReference) {
trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
}
}
const failedLookupLocations: string[] = [];
const affectingLocations: string[] = [];
// Allow type reference directives to opt into `exports` resolution in any resolution mode
// when a `resolution-mode` override is present.
let features = getNodeResolutionFeatures(options);
if (resolutionMode !== undefined) {
features |= NodeResolutionFeatures.AllFeatures;
}
const moduleResolution = getEmitModuleResolutionKind(options);
if (resolutionMode === ModuleKind.ESNext && (ModuleResolutionKind.Node16 <= moduleResolution && moduleResolution <= ModuleResolutionKind.NodeNext)) {
features |= NodeResolutionFeatures.EsmMode;
}
const conditions = (features & NodeResolutionFeatures.Exports)
? getConditions(options, resolutionMode)
: [];
const diagnostics: Diagnostic[] = [];
const moduleResolutionState: ModuleResolutionState = {
compilerOptions: options,
host,
traceEnabled,
failedLookupLocations,
affectingLocations,
packageJsonInfoCache: cache,
features,
conditions,
requestContainingDirectory: containingDirectory,
reportDiagnostic: diag => void diagnostics.push(diag),
isConfigLookup: false,
candidateIsFromPackageJsonField: false,
resolvedPackageDirectory: false,
};
let resolved = primaryLookup();
let primary = true;
if (!resolved) {
resolved = secondaryLookup();
primary = false;
}
let resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined;
if (resolved) {
const { fileName, packageId } = resolved;
let resolvedFileName = fileName, originalPath: string | undefined;
if (!options.preserveSymlinks) ({ resolvedFileName, originalPath } = getOriginalAndResolvedFileName(fileName, host, traceEnabled));
resolvedTypeReferenceDirective = {
primary,
resolvedFileName,
originalPath,
packageId,
isExternalLibraryImport: pathContainsNodeModules(fileName),
};
}
result = {
resolvedTypeReferenceDirective,
failedLookupLocations: initializeResolutionField(failedLookupLocations),
affectingLocations: initializeResolutionField(affectingLocations),
resolutionDiagnostics: initializeResolutionField(diagnostics),
};
if (containingDirectory && cache && !cache.isReadonly) {
cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(typeReferenceDirectiveName, /*mode*/ resolutionMode, result);
if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) {
cache.getOrCreateCacheForNonRelativeName(typeReferenceDirectiveName, resolutionMode, redirectedReference).set(containingDirectory, result);
}
}
if (traceEnabled) traceResult(result);
return result;
function traceResult(result: ResolvedTypeReferenceDirectiveWithFailedLookupLocations) {
if (!result.resolvedTypeReferenceDirective?.resolvedFileName) {
trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
}
else if (result.resolvedTypeReferenceDirective.packageId) {
trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, packageIdToString(result.resolvedTypeReferenceDirective.packageId), result.resolvedTypeReferenceDirective.primary);
}
else {
trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, result.resolvedTypeReferenceDirective.resolvedFileName, result.resolvedTypeReferenceDirective.primary);
}
}
function primaryLookup(): PathAndPackageId | undefined {
// Check primary library paths
if (typeRoots && typeRoots.length) {
if (traceEnabled) {
trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
}
return firstDefined(typeRoots, typeRoot => {
const candidate = getCandidateFromTypeRoot(typeRoot, typeReferenceDirectiveName, moduleResolutionState);
const directoryExists = directoryProbablyExists(typeRoot, host);
if (!directoryExists && traceEnabled) {
trace(host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, typeRoot);
}
if (options.typeRoots) {
// Custom typeRoots resolve as file or directory just like we do modules
const resolvedFromFile = loadModuleFromFile(Extensions.Declaration, candidate, !directoryExists, moduleResolutionState);
if (resolvedFromFile) {
const packageDirectory = parseNodeModuleFromPath(resolvedFromFile.path);
const packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, moduleResolutionState) : undefined;
return resolvedTypeScriptOnly(withPackageId(packageInfo, resolvedFromFile, moduleResolutionState));
}
}
return resolvedTypeScriptOnly(
loadNodeModuleFromDirectory(Extensions.Declaration, candidate, !directoryExists, moduleResolutionState),
);
});
}
else {
if (traceEnabled) {
trace(host, Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
}
}
}
function secondaryLookup(): PathAndPackageId | undefined {
const initialLocationForSecondaryLookup = containingFile && getDirectoryPath(containingFile);
if (initialLocationForSecondaryLookup !== undefined) {
let result: Resolved | undefined;
if (!options.typeRoots || !endsWith(containingFile!, inferredTypesContainingFile)) {
// check secondary locations
if (traceEnabled) {
trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
}
if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) {
const searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.Declaration, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
result = searchResult && searchResult.value;
}
else {
const { path: candidate } = normalizePathForCJSResolution(initialLocationForSecondaryLookup, typeReferenceDirectiveName);
result = nodeLoadModuleByRelativeName(Extensions.Declaration, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
}
}
else if (traceEnabled) {
trace(host, Diagnostics.Resolving_type_reference_directive_for_program_that_specifies_custom_typeRoots_skipping_lookup_in_node_modules_folder);
}
return resolvedTypeScriptOnly(result);
}
else {
if (traceEnabled) {
trace(host, Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
}
}
}
}
function getNodeResolutionFeatures(options: CompilerOptions) {
let features = NodeResolutionFeatures.None;
switch (getEmitModuleResolutionKind(options)) {
case ModuleResolutionKind.Node16:
features = NodeResolutionFeatures.Node16Default;
break;
case ModuleResolutionKind.NodeNext:
features = NodeResolutionFeatures.NodeNextDefault;
break;
case ModuleResolutionKind.Bundler:
features = NodeResolutionFeatures.BundlerDefault;
break;
}
if (options.resolvePackageJsonExports) {
features |= NodeResolutionFeatures.Exports;
}
else if (options.resolvePackageJsonExports === false) {
features &= ~NodeResolutionFeatures.Exports;
}
if (options.resolvePackageJsonImports) {
features |= NodeResolutionFeatures.Imports;
}
else if (options.resolvePackageJsonImports === false) {
features &= ~NodeResolutionFeatures.Imports;
}
return features;
}
/** @internal */
export function getConditions(options: CompilerOptions, resolutionMode?: ResolutionMode): string[] {
const moduleResolution = getEmitModuleResolutionKind(options);
if (resolutionMode === undefined) {
if (moduleResolution === ModuleResolutionKind.Bundler) {
// bundler always uses `import` unless explicitly overridden
resolutionMode = ModuleKind.ESNext;
}
else if (moduleResolution === ModuleResolutionKind.Node10) {
// node10 does not support package.json imports/exports without
// an explicit resolution-mode override on a type-only import
// (indicated by `esmMode` being set)
return [];
}
}
// conditions are only used by the node16/nodenext/bundler resolvers - there's no priority order in the list,
// it's essentially a set (priority is determined by object insertion order in the object we look at).
const conditions = resolutionMode === ModuleKind.ESNext
? ["import"]
: ["require"];
if (!options.noDtsResolution) {
conditions.push("types");
}
if (moduleResolution !== ModuleResolutionKind.Bundler) {
conditions.push("node");
}
return concatenate(conditions, options.customConditions);
}
/**
* @internal
* Does not try `@types/${packageName}` - use a second pass if needed.
*/
export function resolvePackageNameToPackageJson(
packageName: string,
containingDirectory: string,
options: CompilerOptions,
host: ModuleResolutionHost,
cache: ModuleResolutionCache | undefined,
): PackageJsonInfo | undefined {
const moduleResolutionState = getTemporaryModuleResolutionState(cache?.getPackageJsonInfoCache(), host, options);
return forEachAncestorDirectoryStoppingAtGlobalCache(host, containingDirectory, ancestorDirectory => {
if (getBaseFileName(ancestorDirectory) !== "node_modules") {
const nodeModulesFolder = combinePaths(ancestorDirectory, "node_modules");
const candidate = combinePaths(nodeModulesFolder, packageName);
return getPackageJsonInfo(candidate, /*onlyRecordFailures*/ false, moduleResolutionState);
}
});
}
/**
* Given a set of options, returns the set of type directive names
* that should be included for this program automatically.
* This list could either come from the config file,
* or from enumerating the types root + initial secondary types lookup location.
* More type directives might appear in the program later as a result of loading actual source files;
* this list is only the set of defaults that are implicitly included.
*/
export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[] {
// Use explicit type list from tsconfig.json
if (options.types) {
return options.types;
}
// Walk the primary type lookup locations
const result: string[] = [];
if (host.directoryExists && host.getDirectories) {
const typeRoots = getEffectiveTypeRoots(options, host);
if (typeRoots) {
for (const root of typeRoots) {
if (host.directoryExists(root)) {
for (const typeDirectivePath of host.getDirectories(root)) {
const normalized = normalizePath(typeDirectivePath);
const packageJsonPath = combinePaths(root, normalized, "package.json");
// `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
// See `createNotNeededPackageJSON` in the types-publisher` repo.
// eslint-disable-next-line no-restricted-syntax
const isNotNeededPackage = host.fileExists(packageJsonPath) && (readJson(packageJsonPath, host) as PackageJson).typings === null;
if (!isNotNeededPackage) {
const baseFileName = getBaseFileName(normalized);
// At this stage, skip results with leading dot.
if (baseFileName.charCodeAt(0) !== CharacterCodes.dot) {
// Return just the type directive names
result.push(baseFileName);
}
}
}
}
}
}
}
return result;
}
export interface TypeReferenceDirectiveResolutionCache extends PerDirectoryResolutionCache<ResolvedTypeReferenceDirectiveWithFailedLookupLocations>, NonRelativeNameResolutionCache<ResolvedTypeReferenceDirectiveWithFailedLookupLocations>, PackageJsonInfoCache {
/** @internal */ clearAllExceptPackageJsonInfoCache(): void;
}
export interface ModeAwareCache<T> {
get(key: string, mode: ResolutionMode): T | undefined;
set(key: string, mode: ResolutionMode, value: T): this;
delete(key: string, mode: ResolutionMode): this;
has(key: string, mode: ResolutionMode): boolean;
forEach(cb: (elem: T, key: string, mode: ResolutionMode) => void): void;
size(): number;
}
/**
* Cached resolutions per containing directory.
* This assumes that any module id will have the same resolution for sibling files located in the same folder.
*/
export interface PerDirectoryResolutionCache<T> {
getFromDirectoryCache(name: string, mode: ResolutionMode, directoryName: string, redirectedReference: ResolvedProjectReference | undefined): T | undefined;
getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): ModeAwareCache<T>;
clear(): void;
/**
* Updates with the current compilerOptions the cache will operate with.
* This updates the redirects map as well if needed so module resolutions are cached if they can across the projects
*/
update(options: CompilerOptions): void;
/** @internal */ directoryToModuleNameMap: CacheWithRedirects<Path, ModeAwareCache<T>>;
/** @internal */ isReadonly?: boolean;
}
export interface NonRelativeNameResolutionCache<T> {
getFromNonRelativeNameCache(nonRelativeName: string, mode: ResolutionMode, directoryName: string, redirectedReference: ResolvedProjectReference | undefined): T | undefined;
getOrCreateCacheForNonRelativeName(nonRelativeName: string, mode: ResolutionMode, redirectedReference?: ResolvedProjectReference): PerNonRelativeNameCache<T>;
clear(): void;
/**
* Updates with the current compilerOptions the cache will operate with.
* This updates the redirects map as well if needed so module resolutions are cached if they can across the projects
*/
update(options: CompilerOptions): void;
/** @internal */ isReadonly?: boolean;
}
export interface PerNonRelativeNameCache<T> {
get(directory: string): T | undefined;
set(directory: string, result: T): void;
/** @internal */ isReadonly?: boolean;
}
export interface ModuleResolutionCache extends PerDirectoryResolutionCache<ResolvedModuleWithFailedLookupLocations>, NonRelativeModuleNameResolutionCache, PackageJsonInfoCache {
getPackageJsonInfoCache(): PackageJsonInfoCache;
/** @internal */ clearAllExceptPackageJsonInfoCache(): void;
/** @internal */ optionsToRedirectsKey: Map<CompilerOptions, RedirectsCacheKey>;
}
/**
* Stored map from non-relative module name to a table: directory -> result of module lookup in this directory
* We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive.
*/
export interface NonRelativeModuleNameResolutionCache extends NonRelativeNameResolutionCache<ResolvedModuleWithFailedLookupLocations>, PackageJsonInfoCache {
/** @deprecated Use getOrCreateCacheForNonRelativeName */
getOrCreateCacheForModuleName(nonRelativeModuleName: string, mode: ResolutionMode, redirectedReference?: ResolvedProjectReference): PerModuleNameCache;
}
/** @internal */
export interface MissingPackageJsonInfo {
packageDirectory: string;
directoryExists: boolean;
}
/** @internal */
export type PackageJsonInfoCacheEntry = PackageJsonInfo | MissingPackageJsonInfo;
/** @internal */
export function isPackageJsonInfo(entry: PackageJsonInfoCacheEntry | undefined): entry is PackageJsonInfo {
return !!(entry as PackageJsonInfo | undefined)?.contents;
}
/** @internal */
export function isMissingPackageJsonInfo(entry: PackageJsonInfoCacheEntry | undefined): entry is MissingPackageJsonInfo {
return !!entry && !(entry as PackageJsonInfo).contents;
}
export interface PackageJsonInfoCache {
/** @internal */ getPackageJsonInfo(packageJsonPath: string): PackageJsonInfoCacheEntry | undefined;
/** @internal */ setPackageJsonInfo(packageJsonPath: string, info: PackageJsonInfoCacheEntry): void;
/** @internal */ getInternalMap(): Map<Path, PackageJsonInfoCacheEntry> | undefined;
clear(): void;
/** @internal */ isReadonly?: boolean;
}
export type PerModuleNameCache = PerNonRelativeNameCache<ResolvedModuleWithFailedLookupLocations>;
function compilerOptionValueToString(value: unknown): string {
if (value === null || typeof value !== "object") { // eslint-disable-line no-restricted-syntax
return "" + value;
}
if (isArray(value)) {
return `[${value.map(e => compilerOptionValueToString(e))?.join(",")}]`;
}
let str = "{";
for (const key in value) {
if (hasProperty(value, key)) {
str += `${key}: ${compilerOptionValueToString((value as any)[key])}`;
}
}
return str + "}";
}
/** @internal */
export function getKeyForCompilerOptions(options: CompilerOptions, affectingOptionDeclarations: readonly CommandLineOption[]): string {
return affectingOptionDeclarations.map(option => compilerOptionValueToString(getCompilerOptionValue(options, option))).join("|") + `|${options.pathsBasePath}`;
}
/** @internal */
export interface CacheWithRedirects<K, V> {
getMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined): Map<K, V> | undefined;
getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined): Map<K, V>;
update(newOptions: CompilerOptions): void;
clear(): void;
getOwnMap(): Map<K, V>;
}
/** @internal */
export type RedirectsCacheKey = string & { __compilerOptionsKey: any; };
function createCacheWithRedirects<K, V>(ownOptions: CompilerOptions | undefined, optionsToRedirectsKey: Map<CompilerOptions, RedirectsCacheKey>): CacheWithRedirects<K, V> {
const redirectsMap = new Map<CompilerOptions, Map<K, V>>();
const redirectsKeyToMap = new Map<RedirectsCacheKey, Map<K, V>>();
let ownMap = new Map<K, V>();
if (ownOptions) redirectsMap.set(ownOptions, ownMap);
return {
getMapOfCacheRedirects,
getOrCreateMapOfCacheRedirects,
update,
clear,
getOwnMap: () => ownMap,
};
function getMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined): Map<K, V> | undefined {
return redirectedReference ?
getOrCreateMap(redirectedReference.commandLine.options, /*create*/ false) :
ownMap;
}
function getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined): Map<K, V> {
return redirectedReference ?
getOrCreateMap(redirectedReference.commandLine.options, /*create*/ true) :
ownMap;
}
function update(newOptions: CompilerOptions) {
if (ownOptions !== newOptions) {
if (ownOptions) ownMap = getOrCreateMap(newOptions, /*create*/ true); // set new map for new options as ownMap
else redirectsMap.set(newOptions, ownMap); // Use existing map if oldOptions = undefined