UNPKG

purecloud-platform-client-v2

Version:

A JavaScript library to interface with the PureCloud Platform API

1 lines 1.23 MB
define(["axios","qs"],function(e,i){"use strict";function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=t(e),a=t(i),o={us_east_1:"mypurecloud.com",eu_west_1:"mypurecloud.ie",ap_southeast_2:"mypurecloud.com.au",ap_northeast_1:"mypurecloud.jp",eu_central_1:"mypurecloud.de",us_west_2:"usw2.pure.cloud",ca_central_1:"cac1.pure.cloud",ap_northeast_2:"apne2.pure.cloud",eu_west_2:"euw2.pure.cloud",ap_south_1:"aps1.pure.cloud",us_east_2:"use2.us-gov-pure.cloud",sa_east_1:"sae1.pure.cloud",me_central_1:"mec1.pure.cloud",ap_northeast_3:"apne3.pure.cloud",eu_central_2:"euc2.pure.cloud"};class r{constructor(){this.timeout=16e3}setTimeout(e){if(null===e||void 0===e||"number"!=typeof e)throw new Error("The 'timeout' property must be a number");this.timeout=e}setHttpsAgent(e){if(e&&"object"!=typeof e)throw new Error("The 'httpsAgent' property must be an object");this.httpsAgent=e}request(e){throw new Error("method must be implemented")}enableHooks(){throw new Error("method must be implemented")}setPreHook(e){if("function"!=typeof e||1!==e.length)throw new Error("preHook must be a function that accepts (config)");this.preHook=e,this.enableHooks()}setPostHook(e){if("function"!=typeof e||1!==e.length)throw new Error("postHook must be a function that accepts (response)");this.postHook=e,this.enableHooks()}}class s{constructor(e,i,t,n,a,o){this.setUrl(e),this.setMethod(i),t&&this.setHeaders(t),n&&this.setParams(n),a&&this.setData(a),null!==o&&void 0!==o?this.setTimeout(o):this.timeout=16e3}setUrl(e){if(!e)throw new Error("The 'url' property is required");this.url=e}setMethod(e){if(!e||!["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"].includes(e.toUpperCase()))throw new Error("The 'method' property is invalid or missing");this.method=e.toUpperCase()}setData(e){if(void 0===e||null===e)throw new Error("The 'data' property is required");this.data=e}setParams(e){if(e&&"object"!=typeof e)throw new Error("The 'params' property must be an object");this.params=e}setHeaders(e){if(e&&"object"!=typeof e)throw new Error("The 'headers' property must be an object");this.headers=e}setTimeout(e){if(void 0===e||null===e||"number"!=typeof e)throw new Error("The 'timeout' property must be a number");this.timeout=e}}class l extends r{constructor(e,i){super(),null!==e&&void 0!==e?this.setTimeout(e):this.timeout=16e3,null!==i&&void 0!==i?this.setHttpsAgent(i):this.httpsAgent,this._axiosInstance=n.default.create({})}enableHooks(){this.preHook&&"function"==typeof this.preHook&&(void 0!==this.requestInterceptorId&&n.default.interceptors.request.eject(this.requestInterceptorId),this.requestInterceptorId=this._axiosInstance.interceptors.request.use(async e=>e=await this.preHook(e),e=>(console.error("Request Pre-Hook Error:",e.message),Promise.reject(e)))),this.postHook&&"function"==typeof this.postHook&&(void 0!==this.responseInterceptorId&&n.default.interceptors.response.eject(this.responseInterceptorId),this.responseInterceptorId=this._axiosInstance.interceptors.response.use(async e=>e=await this.postHook(e),async e=>(console.error("Post-Hook: Response Error",e.message),Promise.reject(e))))}request(e){if(!(e instanceof s))throw new Error("httpRequestOptions must be instance of HttpRequestOptions ");const i=this.toAxiosConfig(e);return this._axiosInstance.request(i)}toAxiosConfig(e){if(!e.url||!e.method)throw new Error("Mandatory fields 'url' and 'method' must be set before making a request");var i={url:e.url,method:e.method};return e.params&&(i.params=e.params),e.headers&&(i.headers=e.headers),e.data&&(i.data=e.data),null!=this.timeout&&void 0!=this.timeout&&(i.timeout=this.timeout),this.httpsAgent&&(i.httpsAgent=this.httpsAgent),i}}const p={levels:{none:0,error:1,debug:2,trace:3}},u={level:{LNone:"none",LError:"error",LDebug:"debug",LTrace:"trace"}},d={formats:{JSON:"json",TEXT:"text"}};class c{get logLevelEnum(){return u}get logFormatEnum(){return d}constructor(){this.log_level=u.level.LNone,this.log_format=d.formats.TEXT,this.log_to_console=!0,this.log_file_path,this.log_response_body=!1,this.log_request_body=!1,this.setLogger()}setLogger(){if("undefined"==typeof window){const e=require("winston");this.logger=e.createLogger({levels:p.levels,level:this.log_level}),this.log_file_path&&""!==this.log_file_path&&(this.log_format===d.formats.JSON?this.logger.add(new e.transports.File({format:e.format.json(),filename:this.log_file_path})):this.logger.add(new e.transports.File({format:e.format.combine(e.format(e=>(e.level=e.level.toUpperCase(),e))(),e.format.simple()),filename:this.log_file_path}))),this.log_to_console&&(this.log_format===d.formats.JSON?this.logger.add(new e.transports.Console({format:e.format.json()})):this.logger.add(new e.transports.Console({format:e.format.combine(e.format(e=>(e.level=e.level.toUpperCase(),e))(),e.format.simple())})))}}log(e,i,t,n,a,o,r,s){var l=this.formatLog(e,i,t,n,a,o,r,s);"undefined"!=typeof window?this.calculateLogLevel(e)>0&&!0===this.log_to_console&&(this.log_format===this.logFormatEnum.formats.JSON?console.log(l):console.log(`${e.toUpperCase()}: ${l}`)):this.logger.transports.length>0&&this.logger.log(e,l)}calculateLogLevel(e){switch(this.log_level){case this.logLevelEnum.level.LError:return e!==this.logLevelEnum.level.LError?-1:1;case this.logLevelEnum.level.LDebug:return e===this.logLevelEnum.level.LTrace?-1:1;case this.logLevelEnum.level.LTrace:return 1;default:return-1}}formatLog(e,i,t,n,a,o,r,s){var l,p=a?JSON.parse(JSON.stringify(a)):null,u=o?JSON.parse(JSON.stringify(o)):null,c=r?JSON.parse(JSON.stringify(r)):null,g=s?JSON.parse(JSON.stringify(s)):null;return a&&(p.Authorization="[REDACTED]"),this.log_request_body||(c=void 0),this.log_response_body||(g=void 0),this.log_format&&this.log_format===d.formats.JSON?(l={level:e,date:(new Date).toISOString(),method:t,url:decodeURIComponent(n),correlationId:u&&u["inin-correlation-id"]?u["inin-correlation-id"]:"",statusCode:i},p&&(l.requestHeaders=p),u&&(l.responseHeaders=u),c&&(l.requestBody=c),g&&(l.responseBody=g)):l=`${(new Date).toISOString()}\n=== REQUEST === \n${this.formatValue("URL",decodeURIComponent(n))}${this.formatValue("Method",t)}${this.formatValue("Headers",this.formatHeaderString(p))}${this.formatValue("Body",c?JSON.stringify(c,null,2):"")}\n=== RESPONSE ===\n${this.formatValue("Status",i)}${this.formatValue("Headers",this.formatHeaderString(u))}${this.formatValue("CorrelationId",u&&u["inin-correlation-id"]?u["inin-correlation-id"]:"")}${this.formatValue("Body",g?JSON.stringify(g,null,2):"")}`,l}formatHeaderString(e){var i="";if(!e)return i;for(const[t,n]of Object.entries(e))i+=`\n\t${t}: ${n}`;return i}formatValue(e,i){return i&&""!==i&&"{}"!==i?`${e}: ${i}\n`:""}getLogLevel(e){switch(e){case"error":return u.level.LError;case"debug":return u.level.LDebug;case"trace":return u.level.LTrace;default:return u.level.LNone}}getLogFormat(e){switch(e){case"json":return d.formats.JSON;default:return d.formats.TEXT}}}class g{get instance(){return g.instance}set instance(e){g.instance=e}constructor(){if(g.instance||(g.instance=this),"undefined"!=typeof window)this.configPath="";else{const e=require("os"),i=require("path");this.configPath=i.join(e.homedir(),".genesyscloudjavascript","config")}this.refresh_access_token=!0,this.refresh_token_wait_max=10,this.live_reload_config=!0,this.host,this.environment,this.basePath,this.authUrl,this.config,this.gateway=void 0,this.logger=new c,this.setEnvironment(),this.liveLoadConfig()}liveLoadConfig(){if("undefined"!=typeof window)this.configPath="";else if(this.updateConfigFromFile(),this.live_reload_config&&!0===this.live_reload_config)try{const e=require("fs");e.watchFile(this.configPath,{persistent:!1},(i,t)=>{this.updateConfigFromFile(),this.live_reload_config||e.unwatchFile(this.configPath)})}catch(e){}}setConfigPath(e){e&&e!==this.configPath&&(this.configPath=e,this.liveLoadConfig())}updateConfigFromFile(){if("undefined"==typeof window){const t=require("configparser");try{var e=new t;e.read(this.configPath),this.config=e}catch(e){if(e.name&&"MissingSectionHeaderError"===e.name){var i=require("fs").readFileSync(this.configPath,"utf8");this.config={_sections:JSON.parse(i)}}}this.config&&this.updateConfigValues()}}updateConfigValues(){if(this.logger.log_level=this.logger.getLogLevel(this.getConfigString("logging","log_level")),this.logger.log_format=this.logger.getLogFormat(this.getConfigString("logging","log_format")),this.logger.log_to_console=void 0!==this.getConfigBoolean("logging","log_to_console")?this.getConfigBoolean("logging","log_to_console"):this.logger.log_to_console,this.logger.log_file_path=void 0!==this.getConfigString("logging","log_file_path")?this.getConfigString("logging","log_file_path"):this.logger.log_file_path,this.logger.log_response_body=void 0!==this.getConfigBoolean("logging","log_response_body")?this.getConfigBoolean("logging","log_response_body"):this.logger.log_response_body,this.logger.log_request_body=void 0!==this.getConfigBoolean("logging","log_request_body")?this.getConfigBoolean("logging","log_request_body"):this.logger.log_request_body,this.refresh_access_token=void 0!==this.getConfigBoolean("reauthentication","refresh_access_token")?this.getConfigBoolean("reauthentication","refresh_access_token"):this.refresh_access_token,this.refresh_token_wait_max=void 0!==this.getConfigInt("reauthentication","refresh_token_wait_max")?this.getConfigInt("reauthentication","refresh_token_wait_max"):this.refresh_token_wait_max,this.live_reload_config=void 0!==this.getConfigBoolean("general","live_reload_config")?this.getConfigBoolean("general","live_reload_config"):this.live_reload_config,this.host=void 0!==this.getConfigString("general","host")?this.getConfigString("general","host"):this.host,void 0!==this.getConfigString("gateway","host")){let e={host:this.getConfigString("gateway","host")};void 0!==this.getConfigString("gateway","protocol")&&(e.protocol=this.getConfigString("gateway","protocol")),void 0!==this.getConfigInt("gateway","port")&&(e.port=this.getConfigInt("gateway","port")),void 0!==this.getConfigString("gateway","path_params_login")&&(e.path_params_login=this.getConfigString("gateway","path_params_login")),void 0!==this.getConfigString("gateway","path_params_api")&&(e.path_params_api=this.getConfigString("gateway","path_params_api")),void 0!==this.getConfigString("gateway","username")&&(e.username=this.getConfigString("gateway","username")),void 0!==this.getConfigString("gateway","password")&&(e.password=this.getConfigString("gateway","password")),this.setGateway(e)}else this.setGateway();this.setEnvironment(),this.logger.setLogger()}setGateway(e){e?(this.gateway={host:""},e.protocol?this.gateway.protocol=e.protocol:this.gateway.protocol="https",e.host?this.gateway.host=e.host:this.gateway.host="",e.port&&e.port>-1?this.gateway.port=e.port:this.gateway.port=-1,e.path_params_login?(this.gateway.path_params_login=e.path_params_login,this.gateway.path_params_login=this.gateway.path_params_login.replace(/\/+$/,"")):this.gateway.path_params_login="",e.path_params_api?(this.gateway.path_params_api=e.path_params_api,this.gateway.path_params_api=this.gateway.path_params_api.replace(/\/+$/,"")):this.gateway.path_params_api="",e.username&&(this.gateway.username=e.username),e.password&&(this.gateway.password=e.password)):this.gateway=void 0}setEnvironment(e){this.environment=e||(this.host?this.host:"mypurecloud.com"),this.environment=this.environment.replace(/\/+$/,""),this.environment.startsWith("https://")&&(this.environment=this.environment.substring(8)),this.environment.startsWith("http://")&&(this.environment=this.environment.substring(7)),this.environment.startsWith("api.")&&(this.environment=this.environment.substring(4)),this.basePath=`https://api.${this.environment}`,this.authUrl=`https://login.${this.environment}`}getConfUrl(e,i){if(!this.gateway)return i;if(!this.gateway.host)return i;var t=this.gateway.protocol+"://"+this.gateway.host;return this.gateway.port>-1&&(t=t+":"+this.gateway.port.toString()),"login"===e?this.gateway.path_params_login&&(this.gateway.path_params_login.startsWith("/")?t+=this.gateway.path_params_login:t=t+"/"+this.gateway.path_params_login):this.gateway.path_params_api&&(this.gateway.path_params_api.startsWith("/")?t+=this.gateway.path_params_api:t=t+"/"+this.gateway.path_params_api),t}getConfigString(e,i){if(this.config._sections[e])return this.config._sections[e][i]}getConfigBoolean(e,i){if(this.config._sections[e]&&void 0!==this.config._sections[e][i])return"string"==typeof this.config._sections[e][i]?"true"===this.config._sections[e][i]:this.config._sections[e][i]}getConfigInt(e,i){if(this.config._sections[e]&&this.config._sections[e][i])return"string"==typeof this.config._sections[e][i]?parseInt(this.config._sections[e][i]):this.config._sections[e][i]}}class h{get instance(){return h.instance}set instance(e){h.instance=e}constructor(){h.instance||(h.instance=this),this.CollectionFormatEnum={CSV:",",SSV:" ",TSV:"\t",PIPES:"|",MULTI:"multi"};try{localStorage.setItem("purecloud_local_storage_test","purecloud_local_storage_test"),localStorage.removeItem("purecloud_local_storage_test"),this.hasLocalStorage=!0}catch(e){this.hasLocalStorage=!1}this.authentications={"Guest Chat JWT":{type:"apiKey",in:"header",name:"Authorization"},"PureCloud OAuth":{type:"oauth2"}},this.defaultHeaders={},this.timeout=16e3,this.authData={},this.settingsPrefix="purecloud",this.refreshInProgress=!1,this.httpClient,this.proxyAgent,this.config=new g,"undefined"!=typeof window&&(window.ApiClient=this)}setReturnExtendedResponses(e){this.returnExtended=e}setPersistSettings(e,i){this.persistSettings=e,this.settingsPrefix=i?i.replace(/\W+/g,"_"):"purecloud"}_saveSettings(e){try{if(this.authData.accessToken=e.accessToken,this.authentications["PureCloud OAuth"].accessToken=e.accessToken,e.state&&(this.authData.state=e.state),this.authData.error=e.error,this.authData.error_description=e.error_description,e.tokenExpiryTime&&(this.authData.tokenExpiryTime=e.tokenExpiryTime,this.authData.tokenExpiryTimeString=e.tokenExpiryTimeString),!0!==this.persistSettings)return;if(!this.hasLocalStorage)return;let i=JSON.parse(JSON.stringify(this.authData));delete i.state,localStorage.setItem(`${this.settingsPrefix}_auth_data`,JSON.stringify(i))}catch(e){console.error(e)}}_loadSettings(){if(!0!==this.persistSettings)return;if(!this.hasLocalStorage)return;const e=this.authData.state;this.authData=localStorage.getItem(`${this.settingsPrefix}_auth_data`),this.authData?this.authData=JSON.parse(this.authData):this.authData={},this.authData.accessToken&&this.setAccessToken(this.authData.accessToken),this.authData.state=e}setEnvironment(e){this.config.setEnvironment(e)}setHttpClient(e){if(!(e instanceof r))throw new Error("httpclient must be an instance of AbstractHttpClient. See DefaultltHttpClient for a prototype");this.httpClient=e}getHttpClient(){return this.httpClient?this.httpClient:(this.httpClient=new l(this.timeout,this.proxyAgent),this.httpClient)}setMTLSCertificates(e,i,t){if("undefined"!=typeof window)throw new Error("MTLS authentication is managed by the Browser itself. MTLS certificates cannot be set via code on Browser.");{const n={};e&&(n.cert=require("fs").readFileSync(e)),i&&(n.key=require("fs").readFileSync(i)),t&&(n.ca=require("fs").readFileSync(t)),n.rejectUnauthorized=!0,this.proxyAgent=new require("https").Agent(n),this.getHttpClient().setHttpsAgent(this.proxyAgent)}}setPreHook(e){this.getHttpClient().setPreHook(e)}setPostHook(e){this.getHttpClient().setPostHook(e)}setMTLSContents(e,i,t){if("undefined"!=typeof window)throw new Error("MTLS authentication is managed by the Browser itself. MTLS certificates cannot be set via code on Browser.");{const n={};e&&(n.cert=e),i&&(n.key=i),t&&(n.ca=t),n.rejectUnauthorized=!0,this.proxyAgent=new require("https").Agent(n),this.getHttpClient().setHttpsAgent(this.proxyAgent)}}setGateway(e){this.config.setGateway(e)}loginImplicitGrant(e,i,t){const n=this._setValuesFromUrlHash();return this.clientId=e,this.redirectUri=i,t||(t={}),new Promise((e,i)=>{if(t.org&&!t.provider?i(new Error("opts.provider must be set if opts.org is set")):t.provider&&!t.org&&i(new Error("opts.org must be set if opts.provider is set")),n&&n.error)return n.accessToken=void 0,this._saveSettings(n),i(new Error(`[${n.error}] ${n.error_description}`));this._testTokenAccess().then(()=>{!this.authData.state&&t.state&&(this.authData.state=t.state),e(this.authData)}).catch(e=>{var i={client_id:encodeURIComponent(this.clientId),redirect_uri:encodeURIComponent(this.redirectUri),response_type:"token"};t.state&&(i.state=encodeURIComponent(t.state)),t.org&&(i.org=encodeURIComponent(t.org)),t.provider&&(i.provider=encodeURIComponent(t.provider));var n=this._buildAuthUrl("oauth/authorize",i);window.location.replace(n)})})}loginClientCredentialsGrant(e,i){this.clientId=e;var t=Buffer.from(`${e}:${i}`).toString("base64"),n=this.config.getConfUrl("login",`https://login.${this.config.environment}`);return new Promise((e,i)=>{if("undefined"!=typeof window)return void i(new Error("The client credentials grant is not supported in a browser."));const a={Authorization:`Basic ${t}`};var o=new s(`${n}/oauth/token`,"POST",a,null,"grant_type=client_credentials",this.timeout);this.getHttpClient().request(o).then(i=>{this.config.logger.log("trace",i.status,"POST",`${n}/oauth/token`,a,i.headers,{grant_type:"client_credentials"},void 0),this.config.logger.log("debug",i.status,"POST",`${n}/oauth/token`,a,void 0,{grant_type:"client_credentials"},void 0),this.setAccessToken(i.data.access_token),this.authData.tokenExpiryTime=(new Date).getTime()+1e3*i.data.expires_in,this.authData.tokenExpiryTimeString=new Date(this.authData.tokenExpiryTime).toUTCString(),e(this.authData)}).catch(e=>{e.response&&this.config.logger.log("error",e.response.status,"POST",`${n}/oauth/token`,a,e.response.headers,{grant_type:"client_credentials"},e.response.data),i(e)})})}loginSaml2BearerGrant(e,i,t,n){this.clientId=e;var a=this.config.getConfUrl("login",`https://login.${this.config.environment}`);return new Promise((o,r)=>{if("undefined"==typeof window){var s=Buffer.from(e+":"+i).toString("base64"),l=this._formAuthRequest(s,{grant_type:"urn:ietf:params:oauth:grant-type:saml2-bearer",orgName:t,assertion:n});l.proxy=this.proxy;var p={grant_type:"urn:ietf:params:oauth:grant-type:saml2-bearer",orgName:t,assertion:n};l.then(e=>{this.config.logger.log("trace",e.status,"POST",`${a}/oauth/token`,l.headers,e.headers,p,void 0),this.config.logger.log("debug",e.status,"POST",`${a}/oauth/token`,l.headers,void 0,p,void 0);var i=e.data.access_token;this.setAccessToken(i),this.authData.tokenExpiryTime=(new Date).getTime()+1e3*e.data.expires_in,this.authData.tokenExpiryTimeString=new Date(this.authData.tokenExpiryTime).toUTCString(),o(this.authData)}).catch(e=>{e.response&&this.config.logger.log("error",e.response.status,"POST",`${a}/oauth/token`,l.headers,e.response.headers,p,e.response.data),r(e)})}else r(new Error("The saml2bearer grant is not supported in a browser."))})}authorizePKCEGrant(e,i,t,n){this.clientId=e;var o=this.config.getConfUrl("login",`https://login.${this.config.environment}`);return new Promise((r,l)=>{var p=a.default.stringify({grant_type:"authorization_code",code:t,code_verifier:i,client_id:e,redirect_uri:n}),u=new s(`${o}/oauth/token`,"POST",{"Content-Type":"application/x-www-form-urlencoded"},null,p,this.timeout);const d=this.getHttpClient();var c={grant_type:"authorization_code",code:t,code_verifier:i,client_id:e,redirect_uri:n};d.request(u).then(e=>{this.config.logger.log("trace",e.status,"POST",`${o}/oauth/token`,u.headers,e.headers,c,void 0),this.config.logger.log("debug",e.status,"POST",`${o}/oauth/token`,u.headers,void 0,c,void 0);var i=e.data.access_token;this.setAccessToken(i),this.authData.tokenExpiryTime=(new Date).getTime()+1e3*e.data.expires_in,this.authData.tokenExpiryTimeString=new Date(this.authData.tokenExpiryTime).toUTCString(),r(this.authData)}).catch(e=>{e.response&&this.config.logger.log("error",e.response.status,"POST",`${o}/oauth/token`,u.headers,e.response.headers,c,e.response.data),l(e)})})}generatePKCECodeVerifier(e){if(e<43||e>128)throw new Error("PKCE Code Verifier (length) must be between 43 and 128 characters");if("undefined"!=typeof window){const i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~";return Array.from(crypto.getRandomValues(new Uint32Array(e))).map(e=>i[e%i.length]).join("")}try{const i=require("crypto").getRandomValues,t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~";return Array.from(i(new Uint32Array(e))).map(e=>t[e%t.length]).join("")}catch(e){throw new Error("Crypto module is missing/not supported.")}}computePKCECodeChallenge(e){if(e.length<43||e.length>128)throw new Error("PKCE Code Verifier (length) must be between 43 and 128 characters");if("undefined"!=typeof window){const i=(new TextEncoder).encode(e);return new Promise((e,t)=>{window.crypto.subtle.digest("SHA-256",i).then(i=>{let t=Buffer.from(i).toString("base64").replaceAll("+","-").replaceAll("/","_");t=t.split("=")[0],e(t)}).catch(e=>t(new Error(`Code Challenge Error ${e}`)))})}try{const i=require("crypto").createHash,t=(new TextEncoder).encode(e);return new Promise((e,n)=>{const a=i("sha256").update(t).digest();e(Buffer.from(a).toString("base64url"))})}catch(e){throw new Error("Crypto module is missing/not supported.")}}loginPKCEGrant(e,i,t,n){if(!this.hasLocalStorage&&!n)throw new Error("loginPKCEGrant requires Local Storage or codeVerifier as input parameter");const a=this._setValuesFromUrlQuery();return this.clientId=e,this.redirectUri=i,this.codeVerifier=n,t||(t={}),new Promise((e,i)=>{if(t.org&&!t.provider?i(new Error("opts.provider must be set if opts.org is set")):t.provider&&!t.org&&i(new Error("opts.org must be set if opts.provider is set")),a&&a.error)return this.hasLocalStorage&&sessionStorage.removeItem("genesys_cloud_sdk_pkce_code_verifier"),this._saveSettings({accessToken:void 0}),i(new Error(`[${a.error}] ${a.error_description}`));a&&a.code?(this.codeVerifier||this.hasLocalStorage&&(this.codeVerifier=sessionStorage.getItem("genesys_cloud_sdk_pkce_code_verifier")),this.authorizePKCEGrant(this.clientId,this.codeVerifier,a.code,this.redirectUri).then(()=>{this._testTokenAccess().then(()=>{!this.authData.state&&a.state&&(this.authData.state=a.state),this.hasLocalStorage&&sessionStorage.removeItem("genesys_cloud_sdk_pkce_code_verifier"),e(this.authData)}).catch(e=>(this._saveSettings({accessToken:void 0}),this.hasLocalStorage&&sessionStorage.removeItem("genesys_cloud_sdk_pkce_code_verifier"),i(new Error(`[${e.name}] ${e.msg}`))))}).catch(e=>(this._saveSettings({accessToken:void 0}),this.hasLocalStorage&&sessionStorage.removeItem("genesys_cloud_sdk_pkce_code_verifier"),i(new Error(`[${e.name}] ${e.msg}`))))):this._testTokenAccess().then(()=>{!this.authData.state&&t.state&&(this.authData.state=t.state),e(this.authData)}).catch(e=>{this.codeVerifier||(this.codeVerifier=this.generatePKCECodeVerifier(128),this.hasLocalStorage&&sessionStorage.setItem("genesys_cloud_sdk_pkce_code_verifier",this.codeVerifier)),this.computePKCECodeChallenge(this.codeVerifier).then(e=>{var i={client_id:encodeURIComponent(this.clientId),redirect_uri:encodeURIComponent(this.redirectUri),code_challenge:encodeURIComponent(e),response_type:"code",code_challenge_method:"S256"};t.state&&(i.state=encodeURIComponent(t.state)),t.org&&(i.org=encodeURIComponent(t.org)),t.provider&&(i.provider=encodeURIComponent(t.provider));var n=this._buildAuthUrl("oauth/authorize",i);window.location.replace(n)}).catch(e=>i(new Error(`[${e.name}]`)))})})}_setValuesFromUrlQuery(){if("undefined"==typeof window||!window.location.search)return;let e={},i=new URLSearchParams(window.location.search),t=i.get("code"),n=i.get("error"),a=i.get("error_description"),o=i.get("state");if(n)return e.error=n,a&&(e.error_description=a),e;t&&(e.code=t,o&&(e.state=o));var r,s,l=window.location;return"replaceState"in history?history.replaceState("",document.title,l.pathname):(r=document.body.scrollTop,s=document.body.scrollLeft,history.pushState("",document.title,l.pathname),document.body.scrollTop=r,document.body.scrollLeft=s),e}loginCodeAuthorizationGrant(e,i,t,n){return this.clientId=e,this.clientSecret=i,new Promise((a,o)=>{if("undefined"==typeof window){var r=Buffer.from(e+":"+i).toString("base64"),s=this._formAuthRequest(r,{grant_type:"authorization_code",code:t,redirect_uri:n});s.proxy=this.proxy;var l={grant_type:"authorization_code",code:t,redirect_uri:n};this._handleCodeAuthorizationResponse(s,l,a,o)}else o(new Error("The Code Authorization grant is not supported in a browser."))})}refreshCodeAuthorizationGrant(e,i,t){return new Promise((n,a)=>{if("undefined"==typeof window){var o=Buffer.from(e+":"+i).toString("base64"),r=this._formAuthRequest(o,{grant_type:"refresh_token",refresh_token:t});r.proxy=this.proxy;var s={grant_type:"refresh_token",refresh_token:t};this._handleCodeAuthorizationResponse(r,s,n,a)}else a(new Error("The Code Authorization grant is not supported in a browser."))})}_handleCodeAuthorizationResponse(e,i,t,n){var a=this.config.getConfUrl("login",`https://login.${this.config.environment}`);e.then(n=>{this.config.logger.log("trace",n.status,"POST",`${a}/oauth/token`,e.headers,n.headers,i,void 0),this.config.logger.log("debug",n.status,"POST",`${a}/oauth/token`,e.headers,void 0,i,void 0);var o=n.data.access_token,r=n.data.refresh_token;this.setAccessToken(o),this.authData.refreshToken=r,this.authData.tokenExpiryTime=(new Date).getTime()+1e3*n.data.expires_in,this.authData.tokenExpiryTimeString=new Date(this.authData.tokenExpiryTime).toUTCString(),t(this.authData)}).catch(t=>{t.response&&this.config.logger.log("error",t.response.status,"POST",`${a}/oauth/token`,e.headers,t.response.headers,i,t.response.data),n(t)})}_formAuthRequest(e,i){var t=this.config.getConfUrl("login",`https://login.${this.config.environment}`),n=new s(`${t}/oauth/token`,"POST",{Authorization:"Basic "+e,"Content-Type":"application/x-www-form-urlencoded"},null,a.default.stringify(i),this.timeout);return this.getHttpClient().request(n)}_handleExpiredAccessToken(){return new Promise((e,i)=>{"undefined"==typeof window?this.refreshInProgress?this._sleep(this.config.refresh_token_wait_max).then(()=>{this.refreshInProgress?i(new Error(`Token refresh took longer than ${this.config.refresh_token_wait_max} seconds`)):e()}):(this.refreshInProgress=!0,this.refreshCodeAuthorizationGrant(this.clientId,this.clientSecret,this.authData.refreshToken).then(()=>{this.refreshInProgress=!1,e()}).catch(e=>{this.refreshInProgress=!1,i(e)})):i(new Error("This method is not supported in a browser."))})}_sleep(e){return new Promise(i=>setTimeout(i,e))}_testTokenAccess(){return new Promise((e,i)=>{this._loadSettings(),this.authentications["PureCloud OAuth"].accessToken?this.callApi("/api/v2/tokens/me","GET",null,null,null,null,null,["PureCloud OAuth"],["application/json"],["application/json"]).then(()=>{e()}).catch(e=>{this._saveSettings({accessToken:void 0}),i(e)}):i(new Error("Token is not set"))})}_setValuesFromUrlHash(){if("undefined"==typeof window||!window.location.hash)return;const e=new RegExp("^#*(.+?)=(.+?)$","i");let i={};if(window.location.hash.split("&").forEach(t=>{const n=e.exec(t);n&&(i[n[1]]=decodeURIComponent(decodeURIComponent(n[2].replace(/\+/g,"%20"))))}),i.error)return i;if(i.access_token){let e={};i.state&&(e.state=i.state),i.expires_in&&(e.tokenExpiryTime=(new Date).getTime()+1e3*parseInt(i.expires_in.replace(/\+/g,"%20")),e.tokenExpiryTimeString=new Date(e.tokenExpiryTime).toUTCString()),e.accessToken=i.access_token.replace(/\+/g,"%20");var t,n,a=window.location;"replaceState"in history?history.replaceState("",document.title,a.pathname+a.search):(t=document.body.scrollTop,n=document.body.scrollLeft,a.hash="",document.body.scrollTop=t,document.body.scrollLeft=n),this._saveSettings(e)}}setAccessToken(e){this._saveSettings({accessToken:e})}setStorageKey(e){this.storageKey=e,this.setAccessToken(this.authentications["PureCloud OAuth"].accessToken)}logout(e){this.hasLocalStorage&&this._saveSettings({accessToken:void 0,state:void 0,tokenExpiryTime:void 0,tokenExpiryTimeString:void 0});var i={client_id:encodeURIComponent(this.clientId)};e&&(i.redirect_uri=encodeURI(e));var t=this._buildAuthUrl("logout",i);window.location.replace(t)}_buildAuthUrl(e,i){i||(i={});var t=this.config.getConfUrl("login",this.config.authUrl);return Object.keys(i).reduce((e,t)=>i[t]?`${e}&${t}=${i[t]}`:e,`${t}/${e}?`)}paramToString(e){return e?e instanceof Date?e.toJSON():e instanceof Boolean?e.toString().toLowerCase():e.toString():""}serialize(e){var i={};for(var t in e)e.hasOwnProperty(t)&&void 0!==e[t]&&(i[encodeURIComponent(t)]=Array.isArray(e[t])?e[t].join(","):this.paramToString(e[t]));return i}addHeaders(e,...i){return e=e?Object.assign(e,...i):Object.assign(...i)}buildUrl(e,i){e.match(/^\//)||(e=`/${e}`);var t=this.config.getConfUrl("api",this.config.basePath)+e;return t=t.replace(/\{([\w-]+)\}/g,(e,t)=>{var n;return n=i.hasOwnProperty(t)?this.paramToString(i[t]):e,encodeURIComponent(n)})}isJsonMime(e){return Boolean(e&&e.match(/^application\/json(;.*)?$/i))}jsonPreferredMime(e){for(var i=0;i<e.length;i++)if(this.isJsonMime(e[i]))return e[i];return e[0]}isFileParam(e){return!!("undefined"==typeof window&&"function"==typeof require&&require("fs")&&e instanceof require("fs").ReadStream)||("function"==typeof Buffer&&e instanceof Buffer||("function"==typeof Blob&&e instanceof Blob||"function"==typeof File&&e instanceof File))}normalizeParams(e){var i={};for(var t in e)if(e.hasOwnProperty(t)&&void 0!==e[t]){var n=e[t];this.isFileParam(n)||Array.isArray(n)?i[t]=n:i[t]=this.paramToString(n)}return i}buildCollectionParam(e,i){if(e)switch(Array.isArray(e)||(e=[e]),i){case"csv":return e.map(this.paramToString).join(",");case"ssv":return e.map(this.paramToString).join(" ");case"tsv":return e.map(this.paramToString).join("\t");case"pipes":return e.map(this.paramToString).join("|");case"multi":return e.map(this.paramToString);default:throw new Error(`Unknown collection format: ${i}`)}}applyAuthToRequest(e,i){i.forEach(i=>{var t=this.authentications[i];switch(t.type){case"basic":(t.username||t.password)&&(e.auth={username:t.username||"",password:t.password||""});break;case"apiKey":if(t.apiKey){var n={};t.apiKeyPrefix?n[t.name]=`${t.apiKeyPrefix} ${t.apiKey}`:n[t.name]=t.apiKey,"header"===t.in?e.headers=this.addHeaders(e.headers,n):e.setParams(this.serialize(n))}break;case"oauth2":t.accessToken&&(e.headers=this.addHeaders(e.headers,{Authorization:`Bearer ${t.accessToken}`}));break;default:throw new Error(`Unknown authentication type: ${t.type}`)}})}setProxyAgent(e){this.proxyAgent=e,this.getHttpClient().setHttpsAgent(this.proxyAgent)}callApi(e,i,t,n,a,o,r,l,p,u){return new Promise((d,c)=>{!function g(h){var m=h.buildUrl(e,t);var w=new s(m,i,null,h.serialize(n),null,h.timeout);h.applyAuthToRequest(w,l);const v=h.defaultHeaders;const C=h.normalizeParams(a);w.headers=h.addHeaders(w.headers,v,C);var I=h.jsonPreferredMime(p);I?w.headers["Content-Type"]=I:w.headers["Content-Type"]||(w.headers["Content-Type"]="application/json");if("application/x-www-form-urlencoded"===I)w.setData(h.normalizeParams(o));else if("multipart/form-data"==I){var f=h.normalizeParams(o);for(var A in f)if(f.hasOwnProperty(A)){var b=new FormData;b.set(A,f[A]),w.setData(b)}}else r&&w.setData(r);var j=h.jsonPreferredMime(u);j&&(w.headers.Accept=j);const P=h.getHttpClient();P.request(w).then(e=>{var t=!0===h.returnExtended?{status:e.status,statusText:e.statusText,headers:e.headers,body:e.data,text:e.text,error:null}:e.data?e.data:e.text;h.config.logger.log("trace",e.status,i,m,w.headers,e.headers,r,void 0),h.config.logger.log("debug",e.status,i,m,w.headers,void 0,r,void 0),d(t)}).catch(e=>{var t=e;e.response&&401==e.response.status&&h.config.refresh_access_token&&h.authData.refreshToken&&""!==h.authData.refreshToken?h._handleExpiredAccessToken().then(()=>{g(h)}).catch(e=>{c(e)}):e.response&&(h.config.logger.log("error",e.response.status,i,m,w.headers,e.response.headers,r,e.response.data),t=!0===h.returnExtended?{status:e.response.status,statusText:e.response.statusText,headers:e.response.headers,body:e.response.data,text:e.response.text,error:e}:e.response.data?e.response.data:e.response.text),c(t)})}(this)})}}class m{constructor(e){this.apiClient=e||h.instance}deleteAssistant(e){if(void 0===e||null===e)throw'Missing the required parameter "assistantId" when calling deleteAssistant';return this.apiClient.callApi("/api/v2/assistants/{assistantId}","DELETE",{assistantId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}deleteAssistantQueue(e,i){if(void 0===e||null===e)throw'Missing the required parameter "assistantId" when calling deleteAssistantQueue';if(void 0===i||null===i)throw'Missing the required parameter "queueId" when calling deleteAssistantQueue';return this.apiClient.callApi("/api/v2/assistants/{assistantId}/queues/{queueId}","DELETE",{assistantId:e,queueId:i},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}deleteAssistantQueues(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "assistantId" when calling deleteAssistantQueues';return this.apiClient.callApi("/api/v2/assistants/{assistantId}/queues","DELETE",{assistantId:e},{queueIds:i.queueIds},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAssistant(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "assistantId" when calling getAssistant';return this.apiClient.callApi("/api/v2/assistants/{assistantId}","GET",{assistantId:e},{expand:i.expand},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAssistantQueue(e,i,t){if(t=t||{},void 0===e||null===e)throw'Missing the required parameter "assistantId" when calling getAssistantQueue';if(void 0===i||null===i)throw'Missing the required parameter "queueId" when calling getAssistantQueue';return this.apiClient.callApi("/api/v2/assistants/{assistantId}/queues/{queueId}","GET",{assistantId:e,queueId:i},{expand:t.expand},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAssistantQueues(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "assistantId" when calling getAssistantQueues';return this.apiClient.callApi("/api/v2/assistants/{assistantId}/queues","GET",{assistantId:e},{before:i.before,after:i.after,pageSize:i.pageSize,expand:i.expand},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAssistants(e){return e=e||{},this.apiClient.callApi("/api/v2/assistants","GET",{},{before:e.before,after:e.after,limit:e.limit,pageSize:e.pageSize,name:e.name,expand:e.expand},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAssistantsQueues(e){return e=e||{},this.apiClient.callApi("/api/v2/assistants/queues","GET",{},{before:e.before,after:e.after,pageSize:e.pageSize,queueIds:e.queueIds,expand:e.expand},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}patchAssistant(e,i){if(void 0===e||null===e)throw'Missing the required parameter "assistantId" when calling patchAssistant';if(void 0===i||null===i)throw'Missing the required parameter "body" when calling patchAssistant';return this.apiClient.callApi("/api/v2/assistants/{assistantId}","PATCH",{assistantId:e},{},{},{},i,["PureCloud OAuth"],["application/json"],["application/json"])}patchAssistantQueues(e,i){if(void 0===e||null===e)throw'Missing the required parameter "assistantId" when calling patchAssistantQueues';if(void 0===i||null===i)throw'Missing the required parameter "body" when calling patchAssistantQueues';return this.apiClient.callApi("/api/v2/assistants/{assistantId}/queues","PATCH",{assistantId:e},{},{},{},i,["PureCloud OAuth"],["application/json"],["application/json"])}postAssistants(e){if(void 0===e||null===e)throw'Missing the required parameter "body" when calling postAssistants';return this.apiClient.callApi("/api/v2/assistants","POST",{},{},{},{},e,["PureCloud OAuth"],["application/json"],["application/json"])}putAssistantQueue(e,i,t){if(void 0===e||null===e)throw'Missing the required parameter "assistantId" when calling putAssistantQueue';if(void 0===i||null===i)throw'Missing the required parameter "queueId" when calling putAssistantQueue';if(void 0===t||null===t)throw'Missing the required parameter "body" when calling putAssistantQueue';return this.apiClient.callApi("/api/v2/assistants/{assistantId}/queues/{queueId}","PUT",{assistantId:e,queueId:i},{},{},{},t,["PureCloud OAuth"],["application/json"],["application/json"])}}class w{constructor(e){this.apiClient=e||h.instance}getAssistantCopilot(e){if(void 0===e||null===e)throw'Missing the required parameter "assistantId" when calling getAssistantCopilot';return this.apiClient.callApi("/api/v2/assistants/{assistantId}/copilot","GET",{assistantId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}putAssistantCopilot(e,i){if(void 0===e||null===e)throw'Missing the required parameter "assistantId" when calling putAssistantCopilot';if(void 0===i||null===i)throw'Missing the required parameter "body" when calling putAssistantCopilot';return this.apiClient.callApi("/api/v2/assistants/{assistantId}/copilot","PUT",{assistantId:e},{},{},{},i,["PureCloud OAuth"],["application/json"],["application/json"])}}class v{constructor(e){this.apiClient=e||h.instance}deleteUsersAgentuiAgentsAutoanswerAgentIdSettings(e){if(void 0===e||null===e)throw'Missing the required parameter "agentId" when calling deleteUsersAgentuiAgentsAutoanswerAgentIdSettings';return this.apiClient.callApi("/api/v2/users/agentui/agents/autoanswer/{agentId}/settings","DELETE",{agentId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getUsersAgentuiAgentsAutoanswerAgentIdSettings(e){if(void 0===e||null===e)throw'Missing the required parameter "agentId" when calling getUsersAgentuiAgentsAutoanswerAgentIdSettings';return this.apiClient.callApi("/api/v2/users/agentui/agents/autoanswer/{agentId}/settings","GET",{agentId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}patchUsersAgentuiAgentsAutoanswerAgentIdSettings(e,i){if(void 0===e||null===e)throw'Missing the required parameter "agentId" when calling patchUsersAgentuiAgentsAutoanswerAgentIdSettings';if(void 0===i||null===i)throw'Missing the required parameter "body" when calling patchUsersAgentuiAgentsAutoanswerAgentIdSettings';return this.apiClient.callApi("/api/v2/users/agentui/agents/autoanswer/{agentId}/settings","PATCH",{agentId:e},{},{},{},i,["PureCloud OAuth"],["application/json"],["application/json"])}putUsersAgentuiAgentsAutoanswerAgentIdSettings(e,i){if(void 0===e||null===e)throw'Missing the required parameter "agentId" when calling putUsersAgentuiAgentsAutoanswerAgentIdSettings';if(void 0===i||null===i)throw'Missing the required parameter "body" when calling putUsersAgentuiAgentsAutoanswerAgentIdSettings';return this.apiClient.callApi("/api/v2/users/agentui/agents/autoanswer/{agentId}/settings","PUT",{agentId:e},{},{},{},i,["PureCloud OAuth"],["application/json"],["application/json"])}}class C{constructor(e){this.apiClient=e||h.instance}deleteAlertingAlert(e){if(void 0===e||null===e)throw'Missing the required parameter "alertId" when calling deleteAlertingAlert';return this.apiClient.callApi("/api/v2/alerting/alerts/{alertId}","DELETE",{alertId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}deleteAlertingAlertsAll(){return this.apiClient.callApi("/api/v2/alerting/alerts/all","DELETE",{},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}deleteAlertingRule(e){if(void 0===e||null===e)throw'Missing the required parameter "ruleId" when calling deleteAlertingRule';return this.apiClient.callApi("/api/v2/alerting/rules/{ruleId}","DELETE",{ruleId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAlertingAlert(e){if(void 0===e||null===e)throw'Missing the required parameter "alertId" when calling getAlertingAlert';return this.apiClient.callApi("/api/v2/alerting/alerts/{alertId}","GET",{alertId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAlertingRule(e){if(void 0===e||null===e)throw'Missing the required parameter "ruleId" when calling getAlertingRule';return this.apiClient.callApi("/api/v2/alerting/rules/{ruleId}","GET",{ruleId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}patchAlertingAlert(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "alertId" when calling patchAlertingAlert';return this.apiClient.callApi("/api/v2/alerting/alerts/{alertId}","PATCH",{alertId:e},{},{},{},i.body,["PureCloud OAuth"],["application/json"],["application/json"])}patchAlertingAlertsAll(e){return e=e||{},this.apiClient.callApi("/api/v2/alerting/alerts/all","PATCH",{},{},{},{},e.body,["PureCloud OAuth"],["application/json"],["application/json"])}patchAlertingAlertsBulk(e){if(void 0===e||null===e)throw'Missing the required parameter "body" when calling patchAlertingAlertsBulk';return this.apiClient.callApi("/api/v2/alerting/alerts/bulk","PATCH",{},{},{},{},e,["PureCloud OAuth"],["application/json"],["application/json"])}patchAlertingRulesBulk(e){if(void 0===e||null===e)throw'Missing the required parameter "body" when calling patchAlertingRulesBulk';return this.apiClient.callApi("/api/v2/alerting/rules/bulk","PATCH",{},{},{},{},e,["PureCloud OAuth"],["application/json"],["application/json"])}postAlertingAlertsQuery(e){return e=e||{},this.apiClient.callApi("/api/v2/alerting/alerts/query","POST",{},{},{},{},e.body,["PureCloud OAuth"],["application/json"],["application/json"])}postAlertingRules(e){if(void 0===e||null===e)throw'Missing the required parameter "body" when calling postAlertingRules';return this.apiClient.callApi("/api/v2/alerting/rules","POST",{},{},{},{},e,["PureCloud OAuth"],["application/json"],["application/json"])}postAlertingRulesBulkRemove(e){if(void 0===e||null===e)throw'Missing the required parameter "body" when calling postAlertingRulesBulkRemove';return this.apiClient.callApi("/api/v2/alerting/rules/bulk/remove","POST",{},{},{},{},e,["PureCloud OAuth"],["application/json"],["application/json"])}postAlertingRulesQuery(e){return e=e||{},this.apiClient.callApi("/api/v2/alerting/rules/query","POST",{},{},{},{},e.body,["PureCloud OAuth"],["application/json"],["application/json"])}putAlertingAlert(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "alertId" when calling putAlertingAlert';return this.apiClient.callApi("/api/v2/alerting/alerts/{alertId}","PUT",{alertId:e},{},{},{},i.body,["PureCloud OAuth"],["application/json"],["application/json"])}putAlertingRule(e,i){if(void 0===e||null===e)throw'Missing the required parameter "ruleId" when calling putAlertingRule';if(void 0===i||null===i)throw'Missing the required parameter "body" when calling putAlertingRule';return this.apiClient.callApi("/api/v2/alerting/rules/{ruleId}","PUT",{ruleId:e},{},{},{},i,["PureCloud OAuth"],["application/json"],["application/json"])}}class I{constructor(e){this.apiClient=e||h.instance}deleteAnalyticsConversationsDetailsJob(e){if(void 0===e||null===e)throw'Missing the required parameter "jobId" when calling deleteAnalyticsConversationsDetailsJob';return this.apiClient.callApi("/api/v2/analytics/conversations/details/jobs/{jobId}","DELETE",{jobId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}deleteAnalyticsUsersDetailsJob(e){if(void 0===e||null===e)throw'Missing the required parameter "jobId" when calling deleteAnalyticsUsersDetailsJob';return this.apiClient.callApi("/api/v2/analytics/users/details/jobs/{jobId}","DELETE",{jobId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsActionsAggregatesJob(e){if(void 0===e||null===e)throw'Missing the required parameter "jobId" when calling getAnalyticsActionsAggregatesJob';return this.apiClient.callApi("/api/v2/analytics/actions/aggregates/jobs/{jobId}","GET",{jobId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsActionsAggregatesJobResults(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "jobId" when calling getAnalyticsActionsAggregatesJobResults';return this.apiClient.callApi("/api/v2/analytics/actions/aggregates/jobs/{jobId}/results","GET",{jobId:e},{cursor:i.cursor},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsAgentStatus(e){if(void 0===e||null===e)throw'Missing the required parameter "userId" when calling getAnalyticsAgentStatus';return this.apiClient.callApi("/api/v2/analytics/agents/{userId}/status","GET",{userId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsAgentcopilotsAggregatesJob(e){if(void 0===e||null===e)throw'Missing the required parameter "jobId" when calling getAnalyticsAgentcopilotsAggregatesJob';return this.apiClient.callApi("/api/v2/analytics/agentcopilots/aggregates/jobs/{jobId}","GET",{jobId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsAgentcopilotsAggregatesJobResults(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "jobId" when calling getAnalyticsAgentcopilotsAggregatesJobResults';return this.apiClient.callApi("/api/v2/analytics/agentcopilots/aggregates/jobs/{jobId}/results","GET",{jobId:e},{cursor:i.cursor},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsBotflowDivisionsReportingturns(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "botFlowId" when calling getAnalyticsBotflowDivisionsReportingturns';return this.apiClient.callApi("/api/v2/analytics/botflows/{botFlowId}/divisions/reportingturns","GET",{botFlowId:e},{after:i.after,pageSize:i.pageSize,interval:i.interval,actionId:i.actionId,sessionId:i.sessionId,language:i.language,askActionResults:i.askActionResults},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsBotflowReportingturns(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "botFlowId" when calling getAnalyticsBotflowReportingturns';return this.apiClient.callApi("/api/v2/analytics/botflows/{botFlowId}/reportingturns","GET",{botFlowId:e},{after:i.after,pageSize:i.pageSize,interval:i.interval,actionId:i.actionId,sessionId:i.sessionId,language:i.language,askActionResults:i.askActionResults},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsBotflowSessions(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "botFlowId" when calling getAnalyticsBotflowSessions';return this.apiClient.callApi("/api/v2/analytics/botflows/{botFlowId}/sessions","GET",{botFlowId:e},{after:i.after,pageSize:i.pageSize,interval:i.interval,botResultCategories:i.botResultCategories,endLanguage:i.endLanguage},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsBotsAggregatesJob(e){if(void 0===e||null===e)throw'Missing the required parameter "jobId" when calling getAnalyticsBotsAggregatesJob';return this.apiClient.callApi("/api/v2/analytics/bots/aggregates/jobs/{jobId}","GET",{jobId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsBotsAggregatesJobResults(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "jobId" when calling getAnalyticsBotsAggregatesJobResults';return this.apiClient.callApi("/api/v2/analytics/bots/aggregates/jobs/{jobId}/results","GET",{jobId:e},{cursor:i.cursor},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsConversationDetails(e){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getAnalyticsConversationDetails';return this.apiClient.callApi("/api/v2/analytics/conversations/{conversationId}/details","GET",{conversationId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsConversationsAggregatesJob(e){if(void 0===e||null===e)throw'Missing the required parameter "jobId" when calling getAnalyticsConversationsAggregatesJob';return this.apiClient.callApi("/api/v2/analytics/conversations/aggregates/jobs/{jobId}","GET",{jobId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsConversationsAggregatesJobResults(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "jobId" when calling getAnalyticsConversationsAggregatesJobResults';return this.apiClient.callApi("/api/v2/analytics/conversations/aggregates/jobs/{jobId}/results","GET",{jobId:e},{cursor:i.cursor},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsConversationsDetails(e){return e=e||{},this.apiClient.callApi("/api/v2/analytics/conversations/details","GET",{},{id:this.apiClient.buildCollectionParam(e.id,"multi")},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsConversationsDetailsJob(e){if(void 0===e||null===e)throw'Missing the required parameter "jobId" when calling getAnalyticsConversationsDetailsJob';return this.apiClient.callApi("/api/v2/analytics/conversations/details/jobs/{jobId}","GET",{jobId:e},{},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsConversationsDetailsJobResults(e,i){if(i=i||{},void 0===e||null===e)throw'Missing the required parameter "jobId" when calling getAnalyticsConversationsDetailsJobResults';return this.apiClient.callApi("/api/v2/analytics/conversations/details/jobs/{jobId}/results","GET",{jobId:e},{cursor:i.cursor,pageSize:i.pageSize},{},{},null,["PureCloud OAuth"],["application/json"],["application/json"])}getAnalyticsConversationsDetailsJobsAvailability(){return thi