MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / resolveRelativeImport

Function resolveRelativeImport

src/resolution/import-resolver.ts:1387–1423  ·  view source on GitHub ↗

* Resolve a relative import

(
  importPath: string,
  fromDir: string,
  language: Language,
  context: ResolutionContext
)

Source from the content-addressed store, hash-verified

1385 * Resolve a relative import
1386 */
1387function resolveRelativeImport(
1388 importPath: string,
1389 fromDir: string,
1390 language: Language,
1391 context: ResolutionContext
1392): string | null {
1393 const projectRoot = context.getProjectRoot();
1394 const extensions = EXTENSION_RESOLUTION[language] || [];
1395
1396 // Try the path as-is first
1397 const basePath = path.resolve(fromDir, importPath);
1398 const relativePath = path.relative(projectRoot, basePath).replace(/\\/g, '/');
1399
1400 // Try each extension. `require('..')` up to the project root is its `index.js`.
1401 let mainTried = false;
1402 for (const ext of extensions) {
1403 if (relativePath === '' && !ext.startsWith('/')) continue;
1404 // A directory's `package.json` `main` comes before its index files, as
1405 // Node loads a directory (#2964).
1406 if (ext.startsWith('/') && !mainTried && FOLDER_MAIN_LANGUAGES.has(language)) {
1407 mainTried = true;
1408 const main = relativeDirectoryMain(relativePath, language, context);
1409 if (main) return main;
1410 }
1411 const candidatePath = relativePath === '' ? ext.slice(1) : relativePath + ext;
1412 if (context.fileExists(candidatePath)) {
1413 return candidatePath;
1414 }
1415 }
1416
1417 // Try without extension (might already have one)
1418 if (context.fileExists(relativePath)) {
1419 return relativePath;
1420 }
1421
1422 return findSourceForEmittedSpecifier(relativePath, language, context);
1423}
1424
1425/**
1426 * The importers whose relative import of a folder reads the folder's

Callers 1

Calls 6

relativeDirectoryMainFunction · 0.85
hasMethod · 0.80
fileExistsMethod · 0.80
getProjectRootMethod · 0.65
resolveMethod · 0.65

Tested by

no test coverage detected