-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
Copy pathmoduleSpecifiers.ts
959 lines (887 loc) · 54.4 KB
/
moduleSpecifiers.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
// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
/* @internal */
namespace ts.moduleSpecifiers {
const enum RelativePreference { Relative, NonRelative, Shortest, ExternalNonRelative }
// See UserPreferences#importPathEnding
const enum Ending { Minimal, Index, JsExtension }
// Processed preferences
interface Preferences {
readonly relativePreference: RelativePreference;
readonly ending: Ending;
}
function getPreferences(host: ts.ModuleSpecifierResolutionHost, { importModuleSpecifierPreference, importModuleSpecifierEnding }: ts.UserPreferences, compilerOptions: ts.CompilerOptions, importingSourceFile: ts.SourceFile): Preferences {
return {
relativePreference:
importModuleSpecifierPreference === "relative" ? RelativePreference.Relative :
importModuleSpecifierPreference === "non-relative" ? RelativePreference.NonRelative :
importModuleSpecifierPreference === "project-relative" ? RelativePreference.ExternalNonRelative :
RelativePreference.Shortest,
ending: getEnding(),
};
function getEnding(): Ending {
switch (importModuleSpecifierEnding) {
case "minimal": return Ending.Minimal;
case "index": return Ending.Index;
case "js": return Ending.JsExtension;
default: return usesJsExtensionOnImports(importingSourceFile) || isFormatRequiringExtensions(compilerOptions, importingSourceFile.path, host) ? Ending.JsExtension
: ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? Ending.Index : Ending.Minimal;
}
}
}
function getPreferencesForUpdate(compilerOptions: ts.CompilerOptions, oldImportSpecifier: string, importingSourceFileName: ts.Path, host: ts.ModuleSpecifierResolutionHost): Preferences {
return {
relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? RelativePreference.Relative : RelativePreference.NonRelative,
ending: ts.hasJSFileExtension(oldImportSpecifier) || isFormatRequiringExtensions(compilerOptions, importingSourceFileName, host) ?
Ending.JsExtension :
ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? Ending.Index : Ending.Minimal,
};
}
function isFormatRequiringExtensions(compilerOptions: ts.CompilerOptions, importingSourceFileName: ts.Path, host: ts.ModuleSpecifierResolutionHost) {
if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node16
&& ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) {
return false;
}
return ts.getImpliedNodeFormatForFile(importingSourceFileName, host.getPackageJsonInfoCache?.(), getModuleResolutionHost(host), compilerOptions) !== ts.ModuleKind.CommonJS;
}
function getModuleResolutionHost(host: ts.ModuleSpecifierResolutionHost): ts.ModuleResolutionHost {
return {
fileExists: host.fileExists,
readFile: ts.Debug.checkDefined(host.readFile),
directoryExists: host.directoryExists,
getCurrentDirectory: host.getCurrentDirectory,
realpath: host.realpath,
useCaseSensitiveFileNames: host.useCaseSensitiveFileNames?.(),
};
}
// `importingSourceFile` and `importingSourceFileName`? Why not just use `importingSourceFile.path`?
// Because when this is called by the file renamer, `importingSourceFile` is the file being renamed,
// while `importingSourceFileName` its *new* name. We need a source file just to get its
// `impliedNodeFormat` and to detect certain preferences from existing import module specifiers.
export function updateModuleSpecifier(
compilerOptions: ts.CompilerOptions,
importingSourceFile: ts.SourceFile,
importingSourceFileName: ts.Path,
toFileName: string,
host: ts.ModuleSpecifierResolutionHost,
oldImportSpecifier: string,
options: ts.ModuleSpecifierOptions = {},
): string | undefined {
const res = getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier, importingSourceFileName, host), {}, options);
if (res === oldImportSpecifier) return undefined;
return res;
}
// `importingSourceFile` and `importingSourceFileName`? Why not just use `importingSourceFile.path`?
// Because when this is called by the declaration emitter, `importingSourceFile` is the implementation
// file, but `importingSourceFileName` and `toFileName` refer to declaration files (the former to the
// one currently being produced; the latter to the one being imported). We need an implementation file
// just to get its `impliedNodeFormat` and to detect certain preferences from existing import module
// specifiers.
export function getModuleSpecifier(
compilerOptions: ts.CompilerOptions,
importingSourceFile: ts.SourceFile,
importingSourceFileName: ts.Path,
toFileName: string,
host: ts.ModuleSpecifierResolutionHost,
options: ts.ModuleSpecifierOptions = {},
): string {
return getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getPreferences(host, {}, compilerOptions, importingSourceFile), {}, options);
}
export function getNodeModulesPackageName(
compilerOptions: ts.CompilerOptions,
importingSourceFile: ts.SourceFile,
nodeModulesFileName: string,
host: ts.ModuleSpecifierResolutionHost,
preferences: ts.UserPreferences,
options: ts.ModuleSpecifierOptions = {},
): string | undefined {
const info = getInfo(importingSourceFile.path, host);
const modulePaths = getAllModulePaths(importingSourceFile.path, nodeModulesFileName, host, preferences, options);
return ts.firstDefined(modulePaths,
modulePath => tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, preferences, /*packageNameOnly*/ true, options.overrideImportMode));
}
function getModuleSpecifierWorker(
compilerOptions: ts.CompilerOptions,
importingSourceFile: ts.SourceFile,
importingSourceFileName: ts.Path,
toFileName: string,
host: ts.ModuleSpecifierResolutionHost,
preferences: Preferences,
userPreferences: ts.UserPreferences,
options: ts.ModuleSpecifierOptions = {}
): string {
const info = getInfo(importingSourceFileName, host);
const modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences, options);
return ts.firstDefined(modulePaths, modulePath => tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode)) ||
getLocalModuleSpecifier(toFileName, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences);
}
export function tryGetModuleSpecifiersFromCache(
moduleSymbol: ts.Symbol,
importingSourceFile: ts.SourceFile,
host: ts.ModuleSpecifierResolutionHost,
userPreferences: ts.UserPreferences,
options: ts.ModuleSpecifierOptions = {},
): readonly string[] | undefined {
return tryGetModuleSpecifiersFromCacheWorker(
moduleSymbol,
importingSourceFile,
host,
userPreferences,
options)[0];
}
function tryGetModuleSpecifiersFromCacheWorker(
moduleSymbol: ts.Symbol,
importingSourceFile: ts.SourceFile,
host: ts.ModuleSpecifierResolutionHost,
userPreferences: ts.UserPreferences,
options: ts.ModuleSpecifierOptions = {},
): readonly [specifiers?: readonly string[], moduleFile?: ts.SourceFile, modulePaths?: readonly ts.ModulePath[], cache?: ts.ModuleSpecifierCache] {
const moduleSourceFile = ts.getSourceFileOfModule(moduleSymbol);
if (!moduleSourceFile) {
return ts.emptyArray as [];
}
const cache = host.getModuleSpecifierCache?.();
const cached = cache?.get(importingSourceFile.path, moduleSourceFile.path, userPreferences, options);
return [cached?.moduleSpecifiers, moduleSourceFile, cached?.modulePaths, cache];
}
/** Returns an import for each symlink and for the realpath. */
export function getModuleSpecifiers(
moduleSymbol: ts.Symbol,
checker: ts.TypeChecker,
compilerOptions: ts.CompilerOptions,
importingSourceFile: ts.SourceFile,
host: ts.ModuleSpecifierResolutionHost,
userPreferences: ts.UserPreferences,
options: ts.ModuleSpecifierOptions = {},
): readonly string[] {
return getModuleSpecifiersWithCacheInfo(
moduleSymbol,
checker,
compilerOptions,
importingSourceFile,
host,
userPreferences,
options
).moduleSpecifiers;
}
export function getModuleSpecifiersWithCacheInfo(
moduleSymbol: ts.Symbol,
checker: ts.TypeChecker,
compilerOptions: ts.CompilerOptions,
importingSourceFile: ts.SourceFile,
host: ts.ModuleSpecifierResolutionHost,
userPreferences: ts.UserPreferences,
options: ts.ModuleSpecifierOptions = {},
): { moduleSpecifiers: readonly string[], computedWithoutCache: boolean } {
let computedWithoutCache = false;
const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker);
if (ambient) return { moduleSpecifiers: [ambient], computedWithoutCache };
// eslint-disable-next-line prefer-const
let [specifiers, moduleSourceFile, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker(
moduleSymbol,
importingSourceFile,
host,
userPreferences,
options
);
if (specifiers) return { moduleSpecifiers: specifiers, computedWithoutCache };
if (!moduleSourceFile) return { moduleSpecifiers: ts.emptyArray, computedWithoutCache };
computedWithoutCache = true;
modulePaths ||= getAllModulePathsWorker(importingSourceFile.path, moduleSourceFile.originalFileName, host);
const result = computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences, options);
cache?.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, options, modulePaths, result);
return { moduleSpecifiers: result, computedWithoutCache };
}
function computeModuleSpecifiers(
modulePaths: readonly ts.ModulePath[],
compilerOptions: ts.CompilerOptions,
importingSourceFile: ts.SourceFile,
host: ts.ModuleSpecifierResolutionHost,
userPreferences: ts.UserPreferences,
options: ts.ModuleSpecifierOptions = {},
): readonly string[] {
const info = getInfo(importingSourceFile.path, host);
const preferences = getPreferences(host, userPreferences, compilerOptions, importingSourceFile);
const existingSpecifier = ts.forEach(modulePaths, modulePath => ts.forEach(
host.getFileIncludeReasons().get(ts.toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)),
reason => {
if (reason.kind !== ts.FileIncludeKind.Import || reason.file !== importingSourceFile.path) return undefined;
// If the candidate import mode doesn't match the mode we're generating for, don't consider it
// TODO: maybe useful to keep around as an alternative option for certain contexts where the mode is overridable
if (importingSourceFile.impliedNodeFormat && importingSourceFile.impliedNodeFormat !== ts.getModeForResolutionAtIndex(importingSourceFile, reason.index)) return undefined;
const specifier = ts.getModuleNameStringLiteralAt(importingSourceFile, reason.index).text;
// If the preference is for non relative and the module specifier is relative, ignore it
return preferences.relativePreference !== RelativePreference.NonRelative || !ts.pathIsRelative(specifier) ?
specifier :
undefined;
}
));
if (existingSpecifier) {
const moduleSpecifiers = [existingSpecifier];
return moduleSpecifiers;
}
const importedFileIsInNodeModules = ts.some(modulePaths, p => p.isInNodeModules);
// Module specifier priority:
// 1. "Bare package specifiers" (e.g. "@foo/bar") resulting from a path through node_modules to a package.json's "types" entry
// 2. Specifiers generated using "paths" from tsconfig
// 3. Non-relative specfiers resulting from a path through node_modules (e.g. "@foo/bar/path/to/file")
// 4. Relative paths
let nodeModulesSpecifiers: string[] | undefined;
let pathsSpecifiers: string[] | undefined;
let relativeSpecifiers: string[] | undefined;
for (const modulePath of modulePaths) {
const specifier = tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode);
nodeModulesSpecifiers = ts.append(nodeModulesSpecifiers, specifier);
if (specifier && modulePath.isRedirect) {
// If we got a specifier for a redirect, it was a bare package specifier (e.g. "@foo/bar",
// not "@foo/bar/path/to/file"). No other specifier will be this good, so stop looking.
return nodeModulesSpecifiers!;
}
if (!specifier && !modulePath.isRedirect) {
const local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences);
if (ts.pathIsBareSpecifier(local)) {
pathsSpecifiers = ts.append(pathsSpecifiers, local);
}
else if (!importedFileIsInNodeModules || modulePath.isInNodeModules) {
// Why this extra conditional, not just an `else`? If some path to the file contained
// 'node_modules', but we can't create a non-relative specifier (e.g. "@foo/bar/path/to/file"),
// that means we had to go through a *sibling's* node_modules, not one we can access directly.
// If some path to the file was in node_modules but another was not, this likely indicates that
// we have a monorepo structure with symlinks. In this case, the non-node_modules path is
// probably the realpath, e.g. "../bar/path/to/file", but a relative path to another package
// in a monorepo is probably not portable. So, the module specifier we actually go with will be
// the relative path through node_modules, so that the declaration emitter can produce a
// portability error. (See declarationEmitReexportedSymlinkReference3)
relativeSpecifiers = ts.append(relativeSpecifiers, local);
}
}
}
return pathsSpecifiers?.length ? pathsSpecifiers :
nodeModulesSpecifiers?.length ? nodeModulesSpecifiers :
ts.Debug.checkDefined(relativeSpecifiers);
}
interface Info {
readonly getCanonicalFileName: ts.GetCanonicalFileName;
readonly importingSourceFileName: ts.Path
readonly sourceDirectory: ts.Path;
}
// importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
function getInfo(importingSourceFileName: ts.Path, host: ts.ModuleSpecifierResolutionHost): Info {
const getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
const sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
return { getCanonicalFileName, importingSourceFileName, sourceDirectory };
}
function getLocalModuleSpecifier(moduleFileName: string, info: Info, compilerOptions: ts.CompilerOptions, host: ts.ModuleSpecifierResolutionHost, importMode: ts.SourceFile["impliedNodeFormat"], { ending, relativePreference }: Preferences): string {
const { baseUrl, paths, rootDirs } = compilerOptions;
const { sourceDirectory, getCanonicalFileName } = info;
const relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
if (!baseUrl && !paths || relativePreference === RelativePreference.Relative) {
return relativePath;
}
const baseDirectory = ts.getNormalizedAbsolutePath(ts.getPathsBasePath(compilerOptions, host) || baseUrl!, host.getCurrentDirectory());
const relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName);
if (!relativeToBaseUrl) {
return relativePath;
}
const fromPaths = paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, getAllowedEndings(ending, compilerOptions, importMode), host, compilerOptions);
const nonRelative = fromPaths === undefined && baseUrl !== undefined ? removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions) : fromPaths;
if (!nonRelative) {
return relativePath;
}
if (relativePreference === RelativePreference.NonRelative) {
return nonRelative;
}
if (relativePreference === RelativePreference.ExternalNonRelative) {
const projectDirectory = compilerOptions.configFilePath ?
ts.toPath(ts.getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) :
info.getCanonicalFileName(host.getCurrentDirectory());
const modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName);
const sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory);
const targetIsInternal = ts.startsWith(modulePath, projectDirectory);
if (sourceIsInternal && !targetIsInternal || !sourceIsInternal && targetIsInternal) {
// 1. The import path crosses the boundary of the tsconfig.json-containing directory.
//
// src/
// tsconfig.json
// index.ts -------
// lib/ | (path crosses tsconfig.json)
// imported.ts <---
//
return nonRelative;
}
const nearestTargetPackageJson = getNearestAncestorDirectoryWithPackageJson(host, ts.getDirectoryPath(modulePath));
const nearestSourcePackageJson = getNearestAncestorDirectoryWithPackageJson(host, sourceDirectory);
if (nearestSourcePackageJson !== nearestTargetPackageJson) {
// 2. The importing and imported files are part of different packages.
//
// packages/a/
// package.json
// index.ts --------
// packages/b/ | (path crosses package.json)
// package.json |
// component.ts <---
//
return nonRelative;
}
return relativePath;
}
if (relativePreference !== RelativePreference.Shortest) ts.Debug.assertNever(relativePreference);
// Prefer a relative import over a baseUrl import if it has fewer components.
return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
}
export function countPathComponents(path: string): number {
let count = 0;
for (let i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
if (path.charCodeAt(i) === ts.CharacterCodes.slash) count++;
}
return count;
}
function usesJsExtensionOnImports({ imports }: ts.SourceFile): boolean {
return ts.firstDefined(imports, ({ text }) => ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined) || false;
}
function comparePathsByRedirectAndNumberOfDirectorySeparators(a: ts.ModulePath, b: ts.ModulePath) {
return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path);
}
function getNearestAncestorDirectoryWithPackageJson(host: ts.ModuleSpecifierResolutionHost, fileName: string) {
if (host.getNearestAncestorDirectoryWithPackageJson) {
return host.getNearestAncestorDirectoryWithPackageJson(fileName);
}
return !!ts.forEachAncestorDirectory(fileName, directory => {
return host.fileExists(ts.combinePaths(directory, "package.json")) ? true : undefined;
});
}
export function forEachFileNameOfModule<T>(
importingFileName: string,
importedFileName: string,
host: ts.ModuleSpecifierResolutionHost,
preferSymlinks: boolean,
cb: (fileName: string, isRedirect: boolean) => T | undefined
): T | undefined {
const getCanonicalFileName = ts.hostGetCanonicalFileName(host);
const cwd = host.getCurrentDirectory();
const referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
const importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName);
const redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray;
const importedFileNames = [...(referenceRedirect ? [referenceRedirect] : ts.emptyArray), importedFileName, ...redirects];
const targets = importedFileNames.map(f => ts.getNormalizedAbsolutePath(f, cwd));
let shouldFilterIgnoredPaths = !ts.every(targets, ts.containsIgnoredPath);
if (!preferSymlinks) {
// Symlinks inside ignored paths are already filtered out of the symlink cache,
// so we only need to remove them from the realpath filenames.
const result = ts.forEach(targets, p => !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p));
if (result) return result;
}
const symlinkedDirectories = host.getSymlinkCache?.().getSymlinkedDirectoriesByRealpath();
const fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd);
const result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), realPathDirectory => {
const symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName)));
if (!symlinkDirectories) return undefined; // Continue to ancestor directory
// Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts)
if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) {
return false; // Stop search, each ancestor directory will also hit this condition
}
return ts.forEach(targets, target => {
if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) {
return;
}
const relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName);
for (const symlinkDirectory of symlinkDirectories) {
const option = ts.resolvePath(symlinkDirectory, relative);
const result = cb(option, target === referenceRedirect);
shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths
if (result) return result;
}
});
});
return result || (preferSymlinks
? ts.forEach(targets, p => shouldFilterIgnoredPaths && ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect))
: undefined);
}
/**
* Looks for existing imports that use symlinks to this module.
* Symlinks will be returned first so they are preferred over the real path.
*/
function getAllModulePaths(
importingFilePath: ts.Path,
importedFileName: string,
host: ts.ModuleSpecifierResolutionHost,
preferences: ts.UserPreferences,
options: ts.ModuleSpecifierOptions = {},
) {
const importedFilePath = ts.toPath(importedFileName, host.getCurrentDirectory(), ts.hostGetCanonicalFileName(host));
const cache = host.getModuleSpecifierCache?.();
if (cache) {
const cached = cache.get(importingFilePath, importedFilePath, preferences, options);
if (cached?.modulePaths) return cached.modulePaths;
}
const modulePaths = getAllModulePathsWorker(importingFilePath, importedFileName, host);
if (cache) {
cache.setModulePaths(importingFilePath, importedFilePath, preferences, options, modulePaths);
}
return modulePaths;
}
function getAllModulePathsWorker(importingFileName: ts.Path, importedFileName: string, host: ts.ModuleSpecifierResolutionHost): readonly ts.ModulePath[] {
const getCanonicalFileName = ts.hostGetCanonicalFileName(host);
const allFileNames = new ts.Map<string, { path: string, isRedirect: boolean, isInNodeModules: boolean }>();
let importedFileFromNodeModules = false;
forEachFileNameOfModule(
importingFileName,
importedFileName,
host,
/*preferSymlinks*/ true,
(path, isRedirect) => {
const isInNodeModules = ts.pathContainsNodeModules(path);
allFileNames.set(path, { path: getCanonicalFileName(path), isRedirect, isInNodeModules });
importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules;
// don't return value, so we collect everything
}
);
// Sort by paths closest to importing file Name directory
const sortedPaths: ts.ModulePath[] = [];
for (
let directory = ts.getDirectoryPath(importingFileName);
allFileNames.size !== 0;
) {
const directoryStart = ts.ensureTrailingDirectorySeparator(directory);
let pathsInDirectory: ts.ModulePath[] | undefined;
allFileNames.forEach(({ path, isRedirect, isInNodeModules }, fileName) => {
if (ts.startsWith(path, directoryStart)) {
(pathsInDirectory ||= []).push({ path: fileName, isRedirect, isInNodeModules });
allFileNames.delete(fileName);
}
});
if (pathsInDirectory) {
if (pathsInDirectory.length > 1) {
pathsInDirectory.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
}
sortedPaths.push(...pathsInDirectory);
}
const newDirectory = ts.getDirectoryPath(directory);
if (newDirectory === directory) break;
directory = newDirectory;
}
if (allFileNames.size) {
const remainingPaths = ts.arrayFrom(allFileNames.values());
if (remainingPaths.length > 1) remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
sortedPaths.push(...remainingPaths);
}
return sortedPaths;
}
function tryGetModuleNameFromAmbientModule(moduleSymbol: ts.Symbol, checker: ts.TypeChecker): string | undefined {
const decl = moduleSymbol.declarations?.find(
d => ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name)))
) as (ts.ModuleDeclaration & { name: ts.StringLiteral }) | undefined;
if (decl) {
return decl.name.text;
}
// the module could be a namespace, which is export through "export=" from an ambient module.
/**
* declare module "m" {
* namespace ns {
* class c {}
* }
* export = ns;
* }
*/
// `import {c} from "m";` is valid, in which case, `moduleSymbol` is "ns", but the module name should be "m"
const ambientModuleDeclareCandidates = ts.mapDefined(moduleSymbol.declarations,
d => {
if (!ts.isModuleDeclaration(d)) return;
const topNamespace = getTopNamespace(d);
if (!(topNamespace?.parent?.parent
&& ts.isModuleBlock(topNamespace.parent) && ts.isAmbientModule(topNamespace.parent.parent) && ts.isSourceFile(topNamespace.parent.parent.parent))) return;
const exportAssignment = ((topNamespace.parent.parent.symbol.exports?.get("export=" as ts.__String)?.valueDeclaration as ts.ExportAssignment)?.expression as ts.PropertyAccessExpression | ts.Identifier);
if (!exportAssignment) return;
const exportSymbol = checker.getSymbolAtLocation(exportAssignment);
if (!exportSymbol) return;
const originalExportSymbol = exportSymbol?.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(exportSymbol) : exportSymbol;
if (originalExportSymbol === d.symbol) return topNamespace.parent.parent;
function getTopNamespace(namespaceDeclaration: ts.ModuleDeclaration) {
while (namespaceDeclaration.flags & ts.NodeFlags.NestedNamespace) {
namespaceDeclaration = namespaceDeclaration.parent as ts.ModuleDeclaration;
}
return namespaceDeclaration;
}
}
);
const ambientModuleDeclare = ambientModuleDeclareCandidates[0] as (ts.AmbientModuleDeclaration & { name: ts.StringLiteral }) | undefined;
if (ambientModuleDeclare) {
return ambientModuleDeclare.name.text;
}
}
function getAllowedEndings(preferredEnding: Ending, compilerOptions: ts.CompilerOptions, importMode: ts.SourceFile["impliedNodeFormat"]) {
if (ts.getEmitModuleResolutionKind(compilerOptions) >= ts.ModuleResolutionKind.Node16 && importMode === ts.ModuleKind.ESNext) {
return [Ending.JsExtension];
}
switch (preferredEnding) {
case Ending.JsExtension: return [Ending.JsExtension, Ending.Minimal, Ending.Index];
case Ending.Index: return [Ending.Index, Ending.Minimal, Ending.JsExtension];
case Ending.Minimal: return [Ending.Minimal, Ending.Index, Ending.JsExtension];
default: ts.Debug.assertNever(preferredEnding);
}
}
function tryGetModuleNameFromPaths(relativeToBaseUrl: string, paths: ts.MapLike<readonly string[]>, allowedEndings: Ending[], host: ts.ModuleSpecifierResolutionHost, compilerOptions: ts.CompilerOptions): string | undefined {
for (const key in paths) {
for (const patternText of paths[key]) {
const pattern = ts.normalizePath(patternText);
const indexOfStar = pattern.indexOf("*");
// In module resolution, if `pattern` itself has an extension, a file with that extension is looked up directly,
// meaning a '.ts' or '.d.ts' extension is allowed to resolve. This is distinct from the case where a '*' substitution
// causes a module specifier to have an extension, i.e. the extension comes from the module specifier in a JS/TS file
// and matches the '*'. For example:
//
// Module Specifier | Path Mapping (key: [pattern]) | Interpolation | Resolution Action
// ---------------------->------------------------------->--------------------->---------------------------------------------------------------
// import "@app/foo" -> "@app/*": ["./src/app/*.ts"] -> "./src/app/foo.ts" -> tryFile("./src/app/foo.ts") || [continue resolution algorithm]
// import "@app/foo.ts" -> "@app/*": ["./src/app/*"] -> "./src/app/foo.ts" -> [continue resolution algorithm]
//
// (https://github.com/microsoft/TypeScript/blob/ad4ded80e1d58f0bf36ac16bea71bc10d9f09895/src/compiler/moduleNameResolver.ts#L2509-L2516)
//
// The interpolation produced by both scenarios is identical, but only in the former, where the extension is encoded in
// the path mapping rather than in the module specifier, will we prioritize a file lookup on the interpolation result.
// (In fact, currently, the latter scenario will necessarily fail since no resolution mode recognizes '.ts' as a valid
// extension for a module specifier.)
//
// Here, this means we need to be careful about whether we generate a match from the target filename (typically with a
// .ts extension) or the possible relative module specifiers representing that file:
//
// Filename | Relative Module Specifier Candidates | Path Mapping | Filename Result | Module Specifier Results
// --------------------<----------------------------------------------<------------------------------<-------------------||----------------------------
// dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*.d.ts"] <- @app/haha || (none)
// dist/haha.d.ts <- dist/haha, dist/haha.js <- "@app/*": ["./dist/*"] <- (none) || @app/haha, @app/haha.js
// dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*.d.ts"] <- @app/foo/index || (none)
// dist/foo/index.d.ts <- dist/foo, dist/foo/index, dist/foo/index.js <- "@app/*": ["./dist/*"] <- (none) || @app/foo, @app/foo/index, @app/foo/index.js
// dist/wow.js.js <- dist/wow.js, dist/wow.js.js <- "@app/*": ["./dist/*.js"] <- @app/wow.js || @app/wow, @app/wow.js
//
// The "Filename Result" can be generated only if `pattern` has an extension. Care must be taken that the list of
// relative module specifiers to run the interpolation (a) is actually valid for the module resolution mode, (b) takes
// into account the existence of other files (e.g. 'dist/wow.js' cannot refer to 'dist/wow.js.js' if 'dist/wow.js'
// exists) and (c) that they are ordered by preference. The last row shows that the filename result and module
// specifier results are not mutually exclusive. Note that the filename result is a higher priority in module
// resolution, but as long criteria (b) above is met, I don't think its result needs to be the highest priority result
// in module specifier generation. I have included it last, as it's difficult to tell exactly where it should be
// sorted among the others for a particular value of `importModuleSpecifierEnding`.
const candidates: { ending: Ending | undefined, value: string }[] = allowedEndings.map(ending => ({
ending,
value: removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions)
}));
if (ts.tryGetExtensionFromPath(pattern)) {
candidates.push({ ending: undefined, value: relativeToBaseUrl });
}
if (indexOfStar !== -1) {
const prefix = pattern.substring(0, indexOfStar);
const suffix = pattern.substring(indexOfStar + 1);
for (const { ending, value } of candidates) {
if (value.length >= prefix.length + suffix.length &&
ts.startsWith(value, prefix) &&
ts.endsWith(value, suffix) &&
validateEnding({ ending, value })
) {
const matchedStar = value.substring(prefix.length, value.length - suffix.length);
return key.replace("*", matchedStar);
}
}
}
else if (
ts.some(candidates, c => c.ending !== Ending.Minimal && pattern === c.value) ||
ts.some(candidates, c => c.ending === Ending.Minimal && pattern === c.value && validateEnding(c))
) {
return key;
}
}
}
function validateEnding({ ending, value }: { ending: Ending | undefined, value: string }) {
// Optimization: `removeExtensionAndIndexPostFix` can query the file system (a good bit) if `ending` is `Minimal`, the basename
// is 'index', and a `host` is provided. To avoid that until it's unavoidable, we ran the function with no `host` above. Only
// here, after we've checked that the minimal ending is indeed a match (via the length and prefix/suffix checks / `some` calls),
// do we check that the host-validated result is consistent with the answer we got before. If it's not, it falls back to the
// `Ending.Index` result, which should already be in the list of candidates if `Minimal` was. (Note: the assumption here is
// that every module resolution mode that supports dropping extensions also supports dropping `/index`. Like literally
// everything else in this file, this logic needs to be updated if that's not true in some future module resolution mode.)
return ending !== Ending.Minimal || value === removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions, host);
}
}
const enum MatchingMode {
Exact,
Directory,
Pattern
}
function tryGetModuleNameFromExports(options: ts.CompilerOptions, targetFilePath: string, packageDirectory: string, packageName: string, exports: unknown, conditions: string[], mode = MatchingMode.Exact): { moduleFileToTry: string } | undefined {
if (typeof exports === "string") {
const pathOrPattern = ts.getNormalizedAbsolutePath(ts.combinePaths(packageDirectory, exports), /*currentDirectory*/ undefined);
const extensionSwappedTarget = ts.hasTSFileExtension(targetFilePath) ? ts.removeFileExtension(targetFilePath) + tryGetJSExtensionForFile(targetFilePath, options) : undefined;
switch (mode) {
case MatchingMode.Exact:
if (ts.comparePaths(targetFilePath, pathOrPattern) === ts.Comparison.EqualTo || (extensionSwappedTarget && ts.comparePaths(extensionSwappedTarget, pathOrPattern) === ts.Comparison.EqualTo)) {
return { moduleFileToTry: packageName };
}
break;
case MatchingMode.Directory:
if (ts.containsPath(pathOrPattern, targetFilePath)) {
const fragment = ts.getRelativePathFromDirectory(pathOrPattern, targetFilePath, /*ignoreCase*/ false);
return { moduleFileToTry: ts.getNormalizedAbsolutePath(ts.combinePaths(ts.combinePaths(packageName, exports), fragment), /*currentDirectory*/ undefined) };
}
break;
case MatchingMode.Pattern:
const starPos = pathOrPattern.indexOf("*");
const leadingSlice = pathOrPattern.slice(0, starPos);
const trailingSlice = pathOrPattern.slice(starPos + 1);
if (ts.startsWith(targetFilePath, leadingSlice) && ts.endsWith(targetFilePath, trailingSlice)) {
const starReplacement = targetFilePath.slice(leadingSlice.length, targetFilePath.length - trailingSlice.length);
return { moduleFileToTry: packageName.replace("*", starReplacement) };
}
if (extensionSwappedTarget && ts.startsWith(extensionSwappedTarget, leadingSlice) && ts.endsWith(extensionSwappedTarget, trailingSlice)) {
const starReplacement = extensionSwappedTarget.slice(leadingSlice.length, extensionSwappedTarget.length - trailingSlice.length);
return { moduleFileToTry: packageName.replace("*", starReplacement) };
}
break;
}
}
else if (Array.isArray(exports)) {
return ts.forEach(exports, e => tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, e, conditions));
}
else if (typeof exports === "object" && exports !== null) { // eslint-disable-line no-null/no-null
if (ts.allKeysStartWithDot(exports as ts.MapLike<unknown>)) {
// sub-mappings
// 3 cases:
// * directory mappings (legacyish, key ends with / (technically allows index/extension resolution under cjs mode))
// * pattern mappings (contains a *)
// * exact mappings (no *, does not end with /)
return ts.forEach(ts.getOwnKeys(exports as ts.MapLike<unknown>), k => {
const subPackageName = ts.getNormalizedAbsolutePath(ts.combinePaths(packageName, k), /*currentDirectory*/ undefined);
const mode = ts.endsWith(k, "/") ? MatchingMode.Directory
: ts.stringContains(k, "*") ? MatchingMode.Pattern
: MatchingMode.Exact;
return tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, subPackageName, (exports as ts.MapLike<unknown>)[k], conditions, mode);
});
}
else {
// conditional mapping
for (const key of ts.getOwnKeys(exports as ts.MapLike<unknown>)) {
if (key === "default" || conditions.indexOf(key) >= 0 || ts.isApplicableVersionedTypesKey(conditions, key)) {
const subTarget = (exports as ts.MapLike<unknown>)[key];
const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions);
if (result) {
return result;
}
}
}
}
}
return undefined;
}
function tryGetModuleNameFromRootDirs(rootDirs: readonly string[], moduleFileName: string, sourceDirectory: string, getCanonicalFileName: (file: string) => string, ending: Ending, compilerOptions: ts.CompilerOptions): string | undefined {
const normalizedTargetPaths = getPathsRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
if (normalizedTargetPaths === undefined) {
return undefined;
}
const normalizedSourcePaths = getPathsRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
const relativePaths = ts.flatMap(normalizedSourcePaths, sourcePath => {
return ts.map(normalizedTargetPaths, targetPath => ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourcePath, targetPath, getCanonicalFileName)));
});
const shortest = ts.min(relativePaths, ts.compareNumberOfDirectorySeparators);
if (!shortest) {
return undefined;
}
return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
? removeExtensionAndIndexPostFix(shortest, ending, compilerOptions)
: ts.removeFileExtension(shortest);
}
function tryGetModuleNameAsNodeModule({ path, isRedirect }: ts.ModulePath, { getCanonicalFileName, sourceDirectory }: Info, importingSourceFile: ts.SourceFile , host: ts.ModuleSpecifierResolutionHost, options: ts.CompilerOptions, userPreferences: ts.UserPreferences, packageNameOnly?: boolean, overrideMode?: ts.ModuleKind.ESNext | ts.ModuleKind.CommonJS): string | undefined {
if (!host.fileExists || !host.readFile) {
return undefined;
}
const parts: ts.NodeModulePathParts = ts.getNodeModulePathParts(path)!;
if (!parts) {
return undefined;
}
// Simplify the full file path to something that can be resolved by Node.
const preferences = getPreferences(host, userPreferences, options, importingSourceFile);
let moduleSpecifier = path;
let isPackageRootPath = false;
if (!packageNameOnly) {
let packageRootIndex = parts.packageRootIndex;
let moduleFileName: string | undefined;
while (true) {
// If the module could be imported by a directory name, use that directory's name
const { moduleFileToTry, packageRootPath, blockedByExports, verbatimFromExports } = tryDirectoryWithPackageJson(packageRootIndex);
if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.Classic) {
if (blockedByExports) {
return undefined; // File is under this package.json, but is not publicly exported - there's no way to name it via `node_modules` resolution
}
if (verbatimFromExports) {
return moduleFileToTry;
}
}
if (packageRootPath) {
moduleSpecifier = packageRootPath;
isPackageRootPath = true;
break;
}
if (!moduleFileName) moduleFileName = moduleFileToTry;
// try with next level of directory
packageRootIndex = path.indexOf(ts.directorySeparator, packageRootIndex + 1);
if (packageRootIndex === -1) {
moduleSpecifier = removeExtensionAndIndexPostFix(moduleFileName, preferences.ending, options, host);
break;
}
}
}
if (isRedirect && !isPackageRootPath) {
return undefined;
}
const globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
// Get a path that's relative to node_modules or the importing file's path
// if node_modules folder is in this folder or any of its parent folders, no need to keep it.
const pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
return undefined;
}
// If the module was found in @types, get the actual Node package name
const nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
const packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
// For classic resolution, only allow importing from node_modules/@types, not other node_modules
return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Classic && packageName === nodeModulesDirectoryName ? undefined : packageName;
function tryDirectoryWithPackageJson(packageRootIndex: number): { moduleFileToTry: string, packageRootPath?: string, blockedByExports?: true, verbatimFromExports?: true } {
const packageRootPath = path.substring(0, packageRootIndex);
const packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
let moduleFileToTry = path;
let maybeBlockedByTypesVersions = false;
const cachedPackageJson = host.getPackageJsonInfoCache?.()?.getPackageJsonInfo(packageJsonPath);
if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) {
const packageJsonContent = cachedPackageJson?.contents.packageJsonContent || JSON.parse(host.readFile!(packageJsonPath)!);
const importMode = overrideMode || importingSourceFile.impliedNodeFormat;
if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) {
const conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"];
const fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string"
? tryGetModuleNameFromExports(options, path, packageRootPath, ts.getPackageNameFromTypesPackageName(packageJsonContent.name), packageJsonContent.exports, conditions)
: undefined;
if (fromExports) {
const withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry)
? fromExports
: { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) };
return { ...withJsExtension, verbatimFromExports: true };
}
if (packageJsonContent.exports) {
return { moduleFileToTry: path, blockedByExports: true };
}
}
const versionPaths = packageJsonContent.typesVersions
? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
: undefined;
if (versionPaths) {
const subModuleName = path.slice(packageRootPath.length + 1);
const fromPaths = tryGetModuleNameFromPaths(
subModuleName,
versionPaths.paths,
getAllowedEndings(preferences.ending, options, importMode),
host,
options
);
if (fromPaths === undefined) {
maybeBlockedByTypesVersions = true;
}
else {
moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths);
}
}
// If the file is the main module, it can be imported by the package name
const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js";
if (ts.isString(mainFileRelative) && !(maybeBlockedByTypesVersions && ts.matchPatternOrExact(ts.tryParsePatterns(versionPaths!.paths), mainFileRelative))) {
// The 'main' file is also subject to mapping through typesVersions, and we couldn't come up with a path
// explicitly through typesVersions, so if it matches a key in typesVersions now, it's not reachable.
// (The only way this can happen is if some file in a package that's not resolvable from outside the
// package got pulled into the program anyway, e.g. transitively through a file that *is* reachable. It
// happens very easily in fourslash tests though, since every test file listed gets included. See
// importNameCodeFix_typesVersions.ts for an example.)
const mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
// ^ An arbitrary removal of file extension for this comparison is almost certainly wrong
return { packageRootPath, moduleFileToTry };
}
}
}
else {
// No package.json exists; an index.js will still resolve as the package name
const fileName = getCanonicalFileName(moduleFileToTry.substring(parts.packageRootIndex + 1));
if (fileName === "index.d.ts" || fileName === "index.js" || fileName === "index.ts" || fileName === "index.tsx") {
return { moduleFileToTry, packageRootPath };
}
}
return { moduleFileToTry };
}
}
function tryGetAnyFileFromPath(host: ts.ModuleSpecifierResolutionHost, path: string) {
if (!host.fileExists) return;
// We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
const extensions = ts.flatten(ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: ts.ScriptKind.JSON }]));
for (const e of extensions) {
const fullPath = path + e;
if (host.fileExists(fullPath)) {
return fullPath;
}
}
}
function getPathsRelativeToRootDirs(path: string, rootDirs: readonly string[], getCanonicalFileName: ts.GetCanonicalFileName): string[] | undefined {
return ts.mapDefined(rootDirs, rootDir => {
const relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName);
return relativePath !== undefined && isPathRelativeToParent(relativePath) ? undefined : relativePath;
});
}
function removeExtensionAndIndexPostFix(fileName: string, ending: Ending, options: ts.CompilerOptions, host?: ts.ModuleSpecifierResolutionHost): string {
if (ts.fileExtensionIsOneOf(fileName, [ts.Extension.Json, ts.Extension.Mjs, ts.Extension.Cjs])) return fileName;
const noExtension = ts.removeFileExtension(fileName);
if (fileName === noExtension) return fileName;
if (ts.fileExtensionIsOneOf(fileName, [ts.Extension.Dmts, ts.Extension.Mts, ts.Extension.Dcts, ts.Extension.Cts])) return noExtension + getJSExtensionForFile(fileName, options);
switch (ending) {
case Ending.Minimal:
const withoutIndex = ts.removeSuffix(noExtension, "/index");
if (host && withoutIndex !== noExtension && tryGetAnyFileFromPath(host, withoutIndex)) {
// Can't remove index if there's a file by the same name as the directory.
// Probably more callers should pass `host` so we can determine this?
return noExtension;
}
return withoutIndex;
case Ending.Index:
return noExtension;
case Ending.JsExtension:
return noExtension + getJSExtensionForFile(fileName, options);
default:
return ts.Debug.assertNever(ending);
}
}
function getJSExtensionForFile(fileName: string, options: ts.CompilerOptions): ts.Extension {
return tryGetJSExtensionForFile(fileName, options) ?? ts.Debug.fail(`Extension ${ts.extensionFromPath(fileName)} is unsupported:: FileName:: ${fileName}`);
}
export function tryGetJSExtensionForFile(fileName: string, options: ts.CompilerOptions): ts.Extension | undefined {
const ext = ts.tryGetExtensionFromPath(fileName);
switch (ext) {
case ts.Extension.Ts:
case ts.Extension.Dts:
return ts.Extension.Js;
case ts.Extension.Tsx:
return options.jsx === ts.JsxEmit.Preserve ? ts.Extension.Jsx : ts.Extension.Js;
case ts.Extension.Js:
case ts.Extension.Jsx:
case ts.Extension.Json:
return ext;
case ts.Extension.Dmts:
case ts.Extension.Mts:
case ts.Extension.Mjs:
return ts.Extension.Mjs;
case ts.Extension.Dcts:
case ts.Extension.Cts:
case ts.Extension.Cjs:
return ts.Extension.Cjs;
default:
return undefined;
}
}
function getRelativePathIfInDirectory(path: string, directoryPath: string, getCanonicalFileName: ts.GetCanonicalFileName): string | undefined {
const relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
}
function isPathRelativeToParent(path: string): boolean {
return ts.startsWith(path, "..");
}
}