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(html): handle offset magic-string slice error #15435

Merged
merged 1 commit into from Jan 1, 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
24 changes: 13 additions & 11 deletions packages/vite/src/node/plugins/html.ts
Expand Up @@ -345,18 +345,13 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
const nodeStartWithLeadingWhitespace = (
node: DefaultTreeAdapterMap['node'],
) => {
if (node.sourceCodeLocation!.startOffset === 0)
return node.sourceCodeLocation!.startOffset
const startOffset = node.sourceCodeLocation!.startOffset
if (startOffset === 0) return 0

// Gets the offset for the start of the line including the
// newline trailing the previous node
const lineStartOffset =
node.sourceCodeLocation!.startOffset -
node.sourceCodeLocation!.startCol
const line = s.slice(
Math.max(0, lineStartOffset),
node.sourceCodeLocation!.startOffset,
)
startOffset - node.sourceCodeLocation!.startCol

// <previous-line-node></previous-line-node>
// <target-node></target-node>
Expand All @@ -369,9 +364,16 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
//
// However, if there is content between our target node start and the
// previous newline, we cannot strip it out without risking content deletion.
return line.trim()
? node.sourceCodeLocation!.startOffset
: lineStartOffset
let isLineEmpty = false
try {
const line = s.slice(Math.max(0, lineStartOffset), startOffset)
isLineEmpty = !line.trim()
} catch {
// magic-string may throw if there's some content removed in the sliced string,
// which we ignore and assume the line is not empty
}

return isLineEmpty ? lineStartOffset : startOffset
}

// pre-transform
Expand Down
1 change: 1 addition & 0 deletions playground/html/vite.config.js
Expand Up @@ -39,6 +39,7 @@ export default defineConfig({
serveFolder: resolve(__dirname, 'serve/folder/index.html'),
serveBothFile: resolve(__dirname, 'serve/both.html'),
serveBothFolder: resolve(__dirname, 'serve/both/index.html'),
write: resolve(__dirname, 'write.html'),
},
},
},
Expand Down
3 changes: 3 additions & 0 deletions playground/html/write.html
@@ -0,0 +1,3 @@
<!-- prettier-ignore -->
<html><head><style>div {}
</style></head><body><script type="module" src="./shared.js"></script></body></html>