import { UrbitVisorRequest , UrbitVisorEvent , UrbitVisorResponse , UrbitVisorState , UrbitVisorInternalComms } from "./types" ; const Messaging = { sendToPopup : async function ( message ) : Promise < void > { return new Promise ( ( res , rej ) => chrome . runtime . sendMessage ( message , ( response ) => res ( response ) ) ) ; } , sendToBackground : async function ( request ) : Promise < any > { return new Promise ( ( res , rej ) => chrome . runtime . sendMessage ( { ... request , app : "urbit-visor-internal" , } , ( response ) => res ( response ) ) ) ; } , relayToBackground : async function ( request ) : Promise < UrbitVisorResponse > { return new Promise ( ( res , rej ) => chrome . runtime . sendMessage ( request , ( response ) => res ( response ) ) ) ; } , pushEvent : function ( event , recipients ) { for ( let id of recipients ) { if ( typeof id == "number" ) chrome . tabs . sendMessage ( id , { app : "urbitVisorEvent" , event : event } ) ; if ( typeof id == "string" ) chrome . runtime . sendMessage ( id , { app : "urbitVisorEvent" , event : event } ) ; } } , callVisor : function ( { app , action , data } ) : Promise < UrbitVisorResponse > { return new Promise ( ( res , rej ) => { const requestId = Math . random ( ) . toString ( 36 ) . substr ( 2 , 9 ) ; window . addEventListener ( 'message' , function responseHandler ( e ) { const response = e . data ; if ( response . app !== "urbitVisorResponse" || response . id !== requestId ) return ; window . removeEventListener ( 'message' , responseHandler ) ; if ( response . error ) rej ( response . error ) ; else res ( response ) ; } ) ; window . postMessage ( { action , data , app , id : requestId } , window . origin ) ; } ) ; } , createProxyController : ( ) => { console . log ( "Urbit Visor present" ) ; window . addEventListener ( 'message' , async function ( e ) { const request = e . data ; if ( request && request . app !== "urbitVisor" ) return ; request . origin = e . origin ; Messaging . relayToBackground ( request ) . then ( ( response ) => { window . postMessage ( { app : "urbitVisorResponse" , id : request . id , status : response ?. status , response : response ?. response } , window . origin ) ; } ) ; return ; } ) ; chrome . runtime . onMessage . addListener ( ( request , sender , sendResponse ) => { if ( request . app == "urbitVisorEvent" ) { window . postMessage ( request , window . origin ) ; sendResponse ( "ok" ) ; } else sendResponse ( "ng" ) ; return true ; } ) ; } } ; export { Messaging } ;