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

Fix module resolution across multiple dependent workspaces with incompatible tsconfigs #611

Merged
merged 4 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "@fixtures/module-resolution-workspaces",
"version": "1.0.0",
"private": true,
"workspaces": ["packages/*"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "@monorepo/workspaceA",
"version": "0.0.0",
"private": true,
"type": "module",
"main": "src/index.ts",
"dependencies": {
"@monorepo/workspaceB": "*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { usedFunction } from '@monorepo/workspaceB';

usedFunction;
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"outDir": "dist",
"rootDir": "src",
"baseUrl": "src",
"declaration": true,
"paths": {
"#dummy": ["src"]
}
},
"include": ["src/**/*"],
"exclude": ["dist/**/*"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "@monorepo/workspaceB",
"version": "0.0.0",
"private": true,
"type": "module",
"main": "src/index.ts"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const someFunction = () => 'bar';
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from 'exports';
export { usedFunction } from 'used-fn';
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { someFunction } from 'exports';

export const usedFunction = () => {
someFunction();
return 'bar';
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"outDir": "dist",
"rootDir": "src",
"baseUrl": "src",
"declaration": true,
"paths": {
"#dummy-shared": ["src"]
}
},
"include": ["src/**/*"],
"exclude": ["dist/**/*"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"files": [],
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"declaration": true,
"forceConsistentCasingInFileNames": true,
"module": "nodenext",
"moduleResolution": "nodenext",
"outDir": "dist",
"rootDir": "src",
"skipLibCheck": true,
"strict": true,
"target": "ES2022"
},
"references": [
{ "path": "packages/workspaceA" },
{ "path": "packages/workspaceB" },
]
}
36 changes: 23 additions & 13 deletions packages/knip/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,9 +291,18 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => {
}
};

const analyzeSourceFile = (filePath: string, principal: ProjectPrincipal) => {
const analyzeSourceFile = (filePath: string | undefined, principal?: ProjectPrincipal | undefined) => {
if (!filePath || analyzedFiles.has(filePath)) {
return;
}

const workspace = chief.findWorkspaceByFilePath(filePath);
if (workspace) {
principal = principal || !workspace ? principal : factory.getPrincipalByPackageName(workspace.pkgName);

if (workspace && principal) {
// Add to analyzed files early to prevent risk of infinite recursion
analyzedFiles.add(filePath);

const { imports, exports, scripts } = principal.analyzeSourceFile(filePath, {
skipTypeOnly: isStrict,
isFixExports: fixer.isEnabled && fixer.isFixUnusedExports,
Expand All @@ -319,11 +328,9 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => {
const specifiers = _getDependenciesFromScripts(scripts, { cwd, manifestScriptNames, dependencies });
for (const specifier of specifiers) {
const specifierFilePath = handleReferencedDependency(specifier, filePath, workspace);
if (specifierFilePath) internalWorkspaceFilePaths.add(specifierFilePath);
analyzeSourceFile(specifierFilePath, principal);
}
}

analyzedFiles.add(filePath);
}
};

Expand Down Expand Up @@ -358,19 +365,22 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => {
}
} while (size !== principal.entryPaths.size);

for (const specifierFilePath of internalWorkspaceFilePaths) {
if (!analyzedFiles.has(specifierFilePath)) {
analyzeSourceFile(specifierFilePath, principal);
}
}

for (const filePath of principal.getUnreferencedFiles()) unreferencedFiles.add(filePath);
for (const filePath of principal.entryPaths) entryPaths.add(filePath);

principal.reconcileCache(serializableMap);
}

// Delete principals including TS programs for GC, except when we still need its `LS.findReferences`
if (isSkipLibs && !isWatch) factory.deletePrincipal(principal);
// Re-analyze files from local workspaces that were referenced, but have not yet been successfully resolved
for (const specifierFilePath of internalWorkspaceFilePaths) {
analyzeSourceFile(specifierFilePath);
}

// Delete principals including TS programs for GC, except when we still need its `LS.findReferences`
if (isSkipLibs && !isWatch) {
for (const principal of principals) {
factory.deletePrincipal(principal);
}
}

const isIdentifierReferenced = getIsIdentifierReferencedHandler(serializableMap);
Expand Down
5 changes: 4 additions & 1 deletion packages/knip/src/typescript/resolveModuleNames.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ export function createCustomModuleResolver(
: `${containingFile}:${moduleName}`;
if (resolutionCache.has(key)) return resolutionCache.get(key);
const resolvedModule = resolveModuleName(moduleName, containingFile);
resolutionCache.set(key, resolvedModule);
// Don't save resolution misses, because it might be resolved later under a different principal
if (resolvedModule) {
resolutionCache.set(key, resolvedModule);
}
return resolvedModule;
});
}
Expand Down
22 changes: 22 additions & 0 deletions packages/knip/test/workspaces-complex-module-resolution.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { test } from 'bun:test';
import assert from 'node:assert/strict';
import { main } from '../src/index.js';
import { resolve } from '../src/util/path.js';
import baseArguments from './helpers/baseArguments.js';
import baseCounters from './helpers/baseCounters.js';

const cwd = resolve('fixtures/workspaces-complex-module-resolution');

test('Resolve modules properly across multiple workspaces', async () => {
const { counters } = await main({
...baseArguments,
cwd,
isDebug: true,
});

assert.deepEqual(counters, {
...baseCounters,
processed: 4,
total: 4,
});
});