Skip to content

Commit

Permalink
fix: avoid mangling code from incorrect magic-string usage (#7397)
Browse files Browse the repository at this point in the history
  • Loading branch information
benmccann authored Mar 21, 2022
1 parent d23f4ff commit 68d76c9
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 33 deletions.
2 changes: 1 addition & 1 deletion packages/vite/src/node/optimizer/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,7 @@ async function transformGlob(
resolve
)
s.prepend(importsString)
s.overwrite(expStart, endIndex, exp)
s.overwrite(expStart, endIndex, exp, { contentOnly: true })
}
return s.toString()
}
Expand Down
4 changes: 3 additions & 1 deletion packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
const file = getAssetFilename(hash, config) || this.getFileName(hash)
chunk.viteMetadata.importedAssets.add(cleanUrl(file))
const outputFilepath = config.base + file + postfix
s.overwrite(match.index, match.index + full.length, outputFilepath)
s.overwrite(match.index, match.index + full.length, outputFilepath, {
contentOnly: true
})
}

if (s) {
Expand Down
6 changes: 4 additions & 2 deletions packages/vite/src/node/plugins/assetImportMetaUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
index + exp.length,
`new URL(import.meta.globEagerDefault(${JSON.stringify(
pattern
)})[${rawUrl}], self.location)`
)})[${rawUrl}], self.location)`,
{ contentOnly: true }
)
continue
}
Expand All @@ -70,7 +71,8 @@ export function assetImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
s.overwrite(
index,
index + exp.length,
`new URL(${JSON.stringify(builtUrl)}, self.location)`
`new URL(${JSON.stringify(builtUrl)}, self.location)`,
{ contentOnly: true }
)
}
if (s) {
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ export function definePlugin(config: ResolvedConfig): Plugin {
const start = match.index
const end = start + match[0].length
const replacement = '' + replacements[match[1]]
s.overwrite(start, end, replacement)
s.overwrite(start, end, replacement, { contentOnly: true })
}

if (!hasReplaced) {
Expand Down
26 changes: 19 additions & 7 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,8 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
s.overwrite(
src!.value!.loc.start.offset,
src!.value!.loc.end.offset,
`"${config.base + url.slice(1)}"`
`"${config.base + url.slice(1)}"`,
{ contentOnly: true }
)
}

Expand Down Expand Up @@ -340,7 +341,8 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
s.overwrite(
p.value.loc.start.offset,
p.value.loc.end.offset,
`"${config.base + url.slice(1)}"`
`"${config.base + url.slice(1)}"`,
{ contentOnly: true }
)
}
}
Expand Down Expand Up @@ -370,7 +372,8 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
s.overwrite(
styleNode.loc.start.offset,
styleNode.loc.end.offset,
`"__VITE_INLINE_CSS__${cleanUrl(id)}_${inlineModuleIndex}__"`
`"__VITE_INLINE_CSS__${cleanUrl(id)}_${inlineModuleIndex}__"`,
{ contentOnly: true }
)
}

Expand Down Expand Up @@ -430,7 +433,8 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
s.overwrite(
value.loc.start.offset,
value.loc.end.offset,
`"${url}"`
`"${url}"`,
{ contentOnly: true }
)
} catch (e) {
if (e.code !== 'ENOENT') {
Expand All @@ -442,9 +446,16 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
// emit <script>import("./aaa")</script> asset
for (const { start, end, url } of scriptUrls) {
if (!isExcludedUrl(url)) {
s.overwrite(start, end, await urlToBuiltUrl(url, id, config, this))
s.overwrite(
start,
end,
await urlToBuiltUrl(url, id, config, this),
{ contentOnly: true }
)
} else if (checkPublicFile(url, config)) {
s.overwrite(start, end, config.base + url.slice(1))
s.overwrite(start, end, config.base + url.slice(1), {
contentOnly: true
})
}
}

Expand Down Expand Up @@ -599,7 +610,8 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
s.overwrite(
match.index,
match.index + full.length,
cssTransformedCode
cssTransformedCode,
{ contentOnly: true }
)
}
if (s) {
Expand Down
29 changes: 22 additions & 7 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
resolve
)
str().prepend(importsString)
str().overwrite(expStart, endIndex, exp)
str().overwrite(expStart, endIndex, exp, { contentOnly: true })
imports.forEach((url) => {
url = url.replace(base, '/')
importedUrls.add(url)
Expand Down Expand Up @@ -472,7 +472,8 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
str().overwrite(
expStart,
expEnd,
`import('${url}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))`
`import('${url}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))`,
{ contentOnly: true }
)
} else {
const exp = source.slice(expStart, expEnd)
Expand All @@ -483,17 +484,24 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
index
)
if (rewritten) {
str().overwrite(expStart, expEnd, rewritten)
str().overwrite(expStart, expEnd, rewritten, {
contentOnly: true
})
} else {
// #1439 export * from '...'
str().overwrite(start, end, url)
str().overwrite(start, end, url, { contentOnly: true })
}
}
rewriteDone = true
}
}
if (!rewriteDone) {
str().overwrite(start, end, isDynamicImport ? `'${url}'` : url)
str().overwrite(
start,
end,
isDynamicImport ? `'${url}'` : url,
{ contentOnly: true }
)
}
})
}
Expand Down Expand Up @@ -533,7 +541,12 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
isExplicitImportRequired(url.slice(1, -1))
) {
needQueryInjectHelper = true
str().overwrite(start, end, `__vite__injectQuery(${url}, 'import')`)
str().overwrite(
start,
end,
`__vite__injectQuery(${url}, 'import')`,
{ contentOnly: true }
)
}
}
}
Expand Down Expand Up @@ -589,7 +602,9 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
ssr
)
normalizedAcceptedUrls.add(normalized)
str().overwrite(start, end, JSON.stringify(normalized))
str().overwrite(start, end, JSON.stringify(normalized), {
contentOnly: true
})
}

// update the module graph for HMR analysis.
Expand Down
18 changes: 12 additions & 6 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
insertPreload
)
str().prepend(importsString)
str().overwrite(expStart, endIndex, exp)
str().overwrite(expStart, endIndex, exp, { contentOnly: true })
if (!isEager) {
needPreloadHelper = true
}
Expand All @@ -176,7 +176,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
needPreloadHelper = true
const original = source.slice(expStart, expEnd)
const replacement = `${preloadMethod}(() => ${original},${isModernFlag}?"${preloadMarker}":void 0)`
str().overwrite(expStart, expEnd, replacement)
str().overwrite(expStart, expEnd, replacement, { contentOnly: true })
}

// Differentiate CSS imports that use the default export from those that
Expand All @@ -191,7 +191,9 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
!(bareImportRE.test(specifier) && !specifier.includes('/'))
) {
const url = specifier.replace(/\?|$/, (m) => `?used${m ? '&' : ''}`)
str().overwrite(start, end, dynamicIndex > -1 ? `'${url}'` : url)
str().overwrite(start, end, dynamicIndex > -1 ? `'${url}'` : url, {
contentOnly: true
})
}
}

Expand Down Expand Up @@ -223,7 +225,8 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
s.overwrite(
match.index,
match.index + isModernFlag.length,
isModern
isModern,
{ contentOnly: true }
)
}
return {
Expand Down Expand Up @@ -303,7 +306,9 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
hasRemovedPureCssChunk = true
}

s.overwrite(expStart, expEnd, 'Promise.resolve({})')
s.overwrite(expStart, expEnd, 'Promise.resolve({})', {
contentOnly: true
})
}
}
}
Expand All @@ -330,7 +335,8 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
// main chunk is removed
(hasRemovedPureCssChunk && deps.size > 0)
? `[${[...deps].map((d) => JSON.stringify(d)).join(',')}]`
: `[]`
: `[]`,
{ contentOnly: true }
)
}
}
Expand Down
4 changes: 3 additions & 1 deletion packages/vite/src/node/plugins/workerImportMetaUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,9 @@ export function workerImportMetaUrlPlugin(config: ResolvedConfig): Plugin {
url = injectQuery(url, WORKER_FILE_ID)
url = injectQuery(url, `type=${workerType}`)
}
s.overwrite(urlIndex, urlIndex + exp.length, JSON.stringify(url))
s.overwrite(urlIndex, urlIndex + exp.length, JSON.stringify(url), {
contentOnly: true
})
}
if (s) {
return {
Expand Down
9 changes: 6 additions & 3 deletions packages/vite/src/node/server/middlewares/indexHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ const processNodeUrl = (
s.overwrite(
node.value!.loc.start.offset,
node.value!.loc.end.offset,
`"${config.base + url.slice(1)}"`
`"${config.base + url.slice(1)}"`,
{ contentOnly: true }
)
} else if (
url.startsWith('.') &&
Expand All @@ -82,7 +83,8 @@ const processNodeUrl = (
`"${path.posix.join(
path.posix.relative(originalUrl, '/'),
url.slice(1)
)}"`
)}"`,
{ contentOnly: true }
)
}
}
Expand Down Expand Up @@ -123,7 +125,8 @@ const devHtmlHook: IndexHtmlTransformHook = async (
s.overwrite(
node.loc.start.offset,
node.loc.end.offset,
`<script type="module" src="${modulePath}"></script>`
`<script type="module" src="${modulePath}"></script>`,
{ contentOnly: true }
)
}

Expand Down
11 changes: 7 additions & 4 deletions packages/vite/src/node/ssr/ssrTransform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,8 @@ export async function ssrTransform(
s.overwrite(
node.start,
node.start + 14 /* 'export default'.length */,
`${ssrModuleExportsKey}.default =`
`${ssrModuleExportsKey}.default =`,
{ contentOnly: true }
)
}
}
Expand Down Expand Up @@ -207,14 +208,16 @@ export async function ssrTransform(
s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`)
}
} else {
s.overwrite(id.start, id.end, binding)
s.overwrite(id.start, id.end, binding, { contentOnly: true })
}
},
onImportMeta(node) {
s.overwrite(node.start, node.end, ssrImportMetaKey)
s.overwrite(node.start, node.end, ssrImportMetaKey, { contentOnly: true })
},
onDynamicImport(node) {
s.overwrite(node.start, node.start + 6, ssrDynamicImportKey)
s.overwrite(node.start, node.start + 6, ssrDynamicImportKey, {
contentOnly: true
})
if (node.type === 'ImportExpression' && node.source.type === 'Literal') {
dynamicDeps.add(node.source.value as string)
}
Expand Down

0 comments on commit 68d76c9

Please sign in to comment.