import * as gcpMetadata from 'gcp-metadata' ; export enum GCPEnv { APP_ENGINE = 'APP_ENGINE' , KUBERNETES_ENGINE = 'KUBERNETES_ENGINE' , CLOUD_FUNCTIONS = 'CLOUD_FUNCTIONS' , COMPUTE_ENGINE = 'COMPUTE_ENGINE' , CLOUD_RUN = 'CLOUD_RUN' , NONE = 'NONE' } let envPromise ; export function clear ( ) { envPromise = undefined ; } export async function getEnv ( ) { if ( envPromise ) { return envPromise ; } envPromise = getEnvMemoized ( ) ; return envPromise ; } async function getEnvMemoized ( ) { let env = GCPEnv . NONE ; if ( isAppEngine ( ) ) { env = GCPEnv . APP_ENGINE ; } else if ( isCloudFunction ( ) ) { env = GCPEnv . CLOUD_FUNCTIONS ; } else if ( await isComputeEngine ( ) ) { if ( await isKubernetesEngine ( ) ) { env = GCPEnv . KUBERNETES_ENGINE ; } else if ( isCloudRun ( ) ) { env = GCPEnv . CLOUD_RUN ; } else { env = GCPEnv . COMPUTE_ENGINE ; } } else { env = GCPEnv . NONE ; } return env ; } function isAppEngine ( ) { return ! ! ( process . env . GAE_SERVICE || process . env . GAE_MODULE_NAME ) ; } function isCloudFunction ( ) { return ! ! ( process . env . FUNCTION_NAME || process . env . FUNCTION_TARGET ) ; } /**
 * This check only verifies that the environment is running knative.
 * This must be run *after* checking for Kubernetes, otherwise it will
 * return a false positive.
 */ function isCloudRun ( ) { return ! ! process . env . K_CONFIGURATION ; } async function isKubernetesEngine ( ) { try { await gcpMetadata . instance ( 'attributes/cluster-name' ) ; return true ; } catch ( e ) { return false ; } } async function isComputeEngine ( ) { return gcpMetadata . isAvailable ( ) ; }