import type * as d from '../../declarations' ; import { getUsedSelectors , UsedSelectors } from '../style/css-parser/used-selectors' ; import { hasError , catchError } from '@utils' ; import { parseCss } from '../style/css-parser/parse-css' ; import { serializeCss } from '../style/css-parser/serialize-css' ; export const removeUnusedStyles = ( doc , diagnostics ) => { try { const styleElms = doc . head . querySelectorAll < HTMLStyleElement > ( `style[data-styles]` ) ; const styleLen = styleElms . length ; if ( styleLen > 0 ) { const usedSelectors = getUsedSelectors ( doc . documentElement ) ; for ( let i = 0 ; i < styleLen ; i ++ ) { removeUnusedStyleText ( usedSelectors , diagnostics , styleElms [ i ] ) ; } } } catch ( e ) { catchError ( diagnostics , e ) ; } } ; const removeUnusedStyleText = ( usedSelectors , diagnostics , styleElm ) => { try { const parseResults = parseCss ( styleElm . innerHTML ) ; diagnostics . push ( ... parseResults . diagnostics ) ; if ( hasError ( diagnostics ) ) { return ; } try { styleElm . innerHTML = serializeCss ( parseResults . stylesheet , { usedSelectors , } ) ; } catch ( e ) { diagnostics . push ( { level : 'warn' , type : 'css' , header : 'CSS Stringify' , messageText : e , } ) ; } } catch ( e ) { diagnostics . push ( { level : 'warn' , type : 'css' , header : 'CSS Parse' , messageText : e , } ) ; } } ;