Skip to content

Commit

Permalink
fix(html): handle offset magic-string slice error (#15435)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Jan 1, 2024
1 parent 49d21fe commit 5ea9edb
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 11 deletions.
24 changes: 13 additions & 11 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<!-- prettier-ignore -->
<html><head><style>div {}
</style></head><body><script type="module" src="./shared.js"></script></body></html>

0 comments on commit 5ea9edb

Please sign in to comment.