1+ function formatCloseValue ( value ) {
2+ if ( value === undefined || value === null ) {
3+ return "" ;
4+ }
5+ if ( typeof value === "string" ) {
6+ return value ;
7+ }
8+ if ( typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" ) {
9+ return value . toString ( ) ;
10+ }
11+ if ( value instanceof Uint8Array ) {
12+ return Buffer . from ( value ) . toString ( ) ;
13+ }
14+ return JSON . stringify ( value ) ?? "" ;
15+ }
16+
117export function waitForWebSocketOpen ( ws , timeoutMs , message = "ws open timeout" ) {
218 return new Promise ( ( resolve , reject ) => {
319 let settled = false ;
@@ -10,11 +26,19 @@ export function waitForWebSocketOpen(ws, timeoutMs, message = "ws open timeout")
1026 clearTimeout ( timer ) ;
1127 ws . off ?. ( "open" , onOpen ) ;
1228 ws . off ?. ( "error" , onError ) ;
29+ ws . off ?. ( "close" , onClose ) ;
1330 fn ( value ) ;
1431 } ;
1532 const onOpen = ( ) => settle ( resolve ) ;
1633 const onError = ( error ) =>
1734 settle ( reject , error instanceof Error ? error : new Error ( String ( error ) ) ) ;
35+ const onClose = ( code , reason ) => {
36+ const closeDetails = [ formatCloseValue ( code ) , formatCloseValue ( reason ) ]
37+ . filter ( Boolean )
38+ . join ( " " ) ;
39+ const suffix = closeDetails ? `: ${ closeDetails } ` : "" ;
40+ settle ( reject , new Error ( `closed before open${ suffix } ` ) ) ;
41+ } ;
1842 const timer = setTimeout ( ( ) => {
1943 const consumeAbortError = ( ) => { } ;
2044 const removeAbortErrorConsumer = ( ) => {
@@ -23,6 +47,7 @@ export function waitForWebSocketOpen(ws, timeoutMs, message = "ws open timeout")
2347 } ;
2448 try {
2549 ws . off ?. ( "error" , onError ) ;
50+ ws . off ?. ( "close" , onClose ) ;
2651 ws . on ?. ( "error" , consumeAbortError ) ;
2752 ws . once ?. ( "close" , removeAbortErrorConsumer ) ;
2853 ws . terminate ?. ( ) ;
@@ -37,5 +62,6 @@ export function waitForWebSocketOpen(ws, timeoutMs, message = "ws open timeout")
3762 timer . unref ?. ( ) ;
3863 ws . once ( "open" , onOpen ) ;
3964 ws . once ( "error" , onError ) ;
65+ ws . once ( "close" , onClose ) ;
4066 } ) ;
4167}
0 commit comments