Skip to content

fix(regex): sort dictionary keys by length so longer rules match first - #179

Merged
antfu merged 1 commit into
made-in-common:mainfrom
MukundaKatta:fix/sort-rules-by-length
Apr 15, 2026
Merged

antfu merged 1 commit into
made-in-common:mainfrom
MukundaKatta:fix/sort-rules-by-length

Conversation

@MukundaKatta

Copy link
Copy Markdown
Contributor

Summary

Regex alternation is leftmost-wins, not longest-wins. So when the dictionary contains both abc and abc.def, results depended on dictionary insertion order:

// With this order, `AbC.DeF` would only match the shorter `abc` key
{ "abc": "Abc", "abc.def": "Abc.Def" }

Against input AbC AbC.DeF:

  • Before: AbC → Abc, then AbC inside AbC.DeF → Abc, leaving Abc.DeF ❌
  • After: longer key tried first → AbC → Abc, AbC.DeF → Abc.Def ✅

Sort keys by length descending when building the regex so the more specific rule wins, regardless of dictionary order.

Test plan

  • pnpm vitest run — 6 tests pass (2 new cases for both dictionary orderings)
  • pnpm lint
  • pnpm -r build

Fixes #158

Regex alternation is leftmost-wins, not longest-wins, so when the
dictionary contains both `abc` and `abc.def` the result depended on
insertion order: `abc` declared first would shadow `abc.def` for input
like `AbC.DeF`.

Sort keys by length descending when building the regex so that the
more specific rule is tried first, regardless of dictionary order.

Fixes made-in-common#158
@antfu
antfu merged commit 973b0a3 into made-in-common:main Apr 15, 2026
3 checks passed
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.

Rules with a dot in them are ignored if a prior rule matches at least part of it

2 participants