import { Instruction , Device , ConnEvent } from './types' ; import { Subscription } from 'rxjs' ; const isNodeEnvironment = typeof module !== 'undefined' && this . module !== module ; let transportNodeHid ; let outResolve ; const isImported = new Promise ( async ( resolve , reject ) => { outResolve = resolve ; } ) ; if ( isNodeEnvironment ) { import ( '@ledgerhq/hw-transport-node-hid' ) . then ( module => { transportNodeHid = module . default ; outResolve ( ) ; } ) ; } else { throw new Error ( 'Not running in Node environment. This is not supported in the browser.' ) ; } export async function sendApduMsg ( cla , errorHandler , responseHandler , ins , data = Buffer . alloc ( 0 ) , p1 = 0 , p2 = 0 ) { const device = await openConnection ( ) ; if ( cla > 255 || ins > 255 || p1 > 255 || p2 > 255 ) { throw new Error ( `Parameter validation for ADPU message failed. 
                 Too many bytes given in one or several params.` ) ; } try { return responseHandler ( await device . send ( cla , ins , p1 , p2 , data ) ) ; } catch ( e ) { if ( ! e . statusCode ) { throw e ; } throw errorHandler ( e . statusCode ) ; } } export async function subscribeDeviceConnection ( next ) { await isImported ; return transportNodeHid . listen ( { next : async ( obj ) => { switch ( obj . type ) { case 'add' : next ( true ) ; break ; case 'remove' : next ( false ) ; break ; } } , } ) ; } async function openConnection ( ) { await isImported ; const devices = await transportNodeHid . list ( ) ; if ( ! devices [ 0 ] ) { throw new Error ( 'No device found.' ) ; } return transportNodeHid . open ( devices [ 0 ] ) ; }