Skip to content

fix: preserve package import specifiers when removing barrels - #11

Merged
webpro merged 3 commits into
webpro-nl:mainfrom
everton-dgn:fix/preserve-package-import-specifiers
Nov 23, 2026
Merged

webpro merged 3 commits into
webpro-nl:mainfrom
everton-dgn:fix/preserve-package-import-specifiers

Conversation

@everton-dgn

Copy link
Copy Markdown
Contributor

Package imports such as #utils are parsed as URL fragments. Rewriting a barrel reached through package.json#imports can then produce an unmapped key or resolve the wrong conditional target.

Recognize the leading # as part of the module specifier. Reuse a package import only when it resolves to the same file from the consumer; otherwise use a relative path with the correct output extension. Keep import and require conditions separate, preserve query/fragment suffixes, and retain barrels still needed by dynamic imports. Cache compiler configuration and programs within each public call, with separate state for concurrent calls. Relative imports avoid the TypeScript program lookup.

The regression suite executes consumers before and after rewriting and covers package boundaries, conditional mappings, compiled TypeScript/JavaScript, and config changes between calls. Validation: 245 tests passed on Node 24, including 64 focused cases; build, lint, format and installed-check passed. The external-project CI integrations were not run locally.

@webpro webpro left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, Éverton! I could reproduce two failures behind this on main. A barrel reached through a key such as #utils is not seen as imported, so it is deleted as soon as another consumer is rewritten, and #utils then fails with TS2307. And a barrel's own export * from "#internal" is copied into consumers in other packages, where that key is not mapped. This branch fixes both in every layout I tried.

The rest of the diff goes further than that. Selecting import or require conditions for projects that emit CommonJS is out of scope for unbarrelify, which is ESM-only. Please remove usesRequire and computeUsesRequire, the dynamic parameter, the extra resolvers, withResolutionCache and the change to the default conditionNames, together with their tests.

What should remain is the fix for the two failures above and the extension choice for relative fallbacks. Please rebase that onto #8 once it has landed and use its resolveModule(from, specifier, aliases) === to check in buildSpecifier in place of isValidAlias and reusableSpecifier, so one check decides whether a candidate specifier is kept. Two notes on the part that stays are inline.

Comment thread src/rewriter.ts Outdated
Comment on lines +352 to +372
// Do not introduce explicit TypeScript extensions through package mappings.
// If any binding cannot be expressed safely, retain every import of that barrel
// in this consumer so the tracker also retains the barrel.
if (ctx.ext === undefined) {
for (const importSet of analysis.imports.values()) {
const positions = [...importSet].map((item) => `${item.pos.start}:${item.pos.end}`);
const unsafe = [...importSet].some(
(item) =>
item.originalSpecifier?.startsWith("#") &&
[...(rewrites.get(`${item.pos.start}:${item.pos.end}`) ?? [])].some(([target, rewrite]) => {
if (rewrite.externalSpecifier) return false;
const specifier = buildSpecifier(filePath, target, {
originalSpecifier: rewrite.originalSpecifier,
aliases: ctx.aliases,
});
return specifier.startsWith(".") && /\.[cm]?tsx?$/.test(specifier);
}),
);
if (unsafe) for (const pos of positions) rewrites.delete(pos);
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When this pass drops the rewrites, the barrel is reported as preserved with reason namespace-import, although the consumer has a named import. It is also stricter than the project requires. With "#utils": "./src/utils/index.ts" and allowImportingTsExtensions, a second consumer that imports the barrel by relative path is rewritten to ./src/utils/value.ts, while the #utils consumer next to it is left alone and the barrel stays. The pass builds those specifiers a second time and inspects the result with a regex. Could the extension decision live in buildSpecifier, and could a retained barrel get a reason that says why?

}
});

describe("package import repair3 regressions", () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The suite names here and on line 34 (repair3, repair4) describe how the tests came about, not what they cover. The file also takes about 24 seconds, against 1.6 seconds for the whole suite on main, because the tests run their fixtures in child processes before and after rewriting. Once the condition tests are gone, a few cases named after the behavior should be enough, covering the two failures above, a reused wildcard key and the relative fallback.

Sync with upstream after the exact-alias fix and reuse its resolver validation.
Remove the separate condition resolvers and keep the package import cases in process.

@webpro webpro left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is the change we asked for. The condition handling is gone, key reuse goes through the same resolver check as #8, the pass that dropped rewrites afterwards is gone, and the tests are five quick cases named after what they cover. Both failures from the first round are fixed, and the layouts I used then all type-check after the run.

One thing still blocks it: the extension chosen for the relative fallback breaks projects that write extensionless imports. Details and a one-line suggestion are inline, together with three smaller notes on untested additions and the dry-run preview.

Could you also update the description? It still describes the condition handling and the old test counts.

Comment thread src/resolver.ts Outdated
finalExt =
getExtensionFromSpecifier(originalSpecifier) ??
(packageKey
? (packageTargetSpecifier && getExtensionFromSpecifier(packageTargetSpecifier)) || extname(to) || null

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The extname(to) fallback gives a .ts path to projects that write extensionless imports. With Bundler resolution and no allowImportingTsExtensions, a consumer of #utils whose barrel has export { value } from "./value" is rewritten to ./src/utils/value.ts, which fails with TS5097. On main that project is left alone and type-checks. The same happens to a relative, extensionless consumer of a barrel in another package that has export * from "#internal": it becomes ../lib/src/internal.ts. Without the fallback both come out extensionless, the suite still passes, and so do the .ts-style and .js-style layouts I tried. Could you add a case for the extensionless style as well?

Suggested change
? (packageTargetSpecifier && getExtensionFromSpecifier(packageTargetSpecifier)) || extname(to) || null
? (packageTargetSpecifier && getExtensionFromSpecifier(packageTargetSpecifier)) || null

Comment thread src/resolver.ts Outdated
Comment on lines +52 to +56
return isRelativeOrAbsolute || cleanSpecifier.startsWith("#") ? undefined : cleanSpecifier;
}

if (resolvedPath.includes("node_modules")) {
return cleanSpecifier;
return cleanSpecifier.startsWith("#") ? undefined : cleanSpecifier;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No test needs these two changes: the suite passes with either line reverted. They also change behavior beyond the two failures. When a key maps to a package in node_modules, a barrel's export { value } from "#dep" is now dropped from its export map, so value is reported as untraceable and the barrel is kept. That helps a consumer in another package, where main copies the unmapped key, but a consumer in the same package, which main rewrites to #dep, now stays on the barrel too. Could you add a test that shows the intended behavior, or leave resolveModule as it was if this is not needed?

Comment thread src/resolver.ts
Comment on lines +99 to +102
const candidates =
slash < 0 ? [packageKey] : [packageKey, packageKey.slice(0, slash + 1) + basename(to, extname(to))];
for (const candidate of candidates) {
if (resolveModule(from, candidate, aliases ?? null) === to) return candidate;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reusing the barrel's own key has no test either. The suite passes when packageKey is left out of the candidates, and when packageImportSpecifier is removed in buildRewriteItem, buildUnsafeNamespaceRewrites or traceStarExports. The behavior is right in my runs: a same-package consumer of a barrel with export * from "#internal" keeps #internal. One test for that case would pin it.

Comment thread src/rewriter.ts Outdated
Comment on lines +84 to +85
packageImportSpecifier: rewrite.packageImportSpecifier,
packageTargetSpecifier: rewrite.packageTargetSpecifier,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

formatExampleDiff in src/diff.ts builds the same options without these two fields, so the dry-run preview can differ from what --write produces. With "#utils": "./src/utils/index.js" under NodeNext, the preview shows ./src/utils/value.ts and the written import is ./src/utils/value.js.

@webpro webpro left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, that resolves it. The extensionless layouts now keep their style, the key-reuse and package-key cases have tests, and the dry-run preview goes through the same helper as the written output, so the two match. All the layouts from the earlier rounds type-check after the run. Nothing further from my side.

@webpro
webpro merged commit accdd19 into webpro-nl:main Nov 23, 2026
5 checks passed
@webpro

webpro commented Nov 24, 2026

Copy link
Copy Markdown
Member

🚀 This pull request is included in v1.2.0. See Release 1.2.0 for release notes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants