import { TAuditReport , TFlags , TLockfileEntry , TLockfileObject , } from '../ifaces' ; import { formatFlags , formatYaml , invoke , mapFlags , parseYaml } from '../util' ; export const parse = ( raw ) : TLockfileObject => { const data = parseYaml ( raw ) ; delete data . __metadata ; return Object . entries ( data ) . reduce < Record < string , any > > ( ( m , [ key , value ] ) => { key . split ( ', ' ) . forEach ( ( k ) => { m [ k ] = value ; } ) ; return m ; } , { } ) ; } ; export const patchEntry = ( entry , name , newVersion , npmBin ) : TLockfileEntry => { entry . version = newVersion ; entry . resolution = `${ name }@npm:${ newVersion }` ; entry . dependencies = JSON . parse ( invoke ( npmBin , [ 'view' , `${ name }@${ newVersion }` , 'dependencies' , '--json' ] , process . cwd ( ) , true , false ) || 'null' ) || undefined ; delete entry . checksum ; return entry ; } ; export const format = ( lockfile ) : string => { const keymap = Object . entries ( lockfile ) . reduce < Record < string , any > > ( ( m , [ k , { resolution } ] ) => { const entry = m [ resolution ] || ( m [ resolution ] = [ ] ) ; entry . push ( k ) ; return m ; } , { } ) ; const data = Object . values ( lockfile ) . reduce < Record < string , any > > ( ( m , value ) => { const key = keymap [ value . resolution ] . join ( ', ' ) ; m [ key ] = value ; return m ; } , { __metadata : { version : 5 , cacheKey : 8 , } , } ) ; return `# This file is generated by running "yarn install" inside your project.
# Manual changes might be lost - proceed with caution!

${ formatYaml ( data , { quotingType : '"' , flowLevel : - 1 , lineWidth : - 1 , } ) . replace ( /\n([^\s"].+):\n/g , '\n"$1":\n' ) . replace ( /\n(\S)/g , '\n\n$1' ) . replace ( /resolution: ([^\n"]+)/g , 'resolution: "$1"' ) }` ; } ; export const audit = ( flags , temp , bins ) : TAuditReport => { const mapping = { 'audit-level' : 'severity' , level : 'severity' , groups : { key : 'environment' , values : { dependencies : 'production' , } , } , only : { key : 'environment' , values : { prod : 'production' , } , } , } ; const _flags = formatFlags ( mapFlags ( flags , mapping ) , 'groups' , 'verbose' ) ; const report = invoke ( bins . yarn , [ 'npm' , 'audit' , '--all' , '--json' , '--recursive' , ... _flags ] , temp , ! ! flags . silent , false , false ) ; return parseAuditReport ( report ) ; } ; export const parseAuditReport = ( data ) : TAuditReport => Object . values ( JSON . parse ( data ) . advisories ) . reduce < TAuditReport > ( ( m , { vulnerable_versions , module_name , patched_versions } ) => { m [ module_name ] = { patched_versions , vulnerable_versions , module_name , } ; return m ; } , { } ) ;