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

Function resolveRelativeImport

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

* Resolve a relative import

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

Source from the content-addressed store, hash-verified

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