import { DocumentContext } from 'vscode-css-languageservice' ; import { endsWith , startsWith } from '../utils/strings' ; import * as url from 'url' ; import { WorkspaceFolder } from 'vscode-languageserver' ; import { URI } from 'vscode-uri' ; import { join , dirname } from 'path' ; import { existsSync } from 'fs' ; function getModuleNameFromPath ( path ) { if ( path [ 0 ] === '@' ) { return path . substring ( 0 , path . indexOf ( '/' , path . indexOf ( '/' ) + 1 ) ) ; } return path . substring ( 0 , path . indexOf ( '/' ) ) ; } function resolvePathToModule ( _moduleName , _relativeTo ) { const documentFolder = dirname ( URI . parse ( _relativeTo ) . fsPath ) ; const packPath = join ( documentFolder , 'node_modules' , _moduleName , 'package.json' ) ; if ( existsSync ( packPath ) ) { return URI . file ( packPath ) . toString ( ) ; } return undefined ; } export function getDocumentContext ( documentUri , workspaceFolders ) { function getRootFolder ( ) { for ( let folder of workspaceFolders ) { let folderURI = folder . uri ; if ( ! endsWith ( folderURI , '/' ) ) { folderURI = folderURI + '/' ; } if ( startsWith ( documentUri , folderURI ) ) { return folderURI ; } } return undefined ; } return { resolveReference : ( ref , base = documentUri ) => { if ( ref [ 0 ] === '/' ) { if ( startsWith ( base , 'file://' ) ) { let folderUri = getRootFolder ( ) ; if ( folderUri ) { return folderUri + ref . substr ( 1 ) ; } } } if ( ref [ 0 ] === '~' && ref [ 1 ] !== '/' ) { ref = ref . substring ( 1 ) ; if ( startsWith ( base , 'file://' ) ) { const moduleName = getModuleNameFromPath ( ref ) ; const modulePath = resolvePathToModule ( moduleName , base ) ; if ( modulePath ) { const pathWithinModule = ref . substring ( moduleName . length + 1 ) ; return url . resolve ( modulePath , pathWithinModule ) ; } } } return url . resolve ( base , ref ) ; } , } ; }