import { isPlainObject } from 'lodash' ; import { ReadStream } from 'fs' ; import { Zlib } from 'zlib' ; import { isBoom } from '@hapi/boom' ; import type { Request } from '@hapi/hapi' ; import { Logger } from '../../logging' ; type Response = Request [ 'response' ] ; const isBuffer = ( src , variety ) : src is Buffer => variety === 'buffer' && Buffer . isBuffer ( src ) ; const isFsReadStream = ( src , variety ) : src is ReadStream => { return variety === 'stream' && src instanceof ReadStream ; } ; const isZlibStream = ( src , variety ) : src is Zlib => { return variety === 'stream' && typeof src === 'object' && src !== null && 'bytesWritten' in src ; } ; const isString = ( src , variety ) : src is string => variety === 'plain' && typeof src === 'string' ; param response internal export function getResponsePayloadBytes ( response , log ) { try { const headers = isBoom ( response ) ? ( response . output . headers as Record < string , string | string [ ] > ) : response . headers ; const contentLength = headers && headers [ 'content-length' ] ; if ( contentLength ) { const val = parseInt ( Array . isArray ( contentLength ) ? String ( contentLength ) : contentLength , 10 ) ; return ! isNaN ( val ) ? val : undefined ; } if ( isBoom ( response ) ) { return Buffer . byteLength ( JSON . stringify ( response . output . payload ) ) ; } if ( isBuffer ( response . source , response . variety ) ) { return response . source . byteLength ; } if ( isFsReadStream ( response . source , response . variety ) ) { return response . source . bytesRead ; } if ( isZlibStream ( response . source , response . variety ) ) { return response . source . bytesWritten ; } if ( isString ( response . source , response . variety ) ) { return Buffer . byteLength ( response . source ) ; } if ( response . variety === 'plain' && ( isPlainObject ( response . source ) || Array . isArray ( response . source ) ) ) { return Buffer . byteLength ( JSON . stringify ( response . source ) ) ; } } catch ( e ) { log . warn ( 'Failed to calculate response payload bytes.' , e ) ; } return undefined ; }