import * as fs from 'fs' ; import logger from '@mds-core/mds-logger' ; import * as yargs from 'yargs' ; import { Policy , Geography , ComplianceResponse , VehicleEvent , Device } from '@mds-core/mds-types' ; import { validateEvents , validateGeographies , validatePolicies } from '@mds-core/mds-schema-validators' ; import { filterPolicies , processPolicy , filterEvents } from './mds-compliance-engine' ; const args = yargs . options ( 'geographies' , { alias : 'g' , demand : true , description : 'Path to geographies JSON' , type : 'string' } ) . option ( 'devices' , { alias : 'd' , demand : true , description : 'Path to devices JSON' , type : 'string' } ) . options ( 'events' , { alias : 'e' , demand : true , description : 'Path to events JSON' , type : 'string' } ) . option ( 'policies' , { alias : 'p' , demand : true , description : 'Path to policies JSON' , type : 'string' } ) . argv ; async function readJson ( path ) { return Promise . resolve ( JSON . parse ( fs . readFileSync ( path ) . toString ( ) ) ) ; } async function main ( ) { const geographies = ( await readJson ( args . geographies ) ) as Geography [ ] ; if ( ! geographies || ! validateGeographies ( geographies ) ) { logger . error ( 'unable to read geographies' ) ; process . exit ( 1 ) ; } const policies = ( await readJson ( args . policies ) ) as Policy [ ] ; if ( ! policies || ! validatePolicies ( policies ) ) { logger . error ( 'unable to read policies' ) ; process . exit ( 1 ) ; } const events = ( await readJson ( args . events ) ) as VehicleEvent [ ] ; if ( ! events || ! validateEvents ( events ) ) { logger . error ( 'unable to read events' ) ; process . exit ( 1 ) ; } const filteredEvents = filterEvents ( events ) ; const devices = ( ( await readJson ( args . devices ) ) as Device [ ] ) . reduce ( ( map , device ) => { return Object . assign ( map , { [ device . device_id ] : device } ) ; } , { } ) ; if ( ! devices ) { logger . error ( 'unable to read devices' ) ; process . exit ( 1 ) ; } const filteredPolicies = filterPolicies ( policies ) ; return Promise . resolve ( filteredPolicies . map ( ( policy ) => processPolicy ( policy , filteredEvents , geographies , devices ) ) ) ; } main ( ) . then ( result => { logger . info ( JSON . stringify ( result , undefined , 2 ) ) ; } , failure => { const reason = failure . slice && failure . slice ( 0 , 2 ) === '{"' ? JSON . parse ( failure ) : failure ; if ( reason . error_description ) { logger . info ( `${ reason . error_description } (${ reason . error })` ) ; } else if ( reason . result ) { logger . info ( reason . result ) ; } else { logger . info ( 'failure:' , reason ) ; } } ) . catch ( async ( err ) => { logger . error ( 'exception:' , err . stack ) ; } ) ;