import Module , { MozJPEGModule } from './mozjpeg' ; import { defaultInputInfo , defaultEncodeOptions } from './options' ; import { InputInfo , EncodeOptions } from './types' ; import { isGrayscale , ColorSpace } from './colorspace' ; let mozjpeg ; const queue = [ ] ; /**
 * Initialize the mozjpeg module
 */ const initModule = ( ) : Promise < void > => { return new Promise ( ( resolve ) => { queue . push ( ( ) => { Module ( { onRuntimeInitialized : ( ) => { resolve ( ) ; } , } ) . then ( ( instance ) => { mozjpeg = instance ; } ) ; } ) ; if ( queue . length === 1 ) { queue [ 0 ] ( ) ; } } ) ; } ; /**
 * Resets the mozjpeg module to avoid some wasm related problems
 * when optimizing many images after each other
 */ const resetModule = ( ) : void => { mozjpeg = null ; if ( queue . length > 0 ) { queue . shift ( ) ; if ( queue . length > 0 ) { queue [ 0 ] ( ) ; } } } ; async param { Buffer } image param { InputInfo } inputInfo param { EncodeOptions } encodeOptions returns { Buffer } const encode = async ( image , inputInfo , encodeOptions = { } ) : Promise < Buffer > => { try { const filledInputInfo = { ... defaultInputInfo , ... inputInfo } ; const filledEncodeOptions = { ... defaultEncodeOptions , ... encodeOptions } ; if ( filledInputInfo . width < 1 || filledInputInfo . height < 1 ) { throw new Error ( `Invalid input image size: ${ filledInputInfo . width }x${ filledInputInfo . height }` ) ; } else if ( filledInputInfo . channels < 1 || filledInputInfo . channels > 4 ) { throw new Error ( `Invalid input channels: ${ filledInputInfo . channels }` ) ; } await initModule ( ) ; if ( ! mozjpeg ) { throw new Error ( 'MozJPEG Module could not be initialized' ) ; } if ( typeof encodeOptions . colorSpace === 'undefined' && ( inputInfo . channels === 1 || isGrayscale ( image , filledInputInfo . channels ) ) ) { filledEncodeOptions . colorSpace = ColorSpace . GRAYSCALE ; } const resultPointer = mozjpeg . encode ( image , filledInputInfo . width , filledInputInfo . height , filledInputInfo . channels , filledEncodeOptions ) ; const result = mozjpeg . getImage ( resultPointer ) ; mozjpeg . freeImage ( resultPointer ) ; return Buffer . from ( result ) ; } finally { resetModule ( ) ; } } ; export default encode ; export { ColorSpace } from './colorspace' ; export type { InputInfo , EncodeOptions } from './types' ; module . exports = encode ;