dai-shi / waku

⛩️ The minimal React framework
https://waku.gg
MIT License
3.91k stars 102 forks source link

fix(waku/router): regex in file replacement to correctly handle all matches (fs-router) #678

Closed daanlenaerts closed 2 weeks ago

daanlenaerts commented 2 weeks ago

The current fs-router regex, /(^|\/|\\)_([^/]+)_(\/|\\|\.)/g, which is ran during build only replaces the first occurrence of underscores in scenarios where multiple underscore-surrounded segments are separated by single slashes. For example, in the string "app/_propertyId_/_surveyPartKey_.js", only _propertyId_ was being replaced, but _surveyPartKey_ was left unchanged due to the / being consumed during the first match.

This can easily be checked by running the following code:

const file = "app/_propertyId_/_surveyPartKey_.js";
console.log(file.replace(/(^|\/|\\)_([^/]+)_(\/|\\|\.)/g, '$1[$2]$3'));
// app/[propertyId]/_surveyPartKey_.js

Solution

The regex has been updated to /(?<=^|\/|\\)_([^/]+)_(?=\/|\\|\.)/g. This uses positive lookbehind (?<=^|\/|\\) and lookahead (?=\/|\\|\.) assertions to check for preceding and succeeding characters without consuming them. This allows every instance of the pattern to be replaced, regardless of their position in the string.

vercel[bot] commented 2 weeks ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
waku ✅ Ready (Inspect) Visit Preview Apr 27, 2024 11:45am
codesandbox-ci[bot] commented 2 weeks ago

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

daanlenaerts commented 2 weeks ago

No worries, thanks for merging it!