Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- In JavaScript and TypeScript, a call to a name that a function around the caller declares for itself, like a helper an inner arrow function calls, now links to that local declaration instead of the file's import of the same name. Thanks @inth3shadows for the report. (#2949)
- In JavaScript and TypeScript, a call to a helper declared inside a `describe(…)` block, or any other callback, now links to the helper that block declares instead of a same-named one from another block that happens to sit nearer. Thanks @inth3shadows for the report. (#2944)
- In JavaScript and TypeScript, a call inside a spread, like `<input {...register('email')} />` with `register` taken from `useForm()`, no longer links to an unrelated project function that shares the name. Thanks @inth3shadows for the report. (#2962)
- In JavaScript and TypeScript, a module namespace that another module hands on by name, like zod's `import { z } from 'zod'` of `import * as z from './external'; export { z }`, or `export * as ns from './schemas'`, now leads `z.string()` to what that module exports, as `import * as z` does, instead of a same-named method elsewhere. Thanks @inth3shadows for the report. (#2951)
- In JavaScript and TypeScript, an import through a barrel of several `export *` lines now links to the module that exports the name itself, whichever line comes first, instead of a same-named method of an object another module exports. Thanks @inth3shadows for the report. (#3233)

## [1.6.3] - 2026-11-17

Expand Down
117 changes: 117 additions & 0 deletions __tests__/js-namespace-reexports.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/**
* JS/TS module namespaces handed on by name, and `export *` barrels:
* - a name a module exports as a module namespace — `export * as ns3 from
* './schemas'`, or zod's `import * as z from './external'; export { z }` —
* is that module where another file imports it by name, so `z.ipv4()`
* after `import { z } from './index'` is the module's `ipv4`, as after
* `import * as z` (#2951);
* - through a barrel of several `export *` lines, a module's own export of a
* name answers before a member of an object another module exports, in
* whichever order the lines come (#3233).
*/

import { describe, it, expect, afterEach } from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import CodeGraph from '../src/index';

let tempDir: string;
let cg: CodeGraph | null = null;

async function index(files: Record<string, string>): Promise<void> {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-ns-reexport-'));
for (const [rel, content] of Object.entries(files)) {
const abs = path.join(tempDir, rel);
fs.mkdirSync(path.dirname(abs), { recursive: true });
fs.writeFileSync(abs, content);
}
cg = await CodeGraph.init(tempDir, { index: true });
}

/** The calls made by the function with this name, as `kind qualifiedName (file:line)`. */
function callsFrom(name: string): string[] {
const from = cg!.getNodesByKind('function').find((n) => n.name === name);
expect(from, `${name} should be indexed`).toBeDefined();
return cg!.getOutgoingEdges(from!.id).filter((e) => e.kind === 'calls')
.map((e) => { const t = cg!.getNode(e.target)!; return `${t.kind} ${t.qualifiedName} (${t.filePath}:${t.startLine})`; })
.sort();
}

afterEach(() => {
cg?.close();
cg = null;
if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true });
});

const SCHEMAS = {
'schemas.ts':
'export interface ZodString { ipv4(): this; nope(): this; }\n' +
'export function ipv4(): ZodString { return null as any; }\n',
'external.ts': 'export * from "./schemas.js";\n',
'index.ts': 'import * as z from "./external.js";\nexport { z };\n',
'index2.ts': 'import * as ns from "./schemas.js";\nexport { ns };\n',
'index3.ts': 'export * as ns3 from "./schemas.js";\n',
'outer.ts': 'export { z } from "./index.js";\n',
};

describe('a module namespace imported by name (#2951)', () => {
it('is the module, as a namespace import of it is', async () => {
await index({
...SCHEMAS,
'b.ts': 'import * as z from "./external.js";\nexport function fb() { z.ipv4(); }\n',
'a.ts': 'import { z } from "./index.js";\nexport function fa() { z.ipv4(); }\n',
'c.ts': 'import { ns } from "./index2.js";\nexport function fc() { ns.ipv4(); }\n',
'd.ts': 'import { ns3 } from "./index3.js";\nexport function fd() { ns3.ipv4(); }\n',
'e.ts': 'import { z } from "./outer.js";\nexport function fe() { z.ipv4(); }\n',
});
for (const fn of ['fb', 'fa', 'fc', 'fd', 'fe']) {
expect(callsFrom(fn), fn).toEqual(['function ipv4 (schemas.ts:2)']);
}
});

it('links no method of another type to a member the module does not export', async () => {
await index({
...SCHEMAS,
'a.ts': 'import { z } from "./index.js";\nexport function fa() { z.nope(); }\n',
});
expect(callsFrom('fa')).toEqual([]);
});
});

const FX = {
'fx/deaf.ts': 'export const DEAF = {\n log: async () => undefined,\n mark: async () => undefined,\n}\n',
'fx/mark.ts': 'export const mark = (entry: unknown): string => String(entry)\n',
};

describe('an export * barrel (#3233)', () => {
it('answers with a module\'s own export before an object\'s same-named method', async () => {
await index({
...FX,
'fx/index.ts': "export * from './deaf.js'\nexport * from './mark.js'\n",
'c.ts': "import { mark } from './fx'\nexport function useNamed() { return mark(1) }\n",
'd.ts': "import * as NS from './fx'\nexport function useNs() { return NS.mark(1) }\n",
});
expect(callsFrom('useNamed')).toEqual(['function mark (fx/mark.ts:1)']);
expect(callsFrom('useNs')).toEqual(['function mark (fx/mark.ts:1)']);
});

it('does so through `export * as default from` a barrel of itself', async () => {
await index({
...FX,
'fx/index.ts': "export * from './deaf.js'\nexport * from './mark.js'\nexport * as default from '.'\n",
'e.ts': "import Fixtures from './fx'\nexport function useDefault() { return Fixtures.mark(1) }\n",
});
expect(callsFrom('useDefault')).toEqual(['function mark (fx/mark.ts:1)']);
});

it('still answers with a member when no module exports the name itself', async () => {
await index({
'fx/deaf.ts': 'export const DEAF = {\n mark: async () => undefined,\n}\nexport const { mark } = DEAF\n',
'fx/log.ts': 'export const log = (s: string): void => {}\n',
'fx/index.ts': "export * from './log.js'\nexport * from './deaf.js'\n",
'c.ts': "import { mark } from './fx'\nexport function useNamed() { return mark(1) }\n",
});
expect(callsFrom('useNamed')).toEqual(['function DEAF::mark (fx/deaf.ts:2)']);
});
});
106 changes: 91 additions & 15 deletions src/resolution/import-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3176,6 +3176,45 @@ function namespaceDeclaringFile(
return undefined;
}

/**
* The module whose namespace object `file` exports as `name`, when that
* export is one (#2951): `export * as name from './m'`, or a namespace import
* the file exports by clause, zod's `import * as z from './external.js';
* export { z }` — through named re-exports and `export *` lines, as the
* barrels that pass the name on write them. Null when the file declares the
* name itself, or exports no namespace by it.
*/
function namespaceExportModule(
file: string,
name: string,
language: Language,
context: ResolutionContext,
depth = 0,
seen = new Set<string>(),
): string | null {
if (depth > REEXPORT_MAX_DEPTH || seen.has(file)) return null;
seen.add(file);
if (exportedByName(file, getFileExportIndex(file, context), name, context)) return null;
const reExports = context.getReExports?.(file, language) ?? [];
const namespaced = reExports.find((rex) => rex.kind === 'namespace' && rex.exportedName === name);
if (namespaced) return resolveImportPath(namespaced.source, file, language, context);
const source = context.readFile(file);
if (source?.includes('export')) {
for (const { exportedName, localName } of extractLocalExportAliases(source)) {
if (exportedName !== name) continue;
const imported = context.getImportMappings(file, language).find((m) => m.isNamespace && m.localName === localName);
if (imported) return resolveImportPath(imported.source, file, language, context);
}
}
for (const rex of reExports) {
if (rex.kind !== 'wildcard' && !(rex.kind === 'named' && rex.exportedName === name)) continue;
const next = resolveImportPath(rex.source, file, language, context);
const found = next ? namespaceExportModule(next, rex.kind === 'named' ? rex.originalName : name, language, context, depth + 1, seen) : null;
if (found) return found;
}
return null;
}

export function resolveViaImport(
ref: UnresolvedRef,
context: ResolutionContext
Expand Down Expand Up @@ -3426,6 +3465,25 @@ export function resolveViaImport(
const targetNode = findImportedExport(imp.source, resolvedPath, want, ref, context);
const memberRead = !imp.isNamespace && ref.referenceName.startsWith(imp.localName + '.');

// A name the module exports as a module namespace — `export * as ns
// from './m'`, or zod's `import * as z from './external.js'; export
// { z }` — is that module, as `import * as` of it is (#2951): `z.ipv4()`
// is what the module exports as `ipv4` and nothing else, and the import
// itself links the module's file.
const namespace = !targetNode && !imp.isNamespace && !imp.isDefault && resolvedPath && ESM_IMPORT_LANGUAGES.has(ref.language)
? namespaceExportModule(resolvedPath, exportedName, ref.language, context) : null;
if (namespace) {
if (memberRead) {
const member = ref.referenceName.slice(imp.localName.length + 1);
const found = findExportedSymbol(namespace, { isDefault: false, isNamespace: true, exportedName: member.split('.')[0]!, memberName: member }, ref.language, context, new Set());
if (found) return { original: ref, targetNodeId: found.id, confidence: 0.9, resolvedBy: 'import' };
} else if (ref.referenceKind === 'imports') {
const fileNode = context.getNodesInFile(namespace).find((n) => n.kind === 'file');
if (fileNode) return { original: ref, targetNodeId: fileNode.id, confidence: 0.9, resolvedBy: 'import' };
}
continue;
}

// `named.second()` through a default binding: what the module exports
// as `second`. `require('./m')` is the whole module, and so is a
// default import of a CommonJS one. Where the module states no default
Expand Down Expand Up @@ -4281,28 +4339,37 @@ function findExportedSymbol(
language: Language,
context: ResolutionContext,
visited: Set<string>,
depth = 0
depth = 0,
members: MemberAnswers = 'after'
): Node | undefined {
// Memoize fresh (top-level) lookups only: recursive re-export steps carry a
// populated `visited` set, whose contents change the reachable answer.
// Every ref to the same imported symbol repeats this exact walk, so the
// top-level memo removes the re-export chase + per-file linear scans from
// all but the first occurrence.
if (depth === 0 && visited.size === 0) {
if (depth === 0 && visited.size === 0 && members === 'after') {
let memo = exportedSymbolMemos.get(context);
if (!memo) {
memo = new Map();
exportedSymbolMemos.set(context, memo);
}
const key = `${filePath}\0${want.isDefault ? 1 : 0}${want.isNamespace ? 1 : 0}\0${want.exportedName}\0${want.memberName ?? ''}\0${language}`;
if (memo.has(key)) return memo.get(key);
const result = findExportedSymbolWalk(filePath, want, language, context, visited, depth);
const result = findExportedSymbolWalk(filePath, want, language, context, visited, depth, members);
memo.set(key, result);
return result;
}
return findExportedSymbolWalk(filePath, want, language, context, visited, depth);
return findExportedSymbolWalk(filePath, want, language, context, visited, depth, members);
}

/**
* When a member of something else in a file (exportedMember, the walk's last
* answer) may answer: `'yes'` where the walk finds one, `'no'` never, and
* `'after'` only once no module an `export *` reaches exports the name itself
* (#3233) — a walk with no members, then one with them.
*/
type MemberAnswers = 'after' | 'no' | 'yes';

function findExportedSymbolWalk(
filePath: string,
want: {
Expand All @@ -4314,7 +4381,8 @@ function findExportedSymbolWalk(
language: Language,
context: ResolutionContext,
visited: Set<string>,
depth: number
depth: number,
members: MemberAnswers
): Node | undefined {
if (depth > REEXPORT_MAX_DEPTH) return undefined;
if (visited.has(filePath)) return undefined;
Expand All @@ -4334,7 +4402,7 @@ function findExportedSymbolWalk(
const commonJs = typeof stated === 'object' ? null : commonJsDefaultExport(filePath, context);
if (commonJs?.source) {
const next = resolveImportPath(commonJs.source, filePath, language, context);
const forwarded = next ? findExportedSymbol(next, want, language, context, visited, depth + 1) : undefined;
const forwarded = next ? findExportedSymbol(next, want, language, context, visited, depth + 1, members) : undefined;
if (forwarded) return forwarded;
} else if (commonJs?.name) {
const bound = moduleBindingsFirst(filePath, nodesInFileNamed(filePath, commonJs.name, context)
Expand All @@ -4355,7 +4423,7 @@ function findExportedSymbolWalk(
// `module.exports = require('./lib/m')` forwards the whole module.
const source = commonJsDefaultExport(filePath, context)?.source;
const next = source ? resolveImportPath(source, filePath, language, context) : null;
const forwarded = next ? findExportedSymbol(next, want, language, context, visited, depth + 1) : undefined;
const forwarded = next ? findExportedSymbol(next, want, language, context, visited, depth + 1, members) : undefined;
if (forwarded) return forwarded;
} else {
const direct = exportedByName(filePath, exportIndex, want.exportedName, context);
Expand All @@ -4380,7 +4448,7 @@ function findExportedSymbolWalk(

// 2. Re-export hit: the file forwards the symbol to another module.
const reExports = context.getReExports?.(filePath, language) ?? [];
if (reExports.length === 0) return exportedMember(exportIndex, want);
if (reExports.length === 0) return members === 'no' ? undefined : exportedMember(exportIndex, want);

// Look for explicit `export { want } from './other'` (with optional rename) — for
// `ns.member` through `import * as ns`, the member is the name wanted.
Expand All @@ -4402,7 +4470,8 @@ function findExportedSymbolWalk(
language,
context,
visited,
depth + 1
depth + 1,
members
);
if (chained) return chained;
}
Expand All @@ -4417,25 +4486,32 @@ function findExportedSymbolWalk(
const next = resolveImportPath(rex.source, filePath, language, context);
const rest = want.memberName.slice(dot + 1);
return next
? findExportedSymbol(next, { ...want, exportedName: rest.split('.')[0]!, memberName: rest }, language, context, visited, depth + 1)
? findExportedSymbol(next, { ...want, exportedName: rest.split('.')[0]!, memberName: rest }, language, context, visited, depth + 1, members)
: undefined;
}
}

// 3. Wildcard re-export: `export * from './other'` — try every
// forwarding source. This is the barrel-of-barrels case.
for (const rex of reExports) {
if (rex.kind === 'wildcard') {
// forwarding source. This is the barrel-of-barrels case. A source's own
// export of the name answers before any source's member of an object,
// whichever `export *` line comes first (#3233): the members are the
// second pass, over the same sources afresh.
const wildcards = reExports.filter((rex) => rex.kind === 'wildcard');
const passes: MemberAnswers[] = members === 'after' && wildcards.length > 0 ? ['no', 'yes'] : [members];
const before = passes.length > 1 ? new Set(visited) : visited;
for (const [i, pass] of passes.entries()) {
const seen = i > 0 ? new Set(before) : visited;
for (const rex of wildcards) {
const next = resolveImportPath(rex.source, filePath, language, context);
if (!next) continue;
// Python's `from m import *` binds only `m.__all__`, else m's public names.
if (PYTHON_MODULE_FILE.test(next) && !want.isDefault && !pythonStarAllows(next, want.exportedName, context)) continue;
const chained = findExportedSymbol(next, want, language, context, visited, depth + 1);
const chained = findExportedSymbol(next, want, language, context, seen, depth + 1, pass);
if (chained) return chained;
}
}

return exportedMember(exportIndex, want);
return members === 'no' ? undefined : exportedMember(exportIndex, want);
}

/**
Expand Down
8 changes: 7 additions & 1 deletion src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27453,7 +27453,13 @@ function isImportedModuleReceiver(receiver: string, ref: UnresolvedRef, context:
const root = receiver.split('.')[0]!;
const binding = context.getImportMappings?.(ref.filePath, ref.language)?.find((m) => m.localName === root);
if (!binding) return false;
return binding.isNamespace || context.isOutOfRepoImport?.(binding.source, ref.filePath, ref.language) === true;
if (binding.isNamespace || context.isOutOfRepoImport?.(binding.source, ref.filePath, ref.language) === true) return true;
// So is a name the module exports as a module namespace, `import { z }` of
// zod's `export { z }` of `import * as z` (#2951): the import resolver links
// what imports it to that module's file.
if (binding.isDefault || !JS_FAMILY.has(ref.language)) return false;
const bound = context.resolveImport?.({ ...ref, referenceName: root, referenceKind: 'imports' });
return !!bound && context.getNodeById?.(bound.targetNodeId)?.kind === 'file';
}

const JS_ASSIGNED_MEMBERS = new WeakMap<ResolutionContext, Map<string, ReadonlySet<string>>>();
Expand Down