import { Message , MessageRequester , Result } from "@keplr-wallet/router" ; import { JSONUint8Array } from "@keplr-wallet/router/build/json-uint8-array" ; import EventEmitter from "eventemitter3" ; import { RNRouterBackground , RNRouterUI } from "./rn-router" ; export class RNMessageRequesterBase implements MessageRequester { constructor ( protected readonly eventEmitter , protected readonly getSender = ( ) => { return { url : "react-native://internal" , origin : "react-native://internal" , } ; } ) { } async sendMessage < M extends Message < unknown > > ( port , msg ) { msg . validateBasic ( ) ; const sender = this . getSender ( ) ; msg [ "origin" ] = sender . origin ; if ( this . eventEmitter . listenerCount ( "message" ) === 0 ) { throw new Error ( "There is no router to send" ) ; } const result = JSONUint8Array . unwrap ( await new Promise ( ( resolve ) => { this . eventEmitter . emit ( "message" , { message : { port , type : msg . type ( ) , msg : JSONUint8Array . wrap ( msg ) , } , sender : { id : "react-native" , url : sender . url , resolver : resolve , } , } ) ; } ) ) ; if ( ! result ) { throw new Error ( "Null result" ) ; } if ( result . error ) { throw new Error ( result . error ) ; } return result . return ; } } export class RNMessageRequesterInternal extends RNMessageRequesterBase { constructor ( ) { super ( RNRouterBackground . EventEmitter ) ; } } export class RNMessageRequesterInternalToUI extends RNMessageRequesterBase { constructor ( ) { super ( RNRouterUI . EventEmitter ) ; } } export class RNMessageRequesterExternal extends RNMessageRequesterBase { constructor ( getSender ) { super ( RNRouterBackground . EventEmitter , getSender ) ; } }