import { Transform , TransformCallback } from 'stream' ; import rs from '../utilities/replacestream' ; interface GulpReplaceOptions { skipBinary ? : boolean ; } const defaultOptions = { skipBinary : true } ; function gulpReplace ( search , _replacement , options = { } ) { options = { ... defaultOptions , ... options } ; return new Transform ( { objectMode : true , param { import ( "vinyl" ) } file param { BufferEncoding } enc param { ( error ? : Error | null , data ? : any ) => void } callback transform : ( file , encoding , callback ) : void => { if ( file . isNull ( ) ) { return callback ( null , file ) ; } let replacement = _replacement ; if ( typeof _replacement === 'function' ) { replacement = _replacement . bind ( { file : file } ) ; } function doReplace ( ) { if ( file . isStream ( ) ) { file . contents = file . contents . pipe ( rs ( search , replacement ) ) ; return callback ( null , file ) ; } if ( file . isBuffer ( ) ) { const content = file . contents . toString ( ) ; if ( search instanceof RegExp ) { file . contents = Buffer . from ( content . replace ( search , replacement as string ) ) ; } else { const chunks = content . split ( search ) ; let result ; if ( typeof replacement === 'function' ) { result = [ chunks [ 0 ] ] ; for ( let i = 1 ; i < chunks . length ; i ++ ) { result . push ( replacement ( search ) ) ; result . push ( chunks [ i ] ) ; } result = result . join ( '' ) ; } else { result = chunks . join ( replacement ) ; } file . contents = Buffer . from ( result ) ; } return callback ( null , file ) ; } callback ( null , file ) ; } if ( options . skipBinary ) { const isNode16 = process . version . split ( '.' ) [ 0 ] === 'v16' ; if ( isNode16 ) { doReplace ( ) ; } else { if ( require ( 'istextorbinary' ) . isText ( file . path , file . contents ) ) { doReplace ( ) ; } else { callback ( null , file ) ; } } return ; } doReplace ( ) ; } } ) ; } export default gulpReplace ;