import { ErrorWithCause } from '@sap-cloud-sdk/util' ; import { JwtPayload } from './jsonwebtoken-type' ; import { decodeJwt } from './jwt' ; import { CachingOptions } from './cache' ; import { clientCredentialsTokenCache } from './client-credentials-token-cache' ; import { getXsuaaServiceCredentials , resolveService } from './environment-accessor' ; import { Service , XsuaaServiceCredentials } from './environment-accessor-types' ; import { ResilienceOptions } from './resilience-options' ; import { replaceSubdomain } from './subdomain-replacer' ; import { getClientCredentialsToken , getUserToken } from './xsuaa-service' ; param service param options returns export async function serviceToken ( service , options ? ) { const opts = { useCache : true , enableCircuitBreaker : true , ... options } ; service = resolveService ( service ) ; const serviceCredentials = service . credentials ; const xsuaa = multiTenantXsuaaCredentials ( options ) ; if ( opts . useCache ) { const cachedToken = clientCredentialsTokenCache . getToken ( xsuaa . url , serviceCredentials . clientid ) ; if ( cachedToken ) { return cachedToken . access_token ; } } try { const token = await getClientCredentialsToken ( service , options ?. jwt , options ) ; if ( opts . useCache ) { clientCredentialsTokenCache . cacheToken ( xsuaa . url , serviceCredentials . clientid , token ) ; } return token . access_token ; } catch ( err ) { throw new ErrorWithCause ( `Could not fetch client credentials token for service of type "${ service . label }".` , err ) ; } } param jwt param service param options returns export async function jwtBearerToken ( jwt , service , options ? ) { const resolvedService = resolveService ( service ) ; const opts = { enableCircuitBreaker : true , ... options } ; return getUserToken ( resolvedService , jwt , opts ) ; } function multiTenantXsuaaCredentials ( options = { } ) { const xsuaa = options . xsuaaCredentials ? { ... options . xsuaaCredentials } : getXsuaaServiceCredentials ( options . jwt ) ; if ( options . jwt ) { const decodedJwt = typeof options . jwt === 'string' ? decodeJwt ( options . jwt ) : options . jwt ; if ( ! decodedJwt . iss ) { throw Error ( 'Property `iss` is missing in the provided user token.' ) ; } xsuaa . url = replaceSubdomain ( decodedJwt . iss , xsuaa . url ) ; } return xsuaa ; }