Repository navigation
feat(dedupeImports): preserve imports with same from and name, but different type - #507
Conversation
📝 WalkthroughWalkthroughThe changes refactor the import deduplication logic in Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #507 +/- ##
==========================================
- Coverage 98.73% 94.57% -4.16%
==========================================
Files 14 13 -1
Lines 1817 996 -821
Branches 374 336 -38
==========================================
- Hits 1794 942 -852
- Misses 23 50 +27
- Partials 0 4 +4 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/utils.ts`:
- Around line 129-173: The current dedup logic (variables currImp, prevImp,
deduped and helper encodeImportName) drops complementary imports when priorities
differ across specifiers; change to resolve duplicates per (localName,
logicalSpecifier) group instead of per-entry: compute a stable key combining
name and logical specifier (use (typeFrom||from) for type-aware specifier),
collect all imports into groups, then for each group pick the highest-priority
value import and highest-priority type import (preserving complementary pairs
even if priorities differ), and finally populate deduped using encodeImportName
for type aliases and warn only when two selected imports share the same
localName and identical specifier but equal priority conflict; update the
selection logic currently using isSameSpecifier and priorityDiff to operate on
grouped candidates so complementary pairs are not lost.
- Around line 143-166: The deduplication logic incorrectly uses || 1 which
treats priority: 0 as missing; update comparisons in the block that handles
duplicate/complementary imports (the code using currImp.priority,
prevImp.priority and prevImpComplement?.priority around the
encodeImportName/deduped logic) to use the nullish coalescing operator ?? 1
instead of || 1 (including the Math.max call that computes priorityDiff) so an
explicit priority of 0 is preserved.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 55551eab-5495-44d5-875d-3c5731f28d54
📒 Files selected for processing (3)
src/utils.tstest/dedupe.test.tstest/dts.test.ts
| const name = String(currImp.as ?? currImp.name) | ||
| const prevImp = deduped.get(name) | ||
| if (!prevImp) { | ||
| deduped.set(name, currImp) | ||
| continue | ||
| } | ||
|
|
||
| const other = imports[map.get(name)!] | ||
| const isSameSpecifier = (currImp.type || prevImp.type) | ||
| ? (currImp.typeFrom || currImp.from) === (prevImp.typeFrom || prevImp.from) | ||
| : currImp.from === prevImp.from | ||
|
|
||
| if (other.from === i.from) { | ||
| indexToRemove.add(idx) | ||
| return | ||
| if (isSameSpecifier) { | ||
| if (Boolean(currImp.type) === Boolean(prevImp.type)) { | ||
| // currImp and prevImp are the same import | ||
| if ((currImp.priority || 1) > (prevImp.priority || 1)) { | ||
| deduped.delete(name) | ||
| deduped.set(name, currImp) | ||
| } | ||
| } | ||
| else { | ||
| // currImp and prevImp are complementary imports; one for the value and one for the type | ||
| const altName = encodeImportName(name) | ||
| const prevImpComplement = deduped.get(altName) | ||
| if (!prevImpComplement) { | ||
| deduped.set(altName, currImp) | ||
| } | ||
| else if ((currImp.priority || 1) > (prevImpComplement.priority || 1)) { | ||
| deduped.delete(altName) | ||
| deduped.set(altName, currImp) | ||
| } | ||
| } | ||
| continue | ||
| } | ||
| const diff = (other.priority || 1) - (i.priority || 1) | ||
| if (diff === 0) | ||
| warn(`Duplicated imports "${name}", the one from "${other.from}" has been ignored and "${i.from}" is used`) | ||
|
|
||
| if (diff <= 0) { | ||
| indexToRemove.add(map.get(name)!) | ||
| map.set(name, idx) | ||
| // currImp and prevImp are duplicate imports | ||
| const altName = encodeImportName(name) | ||
| const prevImpComplement = deduped.get(altName) | ||
| const priorityDiff = (currImp.priority || 1) - Math.max(prevImp.priority || 1, prevImpComplement?.priority || 1) | ||
| if (priorityDiff > 0) { | ||
| deduped.delete(name) | ||
| deduped.delete(altName) | ||
| deduped.set(name, currImp) | ||
| } | ||
| else { | ||
| indexToRemove.add(idx) | ||
| else if (priorityDiff === 0) { | ||
| warn(`Duplicated imports "${name}", the one from "${currImp.from}" has been ignored and "${prevImp.from}" is used`) |
There was a problem hiding this comment.
Complementary pairs are still lost when their priorities differ.
With { name: 'Foo', from: 'a', priority: 2 }, { name: 'Foo', from: 'a', type: true, priority: 1 }, and { name: 'Foo', from: 'b' }, reverse iteration stores Foo@b first, then drops type Foo@a on the different-specifier path before Foo@a is seen. The final result is only the value import from 'a', so downstream declaration generation loses the type half. Please add a regression for this case and resolve duplicates per (localName, logicalSpecifier) group instead of per individual entry.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/utils.ts` around lines 129 - 173, The current dedup logic (variables
currImp, prevImp, deduped and helper encodeImportName) drops complementary
imports when priorities differ across specifiers; change to resolve duplicates
per (localName, logicalSpecifier) group instead of per-entry: compute a stable
key combining name and logical specifier (use (typeFrom||from) for type-aware
specifier), collect all imports into groups, then for each group pick the
highest-priority value import and highest-priority type import (preserving
complementary pairs even if priorities differ), and finally populate deduped
using encodeImportName for type aliases and warn only when two selected imports
share the same localName and identical specifier but equal priority conflict;
update the selection logic currently using isSameSpecifier and priorityDiff to
operate on grouped candidates so complementary pairs are not lost.
| if ((currImp.priority || 1) > (prevImp.priority || 1)) { | ||
| deduped.delete(name) | ||
| deduped.set(name, currImp) | ||
| } | ||
| } | ||
| else { | ||
| // currImp and prevImp are complementary imports; one for the value and one for the type | ||
| const altName = encodeImportName(name) | ||
| const prevImpComplement = deduped.get(altName) | ||
| if (!prevImpComplement) { | ||
| deduped.set(altName, currImp) | ||
| } | ||
| else if ((currImp.priority || 1) > (prevImpComplement.priority || 1)) { | ||
| deduped.delete(altName) | ||
| deduped.set(altName, currImp) | ||
| } | ||
| } | ||
| continue | ||
| } | ||
| const diff = (other.priority || 1) - (i.priority || 1) | ||
| if (diff === 0) | ||
| warn(`Duplicated imports "${name}", the one from "${other.from}" has been ignored and "${i.from}" is used`) | ||
|
|
||
| if (diff <= 0) { | ||
| indexToRemove.add(map.get(name)!) | ||
| map.set(name, idx) | ||
| // currImp and prevImp are duplicate imports | ||
| const altName = encodeImportName(name) | ||
| const prevImpComplement = deduped.get(altName) | ||
| const priorityDiff = (currImp.priority || 1) - Math.max(prevImp.priority || 1, prevImpComplement?.priority || 1) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Verify the declared `priority` contract and the affected comparisons.
# Expected: `priority` is any number with default 1, and the current implementation uses `|| 1`.
sed -n '8,19p' src/types.ts
printf '\n---\n'
sed -n '136,167p' src/utils.tsRepository: unjs/unimport
Length of output: 1701
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Search for tests related to dedupeImports and priority handling
find . -type f -name "*.test.*" -o -name "*.spec.*" | head -20Repository: unjs/unimport
Length of output: 592
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Examine the dedupe test file for priority-related tests
wc -l test/dedupe.test.ts
printf '\n---\n'
cat -n test/dedupe.test.tsRepository: unjs/unimport
Length of output: 4202
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Search for other uses of priority comparison in the codebase
rg "priority.*\|\|" src/
printf '\n---\n'
# Also check if there are any uses of priority: 0 in tests or code
rg "priority.*0" test/ src/Repository: unjs/unimport
Length of output: 451
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Get full context of the dedupeImports function to verify the logic flow
sed -n '120,175p' src/utils.tsRepository: unjs/unimport
Length of output: 2078
Use ?? 1 instead of || 1 for numeric priority defaults.
Lines 143, 155, and 166 use || 1, which treats priority: 0 as missing since 0 is falsy. This breaks deduplication logic when priority is explicitly set to a valid numeric 0. Replace || with ?? to preserve valid 0 values and only default truly absent priorities:
Suggested fix
if (isSameSpecifier) {
if (Boolean(currImp.type) === Boolean(prevImp.type)) {
// currImp and prevImp are the same import
- if ((currImp.priority || 1) > (prevImp.priority || 1)) {
+ const currPriority = currImp.priority ?? 1
+ const prevPriority = prevImp.priority ?? 1
+ if (currPriority > prevPriority) {
deduped.delete(name)
deduped.set(name, currImp)
}
}
else {
// currImp and prevImp are complementary imports; one for the value and one for the type
const altName = encodeImportName(name)
const prevImpComplement = deduped.get(altName)
if (!prevImpComplement) {
deduped.set(altName, currImp)
}
- else if ((currImp.priority || 1) > (prevImpComplement.priority || 1)) {
+ else if (currPriority > (prevImpComplement.priority ?? 1)) {
deduped.delete(altName)
deduped.set(altName, currImp)
}
}
continue
}
// currImp and prevImp are duplicate imports
const altName = encodeImportName(name)
const prevImpComplement = deduped.get(altName)
- const priorityDiff = (currImp.priority || 1) - Math.max(prevImp.priority || 1, prevImpComplement?.priority || 1)
+ const currPriority = currImp.priority ?? 1
+ const prevPriority = prevImp.priority ?? 1
+ const prevComplementPriority = prevImpComplement?.priority ?? 1
+ const priorityDiff = currPriority - Math.max(prevPriority, prevComplementPriority)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/utils.ts` around lines 143 - 166, The deduplication logic incorrectly
uses || 1 which treats priority: 0 as missing; update comparisons in the block
that handles duplicate/complementary imports (the code using currImp.priority,
prevImp.priority and prevImpComplement?.priority around the
encodeImportName/deduped logic) to use the nullish coalescing operator ?? 1
instead of || 1 (including the Math.max call that computes priorityDiff) so an
explicit priority of 0 is preserved.
When `includeType` is enabled, classes/enums/const-enums/interfaces that live in both the value and type spaces are kept as two separate entries by `dedupeImports` (since unjs#507). `toExports` then emitted them both, producing invalid output like: export { Foo, Foo } from 'src/Foo'; A single `export { Foo }` already re-exports both the value and the type for these declaration kinds, so dedupe by exported alias before stringifying, preferring the value import when both forms exist. Fixes unjs#498
…ons (#529) When `includeType` is enabled, classes/enums/const-enums/interfaces that live in both the value and type spaces are kept as two separate entries by `dedupeImports` (since #507). `toExports` then emitted them both, producing invalid output like: export { Foo, Foo } from 'src/Foo'; A single `export { Foo }` already re-exports both the value and the type for these declaration kinds, so dedupe by exported alias before stringifying, preferring the value import when both forms exist. Fixes #498
Resolves #505 and #506.
Introduction
The main objective of this PR is to refactor
dedupeImportsto support "complementary" imports (i.e., imports with the samefromandnameproperties, but differenttype, see #506) by not deduplicating them.However, while doing that, I encountered that there was a bug and some refactor opportunities to improve performance inside
dedupeImports. Since all changes are for the same piece of code, and adding support for complementary imports would have fixed the bug and do the perf refactors anyway, I decided to submit a single PR, which I hope is not a problem. To clarify what the bug and performance improvements are, commits progressively changededupeImportsto separately address each issue.Bug fix (commits 1 and 2)
As described in #505, filtering disabled imports before collecting duplicate import indexes could result in some imports not being correctly deduplicated. To fix this, instead of creating a filtered array, disabled imports are skipped inside the
forEachloop to preserve index order.Perf refactor (commit 3)
The current implementation of
dedupeImportsmanages aMapof "visited" imports and aSetwith indexes of imports to remove. These collections are populated by iterating through the inputimportsarray once. Then, to produce the array without duplicates,importsis iterated over again to filter out indexes in the Set. The idea is that if instead of a visited-import Map and duplicate-import index Set, a singlededupedcollection only with imports that should be preserved could be built during the firstimportsiteration, then the second iteration only needs to be over deduped imports. This reduces collections used, data stored, and some iterations.This commit accomplishes that with a
Map<string | number, Import>that only stores deduped imports. Thestringkeys are importnames to be preserved.numberkeys are use only to add "skipped" imports (e.g., disabled imports) to the Map without conflicting with other import keys; that is why which number is used is not relevant, they do not need to be looked up, only be present in the map.Is important to mention that care was taken to preserve the relative order of imports from the
importsarray, which is why skipped imports are added to the Map the moment they're found, and when imports with higher priority are encountered, the currently stored import is first deleted before the new import is registered.With this refactor, the resulting deduped imports array can be generated with
deduped.values().toArray()instead ofimports.filter(callback), which can reduce the number of iterations, and reduces the work done on each iteration. Similarly, sinceimportsindexes are no longer required (lookups are made withnameproperties), afor...ofloop can be comfortably be used instead offorEach.Complementary imports support (commits 4 and 5)
An important change to
dedupeImportsin these commits is that theimportsarray iteration is performed in reverse order. This is essentially a better approach because imports with higher index have higher priority, which simplifies handling duplicates. For example, if all imports have the same default priority of1, encountered duplicates are simply ignored; there's no need to swap previously stored imports.Apart from that, there is one particular scenario where identifying complementary imports is hard with forward iteration, but simple with reverse iteration. Consider the following imports:
With forward iteration, when
foofromelsewhereis reached, there is no simple way to know that a complement for the firstfoofromsomewherewill be found, so it is simply removed. Later, the lastfoofromsomewherewill replacefoofromelsewhere, but without further refactoring, the first complement is essentially lost.On the other hand, with reverse iteration the problem is naturally solved because it is known that the first found import with a given name is the one preserved; and then, other duplicates can simply be checked to determine if they are complements, and handle them appropriately.
Now, once a complement is identified, it should also be stored in the
dedupedMap, but do so with a key that does not conflict with the formerly stored import. For this purpose theencodeImportNamefunction is introduced to transform the complement import'snameto\uFFFF${name}\uFFFEto be used as a Map's key. While it is technically possible for export names to have the form'\uFFFF*\uFFFE', I think is reasonable to expect them not to. For more information on'\uFFFE'and'\uFFFF', see Noncharacters and Noncharacter. Also, it would be possible to introduce a separate Map for complement imports instead, but a single Map is preferred because otherwise, two separate arrays need to be created and concatenated at the end.In
dedupeImportsnew conditions are evaluated to determine whether imports with the samenameare complements or duplicates. As an additional measure to preserve priority order, if two equal imports (same identifier and specifier) have different priorities, the one with higher priority is preserved.Like in the previous commit, care was taken to preserve relative order of imports with respect to the input
importsarray to ensure consistent behavior.Since the iteration is now reversed,
deduped.values()iterates over deduped imports in reverse order. An external array andfor (const imp of deduped.values())is used to produce the deduped array with the correct order. For the array,new Array(length)is used instead ofArray.from({length})because the latter initializes all properties toundefinedfirst; in that case it'd be simpler to usededuped.values().toArray().reverse().Another edge case
A scenario similar to the presented above, but involving explicit priorities still has issues with preserving complement imports. Consider:
In this case, with the reverse iteration approach,
foo@elsewhereis preferred overfoo@somewhere, so the latter is removed from thededupedMap. Then,foo@somewhereis preferred overfoo@elsewhere, but the firstfoo@somewhereis not easily recoverable at this point. However, I think addressing the first scenario is enough, especially considering that users could more easily handle this edge case by adjusting priorities (in this example, complementary import priorities should be made the same), and that duplicates between complements might be rare.Summary by CodeRabbit
Bug Fixes
Tests