import * as fs from 'fs' ; import * as _ from 'lodash' ; import { CommandInfo } from '../command' ; import { CommandParser } from './command-parser' ; /**
 * Finds wildcards in npm/yarn/pnpm run commands and replaces them with all matching scripts in the
 * `package.json` file of the current directory.
 */ export class ExpandNpmWildcard implements CommandParser { static readPackage ( ) { try { const json = fs . readFileSync ( 'package.json' , { encoding : 'utf-8' } ) ; return JSON . parse ( json ) ; } catch ( e ) { return { } ; } } private scripts ? : string [ ] ; constructor ( private readonly readPackage = ExpandNpmWildcard . readPackage ) { } parse ( commandInfo ) { const [ , npmCmd , cmdName , args ] = commandInfo . command . match ( /(npm|yarn|pnpm) run (\S+)([^&]*)/ ) || [ ] ; const wildcardPosition = ( cmdName || '' ) . indexOf ( '*' ) ; if ( ! cmdName || wildcardPosition === - 1 ) { return commandInfo ; } if ( ! this . scripts ) { this . scripts = Object . keys ( this . readPackage ( ) . scripts || { } ) ; } const preWildcard = _ . escapeRegExp ( cmdName . substr ( 0 , wildcardPosition ) ) ; const postWildcard = _ . escapeRegExp ( cmdName . substr ( wildcardPosition + 1 ) ) ; const wildcardRegex = new RegExp ( `^${ preWildcard }(.*?)${ postWildcard }$` ) ; const currentName = commandInfo . name || '' ; return this . scripts . map ( script => { const match = script . match ( wildcardRegex ) ; if ( match ) { return Object . assign ( { } , commandInfo , { command : `${ npmCmd } run ${ script }${ args }` , name : currentName + match [ 1 ] , } ) ; } } ) . filter ( ( commandInfo ) : commandInfo is CommandInfo => ! ! commandInfo ) ; } } ;