interface IAction { channel : string ; data ? : any ; } type Handler = ( action : IAction ) => void ; const subscribers = new Map ( ) ; const pubsub = { publish ( action ) { if ( subscribers . has ( action . channel ) ) { const handlers = subscribers . get ( action . channel ) ! ; console . log ( `[PUBSUB] ${ action . channel }: ${ handlers . size } handlers` ) ; for ( const handler of handlers ) { handler ( action ) ; } } } , subscribe ( channel , handler ) { if ( ! subscribers . has ( channel ) ) { subscribers . set ( channel , new Set ( ) ) ; } subscribers . get ( channel ) ! . add ( handler ) ; } , unsubscribe ( channel , handler ) { if ( subscribers . has ( channel ) ) { const handlers = subscribers . get ( channel ) ! ; if ( handlers . has ( handler ) ) { handlers . delete ( handler ) ; } } } , } ; if ( navigator . serviceWorker ) { navigator . serviceWorker . addEventListener ( 'message' , ( event ) => { pubsub . publish ( event . data ) ; } ) ; } export default pubsub ;