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: encode path uri only #16212

Merged
merged 2 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
10 changes: 5 additions & 5 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import {
emptyDir,
joinUrlSegments,
normalizePath,
partialEncodeURI,
partialEncodeURIPath,
requireResolveFromRootWithFallback,
} from './utils'
import { manifestPlugin } from './plugins/manifest'
Expand Down Expand Up @@ -1093,7 +1093,7 @@ const getResolveUrl = (path: string, URL = 'URL') => `new ${URL}(${path}).href`

const getRelativeUrlFromDocument = (relativePath: string, umd = false) =>
getResolveUrl(
`'${escapeId(partialEncodeURI(relativePath))}', ${
`'${escapeId(partialEncodeURIPath(relativePath))}', ${
umd ? `typeof document === 'undefined' ? location.href : ` : ''
}document.currentScript && document.currentScript.src || document.baseURI`,
)
Expand All @@ -1120,13 +1120,13 @@ const relativeUrlMechanisms: Record<
)} : ${getRelativeUrlFromDocument(relativePath)})`,
es: (relativePath) =>
getResolveUrl(
`'${escapeId(partialEncodeURI(relativePath))}', import.meta.url`,
`'${escapeId(partialEncodeURIPath(relativePath))}', import.meta.url`,
),
iife: (relativePath) => getRelativeUrlFromDocument(relativePath),
// NOTE: make sure rollup generate `module` params
system: (relativePath) =>
getResolveUrl(
`'${escapeId(partialEncodeURI(relativePath))}', module.meta.url`,
`'${escapeId(partialEncodeURIPath(relativePath))}', module.meta.url`,
),
umd: (relativePath) =>
`(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(
Expand All @@ -1139,7 +1139,7 @@ const customRelativeUrlMechanisms = {
...relativeUrlMechanisms,
'worker-iife': (relativePath) =>
getResolveUrl(
`'${escapeId(partialEncodeURI(relativePath))}', self.location.href`,
`'${escapeId(partialEncodeURIPath(relativePath))}', self.location.href`,
),
} as const satisfies Record<string, (relativePath: string) => string>

Expand Down
7 changes: 4 additions & 3 deletions packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type { Plugin } from '../plugin'
import type { ResolvedConfig } from '../config'
import { checkPublicFile } from '../publicDir'
import {
encodeURIPath,
getHash,
injectQuery,
joinUrlSegments,
Expand Down Expand Up @@ -100,7 +101,7 @@ export function renderAssetUrlInJS(
)
const replacementString =
typeof replacement === 'string'
? JSON.stringify(encodeURI(replacement)).slice(1, -1)
? JSON.stringify(encodeURIPath(replacement)).slice(1, -1)
: `"+${replacement.runtime}+"`
s.update(match.index, match.index + full.length, replacementString)
}
Expand All @@ -123,7 +124,7 @@ export function renderAssetUrlInJS(
)
const replacementString =
typeof replacement === 'string'
? JSON.stringify(encodeURI(replacement)).slice(1, -1)
? JSON.stringify(encodeURIPath(replacement)).slice(1, -1)
: `"+${replacement.runtime}+"`
s.update(match.index, match.index + full.length, replacementString)
}
Expand Down Expand Up @@ -207,7 +208,7 @@ export function assetPlugin(config: ResolvedConfig): Plugin {

return {
code: `export default ${JSON.stringify(
url.startsWith('data:') ? url : encodeURI(url),
url.startsWith('data:') ? url : encodeURIPath(url),
)}`,
// Force rollup to keep this module from being shared between other entry points if it's an entrypoint.
// If the resulting chunk is empty, it will be removed in generateBundle.
Expand Down
7 changes: 4 additions & 3 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import {
combineSourcemaps,
createSerialPromiseQueue,
emptyCssComments,
encodeURIPath,
generateCodeFrame,
getHash,
getPackageManagerCommand,
Expand Down Expand Up @@ -593,7 +594,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
chunkCSS = chunkCSS.replace(assetUrlRE, (_, fileHash, postfix = '') => {
const filename = this.getFileName(fileHash) + postfix
chunk.viteMetadata!.importedAssets.add(cleanUrl(filename))
return encodeURI(
return encodeURIPath(
toOutputFilePathInCss(
filename,
'asset',
Expand All @@ -612,7 +613,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
)
chunkCSS = chunkCSS.replace(publicAssetUrlRE, (_, hash) => {
const publicUrl = publicAssetUrlMap.get(hash)!.slice(1)
return encodeURI(
return encodeURIPath(
toOutputFilePathInCss(
publicUrl,
'public',
Expand Down Expand Up @@ -715,7 +716,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
)
const replacementString =
typeof replacement === 'string'
? JSON.stringify(encodeURI(replacement)).slice(1, -1)
? JSON.stringify(encodeURIPath(replacement)).slice(1, -1)
: `"+${replacement.runtime}+"`
s.update(start, end, replacementString)
}
Expand Down
23 changes: 14 additions & 9 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ import { stripLiteral } from 'strip-literal'
import type { Plugin } from '../plugin'
import type { ViteDevServer } from '../server'
import {
encodeURIPath,
generateCodeFrame,
getHash,
isDataUrl,
isExternalUrl,
normalizePath,
partialEncodeURI,
partialEncodeURIPath,
processSrcSet,
removeLeadingSlash,
urlCanParse,
Expand Down Expand Up @@ -439,7 +440,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
overwriteAttrValue(
s,
sourceCodeLocation!,
partialEncodeURI(toOutputPublicFilePath(url)),
partialEncodeURIPath(toOutputPublicFilePath(url)),
)
}

Expand Down Expand Up @@ -498,7 +499,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
if (!isExcludedUrl(decodedUrl)) {
const result = await processAssetUrl(url)
return result !== decodedUrl
? encodeURI(result)
? encodeURIPath(result)
: url
}
return url
Expand All @@ -519,7 +520,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
overwriteAttrValue(
s,
getAttrSourceCodeLocation(node, attrKey),
partialEncodeURI(toOutputPublicFilePath(url)),
partialEncodeURIPath(toOutputPublicFilePath(url)),
)
} else if (!isExcludedUrl(url)) {
if (
Expand Down Expand Up @@ -563,7 +564,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
overwriteAttrValue(
s,
getAttrSourceCodeLocation(node, attrKey),
partialEncodeURI(processedUrl),
partialEncodeURIPath(processedUrl),
)
}
})(),
Expand Down Expand Up @@ -636,12 +637,16 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
// emit <script>import("./aaa")</script> asset
for (const { start, end, url } of scriptUrls) {
if (checkPublicFile(url, config)) {
s.update(start, end, partialEncodeURI(toOutputPublicFilePath(url)))
s.update(
start,
end,
partialEncodeURIPath(toOutputPublicFilePath(url)),
)
} else if (!isExcludedUrl(url)) {
s.update(
start,
end,
partialEncodeURI(await urlToBuiltUrl(url, id, config, this)),
partialEncodeURIPath(await urlToBuiltUrl(url, id, config, this)),
)
}
}
Expand Down Expand Up @@ -904,15 +909,15 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
if (chunk) {
chunk.viteMetadata!.importedAssets.add(cleanUrl(file))
}
return encodeURI(toOutputAssetFilePath(file)) + postfix
return encodeURIPath(toOutputAssetFilePath(file)) + postfix
})

result = result.replace(publicAssetUrlRE, (_, fileHash) => {
const publicAssetPath = toOutputPublicAssetFilePath(
getPublicAssetFilename(fileHash, config)!,
)

return encodeURI(
return encodeURIPath(
urlCanParse(publicAssetPath)
? publicAssetPath
: normalizePath(publicAssetPath),
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import {
joinUrlSegments,
moduleListContains,
normalizePath,
partialEncodeURI,
partialEncodeURIPath,
prettifyUrl,
removeImportQuery,
removeTimestampQuery,
Expand Down Expand Up @@ -594,7 +594,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
rewriteDone = true
}
if (!rewriteDone) {
const rewrittenUrl = JSON.stringify(partialEncodeURI(url))
const rewrittenUrl = JSON.stringify(partialEncodeURIPath(url))
const s = isDynamicImport ? start : start - 1
const e = isDynamicImport ? end : end + 1
str().overwrite(s, e, rewrittenUrl, {
Expand Down
10 changes: 8 additions & 2 deletions packages/vite/src/node/plugins/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import type { ViteDevServer } from '../server'
import { ENV_ENTRY, ENV_PUBLIC_PATH } from '../constants'
import { getHash, injectQuery, prettifyUrl, urlRE } from '../utils'
import {
encodeURIPath,
getHash,
injectQuery,
prettifyUrl,
urlRE,
} from '../utils'
import {
createToImportMetaURLBasedRelativeRuntime,
onRollupWarning,
Expand Down Expand Up @@ -411,7 +417,7 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
)
const replacementString =
typeof replacement === 'string'
? JSON.stringify(encodeURI(replacement)).slice(1, -1)
? JSON.stringify(encodeURIPath(replacement)).slice(1, -1)
: `"+${replacement.runtime}+"`
s.update(match.index, match.index + full.length, replacementString)
}
Expand Down
17 changes: 14 additions & 3 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1418,9 +1418,20 @@ export function displayTime(time: number): string {
}

/**
* Like `encodeURI`, but only replacing `%` as `%25`. This is useful for environments
* Encodes the URI path portion (ignores part after ? or #)
*/
export function encodeURIPath(uri: string): string {
const filePath = cleanUrl(uri)
const postfix = filePath !== uri ? uri.slice(filePath.length) : ''
return encodeURI(filePath) + postfix
}

/**
* Like `encodeURIPath`, but only replacing `%` as `%25`. This is useful for environments
* that can handle un-encoded URIs, where `%` is the only ambiguous character.
*/
export function partialEncodeURI(uri: string): string {
return uri.replaceAll('%', '%25')
export function partialEncodeURIPath(uri: string): string {
const filePath = cleanUrl(uri)
const postfix = filePath !== uri ? uri.slice(filePath.length) : ''
return filePath.replaceAll('%', '%25') + postfix
}