Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: clean string regexp #7871

Merged
merged 9 commits into from Apr 24, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/vite/src/node/__tests__/cleanString.spec.ts
@@ -1,3 +1,4 @@
import { assetAttrsConfig } from './../plugins/html'
import { emptyString } from '../../node/cleanString'

test('comments', () => {
Expand Down Expand Up @@ -51,6 +52,22 @@ test('escape character', () => {
expect(clean).not.toMatch('1')
})

test('regexp', () => {
const clean = emptyString(`
/'1\\'1'/
'1\\'1'
/"''''1''''"/
"''''1''''"
/'1'/ // '1'
/'1'/ /* '1' */
/'1'/ // '1'
/'1'/ /* '1' */
/'\\/1'/ // '1'
/'\\/1'/ /* '1' */
`)
expect(clean).not.toMatch('1')
})

test('strings comment nested', () => {
expect(
emptyString(`
Expand Down
6 changes: 4 additions & 2 deletions packages/vite/src/node/cleanString.ts
Expand Up @@ -2,8 +2,10 @@ import type { RollupError } from 'rollup'
// bank on the non-overlapping nature of regex matches and combine all filters into one giant regex
// /`([^`\$\{\}]|\$\{(`|\g<1>)*\})*`/g can match nested string template
// but js not support match expression(\g<0>). so clean string template(`...`) in other ways.
const cleanerRE =
/"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'|\/\*(.|[\r\n])*?\*\/|\/\/.*/g
const stringsRE = /"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'/
const commentsRE = /\/\*(.|[\r\n])*?\*\/|\/\/.*/
const regexpRE = /\/([^\/\r\n]|(?<=\\)\/)*\//
const cleanerRE = new RegExp(`${stringsRE}|${commentsRE}|${regexpRE}`, 'g')

const blankReplacer = (s: string) => ' '.repeat(s.length)
const stringBlankReplacer = (s: string) =>
Expand Down