Skip to content

fix(define): only match escaped dots in escapedDotRE so $-prefixed define keys are replaced - #23249

Open
contactjawad wants to merge 1 commit into
vitejs:mainfrom
contactjawad:fix-define-escaped-dot-regex
Open

fix(define): only match escaped dots in escapedDotRE so $-prefixed define keys are replaced#23249
contactjawad wants to merge 1 commit into
vitejs:mainfrom
contactjawad:fix-define-escaped-dot-regex

Conversation

@contactjawad

Copy link
Copy Markdown

Description

The define plugin silently drops define keys that contain a $ (e.g. define: { $FOO: '"bar"' }) — the transform leaves the source unchanged instead of replacing $FOO.

Root cause: escapedDotRE = /(?<!\\)\\./g is meant to rewrite an escaped dot (\.) inside an already-escapeRegex-escaped key into \??\. (so it also matches optional chaining, ?.). But the . in that regex is unescaped, so it actually matches a backslash followed by any character. escapeRegex('$FOO') produces \$FOO; the replaceAll then rewrites \$\??\., producing the pattern \??\.FOO, which never matches $FOO. The pattern.test(code) pre-check is then false and the replacement is skipped.

Fix: escape the dot (/(?<!\\)\\\./g) so only an escaped literal dot is rewritten. Dotted keys like import.meta.env are unaffected (both regexes yield foo\??\.bar), while escaped metacharacters such as \$ are left intact.

Added a regression test (replaces define keys containing $) that fails on main (the transform returns undefined) and passes with this change.

…keys are replaced

escapedDotRE was /(?<!\\)\\./g, whose `.` is unescaped, so it matched a
backslash followed by any character. For a define key like `$FOO`, escapeRegex
produces `\$FOO`, and the replaceAll then rewrote `\$` to `\??\.`, producing the
pattern `\??\.FOO`, which never matches `$FOO`. The `pattern.test(code)`
pre-check was therefore false and the define was silently skipped.

Escape the dot so only an escaped literal dot is rewritten. Dotted keys like
`import.meta.env` are unaffected (both regexes yield `foo\??\.bar`), while
escaped metacharacters such as `\$` are now left intact.
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.

1 participant