export interface Context { originalAddEventListener : typeof addEventListener ; messageCallbacks : any [ ] ; connected : boolean ; dappPort : MockMessagePort ; nodeProviderPort : MockMessagePort ; } export function createMockMessageEvent ( message , transferables ) { return { data : message , ports : transferables , type : "message" } ; } export function createMockMessageChannel ( ) { return { port1 : createMockMessagePort ( ) , port2 : createMockMessagePort ( ) } ; } export class MockMessagePort { height : number = 0 ; width : number = 0 ; private readonly onMessageCallback : Function [ ] = [ ] ; private readonly onMessageErrorCallback : Function [ ] = [ ] ; onMessage ( callback ) { this . onMessageCallback . push ( callback ) ; } onMessageError ( callback ) { this . onMessageErrorCallback . push ( callback ) ; } addEventListener ( event , callback ) { if ( event === "message" ) { this . onMessage ( callback ) ; } if ( event === "messageerror" ) { this . onMessageError ( callback ) ; } } postMessage ( message , transferables ) { this . onMessageCallback . forEach ( _ => createMockMessageEvent ( message , transferables ) ) ; } start ( ) { } close ( ) { } } export function createMockMessagePort ( ) { return new MockMessagePort ( ) ; } export function mockAddEventListenerFunction ( context ) { return ( eventName , callback ) => { if ( eventName !== "message" ) { context . originalAddEventListener ( eventName , callback ) ; return ; } context . messageCallbacks . push ( callback ) ; } ; } export function mockPostMessageFunction ( context ) { return ( message , target , transferables ) => { context . messageCallbacks . forEach ( callback => { callback ( createMockMessageEvent ( message , transferables ) ) ; } ) ; } ; }