11cb0ef41Sopenharmony_ciconst assert = require('assert')
21cb0ef41Sopenharmony_ciconst {
31cb0ef41Sopenharmony_ci  ResponseStatusCodeError
41cb0ef41Sopenharmony_ci} = require('../core/errors')
51cb0ef41Sopenharmony_ciconst { toUSVString } = require('../core/util')
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ciasync function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
81cb0ef41Sopenharmony_ci  assert(body)
91cb0ef41Sopenharmony_ci
101cb0ef41Sopenharmony_ci  let chunks = []
111cb0ef41Sopenharmony_ci  let limit = 0
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_ci  for await (const chunk of body) {
141cb0ef41Sopenharmony_ci    chunks.push(chunk)
151cb0ef41Sopenharmony_ci    limit += chunk.length
161cb0ef41Sopenharmony_ci    if (limit > 128 * 1024) {
171cb0ef41Sopenharmony_ci      chunks = null
181cb0ef41Sopenharmony_ci      break
191cb0ef41Sopenharmony_ci    }
201cb0ef41Sopenharmony_ci  }
211cb0ef41Sopenharmony_ci
221cb0ef41Sopenharmony_ci  if (statusCode === 204 || !contentType || !chunks) {
231cb0ef41Sopenharmony_ci    process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
241cb0ef41Sopenharmony_ci    return
251cb0ef41Sopenharmony_ci  }
261cb0ef41Sopenharmony_ci
271cb0ef41Sopenharmony_ci  try {
281cb0ef41Sopenharmony_ci    if (contentType.startsWith('application/json')) {
291cb0ef41Sopenharmony_ci      const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))
301cb0ef41Sopenharmony_ci      process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
311cb0ef41Sopenharmony_ci      return
321cb0ef41Sopenharmony_ci    }
331cb0ef41Sopenharmony_ci
341cb0ef41Sopenharmony_ci    if (contentType.startsWith('text/')) {
351cb0ef41Sopenharmony_ci      const payload = toUSVString(Buffer.concat(chunks))
361cb0ef41Sopenharmony_ci      process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
371cb0ef41Sopenharmony_ci      return
381cb0ef41Sopenharmony_ci    }
391cb0ef41Sopenharmony_ci  } catch (err) {
401cb0ef41Sopenharmony_ci    // Process in a fallback if error
411cb0ef41Sopenharmony_ci  }
421cb0ef41Sopenharmony_ci
431cb0ef41Sopenharmony_ci  process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
441cb0ef41Sopenharmony_ci}
451cb0ef41Sopenharmony_ci
461cb0ef41Sopenharmony_cimodule.exports = { getResolveErrorBodyCallback }
47