import { TransformCallback } from 'stream' ; import { BalmError } from '@balm-core/index' ; const PLUGIN_NAME = 'jsmin' ; async function jsMinify ( file , opts , cb ) { const terser = require ( 'terser' ) ; const extname = path . extname ( file . path ) ; if ( extname === '.js' ) { const code = { } ; let content = file . contents . toString ( ) ; code [ path . basename ( file . path ) ] = content ; try { const result = await terser . minify ( code , opts ) ; content = result . code ; file . contents = Buffer . from ( content ) ; cb ( null , file ) ; } catch ( e ) { const error = new PluginError ( PLUGIN_NAME , e as BalmError ) ; cb ( error ) ; } } else { BalmJS . logger . error ( PLUGIN_NAME , 'Invalid JS file' ) ; } return file ; } function gulpJsmin ( options ) { options = BalmJS . utils . deepMerge ( { } , options ) ; function transform ( this , chunk , encoding , callback ) { if ( chunk . isStream ( ) ) { return this . emit ( 'error' , new PluginError ( PLUGIN_NAME , 'Streams not supported' ) ) ; } if ( chunk . isNull ( ) ) { callback ( null , chunk ) ; return ; } jsMinify ( chunk , options , callback ) ; } return through2 . obj ( transform ) ; } export default gulpJsmin ;