@@ -238,4 +238,81 @@ describe('SSE Streaming helper', () => {
238238 const decodedValue = decoder . decode ( value )
239239 expect ( decodedValue ) . toBe ( 'data: <div>Error</div>\n\n' )
240240 } )
241+
242+ it ( 'Check streamSSE handles \\r (CR) line ending correctly' , async ( ) => {
243+ const res = streamSSE ( c , async ( stream ) => {
244+ await stream . writeSSE ( {
245+ data : 'Line1\rLine2' ,
246+ event : 'test-cr' ,
247+ } )
248+ } )
249+
250+ if ( ! res . body ) {
251+ throw new Error ( 'Body is null' )
252+ }
253+ const reader = res . body . getReader ( )
254+ const decoder = new TextDecoder ( )
255+ const { value } = await reader . read ( )
256+ const decodedValue = decoder . decode ( value )
257+
258+ expect ( decodedValue ) . toBe ( 'event: test-cr\ndata: Line1\ndata: Line2\n\n' )
259+ } )
260+
261+ it ( 'Check streamSSE handles \\r\\n (CRLF) line ending correctly' , async ( ) => {
262+ const res = streamSSE ( c , async ( stream ) => {
263+ await stream . writeSSE ( {
264+ data : 'Line1\r\nLine2' ,
265+ event : 'test-crlf' ,
266+ } )
267+ } )
268+
269+ if ( ! res . body ) {
270+ throw new Error ( 'Body is null' )
271+ }
272+ const reader = res . body . getReader ( )
273+ const decoder = new TextDecoder ( )
274+ const { value } = await reader . read ( )
275+ const decodedValue = decoder . decode ( value )
276+
277+ expect ( decodedValue ) . toBe ( 'event: test-crlf\ndata: Line1\ndata: Line2\n\n' )
278+ } )
279+
280+ it ( 'Check streamSSE handles mixed line endings correctly' , async ( ) => {
281+ const res = streamSSE ( c , async ( stream ) => {
282+ await stream . writeSSE ( {
283+ data : 'A\nB\rC\r\nD' ,
284+ event : 'test-mixed' ,
285+ } )
286+ } )
287+
288+ if ( ! res . body ) {
289+ throw new Error ( 'Body is null' )
290+ }
291+ const reader = res . body . getReader ( )
292+ const decoder = new TextDecoder ( )
293+ const { value } = await reader . read ( )
294+ const decodedValue = decoder . decode ( value )
295+
296+ expect ( decodedValue ) . toBe ( 'event: test-mixed\ndata: A\ndata: B\ndata: C\ndata: D\n\n' )
297+ } )
298+
299+ it ( 'Check streamSSE handles consecutive \\r correctly' , async ( ) => {
300+ const res = streamSSE ( c , async ( stream ) => {
301+ await stream . writeSSE ( {
302+ data : 'Left\r\rRight' ,
303+ event : 'test-double-cr' ,
304+ } )
305+ } )
306+
307+ if ( ! res . body ) {
308+ throw new Error ( 'Body is null' )
309+ }
310+ const reader = res . body . getReader ( )
311+ const decoder = new TextDecoder ( )
312+ const { value } = await reader . read ( )
313+ const decodedValue = decoder . decode ( value )
314+
315+ // Two \r should produce an empty line in between
316+ expect ( decodedValue ) . toBe ( 'event: test-double-cr\ndata: Left\ndata: \ndata: Right\n\n' )
317+ } )
241318} )
0 commit comments