import path from 'path' ; import fs from 'fs' ; import { workspace } from 'vscode' ; interface File { path : string ; contents : string ; } const isPortFile = ( file ) => { let hasListen = false ; let hasPort = false ; const LINES = file . contents . split ( '\n' ) ; for ( const LINE of LINES ) { if ( LINE . match ( /\.listen/i ) ) { hasListen = true ; } if ( LINE . match ( /port/i ) ) { hasPort = true ; } if ( hasListen && hasPort ) { break ; } } return hasListen && hasPort ; } ; const findPortFiles = ( codeFileContents ) => { const portFiles = [ ] ; for ( const codeFileContent of codeFileContents ) { if ( isPortFile ( codeFileContent ) ) { portFiles . push ( codeFileContent . path ) ; } } return portFiles ; } ; const readCodeFiles = ( codeFileNames ) => { const fileContents = [ ] ; for ( const file of codeFileNames ) { const data = fs . readFileSync ( file , { encoding : 'utf8' , flag : 'r' } ) ; fileContents . push ( { path : file , contents : data } ) ; } return fileContents ; } ; const findCodeFiles = ( dir ) => { if ( dir === undefined ) { return [ ] ; } const codeFiles = [ ] ; const dirContents = fs . readdirSync ( dir ) ; let files = dirContents . map ( ( content ) => { if ( [ 'node_modules' , 'dist' , 'out' , 'build' ] . includes ( content ) ) { return '' ; } const resource = path . resolve ( dir , content ) . replace ( /\\/g , '/' ) ; return fs . statSync ( resource ) . isDirectory ( ) ? findCodeFiles ( resource ) : resource ; } ) ; files = files . flat ( Infinity ) ; files . forEach ( ( file ) => { if ( file . match ( /.*\.(js|ts)$/ ) ) { codeFiles . push ( file ) ; } } ) ; return codeFiles ; } ; let pathStr = workspace . workspaceFolders ! [ 0 ] . uri . path ; if ( pathStr [ 2 ] === ':' ) pathStr = pathStr . slice ( 1 ) ; const codeFileNames = findCodeFiles ( pathStr ) ; const codeFileContents = readCodeFiles ( codeFileNames ) ; export default function getServerPaths ( ) { return findPortFiles ( codeFileContents ) ; }