import { browser , Runtime } from "webextension-polyfill-ts" ; import { DisconnectMessage , Message } from "../types" ; import { PANEL_SOURCE , PORT_NAME , BACKGROUND_SOURCE , RUNTIME_SOURCE , } from "../constants" ; import { createLogger } from "../logger" ; import { PortController } from "@devtools-ds/port-controller" ; const controller = new PortController < Message > ( ) ; const logger = createLogger ( BACKGROUND_SOURCE ) ; browser . runtime . onConnect . addListener ( function ( port ) { if ( port . name === PORT_NAME ) { const panelListener = function ( message ) { if ( message . type === "connect" && message . tabId ) { controller . connect ( message . tabId , port ) ; } controller . toContent ( message . tabId , message ) ; } ; port . onMessage . addListener ( panelListener ) ; port . onDisconnect . addListener ( function ( p ) { const message = { type : "disconnect" , source : PANEL_SOURCE , tabId : 0 , } ; controller . disconnect ( p , message ) ; } ) ; } } ) ; browser . runtime . onMessage . addListener ( function ( message , sender ) { if ( sender . tab && message . source === RUNTIME_SOURCE ) { const tabId = sender . tab . id ; if ( tabId ) controller . toPanel ( tabId , message ) ; } else { logger . log ( "Could not pass message, sender.tab not defined." , message ) ; } } ) ;