-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
Copy pathmoduleSpecifiers.ts
1470 lines (1379 loc) · 77.7 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
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 {
__String,
allKeysStartWithDot,
AmbientModuleDeclaration,
append,
arrayFrom,
changeFullExtension,
CharacterCodes,
combinePaths,
compareBooleans,
compareNumberOfDirectorySeparators,
comparePaths,
Comparison,
CompilerOptions,
concatenate,
containsIgnoredPath,
containsPath,
createGetCanonicalFileName,
Debug,
directorySeparator,
emptyArray,
endsWith,
ensurePathIsNonModuleName,
ensureTrailingDirectorySeparator,
every,
ExportAssignment,
Extension,
extensionFromPath,
extensionsNotSupportingExtensionlessResolution,
fileExtensionIsOneOf,
FileIncludeKind,
firstDefined,
flatMap,
flatten,
forEach,
forEachAncestorDirectoryStoppingAtGlobalCache,
FutureSourceFile,
getBaseFileName,
GetCanonicalFileName,
getConditions,
getDefaultResolutionModeForFileWorker,
getDirectoryPath,
getEmitModuleResolutionKind,
getModuleNameStringLiteralAt,
getModuleSpecifierEndingPreference,
getNodeModulePathParts,
getNormalizedAbsolutePath,
getOutputDeclarationFileNameWorker,
getOutputJSFileNameWorker,
getOwnKeys,
getPackageJsonTypesVersionsPaths,
getPackageNameFromTypesPackageName,
getPackageScopeForPath,
getPathsBasePath,
getRelativePathFromDirectory,
getRelativePathToDirectoryOrUrl,
getResolvePackageJsonExports,
getResolvePackageJsonImports,
getSourceFileOfModule,
getSupportedExtensions,
getTemporaryModuleResolutionState,
getTextOfIdentifierOrLiteral,
hasImplementationTSFileExtension,
hasJSFileExtension,
hasTSFileExtension,
hostGetCanonicalFileName,
hostUsesCaseSensitiveFileNames,
Identifier,
isAmbientModule,
isApplicableVersionedTypesKey,
isDeclarationFileName,
isExternalModuleAugmentation,
isExternalModuleNameRelative,
isFullSourceFile,
isMissingPackageJsonInfo,
isModuleBlock,
isModuleDeclaration,
isNonGlobalAmbientModule,
isPackageJsonInfo,
isRootedDiskPath,
isSourceFile,
isString,
JsxEmit,
map,
mapDefined,
MapLike,
matchPatternOrExact,
memoizeOne,
min,
ModuleDeclaration,
ModuleKind,
ModulePath,
ModuleResolutionHost,
ModuleResolutionKind,
ModuleSpecifierCache,
ModuleSpecifierEnding,
ModuleSpecifierOptions,
ModuleSpecifierResolutionHost,
NodeFlags,
NodeModulePathParts,
normalizePath,
PackageJsonPathFields,
pathContainsNodeModules,
pathIsBareSpecifier,
pathIsRelative,
PropertyAccessExpression,
removeExtension,
removeFileExtension,
removeSuffix,
removeTrailingDirectorySeparator,
replaceFirstStar,
ResolutionMode,
ResolvedModuleSpecifierInfo,
resolveModuleName,
resolvePath,
ScriptKind,
shouldAllowImportingTsExtension,
some,
SourceFile,
startsWith,
startsWithDirectory,
StringLiteral,
Symbol,
SymbolFlags,
toPath,
tryGetExtensionFromPath,
tryParseJson,
tryParsePatterns,
TypeChecker,
UserPreferences,
} from "./_namespaces/ts.js";
const stringToRegex = memoizeOne((pattern: string) => {
try {
let slash = pattern.indexOf("/");
if (slash !== 0) {
// No leading slash, treat as a pattern
return new RegExp(pattern);
}
const lastSlash = pattern.lastIndexOf("/");
if (slash === lastSlash) {
// Only one slash, treat as a pattern
return new RegExp(pattern);
}
while ((slash = pattern.indexOf("/", slash + 1)) !== lastSlash) {
if (pattern[slash - 1] !== "\\") {
// Unescaped middle slash, treat as a pattern
return new RegExp(pattern);
}
}
// Only case-insensitive and unicode flags make sense
const flags = pattern.substring(lastSlash + 1).replace(/[^iu]/g, "");
pattern = pattern.substring(1, lastSlash);
return new RegExp(pattern, flags);
}
catch {
return undefined;
}
});
// Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
/** @internal */
export const enum RelativePreference {
Relative,
NonRelative,
Shortest,
ExternalNonRelative,
}
/** @internal */
export interface ModuleSpecifierPreferences {
readonly relativePreference: RelativePreference;
/**
* @param syntaxImpliedNodeFormat Used when the import syntax implies ESM or CJS irrespective of the mode of the file.
*/
getAllowedEndingsInPreferredOrder(syntaxImpliedNodeFormat?: ResolutionMode): ModuleSpecifierEnding[];
readonly excludeRegexes?: readonly string[];
}
/** @internal */
export function getModuleSpecifierPreferences(
{ importModuleSpecifierPreference, importModuleSpecifierEnding, autoImportSpecifierExcludeRegexes }: UserPreferences,
host: Pick<ModuleSpecifierResolutionHost, "getDefaultResolutionModeForFile">,
compilerOptions: CompilerOptions,
importingSourceFile: Pick<SourceFile, "fileName" | "impliedNodeFormat">,
oldImportSpecifier?: string,
): ModuleSpecifierPreferences {
const filePreferredEnding = getPreferredEnding();
return {
excludeRegexes: autoImportSpecifierExcludeRegexes,
relativePreference: oldImportSpecifier !== undefined ? (isExternalModuleNameRelative(oldImportSpecifier) ?
RelativePreference.Relative :
RelativePreference.NonRelative) :
importModuleSpecifierPreference === "relative" ? RelativePreference.Relative :
importModuleSpecifierPreference === "non-relative" ? RelativePreference.NonRelative :
importModuleSpecifierPreference === "project-relative" ? RelativePreference.ExternalNonRelative :
RelativePreference.Shortest,
getAllowedEndingsInPreferredOrder: syntaxImpliedNodeFormat => {
const impliedNodeFormat = getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions);
const preferredEnding = syntaxImpliedNodeFormat !== impliedNodeFormat ? getPreferredEnding(syntaxImpliedNodeFormat) : filePreferredEnding;
const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
if ((syntaxImpliedNodeFormat ?? impliedNodeFormat) === ModuleKind.ESNext && ModuleResolutionKind.Node16 <= moduleResolution && moduleResolution <= ModuleResolutionKind.NodeNext) {
if (shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName)) {
return [ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.JsExtension];
}
return [ModuleSpecifierEnding.JsExtension];
}
if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Classic) {
return preferredEnding === ModuleSpecifierEnding.JsExtension
? [ModuleSpecifierEnding.JsExtension, ModuleSpecifierEnding.Index]
: [ModuleSpecifierEnding.Index, ModuleSpecifierEnding.JsExtension];
}
const allowImportingTsExtension = shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName);
switch (preferredEnding) {
case ModuleSpecifierEnding.JsExtension:
return allowImportingTsExtension
? [ModuleSpecifierEnding.JsExtension, ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.Index]
: [ModuleSpecifierEnding.JsExtension, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.Index];
case ModuleSpecifierEnding.TsExtension:
return [ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.JsExtension, ModuleSpecifierEnding.Index];
case ModuleSpecifierEnding.Index:
return allowImportingTsExtension
? [ModuleSpecifierEnding.Index, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.JsExtension]
: [ModuleSpecifierEnding.Index, ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.JsExtension];
case ModuleSpecifierEnding.Minimal:
return allowImportingTsExtension
? [ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.Index, ModuleSpecifierEnding.TsExtension, ModuleSpecifierEnding.JsExtension]
: [ModuleSpecifierEnding.Minimal, ModuleSpecifierEnding.Index, ModuleSpecifierEnding.JsExtension];
default:
Debug.assertNever(preferredEnding);
}
},
};
function getPreferredEnding(resolutionMode?: ResolutionMode): ModuleSpecifierEnding {
if (oldImportSpecifier !== undefined) {
if (hasJSFileExtension(oldImportSpecifier)) return ModuleSpecifierEnding.JsExtension;
if (endsWith(oldImportSpecifier, "/index")) return ModuleSpecifierEnding.Index;
}
return getModuleSpecifierEndingPreference(
importModuleSpecifierEnding,
resolutionMode ?? getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions),
compilerOptions,
isFullSourceFile(importingSourceFile) ? importingSourceFile : undefined,
);
}
}
// `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.
/** @internal */
export function updateModuleSpecifier(
compilerOptions: CompilerOptions,
importingSourceFile: SourceFile,
importingSourceFileName: string,
toFileName: string,
host: ModuleSpecifierResolutionHost,
oldImportSpecifier: string,
options: ModuleSpecifierOptions = {},
): string | undefined {
const res = getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getModuleSpecifierPreferences({}, host, compilerOptions, importingSourceFile, oldImportSpecifier), {}, 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.
/** @internal */
export function getModuleSpecifier(
compilerOptions: CompilerOptions,
importingSourceFile: SourceFile | FutureSourceFile,
importingSourceFileName: string,
toFileName: string,
host: ModuleSpecifierResolutionHost,
options: ModuleSpecifierOptions = {},
): string {
return getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getModuleSpecifierPreferences({}, host, compilerOptions, importingSourceFile), {}, options);
}
/** @internal */
export function getNodeModulesPackageName(
compilerOptions: CompilerOptions,
importingSourceFile: SourceFile | FutureSourceFile,
nodeModulesFileName: string,
host: ModuleSpecifierResolutionHost,
preferences: UserPreferences,
options: ModuleSpecifierOptions = {},
): string | undefined {
const info = getInfo(importingSourceFile.fileName, host);
const modulePaths = getAllModulePaths(info, nodeModulesFileName, host, preferences, compilerOptions, options);
return firstDefined(modulePaths, modulePath => tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, preferences, /*packageNameOnly*/ true, options.overrideImportMode));
}
function getModuleSpecifierWorker(
compilerOptions: CompilerOptions,
importingSourceFile: SourceFile | FutureSourceFile,
importingSourceFileName: string,
toFileName: string,
host: ModuleSpecifierResolutionHost,
preferences: ModuleSpecifierPreferences,
userPreferences: UserPreferences,
options: ModuleSpecifierOptions = {},
): string {
const info = getInfo(importingSourceFileName, host);
const modulePaths = getAllModulePaths(info, toFileName, host, userPreferences, compilerOptions, options);
return firstDefined(modulePaths, modulePath => tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode)) ||
getLocalModuleSpecifier(toFileName, info, compilerOptions, host, options.overrideImportMode || getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions), preferences);
}
/** @internal */
export function tryGetModuleSpecifiersFromCache(
moduleSymbol: Symbol,
importingSourceFile: SourceFile | FutureSourceFile,
host: ModuleSpecifierResolutionHost,
userPreferences: UserPreferences,
options: ModuleSpecifierOptions = {},
): ModuleSpecifierResult | undefined {
const result = tryGetModuleSpecifiersFromCacheWorker(
moduleSymbol,
importingSourceFile,
host,
userPreferences,
options,
);
return result[1] && { kind: result[0], moduleSpecifiers: result[1], computedWithoutCache: false };
}
function tryGetModuleSpecifiersFromCacheWorker(
moduleSymbol: Symbol,
importingSourceFile: SourceFile | FutureSourceFile,
host: ModuleSpecifierResolutionHost,
userPreferences: UserPreferences,
options: ModuleSpecifierOptions = {},
): readonly [kind?: ModuleSpecifierResult["kind"], specifiers?: readonly string[], moduleFile?: SourceFile, modulePaths?: readonly ModulePath[], cache?: ModuleSpecifierCache] {
const moduleSourceFile = getSourceFileOfModule(moduleSymbol);
if (!moduleSourceFile) {
return emptyArray as [];
}
const cache = host.getModuleSpecifierCache?.();
const cached = cache?.get(importingSourceFile.path, moduleSourceFile.path, userPreferences, options);
return [cached?.kind, cached?.moduleSpecifiers, moduleSourceFile, cached?.modulePaths, cache];
}
/**
* Returns an import for each symlink and for the realpath.
*
* @internal
*/
export function getModuleSpecifiers(
moduleSymbol: Symbol,
checker: TypeChecker,
compilerOptions: CompilerOptions,
importingSourceFile: SourceFile,
host: ModuleSpecifierResolutionHost,
userPreferences: UserPreferences,
options: ModuleSpecifierOptions = {},
): readonly string[] {
return getModuleSpecifiersWithCacheInfo(
moduleSymbol,
checker,
compilerOptions,
importingSourceFile,
host,
userPreferences,
options,
/*forAutoImport*/ false,
).moduleSpecifiers;
}
/** @internal */
export interface ModuleSpecifierResult {
kind: ResolvedModuleSpecifierInfo["kind"];
moduleSpecifiers: readonly string[];
computedWithoutCache: boolean;
}
/** @internal */
export function getModuleSpecifiersWithCacheInfo(
moduleSymbol: Symbol,
checker: TypeChecker,
compilerOptions: CompilerOptions,
importingSourceFile: SourceFile | FutureSourceFile,
host: ModuleSpecifierResolutionHost,
userPreferences: UserPreferences,
options: ModuleSpecifierOptions | undefined = {},
forAutoImport: boolean,
): ModuleSpecifierResult {
let computedWithoutCache = false;
const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker);
if (ambient) {
return {
kind: "ambient",
moduleSpecifiers: !(forAutoImport && isExcludedByRegex(ambient, userPreferences.autoImportSpecifierExcludeRegexes)) ? [ambient] : emptyArray,
computedWithoutCache,
};
}
// eslint-disable-next-line prefer-const
let [kind, specifiers, moduleSourceFile, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker(
moduleSymbol,
importingSourceFile,
host,
userPreferences,
options,
);
if (specifiers) return { kind, moduleSpecifiers: specifiers, computedWithoutCache };
if (!moduleSourceFile) return { kind: undefined, moduleSpecifiers: emptyArray, computedWithoutCache };
computedWithoutCache = true;
modulePaths ||= getAllModulePathsWorker(getInfo(importingSourceFile.fileName, host), moduleSourceFile.originalFileName, host, compilerOptions, options);
const result = computeModuleSpecifiers(
modulePaths,
compilerOptions,
importingSourceFile,
host,
userPreferences,
options,
forAutoImport,
);
cache?.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, options, result.kind, modulePaths, result.moduleSpecifiers);
return result;
}
/** @internal */
export function getLocalModuleSpecifierBetweenFileNames(
importingFile: Pick<SourceFile, "fileName" | "impliedNodeFormat">,
targetFileName: string,
compilerOptions: CompilerOptions,
host: ModuleSpecifierResolutionHost,
preferences: UserPreferences,
options: ModuleSpecifierOptions = {},
): string {
const info = getInfo(importingFile.fileName, host);
const importMode = options.overrideImportMode ?? importingFile.impliedNodeFormat;
return getLocalModuleSpecifier(
targetFileName,
info,
compilerOptions,
host,
importMode,
getModuleSpecifierPreferences(preferences, host, compilerOptions, importingFile),
);
}
function computeModuleSpecifiers(
modulePaths: readonly ModulePath[],
compilerOptions: CompilerOptions,
importingSourceFile: SourceFile | FutureSourceFile,
host: ModuleSpecifierResolutionHost,
userPreferences: UserPreferences,
options: ModuleSpecifierOptions = {},
forAutoImport: boolean,
): ModuleSpecifierResult {
const info = getInfo(importingSourceFile.fileName, host);
const preferences = getModuleSpecifierPreferences(userPreferences, host, compilerOptions, importingSourceFile);
const existingSpecifier = isFullSourceFile(importingSourceFile) && forEach(modulePaths, modulePath =>
forEach(
host.getFileIncludeReasons().get(toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)),
reason => {
if (reason.kind !== 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
const existingMode = host.getModeForResolutionAtIndex(importingSourceFile, reason.index);
const targetMode = options.overrideImportMode ?? host.getDefaultResolutionModeForFile(importingSourceFile);
if (existingMode !== targetMode && existingMode !== undefined && targetMode !== undefined) {
return undefined;
}
const specifier = 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 || !pathIsRelative(specifier) ?
specifier :
undefined;
},
));
if (existingSpecifier) {
return { kind: undefined, moduleSpecifiers: [existingSpecifier], computedWithoutCache: true };
}
const importedFileIsInNodeModules = 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 redirectPathsSpecifiers: string[] | undefined;
let relativeSpecifiers: string[] | undefined;
for (const modulePath of modulePaths) {
const specifier = modulePath.isInNodeModules
? tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, userPreferences, /*packageNameOnly*/ undefined, options.overrideImportMode)
: undefined;
if (specifier && !(forAutoImport && isExcludedByRegex(specifier, preferences.excludeRegexes))) {
nodeModulesSpecifiers = append(nodeModulesSpecifiers, specifier);
if (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 { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true };
}
}
const local = getLocalModuleSpecifier(
modulePath.path,
info,
compilerOptions,
host,
options.overrideImportMode || importingSourceFile.impliedNodeFormat,
preferences,
/*pathsOnly*/ modulePath.isRedirect || !!specifier,
);
if (!local || forAutoImport && isExcludedByRegex(local, preferences.excludeRegexes)) {
continue;
}
if (modulePath.isRedirect) {
redirectPathsSpecifiers = append(redirectPathsSpecifiers, local);
}
else if (pathIsBareSpecifier(local)) {
if (pathContainsNodeModules(local)) {
// We could be in this branch due to inappropriate use of `baseUrl`, not intentional `paths`
// usage. It's impossible to reason about where to prioritize baseUrl-generated module
// specifiers, but if they contain `/node_modules/`, they're going to trigger a portability
// error, so *at least* don't prioritize those.
relativeSpecifiers = append(relativeSpecifiers, local);
}
else {
pathsSpecifiers = append(pathsSpecifiers, local);
}
}
else if (forAutoImport || !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 = append(relativeSpecifiers, local);
}
}
return pathsSpecifiers?.length ? { kind: "paths", moduleSpecifiers: pathsSpecifiers, computedWithoutCache: true } :
redirectPathsSpecifiers?.length ? { kind: "redirect", moduleSpecifiers: redirectPathsSpecifiers, computedWithoutCache: true } :
nodeModulesSpecifiers?.length ? { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true } :
{ kind: "relative", moduleSpecifiers: relativeSpecifiers ?? emptyArray, computedWithoutCache: true };
}
function isExcludedByRegex(moduleSpecifier: string, excludeRegexes: readonly string[] | undefined): boolean {
return some(excludeRegexes, pattern => !!stringToRegex(pattern)?.test(moduleSpecifier));
}
interface Info {
readonly getCanonicalFileName: GetCanonicalFileName;
readonly importingSourceFileName: string;
readonly sourceDirectory: string;
readonly canonicalSourceDirectory: string;
}
// importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
function getInfo(importingSourceFileName: string, host: ModuleSpecifierResolutionHost): Info {
importingSourceFileName = getNormalizedAbsolutePath(importingSourceFileName, host.getCurrentDirectory());
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
const sourceDirectory = getDirectoryPath(importingSourceFileName);
return {
getCanonicalFileName,
importingSourceFileName,
sourceDirectory,
canonicalSourceDirectory: getCanonicalFileName(sourceDirectory),
};
}
function getLocalModuleSpecifier(moduleFileName: string, info: Info, compilerOptions: CompilerOptions, host: ModuleSpecifierResolutionHost, importMode: ResolutionMode, preferences: ModuleSpecifierPreferences): string;
function getLocalModuleSpecifier(moduleFileName: string, info: Info, compilerOptions: CompilerOptions, host: ModuleSpecifierResolutionHost, importMode: ResolutionMode, preferences: ModuleSpecifierPreferences, pathsOnly?: boolean): string | undefined;
function getLocalModuleSpecifier(moduleFileName: string, info: Info, compilerOptions: CompilerOptions, host: ModuleSpecifierResolutionHost, importMode: ResolutionMode, { getAllowedEndingsInPreferredOrder: getAllowedEndingsInPrefererredOrder, relativePreference, excludeRegexes }: ModuleSpecifierPreferences, pathsOnly?: boolean): string | undefined {
const { baseUrl, paths, rootDirs } = compilerOptions;
if (pathsOnly && !paths) {
return undefined;
}
const { sourceDirectory, canonicalSourceDirectory, getCanonicalFileName } = info;
const allowedEndings = getAllowedEndingsInPrefererredOrder(importMode);
const relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, allowedEndings, compilerOptions) ||
processEnding(ensurePathIsNonModuleName(getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), allowedEndings, compilerOptions);
if (!baseUrl && !paths && !getResolvePackageJsonImports(compilerOptions) || relativePreference === RelativePreference.Relative) {
return pathsOnly ? undefined : relativePath;
}
const baseDirectory = getNormalizedAbsolutePath(getPathsBasePath(compilerOptions, host) || baseUrl!, host.getCurrentDirectory());
const relativeToBaseUrl = getRelativePathIfInSameVolume(moduleFileName, baseDirectory, getCanonicalFileName);
if (!relativeToBaseUrl) {
return pathsOnly ? undefined : relativePath;
}
const fromPackageJsonImports = pathsOnly
? undefined
: tryGetModuleNameFromPackageJsonImports(
moduleFileName,
sourceDirectory,
compilerOptions,
host,
importMode,
prefersTsExtension(allowedEndings),
);
const fromPaths = pathsOnly || fromPackageJsonImports === undefined ? paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, baseDirectory, getCanonicalFileName, host, compilerOptions) : undefined;
if (pathsOnly) {
return fromPaths;
}
const maybeNonRelative = fromPackageJsonImports ?? (fromPaths === undefined && baseUrl !== undefined ? processEnding(relativeToBaseUrl, allowedEndings, compilerOptions) : fromPaths);
if (!maybeNonRelative) {
return relativePath;
}
const relativeIsExcluded = isExcludedByRegex(relativePath, excludeRegexes);
const nonRelativeIsExcluded = isExcludedByRegex(maybeNonRelative, excludeRegexes);
if (!relativeIsExcluded && nonRelativeIsExcluded) {
return relativePath;
}
if (relativeIsExcluded && !nonRelativeIsExcluded) {
return maybeNonRelative;
}
if (relativePreference === RelativePreference.NonRelative && !pathIsRelative(maybeNonRelative)) {
return maybeNonRelative;
}
if (relativePreference === RelativePreference.ExternalNonRelative && !pathIsRelative(maybeNonRelative)) {
const projectDirectory = compilerOptions.configFilePath ?
toPath(getDirectoryPath(compilerOptions.configFilePath), host.getCurrentDirectory(), info.getCanonicalFileName) :
info.getCanonicalFileName(host.getCurrentDirectory());
const modulePath = toPath(moduleFileName, projectDirectory, getCanonicalFileName);
const sourceIsInternal = startsWith(canonicalSourceDirectory, projectDirectory);
const targetIsInternal = 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 maybeNonRelative;
}
const nearestTargetPackageJson = getNearestAncestorDirectoryWithPackageJson(host, getDirectoryPath(modulePath));
const nearestSourcePackageJson = getNearestAncestorDirectoryWithPackageJson(host, sourceDirectory);
const ignoreCase = !hostUsesCaseSensitiveFileNames(host);
if (!packageJsonPathsAreEqual(nearestTargetPackageJson, nearestSourcePackageJson, ignoreCase)) {
// 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 maybeNonRelative;
}
return relativePath;
}
// Prefer a relative import over a baseUrl import if it has fewer components.
return isPathRelativeToParent(maybeNonRelative) || countPathComponents(relativePath) < countPathComponents(maybeNonRelative) ? relativePath : maybeNonRelative;
}
function packageJsonPathsAreEqual(a: string | undefined, b: string | undefined, ignoreCase?: boolean) {
if (a === b) return true;
if (a === undefined || b === undefined) return false;
return comparePaths(a, b, ignoreCase) === Comparison.EqualTo;
}
/** @internal */
export function countPathComponents(path: string): number {
let count = 0;
for (let i = startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
if (path.charCodeAt(i) === CharacterCodes.slash) count++;
}
return count;
}
function comparePathsByRedirectAndNumberOfDirectorySeparators(a: ModulePath, b: ModulePath) {
return compareBooleans(b.isRedirect, a.isRedirect) || compareNumberOfDirectorySeparators(a.path, b.path);
}
function getNearestAncestorDirectoryWithPackageJson(host: ModuleSpecifierResolutionHost, fileName: string) {
if (host.getNearestAncestorDirectoryWithPackageJson) {
return host.getNearestAncestorDirectoryWithPackageJson(fileName);
}
return forEachAncestorDirectoryStoppingAtGlobalCache(
host,
fileName,
directory =>
host.fileExists(combinePaths(directory, "package.json")) ?
directory :
undefined,
);
}
/** @internal */
export function forEachFileNameOfModule<T>(
importingFileName: string,
importedFileName: string,
host: ModuleSpecifierResolutionHost,
preferSymlinks: boolean,
cb: (fileName: string, isRedirect: boolean) => T | undefined,
): T | undefined {
const getCanonicalFileName = hostGetCanonicalFileName(host);
const cwd = host.getCurrentDirectory();
const referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
const importedPath = toPath(importedFileName, cwd, getCanonicalFileName);
const redirects = host.redirectTargetsMap.get(importedPath) || emptyArray;
const importedFileNames = [...(referenceRedirect ? [referenceRedirect] : emptyArray), importedFileName, ...redirects];
const targets = importedFileNames.map(f => getNormalizedAbsolutePath(f, cwd));
let shouldFilterIgnoredPaths = !every(targets, 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 = forEach(targets, p => !(shouldFilterIgnoredPaths && containsIgnoredPath(p)) && cb(p, referenceRedirect === p));
if (result) return result;
}
const symlinkedDirectories = host.getSymlinkCache?.().getSymlinkedDirectoriesByRealpath();
const fullImportedFileName = getNormalizedAbsolutePath(importedFileName, cwd);
const result = symlinkedDirectories && forEachAncestorDirectoryStoppingAtGlobalCache(
host,
getDirectoryPath(fullImportedFileName),
realPathDirectory => {
const symlinkDirectories = symlinkedDirectories.get(ensureTrailingDirectorySeparator(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 (startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) {
return false; // Stop search, each ancestor directory will also hit this condition
}
return forEach(targets, target => {
if (!startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) {
return;
}
const relative = getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName);
for (const symlinkDirectory of symlinkDirectories) {
const option = 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
? forEach(targets, p => shouldFilterIgnoredPaths && 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(
info: Info,
importedFileName: string,
host: ModuleSpecifierResolutionHost,
preferences: UserPreferences,
compilerOptions: CompilerOptions,
options: ModuleSpecifierOptions = {},
) {
const importingFilePath = toPath(info.importingSourceFileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host));
const importedFilePath = toPath(importedFileName, host.getCurrentDirectory(), 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(info, importedFileName, host, compilerOptions, options);
if (cache) {
cache.setModulePaths(importingFilePath, importedFilePath, preferences, options, modulePaths);
}
return modulePaths;
}
const runtimeDependencyFields = ["dependencies", "peerDependencies", "optionalDependencies"] as const;
function getAllRuntimeDependencies(packageJson: PackageJsonPathFields) {
let result;
for (const field of runtimeDependencyFields) {
const deps = packageJson[field];
if (deps && typeof deps === "object") {
result = concatenate(result, getOwnKeys(deps));
}
}
return result;
}
function getAllModulePathsWorker(info: Info, importedFileName: string, host: ModuleSpecifierResolutionHost, compilerOptions: CompilerOptions, options: ModuleSpecifierOptions): readonly ModulePath[] {
const cache = host.getModuleResolutionCache?.();
const links = host.getSymlinkCache?.();
if (cache && links && host.readFile && !pathContainsNodeModules(info.importingSourceFileName)) {
Debug.type<ModuleResolutionHost>(host);
// Cache resolutions for all `dependencies` of the `package.json` context of the input file.
// This should populate all the relevant symlinks in the symlink cache, and most, if not all, of these resolutions
// should get (re)used.
const state = getTemporaryModuleResolutionState(cache.getPackageJsonInfoCache(), host, {});
const packageJson = getPackageScopeForPath(getDirectoryPath(info.importingSourceFileName), state);
if (packageJson) {
const toResolve = getAllRuntimeDependencies(packageJson.contents.packageJsonContent);
for (const depName of (toResolve || emptyArray)) {
const resolved = resolveModuleName(depName, combinePaths(packageJson.packageDirectory, "package.json"), compilerOptions, host, cache, /*redirectedReference*/ undefined, options.overrideImportMode);
links.setSymlinksFromResolution(resolved.resolvedModule);
}
}
}
const allFileNames = new Map<string, { path: string; isRedirect: boolean; isInNodeModules: boolean; }>();
let importedFileFromNodeModules = false;
forEachFileNameOfModule(
info.importingSourceFileName,
importedFileName,
host,
/*preferSymlinks*/ true,
(path, isRedirect) => {
const isInNodeModules = pathContainsNodeModules(path);
allFileNames.set(path, { path: info.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: ModulePath[] = [];
for (
let directory = info.canonicalSourceDirectory;
allFileNames.size !== 0;
) {
const directoryStart = ensureTrailingDirectorySeparator(directory);
let pathsInDirectory: ModulePath[] | undefined;
allFileNames.forEach(({ path, isRedirect, isInNodeModules }, fileName) => {
if (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 = getDirectoryPath(directory);
if (newDirectory === directory) break;
directory = newDirectory;
}
if (allFileNames.size) {
const remainingPaths = arrayFrom(
allFileNames.entries(),
([fileName, { isRedirect, isInNodeModules }]): ModulePath => ({ path: fileName, isRedirect, isInNodeModules }),
);
if (remainingPaths.length > 1) remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
sortedPaths.push(...remainingPaths);
}
return sortedPaths;
}
function tryGetModuleNameFromAmbientModule(moduleSymbol: Symbol, checker: TypeChecker): string | undefined {
const decl = moduleSymbol.declarations?.find(
d => isNonGlobalAmbientModule(d) && (!isExternalModuleAugmentation(d) || !isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(d.name))),
) as (ModuleDeclaration & { name: 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 = mapDefined(moduleSymbol.declarations, d => {
if (!isModuleDeclaration(d)) return;
const topNamespace = getTopNamespace(d);
if (
!(topNamespace?.parent?.parent
&& isModuleBlock(topNamespace.parent)
&& isAmbientModule(topNamespace.parent.parent)
&& isSourceFile(topNamespace.parent.parent.parent))
) return;
const exportAssignment = (topNamespace.parent.parent.symbol.exports?.get("export=" as __String)?.valueDeclaration as ExportAssignment)?.expression as PropertyAccessExpression | Identifier;
if (!exportAssignment) return;
const exportSymbol = checker.getSymbolAtLocation(exportAssignment);
if (!exportSymbol) return;
const originalExportSymbol = exportSymbol?.flags & SymbolFlags.Alias ? checker.getAliasedSymbol(exportSymbol) : exportSymbol;
if (originalExportSymbol === d.symbol) return topNamespace.parent.parent;
function getTopNamespace(namespaceDeclaration: ModuleDeclaration) {
while (namespaceDeclaration.flags & NodeFlags.NestedNamespace) {
namespaceDeclaration = namespaceDeclaration.parent as ModuleDeclaration;
}
return namespaceDeclaration;
}
});
const ambientModuleDeclare = ambientModuleDeclareCandidates[0] as (AmbientModuleDeclaration & { name: StringLiteral; }) | undefined;
if (ambientModuleDeclare) {
return ambientModuleDeclare.name.text;
}
}
function tryGetModuleNameFromPaths(relativeToBaseUrl: string, paths: MapLike<readonly string[]>, allowedEndings: ModuleSpecifierEnding[], baseDirectory: string, getCanonicalFileName: GetCanonicalFileName, host: ModuleSpecifierResolutionHost, compilerOptions: CompilerOptions): string | undefined {
for (const key in paths) {
for (const patternText of paths[key]) {
const normalized = normalizePath(patternText);
const pattern = getRelativePathIfInSameVolume(normalized, baseDirectory, getCanonicalFileName) ?? normalized;
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: ModuleSpecifierEnding | undefined; value: string; }[] = allowedEndings.map(ending => ({
ending,
value: processEnding(relativeToBaseUrl, [ending], compilerOptions),
}));
if (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 &&
startsWith(value, prefix) &&
endsWith(value, suffix) &&
validateEnding({ ending, value })
) {
const matchedStar = value.substring(prefix.length, value.length - suffix.length);
if (!pathIsRelative(matchedStar)) {
return replaceFirstStar(key, matchedStar);
}
}
}
}
else if (
some(candidates, c => c.ending !== ModuleSpecifierEnding.Minimal && pattern === c.value) ||
some(candidates, c => c.ending === ModuleSpecifierEnding.Minimal && pattern === c.value && validateEnding(c))
) {
return key;
}
}
}