fix(core): avoid corrupting JSON strings in SSE whitespace normalization

Replace broad \s+} and \s+] regexes with a narrower pattern that only
strips whitespace before closing braces/brackets when preceded by a
JSON value terminator (", digit, ] or }). Prevents mangling string
values like "hello   }" which contain whitespace before braces.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Shaojin Wen 2026-03-14 17:46:54 +08:00
parent 1b651d5c4f
commit cf7204118f

View file

@ -111,10 +111,10 @@ export function parseAnthropicSseData(
//
// Try to fix by removing whitespace before } and ]
// Remove trailing whitespace before closing braces
normalizedData = normalizedData.replace(/\s+}/g, '}');
// Remove trailing whitespace before closing brackets
normalizedData = normalizedData.replace(/\s+]/g, ']');
// Remove trailing whitespace before closing braces/brackets, but only
// when preceded by a JSON value terminator (" or digit or ] or })
// to avoid corrupting whitespace inside string values like "hello }".
normalizedData = normalizedData.replace(/(["\d\]}])\s+([\]}])/g, '$1$2');
try {
return JSON.parse(normalizedData) as AnthropicStreamEvent;