Skip to content

Commit 2c5f948

Browse files
fix: injectQuery double encoding (#18246)
Co-authored-by: mykwillis <myk@mykwillis.com>
1 parent 4389a91 commit 2c5f948

File tree

2 files changed

+16
-14
lines changed

2 files changed

+16
-14
lines changed

packages/vite/src/node/__tests__/utils.spec.ts

+6
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,12 @@ describe('injectQuery', () => {
113113
'/usr/vite/東京 %20 hello?direct',
114114
)
115115
})
116+
117+
test('path with url-encoded path as query parameter', () => {
118+
const src = '/src/module.ts?url=https%3A%2F%2Fusr.vite%2F'
119+
const expected = '/src/module.ts?t=1234&url=https%3A%2F%2Fusr.vite%2F'
120+
expect(injectQuery(src, 't=1234')).toEqual(expected)
121+
})
116122
})
117123

118124
describe('resolveHostname', () => {

packages/vite/src/node/utils.ts

+10-14
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,13 @@ import type MagicString from 'magic-string'
1919

2020
import type { TransformResult } from 'rollup'
2121
import { createFilter as _createFilter } from '@rollup/pluginutils'
22-
import { cleanUrl, isWindows, slash, withTrailingSlash } from '../shared/utils'
22+
import {
23+
cleanUrl,
24+
isWindows,
25+
slash,
26+
splitFileAndPostfix,
27+
withTrailingSlash,
28+
} from '../shared/utils'
2329
import { VALID_ID_PREFIX } from '../shared/constants'
2430
import {
2531
CLIENT_ENTRY,
@@ -311,20 +317,10 @@ export function removeRawQuery(url: string): string {
311317
return url.replace(rawRE, '$1').replace(trailingSeparatorRE, '')
312318
}
313319

314-
const replacePercentageRE = /%/g
315320
export function injectQuery(url: string, queryToInject: string): string {
316-
// encode percents for consistent behavior with pathToFileURL
317-
// see #2614 for details
318-
const resolvedUrl = new URL(
319-
url.replace(replacePercentageRE, '%25'),
320-
'relative:///',
321-
)
322-
const { search, hash } = resolvedUrl
323-
let pathname = cleanUrl(url)
324-
pathname = isWindows ? slash(pathname) : pathname
325-
return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${
326-
hash ?? ''
327-
}`
321+
const { file, postfix } = splitFileAndPostfix(url)
322+
const normalizedFile = isWindows ? slash(file) : file
323+
return `${normalizedFile}?${queryToInject}${postfix[0] === '?' ? `&${postfix.slice(1)}` : /* hash only */ postfix}`
328324
}
329325

330326
const timestampRE = /\bt=\d{13}&?\b/

0 commit comments

Comments
 (0)