UNPKG

@sap/cli-core

Version:

Command-Line Interface (CLI) Core Module

77 lines (76 loc) 2.93 kB
import axios from "axios"; import { getPackageName, getVersion } from "../../config/core.js"; import { get as getConfig, set as setConfig } from "../../config/index.js"; import { X_CSRF_TOKEN } from "../../constants.js"; import { get } from "../../logger/index.js"; import { logVerbose } from "../../logger/utils.js"; import { createHttpsAgent, getTlsVersion, isLegacyTlsDetectionEnabled, } from "./httpsAgent.js"; import { printCorrelationId, printError } from "./utils.js"; export const DEFAULTS = { maxBodyLength: -1, maxContentLength: -1, maxRedirects: 0, // must be set to 0 because maxBodyLength: -1 won't work otherwise, see github.com/axios/axios/issues/4263, }; const HEADERS_ETAG = "x-sap-cli-core-discovery-etag"; const getLogger = () => get("http"); const setEtag = (headers) => { const { debug } = getLogger(); if (headers?.[HEADERS_ETAG]) { setConfig({ etag: headers[HEADERS_ETAG] }); } else { debug("header %s is not available", HEADERS_ETAG); } }; const getCsrfTokenFromConfig = () => { const cnfg = getConfig(); return cnfg[X_CSRF_TOKEN] ? { [X_CSRF_TOKEN]: cnfg[X_CSRF_TOKEN] } : {}; }; export const fetch = async (config) => { const cnfg = getConfig(); const logger = getLogger(); const { debug, trace, error } = logger; try { logVerbose(logger, "%s %s", config.method.toUpperCase(), config.url); debug("http config: %s", JSON.stringify(config)); const HTTPS_PROXY = process.env.https_proxy ?? process.env.HTTPS_PROXY; const httpsAgent = createHttpsAgent(HTTPS_PROXY); if (HTTPS_PROXY) { logVerbose(logger, "using https proxy agent for https proxy"); debug(`using https proxy agent for https proxy ${HTTPS_PROXY}`); } else { debug("no https proxy defined via environment variable https_proxy"); } const tlsVersion = getTlsVersion(); const useLegacyTls = isLegacyTlsDetectionEnabled(); debug(`TLS configuration - version: ${tlsVersion}, legacy detection: ${useLegacyTls}`); const res = await axios({ httpsAgent, proxy: false, ...config, ...DEFAULTS, headers: { ...getCsrfTokenFromConfig(), ...config.headers, "User-Agent": `${getPackageName()}+${getVersion()}`, }, }); if (cnfg.verbose) { logVerbose(logger, "%d %s", res.status, res.statusText); printCorrelationId(res); } trace("response", res); setEtag(res.headers); return res; } catch (err) { error("error while executing http request", err.toString(), err.response); if (cnfg.verbose) { printError(err); printCorrelationId(err.response); } setEtag(err.response?.headers); throw err; } };