@@ -35,13 +35,17 @@ type ReadablePassthrough = {
3535 destroyed : boolean
3636}
3737
38- function createPassthrough ( ) {
38+ function createPassthrough ( onCancel ?: ( ) => void ) {
3939 let controller : ReadableStreamDefaultController < any >
4040 const encoder = new TextEncoder ( )
4141 const stream = new ReadableStream ( {
4242 start ( c ) {
4343 controller = c
4444 } ,
45+ cancel ( ) {
46+ res . destroyed = true
47+ onCancel ?.( )
48+ } ,
4549 } )
4650
4751 const res : ReadablePassthrough = {
@@ -96,7 +100,13 @@ export function transformStreamWithRouter(
96100 timeoutMs ?: number
97101 } ,
98102) {
99- const finalPassThrough = createPassthrough ( )
103+ let stopListeningToInjectedHtml : ( ( ) => void ) | undefined = undefined
104+ let timeoutHandle : NodeJS . Timeout
105+
106+ const finalPassThrough = createPassthrough ( ( ) => {
107+ stopListeningToInjectedHtml ?.( )
108+ clearTimeout ( timeoutHandle )
109+ } )
100110 const textDecoder = new TextDecoder ( )
101111
102112 let isAppRendering = true as boolean
@@ -105,7 +115,6 @@ export function transformStreamWithRouter(
105115 let streamBarrierLifted = false as boolean
106116 let leftover = ''
107117 let leftoverHtml = ''
108- let timeoutHandle : NodeJS . Timeout
109118
110119 function getBufferedRouterStream ( ) {
111120 const html = routerStreamBuffer
@@ -130,12 +139,9 @@ export function transformStreamWithRouter(
130139 } )
131140
132141 // Listen for any new injected HTML
133- const stopListeningToInjectedHtml = router . subscribe (
134- 'onInjectedHtml' ,
135- ( e ) => {
136- handleInjectedHtml ( e . promise )
137- } ,
138- )
142+ stopListeningToInjectedHtml = router . subscribe ( 'onInjectedHtml' , ( e ) => {
143+ handleInjectedHtml ( e . promise )
144+ } )
139145
140146 function handleInjectedHtml ( promise : Promise < string > ) {
141147 processingCount ++
@@ -170,7 +176,7 @@ export function transformStreamWithRouter(
170176 console . error ( 'Error reading routerStream:' , err )
171177 finalPassThrough . destroy ( err )
172178 } )
173- . finally ( stopListeningToInjectedHtml )
179+ . finally ( ( ) => stopListeningToInjectedHtml ?. ( ) )
174180
175181 // Transform the appStream
176182 readStream ( appStream , {
0 commit comments