import { Metadata } from "grpc" ; import { parse as parseUrl } from "url" ; import { HttpHeader } from "./types" ; import EnvoyContext from "./envoy-context" ; import EnvoyHttpRequestParams , { EnvoyHttpRequestInit } from "./envoy-http-request-params" ; import { Options , OptionsWithUrl , OptionsWithUri } from "request" ; param params param ctx param init export default function envoyRequestParamsRefiner ( params , ctx ? , init ? ) { if ( ! ctx ) { return typeof params === "string" ? { url : params } : params ; } let envoyContext ; if ( ctx instanceof EnvoyContext ) { envoyContext = ctx ; } else { envoyContext = new EnvoyContext ( ctx ) ; } const envoyParams = new EnvoyHttpRequestParams ( envoyContext , init ) ; let refinedParams ; if ( typeof params === "string" ) { refinedParams = { url : params } ; } else { refinedParams = { ... params } ; } const refinedParamsWithUrl = refinedParams as OptionsWithUrl ; const refinedParamsWithUri = refinedParams as OptionsWithUri ; if ( Object . prototype . hasOwnProperty . call ( refinedParams , "url" ) ) { refinedParamsWithUri . uri = refinedParamsWithUrl . url ; delete refinedParamsWithUrl . url ; } if ( ! refinedParamsWithUri . uri ) { throw new Error ( "Cannot read url from params" ) ; } if ( typeof refinedParamsWithUri . uri === "string" ) { refinedParamsWithUri . uri = parseUrl ( refinedParamsWithUri . uri ) ; } const { protocol , host , path } = refinedParamsWithUri . uri ; if ( ! protocol || ! host || ! path ) { throw new Error ( "Cannot read the URL for envoy to fetch" ) ; } const callDirectly = envoyParams . context . shouldCallWithoutEnvoy ( host ) ; if ( protocol !== "http:" && protocol !== "https:" ) { throw new Error ( `envoy request is designed only for http / https for now, current found: ${ protocol }` ) ; } const oldHeaders = { } ; Object . assign ( oldHeaders , refinedParamsWithUri . headers ) ; refinedParamsWithUri . headers = { ... oldHeaders , ... envoyParams . assembleRequestHeaders ( ) , host } ; if ( ! callDirectly ) { refinedParamsWithUri . uri = `http://${ envoyParams . context . envoyEgressAddr }:${ envoyParams . context . envoyEgressPort }${ path }` ; } return refinedParams ; }