@@ -22,7 +22,7 @@ export class WindowsScriptingHost extends EventEmitter {
2222 #trace;
2323 #finalizer = new FinalizationRegistry ( this . #finalized. bind ( this ) ) ;
2424 #ref2proxy = new Map ( ) ;
25- #proxy2ref = new Map ( ) ;
25+ #proxy2ref = new WeakMap ( ) ;
2626
2727 #objectHandler = {
2828
@@ -137,21 +137,24 @@ export class WindowsScriptingHost extends EventEmitter {
137137 }
138138
139139 #getOrCreate( ref , handler ) {
140- const existingProxy = this . #ref2proxy. get ( ref ) ;
140+ const existingWeakRef = this . #ref2proxy. get ( ref ) ;
141+ const existingProxy = existingWeakRef && existingWeakRef . deref ( ) ;
141142 if ( existingProxy )
142143 return existingProxy ;
143144
144145 const target = handler === this . #objectHandler? new RemoteObject ( ref ) : function ( ) { } ;
145146 const newProxy = new Proxy ( target , handler ) ;
146147 target [ PROXY ] = newProxy ;
147- this . #ref2proxy. set ( ref , newProxy ) ;
148+ this . #ref2proxy. set ( ref , new WeakRef ( newProxy ) ) ; // may be overwriting a dead WeakRef
148149 this . #proxy2ref. set ( newProxy , ref ) ;
149150 this . #finalizer. register ( newProxy , ref ) ;
150151 this . emit ( 'ref' , ref , newProxy ) ;
151152 return newProxy ;
152153 }
153154
154155 #finalized( ref ) {
156+ if ( this . #ref2proxy. get ( ref ) . deref ( ) === undefined ) // otherwise, it's overwritten by a refreshed proxy
157+ this . #ref2proxy. delete ( ref ) ;
155158 const output = this . #syncline. exchange ( JSON . stringify ( [ 'unref' , ref ] ) ) ;
156159 if ( this . #trace >= TRACE_REF )
157160 switch ( output [ 0 ] ) {
@@ -186,7 +189,7 @@ export class WindowsScriptingHost extends EventEmitter {
186189 }
187190 if ( decoded instanceof RemoteObject ) {
188191 const objref = this . #proxy2ref. get ( decoded ) ;
189- if ( objref === undefined )
192+ if ( objref === undefined ) // not because garbage-collected, because clearly `decoded` is still alive
190193 throw new Error ( `remote object reference not found: ${ decoded } ` ) ;
191194 return { type : 'objref' , value : objref } ;
192195 }
@@ -196,7 +199,7 @@ export class WindowsScriptingHost extends EventEmitter {
196199 return encoded ;
197200 case 'function' :
198201 const funref = this . #proxy2ref. get ( decoded ) ;
199- if ( funref === undefined )
202+ if ( funref === undefined ) // not because garbage-collected, because clearly `decoded` is still alive
200203 throw new Error ( `functions from node are disallowed: ${ decoded } ` ) ;
201204 return { type : 'funref' , value : funref } ;
202205 case 'bigint' :
0 commit comments