Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check nearest package.json dependencies for possible package names for specifier candidates #58176

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 51 additions & 2 deletions src/compiler/moduleSpecifiers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ import {
NodeFlags,
NodeModulePathParts,
normalizePath,
Path,
pathContainsNodeModules,
pathIsBareSpecifier,
pathIsRelative,
Expand All @@ -102,6 +103,7 @@ import {
removeTrailingDirectorySeparator,
replaceFirstStar,
ResolutionMode,
resolveModuleName,
resolvePath,
ScriptKind,
shouldAllowImportingTsExtension,
Expand Down Expand Up @@ -1026,6 +1028,46 @@ function tryGetModuleNameFromPackageJsonImports(moduleFileName: string, sourceDi
})?.moduleFileToTry;
}

function tryGetModuleNameFromPackageJsonDependencies(moduleFileName: Path, { sourceDirectory, getCanonicalFileName }: Info, options: CompilerOptions, host: ModuleSpecifierResolutionHost, importMode: ResolutionMode) {
if (!host.readFile) {
return undefined;
}
const cache = host.getModuleResolutionCache?.();
if (!cache) {
return undefined;
}

const ancestorDirectoryWithPackageJson = getNearestAncestorDirectoryWithPackageJson(host, sourceDirectory);
if (!ancestorDirectoryWithPackageJson) {
return undefined;
}
const packageJsonPath = combinePaths(ancestorDirectoryWithPackageJson, "package.json");
const cachedPackageJson = host.getPackageJsonInfoCache?.()?.getPackageJsonInfo(packageJsonPath);
if (isMissingPackageJsonInfo(cachedPackageJson) || !host.fileExists(packageJsonPath)) {
return undefined;
}
const packageJsonContent = cachedPackageJson?.contents.packageJsonContent || tryParseJson(host.readFile(packageJsonPath)!);
const dependencies = packageJsonContent?.dependencies;
if (!dependencies) {
return undefined;
}

const candidates = getOwnKeys(dependencies);
for (const name of candidates) {
const resolved = resolveModuleName(name, combinePaths(sourceDirectory, "dummy.ts"), options, host as (typeof host & { readFile: NonNullable<(typeof host)["readFile"]> }), cache, /*redirectedReference*/ undefined, importMode);
if (resolved && resolved.resolvedModule && resolved.resolvedModule) {
const resolvedPath = toPath(resolved.resolvedModule.resolvedFileName, sourceDirectory, getCanonicalFileName);
if (resolvedPath === moduleFileName) {
return name;
}
if (host.realpath && host.realpath(resolvedPath) === host.realpath(moduleFileName)) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't want to have to realpath here, but it seems to be the only way we can check if the two paths actually refer to the same thing through symlinks.

return name;
}
}
}
return undefined;
}

function tryGetModuleNameFromRootDirs(rootDirs: readonly string[], moduleFileName: string, sourceDirectory: string, getCanonicalFileName: (file: string) => string, allowedEndings: readonly ModuleSpecifierEnding[], compilerOptions: CompilerOptions): string | undefined {
const normalizedTargetPaths = getPathsRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
if (normalizedTargetPaths === undefined) {
Expand All @@ -1043,10 +1085,18 @@ function tryGetModuleNameFromRootDirs(rootDirs: readonly string[], moduleFileNam
return processEnding(shortest, allowedEndings, compilerOptions);
}

function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCanonicalFileName, canonicalSourceDirectory }: Info, importingSourceFile: SourceFile | FutureSourceFile, host: ModuleSpecifierResolutionHost, options: CompilerOptions, userPreferences: UserPreferences, packageNameOnly?: boolean, overrideMode?: ResolutionMode): string | undefined {
function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, info: Info, importingSourceFile: SourceFile | FutureSourceFile, host: ModuleSpecifierResolutionHost, options: CompilerOptions, userPreferences: UserPreferences, packageNameOnly?: boolean, overrideMode?: ResolutionMode): string | undefined {
if (!host.fileExists || !host.readFile) {
return undefined;
}
const { getCanonicalFileName, canonicalSourceDirectory } = info;

const importMode = overrideMode || getDefaultResolutionModeForFile(importingSourceFile, host, options);
const fromDeps = tryGetModuleNameFromPackageJsonDependencies(toPath(path, canonicalSourceDirectory, getCanonicalFileName), info, options, host, importMode);
if (fromDeps) {
return fromDeps;
}

const parts: NodeModulePathParts = getNodeModulePathParts(path)!;
if (!parts) {
return undefined;
Expand Down Expand Up @@ -1114,7 +1164,6 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCan
const cachedPackageJson = host.getPackageJsonInfoCache?.()?.getPackageJsonInfo(packageJsonPath);
if (isPackageJsonInfo(cachedPackageJson) || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) {
const packageJsonContent: Record<string, any> | undefined = cachedPackageJson?.contents.packageJsonContent || tryParseJson(host.readFile!(packageJsonPath)!);
const importMode = overrideMode || getDefaultResolutionModeForFile(importingSourceFile, host, options);
if (getResolvePackageJsonExports(options)) {
// The package name that we found in node_modules could be different from the package
// name in the package.json content via url/filepath dependency specifiers. We need to
Expand Down
2 changes: 2 additions & 0 deletions src/compiler/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2698,12 +2698,14 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg
// Before falling back to the host
return host.fileExists(f);
},
realpath: maybeBind(host, host.realpath),
useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(),
getBuildInfo: () => program.getBuildInfo?.(),
getSourceFileFromReference: (file, ref) => program.getSourceFileFromReference(file, ref),
redirectTargetsMap,
getFileIncludeReasons: program.getFileIncludeReasons,
createHash: maybeBind(host, host.createHash),
getModuleResolutionCache: () => program.getModuleResolutionCache(),
};
}

Expand Down
2 changes: 2 additions & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9702,6 +9702,8 @@ export interface ModuleSpecifierResolutionHost {
getCommonSourceDirectory(): string;
getDefaultResolutionModeForFile(sourceFile: SourceFile): ResolutionMode;
getModeForResolutionAtIndex(file: SourceFile, index: number): ResolutionMode;

getModuleResolutionCache?(): ModuleResolutionCache | undefined;
}

/** @internal */
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//// [tests/cases/compiler/symlinkedWorkspaceDependenciesNoDirectLinkGeneratesNonrelativeName.ts] ////

//// [index.d.ts]
export declare class Foo {
private f: any;
}
//// [package.json]
{
"private": true,
"dependencies": {
"package-a": "file:../packageA"
}
}
//// [index.d.ts]
import { Foo } from "package-a";
export declare function invoke(): Foo;
//// [package.json]
{
"private": true,
"dependencies": {
"package-b": "file:../packageB",
"package-a": "file:../packageA"
}
}
//// [index.ts]
import * as pkg from "package-b";

export const a = pkg.invoke();

//// [index.js]
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.a = void 0;
var pkg = require("package-b");
exports.a = pkg.invoke();


//// [index.d.ts]
export declare const a: import("package-a").Foo;
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//// [tests/cases/compiler/symlinkedWorkspaceDependenciesNoDirectLinkGeneratesNonrelativeName.ts] ////

=== workspace/packageA/index.d.ts ===
export declare class Foo {
>Foo : Symbol(Foo, Decl(index.d.ts, 0, 0))

private f: any;
>f : Symbol(Foo.f, Decl(index.d.ts, 0, 26))
}
=== workspace/packageB/index.d.ts ===
import { Foo } from "package-a";
>Foo : Symbol(Foo, Decl(index.d.ts, 0, 8))

export declare function invoke(): Foo;
>invoke : Symbol(invoke, Decl(index.d.ts, 0, 32))
>Foo : Symbol(Foo, Decl(index.d.ts, 0, 8))

=== workspace/packageC/index.ts ===
import * as pkg from "package-b";
>pkg : Symbol(pkg, Decl(index.ts, 0, 6))

export const a = pkg.invoke();
>a : Symbol(a, Decl(index.ts, 2, 12))
>pkg.invoke : Symbol(pkg.invoke, Decl(index.d.ts, 0, 32))
>pkg : Symbol(pkg, Decl(index.ts, 0, 6))
>invoke : Symbol(pkg.invoke, Decl(index.d.ts, 0, 32))

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//// [tests/cases/compiler/symlinkedWorkspaceDependenciesNoDirectLinkGeneratesNonrelativeName.ts] ////

=== workspace/packageA/index.d.ts ===
export declare class Foo {
>Foo : Foo
> : ^^^

private f: any;
>f : any
}
=== workspace/packageB/index.d.ts ===
import { Foo } from "package-a";
>Foo : typeof Foo
> : ^^^^^^^^^^

export declare function invoke(): Foo;
>invoke : () => Foo
> : ^^^^^^

=== workspace/packageC/index.ts ===
import * as pkg from "package-b";
>pkg : typeof pkg
> : ^^^^^^^^^^

export const a = pkg.invoke();
>a : import("workspace/packageA/index").Foo
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>pkg.invoke() : import("workspace/packageA/index").Foo
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>pkg.invoke : () => import("workspace/packageA/index").Foo
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>pkg : typeof pkg
> : ^^^^^^^^^^
>invoke : () => import("workspace/packageA/index").Foo
> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// @declaration: true
// @filename: workspace/packageA/index.d.ts
export declare class Foo {
private f: any;
}
// @filename: workspace/packageB/package.json
{
"private": true,
"dependencies": {
"package-a": "file:../packageA"
}
}
// @filename: workspace/packageB/index.d.ts
import { Foo } from "package-a";
export declare function invoke(): Foo;
// @filename: workspace/packageC/package.json
{
"private": true,
"dependencies": {
"package-b": "file:../packageB",
"package-a": "file:../packageA"
}
}
// @filename: workspace/packageC/index.ts
import * as pkg from "package-b";

export const a = pkg.invoke();
// @link: workspace/packageA -> workspace/packageC/node_modules/package-a
// @link: workspace/packageA -> workspace/packageB/node_modules/package-a
// @link: workspace/packageB -> workspace/packageC/node_modules/package-b
Loading