Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions packages/vite/src/module-runner/evaluatedModules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,31 @@ export class EvaluatedModules {
if (!mod) return null
if (mod.map) return mod.map
if (!mod.meta || !('code' in mod.meta)) return null
const mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(
mod.meta.code,
)?.[1]

// Find the last occurrence of sourceMappingURL by finding the last line that contains it
const pattern = `//# ${SOURCEMAPPING_URL}=data:application/json;base64,`
const lastIndex = mod.meta.code.lastIndexOf(pattern)
if (lastIndex === -1) return null

// Extract the line containing the last occurrence
const codeFromLastMatch = mod.meta.code.substring(lastIndex)
const firstLineBreak = codeFromLastMatch.indexOf('\n')
const line =
firstLineBreak === -1
? codeFromLastMatch
: codeFromLastMatch.substring(0, firstLineBreak)

// Apply the original regex to just this line
const mapString = MODULE_RUNNER_SOURCEMAPPING_REGEXP.exec(line)?.[1]
if (!mapString) return null
mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), mod.file)
return mod.map

try {
mod.map = new DecodedMap(JSON.parse(decodeBase64(mapString)), mod.file)
return mod.map
} catch {
// Invalid base64 or malformed JSON - return null gracefully
return null
}
}

public clear(): void {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,29 @@ describe('module runner initialization', async () => {
' at Module.main (<root>/fixtures/has-error-deep.ts:6:3)',
])
})

it('should not crash when sourceMappingURL pattern appears in string literals', async ({
runner,
}) => {
// This test ensures that the ModuleRunner doesn't crash with InvalidCharacterError
// when source code contains string literals with sourceMappingURL pattern
const modules = runner.evaluatedModules

const moduleId = '/test/string-literal-sourcemap.js'
const moduleUrl = 'http://localhost:3000/test/string-literal-sourcemap.js'
const node = modules.ensureModule(moduleId, moduleUrl)

// This code pattern was causing crashes in issue #20551
node.meta = {
code: `const text = "//# sourceMappingURL=data:application/json;base64,invalidbase64";
console.log(text);`,
}

// Before the fix: This would throw InvalidCharacterError: Invalid character
// After the fix: This should not crash and should return null gracefully
expect(() => {
const sourceMap = modules.getModuleSourceMapById(moduleId)
expect(sourceMap).toBeNull()
}).not.toThrow()
})
})
Loading