2016-09-08 22:26:01 +02:00
|
|
|
namespace ts {
|
2016-11-02 22:41:26 +01:00
|
|
|
/* @internal */
|
|
|
|
export function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void;
|
|
|
|
export function trace(host: ModuleResolutionHost): void {
|
2018-05-22 23:46:57 +02:00
|
|
|
host.trace!(formatMessage.apply(undefined, arguments));
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
|
2016-11-02 22:41:26 +01:00
|
|
|
/* @internal */
|
|
|
|
export function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean {
|
2018-05-22 23:46:57 +02:00
|
|
|
return !!compilerOptions.traceResolution && host.trace !== undefined;
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
|
2019-05-22 23:22:46 +02:00
|
|
|
function withPackageId(packageInfo: PackageJsonInfo | undefined, r: PathAndExtension | undefined): Resolved | undefined {
|
|
|
|
let packageId: PackageId | undefined;
|
|
|
|
if (r && packageInfo) {
|
|
|
|
const packageJsonContent = packageInfo.packageJsonContent as PackageJson;
|
|
|
|
if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
|
|
|
|
packageId = {
|
|
|
|
name: packageJsonContent.name,
|
|
|
|
subModuleName: r.path.slice(packageInfo.packageDirectory.length + directorySeparator.length),
|
|
|
|
version: packageJsonContent.version
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
2017-08-09 23:39:06 +02:00
|
|
|
return r && { path: r.path, extension: r.ext, packageId };
|
|
|
|
}
|
|
|
|
|
2018-05-22 23:46:57 +02:00
|
|
|
function noPackageId(r: PathAndExtension | undefined): Resolved | undefined {
|
2019-05-22 23:22:46 +02:00
|
|
|
return withPackageId(/*packageInfo*/ undefined, r);
|
2017-08-09 23:39:06 +02:00
|
|
|
}
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
function removeIgnoredPackageId(r: Resolved | undefined): PathAndExtension | undefined {
|
|
|
|
if (r) {
|
|
|
|
Debug.assert(r.packageId === undefined);
|
|
|
|
return { path: r.path, ext: r.extension };
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-08-09 23:39:06 +02:00
|
|
|
/** Result of trying to resolve a module. */
|
2016-10-13 22:02:22 +02:00
|
|
|
interface Resolved {
|
2016-10-25 21:38:59 +02:00
|
|
|
path: string;
|
|
|
|
extension: Extension;
|
2017-08-09 23:39:06 +02:00
|
|
|
packageId: PackageId | undefined;
|
2018-08-11 02:08:53 +02:00
|
|
|
/**
|
|
|
|
* When the resolved is not created from cache, the value is
|
|
|
|
* - string if original Path if it is symbolic link to the resolved path
|
|
|
|
* - undefined if path is not a symbolic link
|
|
|
|
* When the resolved is created using value from cache of ResolvedModuleWithFailedLookupLocations, the value is:
|
|
|
|
* - string if original Path if it is symbolic link to the resolved path
|
|
|
|
* - true if path is not a symbolic link - this indicates that the originalPath calculation is already done and needs to be skipped
|
|
|
|
*/
|
2018-08-11 00:23:35 +02:00
|
|
|
originalPath?: string | true;
|
2017-08-09 23:39:06 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/** Result of trying to resolve a module at a file. Needs to have 'packageId' added later. */
|
|
|
|
interface PathAndExtension {
|
|
|
|
path: string;
|
|
|
|
// (Use a different name than `extension` to make sure Resolved isn't assignable to PathAndExtension.)
|
|
|
|
ext: Extension;
|
2016-10-13 22:02:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2016-10-25 21:38:59 +02:00
|
|
|
* Kinds of file that we are currently looking for.
|
|
|
|
* Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
|
2016-10-13 22:02:22 +02:00
|
|
|
*/
|
2016-12-28 00:50:14 +01:00
|
|
|
enum Extensions {
|
2016-10-25 21:38:59 +02:00
|
|
|
TypeScript, /** '.ts', '.tsx', or '.d.ts' */
|
|
|
|
JavaScript, /** '.js' or '.jsx' */
|
2017-01-17 22:51:00 +01:00
|
|
|
Json, /** '.json' */
|
2018-10-25 19:19:57 +02:00
|
|
|
TSConfig, /** '.json' with `tsconfig` used instead of `index` */
|
2016-10-25 21:38:59 +02:00
|
|
|
DtsOnly /** Only '.d.ts' */
|
2016-10-13 22:02:22 +02:00
|
|
|
}
|
|
|
|
|
2017-09-07 23:31:20 +02:00
|
|
|
interface PathAndPackageId {
|
|
|
|
readonly fileName: string;
|
2018-05-22 23:46:57 +02:00
|
|
|
readonly packageId: PackageId | undefined;
|
2017-09-07 23:31:20 +02:00
|
|
|
}
|
2016-10-25 21:38:59 +02:00
|
|
|
/** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
|
2017-09-07 23:31:20 +02:00
|
|
|
function resolvedTypeScriptOnly(resolved: Resolved | undefined): PathAndPackageId | undefined {
|
2016-10-25 21:38:59 +02:00
|
|
|
if (!resolved) {
|
|
|
|
return undefined;
|
|
|
|
}
|
2018-09-14 00:05:57 +02:00
|
|
|
Debug.assert(extensionIsTS(resolved.extension));
|
2017-09-07 23:31:20 +02:00
|
|
|
return { fileName: resolved.path, packageId: resolved.packageId };
|
2016-10-13 22:02:22 +02:00
|
|
|
}
|
|
|
|
|
2020-03-11 22:35:26 +01:00
|
|
|
function createResolvedModuleWithFailedLookupLocations(resolved: Resolved | undefined, isExternalLibraryImport: boolean | undefined, failedLookupLocations: string[], resultFromCache: ResolvedModuleWithFailedLookupLocations | undefined): ResolvedModuleWithFailedLookupLocations {
|
|
|
|
if (resultFromCache) {
|
|
|
|
resultFromCache.failedLookupLocations.push(...failedLookupLocations);
|
|
|
|
return resultFromCache;
|
|
|
|
}
|
2017-05-11 22:39:37 +02:00
|
|
|
return {
|
2018-08-11 00:23:35 +02:00
|
|
|
resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport, packageId: resolved.packageId },
|
2017-05-11 22:39:37 +02:00
|
|
|
failedLookupLocations
|
|
|
|
};
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
|
2016-10-13 22:02:22 +02:00
|
|
|
interface ModuleResolutionState {
|
2016-09-27 19:22:41 +02:00
|
|
|
host: ModuleResolutionHost;
|
2016-10-28 23:15:15 +02:00
|
|
|
compilerOptions: CompilerOptions;
|
2016-09-27 19:22:41 +02:00
|
|
|
traceEnabled: boolean;
|
2018-08-27 21:06:45 +02:00
|
|
|
failedLookupLocations: Push<string>;
|
2020-03-11 22:35:26 +01:00
|
|
|
resultFromCache?: ResolvedModuleWithFailedLookupLocations;
|
2016-10-13 22:02:22 +02:00
|
|
|
}
|
|
|
|
|
2017-10-16 22:02:15 +02:00
|
|
|
/** Just the fields that we use for module resolution. */
|
|
|
|
interface PackageJsonPathFields {
|
2017-08-09 23:39:06 +02:00
|
|
|
typings?: string;
|
|
|
|
types?: string;
|
2018-08-27 21:06:45 +02:00
|
|
|
typesVersions?: MapLike<MapLike<string[]>>;
|
2017-08-09 23:39:06 +02:00
|
|
|
main?: string;
|
2018-10-25 19:19:57 +02:00
|
|
|
tsconfig?: string;
|
2017-08-09 23:39:06 +02:00
|
|
|
}
|
|
|
|
|
2017-10-16 22:02:15 +02:00
|
|
|
interface PackageJson extends PackageJsonPathFields {
|
|
|
|
name?: string;
|
|
|
|
version?: string;
|
|
|
|
}
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
function readPackageJsonField<TMatch, K extends MatchingKeys<PackageJson, string | undefined>>(jsonContent: PackageJson, fieldName: K, typeOfTag: "string", state: ModuleResolutionState): PackageJson[K] | undefined;
|
|
|
|
function readPackageJsonField<K extends MatchingKeys<PackageJson, object | undefined>>(jsonContent: PackageJson, fieldName: K, typeOfTag: "object", state: ModuleResolutionState): PackageJson[K] | undefined;
|
|
|
|
function readPackageJsonField<K extends keyof PackageJson>(jsonContent: PackageJson, fieldName: K, typeOfTag: "string" | "object", state: ModuleResolutionState): PackageJson[K] | undefined {
|
|
|
|
if (!hasProperty(jsonContent, fieldName)) {
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName);
|
2017-01-25 16:31:24 +01:00
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
const value = jsonContent[fieldName];
|
2019-07-18 09:50:38 +02:00
|
|
|
if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
|
2018-08-27 21:06:45 +02:00
|
|
|
if (state.traceEnabled) {
|
2019-07-18 09:50:38 +02:00
|
|
|
// eslint-disable-next-line no-null/no-null
|
2018-08-27 21:06:45 +02:00
|
|
|
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value);
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
return value;
|
|
|
|
}
|
2016-10-25 21:38:59 +02:00
|
|
|
|
2018-10-25 19:19:57 +02:00
|
|
|
function readPackageJsonPathField<K extends "typings" | "types" | "main" | "tsconfig">(jsonContent: PackageJson, fieldName: K, baseDirectory: string, state: ModuleResolutionState): PackageJson[K] | undefined {
|
2018-08-27 21:06:45 +02:00
|
|
|
const fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
|
2019-05-24 02:19:32 +02:00
|
|
|
if (fileName === undefined) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (!fileName) {
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.package_json_had_a_falsy_0_field, fieldName);
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
const path = normalizePath(combinePaths(baseDirectory, fileName));
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
|
|
|
|
}
|
|
|
|
return path;
|
|
|
|
}
|
|
|
|
|
|
|
|
function readPackageJsonTypesFields(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) {
|
|
|
|
return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
|
|
|
|
|| readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
|
|
|
|
}
|
|
|
|
|
2018-10-25 19:19:57 +02:00
|
|
|
function readPackageJsonTSConfigField(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) {
|
|
|
|
return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
|
|
|
|
}
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
function readPackageJsonMainField(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) {
|
|
|
|
return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
|
|
|
|
}
|
|
|
|
|
|
|
|
function readPackageJsonTypesVersionsField(jsonContent: PackageJson, state: ModuleResolutionState) {
|
|
|
|
const typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
|
|
|
|
if (typesVersions === undefined) return;
|
|
|
|
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
|
|
|
|
}
|
|
|
|
|
|
|
|
return typesVersions;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface VersionPaths {
|
|
|
|
version: string;
|
|
|
|
paths: MapLike<string[]>;
|
|
|
|
}
|
|
|
|
|
|
|
|
function readPackageJsonTypesVersionPaths(jsonContent: PackageJson, state: ModuleResolutionState): VersionPaths | undefined {
|
|
|
|
const typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
|
|
|
|
if (typesVersions === undefined) return;
|
|
|
|
|
2018-09-05 20:23:39 +02:00
|
|
|
if (state.traceEnabled) {
|
|
|
|
for (const key in typesVersions) {
|
|
|
|
if (hasProperty(typesVersions, key) && !VersionRange.tryParse(key)) {
|
|
|
|
trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
const result = getPackageJsonTypesVersionsPaths(typesVersions);
|
|
|
|
if (!result) {
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, versionMajorMinor);
|
2017-01-25 16:31:24 +01:00
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
return;
|
|
|
|
}
|
2016-10-25 21:38:59 +02:00
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
const { version: bestVersionKey, paths: bestVersionPaths } = result;
|
|
|
|
if (typeof bestVersionPaths !== "object") {
|
2017-01-25 16:31:24 +01:00
|
|
|
if (state.traceEnabled) {
|
2018-08-27 21:06:45 +02:00
|
|
|
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersions['${bestVersionKey}']`, "object", typeof bestVersionPaths);
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
return;
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
return result;
|
2018-08-22 20:22:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
let typeScriptVersion: Version | undefined;
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
/* @internal */
|
|
|
|
export function getPackageJsonTypesVersionsPaths(typesVersions: MapLike<MapLike<string[]>>) {
|
2018-08-29 02:24:02 +02:00
|
|
|
if (!typeScriptVersion) typeScriptVersion = new Version(version);
|
2018-08-22 20:22:09 +02:00
|
|
|
|
2018-08-18 03:27:45 +02:00
|
|
|
for (const key in typesVersions) {
|
|
|
|
if (!hasProperty(typesVersions, key)) continue;
|
|
|
|
|
2018-08-29 02:24:02 +02:00
|
|
|
const keyRange = VersionRange.tryParse(key);
|
|
|
|
if (keyRange === undefined) {
|
2018-08-18 03:27:45 +02:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2018-08-29 02:24:02 +02:00
|
|
|
// return the first entry whose range matches the current compiler version.
|
|
|
|
if (keyRange.test(typeScriptVersion)) {
|
|
|
|
return { version: key, paths: typesVersions[key] };
|
2018-08-18 03:27:45 +02:00
|
|
|
}
|
|
|
|
}
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
|
Add exported members of all project files in the global completion list (#19069)
* checker.ts: Remove null check on symbols
* tsserverProjectSystem.ts: add two tests
* client.ts, completions.ts, types.ts: Add codeActions member to CompletionEntryDetails
* protocol.ts, session.ts: Add codeActions member to CompletionEntryDetails protocol
* protocol.ts, session.ts, types.ts: add hasAction to CompletionEntry
* session.ts, services.ts, types.ts: Add formattingOptions parameter to getCompletionEntryDetails
* completions.ts: define SymbolOriginInfo type
* completions.ts, services.ts: Add allSourceFiles parameter to getCompletionsAtPosition
* completions.ts, services.ts: Plumb allSourceFiles into new function getSymbolsFromOtherSourceFileExports inside getCompletionData
* completions.ts: add symbolToOriginInfoMap parameter to getCompletionEntriesFromSymbols and to return value of getCompletionData
* utilities.ts: Add getOtherModuleSymbols, getUniqueSymbolIdAsString, getUniqueSymbolId
* completions.ts: Set CompletionEntry.hasAction when symbol is found in symbolToOriginInfoMap (meaning there's an import action)
* completions.ts: Populate list with possible exports (implement getSymbolsFromOtherSourceFileExports)
* completions.ts, services.ts: Plumb host and rulesProvider into getCompletionEntryDetails
* completions.ts: Add TODO comment
* importFixes.ts: Add types ImportDeclarationMap and ImportCodeFixContext
* Move getImportDeclarations into getCodeActionForImport, immediately after the implementation
* importFixes.ts: Move createChangeTracker into getCodeActionForImport, immediately after getImportDeclarations
* importFixes.ts: Add convertToImportCodeFixContext function and reference it from the getCodeActions lambda
* importFixes.ts: Add context: ImportCodeFixContext parameter to getCodeActionForImport, update call sites, destructure it, use compilerOptions in getModuleSpecifierForNewImport
* importFixes.ts: Remove moduleSymbol parameter from getImportDeclarations and use the ambient one
* importFixes.ts: Use cachedImportDeclarations from context in getCodeActionForImport
* importFixes.ts: Move createCodeAction out, immediately above convertToImportCodeFixContext
* Move the declaration for lastImportDeclaration out of the getCodeActions lambda into getCodeActionForImport
* importFixes.ts: Use symbolToken in getCodeActionForImport
* importFixes.ts: Remove useCaseSensitiveFileNames altogether from getCodeActions lambda
* importFixes.ts: Remove local getUniqueSymbolId function and add checker parameter to calls to it
* importFixes.ts: Move getCodeActionForImport out into an export, immediately below convertToImportCodeFixContext
* completions.ts: In getCompletionEntryDetails, if there's symbolOriginInfo, call getCodeActionForImport
* importFixes.ts: Create and use importFixContext within getCodeActions lambda
* importFixes.ts: Use local newLineCharacter instead of context.newLineCharacter in getCodeActionForImport
* importFixes.ts: Use local host instead of context.host in getCodeActionForImport
* importFixes.ts: Remove dummy getCanonicalFileName line
* Filter symbols after gathering exports instead of before
* Lint
* Test, fix bugs, refactor
* Suggestions from code review
* Update api baseline
* Fix bug if previousToken is not an Identifier
* Replace `startsWith` with `stringContainsCharactersInOrder`
2017-10-17 19:20:11 +02:00
|
|
|
export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined {
|
2016-09-27 19:22:41 +02:00
|
|
|
if (options.typeRoots) {
|
|
|
|
return options.typeRoots;
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
|
2018-05-22 23:46:57 +02:00
|
|
|
let currentDirectory: string | undefined;
|
2016-09-27 19:22:41 +02:00
|
|
|
if (options.configFilePath) {
|
|
|
|
currentDirectory = getDirectoryPath(options.configFilePath);
|
|
|
|
}
|
|
|
|
else if (host.getCurrentDirectory) {
|
|
|
|
currentDirectory = host.getCurrentDirectory();
|
|
|
|
}
|
|
|
|
|
2016-10-28 23:15:15 +02:00
|
|
|
if (currentDirectory !== undefined) {
|
|
|
|
return getDefaultTypeRoots(currentDirectory, host);
|
|
|
|
}
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2016-09-27 19:22:41 +02:00
|
|
|
* Returns the path to every node_modules/@types directory from some ancestor directory.
|
|
|
|
* Returns undefined if there are none.
|
2016-09-08 22:26:01 +02:00
|
|
|
*/
|
2016-09-27 19:22:41 +02:00
|
|
|
function getDefaultTypeRoots(currentDirectory: string, host: { directoryExists?: (directoryName: string) => boolean }): string[] | undefined {
|
|
|
|
if (!host.directoryExists) {
|
|
|
|
return [combinePaths(currentDirectory, nodeModulesAtTypes)];
|
|
|
|
// And if it doesn't exist, tough.
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
|
2018-05-22 23:46:57 +02:00
|
|
|
let typeRoots: string[] | undefined;
|
2018-03-01 23:20:18 +01:00
|
|
|
forEachAncestorDirectory(normalizePath(currentDirectory), directory => {
|
2016-10-28 23:15:15 +02:00
|
|
|
const atTypes = combinePaths(directory, nodeModulesAtTypes);
|
2018-05-22 23:46:57 +02:00
|
|
|
if (host.directoryExists!(atTypes)) {
|
2016-09-27 19:22:41 +02:00
|
|
|
(typeRoots || (typeRoots = [])).push(atTypes);
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
2016-12-21 19:02:28 +01:00
|
|
|
return undefined;
|
2016-10-28 23:15:15 +02:00
|
|
|
});
|
2016-09-27 19:22:41 +02:00
|
|
|
return typeRoots;
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
const nodeModulesAtTypes = combinePaths("node_modules", "@types");
|
2016-09-08 22:26:01 +02:00
|
|
|
|
2016-09-27 19:22:41 +02:00
|
|
|
/**
|
|
|
|
* @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
|
|
|
|
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
|
|
|
|
* is assumed to be the same as root directory of the project.
|
|
|
|
*/
|
2018-10-02 00:30:06 +02:00
|
|
|
export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
|
2016-09-27 19:22:41 +02:00
|
|
|
const traceEnabled = isTraceEnabled(options, host);
|
2018-10-02 00:30:06 +02:00
|
|
|
if (redirectedReference) {
|
|
|
|
options = redirectedReference.commandLine.options;
|
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
const failedLookupLocations: string[] = [];
|
|
|
|
const moduleResolutionState: ModuleResolutionState = { compilerOptions: options, host, traceEnabled, failedLookupLocations };
|
2016-09-08 22:26:01 +02:00
|
|
|
|
2016-09-27 19:22:41 +02:00
|
|
|
const typeRoots = getEffectiveTypeRoots(options, host);
|
|
|
|
if (traceEnabled) {
|
|
|
|
if (containingFile === undefined) {
|
|
|
|
if (typeRoots === undefined) {
|
|
|
|
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
2016-09-27 19:22:41 +02:00
|
|
|
if (typeRoots === undefined) {
|
|
|
|
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
|
|
|
|
}
|
|
|
|
}
|
2018-10-02 00:30:06 +02:00
|
|
|
if (redirectedReference) {
|
|
|
|
trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
|
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
|
2016-11-09 16:41:25 +01:00
|
|
|
let resolved = primaryLookup();
|
|
|
|
let primary = true;
|
|
|
|
if (!resolved) {
|
|
|
|
resolved = secondaryLookup();
|
|
|
|
primary = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
let resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined;
|
|
|
|
if (resolved) {
|
2018-10-20 03:00:45 +02:00
|
|
|
const { fileName, packageId } = resolved;
|
|
|
|
const resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
|
2016-09-27 19:22:41 +02:00
|
|
|
if (traceEnabled) {
|
2019-05-22 20:06:49 +02:00
|
|
|
if (packageId) {
|
|
|
|
trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, packageIdToString(packageId), primary);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
|
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2018-10-20 03:00:45 +02:00
|
|
|
resolvedTypeReferenceDirective = { primary, resolvedFileName, packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
|
2016-11-09 16:41:25 +01:00
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
|
2016-11-09 16:41:25 +01:00
|
|
|
return { resolvedTypeReferenceDirective, failedLookupLocations };
|
2016-10-13 22:02:22 +02:00
|
|
|
|
2017-09-07 23:31:20 +02:00
|
|
|
function primaryLookup(): PathAndPackageId | undefined {
|
2016-11-09 16:41:25 +01:00
|
|
|
// Check primary library paths
|
|
|
|
if (typeRoots && typeRoots.length) {
|
|
|
|
if (traceEnabled) {
|
|
|
|
trace(host, Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
2018-10-20 03:00:45 +02:00
|
|
|
return firstDefined(typeRoots, typeRoot => {
|
2016-11-09 16:41:25 +01:00
|
|
|
const candidate = combinePaths(typeRoot, typeReferenceDirectiveName);
|
|
|
|
const candidateDirectory = getDirectoryPath(candidate);
|
2016-12-28 00:50:14 +01:00
|
|
|
const directoryExists = directoryProbablyExists(candidateDirectory, host);
|
|
|
|
if (!directoryExists && traceEnabled) {
|
|
|
|
trace(host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
|
|
|
|
}
|
2016-11-09 16:41:25 +01:00
|
|
|
return resolvedTypeScriptOnly(
|
2018-08-27 21:06:45 +02:00
|
|
|
loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate,
|
2016-12-28 00:50:14 +01:00
|
|
|
!directoryExists, moduleResolutionState));
|
2016-11-09 16:41:25 +01:00
|
|
|
});
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
2016-11-09 16:41:25 +01:00
|
|
|
else {
|
|
|
|
if (traceEnabled) {
|
|
|
|
trace(host, Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
|
|
|
|
}
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-09-07 23:31:20 +02:00
|
|
|
function secondaryLookup(): PathAndPackageId | undefined {
|
2016-11-09 16:41:25 +01:00
|
|
|
const initialLocationForSecondaryLookup = containingFile && getDirectoryPath(containingFile);
|
2016-09-08 22:26:01 +02:00
|
|
|
|
2016-11-09 16:41:25 +01:00
|
|
|
if (initialLocationForSecondaryLookup !== undefined) {
|
|
|
|
// check secondary locations
|
|
|
|
if (traceEnabled) {
|
|
|
|
trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
2018-10-20 03:00:45 +02:00
|
|
|
let result: Resolved | undefined;
|
2018-09-28 19:53:53 +02:00
|
|
|
if (!isExternalModuleNameRelative(typeReferenceDirectiveName)) {
|
2018-10-20 03:00:45 +02:00
|
|
|
const searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
|
|
|
|
result = searchResult && searchResult.value;
|
2018-09-28 19:53:53 +02:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
const { path: candidate } = normalizePathAndParts(combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName));
|
2018-10-20 03:00:45 +02:00
|
|
|
result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
|
2018-09-28 19:53:53 +02:00
|
|
|
}
|
2018-10-20 03:00:45 +02:00
|
|
|
const resolvedFile = resolvedTypeScriptOnly(result);
|
2016-11-09 16:41:25 +01:00
|
|
|
if (!resolvedFile && traceEnabled) {
|
2016-09-27 19:22:41 +02:00
|
|
|
trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
2016-11-09 16:41:25 +01:00
|
|
|
return resolvedFile;
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
2016-11-09 16:41:25 +01:00
|
|
|
else {
|
|
|
|
if (traceEnabled) {
|
|
|
|
trace(host, Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
|
|
|
|
}
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-27 19:22:41 +02:00
|
|
|
/**
|
2017-04-03 18:32:39 +02:00
|
|
|
* Given a set of options, returns the set of type directive names
|
|
|
|
* that should be included for this program automatically.
|
|
|
|
* This list could either come from the config file,
|
|
|
|
* or from enumerating the types root + initial secondary types lookup location.
|
|
|
|
* More type directives might appear in the program later as a result of loading actual source files;
|
|
|
|
* this list is only the set of defaults that are implicitly included.
|
|
|
|
*/
|
2016-09-27 19:22:41 +02:00
|
|
|
export function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[] {
|
|
|
|
// Use explicit type list from tsconfig.json
|
|
|
|
if (options.types) {
|
|
|
|
return options.types;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Walk the primary type lookup locations
|
|
|
|
const result: string[] = [];
|
|
|
|
if (host.directoryExists && host.getDirectories) {
|
|
|
|
const typeRoots = getEffectiveTypeRoots(options, host);
|
|
|
|
if (typeRoots) {
|
|
|
|
for (const root of typeRoots) {
|
|
|
|
if (host.directoryExists(root)) {
|
|
|
|
for (const typeDirectivePath of host.getDirectories(root)) {
|
|
|
|
const normalized = normalizePath(typeDirectivePath);
|
2018-08-27 21:06:45 +02:00
|
|
|
const packageJsonPath = combinePaths(root, normalized, "package.json");
|
2017-07-26 16:09:22 +02:00
|
|
|
// `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
|
|
|
|
// See `createNotNeededPackageJSON` in the types-publisher` repo.
|
2019-07-18 09:50:38 +02:00
|
|
|
// eslint-disable-next-line no-null/no-null
|
2018-04-06 21:19:08 +02:00
|
|
|
const isNotNeededPackage = host.fileExists(packageJsonPath) && (readJson(packageJsonPath, host) as PackageJson).typings === null;
|
2016-09-27 19:22:41 +02:00
|
|
|
if (!isNotNeededPackage) {
|
2018-09-21 10:11:41 +02:00
|
|
|
const baseFileName = getBaseFileName(normalized);
|
|
|
|
|
|
|
|
// At this stage, skip results with leading dot.
|
|
|
|
if (baseFileName.charCodeAt(0) !== CharacterCodes.dot) {
|
|
|
|
// Return just the type directive names
|
|
|
|
result.push(baseFileName);
|
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return result;
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
|
2016-12-19 22:48:45 +01:00
|
|
|
/**
|
|
|
|
* Cached module resolutions per containing directory.
|
|
|
|
* This assumes that any module id will have the same resolution for sibling files located in the same folder.
|
|
|
|
*/
|
2016-12-21 19:02:28 +01:00
|
|
|
export interface ModuleResolutionCache extends NonRelativeModuleNameResolutionCache {
|
2020-07-02 02:00:26 +02:00
|
|
|
getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference): Map<ResolvedModuleWithFailedLookupLocations>;
|
|
|
|
/*@internal*/ directoryToModuleNameMap: CacheWithRedirects<ESMap<string, ResolvedModuleWithFailedLookupLocations>>;
|
2016-12-19 22:48:45 +01:00
|
|
|
}
|
|
|
|
|
2016-12-21 19:02:28 +01:00
|
|
|
/**
|
|
|
|
* Stored map from non-relative module name to a table: directory -> result of module lookup in this directory
|
|
|
|
* We support only non-relative module names because resolution of relative module names is usually more deterministic and thus less expensive.
|
|
|
|
*/
|
|
|
|
export interface NonRelativeModuleNameResolutionCache {
|
2018-10-02 01:07:52 +02:00
|
|
|
getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache;
|
2019-04-24 21:38:25 +02:00
|
|
|
/*@internal*/ moduleNameToDirectoryMap: CacheWithRedirects<PerModuleNameCache>;
|
2016-12-21 19:02:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export interface PerModuleNameCache {
|
2018-05-22 23:46:57 +02:00
|
|
|
get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined;
|
2016-12-21 19:02:28 +01:00
|
|
|
set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void;
|
|
|
|
}
|
|
|
|
|
2019-04-24 00:32:02 +02:00
|
|
|
export function createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: CompilerOptions): ModuleResolutionCache {
|
2018-02-22 20:09:23 +01:00
|
|
|
return createModuleResolutionCacheWithMaps(
|
2019-04-24 00:32:02 +02:00
|
|
|
createCacheWithRedirects(options),
|
|
|
|
createCacheWithRedirects(options),
|
2018-02-22 20:09:23 +01:00
|
|
|
currentDirectory,
|
|
|
|
getCanonicalFileName
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2019-04-24 21:38:25 +02:00
|
|
|
|
2018-10-02 01:07:52 +02:00
|
|
|
/*@internal*/
|
|
|
|
export interface CacheWithRedirects<T> {
|
2020-07-02 02:00:26 +02:00
|
|
|
ownMap: ESMap<string, T>;
|
|
|
|
redirectsMap: ESMap<Path, ESMap<string, T>>;
|
|
|
|
getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined): ESMap<string, T>;
|
2018-10-02 01:07:52 +02:00
|
|
|
clear(): void;
|
2019-04-24 21:38:25 +02:00
|
|
|
setOwnOptions(newOptions: CompilerOptions): void;
|
2020-07-02 02:00:26 +02:00
|
|
|
setOwnMap(newOwnMap: ESMap<string, T>): void;
|
2018-10-02 01:07:52 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/*@internal*/
|
2019-04-24 00:32:02 +02:00
|
|
|
export function createCacheWithRedirects<T>(options?: CompilerOptions): CacheWithRedirects<T> {
|
2020-07-07 22:53:46 +02:00
|
|
|
let ownMap: ESMap<string, T> = new Map();
|
2020-07-02 02:00:26 +02:00
|
|
|
const redirectsMap = new Map<Path, ESMap<string, T>>();
|
2018-10-02 01:07:52 +02:00
|
|
|
return {
|
|
|
|
ownMap,
|
|
|
|
redirectsMap,
|
|
|
|
getOrCreateMapOfCacheRedirects,
|
2019-04-24 21:38:25 +02:00
|
|
|
clear,
|
|
|
|
setOwnOptions,
|
|
|
|
setOwnMap
|
2018-10-02 01:07:52 +02:00
|
|
|
};
|
|
|
|
|
2019-04-24 21:38:25 +02:00
|
|
|
function setOwnOptions(newOptions: CompilerOptions) {
|
|
|
|
options = newOptions;
|
|
|
|
}
|
|
|
|
|
2020-07-02 02:00:26 +02:00
|
|
|
function setOwnMap(newOwnMap: ESMap<string, T>) {
|
2019-04-24 21:38:25 +02:00
|
|
|
ownMap = newOwnMap;
|
|
|
|
}
|
|
|
|
|
2018-10-02 01:07:52 +02:00
|
|
|
function getOrCreateMapOfCacheRedirects(redirectedReference: ResolvedProjectReference | undefined) {
|
|
|
|
if (!redirectedReference) {
|
|
|
|
return ownMap;
|
|
|
|
}
|
|
|
|
const path = redirectedReference.sourceFile.path;
|
|
|
|
let redirects = redirectsMap.get(path);
|
|
|
|
if (!redirects) {
|
2019-04-24 00:32:02 +02:00
|
|
|
// Reuse map if redirected reference map uses same resolution
|
2020-06-26 01:03:25 +02:00
|
|
|
redirects = !options || optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? new Map() : ownMap;
|
2018-10-02 01:07:52 +02:00
|
|
|
redirectsMap.set(path, redirects);
|
|
|
|
}
|
|
|
|
return redirects;
|
|
|
|
}
|
|
|
|
|
|
|
|
function clear() {
|
|
|
|
ownMap.clear();
|
|
|
|
redirectsMap.clear();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-22 20:09:23 +01:00
|
|
|
/*@internal*/
|
|
|
|
export function createModuleResolutionCacheWithMaps(
|
2020-07-02 02:00:26 +02:00
|
|
|
directoryToModuleNameMap: CacheWithRedirects<ESMap<string, ResolvedModuleWithFailedLookupLocations>>,
|
2018-10-02 01:07:52 +02:00
|
|
|
moduleNameToDirectoryMap: CacheWithRedirects<PerModuleNameCache>,
|
2018-02-22 20:09:23 +01:00
|
|
|
currentDirectory: string,
|
|
|
|
getCanonicalFileName: GetCanonicalFileName): ModuleResolutionCache {
|
2016-12-19 22:48:45 +01:00
|
|
|
|
2019-04-24 21:38:25 +02:00
|
|
|
return { getOrCreateCacheForDirectory, getOrCreateCacheForModuleName, directoryToModuleNameMap, moduleNameToDirectoryMap };
|
2016-12-19 22:48:45 +01:00
|
|
|
|
2018-10-02 01:07:52 +02:00
|
|
|
function getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference) {
|
2016-12-19 22:48:45 +01:00
|
|
|
const path = toPath(directoryName, currentDirectory, getCanonicalFileName);
|
2020-07-07 22:53:46 +02:00
|
|
|
return getOrCreateCache<ESMap<string, ResolvedModuleWithFailedLookupLocations>>(directoryToModuleNameMap, redirectedReference, path, () => new Map());
|
2016-12-19 22:48:45 +01:00
|
|
|
}
|
2016-12-21 19:02:28 +01:00
|
|
|
|
2018-10-02 01:07:52 +02:00
|
|
|
function getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache {
|
2018-08-11 00:59:08 +02:00
|
|
|
Debug.assert(!isExternalModuleNameRelative(nonRelativeModuleName));
|
2018-10-02 01:07:52 +02:00
|
|
|
return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
|
|
|
|
}
|
|
|
|
|
|
|
|
function getOrCreateCache<T>(cacheWithRedirects: CacheWithRedirects<T>, redirectedReference: ResolvedProjectReference | undefined, key: string, create: () => T): T {
|
|
|
|
const cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
|
|
|
|
let result = cache.get(key);
|
|
|
|
if (!result) {
|
|
|
|
result = create();
|
|
|
|
cache.set(key, result);
|
2016-12-21 19:02:28 +01:00
|
|
|
}
|
2018-10-02 01:07:52 +02:00
|
|
|
return result;
|
2016-12-21 19:02:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
function createPerModuleNameCache(): PerModuleNameCache {
|
2020-06-26 01:03:25 +02:00
|
|
|
const directoryPathMap = new Map<string, ResolvedModuleWithFailedLookupLocations>();
|
2016-12-21 19:02:28 +01:00
|
|
|
|
|
|
|
return { get, set };
|
|
|
|
|
2018-05-22 23:46:57 +02:00
|
|
|
function get(directory: string): ResolvedModuleWithFailedLookupLocations | undefined {
|
2016-12-21 19:02:28 +01:00
|
|
|
return directoryPathMap.get(toPath(directory, currentDirectory, getCanonicalFileName));
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* At first this function add entry directory -> module resolution result to the table.
|
|
|
|
* Then it computes the set of parent folders for 'directory' that should have the same module resolution result
|
|
|
|
* and for every parent folder in set it adds entry: parent -> module resolution. .
|
|
|
|
* Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
|
2017-01-09 16:47:52 +01:00
|
|
|
* Set of parent folders that should have the same result will be:
|
2016-12-21 19:02:28 +01:00
|
|
|
* [
|
|
|
|
* /a/b/c/d, /a/b/c, /a/b
|
|
|
|
* ]
|
|
|
|
* this means that request for module resolution from file in any of these folder will be immediately found in cache.
|
|
|
|
*/
|
|
|
|
function set(directory: string, result: ResolvedModuleWithFailedLookupLocations): void {
|
|
|
|
const path = toPath(directory, currentDirectory, getCanonicalFileName);
|
|
|
|
// if entry is already in cache do nothing
|
2017-06-28 22:15:34 +02:00
|
|
|
if (directoryPathMap.has(path)) {
|
2016-12-21 19:02:28 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
directoryPathMap.set(path, result);
|
|
|
|
|
2018-08-08 11:12:48 +02:00
|
|
|
const resolvedFileName = result.resolvedModule &&
|
|
|
|
(result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
|
2016-12-21 19:02:28 +01:00
|
|
|
// find common prefix between directory and resolved file name
|
2018-08-08 20:45:31 +02:00
|
|
|
// this common prefix should be the shortest path that has the same resolution
|
2016-12-21 19:02:28 +01:00
|
|
|
// directory: /a/b/c/d/e
|
|
|
|
// resolvedFileName: /a/b/foo.d.ts
|
2018-08-08 20:45:31 +02:00
|
|
|
// commonPrefix: /a/b
|
2018-08-09 11:50:00 +02:00
|
|
|
// for failed lookups cache the result for every directory up to root
|
|
|
|
const commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
|
2016-12-21 19:02:28 +01:00
|
|
|
let current = path;
|
2018-08-08 16:58:35 +02:00
|
|
|
while (current !== commonPrefix) {
|
2016-12-21 19:02:28 +01:00
|
|
|
const parent = getDirectoryPath(current);
|
2017-06-28 22:15:34 +02:00
|
|
|
if (parent === current || directoryPathMap.has(parent)) {
|
2016-12-21 19:02:28 +01:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
directoryPathMap.set(parent, result);
|
|
|
|
current = parent;
|
|
|
|
}
|
|
|
|
}
|
2016-12-28 17:58:31 +01:00
|
|
|
|
2018-08-08 20:45:31 +02:00
|
|
|
function getCommonPrefix(directory: Path, resolution: string) {
|
2016-12-21 19:02:28 +01:00
|
|
|
const resolutionDirectory = toPath(getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
|
|
|
|
|
2018-08-10 22:11:16 +02:00
|
|
|
// find first position where directory and resolution differs
|
|
|
|
let i = 0;
|
|
|
|
const limit = Math.min(directory.length, resolutionDirectory.length);
|
|
|
|
while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
|
|
|
|
i++;
|
|
|
|
}
|
|
|
|
if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === directorySeparator)) {
|
|
|
|
return directory;
|
|
|
|
}
|
|
|
|
const rootLength = getRootLength(directory);
|
|
|
|
if (i < rootLength) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
const sep = directory.lastIndexOf(directorySeparator, i - 1);
|
|
|
|
if (sep === -1) {
|
|
|
|
return undefined;
|
2016-12-21 19:02:28 +01:00
|
|
|
}
|
2018-08-10 22:11:16 +02:00
|
|
|
return directory.substr(0, Math.max(sep, rootLength));
|
2016-12-21 19:02:28 +01:00
|
|
|
}
|
|
|
|
}
|
2016-12-19 22:48:45 +01:00
|
|
|
}
|
|
|
|
|
2018-04-20 22:43:09 +02:00
|
|
|
export function resolveModuleNameFromCache(moduleName: string, containingFile: string, cache: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations | undefined {
|
|
|
|
const containingDirectory = getDirectoryPath(containingFile);
|
|
|
|
const perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
|
|
|
|
return perFolderCache && perFolderCache.get(moduleName);
|
|
|
|
}
|
|
|
|
|
2018-10-02 00:30:06 +02:00
|
|
|
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations {
|
2016-09-08 22:26:01 +02:00
|
|
|
const traceEnabled = isTraceEnabled(compilerOptions, host);
|
2018-10-02 00:30:06 +02:00
|
|
|
if (redirectedReference) {
|
|
|
|
compilerOptions = redirectedReference.commandLine.options;
|
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
if (traceEnabled) {
|
|
|
|
trace(host, Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
|
2018-10-02 00:30:06 +02:00
|
|
|
if (redirectedReference) {
|
|
|
|
trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
|
|
|
|
}
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
2016-12-21 19:02:28 +01:00
|
|
|
const containingDirectory = getDirectoryPath(containingFile);
|
2018-10-02 01:07:52 +02:00
|
|
|
const perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
|
2016-12-27 21:56:05 +01:00
|
|
|
let result = perFolderCache && perFolderCache.get(moduleName);
|
2016-09-08 22:26:01 +02:00
|
|
|
|
2016-12-19 22:48:45 +01:00
|
|
|
if (result) {
|
2016-09-27 19:22:41 +02:00
|
|
|
if (traceEnabled) {
|
2018-02-22 20:09:23 +01:00
|
|
|
trace(host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
2016-12-19 22:48:45 +01:00
|
|
|
let moduleResolution = compilerOptions.moduleResolution;
|
|
|
|
if (moduleResolution === undefined) {
|
|
|
|
moduleResolution = getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
|
|
|
|
if (traceEnabled) {
|
|
|
|
trace(host, Diagnostics.Module_resolution_kind_is_not_specified_using_0, ModuleResolutionKind[moduleResolution]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
if (traceEnabled) {
|
|
|
|
trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]);
|
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2016-09-08 22:26:01 +02:00
|
|
|
|
2019-08-03 01:39:33 +02:00
|
|
|
perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
|
2016-12-19 22:48:45 +01:00
|
|
|
switch (moduleResolution) {
|
|
|
|
case ModuleResolutionKind.NodeJs:
|
2018-10-02 01:07:52 +02:00
|
|
|
result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
|
2016-12-19 22:48:45 +01:00
|
|
|
break;
|
|
|
|
case ModuleResolutionKind.Classic:
|
2018-10-02 01:07:52 +02:00
|
|
|
result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
|
2016-12-19 22:48:45 +01:00
|
|
|
break;
|
2017-05-11 18:06:01 +02:00
|
|
|
default:
|
2018-05-22 23:46:57 +02:00
|
|
|
return Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`);
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2019-08-03 01:39:33 +02:00
|
|
|
if (result && result.resolvedModule) perfLogger.logInfoEvent(`Module "${moduleName}" resolved to "${result.resolvedModule.resolvedFileName}"`);
|
|
|
|
perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
|
2016-09-08 22:26:01 +02:00
|
|
|
|
2016-12-19 22:48:45 +01:00
|
|
|
if (perFolderCache) {
|
2016-12-27 21:56:05 +01:00
|
|
|
perFolderCache.set(moduleName, result);
|
2018-08-11 00:59:08 +02:00
|
|
|
if (!isExternalModuleNameRelative(moduleName)) {
|
|
|
|
// put result in per-module name cache
|
2018-10-02 01:07:52 +02:00
|
|
|
cache!.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
|
2016-12-21 19:02:28 +01:00
|
|
|
}
|
2016-12-19 22:48:45 +01:00
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2016-09-08 22:26:01 +02:00
|
|
|
|
2016-09-27 19:22:41 +02:00
|
|
|
if (traceEnabled) {
|
|
|
|
if (result.resolvedModule) {
|
2019-05-22 20:06:49 +02:00
|
|
|
if (result.resolvedModule.packageId) {
|
|
|
|
trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1_with_Package_ID_2, moduleName, result.resolvedModule.resolvedFileName, packageIdToString(result.resolvedModule.packageId));
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
trace(host, Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
|
|
|
|
}
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
else {
|
2016-09-27 19:22:41 +02:00
|
|
|
trace(host, Diagnostics.Module_name_0_was_not_resolved, moduleName);
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-27 19:22:41 +02:00
|
|
|
return result;
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
|
2016-09-27 19:22:41 +02:00
|
|
|
/*
|
|
|
|
* Every module resolution kind can has its specific understanding how to load module from a specific path on disk
|
|
|
|
* I.e. for path '/a/b/c':
|
|
|
|
* - Node loader will first to try to check if '/a/b/c' points to a file with some supported extension and if this fails
|
|
|
|
* it will try to load module from directory: directory '/a/b/c' should exist and it should have either 'package.json' with
|
|
|
|
* 'typings' entry or file 'index' with some supported extension
|
|
|
|
* - Classic loader will only try to interpret '/a/b/c' as file.
|
|
|
|
*/
|
2018-08-27 21:06:45 +02:00
|
|
|
type ResolutionKindSpecificLoader = (extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState) => Resolved | undefined;
|
2016-09-08 22:26:01 +02:00
|
|
|
|
2016-09-27 19:22:41 +02:00
|
|
|
/**
|
|
|
|
* Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
|
|
|
|
* mitigate differences between design time structure of the project and its runtime counterpart so the same import name
|
|
|
|
* can be resolved successfully by TypeScript compiler and runtime module loader.
|
|
|
|
* If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
|
|
|
|
* fallback to standard resolution routine.
|
|
|
|
*
|
|
|
|
* - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
|
|
|
|
* names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
|
|
|
|
* be '/a/b/c/d'
|
|
|
|
* - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
|
|
|
|
* will be resolved based on the content of the module name.
|
|
|
|
* Structure of 'paths' compiler options
|
|
|
|
* 'paths': {
|
|
|
|
* pattern-1: [...substitutions],
|
|
|
|
* pattern-2: [...substitutions],
|
|
|
|
* ...
|
|
|
|
* pattern-n: [...substitutions]
|
|
|
|
* }
|
|
|
|
* Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
|
|
|
|
* all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
|
|
|
|
* If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
|
|
|
|
* <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
|
|
|
|
* If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
|
|
|
|
* After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
|
|
|
|
* from the candidate location.
|
|
|
|
* Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
|
|
|
|
* substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
|
|
|
|
* will be converted to absolute using baseUrl.
|
|
|
|
* For example:
|
|
|
|
* baseUrl: /a/b/c
|
|
|
|
* "paths": {
|
|
|
|
* // match all module names
|
|
|
|
* "*": [
|
|
|
|
* "*", // use matched name as is,
|
|
|
|
* // <matched name> will be looked as /a/b/c/<matched name>
|
|
|
|
*
|
|
|
|
* "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
|
|
|
|
* // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
|
|
|
|
* ],
|
|
|
|
* // match module names that start with 'components/'
|
|
|
|
* "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
|
|
|
|
* // it is rooted so it will be final candidate location
|
|
|
|
* }
|
|
|
|
*
|
|
|
|
* 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
|
|
|
|
* they were in the same location. For example lets say there are two files
|
|
|
|
* '/local/src/content/file1.ts'
|
|
|
|
* '/shared/components/contracts/src/content/protocols/file2.ts'
|
|
|
|
* After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
|
|
|
|
* if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
|
|
|
|
* 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
|
|
|
|
* root dirs were merged together.
|
|
|
|
* I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
|
|
|
|
* Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
|
|
|
|
* '/local/src/content/protocols/file2' and try to load it - failure.
|
|
|
|
* Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
|
|
|
|
* be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
|
|
|
|
* entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
|
|
|
|
*/
|
2016-10-25 21:38:59 +02:00
|
|
|
function tryLoadModuleUsingOptionalResolutionSettings(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader,
|
2018-08-27 21:06:45 +02:00
|
|
|
state: ModuleResolutionState): Resolved | undefined {
|
2016-09-08 22:26:01 +02:00
|
|
|
|
2018-10-19 00:10:13 +02:00
|
|
|
const resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
|
|
|
|
if (resolved) return resolved.value;
|
|
|
|
|
2017-07-13 22:46:04 +02:00
|
|
|
if (!isExternalModuleNameRelative(moduleName)) {
|
2018-08-27 21:06:45 +02:00
|
|
|
return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
else {
|
2018-08-27 21:06:45 +02:00
|
|
|
return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
|
|
|
|
2018-10-19 00:10:13 +02:00
|
|
|
function tryLoadModuleUsingPathsIfEligible(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState) {
|
|
|
|
const { baseUrl, paths } = state.compilerOptions;
|
|
|
|
if (baseUrl && paths && !pathIsRelative(moduleName)) {
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
|
|
|
|
trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
|
|
|
|
}
|
|
|
|
return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-25 21:38:59 +02:00
|
|
|
function tryLoadModuleUsingRootDirs(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader,
|
2018-08-27 21:06:45 +02:00
|
|
|
state: ModuleResolutionState): Resolved | undefined {
|
2016-09-08 22:26:01 +02:00
|
|
|
|
|
|
|
if (!state.compilerOptions.rootDirs) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
|
|
|
|
}
|
|
|
|
|
|
|
|
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
|
|
|
|
|
2018-05-22 23:46:57 +02:00
|
|
|
let matchedRootDir: string | undefined;
|
|
|
|
let matchedNormalizedPrefix: string | undefined;
|
2016-09-08 22:26:01 +02:00
|
|
|
for (const rootDir of state.compilerOptions.rootDirs) {
|
|
|
|
// rootDirs are expected to be absolute
|
|
|
|
// in case of tsconfig.json this will happen automatically - compiler will expand relative names
|
|
|
|
// using location of tsconfig.json as base location
|
|
|
|
let normalizedRoot = normalizePath(rootDir);
|
|
|
|
if (!endsWith(normalizedRoot, directorySeparator)) {
|
|
|
|
normalizedRoot += directorySeparator;
|
|
|
|
}
|
|
|
|
const isLongestMatchingPrefix =
|
|
|
|
startsWith(candidate, normalizedRoot) &&
|
|
|
|
(matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
|
|
|
|
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isLongestMatchingPrefix) {
|
|
|
|
matchedNormalizedPrefix = normalizedRoot;
|
|
|
|
matchedRootDir = rootDir;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (matchedNormalizedPrefix) {
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
|
|
|
|
}
|
|
|
|
const suffix = candidate.substr(matchedNormalizedPrefix.length);
|
|
|
|
|
|
|
|
// first - try to load from a initial location
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
|
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
const resolvedFileName = loader(extensions, candidate, !directoryProbablyExists(containingDirectory, state.host), state);
|
2016-09-08 22:26:01 +02:00
|
|
|
if (resolvedFileName) {
|
|
|
|
return resolvedFileName;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Trying_other_entries_in_rootDirs);
|
|
|
|
}
|
|
|
|
// then try to resolve using remaining entries in rootDirs
|
|
|
|
for (const rootDir of state.compilerOptions.rootDirs) {
|
|
|
|
if (rootDir === matchedRootDir) {
|
|
|
|
// skip the initially matched entry
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
const candidate = combinePaths(normalizePath(rootDir), suffix);
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate);
|
|
|
|
}
|
|
|
|
const baseDirectory = getDirectoryPath(candidate);
|
2018-08-27 21:06:45 +02:00
|
|
|
const resolvedFileName = loader(extensions, candidate, !directoryProbablyExists(baseDirectory, state.host), state);
|
2016-09-08 22:26:01 +02:00
|
|
|
if (resolvedFileName) {
|
|
|
|
return resolvedFileName;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Module_resolution_using_rootDirs_has_failed);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
function tryLoadModuleUsingBaseUrl(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState): Resolved | undefined {
|
2018-10-19 00:10:13 +02:00
|
|
|
const { baseUrl } = state.compilerOptions;
|
2018-08-27 21:06:45 +02:00
|
|
|
if (!baseUrl) {
|
2016-09-08 22:26:01 +02:00
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
if (state.traceEnabled) {
|
2018-08-27 21:06:45 +02:00
|
|
|
trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
const candidate = normalizePath(combinePaths(baseUrl, moduleName));
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
|
2016-09-08 22:26:01 +02:00
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
return loader(extensions, candidate, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
|
2017-02-14 22:35:16 +01:00
|
|
|
}
|
|
|
|
|
2017-04-06 00:24:10 +02:00
|
|
|
/**
|
|
|
|
* Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
|
|
|
|
* No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
|
|
|
|
* Throws an error if the module can't be resolved.
|
|
|
|
*/
|
2017-02-14 22:35:16 +01:00
|
|
|
/* @internal */
|
2018-09-14 00:05:57 +02:00
|
|
|
export function resolveJSModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string {
|
2018-09-18 20:47:29 +02:00
|
|
|
const { resolvedModule, failedLookupLocations } = tryResolveJSModuleWorker(moduleName, initialDir, host);
|
2017-04-06 00:24:10 +02:00
|
|
|
if (!resolvedModule) {
|
2017-08-08 16:54:08 +02:00
|
|
|
throw new Error(`Could not resolve JS module '${moduleName}' starting at '${initialDir}'. Looked in: ${failedLookupLocations.join(", ")}`);
|
2017-04-06 00:24:10 +02:00
|
|
|
}
|
|
|
|
return resolvedModule.resolvedFileName;
|
|
|
|
}
|
|
|
|
|
2018-09-18 20:47:29 +02:00
|
|
|
/* @internal */
|
|
|
|
export function tryResolveJSModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string | undefined {
|
|
|
|
const { resolvedModule } = tryResolveJSModuleWorker(moduleName, initialDir, host);
|
|
|
|
return resolvedModule && resolvedModule.resolvedFileName;
|
|
|
|
}
|
|
|
|
|
2018-10-25 19:19:57 +02:00
|
|
|
const jsOnlyExtensions = [Extensions.JavaScript];
|
|
|
|
const tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
|
|
|
|
const tsPlusJsonExtensions = [...tsExtensions, Extensions.Json];
|
|
|
|
const tsconfigExtensions = [Extensions.TSConfig];
|
2018-09-18 20:47:29 +02:00
|
|
|
function tryResolveJSModuleWorker(moduleName: string, initialDir: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
|
2018-10-25 19:19:57 +02:00
|
|
|
return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
|
2018-09-18 20:47:29 +02:00
|
|
|
}
|
|
|
|
|
2018-10-25 19:19:57 +02:00
|
|
|
export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations;
|
2019-08-19 12:38:58 +02:00
|
|
|
/* @internal */ export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, lookupConfig?: boolean): ResolvedModuleWithFailedLookupLocations; // eslint-disable-line @typescript-eslint/unified-signatures
|
2018-10-25 19:19:57 +02:00
|
|
|
export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache, redirectedReference?: ResolvedProjectReference, lookupConfig?: boolean): ResolvedModuleWithFailedLookupLocations {
|
|
|
|
return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
|
2018-08-27 21:06:45 +02:00
|
|
|
}
|
|
|
|
|
2018-10-25 19:19:57 +02:00
|
|
|
function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, extensions: Extensions[], redirectedReference: ResolvedProjectReference | undefined): ResolvedModuleWithFailedLookupLocations {
|
2016-09-27 19:22:41 +02:00
|
|
|
const traceEnabled = isTraceEnabled(compilerOptions, host);
|
|
|
|
|
|
|
|
const failedLookupLocations: string[] = [];
|
2018-08-27 21:06:45 +02:00
|
|
|
const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations };
|
2016-09-27 19:22:41 +02:00
|
|
|
|
2018-10-25 19:19:57 +02:00
|
|
|
const result = forEach(extensions, ext => tryResolve(ext));
|
2020-03-11 22:35:26 +01:00
|
|
|
return createResolvedModuleWithFailedLookupLocations(result?.value?.resolved, result?.value?.isExternalLibraryImport, failedLookupLocations, state.resultFromCache);
|
2016-10-25 21:38:59 +02:00
|
|
|
|
2018-08-11 00:23:35 +02:00
|
|
|
function tryResolve(extensions: Extensions): SearchResult<{ resolved: Resolved, isExternalLibraryImport: boolean }> {
|
2018-08-27 21:06:45 +02:00
|
|
|
const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true);
|
|
|
|
const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
|
2016-10-25 21:38:59 +02:00
|
|
|
if (resolved) {
|
2018-10-20 03:00:45 +02:00
|
|
|
return toSearchResult({ resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
|
2016-10-25 21:38:59 +02:00
|
|
|
}
|
|
|
|
|
2017-07-13 22:46:04 +02:00
|
|
|
if (!isExternalModuleNameRelative(moduleName)) {
|
2016-09-27 19:22:41 +02:00
|
|
|
if (traceEnabled) {
|
2016-12-28 00:50:14 +01:00
|
|
|
trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2018-10-02 01:07:52 +02:00
|
|
|
const resolved = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
|
2017-08-11 19:03:21 +02:00
|
|
|
if (!resolved) return undefined;
|
|
|
|
|
|
|
|
let resolvedValue = resolved.value;
|
2018-08-11 00:23:35 +02:00
|
|
|
if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
|
2018-05-22 23:46:57 +02:00
|
|
|
const path = realPath(resolvedValue.path, host, traceEnabled);
|
2018-08-11 00:23:35 +02:00
|
|
|
const originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
|
|
|
|
resolvedValue = { ...resolvedValue, path, originalPath };
|
2017-08-11 19:03:21 +02:00
|
|
|
}
|
2016-11-03 14:09:47 +01:00
|
|
|
// For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
|
2018-08-11 00:23:35 +02:00
|
|
|
return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
else {
|
2017-08-17 22:26:38 +02:00
|
|
|
const { path: candidate, parts } = normalizePathAndParts(combinePaths(containingDirectory, moduleName));
|
2018-08-27 21:06:45 +02:00
|
|
|
const resolved = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
|
2017-08-17 22:26:38 +02:00
|
|
|
// Treat explicit "node_modules" import as an external library import.
|
|
|
|
return resolved && toSearchResult({ resolved, isExternalLibraryImport: contains(parts, "node_modules") });
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
}
|
2016-10-13 22:02:22 +02:00
|
|
|
}
|
|
|
|
|
2017-08-15 21:26:00 +02:00
|
|
|
function realPath(path: string, host: ModuleResolutionHost, traceEnabled: boolean): string {
|
2016-10-25 21:38:59 +02:00
|
|
|
if (!host.realpath) {
|
2016-11-09 16:41:25 +01:00
|
|
|
return path;
|
2016-10-25 21:38:59 +02:00
|
|
|
}
|
2016-10-13 22:02:22 +02:00
|
|
|
|
2016-11-09 16:41:25 +01:00
|
|
|
const real = normalizePath(host.realpath(path));
|
2016-10-25 21:38:59 +02:00
|
|
|
if (traceEnabled) {
|
2016-11-09 16:41:25 +01:00
|
|
|
trace(host, Diagnostics.Resolving_real_path_for_0_result_1, path, real);
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2019-06-27 12:49:35 +02:00
|
|
|
Debug.assert(host.fileExists(real), `${path} linked to nonexistent file ${real}`);
|
2016-11-09 16:41:25 +01:00
|
|
|
return real;
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson: boolean): Resolved | undefined {
|
2016-09-27 19:22:41 +02:00
|
|
|
if (state.traceEnabled) {
|
2016-12-28 00:50:14 +01:00
|
|
|
trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2018-04-27 22:58:45 +02:00
|
|
|
if (!hasTrailingDirectorySeparator(candidate)) {
|
2016-12-28 00:50:14 +01:00
|
|
|
if (!onlyRecordFailures) {
|
|
|
|
const parentOfCandidate = getDirectoryPath(candidate);
|
|
|
|
if (!directoryProbablyExists(parentOfCandidate, state.host)) {
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
|
|
|
|
}
|
|
|
|
onlyRecordFailures = true;
|
|
|
|
}
|
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
const resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
|
2016-12-28 00:50:14 +01:00
|
|
|
if (resolvedFromFile) {
|
2019-05-22 23:22:46 +02:00
|
|
|
const packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
|
|
|
|
const packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
|
|
|
|
return withPackageId(packageInfo, resolvedFromFile);
|
2016-12-28 00:50:14 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!onlyRecordFailures) {
|
|
|
|
const candidateExists = directoryProbablyExists(candidate, state.host);
|
|
|
|
if (!candidateExists) {
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
|
|
|
|
}
|
|
|
|
onlyRecordFailures = true;
|
|
|
|
}
|
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
|
2018-08-15 20:47:16 +02:00
|
|
|
/*@internal*/
|
|
|
|
export const nodeModulesPathPart = "/node_modules/";
|
2018-10-20 03:00:45 +02:00
|
|
|
/*@internal*/
|
|
|
|
export function pathContainsNodeModules(path: string): boolean {
|
|
|
|
return stringContains(path, nodeModulesPathPart);
|
|
|
|
}
|
2018-01-17 20:14:03 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* This will be called on the successfully resolved path from `loadModuleFromFile`.
|
|
|
|
* (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
|
|
|
|
*
|
|
|
|
* packageDirectory is the directory of the package itself.
|
2019-05-22 23:22:46 +02:00
|
|
|
* For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
|
|
|
|
* For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
|
|
|
|
* For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
|
|
|
|
* For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
|
2018-01-17 20:14:03 +01:00
|
|
|
*/
|
2019-05-22 23:22:46 +02:00
|
|
|
function parseNodeModuleFromPath(resolved: PathAndExtension): string | undefined {
|
2018-01-30 20:09:48 +01:00
|
|
|
const path = normalizePath(resolved.path);
|
2018-01-17 20:14:03 +01:00
|
|
|
const idx = path.lastIndexOf(nodeModulesPathPart);
|
|
|
|
if (idx === -1) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
const indexAfterNodeModules = idx + nodeModulesPathPart.length;
|
|
|
|
let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
|
|
|
|
if (path.charCodeAt(indexAfterNodeModules) === CharacterCodes.at) {
|
|
|
|
indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
|
|
|
|
}
|
2019-05-22 23:22:46 +02:00
|
|
|
return path.slice(0, indexAfterPackageName);
|
2018-01-17 20:14:03 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
function moveToNextDirectorySeparatorIfAvailable(path: string, prevSeparatorIndex: number): number {
|
|
|
|
const nextSeparatorIndex = path.indexOf(directorySeparator, prevSeparatorIndex + 1);
|
|
|
|
return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
|
|
|
|
}
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
function loadModuleFromFileNoPackageId(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined {
|
|
|
|
return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
|
2017-08-09 23:39:06 +02:00
|
|
|
}
|
2017-08-05 14:01:33 +02:00
|
|
|
|
2016-09-27 19:22:41 +02:00
|
|
|
/**
|
|
|
|
* @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
|
|
|
|
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
|
|
|
|
*/
|
2018-08-27 21:06:45 +02:00
|
|
|
function loadModuleFromFile(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined {
|
2018-10-25 19:19:57 +02:00
|
|
|
if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
|
2018-02-24 00:08:18 +01:00
|
|
|
const extensionLess = tryRemoveExtension(candidate, Extension.Json);
|
2018-10-25 19:19:57 +02:00
|
|
|
return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
|
2018-02-24 00:08:18 +01:00
|
|
|
}
|
|
|
|
|
2016-09-27 19:22:41 +02:00
|
|
|
// First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
|
2018-08-27 21:06:45 +02:00
|
|
|
const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
|
2016-09-27 19:22:41 +02:00
|
|
|
if (resolvedByAddingExtension) {
|
|
|
|
return resolvedByAddingExtension;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
|
|
|
|
// e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
|
2018-09-14 00:05:57 +02:00
|
|
|
if (hasJSFileExtension(candidate)) {
|
2016-09-27 19:22:41 +02:00
|
|
|
const extensionless = removeFileExtension(candidate);
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
const extension = candidate.substring(extensionless.length);
|
|
|
|
trace(state.host, Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
|
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/** Try to return an existing file that adds one of the `extensions` to `candidate`. */
|
2018-08-27 21:06:45 +02:00
|
|
|
function tryAddingExtensions(candidate: string, extensions: Extensions, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined {
|
2016-09-27 19:22:41 +02:00
|
|
|
if (!onlyRecordFailures) {
|
|
|
|
// check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
|
|
|
|
const directory = getDirectoryPath(candidate);
|
|
|
|
if (directory) {
|
|
|
|
onlyRecordFailures = !directoryProbablyExists(directory, state.host);
|
|
|
|
}
|
|
|
|
}
|
2016-10-13 22:02:22 +02:00
|
|
|
|
|
|
|
switch (extensions) {
|
2016-10-25 21:38:59 +02:00
|
|
|
case Extensions.DtsOnly:
|
2017-06-10 04:32:44 +02:00
|
|
|
return tryExtension(Extension.Dts);
|
2016-10-25 21:38:59 +02:00
|
|
|
case Extensions.TypeScript:
|
2017-06-10 04:32:44 +02:00
|
|
|
return tryExtension(Extension.Ts) || tryExtension(Extension.Tsx) || tryExtension(Extension.Dts);
|
2016-10-25 21:38:59 +02:00
|
|
|
case Extensions.JavaScript:
|
2017-06-10 04:32:44 +02:00
|
|
|
return tryExtension(Extension.Js) || tryExtension(Extension.Jsx);
|
2018-10-25 19:19:57 +02:00
|
|
|
case Extensions.TSConfig:
|
2017-01-17 22:51:00 +01:00
|
|
|
case Extensions.Json:
|
|
|
|
return tryExtension(Extension.Json);
|
2016-10-13 22:02:22 +02:00
|
|
|
}
|
|
|
|
|
2017-08-09 23:39:06 +02:00
|
|
|
function tryExtension(ext: Extension): PathAndExtension | undefined {
|
2018-08-27 21:06:45 +02:00
|
|
|
const path = tryFile(candidate + ext, onlyRecordFailures, state);
|
2018-05-22 23:46:57 +02:00
|
|
|
return path === undefined ? undefined : { path, ext };
|
2016-10-13 22:02:22 +02:00
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/** Return the file if it exists. */
|
2018-08-27 21:06:45 +02:00
|
|
|
function tryFile(fileName: string, onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined {
|
2016-12-28 00:50:14 +01:00
|
|
|
if (!onlyRecordFailures) {
|
|
|
|
if (state.host.fileExists(fileName)) {
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
|
|
|
|
}
|
|
|
|
return fileName;
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2016-12-28 00:50:14 +01:00
|
|
|
else {
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.File_0_does_not_exist, fileName);
|
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
state.failedLookupLocations.push(fileName);
|
2016-12-28 00:50:14 +01:00
|
|
|
return undefined;
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson = true) {
|
2019-05-22 23:22:46 +02:00
|
|
|
const packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
|
2018-08-27 21:06:45 +02:00
|
|
|
const packageJsonContent = packageInfo && packageInfo.packageJsonContent;
|
2019-04-25 20:06:31 +02:00
|
|
|
const versionPaths = packageInfo && packageInfo.versionPaths;
|
2019-05-22 23:22:46 +02:00
|
|
|
return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
|
2017-09-07 23:31:20 +02:00
|
|
|
}
|
2017-08-09 23:39:06 +02:00
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
interface PackageJsonInfo {
|
2019-05-22 23:22:46 +02:00
|
|
|
packageDirectory: string;
|
|
|
|
packageJsonContent: PackageJsonPathFields;
|
2018-08-27 21:06:45 +02:00
|
|
|
versionPaths: VersionPaths | undefined;
|
2017-09-07 23:31:20 +02:00
|
|
|
}
|
|
|
|
|
2019-05-22 23:22:46 +02:00
|
|
|
function getPackageJsonInfo(packageDirectory: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PackageJsonInfo | undefined {
|
2018-01-30 20:09:48 +01:00
|
|
|
const { host, traceEnabled } = state;
|
2018-08-27 21:06:45 +02:00
|
|
|
const directoryExists = !onlyRecordFailures && directoryProbablyExists(packageDirectory, host);
|
|
|
|
const packageJsonPath = combinePaths(packageDirectory, "package.json");
|
2017-09-07 23:31:20 +02:00
|
|
|
if (directoryExists && host.fileExists(packageJsonPath)) {
|
2018-04-06 21:19:08 +02:00
|
|
|
const packageJsonContent = readJson(packageJsonPath, host) as PackageJson;
|
2018-01-17 20:41:23 +01:00
|
|
|
if (traceEnabled) {
|
2019-05-22 20:06:49 +02:00
|
|
|
trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath);
|
2018-01-17 20:41:23 +01:00
|
|
|
}
|
2019-05-22 23:22:46 +02:00
|
|
|
const versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
|
|
|
|
return { packageDirectory, packageJsonContent, versionPaths };
|
2017-09-07 23:31:20 +02:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
if (directoryExists && traceEnabled) {
|
|
|
|
trace(host, Diagnostics.File_0_does_not_exist, packageJsonPath);
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2018-08-18 03:27:45 +02:00
|
|
|
|
2017-09-07 23:31:20 +02:00
|
|
|
// record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
|
2018-08-27 21:06:45 +02:00
|
|
|
state.failedLookupLocations.push(packageJsonPath);
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2017-01-25 16:31:24 +01:00
|
|
|
}
|
|
|
|
|
2018-10-03 20:44:16 +02:00
|
|
|
function loadNodeModuleFromDirectoryWorker(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, jsonContent: PackageJsonPathFields | undefined, versionPaths: VersionPaths | undefined): PathAndExtension | undefined {
|
2018-10-25 19:19:57 +02:00
|
|
|
let packageFile: string | undefined;
|
|
|
|
if (jsonContent) {
|
|
|
|
switch (extensions) {
|
|
|
|
case Extensions.JavaScript:
|
|
|
|
case Extensions.Json:
|
|
|
|
packageFile = readPackageJsonMainField(jsonContent, candidate, state);
|
|
|
|
break;
|
|
|
|
case Extensions.TypeScript:
|
|
|
|
// When resolving typescript modules, try resolving using main field as well
|
|
|
|
packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
|
|
|
|
break;
|
|
|
|
case Extensions.DtsOnly:
|
|
|
|
packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
|
|
|
|
break;
|
|
|
|
case Extensions.TSConfig:
|
|
|
|
packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
return Debug.assertNever(extensions);
|
|
|
|
}
|
|
|
|
}
|
2017-01-25 16:31:24 +01:00
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => {
|
|
|
|
const fromFile = tryFile(candidate, onlyRecordFailures, state);
|
|
|
|
if (fromFile) {
|
|
|
|
const resolved = resolvedIfExtensionMatches(extensions, fromFile);
|
|
|
|
if (resolved) {
|
|
|
|
return noPackageId(resolved);
|
|
|
|
}
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
|
|
|
|
}
|
2017-01-25 16:31:24 +01:00
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
|
|
|
|
// Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
|
|
|
|
const nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
|
|
|
|
// Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
|
|
|
|
return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
|
|
|
|
};
|
|
|
|
|
2018-10-03 20:44:16 +02:00
|
|
|
const onlyRecordFailuresForPackageFile = packageFile ? !directoryProbablyExists(getDirectoryPath(packageFile), state.host) : undefined;
|
|
|
|
const onlyRecordFailuresForIndex = onlyRecordFailures || !directoryProbablyExists(candidate, state.host);
|
2018-10-25 19:19:57 +02:00
|
|
|
const indexPath = combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
|
2018-08-27 21:06:45 +02:00
|
|
|
|
2018-10-03 20:44:16 +02:00
|
|
|
if (versionPaths && (!packageFile || containsPath(candidate, packageFile))) {
|
|
|
|
const moduleName = getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
|
2017-01-25 16:31:24 +01:00
|
|
|
if (state.traceEnabled) {
|
2018-08-29 02:24:02 +02:00
|
|
|
trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, moduleName);
|
2018-08-27 21:06:45 +02:00
|
|
|
}
|
2018-10-03 20:44:16 +02:00
|
|
|
const result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
|
2018-08-27 21:06:45 +02:00
|
|
|
if (result) {
|
|
|
|
return removeIgnoredPackageId(result.value);
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
// It won't have a `packageId` set, because we disabled `considerPackageJson`.
|
2018-10-03 20:44:16 +02:00
|
|
|
const packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile!, state));
|
|
|
|
if (packageFileResult) return packageFileResult;
|
|
|
|
|
|
|
|
return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
|
2016-12-19 17:10:05 +01:00
|
|
|
/** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
|
2017-08-09 23:39:06 +02:00
|
|
|
function resolvedIfExtensionMatches(extensions: Extensions, path: string): PathAndExtension | undefined {
|
|
|
|
const ext = tryGetExtensionFromPath(path);
|
|
|
|
return ext !== undefined && extensionIsOk(extensions, ext) ? { path, ext } : undefined;
|
2016-12-19 17:10:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/** True if `extension` is one of the supported `extensions`. */
|
|
|
|
function extensionIsOk(extensions: Extensions, extension: Extension): boolean {
|
|
|
|
switch (extensions) {
|
|
|
|
case Extensions.JavaScript:
|
|
|
|
return extension === Extension.Js || extension === Extension.Jsx;
|
2018-10-25 19:19:57 +02:00
|
|
|
case Extensions.TSConfig:
|
2017-01-17 22:51:00 +01:00
|
|
|
case Extensions.Json:
|
|
|
|
return extension === Extension.Json;
|
2016-12-19 17:10:05 +01:00
|
|
|
case Extensions.TypeScript:
|
|
|
|
return extension === Extension.Ts || extension === Extension.Tsx || extension === Extension.Dts;
|
|
|
|
case Extensions.DtsOnly:
|
|
|
|
return extension === Extension.Dts;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-18 00:04:09 +02:00
|
|
|
/* @internal */
|
2018-08-18 03:27:45 +02:00
|
|
|
export function parsePackageName(moduleName: string): { packageName: string, rest: string } {
|
2017-09-20 17:15:24 +02:00
|
|
|
let idx = moduleName.indexOf(directorySeparator);
|
|
|
|
if (moduleName[0] === "@") {
|
|
|
|
idx = moduleName.indexOf(directorySeparator, idx + 1);
|
|
|
|
}
|
|
|
|
return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
|
2018-10-02 01:07:52 +02:00
|
|
|
function loadModuleFromNearestNodeModulesDirectory(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined): SearchResult<Resolved> {
|
|
|
|
return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
|
2016-09-26 15:53:36 +02:00
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
|
|
|
|
function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName: string, directory: string, state: ModuleResolutionState): SearchResult<Resolved> {
|
2016-10-28 23:15:15 +02:00
|
|
|
// Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
|
2018-10-02 01:07:52 +02:00
|
|
|
return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
|
2016-09-26 15:53:36 +02:00
|
|
|
}
|
|
|
|
|
2018-10-02 01:07:52 +02:00
|
|
|
function loadModuleFromNearestNodeModulesDirectoryWorker(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, typesScopeOnly: boolean, cache: NonRelativeModuleNameResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined): SearchResult<Resolved> {
|
|
|
|
const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
|
2016-10-28 23:15:15 +02:00
|
|
|
return forEachAncestorDirectory(normalizeSlashes(directory), ancestorDirectory => {
|
|
|
|
if (getBaseFileName(ancestorDirectory) !== "node_modules") {
|
2018-08-27 21:06:45 +02:00
|
|
|
const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
|
2016-12-21 19:02:28 +01:00
|
|
|
if (resolutionFromCache) {
|
|
|
|
return resolutionFromCache;
|
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2016-10-28 23:15:15 +02:00
|
|
|
});
|
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
function loadModuleFromImmediateNodeModulesDirectory(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, typesScopeOnly: boolean): Resolved | undefined {
|
2016-12-28 00:50:14 +01:00
|
|
|
const nodeModulesFolder = combinePaths(directory, "node_modules");
|
|
|
|
const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
|
|
|
|
if (!nodeModulesFolderExists && state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
|
|
|
|
}
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
const packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
|
2016-10-28 23:15:15 +02:00
|
|
|
if (packageResult) {
|
|
|
|
return packageResult;
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2018-10-25 19:19:57 +02:00
|
|
|
if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
|
2016-12-28 00:50:14 +01:00
|
|
|
const nodeModulesAtTypes = combinePaths(nodeModulesFolder, "@types");
|
|
|
|
let nodeModulesAtTypesExists = nodeModulesFolderExists;
|
|
|
|
if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes, state.host)) {
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes);
|
|
|
|
}
|
|
|
|
nodeModulesAtTypesExists = false;
|
|
|
|
}
|
2018-08-27 21:06:45 +02:00
|
|
|
return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes, nodeModulesAtTypesExists, state);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function loadModuleFromSpecificNodeModulesDirectory(extensions: Extensions, moduleName: string, nodeModulesDirectory: string, nodeModulesDirectoryExists: boolean, state: ModuleResolutionState): Resolved | undefined {
|
|
|
|
const candidate = normalizePath(combinePaths(nodeModulesDirectory, moduleName));
|
|
|
|
|
|
|
|
// First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
|
2019-05-22 23:22:46 +02:00
|
|
|
let packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
|
2018-08-27 21:06:45 +02:00
|
|
|
if (packageInfo) {
|
|
|
|
const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
|
|
|
|
if (fromFile) {
|
|
|
|
return noPackageId(fromFile);
|
|
|
|
}
|
|
|
|
|
2019-05-22 23:22:46 +02:00
|
|
|
const fromDirectory = loadNodeModuleFromDirectoryWorker(
|
|
|
|
extensions,
|
|
|
|
candidate,
|
|
|
|
!nodeModulesDirectoryExists,
|
|
|
|
state,
|
|
|
|
packageInfo.packageJsonContent,
|
|
|
|
packageInfo.versionPaths
|
|
|
|
);
|
|
|
|
return withPackageId(packageInfo, fromDirectory);
|
2018-08-27 21:06:45 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => {
|
|
|
|
const pathAndExtension =
|
|
|
|
loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
|
2019-05-22 23:22:46 +02:00
|
|
|
loadNodeModuleFromDirectoryWorker(
|
|
|
|
extensions,
|
|
|
|
candidate,
|
|
|
|
onlyRecordFailures,
|
|
|
|
state,
|
|
|
|
packageInfo && packageInfo.packageJsonContent,
|
|
|
|
packageInfo && packageInfo.versionPaths
|
|
|
|
);
|
|
|
|
return withPackageId(packageInfo, pathAndExtension);
|
2018-08-27 21:06:45 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
const { packageName, rest } = parsePackageName(moduleName);
|
|
|
|
if (rest !== "") { // If "rest" is empty, we just did this search above.
|
|
|
|
const packageDirectory = combinePaths(nodeModulesDirectory, packageName);
|
|
|
|
|
|
|
|
// Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
|
2019-05-22 23:22:46 +02:00
|
|
|
packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
|
|
|
|
if (packageInfo && packageInfo.versionPaths) {
|
2018-08-27 21:06:45 +02:00
|
|
|
if (state.traceEnabled) {
|
2019-05-22 23:22:46 +02:00
|
|
|
trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, version, rest);
|
2018-08-27 21:06:45 +02:00
|
|
|
}
|
|
|
|
const packageDirectoryExists = nodeModulesDirectoryExists && directoryProbablyExists(packageDirectory, state.host);
|
2019-05-22 23:22:46 +02:00
|
|
|
const fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
|
2018-08-27 21:06:45 +02:00
|
|
|
if (fromPaths) {
|
|
|
|
return fromPaths.value;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
|
|
|
|
}
|
|
|
|
|
|
|
|
function tryLoadModuleUsingPaths(extensions: Extensions, moduleName: string, baseDirectory: string, paths: MapLike<string[]>, loader: ResolutionKindSpecificLoader, onlyRecordFailures: boolean, state: ModuleResolutionState): SearchResult<Resolved> {
|
|
|
|
const matchedPattern = matchPatternOrExact(getOwnKeys(paths), moduleName);
|
|
|
|
if (matchedPattern) {
|
|
|
|
const matchedStar = isString(matchedPattern) ? undefined : matchedText(matchedPattern, moduleName);
|
|
|
|
const matchedPatternText = isString(matchedPattern) ? matchedPattern : patternText(matchedPattern);
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
|
|
|
|
}
|
|
|
|
const resolved = forEach(paths[matchedPatternText], subst => {
|
|
|
|
const path = matchedStar ? subst.replace("*", matchedStar) : subst;
|
|
|
|
const candidate = normalizePath(combinePaths(baseDirectory, path));
|
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
|
|
|
|
}
|
|
|
|
// A path mapping may have an extension, in contrast to an import, which should omit it.
|
|
|
|
const extension = tryGetExtensionFromPath(candidate);
|
|
|
|
if (extension !== undefined) {
|
|
|
|
const path = tryFile(candidate, onlyRecordFailures, state);
|
|
|
|
if (path !== undefined) {
|
|
|
|
return noPackageId({ path, ext: extension });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return loader(extensions, candidate, onlyRecordFailures || !directoryProbablyExists(getDirectoryPath(candidate), state.host), state);
|
|
|
|
});
|
|
|
|
return { value: resolved };
|
2016-10-25 21:38:59 +02:00
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
|
|
|
|
2017-05-03 22:13:28 +02:00
|
|
|
/** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
|
|
|
|
const mangledScopedPackageSeparator = "__";
|
|
|
|
|
2017-04-06 17:01:15 +02:00
|
|
|
/** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
|
2018-08-18 03:27:45 +02:00
|
|
|
function mangleScopedPackageNameWithTrace(packageName: string, state: ModuleResolutionState): string {
|
|
|
|
const mangled = mangleScopedPackageName(packageName);
|
2017-10-18 00:04:09 +02:00
|
|
|
if (state.traceEnabled && mangled !== packageName) {
|
|
|
|
trace(state.host, Diagnostics.Scoped_package_detected_looking_in_0, mangled);
|
|
|
|
}
|
|
|
|
return mangled;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* @internal */
|
|
|
|
export function getTypesPackageName(packageName: string): string {
|
2018-08-18 03:27:45 +02:00
|
|
|
return `@types/${mangleScopedPackageName(packageName)}`;
|
2017-10-18 00:04:09 +02:00
|
|
|
}
|
|
|
|
|
2018-02-26 19:38:54 +01:00
|
|
|
/* @internal */
|
2018-08-18 03:27:45 +02:00
|
|
|
export function mangleScopedPackageName(packageName: string): string {
|
2017-10-18 00:04:09 +02:00
|
|
|
if (startsWith(packageName, "@")) {
|
2018-03-01 23:20:18 +01:00
|
|
|
const replaceSlash = packageName.replace(directorySeparator, mangledScopedPackageSeparator);
|
2017-10-18 00:04:09 +02:00
|
|
|
if (replaceSlash !== packageName) {
|
|
|
|
return replaceSlash.slice(1); // Take off the "@"
|
2017-04-06 17:01:15 +02:00
|
|
|
}
|
|
|
|
}
|
2017-10-18 00:04:09 +02:00
|
|
|
return packageName;
|
2017-04-06 17:01:15 +02:00
|
|
|
}
|
|
|
|
|
2017-05-03 23:12:24 +02:00
|
|
|
/* @internal */
|
2018-08-18 03:27:45 +02:00
|
|
|
export function getPackageNameFromTypesPackageName(mangledName: string): string {
|
2017-05-03 22:13:28 +02:00
|
|
|
const withoutAtTypePrefix = removePrefix(mangledName, "@types/");
|
|
|
|
if (withoutAtTypePrefix !== mangledName) {
|
2018-08-18 03:27:45 +02:00
|
|
|
return unmangleScopedPackageName(withoutAtTypePrefix);
|
2017-05-03 22:13:28 +02:00
|
|
|
}
|
|
|
|
return mangledName;
|
|
|
|
}
|
|
|
|
|
2018-01-10 00:40:32 +01:00
|
|
|
/* @internal */
|
2018-08-18 03:27:45 +02:00
|
|
|
export function unmangleScopedPackageName(typesPackageName: string): string {
|
2018-01-11 00:17:27 +01:00
|
|
|
return stringContains(typesPackageName, mangledScopedPackageSeparator) ?
|
2018-03-01 23:20:18 +01:00
|
|
|
"@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) :
|
2018-01-11 00:17:27 +01:00
|
|
|
typesPackageName;
|
2018-01-10 00:40:32 +01:00
|
|
|
}
|
|
|
|
|
2018-08-27 21:06:45 +02:00
|
|
|
function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, state: ModuleResolutionState): SearchResult<Resolved> {
|
2016-12-21 19:02:28 +01:00
|
|
|
const result = cache && cache.get(containingDirectory);
|
|
|
|
if (result) {
|
2018-08-27 21:06:45 +02:00
|
|
|
if (state.traceEnabled) {
|
|
|
|
trace(state.host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
|
2016-12-21 19:02:28 +01:00
|
|
|
}
|
2020-03-11 22:35:26 +01:00
|
|
|
state.resultFromCache = result;
|
2018-08-11 00:23:35 +02:00
|
|
|
return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
|
2016-12-21 19:02:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-02 01:07:52 +02:00
|
|
|
export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache, redirectedReference?: ResolvedProjectReference): ResolvedModuleWithFailedLookupLocations {
|
2016-09-27 19:22:41 +02:00
|
|
|
const traceEnabled = isTraceEnabled(compilerOptions, host);
|
|
|
|
const failedLookupLocations: string[] = [];
|
2018-08-27 21:06:45 +02:00
|
|
|
const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations };
|
2016-09-26 15:53:36 +02:00
|
|
|
const containingDirectory = getDirectoryPath(containingFile);
|
2016-09-27 19:22:41 +02:00
|
|
|
|
2016-10-25 21:38:59 +02:00
|
|
|
const resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
|
2017-12-06 20:27:38 +01:00
|
|
|
// No originalPath because classic resolution doesn't resolve realPath
|
2020-03-11 22:35:26 +01:00
|
|
|
return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
|
2016-09-27 19:22:41 +02:00
|
|
|
|
2016-12-21 19:02:28 +01:00
|
|
|
function tryResolve(extensions: Extensions): SearchResult<Resolved> {
|
2018-08-27 21:06:45 +02:00
|
|
|
const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
|
2016-10-25 21:38:59 +02:00
|
|
|
if (resolvedUsingSettings) {
|
2016-12-21 19:02:28 +01:00
|
|
|
return { value: resolvedUsingSettings };
|
2016-10-25 21:38:59 +02:00
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
|
2017-07-13 22:46:04 +02:00
|
|
|
if (!isExternalModuleNameRelative(moduleName)) {
|
2018-10-02 01:07:52 +02:00
|
|
|
const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
|
2016-10-28 23:15:15 +02:00
|
|
|
// Climb up parent directories looking for a module.
|
|
|
|
const resolved = forEachAncestorDirectory(containingDirectory, directory => {
|
2018-08-27 21:06:45 +02:00
|
|
|
const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, state);
|
2016-12-21 19:02:28 +01:00
|
|
|
if (resolutionFromCache) {
|
|
|
|
return resolutionFromCache;
|
|
|
|
}
|
2016-10-28 23:15:15 +02:00
|
|
|
const searchName = normalizePath(combinePaths(directory, moduleName));
|
2018-08-27 21:06:45 +02:00
|
|
|
return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
|
2016-10-28 23:15:15 +02:00
|
|
|
});
|
2016-10-25 21:38:59 +02:00
|
|
|
if (resolved) {
|
|
|
|
return resolved;
|
|
|
|
}
|
|
|
|
if (extensions === Extensions.TypeScript) {
|
|
|
|
// If we didn't find the file normally, look it up in @types.
|
2018-08-27 21:06:45 +02:00
|
|
|
return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
|
2016-10-25 21:38:59 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
const candidate = normalizePath(combinePaths(containingDirectory, moduleName));
|
2018-08-27 21:06:45 +02:00
|
|
|
return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
|
2016-10-25 21:38:59 +02:00
|
|
|
}
|
|
|
|
}
|
2016-09-27 19:22:41 +02:00
|
|
|
}
|
2016-09-26 15:53:36 +02:00
|
|
|
|
2016-10-25 17:02:16 +02:00
|
|
|
/**
|
2019-06-21 04:11:46 +02:00
|
|
|
* A host may load a module from a global cache of typings.
|
|
|
|
* This is the minumum code needed to expose that functionality; the rest is in the host.
|
2016-10-25 17:02:16 +02:00
|
|
|
*/
|
|
|
|
/* @internal */
|
2018-05-22 23:46:57 +02:00
|
|
|
export function loadModuleFromGlobalCache(moduleName: string, projectName: string | undefined, compilerOptions: CompilerOptions, host: ModuleResolutionHost, globalCache: string): ResolvedModuleWithFailedLookupLocations {
|
2016-10-25 17:02:16 +02:00
|
|
|
const traceEnabled = isTraceEnabled(compilerOptions, host);
|
|
|
|
if (traceEnabled) {
|
|
|
|
trace(host, Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache);
|
|
|
|
}
|
|
|
|
const failedLookupLocations: string[] = [];
|
2018-08-27 21:06:45 +02:00
|
|
|
const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations };
|
|
|
|
const resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
|
2020-03-11 22:35:26 +01:00
|
|
|
return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
|
2016-10-25 17:02:16 +02:00
|
|
|
}
|
2016-10-28 23:15:15 +02:00
|
|
|
|
2016-12-21 19:02:28 +01:00
|
|
|
/**
|
|
|
|
* Represents result of search. Normally when searching among several alternatives we treat value `undefined` as indicator
|
2017-01-09 16:47:52 +01:00
|
|
|
* that search fails and we should try another option.
|
2016-12-21 19:02:28 +01:00
|
|
|
* However this does not allow us to represent final result that should be used instead of further searching (i.e. a final result that was found in cache).
|
|
|
|
* SearchResult is used to deal with this issue, its values represents following outcomes:
|
|
|
|
* - undefined - not found, continue searching
|
|
|
|
* - { value: undefined } - not found - stop searching
|
|
|
|
* - { value: <some-value> } - found - stop searching
|
|
|
|
*/
|
|
|
|
type SearchResult<T> = { value: T | undefined } | undefined;
|
2016-12-28 17:58:31 +01:00
|
|
|
|
2016-12-21 19:02:28 +01:00
|
|
|
/**
|
|
|
|
* Wraps value to SearchResult.
|
|
|
|
* @returns undefined if value is undefined or { value } otherwise
|
|
|
|
*/
|
|
|
|
function toSearchResult<T>(value: T | undefined): SearchResult<T> {
|
|
|
|
return value !== undefined ? { value } : undefined;
|
|
|
|
}
|
2017-01-13 12:55:59 +01:00
|
|
|
}
|