const { Duplex } = require ( 'readable-stream' ) ; const { inherits } = require ( 'util' ) ; const noop = ( ) => undefined ; module . exports = MobilePortStream ; inherits ( MobilePortStream , Duplex ) ; class param { Object } port function MobilePortStream ( port ) { Duplex . call ( this , { objectMode : true } ) ; this . _name = port . name ; this . _targetWindow = window ; this . _port = port ; this . _origin = location . origin ; window . addEventListener ( 'message' , this . _onMessage . bind ( this ) , false ) ; } private param { Object } msg MobilePortStream . prototype . _onMessage = function ( event ) { const msg = event . data ; if ( this . _origin !== '*' && event . origin !== this . _origin ) { return ; } if ( ! msg || typeof msg !== 'object' ) { return ; } if ( ! msg . data || typeof msg . data !== 'object' ) { return ; } if ( msg . target && msg . target !== this . _name ) { return ; } if ( msg . data . data && msg . data . data . toNative ) { return ; } if ( Buffer . isBuffer ( msg ) ) { delete msg . _isBuffer ; const data = Buffer . from ( msg ) ; this . push ( data ) ; } else { this . push ( msg ) ; } } ; private MobilePortStream . prototype . _onDisconnect = function ( ) { this . destroy ( ) ; } ; /**
 * Explicitly sets read operations to a no-op
 */ MobilePortStream . prototype . _read = noop ; private param { * } msg param { string } encoding param { Function } cb MobilePortStream . prototype . _write = function ( msg , _encoding , cb ) { try { if ( Buffer . isBuffer ( msg ) ) { const data = msg . toJSON ( ) ; data . _isBuffer = true ; window . ReactNativeWebView . postMessage ( JSON . stringify ( { ... data , origin : window . location . href } ) ) ; } else { if ( msg . data ) { msg . data . toNative = true ; } window . ReactNativeWebView . postMessage ( JSON . stringify ( { ... msg , origin : window . location . href } ) ) ; } } catch ( err ) { return cb ( new Error ( 'MobilePortStream - disconnected' ) ) ; } return cb ( ) ; } ;