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
29 changes: 29 additions & 0 deletions __tests__/require-directory-package-main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,25 @@ const Srv = require('..')
const Srv2 = require('../')
const Srv3 = require('../srv')
function t () { Srv(); Srv2(); Srv3() }
`,
// A package.json a Windows editor saved with a byte-order mark.
'lib/bom/package.json': '\uFEFF' + JSON.stringify({ main: 'entry.js' }),
'lib/bom/entry.js': `function bom () { return 4 }
module.exports = bom
`,
'c.js': `const bom = require('./lib/bom')
function v () { bom() }
`,
// Nix imports a folder's default.nix, whatever else the folder holds.
'default.nix': `{ pkgs ? import <nixpkgs> {} }:
let web = import ./web { inherit pkgs; };
in web
`,
'web/default.nix': `{ pkgs }: pkgs.hello
`,
'web/package.json': JSON.stringify({ main: 'index.js' }),
'web/index.js': `function web () { return 5 }
module.exports = web
`,
'b.js': `const helper = require('./lib')
const inner = require('./lib/inner')
Expand Down Expand Up @@ -70,6 +89,16 @@ describe('a relative require of a directory', () => {
expect(callsOf('test/a.test.js', 't')).toEqual(['srv srv.js', 'srv srv.js', 'srv srv.js']);
});

it('reads a package.json that starts with a byte-order mark, as Node does', () => {
expect(callsOf('c.js', 'v')).toEqual(['bom lib/bom/entry.js']);
});

it("leaves other languages' folder imports alone: Nix still imports the folder's default.nix", () => {
const file = cg.getNodesInFile('default.nix').find((n) => n.kind === 'file')!;
const imports = cg.getOutgoingEdges(file.id).filter((e) => e.kind === 'imports').map((e) => cg.getNode(e.target)!.filePath);
expect(imports).toEqual(['web/default.nix']);
});

it("reaches a subdirectory's main, with or without its extension, and still an index.js", () => {
expect(callsOf('b.js', 'u')).toEqual(['bare lib/bare/main.js', 'helper lib/index.js', 'inner lib/inner/entry.js']);
});
Expand Down
12 changes: 12 additions & 0 deletions __tests__/sync-module-config-change.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,18 @@ describe('a sync follows a module-config change (#2977)', () => {
expect(stateOf(root, graph)).toEqual(full);
}, 120_000);

it("a folder's package.json main retargeted, the importer untouched (#2964)", async () => {
const before: Files = {
'lib/package.json': JSON.stringify({ main: 'a.js' }),
'lib/a.js': 'function a () { return 1 }\nmodule.exports = a\n',
'lib/b.js': 'function b () { return 2 }\nmodule.exports = b\n',
'app.js': "const lib = require('./lib')\nfunction go () { return lib() }\n",
};
const { root, graph, full } = await syncEdit(before, { 'lib/package.json': JSON.stringify({ main: 'b.js' }) });
expect(callTargets(graph, 'go')).toEqual(['lib/b.js::b']);
expect(stateOf(root, graph)).toEqual(full);
}, 120_000);

it('a mapping declared in the extends chain', async () => {
const before: Files = {
...TS_BEFORE,
Expand Down
37 changes: 27 additions & 10 deletions src/resolution/import-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1386,7 +1386,7 @@ function resolveRelativeImport(
if (relativePath === '' && !ext.startsWith('/')) continue;
// A directory's `package.json` `main` comes before its index files, as
// Node loads a directory (#2964).
if (ext.startsWith('/') && !mainTried) {
if (ext.startsWith('/') && !mainTried && FOLDER_MAIN_LANGUAGES.has(language)) {
mainTried = true;
const main = relativeDirectoryMain(relativePath, language, context);
if (main) return main;
Expand All @@ -1406,21 +1406,38 @@ function resolveRelativeImport(
}

/**
* The indexed file a directory's `package.json` names as `main`: fastify's
* tests `require('..')` for the root's `"main": "fastify.js"`. Null when the
* directory has no manifest, no `main`, or one outside the project.
* The importers whose relative import of a folder reads the folder's
* `package.json` `main`, as Node and the bundlers do. Nix (`/default.nix`),
* Python (`/__init__.py`) and the rest load a folder their own way.
*/
function relativeDirectoryMain(dir: string, language: Language, context: ResolutionContext): string | null {
const manifest = context.readFile(dir === '' ? 'package.json' : `${dir}/package.json`);
if (!manifest) return null;
const FOLDER_MAIN_LANGUAGES: ReadonlySet<Language> = new Set<Language>(['javascript', 'typescript', 'tsx', 'jsx']);

/** A `package.json`'s `main`, trimmed; null when it has none or doesn't parse. A leading byte-order mark is skipped, as Node skips it. */
export function packageJsonMain(text: string): string | null {
let main: unknown;
try {
main = (JSON.parse(manifest) as { main?: unknown } | null)?.main;
main = (JSON.parse(text.replace(/^\uFEFF/, '')) as { main?: unknown } | null)?.main;
} catch {
return null;
}
if (typeof main !== 'string' || !main.trim()) return null;
const entry = path.posix.normalize(path.posix.join(dir, main.trim()));
return typeof main === 'string' && main.trim() ? main.trim() : null;
}

/**
* The indexed file a directory's `package.json` names as `main`: fastify's
* tests `require('..')` for the root's `"main": "fastify.js"`. Null when the
* directory has no manifest, no `main`, or one outside the project. A
* manifest it reads joins the module-config snapshot, so a sync after an
* edit to its `main` resolves the folder's importers again.
*/
function relativeDirectoryMain(dir: string, language: Language, context: ResolutionContext): string | null {
const manifestPath = dir === '' ? 'package.json' : `${dir}/package.json`;
const manifest = context.readFile(manifestPath);
if (!manifest) return null;
context.noteModuleConfigFile?.(manifestPath);
const main = packageJsonMain(manifest);
if (!main) return null;
const entry = path.posix.normalize(path.posix.join(dir, main));
if (entry.startsWith('..') || entry === '.') return null;
return indexedTarget(entry, language, context);
}
Expand Down
15 changes: 14 additions & 1 deletion src/resolution/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import { matchShopifyThemeFile } from './shopify-themes';
import { isJsSuperCallLanguage, isJsSuperCallSite, matchJsSuperCall } from './js-super-calls';
import { CLASS_EXPRESSION_REF_LANGUAGES, isCommonJsExportedClass, isJsClassExpression, writtenIn, type ClassExpressionIndex } from './js-class-expressions';
import { clearRubyConstantPathMemos, matchRubyConstantPathRef } from './ruby-constant-paths';
import { resolveViaImport, resolvePhpImportedStaticCall, resolvePhpQualifiedClassRef, resolveTsQualifiedTypeRef, resolveJvmImport, extractImportMappings, extractReExports, CPP_COMPILE_DB_FILES, loadCppIncludeDirsFromCompileDB, loadCppIncludeDirsHeuristic, readCompileDbIncludeDirs, isPhpIncludePathRef, isCobolCopybookRef, isNixPathImportRef, isDartImportRef, isLuaRequireRef, isJsPathImportRef, isBoundToOutOfRepoImport, reachesAmbientModule, importBindingTail, clearImportResolverMemos, resolveImportPath, isExternalImport, pythonImportsInScope, ESM_IMPORT_LANGUAGES, jsModuleFile, pythonRootFingerprint, pythonReopenScope, pythonScriptModuleScope, pythonPackageImporters, moduleDefaultExport, isJsFamilyFile, isModuleBindingName } from './import-resolver';
import { resolveViaImport, resolvePhpImportedStaticCall, resolvePhpQualifiedClassRef, resolveTsQualifiedTypeRef, resolveJvmImport, extractImportMappings, extractReExports, CPP_COMPILE_DB_FILES, loadCppIncludeDirsFromCompileDB, loadCppIncludeDirsHeuristic, readCompileDbIncludeDirs, isPhpIncludePathRef, isCobolCopybookRef, isNixPathImportRef, isDartImportRef, isLuaRequireRef, isJsPathImportRef, isBoundToOutOfRepoImport, reachesAmbientModule, importBindingTail, clearImportResolverMemos, resolveImportPath, isExternalImport, pythonImportsInScope, ESM_IMPORT_LANGUAGES, jsModuleFile, pythonRootFingerprint, pythonReopenScope, pythonScriptModuleScope, pythonPackageImporters, moduleDefaultExport, isJsFamilyFile, isModuleBindingName, packageJsonMain } from './import-resolver';
import { ResolverPool, minRefsForPool, poolStartSettled, resolveWorkersWorthStarting, shouldEngageAdaptively } from './resolver-pool';
import { resolveAliasBinding } from './alias-binding';
import { readCargoWorkspaceCrateMap } from './frameworks/cargo-workspace';
Expand Down Expand Up @@ -358,6 +358,7 @@ function moduleConfigDigest(abs: string, projectRoot: string): string {
const read = file === 'go.mod' ? loadGoModule(path.dirname(abs))?.modulePath ?? ''
: file === 'Cargo.toml' ? cargoManifestDigestText(abs)
: file === 'compile_commands.json' ? (readCompileDbIncludeDirs(abs, projectRoot) ?? []).join('\n')
: file === 'package.json' ? packageJsonMainOf(abs)
: aliasConfigFields(abs) ?? '';
return createHash('sha256').update(read).digest('hex').slice(0, 16);
}
Expand All @@ -381,6 +382,15 @@ function readPackageJson(abs: string): Record<string, unknown> | null {
/** A dependency spec that takes the package from the project: a protocol, or npm's bare local path. */
const LOCAL_DEPENDENCY_SPEC = /^(?:(?:workspace|file|link|portal):|\.{1,2}\/|~\/|\/)/;

/** A folder's `package.json` `main`, which a relative import of the folder loads (see `relativeDirectoryMain`). */
function packageJsonMainOf(abs: string): string {
try {
return packageJsonMain(fs.readFileSync(abs, 'utf-8')) ?? '';
} catch {
return '';
}
}

function cargoManifestDigestText(abs: string): string {
try {
return cargoManifestFields(fs.readFileSync(abs, 'utf-8'));
Expand Down Expand Up @@ -1124,6 +1134,9 @@ export class ReferenceResolver {
},

readFile: (filePath: string) => this.readFileCached(filePath),
noteModuleConfigFile: (filePath: string) => {
this.moduleConfigFiles.add(path.join(this.projectRoot, filePath));
},

fileContains: (filePath: string, needle: string) => this.fileContains(filePath, needle),
scanFile: (filePath: string) => this.scanFile(filePath),
Expand Down
2 changes: 2 additions & 0 deletions src/resolution/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ export interface ResolutionContext {
fileExists(filePath: string): boolean;
/** Read file content */
readFile(filePath: string): string | null;
/** Record a project-relative file resolution read its answer from, for sync to watch (see `getModuleConfigSnapshot`). */
noteModuleConfigFile?(filePath: string): void;
/** `readFile(filePath)?.includes(needle) ?? false` for an ASCII `needle`, without decoding a file that lacks it. */
fileContains?(filePath: string, needle: string): boolean;
/**
Expand Down