@@ -10,6 +10,7 @@ const {
10
10
ObjectDefineProperty,
11
11
ObjectSetPrototypeOf,
12
12
ReflectApply,
13
+ SafeSet,
13
14
StringPrototypeSlice,
14
15
Symbol,
15
16
Uint8Array,
@@ -81,6 +82,7 @@ let HTTPParser;
81
82
const MAX_HANDLE_RETRANSMISSIONS = 3 ;
82
83
const kChannelHandle = Symbol ( 'kChannelHandle' ) ;
83
84
const kIsUsedAsStdio = Symbol ( 'kIsUsedAsStdio' ) ;
85
+ const kPendingMessages = Symbol ( 'pendingMessages' ) ;
84
86
85
87
// This object contain function to convert TCP objects to native handle objects
86
88
// and back again.
@@ -526,6 +528,7 @@ class Control extends EventEmitter {
526
528
constructor ( channel ) {
527
529
super ( ) ;
528
530
this . #channel = channel ;
531
+ this [ kPendingMessages ] = new SafeSet ( ) ;
529
532
}
530
533
531
534
// The methods keeping track of the counter are being used to track the
@@ -699,6 +702,19 @@ function setupChannel(target, channel, serializationMode) {
699
702
} ) ;
700
703
} ) ;
701
704
705
+ target . on ( 'newListener' , function ( ) {
706
+ if ( ! target . channel ) return ;
707
+
708
+ const messages = target . channel [ kPendingMessages ] ;
709
+ if ( ! messages . size ) return ;
710
+
711
+ for ( const messageParams of messages ) {
712
+ process . nextTick ( ( ) => ReflectApply ( target . emit , target , messageParams ) ) ;
713
+ }
714
+
715
+ messages . clear ( ) ;
716
+ } ) ;
717
+
702
718
target . send = function ( message , handle , options , callback ) {
703
719
if ( typeof handle === 'function' ) {
704
720
callback = handle ;
@@ -912,7 +928,14 @@ function setupChannel(target, channel, serializationMode) {
912
928
} ;
913
929
914
930
function emit ( event , message , handle ) {
915
- target . emit ( event , message , handle ) ;
931
+ const isInternalMessage = 'internalMessage' === event ;
932
+ const hasListenersInstalled = target . listenerCount ( 'message' ) ;
933
+ if ( hasListenersInstalled || isInternalMessage ) {
934
+ target . emit ( event , message , handle ) ;
935
+ return ;
936
+ }
937
+
938
+ target . channel [ kPendingMessages ] . add ( [ event , message , handle ] ) ;
916
939
}
917
940
918
941
function handleMessage ( message , handle , internal ) {
0 commit comments