pilotswarm-web 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +144 -0
  2. package/auth/authz/engine.js +139 -0
  3. package/auth/config.js +110 -0
  4. package/auth/index.js +153 -0
  5. package/auth/normalize/entra.js +22 -0
  6. package/auth/providers/entra.js +76 -0
  7. package/auth/providers/none.js +24 -0
  8. package/auth.js +10 -0
  9. package/bin/serve.js +53 -0
  10. package/config.js +20 -0
  11. package/dist/app.js +469 -0
  12. package/dist/assets/index-BSVg-lGb.css +1 -0
  13. package/dist/assets/index-BXD5YP7A.js +24 -0
  14. package/dist/assets/msal-CytV9RFv.js +7 -0
  15. package/dist/assets/pilotswarm-WX3NED6m.js +40 -0
  16. package/dist/assets/react-jg0oazEi.js +1 -0
  17. package/dist/index.html +16 -0
  18. package/node_modules/pilotswarm-ui-core/README.md +6 -0
  19. package/node_modules/pilotswarm-ui-core/package.json +32 -0
  20. package/node_modules/pilotswarm-ui-core/src/commands.js +72 -0
  21. package/node_modules/pilotswarm-ui-core/src/context-usage.js +212 -0
  22. package/node_modules/pilotswarm-ui-core/src/controller.js +3613 -0
  23. package/node_modules/pilotswarm-ui-core/src/formatting.js +872 -0
  24. package/node_modules/pilotswarm-ui-core/src/history.js +571 -0
  25. package/node_modules/pilotswarm-ui-core/src/index.js +13 -0
  26. package/node_modules/pilotswarm-ui-core/src/layout.js +196 -0
  27. package/node_modules/pilotswarm-ui-core/src/reducer.js +1027 -0
  28. package/node_modules/pilotswarm-ui-core/src/selectors.js +2786 -0
  29. package/node_modules/pilotswarm-ui-core/src/session-tree.js +109 -0
  30. package/node_modules/pilotswarm-ui-core/src/state.js +80 -0
  31. package/node_modules/pilotswarm-ui-core/src/store.js +23 -0
  32. package/node_modules/pilotswarm-ui-core/src/system-titles.js +24 -0
  33. package/node_modules/pilotswarm-ui-core/src/themes/catppuccin-mocha.js +56 -0
  34. package/node_modules/pilotswarm-ui-core/src/themes/cobalt2.js +56 -0
  35. package/node_modules/pilotswarm-ui-core/src/themes/dark-high-contrast.js +56 -0
  36. package/node_modules/pilotswarm-ui-core/src/themes/dracula.js +56 -0
  37. package/node_modules/pilotswarm-ui-core/src/themes/github-dark.js +56 -0
  38. package/node_modules/pilotswarm-ui-core/src/themes/gruvbox-dark.js +56 -0
  39. package/node_modules/pilotswarm-ui-core/src/themes/hacker-x-matrix.js +56 -0
  40. package/node_modules/pilotswarm-ui-core/src/themes/hacker-x-orion-prime.js +56 -0
  41. package/node_modules/pilotswarm-ui-core/src/themes/helpers.js +77 -0
  42. package/node_modules/pilotswarm-ui-core/src/themes/index.js +42 -0
  43. package/node_modules/pilotswarm-ui-core/src/themes/noctis-viola.js +56 -0
  44. package/node_modules/pilotswarm-ui-core/src/themes/noctis.js +56 -0
  45. package/node_modules/pilotswarm-ui-core/src/themes/nord.js +56 -0
  46. package/node_modules/pilotswarm-ui-core/src/themes/solarized-dark.js +56 -0
  47. package/node_modules/pilotswarm-ui-core/src/themes/tokyo-night.js +56 -0
  48. package/node_modules/pilotswarm-ui-react/README.md +5 -0
  49. package/node_modules/pilotswarm-ui-react/package.json +36 -0
  50. package/node_modules/pilotswarm-ui-react/src/components.js +1316 -0
  51. package/node_modules/pilotswarm-ui-react/src/index.js +4 -0
  52. package/node_modules/pilotswarm-ui-react/src/platform.js +15 -0
  53. package/node_modules/pilotswarm-ui-react/src/use-controller-state.js +38 -0
  54. package/node_modules/pilotswarm-ui-react/src/web-app.js +2661 -0
  55. package/package.json +64 -0
  56. package/runtime.js +146 -0
  57. package/server.js +311 -0
@@ -0,0 +1,7 @@
1
+ const f={LIBRARY_NAME:"MSAL.JS",SKU:"msal.js.common",DEFAULT_AUTHORITY:"https://login.microsoftonline.com/common/",DEFAULT_AUTHORITY_HOST:"login.microsoftonline.com",DEFAULT_COMMON_TENANT:"common",ADFS:"adfs",DSTS:"dstsv2",AAD_INSTANCE_DISCOVERY_ENDPT:"https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=",CIAM_AUTH_URL:".ciamlogin.com",AAD_TENANT_DOMAIN_SUFFIX:".onmicrosoft.com",RESOURCE_DELIM:"|",NO_ACCOUNT:"NO_ACCOUNT",CLAIMS:"claims",CONSUMER_UTID:"9188040d-6c67-4c5b-b112-36a304b66dad",OPENID_SCOPE:"openid",PROFILE_SCOPE:"profile",OFFLINE_ACCESS_SCOPE:"offline_access",EMAIL_SCOPE:"email",CODE_GRANT_TYPE:"authorization_code",RT_GRANT_TYPE:"refresh_token",S256_CODE_CHALLENGE_METHOD:"S256",URL_FORM_CONTENT_TYPE:"application/x-www-form-urlencoded;charset=utf-8",AUTHORIZATION_PENDING:"authorization_pending",NOT_DEFINED:"not_defined",EMPTY_STRING:"",NOT_APPLICABLE:"N/A",NOT_AVAILABLE:"Not Available",FORWARD_SLASH:"/",IMDS_ENDPOINT:"http://169.254.169.254/metadata/instance/compute/location",IMDS_VERSION:"2020-06-01",IMDS_TIMEOUT:2e3,AZURE_REGION_AUTO_DISCOVER_FLAG:"TryAutoDetect",REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX:"login.microsoft.com",KNOWN_PUBLIC_CLOUDS:["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"],SHR_NONCE_VALIDITY:240,INVALID_INSTANCE:"invalid_instance"},pe={SUCCESS:200,SUCCESS_RANGE_START:200,SUCCESS_RANGE_END:299,REDIRECT:302,CLIENT_ERROR:400,CLIENT_ERROR_RANGE_START:400,BAD_REQUEST:400,UNAUTHORIZED:401,NOT_FOUND:404,REQUEST_TIMEOUT:408,GONE:410,TOO_MANY_REQUESTS:429,CLIENT_ERROR_RANGE_END:499,SERVER_ERROR:500,SERVER_ERROR_RANGE_START:500,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,SERVER_ERROR_RANGE_END:599,MULTI_SIDED_ERROR:600},_e={GET:"GET",POST:"POST"},Ve=[f.OPENID_SCOPE,f.PROFILE_SCOPE,f.OFFLINE_ACCESS_SCOPE],Lo=[...Ve,f.EMAIL_SCOPE],G={CONTENT_TYPE:"Content-Type",CONTENT_LENGTH:"Content-Length",RETRY_AFTER:"Retry-After",CCS_HEADER:"X-AnchorMailbox",WWWAuthenticate:"WWW-Authenticate",AuthenticationInfo:"Authentication-Info",X_MS_REQUEST_ID:"x-ms-request-id",X_MS_HTTP_VERSION:"x-ms-httpver"},Ho={ACTIVE_ACCOUNT_FILTERS:"active-account-filters"},Ce={COMMON:"common",ORGANIZATIONS:"organizations",CONSUMERS:"consumers"},dt={ACCESS_TOKEN:"access_token",XMS_CC:"xms_cc"},U={LOGIN:"login",SELECT_ACCOUNT:"select_account",CONSENT:"consent",NONE:"none",NO_SESSION:"no_session"},Rn={CODE:"code",IDTOKEN_TOKEN_REFRESHTOKEN:"id_token token refresh_token"},Gt={QUERY:"query",FRAGMENT:"fragment"},Ms={QUERY:"query"},wr={AUTHORIZATION_CODE_GRANT:"authorization_code",REFRESH_TOKEN_GRANT:"refresh_token"},ut={MSSTS_ACCOUNT_TYPE:"MSSTS",ADFS_ACCOUNT_TYPE:"ADFS",GENERIC_ACCOUNT_TYPE:"Generic"},ot={CACHE_KEY_SEPARATOR:"-",CLIENT_INFO_SEPARATOR:"."},H={ID_TOKEN:"IdToken",ACCESS_TOKEN:"AccessToken",ACCESS_TOKEN_WITH_AUTH_SCHEME:"AccessToken_With_AuthScheme",REFRESH_TOKEN:"RefreshToken"},bn="appmetadata",Us="client_info",Et="1",St={CACHE_KEY:"authority-metadata",REFRESH_TIME_SECONDS:3600*24},Y={CONFIG:"config",CACHE:"cache",NETWORK:"network",HARDCODED_VALUES:"hardcoded_values"},L={SCHEMA_VERSION:5,MAX_LAST_HEADER_BYTES:330,MAX_CACHED_ERRORS:50,CACHE_KEY:"server-telemetry",CATEGORY_SEPARATOR:"|",VALUE_SEPARATOR:",",OVERFLOW_TRUE:"1",OVERFLOW_FALSE:"0",UNKNOWN_ERROR:"unknown_error"},v={BEARER:"Bearer",POP:"pop",SSH:"ssh-cert"},et={DEFAULT_THROTTLE_TIME_SECONDS:60,DEFAULT_MAX_THROTTLE_TIME_SECONDS:3600,THROTTLING_PREFIX:"throttling",X_MS_LIB_CAPABILITY_VALUE:"retry-after, h429"},xo={INVALID_GRANT_ERROR:"invalid_grant",CLIENT_MISMATCH_ERROR:"client_mismatch"},Ue={FAILED_AUTO_DETECTION:"1",INTERNAL_CACHE:"2",ENVIRONMENT_VARIABLE:"3",IMDS:"4"},cn={CONFIGURED_NO_AUTO_DETECTION:"2",AUTO_DETECTION_REQUESTED_SUCCESSFUL:"4",AUTO_DETECTION_REQUESTED_FAILED:"5"},ve={NOT_APPLICABLE:"0",FORCE_REFRESH_OR_CLAIMS:"1",NO_CACHED_ACCESS_TOKEN:"2",CACHED_ACCESS_TOKEN_EXPIRED:"3",PROACTIVELY_REFRESHED:"4"},Ds={Pop:"pop"},Er=300;const kt="unexpected_error",Ls="post_request_failed";const Fo={[kt]:"Unexpected error in authentication.",[Ls]:"Post request failed from the network, could be a 4xx/5xx or a network unavailability. Please check the exact error code for details."};class R extends Error{constructor(e,t,n){const o=t?`${e}: ${t}`:e;super(o),Object.setPrototypeOf(this,R.prototype),this.errorCode=e||f.EMPTY_STRING,this.errorMessage=t||f.EMPTY_STRING,this.subError=n||f.EMPTY_STRING,this.name="AuthError"}setCorrelationId(e){this.correlationId=e}}function fn(i,e){return new R(i,e?`${Fo[i]} ${e}`:Fo[i])}const Pn="client_info_decoding_error",Sr="client_info_empty_error",On="token_parsing_error",kr="null_or_empty_token",he="endpoints_resolution_error",vr="network_error",_r="openid_config_error",Rr="hash_not_deserialized",$e="invalid_state",br="state_mismatch",mn="state_not_found",Pr="nonce_mismatch",Nn="auth_time_not_found",Or="max_age_transpired",Hs="multiple_matching_tokens",xs="multiple_matching_accounts",Nr="multiple_matching_appMetadata",Mr="request_cannot_be_made",Ur="cannot_remove_empty_scope",Dr="cannot_append_scopeset",pn="empty_input_scopeset",Fs="device_code_polling_cancelled",Ks="device_code_expired",Bs="device_code_unknown_error",Mn="no_account_in_silent_request",Lr="invalid_cache_record",Un="invalid_cache_environment",Cn="no_account_found",yn="no_crypto_object",Gs="unexpected_credential_type",zs="invalid_assertion",qs="invalid_client_credential",ye="token_refresh_required",$s="user_timeout_reached",Hr="token_claims_cnf_required_for_signedjwt",xr="authorization_code_missing_from_server_response",Fr="binding_key_not_removed",Kr="end_session_endpoint_not_supported",Dn="key_id_missing",Qs="no_network_connectivity",Vs="user_canceled",Ws="missing_tenant_id_error",w="method_not_implemented",js="nested_app_auth_bridge_disabled",Ys="platform_broker_error";const Ko={[Pn]:"The client info could not be parsed/decoded correctly",[Sr]:"The client info was empty",[On]:"Token cannot be parsed",[kr]:"The token is null or empty",[he]:"Endpoints cannot be resolved",[vr]:"Network request failed",[_r]:"Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints.",[Rr]:"The hash parameters could not be deserialized",[$e]:"State was not the expected format",[br]:"State mismatch error",[mn]:"State not found",[Pr]:"Nonce mismatch error",[Nn]:"Max Age was requested and the ID token is missing the auth_time variable. auth_time is an optional claim and is not enabled by default - it must be enabled. See https://aka.ms/msaljs/optional-claims for more information.",[Or]:"Max Age is set to 0, or too much time has elapsed since the last end-user authentication.",[Hs]:"The cache contains multiple tokens satisfying the requirements. Call AcquireToken again providing more requirements such as authority or account.",[xs]:"The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account",[Nr]:"The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata",[Mr]:"Token request cannot be made without authorization code or refresh token.",[Ur]:"Cannot remove null or empty scope from ScopeSet",[Dr]:"Cannot append ScopeSet",[pn]:"Empty input ScopeSet cannot be processed",[Fs]:"Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true.",[Ks]:"Device code is expired.",[Bs]:"Device code stopped polling for unknown reasons.",[Mn]:"Please pass an account object, silent flow is not supported without account information",[Lr]:"Cache record object was null or undefined.",[Un]:"Invalid environment when attempting to create cache entry",[Cn]:"No account found in cache for given key.",[yn]:"No crypto object detected.",[Gs]:"Unexpected credential type.",[zs]:"Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515",[qs]:"Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential",[ye]:"Cannot return token from cache because it must be refreshed. This may be due to one of the following reasons: forceRefresh parameter is set to true, claims have been requested, there is no cached access token or it is expired.",[$s]:"User defined timeout for device code polling reached",[Hr]:"Cannot generate a POP jwt if the token_claims are not populated",[xr]:"Server response does not contain an authorization code to proceed",[Fr]:"Could not remove the credential's binding key from storage.",[Kr]:"The provided authority does not support logout",[Dn]:"A keyId value is missing from the requested bound token's cache record and is required to match the token to it's stored binding key.",[Qs]:"No network connectivity. Check your internet connection.",[Vs]:"User cancelled the flow.",[Ws]:"A tenant id - not common, organizations, or consumers - must be specified when using the client_credentials flow.",[w]:"This method has not been implemented",[js]:"The nested app auth bridge is disabled",[Ys]:"An error occurred in the native broker. See the platformBrokerError property for details."};class Ln extends R{constructor(e,t){super(e,t?`${Ko[e]}: ${t}`:Ko[e]),this.name="ClientAuthError",Object.setPrototypeOf(this,Ln.prototype)}}function p(i,e){return new Ln(i,e)}const vt={createNewGuid:()=>{throw p(w)},base64Decode:()=>{throw p(w)},base64Encode:()=>{throw p(w)},base64UrlEncode:()=>{throw p(w)},encodeKid:()=>{throw p(w)},async getPublicKeyThumbprint(){throw p(w)},async removeTokenBindingKey(){throw p(w)},async clearKeystore(){throw p(w)},async signJwt(){throw p(w)},async hashString(){throw p(w)}};var b;(function(i){i[i.Error=0]="Error",i[i.Warning=1]="Warning",i[i.Info=2]="Info",i[i.Verbose=3]="Verbose",i[i.Trace=4]="Trace"})(b||(b={}));class we{constructor(e,t,n){this.level=b.Info;const o=()=>{},r=e||we.createDefaultLoggerOptions();this.localCallback=r.loggerCallback||o,this.piiLoggingEnabled=r.piiLoggingEnabled||!1,this.level=typeof r.logLevel=="number"?r.logLevel:b.Info,this.correlationId=r.correlationId||f.EMPTY_STRING,this.packageName=t||f.EMPTY_STRING,this.packageVersion=n||f.EMPTY_STRING}static createDefaultLoggerOptions(){return{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:b.Info}}clone(e,t,n){return new we({loggerCallback:this.localCallback,piiLoggingEnabled:this.piiLoggingEnabled,logLevel:this.level,correlationId:n||this.correlationId},e,t)}logMessage(e,t){if(t.logLevel>this.level||!this.piiLoggingEnabled&&t.containsPii)return;const r=`${`[${new Date().toUTCString()}] : [${t.correlationId||this.correlationId||""}]`} : ${this.packageName}@${this.packageVersion} : ${b[t.logLevel]} - ${e}`;this.executeCallback(t.logLevel,r,t.containsPii||!1)}executeCallback(e,t,n){this.localCallback&&this.localCallback(e,t,n)}error(e,t){this.logMessage(e,{logLevel:b.Error,containsPii:!1,correlationId:t||f.EMPTY_STRING})}errorPii(e,t){this.logMessage(e,{logLevel:b.Error,containsPii:!0,correlationId:t||f.EMPTY_STRING})}warning(e,t){this.logMessage(e,{logLevel:b.Warning,containsPii:!1,correlationId:t||f.EMPTY_STRING})}warningPii(e,t){this.logMessage(e,{logLevel:b.Warning,containsPii:!0,correlationId:t||f.EMPTY_STRING})}info(e,t){this.logMessage(e,{logLevel:b.Info,containsPii:!1,correlationId:t||f.EMPTY_STRING})}infoPii(e,t){this.logMessage(e,{logLevel:b.Info,containsPii:!0,correlationId:t||f.EMPTY_STRING})}verbose(e,t){this.logMessage(e,{logLevel:b.Verbose,containsPii:!1,correlationId:t||f.EMPTY_STRING})}verbosePii(e,t){this.logMessage(e,{logLevel:b.Verbose,containsPii:!0,correlationId:t||f.EMPTY_STRING})}trace(e,t){this.logMessage(e,{logLevel:b.Trace,containsPii:!1,correlationId:t||f.EMPTY_STRING})}tracePii(e,t){this.logMessage(e,{logLevel:b.Trace,containsPii:!0,correlationId:t||f.EMPTY_STRING})}isPiiLoggingEnabled(){return this.piiLoggingEnabled||!1}}const Br="@azure/msal-common",Hn="15.17.0";const xn={None:"none"};const Gr="redirect_uri_empty",Js="claims_request_parsing_error",zr="authority_uri_insecure",Xe="url_parse_error",qr="empty_url_error",$r="empty_input_scopes_error",Fn="invalid_claims",Qr="token_request_empty",Vr="logout_request_empty",Xs="invalid_code_challenge_method",Kn="pkce_params_missing",Bn="invalid_cloud_discovery_metadata",Wr="invalid_authority_metadata",jr="untrusted_authority",zt="missing_ssh_jwk",Yr="missing_ssh_kid",Zs="missing_nonce_authentication_header",ea="invalid_authentication_header",Jr="cannot_set_OIDCOptions",Xr="cannot_allow_platform_broker",Zr="authority_mismatch",ei="invalid_request_method_for_EAR",ti="invalid_authorize_post_body_parameters",ni="invalid_platform_broker_configuration";const ta={[Gr]:"A redirect URI is required for all calls, and none has been set.",[Js]:"Could not parse the given claims request object.",[zr]:"Authority URIs must use https. Please see here for valid authority configuration options: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications#configuration-options",[Xe]:"URL could not be parsed into appropriate segments.",[qr]:"URL was empty or null.",[$r]:"Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token.",[Fn]:"Given claims parameter must be a stringified JSON object.",[Qr]:"Token request was empty and not found in cache.",[Vr]:"The logout request was null or undefined.",[Xs]:'code_challenge_method passed is invalid. Valid values are "plain" and "S256".',[Kn]:"Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request",[Bn]:"Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields",[Wr]:"Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields.",[jr]:"The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.",[zt]:"Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme.",[Yr]:"Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme.",[Zs]:"Unable to find an authentication header containing server nonce. Either the Authentication-Info or WWW-Authenticate headers must be present in order to obtain a server nonce.",[ea]:"Invalid authentication header provided",[Jr]:"Cannot set OIDCOptions parameter. Please change the protocol mode to OIDC or use a non-Microsoft authority.",[Xr]:"Cannot set allowPlatformBroker parameter to true when not in AAD protocol mode.",[Zr]:"Authority mismatch error. Authority provided in login request or PublicClientApplication config does not match the environment of the provided account. Please use a matching account or make an interactive request to login to this authority.",[ti]:"Invalid authorize post body parameters provided. If you are using authorizePostBodyParameters, the request method must be POST. Please check the request method and parameters.",[ei]:"Invalid request method for EAR protocol mode. The request method cannot be GET when using EAR protocol mode. Please change the request method to POST.",[ni]:"Invalid platform broker configuration. `allowPlatformBrokerWithDOM` can only be enabled when `allowPlatformBroker` is enabled."};class Gn extends R{constructor(e){super(e,ta[e]),this.name="ClientConfigurationError",Object.setPrototypeOf(this,Gn.prototype)}}function _(i){return new Gn(i)}class J{static isEmptyObj(e){if(e)try{const t=JSON.parse(e);return Object.keys(t).length===0}catch{}return!0}static startsWith(e,t){return e.indexOf(t)===0}static endsWith(e,t){return e.length>=t.length&&e.lastIndexOf(t)===e.length-t.length}static queryStringToObject(e){const t={},n=e.split("&"),o=r=>decodeURIComponent(r.replace(/\+/g," "));return n.forEach(r=>{if(r.trim()){const[s,a]=r.split(/=(.+)/g,2);s&&a&&(t[o(s)]=o(a))}}),t}static trimArrayEntries(e){return e.map(t=>t.trim())}static removeEmptyStringsFromArray(e){return e.filter(t=>!!t)}static jsonParseHelper(e){try{return JSON.parse(e)}catch{return null}}static matchPattern(e,t){return new RegExp(e.replace(/\\/g,"\\\\").replace(/\*/g,"[^ ]*").replace(/\?/g,"\\?")).test(t)}static matchPatternStrict(e,t,n){const o=n?.component;let r=e.replace(/[.+^${}()|[\]\\*?]/g,"\\$&");return o==="host"?r=r.replace(/\\\*/g,"[^.]*"):r=r.replace(/\\\*/g,".*"),new RegExp(`^${r}$`).test(t)}}class M{constructor(e){const t=e?J.trimArrayEntries([...e]):[],n=t?J.removeEmptyStringsFromArray(t):[];if(!n||!n.length)throw _($r);this.scopes=new Set,n.forEach(o=>this.scopes.add(o))}static fromString(e){const n=(e||f.EMPTY_STRING).split(" ");return new M(n)}static createSearchScopes(e){const t=e&&e.length>0?e:[...Ve],n=new M(t);return n.containsOnlyOIDCScopes()?n.removeScope(f.OFFLINE_ACCESS_SCOPE):n.removeOIDCScopes(),n}containsScope(e){const t=this.printScopesLowerCase().split(" "),n=new M(t);return e?n.scopes.has(e.toLowerCase()):!1}containsScopeSet(e){return!e||e.scopes.size<=0?!1:this.scopes.size>=e.scopes.size&&e.asArray().every(t=>this.containsScope(t))}containsOnlyOIDCScopes(){let e=0;return Lo.forEach(t=>{this.containsScope(t)&&(e+=1)}),this.scopes.size===e}appendScope(e){e&&this.scopes.add(e.trim())}appendScopes(e){try{e.forEach(t=>this.appendScope(t))}catch{throw p(Dr)}}removeScope(e){if(!e)throw p(Ur);this.scopes.delete(e.trim())}removeOIDCScopes(){Lo.forEach(e=>{this.scopes.delete(e)})}unionScopeSets(e){if(!e)throw p(pn);const t=new Set;return e.scopes.forEach(n=>t.add(n.toLowerCase())),this.scopes.forEach(n=>t.add(n.toLowerCase())),t}intersectingScopeSets(e){if(!e)throw p(pn);e.containsOnlyOIDCScopes()||e.removeOIDCScopes();const t=this.unionScopeSets(e),n=e.getScopeCount(),o=this.getScopeCount();return t.size<o+n}getScopeCount(){return this.scopes.size}asArray(){const e=[];return this.scopes.forEach(t=>e.push(t)),e}printScopes(){return this.scopes?this.asArray().join(" "):f.EMPTY_STRING}printScopesLowerCase(){return this.printScopes().toLowerCase()}}function _t(i,e){if(!i)throw p(Sr);try{const t=e(i);return JSON.parse(t)}catch{throw p(Pn)}}function He(i){if(!i)throw p(Pn);const e=i.split(ot.CLIENT_INFO_SEPARATOR,2);return{uid:e[0],utid:e.length<2?f.EMPTY_STRING:e[1]}}function Bo(i,e){return!!i&&!!e&&i===e.split(".")[1]}function xe(i,e,t,n){if(n){const{oid:o,sub:r,tid:s,name:a,tfp:c,acr:l,preferred_username:d,upn:u,login_hint:m}=n,C=s||c||l||"";return{tenantId:C,localAccountId:o||r||"",name:a,username:d||u||"",loginHint:m,isHomeTenant:Bo(C,i)}}else return{tenantId:t,localAccountId:e,username:"",isHomeTenant:Bo(t,i)}}function zn(i,e,t,n){let o=i;if(e){const{isHomeTenant:r,...s}=e;o={...i,...s}}if(t){const{isHomeTenant:r,...s}=xe(i.homeAccountId,i.localAccountId,i.tenantId,t);return o={...o,...s,idTokenClaims:t,idToken:n},o}return o}const te={Default:0,Adfs:1,Dsts:2,Ciam:3};function qn(i){return i&&(i.tid||i.tfp||i.acr)||null}const V={AAD:"AAD",OIDC:"OIDC",EAR:"EAR"};class O{static getAccountInfo(e){const t=e.tenantProfiles||[];return t.length===0&&e.realm&&e.localAccountId&&t.push(xe(e.homeAccountId,e.localAccountId,e.realm)),{homeAccountId:e.homeAccountId,environment:e.environment,tenantId:e.realm,username:e.username,localAccountId:e.localAccountId,loginHint:e.loginHint,name:e.name,nativeAccountId:e.nativeAccountId,authorityType:e.authorityType,tenantProfiles:new Map(t.map(n=>[n.tenantId,n])),dataBoundary:e.dataBoundary}}isSingleTenant(){return!this.tenantProfiles}static createAccount(e,t,n){const o=new O;t.authorityType===te.Adfs?o.authorityType=ut.ADFS_ACCOUNT_TYPE:t.protocolMode===V.OIDC?o.authorityType=ut.GENERIC_ACCOUNT_TYPE:o.authorityType=ut.MSSTS_ACCOUNT_TYPE;let r;e.clientInfo&&n&&(r=_t(e.clientInfo,n),r.xms_tdbr&&(o.dataBoundary=r.xms_tdbr==="EU"?"EU":"None")),o.clientInfo=e.clientInfo,o.homeAccountId=e.homeAccountId,o.nativeAccountId=e.nativeAccountId;const s=e.environment||t&&t.getPreferredCache();if(!s)throw p(Un);o.environment=s,o.realm=r?.utid||qn(e.idTokenClaims)||"",o.localAccountId=r?.uid||e.idTokenClaims?.oid||e.idTokenClaims?.sub||"";const a=e.idTokenClaims?.preferred_username||e.idTokenClaims?.upn,c=e.idTokenClaims?.emails?e.idTokenClaims.emails[0]:null;if(o.username=a||c||"",o.loginHint=e.idTokenClaims?.login_hint,o.name=e.idTokenClaims?.name||"",o.cloudGraphHostName=e.cloudGraphHostName,o.msGraphHost=e.msGraphHost,e.tenantProfiles)o.tenantProfiles=e.tenantProfiles;else{const l=xe(e.homeAccountId,o.localAccountId,o.realm,e.idTokenClaims);o.tenantProfiles=[l]}return o}static createFromAccountInfo(e,t,n){const o=new O;o.authorityType=e.authorityType||ut.GENERIC_ACCOUNT_TYPE,o.homeAccountId=e.homeAccountId,o.localAccountId=e.localAccountId,o.nativeAccountId=e.nativeAccountId,o.realm=e.tenantId,o.environment=e.environment,o.username=e.username,o.name=e.name,o.loginHint=e.loginHint,o.cloudGraphHostName=t,o.msGraphHost=n;const r=Array.from(e.tenantProfiles?.values()||[]);return r.length===0&&e.tenantId&&e.localAccountId&&r.push(xe(e.homeAccountId,e.localAccountId,e.tenantId,e.idTokenClaims)),o.tenantProfiles=r,o.dataBoundary=e.dataBoundary,o}static generateHomeAccountId(e,t,n,o,r){if(!(t===te.Adfs||t===te.Dsts)){if(e)try{const s=_t(e,o.base64Decode);if(s.uid&&s.utid)return`${s.uid}.${s.utid}`}catch{}n.warning("No client info in response")}return r?.sub||""}static isAccountEntity(e){return e?e.hasOwnProperty("homeAccountId")&&e.hasOwnProperty("environment")&&e.hasOwnProperty("realm")&&e.hasOwnProperty("localAccountId")&&e.hasOwnProperty("username")&&e.hasOwnProperty("authorityType"):!1}static accountInfoIsEqual(e,t,n){if(!e||!t)return!1;let o=!0;if(n){const r=e.idTokenClaims||{},s=t.idTokenClaims||{};o=r.iat===s.iat&&r.nonce===s.nonce}return e.homeAccountId===t.homeAccountId&&e.localAccountId===t.localAccountId&&e.username===t.username&&e.tenantId===t.tenantId&&e.loginHint===t.loginHint&&e.environment===t.environment&&e.nativeAccountId===t.nativeAccountId&&o}}function se(i,e){const t=na(i);try{const n=e(t);return JSON.parse(n)}catch{throw p(On)}}function ae(i){if(!i.signin_state)return!1;const e=["kmsi","dvc_dmjd"];return i.signin_state.some(n=>e.includes(n.trim().toLowerCase()))}function na(i){if(!i)throw p(kr);const t=/^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/.exec(i);if(!t||t.length<4)throw p(On);return t[2]}function oi(i,e){if(e===0||Date.now()-3e5>i+e)throw p(Or)}function Go(i){if(!i)return i;let e=i.toLowerCase();return J.endsWith(e,"?")?e=e.slice(0,-1):J.endsWith(e,"?/")&&(e=e.slice(0,-2)),J.endsWith(e,"/")||(e+="/"),e}function ri(i){return i.startsWith("#/")?i.substring(2):i.startsWith("#")||i.startsWith("?")?i.substring(1):i}function Rt(i){if(!i||i.indexOf("=")<0)return null;try{const e=ri(i),t=Object.fromEntries(new URLSearchParams(e));if(t.code||t.ear_jwe||t.error||t.error_description||t.state)return t}catch{throw p(Rr)}return null}function rt(i,e=!0,t){const n=new Array;return i.forEach((o,r)=>{!e&&t&&r in t?n.push(`${r}=${o}`):n.push(`${r}=${encodeURIComponent(o)}`)}),n.join("&")}function zo(i){if(!i)return i;const e=i.split("#")[0];try{const t=new URL(e),n=t.origin+t.pathname+t.search;return Go(n)}catch{return Go(e)}}class k{get urlString(){return this._urlString}constructor(e){if(this._urlString=e,!this._urlString)throw _(qr);e.includes("#")||(this._urlString=k.canonicalizeUri(e))}static canonicalizeUri(e){if(e){let t=e.toLowerCase();return J.endsWith(t,"?")?t=t.slice(0,-1):J.endsWith(t,"?/")&&(t=t.slice(0,-2)),J.endsWith(t,"/")||(t+="/"),t}return e}validateAsUri(){let e;try{e=this.getUrlComponents()}catch{throw _(Xe)}if(!e.HostNameAndPort||!e.PathSegments)throw _(Xe);if(!e.Protocol||e.Protocol.toLowerCase()!=="https:")throw _(zr)}static appendQueryString(e,t){return t?e.indexOf("?")<0?`${e}?${t}`:`${e}&${t}`:e}static removeHashFromUrl(e){return k.canonicalizeUri(e.split("#")[0])}replaceTenantPath(e){const t=this.getUrlComponents(),n=t.PathSegments;return e&&n.length!==0&&(n[0]===Ce.COMMON||n[0]===Ce.ORGANIZATIONS)&&(n[0]=e),k.constructAuthorityUriFromObject(t)}getUrlComponents(){const e=RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"),t=this.urlString.match(e);if(!t)throw _(Xe);const n={Protocol:t[1],HostNameAndPort:t[4],AbsolutePath:t[5],QueryString:t[7]};let o=n.AbsolutePath.split("/");return o=o.filter(r=>r&&r.length>0),n.PathSegments=o,n.QueryString&&n.QueryString.endsWith("/")&&(n.QueryString=n.QueryString.substring(0,n.QueryString.length-1)),n}static getDomainFromUrl(e){const t=RegExp("^([^:/?#]+://)?([^/?#]*)"),n=e.match(t);if(!n)throw _(Xe);return n[2]}static getAbsoluteUrl(e,t){if(e[0]===f.FORWARD_SLASH){const o=new k(t).getUrlComponents();return o.Protocol+"//"+o.HostNameAndPort+e}return e}static constructAuthorityUriFromObject(e){return new k(e.Protocol+"//"+e.HostNameAndPort+"/"+e.PathSegments.join("/"))}static hashContainsKnownProperties(e){return!!Rt(e)}}const ii={endpointMetadata:{"login.microsoftonline.com":{token_endpoint:"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.microsoftonline.com/{tenantid}/discovery/v2.0/keys",issuer:"https://login.microsoftonline.com/{tenantid}/v2.0",authorization_endpoint:"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/logout"},"login.chinacloudapi.cn":{token_endpoint:"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.chinacloudapi.cn/{tenantid}/discovery/v2.0/keys",issuer:"https://login.partner.microsoftonline.cn/{tenantid}/v2.0",authorization_endpoint:"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/logout"},"login.microsoftonline.us":{token_endpoint:"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.microsoftonline.us/{tenantid}/discovery/v2.0/keys",issuer:"https://login.microsoftonline.us/{tenantid}/v2.0",authorization_endpoint:"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/logout"},"login.sovcloud-identity.fr":{token_endpoint:"https://login.sovcloud-identity.fr/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.sovcloud-identity.fr/{tenantid}/discovery/v2.0/keys",issuer:"https://login.sovcloud-identity.fr/{tenantid}/v2.0",authorization_endpoint:"https://login.sovcloud-identity.fr/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.sovcloud-identity.fr/{tenantid}/oauth2/v2.0/logout"},"login.sovcloud-identity.de":{token_endpoint:"https://login.sovcloud-identity.de/{tenantid}/oauth2/v2.0/token",jwks_uri:"https://login.sovcloud-identity.de/{tenantid}/discovery/v2.0/keys",issuer:"https://login.sovcloud-identity.de/{tenantid}/v2.0",authorization_endpoint:"https://login.sovcloud-identity.de/{tenantid}/oauth2/v2.0/authorize",end_session_endpoint:"https://login.sovcloud-identity.de/{tenantid}/oauth2/v2.0/logout"},"login.sovcloud-identity.sg":{token_endpoint:"https://login.sovcloud-identity.sg/common/oauth2/v2.0/token",jwks_uri:"https://login.sovcloud-identity.sg/common/discovery/v2.0/keys",issuer:"https://login.sovcloud-identity.sg/{tenantid}/v2.0",authorization_endpoint:"https://login.sovcloud-identity.sg/common/oauth2/v2.0/authorize",end_session_endpoint:"https://login.sovcloud-identity.sg/common/oauth2/v2.0/logout"}},instanceDiscoveryMetadata:{metadata:[{preferred_network:"login.microsoftonline.com",preferred_cache:"login.windows.net",aliases:["login.microsoftonline.com","login.windows.net","login.microsoft.com","sts.windows.net"]},{preferred_network:"login.partner.microsoftonline.cn",preferred_cache:"login.partner.microsoftonline.cn",aliases:["login.partner.microsoftonline.cn","login.chinacloudapi.cn"]},{preferred_network:"login.microsoftonline.de",preferred_cache:"login.microsoftonline.de",aliases:["login.microsoftonline.de"]},{preferred_network:"login.microsoftonline.us",preferred_cache:"login.microsoftonline.us",aliases:["login.microsoftonline.us","login.usgovcloudapi.net"]},{preferred_network:"login-us.microsoftonline.com",preferred_cache:"login-us.microsoftonline.com",aliases:["login-us.microsoftonline.com"]},{preferred_network:"login.sovcloud-identity.fr",preferred_cache:"login.sovcloud-identity.fr",aliases:["login.sovcloud-identity.fr"]},{preferred_network:"login.sovcloud-identity.de",preferred_cache:"login.sovcloud-identity.de",aliases:["login.sovcloud-identity.de"]},{preferred_network:"login.sovcloud-identity.sg",preferred_cache:"login.sovcloud-identity.sg",aliases:["login.sovcloud-identity.sg"]}]}},qo=ii.endpointMetadata,$n=ii.instanceDiscoveryMetadata,si=new Set;$n.metadata.forEach(i=>{i.aliases.forEach(e=>{si.add(e)})});function oa(i,e){let t;const n=i.canonicalAuthority;if(n){const o=new k(n).getUrlComponents().HostNameAndPort;t=$o(o,i.cloudDiscoveryMetadata?.metadata,Y.CONFIG,e)||$o(o,$n.metadata,Y.HARDCODED_VALUES,e)||i.knownAuthorities}return t||[]}function $o(i,e,t,n){if(n?.trace(`getAliasesFromMetadata called with source: ${t}`),i&&e){const o=bt(e,i);if(o)return n?.trace(`getAliasesFromMetadata: found cloud discovery metadata in ${t}, returning aliases`),o.aliases;n?.trace(`getAliasesFromMetadata: did not find cloud discovery metadata in ${t}`)}return null}function ra(i){return bt($n.metadata,i)}function bt(i,e){for(let t=0;t<i.length;t++){const n=i[t];if(n.aliases.includes(e))return n}return null}const Pt="cache_quota_exceeded",Qn="cache_error_unknown";const ln={[Pt]:"Exceeded cache storage capacity.",[Qn]:"Unexpected error occurred when using cache storage."};class Fe extends R{constructor(e,t){const n=t||(ln[e]?ln[e]:ln[Qn]);super(`${e}: ${n}`),Object.setPrototypeOf(this,Fe.prototype),this.name="CacheError",this.errorCode=e,this.errorMessage=n}}function Tn(i){return i instanceof Error?i.name==="QuotaExceededError"||i.name==="NS_ERROR_DOM_QUOTA_REACHED"||i.message.includes("exceeded the quota")?new Fe(Pt):new Fe(i.name,i.message):new Fe(Qn)}class An{constructor(e,t,n,o,r){this.clientId=e,this.cryptoImpl=t,this.commonLogger=n.clone(Br,Hn),this.staticAuthorityOptions=r,this.performanceClient=o}getAllAccounts(e,t){return this.buildTenantProfiles(this.getAccountsFilteredBy(e,t),t,e)}getAccountInfoFilteredBy(e,t){if(Object.keys(e).length===0||Object.values(e).every(o=>!o))return this.commonLogger.warning("getAccountInfoFilteredBy: Account filter is empty or invalid, returning null"),null;const n=this.getAllAccounts(e,t);return n.length>1?n.sort(r=>r.idTokenClaims?-1:1)[0]:n.length===1?n[0]:null}getBaseAccountInfo(e,t){const n=this.getAccountsFilteredBy(e,t);return n.length>0?O.getAccountInfo(n[0]):null}buildTenantProfiles(e,t,n){return e.flatMap(o=>this.getTenantProfilesFromAccountEntity(o,t,n?.tenantId,n))}getTenantedAccountInfoByFilter(e,t,n,o,r){let s=null,a;if(r&&!this.tenantProfileMatchesFilter(n,r))return null;const c=this.getIdToken(e,o,t,n.tenantId);return c&&(a=se(c.secret,this.cryptoImpl.base64Decode),!this.idTokenClaimsMatchTenantProfileFilter(a,r))?null:(s=zn(e,n,a,c?.secret),s)}getTenantProfilesFromAccountEntity(e,t,n,o){const r=O.getAccountInfo(e);let s=r.tenantProfiles||new Map;const a=this.getTokenKeys();if(n){const l=s.get(n);if(l)s=new Map([[n,l]]);else return[]}const c=[];return s.forEach(l=>{const d=this.getTenantedAccountInfoByFilter(r,a,l,t,o);d&&c.push(d)}),c}tenantProfileMatchesFilter(e,t){return!(t.localAccountId&&!this.matchLocalAccountIdFromTenantProfile(e,t.localAccountId)||t.name&&e.name!==t.name||t.isHomeTenant!==void 0&&e.isHomeTenant!==t.isHomeTenant)}idTokenClaimsMatchTenantProfileFilter(e,t){return!(t&&(t.localAccountId&&!this.matchLocalAccountIdFromTokenClaims(e,t.localAccountId)||t.loginHint&&!this.matchLoginHintFromTokenClaims(e,t.loginHint)||t.username&&!this.matchUsername(e.preferred_username,t.username)||t.name&&!this.matchName(e,t.name)||t.sid&&!this.matchSid(e,t.sid)))}async saveCacheRecord(e,t,n,o,r){if(!e)throw p(Lr);try{e.account&&await this.setAccount(e.account,t,n,o),e.idToken&&r?.idToken!==!1&&await this.setIdTokenCredential(e.idToken,t,n),e.accessToken&&r?.accessToken!==!1&&await this.saveAccessToken(e.accessToken,t,n),e.refreshToken&&r?.refreshToken!==!1&&await this.setRefreshTokenCredential(e.refreshToken,t,n),e.appMetadata&&this.setAppMetadata(e.appMetadata,t)}catch(s){throw this.commonLogger?.error("CacheManager.saveCacheRecord: failed"),s instanceof R?s:Tn(s)}}async saveAccessToken(e,t,n){const o={clientId:e.clientId,credentialType:e.credentialType,environment:e.environment,homeAccountId:e.homeAccountId,realm:e.realm,tokenType:e.tokenType,requestedClaimsHash:e.requestedClaimsHash},r=this.getTokenKeys(),s=M.fromString(e.target);r.accessToken.forEach(a=>{if(!this.accessTokenKeyMatchesFilter(a,o,!1))return;const c=this.getAccessTokenCredential(a,t);c&&this.credentialMatchesFilter(c,o)&&M.fromString(c.target).intersectingScopeSets(s)&&this.removeAccessToken(a,t)}),await this.setAccessTokenCredential(e,t,n)}getAccountsFilteredBy(e,t){const n=this.getAccountKeys(),o=[];return n.forEach(r=>{const s=this.getAccount(r,t);if(!s||e.homeAccountId&&!this.matchHomeAccountId(s,e.homeAccountId)||e.username&&!this.matchUsername(s.username,e.username)||e.environment&&!this.matchEnvironment(s,e.environment)||e.realm&&!this.matchRealm(s,e.realm)||e.nativeAccountId&&!this.matchNativeAccountId(s,e.nativeAccountId)||e.authorityType&&!this.matchAuthorityType(s,e.authorityType))return;const a={localAccountId:e?.localAccountId,name:e?.name},c=s.tenantProfiles?.filter(l=>this.tenantProfileMatchesFilter(l,a));c&&c.length===0||o.push(s)}),o}credentialMatchesFilter(e,t){return!(t.clientId&&!this.matchClientId(e,t.clientId)||t.userAssertionHash&&!this.matchUserAssertionHash(e,t.userAssertionHash)||typeof t.homeAccountId=="string"&&!this.matchHomeAccountId(e,t.homeAccountId)||t.environment&&!this.matchEnvironment(e,t.environment)||t.realm&&!this.matchRealm(e,t.realm)||t.credentialType&&!this.matchCredentialType(e,t.credentialType)||t.familyId&&!this.matchFamilyId(e,t.familyId)||t.target&&!this.matchTarget(e,t.target)||(t.requestedClaimsHash||e.requestedClaimsHash)&&e.requestedClaimsHash!==t.requestedClaimsHash||e.credentialType===H.ACCESS_TOKEN_WITH_AUTH_SCHEME&&(t.tokenType&&!this.matchTokenType(e,t.tokenType)||t.tokenType===v.SSH&&t.keyId&&!this.matchKeyId(e,t.keyId)))}getAppMetadataFilteredBy(e){const t=this.getKeys(),n={};return t.forEach(o=>{if(!this.isAppMetadata(o))return;const r=this.getAppMetadata(o);r&&(e.environment&&!this.matchEnvironment(r,e.environment)||e.clientId&&!this.matchClientId(r,e.clientId)||(n[o]=r))}),n}getAuthorityMetadataByAlias(e){const t=this.getAuthorityMetadataKeys();let n=null;return t.forEach(o=>{if(!this.isAuthorityMetadata(o)||o.indexOf(this.clientId)===-1)return;const r=this.getAuthorityMetadata(o);r&&r.aliases.indexOf(e)!==-1&&(n=r)}),n}removeAllAccounts(e){this.getAllAccounts({},e).forEach(n=>{this.removeAccount(n,e)})}removeAccount(e,t){this.removeAccountContext(e,t);const n=this.getAccountKeys(),o=r=>r.includes(e.homeAccountId)&&r.includes(e.environment);n.filter(o).forEach(r=>{this.removeItem(r,t),this.performanceClient.incrementFields({accountsRemoved:1},t)})}removeAccountContext(e,t){const n=this.getTokenKeys(),o=r=>r.includes(e.homeAccountId)&&r.includes(e.environment);n.idToken.filter(o).forEach(r=>{this.removeIdToken(r,t)}),n.accessToken.filter(o).forEach(r=>{this.removeAccessToken(r,t)}),n.refreshToken.filter(o).forEach(r=>{this.removeRefreshToken(r,t)})}removeAccessToken(e,t){const n=this.getAccessTokenCredential(e,t);if(this.removeItem(e,t),this.performanceClient.incrementFields({accessTokensRemoved:1},t),!n||n.credentialType.toLowerCase()!==H.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()||n.tokenType!==v.POP)return;const o=n.keyId;o&&this.cryptoImpl.removeTokenBindingKey(o).catch(()=>{this.commonLogger.error(`Failed to remove token binding key ${o}`,t),this.performanceClient?.incrementFields({removeTokenBindingKeyFailure:1},t)})}removeAppMetadata(e){return this.getKeys().forEach(n=>{this.isAppMetadata(n)&&this.removeItem(n,e)}),!0}getIdToken(e,t,n,o,r){this.commonLogger.trace("CacheManager - getIdToken called");const s={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:H.ID_TOKEN,clientId:this.clientId,realm:o},a=this.getIdTokensByFilter(s,t,n),c=a.size;if(c<1)return this.commonLogger.info("CacheManager:getIdToken - No token found"),null;if(c>1){let l=a;if(!o){const d=new Map;a.forEach((m,C)=>{m.realm===e.tenantId&&d.set(C,m)});const u=d.size;if(u<1)return this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account but none match account entity tenant id, returning first result"),a.values().next().value;if(u===1)return this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account, defaulting to home tenant profile"),d.values().next().value;l=d}return this.commonLogger.info("CacheManager:getIdToken - Multiple matching ID tokens found, clearing them"),l.forEach((d,u)=>{this.removeIdToken(u,t)}),r&&t&&r.addFields({multiMatchedID:a.size},t),null}return this.commonLogger.info("CacheManager:getIdToken - Returning ID token"),a.values().next().value}getIdTokensByFilter(e,t,n){const o=n&&n.idToken||this.getTokenKeys().idToken,r=new Map;return o.forEach(s=>{if(!this.idTokenKeyMatchesFilter(s,{clientId:this.clientId,...e}))return;const a=this.getIdTokenCredential(s,t);a&&this.credentialMatchesFilter(a,e)&&r.set(s,a)}),r}idTokenKeyMatchesFilter(e,t){const n=e.toLowerCase();return!(t.clientId&&n.indexOf(t.clientId.toLowerCase())===-1||t.homeAccountId&&n.indexOf(t.homeAccountId.toLowerCase())===-1)}removeIdToken(e,t){this.removeItem(e,t)}removeRefreshToken(e,t){this.removeItem(e,t)}getAccessToken(e,t,n,o){const r=t.correlationId;this.commonLogger.trace("CacheManager - getAccessToken called",r);const s=M.createSearchScopes(t.scopes),a=t.authenticationScheme||v.BEARER,c=a.toLowerCase()!==v.BEARER.toLowerCase()?H.ACCESS_TOKEN_WITH_AUTH_SCHEME:H.ACCESS_TOKEN,l={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:c,clientId:this.clientId,realm:o||e.tenantId,target:s,tokenType:a,keyId:t.sshKid,requestedClaimsHash:t.requestedClaimsHash},d=n&&n.accessToken||this.getTokenKeys().accessToken,u=[];d.forEach(C=>{if(this.accessTokenKeyMatchesFilter(C,l,!0)){const E=this.getAccessTokenCredential(C,r);E&&this.credentialMatchesFilter(E,l)&&u.push(E)}});const m=u.length;return m<1?(this.commonLogger.info("CacheManager:getAccessToken - No token found",r),null):m>1?(this.commonLogger.info("CacheManager:getAccessToken - Multiple access tokens found, clearing them",r),u.forEach(C=>{this.removeAccessToken(this.generateCredentialKey(C),r)}),this.performanceClient.addFields({multiMatchedAT:u.length},r),null):(this.commonLogger.info("CacheManager:getAccessToken - Returning access token",r),u[0])}accessTokenKeyMatchesFilter(e,t,n){const o=e.toLowerCase();if(t.clientId&&o.indexOf(t.clientId.toLowerCase())===-1||t.homeAccountId&&o.indexOf(t.homeAccountId.toLowerCase())===-1||t.realm&&o.indexOf(t.realm.toLowerCase())===-1||t.requestedClaimsHash&&o.indexOf(t.requestedClaimsHash.toLowerCase())===-1)return!1;if(t.target){const r=t.target.asArray();for(let s=0;s<r.length;s++){if(n&&!o.includes(r[s].toLowerCase()))return!1;if(!n&&o.includes(r[s].toLowerCase()))return!0}}return!0}getAccessTokensByFilter(e,t){const n=this.getTokenKeys(),o=[];return n.accessToken.forEach(r=>{if(!this.accessTokenKeyMatchesFilter(r,e,!0))return;const s=this.getAccessTokenCredential(r,t);s&&this.credentialMatchesFilter(s,e)&&o.push(s)}),o}getRefreshToken(e,t,n,o,r){this.commonLogger.trace("CacheManager - getRefreshToken called");const s=t?Et:void 0,a={homeAccountId:e.homeAccountId,environment:e.environment,credentialType:H.REFRESH_TOKEN,clientId:this.clientId,familyId:s},c=o&&o.refreshToken||this.getTokenKeys().refreshToken,l=[];c.forEach(u=>{if(this.refreshTokenKeyMatchesFilter(u,a)){const m=this.getRefreshTokenCredential(u,n);m&&this.credentialMatchesFilter(m,a)&&l.push(m)}});const d=l.length;return d<1?(this.commonLogger.info("CacheManager:getRefreshToken - No refresh token found."),null):(d>1&&r&&n&&r.addFields({multiMatchedRT:d},n),this.commonLogger.info("CacheManager:getRefreshToken - returning refresh token"),l[0])}refreshTokenKeyMatchesFilter(e,t){const n=e.toLowerCase();return!(t.familyId&&n.indexOf(t.familyId.toLowerCase())===-1||!t.familyId&&t.clientId&&n.indexOf(t.clientId.toLowerCase())===-1||t.homeAccountId&&n.indexOf(t.homeAccountId.toLowerCase())===-1)}readAppMetadataFromCache(e){const t={environment:e,clientId:this.clientId},n=this.getAppMetadataFilteredBy(t),o=Object.keys(n).map(s=>n[s]),r=o.length;if(r<1)return null;if(r>1)throw p(Nr);return o[0]}isAppMetadataFOCI(e){const t=this.readAppMetadataFromCache(e);return!!(t&&t.familyId===Et)}matchHomeAccountId(e,t){return typeof e.homeAccountId=="string"&&t===e.homeAccountId}matchLocalAccountIdFromTokenClaims(e,t){const n=e.oid||e.sub;return t===n}matchLocalAccountIdFromTenantProfile(e,t){return e.localAccountId===t}matchName(e,t){return t.toLowerCase()===e.name?.toLowerCase()}matchUsername(e,t){return!!(e&&typeof e=="string"&&t?.toLowerCase()===e.toLowerCase())}matchUserAssertionHash(e,t){return!!(e.userAssertionHash&&t===e.userAssertionHash)}matchEnvironment(e,t){if(this.staticAuthorityOptions){const o=oa(this.staticAuthorityOptions,this.commonLogger);if(o.includes(t)&&o.includes(e.environment))return!0}const n=this.getAuthorityMetadataByAlias(t);return!!(n&&n.aliases.indexOf(e.environment)>-1)}matchCredentialType(e,t){return e.credentialType&&t.toLowerCase()===e.credentialType.toLowerCase()}matchClientId(e,t){return!!(e.clientId&&t===e.clientId)}matchFamilyId(e,t){return!!(e.familyId&&t===e.familyId)}matchRealm(e,t){return e.realm?.toLowerCase()===t.toLowerCase()}matchNativeAccountId(e,t){return!!(e.nativeAccountId&&t===e.nativeAccountId)}matchLoginHintFromTokenClaims(e,t){return e.login_hint===t||e.preferred_username===t||e.upn===t}matchSid(e,t){return e.sid===t}matchAuthorityType(e,t){return!!(e.authorityType&&t.toLowerCase()===e.authorityType.toLowerCase())}matchTarget(e,t){return e.credentialType!==H.ACCESS_TOKEN&&e.credentialType!==H.ACCESS_TOKEN_WITH_AUTH_SCHEME||!e.target?!1:M.fromString(e.target).containsScopeSet(t)}matchTokenType(e,t){return!!(e.tokenType&&e.tokenType===t)}matchKeyId(e,t){return!!(e.keyId&&e.keyId===t)}isAppMetadata(e){return e.indexOf(bn)!==-1}isAuthorityMetadata(e){return e.indexOf(St.CACHE_KEY)!==-1}generateAuthorityMetadataCacheKey(e){return`${St.CACHE_KEY}-${this.clientId}-${e}`}static toObject(e,t){for(const n in t)e[n]=t[n];return e}}class ia extends An{async setAccount(){throw p(w)}getAccount(){throw p(w)}async setIdTokenCredential(){throw p(w)}getIdTokenCredential(){throw p(w)}async setAccessTokenCredential(){throw p(w)}getAccessTokenCredential(){throw p(w)}async setRefreshTokenCredential(){throw p(w)}getRefreshTokenCredential(){throw p(w)}setAppMetadata(){throw p(w)}getAppMetadata(){throw p(w)}setServerTelemetry(){throw p(w)}getServerTelemetry(){throw p(w)}setAuthorityMetadata(){throw p(w)}getAuthorityMetadata(){throw p(w)}getAuthorityMetadataKeys(){throw p(w)}setThrottlingCache(){throw p(w)}getThrottlingCache(){throw p(w)}removeItem(){throw p(w)}getKeys(){throw p(w)}getAccountKeys(){throw p(w)}getTokenKeys(){throw p(w)}generateCredentialKey(){throw p(w)}generateAccountKey(){throw p(w)}}const h={AcquireTokenByCode:"acquireTokenByCode",AcquireTokenByRefreshToken:"acquireTokenByRefreshToken",AcquireTokenSilent:"acquireTokenSilent",AcquireTokenSilentAsync:"acquireTokenSilentAsync",AcquireTokenPopup:"acquireTokenPopup",AcquireTokenPreRedirect:"acquireTokenPreRedirect",AcquireTokenRedirect:"acquireTokenRedirect",CryptoOptsGetPublicKeyThumbprint:"cryptoOptsGetPublicKeyThumbprint",CryptoOptsSignJwt:"cryptoOptsSignJwt",SilentCacheClientAcquireToken:"silentCacheClientAcquireToken",SilentIframeClientAcquireToken:"silentIframeClientAcquireToken",AwaitConcurrentIframe:"awaitConcurrentIframe",SilentRefreshClientAcquireToken:"silentRefreshClientAcquireToken",SsoSilent:"ssoSilent",StandardInteractionClientGetDiscoveredAuthority:"standardInteractionClientGetDiscoveredAuthority",FetchAccountIdWithNativeBroker:"fetchAccountIdWithNativeBroker",NativeInteractionClientAcquireToken:"nativeInteractionClientAcquireToken",BaseClientCreateTokenRequestHeaders:"baseClientCreateTokenRequestHeaders",NetworkClientSendPostRequestAsync:"networkClientSendPostRequestAsync",RefreshTokenClientExecutePostToTokenEndpoint:"refreshTokenClientExecutePostToTokenEndpoint",AuthorizationCodeClientExecutePostToTokenEndpoint:"authorizationCodeClientExecutePostToTokenEndpoint",BrokerHandhshake:"brokerHandshake",AcquireTokenByRefreshTokenInBroker:"acquireTokenByRefreshTokenInBroker",AcquireTokenByBroker:"acquireTokenByBroker",RefreshTokenClientExecuteTokenRequest:"refreshTokenClientExecuteTokenRequest",RefreshTokenClientAcquireToken:"refreshTokenClientAcquireToken",RefreshTokenClientAcquireTokenWithCachedRefreshToken:"refreshTokenClientAcquireTokenWithCachedRefreshToken",RefreshTokenClientAcquireTokenByRefreshToken:"refreshTokenClientAcquireTokenByRefreshToken",RefreshTokenClientCreateTokenRequestBody:"refreshTokenClientCreateTokenRequestBody",AcquireTokenFromCache:"acquireTokenFromCache",SilentFlowClientAcquireCachedToken:"silentFlowClientAcquireCachedToken",SilentFlowClientGenerateResultFromCacheRecord:"silentFlowClientGenerateResultFromCacheRecord",AcquireTokenBySilentIframe:"acquireTokenBySilentIframe",InitializeBaseRequest:"initializeBaseRequest",InitializeSilentRequest:"initializeSilentRequest",InitializeClientApplication:"initializeClientApplication",InitializeCache:"initializeCache",SilentIframeClientTokenHelper:"silentIframeClientTokenHelper",SilentHandlerInitiateAuthRequest:"silentHandlerInitiateAuthRequest",SilentHandlerMonitorIframeForHash:"silentHandlerMonitorIframeForHash",SilentHandlerLoadFrame:"silentHandlerLoadFrame",SilentHandlerLoadFrameSync:"silentHandlerLoadFrameSync",StandardInteractionClientCreateAuthCodeClient:"standardInteractionClientCreateAuthCodeClient",StandardInteractionClientGetClientConfiguration:"standardInteractionClientGetClientConfiguration",StandardInteractionClientInitializeAuthorizationRequest:"standardInteractionClientInitializeAuthorizationRequest",GetAuthCodeUrl:"getAuthCodeUrl",GetStandardParams:"getStandardParams",HandleCodeResponseFromServer:"handleCodeResponseFromServer",HandleCodeResponse:"handleCodeResponse",HandleResponseEar:"handleResponseEar",HandleResponsePlatformBroker:"handleResponsePlatformBroker",HandleResponseCode:"handleResponseCode",UpdateTokenEndpointAuthority:"updateTokenEndpointAuthority",AuthClientAcquireToken:"authClientAcquireToken",AuthClientExecuteTokenRequest:"authClientExecuteTokenRequest",AuthClientCreateTokenRequestBody:"authClientCreateTokenRequestBody",PopTokenGenerateCnf:"popTokenGenerateCnf",PopTokenGenerateKid:"popTokenGenerateKid",HandleServerTokenResponse:"handleServerTokenResponse",DeserializeResponse:"deserializeResponse",AuthorityFactoryCreateDiscoveredInstance:"authorityFactoryCreateDiscoveredInstance",AuthorityResolveEndpointsAsync:"authorityResolveEndpointsAsync",AuthorityResolveEndpointsFromLocalSources:"authorityResolveEndpointsFromLocalSources",AuthorityGetCloudDiscoveryMetadataFromNetwork:"authorityGetCloudDiscoveryMetadataFromNetwork",AuthorityUpdateCloudDiscoveryMetadata:"authorityUpdateCloudDiscoveryMetadata",AuthorityGetEndpointMetadataFromNetwork:"authorityGetEndpointMetadataFromNetwork",AuthorityUpdateEndpointMetadata:"authorityUpdateEndpointMetadata",AuthorityUpdateMetadataWithRegionalInformation:"authorityUpdateMetadataWithRegionalInformation",RegionDiscoveryDetectRegion:"regionDiscoveryDetectRegion",RegionDiscoveryGetRegionFromIMDS:"regionDiscoveryGetRegionFromIMDS",RegionDiscoveryGetCurrentVersion:"regionDiscoveryGetCurrentVersion",AcquireTokenByCodeAsync:"acquireTokenByCodeAsync",GetEndpointMetadataFromNetwork:"getEndpointMetadataFromNetwork",GetCloudDiscoveryMetadataFromNetworkMeasurement:"getCloudDiscoveryMetadataFromNetworkMeasurement",HandleRedirectPromiseMeasurement:"handleRedirectPromise",HandleNativeRedirectPromiseMeasurement:"handleNativeRedirectPromise",UpdateCloudDiscoveryMetadataMeasurement:"updateCloudDiscoveryMetadataMeasurement",UsernamePasswordClientAcquireToken:"usernamePasswordClientAcquireToken",NativeMessageHandlerHandshake:"nativeMessageHandlerHandshake",NativeGenerateAuthResult:"nativeGenerateAuthResult",RemoveHiddenIframe:"removeHiddenIframe",ClearTokensAndKeysWithClaims:"clearTokensAndKeysWithClaims",CacheManagerGetRefreshToken:"cacheManagerGetRefreshToken",ImportExistingCache:"importExistingCache",SetUserData:"setUserData",LocalStorageUpdated:"localStorageUpdated",GeneratePkceCodes:"generatePkceCodes",GenerateCodeVerifier:"generateCodeVerifier",GenerateCodeChallengeFromVerifier:"generateCodeChallengeFromVerifier",Sha256Digest:"sha256Digest",GetRandomValues:"getRandomValues",GenerateHKDF:"generateHKDF",GenerateBaseKey:"generateBaseKey",Base64Decode:"base64Decode",UrlEncodeArr:"urlEncodeArr",Encrypt:"encrypt",Decrypt:"decrypt",GenerateEarKey:"generateEarKey",DecryptEarResponse:"decryptEarResponse",LoadExternalTokens:"LoadExternalTokens",LoadAccount:"loadAccount",LoadIdToken:"loadIdToken",LoadAccessToken:"loadAccessToken",LoadRefreshToken:"loadRefreshToken",SsoCapable:"ssoCapable"},sa={InProgress:1};class Qo{startMeasurement(){}endMeasurement(){}flushMeasurement(){return null}}class ai{generateId(){return"callback-id"}startMeasurement(e,t){return{end:()=>null,discard:()=>{},add:()=>{},increment:()=>{},event:{eventId:this.generateId(),status:sa.InProgress,authority:"",libraryName:"",libraryVersion:"",clientId:"",name:e,startTimeMs:Date.now(),correlationId:t||""},measurement:new Qo}}startPerformanceMeasurement(){return new Qo}calculateQueuedTime(){return 0}addQueueMeasurement(){}setPreQueueTime(){}endMeasurement(){return null}discardMeasurements(){}removePerformanceCallback(){return!0}addPerformanceCallback(){return""}emitEvents(){}addFields(){}incrementFields(){}cacheEventByCorrelationId(){}}const ci={tokenRenewalOffsetSeconds:Er,preventCorsPreflight:!1},aa={loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:b.Info,correlationId:f.EMPTY_STRING},ca={claimsBasedCachingEnabled:!1},la={async sendGetRequestAsync(){throw p(w)},async sendPostRequestAsync(){throw p(w)}},ha={sku:f.SKU,version:Hn,cpu:f.EMPTY_STRING,os:f.EMPTY_STRING},da={clientSecret:f.EMPTY_STRING,clientAssertion:void 0},ua={azureCloudInstance:xn.None,tenant:`${f.DEFAULT_COMMON_TENANT}`},ga={application:{appName:"",appVersion:""}};function fa({authOptions:i,systemOptions:e,loggerOptions:t,cacheOptions:n,storageInterface:o,networkInterface:r,cryptoInterface:s,clientCredentials:a,libraryInfo:c,telemetry:l,serverTelemetryManager:d,persistencePlugin:u,serializableCache:m}){const C={...aa,...t};return{authOptions:ma(i),systemOptions:{...ci,...e},loggerOptions:C,cacheOptions:{...ca,...n},storageInterface:o||new ia(i.clientId,vt,new we(C),new ai),networkInterface:r||la,cryptoInterface:s||vt,clientCredentials:a||da,libraryInfo:{...ha,...c},telemetry:{...ga,...l},serverTelemetryManager:d||null,persistencePlugin:u||null,serializableCache:m||null}}function ma(i){return{clientCapabilities:[],azureCloudOptions:ua,skipAuthorityMetadataCache:!1,instanceAware:!1,encodeExtraQueryParams:!1,...i}}function li(i){return i.authOptions.authority.options.protocolMode===V.OIDC}const ne={HOME_ACCOUNT_ID:"home_account_id",UPN:"UPN"};const Re="client_id",hi="redirect_uri",pa="response_type",Ca="response_mode",ya="grant_type",Ta="claims",Aa="scope",Ia="refresh_token",wa="state",Ea="nonce",Sa="prompt",ka="code",va="code_challenge",_a="code_challenge_method",Ra="code_verifier",ba="client-request-id",Pa="x-client-SKU",Oa="x-client-VER",Na="x-client-OS",Ma="x-client-CPU",Ua="x-client-current-telemetry",Da="x-client-last-telemetry",La="x-ms-lib-capability",Ha="x-app-name",xa="x-app-ver",Fa="post_logout_redirect_uri",Ka="id_token_hint",Ba="client_secret",Ga="client_assertion",za="client_assertion_type",di="token_type",ui="req_cnf",Vo="return_spa_code",qa="nativebroker",$a="logout_hint",Qa="sid",Va="login_hint",Wa="domain_hint",ja="x-client-xtra-sku",be="brk_client_id",Ot="brk_redirect_uri",In="instance_aware",Ya="ear_jwk",Ja="ear_jwe_crypto",Xa="clidata";function qt(i,e,t){if(!e)return;const n=i.get(Re);n&&i.has(be)&&t?.addFields({embeddedClientId:n,embeddedRedirectUri:i.get(hi)},e)}function Vn(i,e){i.set(pa,e)}function Za(i,e){i.set(Ca,e||Ms.QUERY)}function ec(i){i.set(qa,"1")}function Wn(i,e,t=!0,n=Ve){t&&!n.includes("openid")&&!e.includes("openid")&&n.push("openid");const o=t?[...e||[],...n]:e||[],r=new M(o);i.set(Aa,r.printScopes())}function jn(i,e){i.set(Re,e)}function Yn(i,e){i.set(hi,e)}function tc(i,e){i.set(Fa,e)}function nc(i,e){i.set(Ka,e)}function oc(i,e){i.set(Wa,e)}function gt(i,e){i.set(Va,e)}function Nt(i,e){i.set(G.CCS_HEADER,`UPN:${e}`)}function tt(i,e){i.set(G.CCS_HEADER,`Oid:${e.uid}@${e.utid}`)}function Wo(i,e){i.set(Qa,e)}function Jn(i,e,t){const n=Ti(e,t);try{JSON.parse(n)}catch{throw _(Fn)}i.set(Ta,n)}function lt(i,e){i.set(ba,e)}function Xn(i,e){i.set(Pa,e.sku),i.set(Oa,e.version),e.os&&i.set(Na,e.os),e.cpu&&i.set(Ma,e.cpu)}function Zn(i,e){e?.appName&&i.set(Ha,e.appName),e?.appVersion&&i.set(xa,e.appVersion)}function rc(i,e){i.set(Sa,e)}function gi(i,e){e&&i.set(wa,e)}function ic(i,e){i.set(Ea,e)}function eo(i,e,t){if(e&&t)i.set(va,e),i.set(_a,t);else throw _(Kn)}function sc(i,e){i.set(ka,e)}function ac(i,e){i.set(Ia,e)}function cc(i,e){i.set(Ra,e)}function fi(i,e){i.set(Ba,e)}function mi(i,e){e&&i.set(Ga,e)}function pi(i,e){e&&i.set(za,e)}function Ci(i,e){i.set(ya,e)}function to(i){i.set(Us,"1")}function lc(i){i.set(Xa,"1")}function yi(i){i.has(In)||i.set(In,"true")}function Te(i,e){Object.entries(e).forEach(([t,n])=>{!i.has(t)&&n&&i.set(t,n)})}function Ti(i,e){let t;if(!i)t={};else try{t=JSON.parse(i)}catch{throw _(Fn)}return e&&e.length>0&&(t.hasOwnProperty(dt.ACCESS_TOKEN)||(t[dt.ACCESS_TOKEN]={}),t[dt.ACCESS_TOKEN][dt.XMS_CC]={values:e}),JSON.stringify(t)}function no(i,e){e&&(i.set(di,v.POP),i.set(ui,e))}function Ai(i,e){e&&(i.set(di,v.SSH),i.set(ui,e))}function Ii(i,e){i.set(Ua,e.generateCurrentRequestHeaderValue()),i.set(Da,e.generateLastRequestHeaderValue())}function wi(i){i.set(La,et.X_MS_LIB_CAPABILITY_VALUE)}function hc(i,e){i.set($a,e)}function $t(i,e,t){i.has(be)||i.set(be,e),i.has(Ot)||i.set(Ot,t)}function dc(i,e){i.set(Ya,encodeURIComponent(e)),i.set(Ja,"eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0")}function uc(i,e){Object.entries(e).forEach(([t,n])=>{n&&i.set(t,n)})}function gc(i){return i.hasOwnProperty("authorization_endpoint")&&i.hasOwnProperty("token_endpoint")&&i.hasOwnProperty("issuer")&&i.hasOwnProperty("jwks_uri")}function fc(i){return i.hasOwnProperty("tenant_discovery_endpoint")&&i.hasOwnProperty("metadata")}function mc(i){return i.hasOwnProperty("error")&&i.hasOwnProperty("error_description")}const W=(i,e,t,n,o)=>(...r)=>{t.trace(`Executing function ${e}`);const s=n?.startMeasurement(e,o);if(o){const a=e+"CallCount";n?.incrementFields({[a]:1},o)}try{const a=i(...r);return s?.end({success:!0}),t.trace(`Returning result from ${e}`),a}catch(a){t.trace(`Error occurred in ${e}`);try{t.trace(JSON.stringify(a))}catch{t.trace("Unable to print error message.")}throw s?.end({success:!1},a),a}},g=(i,e,t,n,o)=>(...r)=>{t.trace(`Executing function ${e}`);const s=n?.startMeasurement(e,o);if(o){const a=e+"CallCount";n?.incrementFields({[a]:1},o)}return n?.setPreQueueTime(e,o),i(...r).then(a=>(t.trace(`Returning result from ${e}`),s?.end({success:!0}),a)).catch(a=>{t.trace(`Error occurred in ${e}`);try{t.trace(JSON.stringify(a))}catch{t.trace("Unable to print error message.")}throw s?.end({success:!1},a),a})};class Qt{constructor(e,t,n,o){this.networkInterface=e,this.logger=t,this.performanceClient=n,this.correlationId=o}async detectRegion(e,t){this.performanceClient?.addQueueMeasurement(h.RegionDiscoveryDetectRegion,this.correlationId);let n=e;if(n)t.region_source=Ue.ENVIRONMENT_VARIABLE;else{const o=Qt.IMDS_OPTIONS;try{const r=await g(this.getRegionFromIMDS.bind(this),h.RegionDiscoveryGetRegionFromIMDS,this.logger,this.performanceClient,this.correlationId)(f.IMDS_VERSION,o);if(r.status===pe.SUCCESS&&(n=r.body,t.region_source=Ue.IMDS),r.status===pe.BAD_REQUEST){const s=await g(this.getCurrentVersion.bind(this),h.RegionDiscoveryGetCurrentVersion,this.logger,this.performanceClient,this.correlationId)(o);if(!s)return t.region_source=Ue.FAILED_AUTO_DETECTION,null;const a=await g(this.getRegionFromIMDS.bind(this),h.RegionDiscoveryGetRegionFromIMDS,this.logger,this.performanceClient,this.correlationId)(s,o);a.status===pe.SUCCESS&&(n=a.body,t.region_source=Ue.IMDS)}}catch{return t.region_source=Ue.FAILED_AUTO_DETECTION,null}}return n||(t.region_source=Ue.FAILED_AUTO_DETECTION),n||null}async getRegionFromIMDS(e,t){return this.performanceClient?.addQueueMeasurement(h.RegionDiscoveryGetRegionFromIMDS,this.correlationId),this.networkInterface.sendGetRequestAsync(`${f.IMDS_ENDPOINT}?api-version=${e}&format=text`,t,f.IMDS_TIMEOUT)}async getCurrentVersion(e){this.performanceClient?.addQueueMeasurement(h.RegionDiscoveryGetCurrentVersion,this.correlationId);try{const t=await this.networkInterface.sendGetRequestAsync(`${f.IMDS_ENDPOINT}?format=json`,e);return t.status===pe.BAD_REQUEST&&t.body&&t.body["newest-versions"]&&t.body["newest-versions"].length>0?t.body["newest-versions"][0]:null}catch{return null}}}Qt.IMDS_OPTIONS={headers:{Metadata:"true"}};function $(){return Math.round(new Date().getTime()/1e3)}function jo(i){return i.getTime()/1e3}function Ke(i){return i?new Date(Number(i)*1e3):new Date}function Mt(i,e){const t=Number(i)||0;return $()+e>t}function Yo(i,e){const t=Number(i)+e*24*60*60*1e3;return Date.now()>t}function pc(i){return Number(i)>$()}function Vt(i,e,t,n,o){return{credentialType:H.ID_TOKEN,homeAccountId:i,environment:e,clientId:n,secret:t,realm:o,lastUpdatedAt:Date.now().toString()}}function Wt(i,e,t,n,o,r,s,a,c,l,d,u,m,C,E){const I={homeAccountId:i,credentialType:H.ACCESS_TOKEN,secret:t,cachedAt:$().toString(),expiresOn:s.toString(),extendedExpiresOn:a.toString(),environment:e,clientId:n,realm:o,target:r,tokenType:d||v.BEARER,lastUpdatedAt:Date.now().toString()};if(u&&(I.userAssertionHash=u),l&&(I.refreshOn=l.toString()),C&&(I.requestedClaims=C,I.requestedClaimsHash=E),I.tokenType?.toLowerCase()!==v.BEARER.toLowerCase())switch(I.credentialType=H.ACCESS_TOKEN_WITH_AUTH_SCHEME,I.tokenType){case v.POP:const D=se(t,c);if(!D?.cnf?.kid)throw p(Hr);I.keyId=D.cnf.kid;break;case v.SSH:I.keyId=m}return I}function Ei(i,e,t,n,o,r,s){const a={credentialType:H.REFRESH_TOKEN,homeAccountId:i,environment:e,clientId:n,secret:t,lastUpdatedAt:Date.now().toString()};return r&&(a.userAssertionHash=r),o&&(a.familyId=o),s&&(a.expiresOn=s.toString()),a}function jt(i){return i.hasOwnProperty("homeAccountId")&&i.hasOwnProperty("environment")&&i.hasOwnProperty("credentialType")&&i.hasOwnProperty("clientId")&&i.hasOwnProperty("secret")}function Jo(i){return i?jt(i)&&i.hasOwnProperty("realm")&&i.hasOwnProperty("target")&&(i.credentialType===H.ACCESS_TOKEN||i.credentialType===H.ACCESS_TOKEN_WITH_AUTH_SCHEME):!1}function Cc(i){return i?jt(i)&&i.hasOwnProperty("realm")&&i.credentialType===H.ID_TOKEN:!1}function Xo(i){return i?jt(i)&&i.credentialType===H.REFRESH_TOKEN:!1}function yc(i,e){const t=i.indexOf(L.CACHE_KEY)===0;let n=!0;return e&&(n=e.hasOwnProperty("failedRequests")&&e.hasOwnProperty("errors")&&e.hasOwnProperty("cacheHits")),t&&n}function Tc(i,e){let t=!1;i&&(t=i.indexOf(et.THROTTLING_PREFIX)===0);let n=!0;return e&&(n=e.hasOwnProperty("throttleTime")),t&&n}function Ac({environment:i,clientId:e}){return[bn,i,e].join(ot.CACHE_KEY_SEPARATOR).toLowerCase()}function Ic(i,e){return e?i.indexOf(bn)===0&&e.hasOwnProperty("clientId")&&e.hasOwnProperty("environment"):!1}function wc(i,e){return e?i.indexOf(St.CACHE_KEY)===0&&e.hasOwnProperty("aliases")&&e.hasOwnProperty("preferred_cache")&&e.hasOwnProperty("preferred_network")&&e.hasOwnProperty("canonical_authority")&&e.hasOwnProperty("authorization_endpoint")&&e.hasOwnProperty("token_endpoint")&&e.hasOwnProperty("issuer")&&e.hasOwnProperty("aliasesFromNetwork")&&e.hasOwnProperty("endpointsFromNetwork")&&e.hasOwnProperty("expiresAt")&&e.hasOwnProperty("jwks_uri"):!1}function Zo(){return $()+St.REFRESH_TIME_SECONDS}function ft(i,e,t){i.authorization_endpoint=e.authorization_endpoint,i.token_endpoint=e.token_endpoint,i.end_session_endpoint=e.end_session_endpoint,i.issuer=e.issuer,i.endpointsFromNetwork=t,i.jwks_uri=e.jwks_uri}function hn(i,e,t){i.aliases=e.aliases,i.preferred_cache=e.preferred_cache,i.preferred_network=e.preferred_network,i.aliasesFromNetwork=t}function er(i){return i.expiresAt<=$()}class z{constructor(e,t,n,o,r,s,a,c){this.canonicalAuthority=e,this._canonicalAuthority.validateAsUri(),this.networkInterface=t,this.cacheManager=n,this.authorityOptions=o,this.regionDiscoveryMetadata={region_used:void 0,region_source:void 0,region_outcome:void 0},this.logger=r,this.performanceClient=a,this.correlationId=s,this.managedIdentity=c||!1,this.regionDiscovery=new Qt(t,this.logger,this.performanceClient,this.correlationId)}getAuthorityType(e){if(e.HostNameAndPort.endsWith(f.CIAM_AUTH_URL))return te.Ciam;const t=e.PathSegments;if(t.length)switch(t[0].toLowerCase()){case f.ADFS:return te.Adfs;case f.DSTS:return te.Dsts}return te.Default}get authorityType(){return this.getAuthorityType(this.canonicalAuthorityUrlComponents)}get protocolMode(){return this.authorityOptions.protocolMode}get options(){return this.authorityOptions}get canonicalAuthority(){return this._canonicalAuthority.urlString}set canonicalAuthority(e){this._canonicalAuthority=new k(e),this._canonicalAuthority.validateAsUri(),this._canonicalAuthorityUrlComponents=null}get canonicalAuthorityUrlComponents(){return this._canonicalAuthorityUrlComponents||(this._canonicalAuthorityUrlComponents=this._canonicalAuthority.getUrlComponents()),this._canonicalAuthorityUrlComponents}get hostnameAndPort(){return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase()}get tenant(){return this.canonicalAuthorityUrlComponents.PathSegments[0]}get authorizationEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.authorization_endpoint);throw p(he)}get tokenEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint);throw p(he)}get deviceCodeEndpoint(){if(this.discoveryComplete())return this.replacePath(this.metadata.token_endpoint.replace("/token","/devicecode"));throw p(he)}get endSessionEndpoint(){if(this.discoveryComplete()){if(!this.metadata.end_session_endpoint)throw p(Kr);return this.replacePath(this.metadata.end_session_endpoint)}else throw p(he)}get selfSignedJwtAudience(){if(this.discoveryComplete())return this.replacePath(this.metadata.issuer);throw p(he)}get jwksUri(){if(this.discoveryComplete())return this.replacePath(this.metadata.jwks_uri);throw p(he)}canReplaceTenant(e){return e.PathSegments.length===1&&!z.reservedTenantDomains.has(e.PathSegments[0])&&this.getAuthorityType(e)===te.Default&&this.protocolMode!==V.OIDC}replaceTenant(e){return e.replace(/{tenant}|{tenantid}/g,this.tenant)}replacePath(e){let t=e;const o=new k(this.metadata.canonical_authority).getUrlComponents(),r=o.PathSegments;return this.canonicalAuthorityUrlComponents.PathSegments.forEach((a,c)=>{let l=r[c];if(c===0&&this.canReplaceTenant(o)){const d=new k(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0];l!==d&&(this.logger.verbose(`Replacing tenant domain name ${l} with id ${d}`),l=d)}a!==l&&(t=t.replace(`/${l}/`,`/${a}/`))}),this.replaceTenant(t)}get defaultOpenIdConfigurationEndpoint(){const e=this.hostnameAndPort;return this.canonicalAuthority.endsWith("v2.0/")||this.authorityType===te.Adfs||this.protocolMode===V.OIDC&&!this.isAliasOfKnownMicrosoftAuthority(e)?`${this.canonicalAuthority}.well-known/openid-configuration`:`${this.canonicalAuthority}v2.0/.well-known/openid-configuration`}discoveryComplete(){return!!this.metadata}async resolveEndpointsAsync(){this.performanceClient?.addQueueMeasurement(h.AuthorityResolveEndpointsAsync,this.correlationId);const e=this.getCurrentMetadataEntity(),t=await g(this.updateCloudDiscoveryMetadata.bind(this),h.AuthorityUpdateCloudDiscoveryMetadata,this.logger,this.performanceClient,this.correlationId)(e);this.canonicalAuthority=this.canonicalAuthority.replace(this.hostnameAndPort,e.preferred_network);const n=await g(this.updateEndpointMetadata.bind(this),h.AuthorityUpdateEndpointMetadata,this.logger,this.performanceClient,this.correlationId)(e);this.updateCachedMetadata(e,t,{source:n}),this.performanceClient?.addFields({cloudDiscoverySource:t,authorityEndpointSource:n},this.correlationId)}getCurrentMetadataEntity(){let e=this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort);return e||(e={aliases:[],preferred_cache:this.hostnameAndPort,preferred_network:this.hostnameAndPort,canonical_authority:this.canonicalAuthority,authorization_endpoint:"",token_endpoint:"",end_session_endpoint:"",issuer:"",aliasesFromNetwork:!1,endpointsFromNetwork:!1,expiresAt:Zo(),jwks_uri:""}),e}updateCachedMetadata(e,t,n){t!==Y.CACHE&&n?.source!==Y.CACHE&&(e.expiresAt=Zo(),e.canonical_authority=this.canonicalAuthority);const o=this.cacheManager.generateAuthorityMetadataCacheKey(e.preferred_cache);this.cacheManager.setAuthorityMetadata(o,e),this.metadata=e}async updateEndpointMetadata(e){this.performanceClient?.addQueueMeasurement(h.AuthorityUpdateEndpointMetadata,this.correlationId);const t=this.updateEndpointMetadataFromLocalSources(e);if(t){if(t.source===Y.HARDCODED_VALUES&&this.authorityOptions.azureRegionConfiguration?.azureRegion&&t.metadata){const o=await g(this.updateMetadataWithRegionalInformation.bind(this),h.AuthorityUpdateMetadataWithRegionalInformation,this.logger,this.performanceClient,this.correlationId)(t.metadata);ft(e,o,!1),e.canonical_authority=this.canonicalAuthority}return t.source}let n=await g(this.getEndpointMetadataFromNetwork.bind(this),h.AuthorityGetEndpointMetadataFromNetwork,this.logger,this.performanceClient,this.correlationId)();if(n)return this.authorityOptions.azureRegionConfiguration?.azureRegion&&(n=await g(this.updateMetadataWithRegionalInformation.bind(this),h.AuthorityUpdateMetadataWithRegionalInformation,this.logger,this.performanceClient,this.correlationId)(n)),ft(e,n,!0),Y.NETWORK;throw p(_r,this.defaultOpenIdConfigurationEndpoint)}updateEndpointMetadataFromLocalSources(e){this.logger.verbose("Attempting to get endpoint metadata from authority configuration");const t=this.getEndpointMetadataFromConfig();if(t)return this.logger.verbose("Found endpoint metadata in authority configuration"),ft(e,t,!1),{source:Y.CONFIG};if(this.logger.verbose("Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values."),this.authorityOptions.skipAuthorityMetadataCache)this.logger.verbose("Skipping hardcoded metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get endpoint metadata from the network metadata cache.");else{const o=this.getEndpointMetadataFromHardcodedValues();if(o)return ft(e,o,!1),{source:Y.HARDCODED_VALUES,metadata:o};this.logger.verbose("Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache.")}const n=er(e);return this.isAuthoritySameType(e)&&e.endpointsFromNetwork&&!n?(this.logger.verbose("Found endpoint metadata in the cache."),{source:Y.CACHE}):(n&&this.logger.verbose("The metadata entity is expired."),null)}isAuthoritySameType(e){return new k(e.canonical_authority).getUrlComponents().PathSegments.length===this.canonicalAuthorityUrlComponents.PathSegments.length}getEndpointMetadataFromConfig(){if(this.authorityOptions.authorityMetadata)try{return JSON.parse(this.authorityOptions.authorityMetadata)}catch{throw _(Wr)}return null}async getEndpointMetadataFromNetwork(){this.performanceClient?.addQueueMeasurement(h.AuthorityGetEndpointMetadataFromNetwork,this.correlationId);const e={},t=this.defaultOpenIdConfigurationEndpoint;this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from ${t}`);try{const n=await this.networkInterface.sendGetRequestAsync(t,e);return gc(n.body)?n.body:(this.logger.verbose("Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration"),null)}catch(n){return this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: ${n}`),null}}getEndpointMetadataFromHardcodedValues(){return this.hostnameAndPort in qo?qo[this.hostnameAndPort]:null}async updateMetadataWithRegionalInformation(e){this.performanceClient?.addQueueMeasurement(h.AuthorityUpdateMetadataWithRegionalInformation,this.correlationId);const t=this.authorityOptions.azureRegionConfiguration?.azureRegion;if(t){if(t!==f.AZURE_REGION_AUTO_DISCOVER_FLAG)return this.regionDiscoveryMetadata.region_outcome=cn.CONFIGURED_NO_AUTO_DETECTION,this.regionDiscoveryMetadata.region_used=t,z.replaceWithRegionalInformation(e,t);const n=await g(this.regionDiscovery.detectRegion.bind(this.regionDiscovery),h.RegionDiscoveryDetectRegion,this.logger,this.performanceClient,this.correlationId)(this.authorityOptions.azureRegionConfiguration?.environmentRegion,this.regionDiscoveryMetadata);if(n)return this.regionDiscoveryMetadata.region_outcome=cn.AUTO_DETECTION_REQUESTED_SUCCESSFUL,this.regionDiscoveryMetadata.region_used=n,z.replaceWithRegionalInformation(e,n);this.regionDiscoveryMetadata.region_outcome=cn.AUTO_DETECTION_REQUESTED_FAILED}return e}async updateCloudDiscoveryMetadata(e){this.performanceClient?.addQueueMeasurement(h.AuthorityUpdateCloudDiscoveryMetadata,this.correlationId);const t=this.updateCloudDiscoveryMetadataFromLocalSources(e);if(t)return t;const n=await g(this.getCloudDiscoveryMetadataFromNetwork.bind(this),h.AuthorityGetCloudDiscoveryMetadataFromNetwork,this.logger,this.performanceClient,this.correlationId)();if(n)return hn(e,n,!0),Y.NETWORK;throw _(jr)}updateCloudDiscoveryMetadataFromLocalSources(e){this.logger.verbose("Attempting to get cloud discovery metadata from authority configuration"),this.logger.verbosePii(`Known Authorities: ${this.authorityOptions.knownAuthorities||f.NOT_APPLICABLE}`),this.logger.verbosePii(`Authority Metadata: ${this.authorityOptions.authorityMetadata||f.NOT_APPLICABLE}`),this.logger.verbosePii(`Canonical Authority: ${e.canonical_authority||f.NOT_APPLICABLE}`);const t=this.getCloudDiscoveryMetadataFromConfig();if(t)return this.logger.verbose("Found cloud discovery metadata in authority configuration"),hn(e,t,!1),Y.CONFIG;if(this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values."),this.options.skipAuthorityMetadataCache)this.logger.verbose("Skipping hardcoded cloud discovery metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get cloud discovery metadata from the network metadata cache.");else{const o=ra(this.hostnameAndPort);if(o)return this.logger.verbose("Found cloud discovery metadata from hardcoded values."),hn(e,o,!1),Y.HARDCODED_VALUES;this.logger.verbose("Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache.")}const n=er(e);return this.isAuthoritySameType(e)&&e.aliasesFromNetwork&&!n?(this.logger.verbose("Found cloud discovery metadata in the cache."),Y.CACHE):(n&&this.logger.verbose("The metadata entity is expired."),null)}getCloudDiscoveryMetadataFromConfig(){if(this.authorityType===te.Ciam)return this.logger.verbose("CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host."),z.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);if(this.authorityOptions.cloudDiscoveryMetadata){this.logger.verbose("The cloud discovery metadata has been provided as a network response, in the config.");try{this.logger.verbose("Attempting to parse the cloud discovery metadata.");const e=JSON.parse(this.authorityOptions.cloudDiscoveryMetadata),t=bt(e.metadata,this.hostnameAndPort);if(this.logger.verbose("Parsed the cloud discovery metadata."),t)return this.logger.verbose("There is returnable metadata attached to the parsed cloud discovery metadata."),t;this.logger.verbose("There is no metadata attached to the parsed cloud discovery metadata.")}catch{throw this.logger.verbose("Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error."),_(Bn)}}return this.isInKnownAuthorities()?(this.logger.verbose("The host is included in knownAuthorities. Creating new cloud discovery metadata from the host."),z.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)):null}async getCloudDiscoveryMetadataFromNetwork(){this.performanceClient?.addQueueMeasurement(h.AuthorityGetCloudDiscoveryMetadataFromNetwork,this.correlationId);const e=`${f.AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`,t={};let n=null;try{const o=await this.networkInterface.sendGetRequestAsync(e,t);let r,s;if(fc(o.body))r=o.body,s=r.metadata,this.logger.verbosePii(`tenant_discovery_endpoint is: ${r.tenant_discovery_endpoint}`);else if(mc(o.body)){if(this.logger.warning(`A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: ${o.status}`),r=o.body,r.error===f.INVALID_INSTANCE)return this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance."),null;this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is ${r.error}`),this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is ${r.error_description}`),this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network) to []"),s=[]}else return this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse"),null;this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request."),n=bt(s,this.hostnameAndPort)}catch(o){if(o instanceof R)this.logger.error(`There was a network error while attempting to get the cloud discovery instance metadata.
2
+ Error: ${o.errorCode}
3
+ Error Description: ${o.errorMessage}`);else{const r=o;this.logger.error(`A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.
4
+ Error: ${r.name}
5
+ Error Description: ${r.message}`)}return null}return n||(this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request."),this.logger.verbose("Creating custom Authority for custom domain scenario."),n=z.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort)),n}isInKnownAuthorities(){return this.authorityOptions.knownAuthorities.filter(t=>t&&k.getDomainFromUrl(t).toLowerCase()===this.hostnameAndPort).length>0}static generateAuthority(e,t){let n;if(t&&t.azureCloudInstance!==xn.None){const o=t.tenant?t.tenant:f.DEFAULT_COMMON_TENANT;n=`${t.azureCloudInstance}/${o}/`}return n||e}static createCloudDiscoveryMetadataFromHost(e){return{preferred_network:e,preferred_cache:e,aliases:[e]}}getPreferredCache(){if(this.managedIdentity)return f.DEFAULT_AUTHORITY_HOST;if(this.discoveryComplete())return this.metadata.preferred_cache;throw p(he)}isAlias(e){return this.metadata.aliases.indexOf(e)>-1}isAliasOfKnownMicrosoftAuthority(e){return si.has(e)}static isPublicCloudAuthority(e){return f.KNOWN_PUBLIC_CLOUDS.indexOf(e)>=0}static buildRegionalAuthorityString(e,t,n){const o=new k(e);o.validateAsUri();const r=o.getUrlComponents();let s=`${t}.${r.HostNameAndPort}`;this.isPublicCloudAuthority(r.HostNameAndPort)&&(s=`${t}.${f.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`);const a=k.constructAuthorityUriFromObject({...o.getUrlComponents(),HostNameAndPort:s}).urlString;return n?`${a}?${n}`:a}static replaceWithRegionalInformation(e,t){const n={...e};return n.authorization_endpoint=z.buildRegionalAuthorityString(n.authorization_endpoint,t),n.token_endpoint=z.buildRegionalAuthorityString(n.token_endpoint,t),n.end_session_endpoint&&(n.end_session_endpoint=z.buildRegionalAuthorityString(n.end_session_endpoint,t)),n}static transformCIAMAuthority(e){let t=e;const o=new k(e).getUrlComponents();if(o.PathSegments.length===0&&o.HostNameAndPort.endsWith(f.CIAM_AUTH_URL)){const r=o.HostNameAndPort.split(".")[0];t=`${t}${r}${f.AAD_TENANT_DOMAIN_SUFFIX}`}return t}}z.reservedTenantDomains=new Set(["{tenant}","{tenantid}",Ce.COMMON,Ce.CONSUMERS,Ce.ORGANIZATIONS]);function Ec(i){const n=new k(i).getUrlComponents().PathSegments.slice(-1)[0]?.toLowerCase();switch(n){case Ce.COMMON:case Ce.ORGANIZATIONS:case Ce.CONSUMERS:return;default:return n}}function Si(i){return i.endsWith(f.FORWARD_SLASH)?i:`${i}${f.FORWARD_SLASH}`}function Sc(i){const e=i.cloudDiscoveryMetadata;let t;if(e)try{t=JSON.parse(e)}catch{throw _(Bn)}return{canonicalAuthority:i.authority?Si(i.authority):void 0,knownAuthorities:i.knownAuthorities,cloudDiscoveryMetadata:t}}async function oo(i,e,t,n,o,r,s){s?.addQueueMeasurement(h.AuthorityFactoryCreateDiscoveredInstance,r);const a=z.transformCIAMAuthority(Si(i)),c=new z(a,e,t,n,o,r,s);try{return await g(c.resolveEndpointsAsync.bind(c),h.AuthorityResolveEndpointsAsync,o,s,r)(),c}catch{throw p(he)}}class Me extends R{constructor(e,t,n,o,r){super(e,t,n),this.name="ServerError",this.errorNo=o,this.status=r,Object.setPrototypeOf(this,Me.prototype)}}function Yt(i,e,t){return{clientId:i,authority:e.authority,scopes:e.scopes,homeAccountIdentifier:t,claims:e.claims,authenticationScheme:e.authenticationScheme,resourceRequestMethod:e.resourceRequestMethod,resourceRequestUri:e.resourceRequestUri,shrClaims:e.shrClaims,sshKid:e.sshKid,embeddedClientId:e.embeddedClientId||e.tokenBodyParameters?.clientId}}class re{static generateThrottlingStorageKey(e){return`${et.THROTTLING_PREFIX}.${JSON.stringify(e)}`}static preProcess(e,t,n){const o=re.generateThrottlingStorageKey(t),r=e.getThrottlingCache(o);if(r){if(r.throttleTime<Date.now()){e.removeItem(o,n);return}throw new Me(r.errorCodes?.join(" ")||f.EMPTY_STRING,r.errorMessage,r.subError)}}static postProcess(e,t,n,o){if(re.checkResponseStatus(n)||re.checkResponseForRetryAfter(n)){const r={throttleTime:re.calculateThrottleTime(parseInt(n.headers[G.RETRY_AFTER])),error:n.body.error,errorCodes:n.body.error_codes,errorMessage:n.body.error_description,subError:n.body.suberror};e.setThrottlingCache(re.generateThrottlingStorageKey(t),r,o)}}static checkResponseStatus(e){return e.status===429||e.status>=500&&e.status<600}static checkResponseForRetryAfter(e){return e.headers?e.headers.hasOwnProperty(G.RETRY_AFTER)&&(e.status<200||e.status>=300):!1}static calculateThrottleTime(e){const t=e<=0?0:e,n=Date.now()/1e3;return Math.floor(Math.min(n+(t||et.DEFAULT_THROTTLE_TIME_SECONDS),n+et.DEFAULT_MAX_THROTTLE_TIME_SECONDS)*1e3)}static removeThrottle(e,t,n,o){const r=Yt(t,n,o),s=this.generateThrottlingStorageKey(r);e.removeItem(s,n.correlationId)}}class Jt extends R{constructor(e,t,n){super(e.errorCode,e.errorMessage,e.subError),Object.setPrototypeOf(this,Jt.prototype),this.name="NetworkError",this.error=e,this.httpStatus=t,this.responseHeaders=n}}function Ze(i,e,t,n){return i.errorMessage=`${i.errorMessage}, additionalErrorInfo: error.name:${n?.name}, error.message:${n?.message}`,new Jt(i,e,t)}class ro{constructor(e,t){this.config=fa(e),this.logger=new we(this.config.loggerOptions,Br,Hn),this.cryptoUtils=this.config.cryptoInterface,this.cacheManager=this.config.storageInterface,this.networkClient=this.config.networkInterface,this.serverTelemetryManager=this.config.serverTelemetryManager,this.authority=this.config.authOptions.authority,this.performanceClient=t}createTokenRequestHeaders(e){const t={};if(t[G.CONTENT_TYPE]=f.URL_FORM_CONTENT_TYPE,!this.config.systemOptions.preventCorsPreflight&&e)switch(e.type){case ne.HOME_ACCOUNT_ID:try{const n=He(e.credential);t[G.CCS_HEADER]=`Oid:${n.uid}@${n.utid}`}catch(n){this.logger.verbose("Could not parse home account ID for CCS Header: "+n)}break;case ne.UPN:t[G.CCS_HEADER]=`UPN: ${e.credential}`;break}return t}async executePostToTokenEndpoint(e,t,n,o,r,s){s&&this.performanceClient?.addQueueMeasurement(s,r);const a=await this.sendPostRequest(o,e,{body:t,headers:n},r);return this.config.serverTelemetryManager&&a.status<500&&a.status!==429&&this.config.serverTelemetryManager.clearTelemetryCache(),a}async sendPostRequest(e,t,n,o){re.preProcess(this.cacheManager,e,o);let r;try{r=await g(this.networkClient.sendPostRequestAsync.bind(this.networkClient),h.NetworkClientSendPostRequestAsync,this.logger,this.performanceClient,o)(t,n);const s=r.headers||{};this.performanceClient?.addFields({refreshTokenSize:r.body.refresh_token?.length||0,httpVerToken:s[G.X_MS_HTTP_VERSION]||"",requestId:s[G.X_MS_REQUEST_ID]||""},o)}catch(s){if(s instanceof Jt){const a=s.responseHeaders;throw a&&this.performanceClient?.addFields({httpVerToken:a[G.X_MS_HTTP_VERSION]||"",requestId:a[G.X_MS_REQUEST_ID]||"",contentTypeHeader:a[G.CONTENT_TYPE]||void 0,contentLengthHeader:a[G.CONTENT_LENGTH]||void 0,httpStatus:s.httpStatus},o),s.error}throw s instanceof R?s:p(vr)}return re.postProcess(this.cacheManager,e,r,o),r}async updateAuthority(e,t){this.performanceClient?.addQueueMeasurement(h.UpdateTokenEndpointAuthority,t);const n=`https://${e}/${this.authority.tenant}/`,o=await oo(n,this.networkClient,this.cacheManager,this.authority.options,this.logger,t,this.performanceClient);this.authority=o}createTokenQueryParameters(e){const t=new Map;return e.embeddedClientId&&$t(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.tokenQueryParameters&&Te(t,e.tokenQueryParameters),lt(t,e.correlationId),qt(t,e.correlationId,this.performanceClient),rt(t)}}const Ut="no_tokens_found",ki="native_account_unavailable",io="refresh_token_expired",so="ux_not_allowed",kc="interaction_required",vc="consent_required",_c="login_required",Xt="bad_token",vi="interrupted_user";const tr=[kc,vc,_c,Xt,so,vi],Rc=["message_only","additional_action","basic_action","user_password_expired","consent_required","bad_token","interrupted_user"],bc={[Ut]:"No refresh token found in the cache. Please sign-in.",[ki]:"The requested account is not available in the native broker. It may have been deleted or logged out. Please sign-in again using an interactive API.",[io]:"Refresh token has expired.",[Xt]:"Identity provider returned bad_token due to an expired or invalid refresh token. Please invoke an interactive API to resolve.",[so]:"`canShowUI` flag in Edge was set to false. User interaction required on web page. Please invoke an interactive API to resolve.",[vi]:"The user could not be authenticated due to an interrupted state. Please invoke an interactive API to resolve."};class oe extends R{constructor(e,t,n,o,r,s,a,c){super(e,t,n),Object.setPrototypeOf(this,oe.prototype),this.timestamp=o||f.EMPTY_STRING,this.traceId=r||f.EMPTY_STRING,this.correlationId=s||f.EMPTY_STRING,this.claims=a||f.EMPTY_STRING,this.name="InteractionRequiredAuthError",this.errorNo=c}}function _i(i,e,t){const n=!!i&&tr.indexOf(i)>-1,o=!!t&&Rc.indexOf(t)>-1,r=!!e&&tr.some(s=>e.indexOf(s)>-1);return n||r||o}function Dt(i){return new oe(i,bc[i])}class We{static setRequestState(e,t,n){const o=We.generateLibraryState(e,n);return t?`${o}${f.RESOURCE_DELIM}${t}`:o}static generateLibraryState(e,t){if(!e)throw p(yn);const n={id:e.createNewGuid()};t&&(n.meta=t);const o=JSON.stringify(n);return e.base64Encode(o)}static parseRequestState(e,t){if(!e)throw p(yn);if(!t)throw p($e);try{const n=t.split(f.RESOURCE_DELIM),o=n[0],r=n.length>1?n.slice(1).join(f.RESOURCE_DELIM):f.EMPTY_STRING,s=e.base64Decode(o),a=JSON.parse(s);return{userRequestState:r||f.EMPTY_STRING,libraryState:a}}catch{throw p($e)}}}const Pc={SW:"sw"};class Qe{constructor(e,t){this.cryptoUtils=e,this.performanceClient=t}async generateCnf(e,t){this.performanceClient?.addQueueMeasurement(h.PopTokenGenerateCnf,e.correlationId);const n=await g(this.generateKid.bind(this),h.PopTokenGenerateCnf,t,this.performanceClient,e.correlationId)(e),o=this.cryptoUtils.base64UrlEncode(JSON.stringify(n));return{kid:n.kid,reqCnfString:o}}async generateKid(e){return this.performanceClient?.addQueueMeasurement(h.PopTokenGenerateKid,e.correlationId),{kid:await this.cryptoUtils.getPublicKeyThumbprint(e),xms_ksl:Pc.SW}}async signPopToken(e,t,n){return this.signPayload(e,t,n)}async signPayload(e,t,n,o){const{resourceRequestMethod:r,resourceRequestUri:s,shrClaims:a,shrNonce:c,shrOptions:l}=n,u=(s?new k(s):void 0)?.getUrlComponents();return this.cryptoUtils.signJwt({at:e,ts:$(),m:r?.toUpperCase(),u:u?.HostNameAndPort,nonce:c||this.cryptoUtils.createNewGuid(),p:u?.AbsolutePath,q:u?.QueryString?[[],u.QueryString]:void 0,client_claims:a||void 0,...o},t,l,n.correlationId)}}class Oc{constructor(e,t){this.cache=e,this.hasChanged=t}get cacheHasChanged(){return this.hasChanged}get tokenCache(){return this.cache}}class Pe{constructor(e,t,n,o,r,s,a){this.clientId=e,this.cacheStorage=t,this.cryptoObj=n,this.logger=o,this.serializableCache=r,this.persistencePlugin=s,this.performanceClient=a}validateTokenResponse(e,t){if(e.error||e.error_description||e.suberror){const n=`Error(s): ${e.error_codes||f.NOT_AVAILABLE} - Timestamp: ${e.timestamp||f.NOT_AVAILABLE} - Description: ${e.error_description||f.NOT_AVAILABLE} - Correlation ID: ${e.correlation_id||f.NOT_AVAILABLE} - Trace ID: ${e.trace_id||f.NOT_AVAILABLE}`,o=e.error_codes?.length?e.error_codes[0]:void 0,r=new Me(e.error,n,e.suberror,o,e.status);if(t&&e.status&&e.status>=pe.SERVER_ERROR_RANGE_START&&e.status<=pe.SERVER_ERROR_RANGE_END){this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently unavailable and the access token is unable to be refreshed.
6
+ ${r}`);return}else if(t&&e.status&&e.status>=pe.CLIENT_ERROR_RANGE_START&&e.status<=pe.CLIENT_ERROR_RANGE_END){this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently available but is unable to refresh the access token.
7
+ ${r}`);return}throw _i(e.error,e.error_description,e.suberror)?new oe(e.error,e.error_description,e.suberror,e.timestamp||f.EMPTY_STRING,e.trace_id||f.EMPTY_STRING,e.correlation_id||f.EMPTY_STRING,e.claims||f.EMPTY_STRING,o):r}}async handleServerTokenResponse(e,t,n,o,r,s,a,c,l,d){this.performanceClient?.addQueueMeasurement(h.HandleServerTokenResponse,e.correlation_id);let u;if(e.id_token){if(u=se(e.id_token||f.EMPTY_STRING,this.cryptoObj.base64Decode),s&&s.nonce&&u.nonce!==s.nonce)throw p(Pr);if(o.maxAge||o.maxAge===0){const I=u.auth_time;if(!I)throw p(Nn);oi(I,o.maxAge)}}this.homeAccountIdentifier=O.generateHomeAccountId(e.client_info||f.EMPTY_STRING,t.authorityType,this.logger,this.cryptoObj,u);let m;s&&s.state&&(m=We.parseRequestState(this.cryptoObj,s.state)),e.key_id=e.key_id||o.sshKid||void 0;const C=this.generateCacheRecord(e,t,n,o,u,a,s);let E;try{if(this.persistencePlugin&&this.serializableCache&&(this.logger.verbose("Persistence enabled, calling beforeCacheAccess"),E=new Oc(this.serializableCache,!0),await this.persistencePlugin.beforeCacheAccess(E)),c&&!l&&C.account&&this.cacheStorage.getAllAccounts({homeAccountId:C.account.homeAccountId,environment:C.account.environment},o.correlationId).length<1)return this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache"),this.performanceClient?.addFields({acntLoggedOut:!0},o.correlationId),await Pe.generateAuthenticationResult(this.cryptoObj,t,C,!1,o,u,m,void 0,d);await this.cacheStorage.saveCacheRecord(C,o.correlationId,ae(u||{}),r,o.storeInCache)}finally{this.persistencePlugin&&this.serializableCache&&E&&(this.logger.verbose("Persistence enabled, calling afterCacheAccess"),await this.persistencePlugin.afterCacheAccess(E))}return Pe.generateAuthenticationResult(this.cryptoObj,t,C,!1,o,u,m,e,d)}generateCacheRecord(e,t,n,o,r,s,a){const c=t.getPreferredCache();if(!c)throw p(Un);const l=qn(r);let d,u;e.id_token&&r&&(d=Vt(this.homeAccountIdentifier,c,e.id_token,this.clientId,l||""),u=ao(this.cacheStorage,t,this.homeAccountIdentifier,this.cryptoObj.base64Decode,o.correlationId,r,e.client_info,c,l,a,void 0,this.logger));let m=null;if(e.access_token){const I=e.scope?M.fromString(e.scope):new M(o.scopes||[]),D=(typeof e.expires_in=="string"?parseInt(e.expires_in,10):e.expires_in)||0,Z=(typeof e.ext_expires_in=="string"?parseInt(e.ext_expires_in,10):e.ext_expires_in)||0,P=(typeof e.refresh_in=="string"?parseInt(e.refresh_in,10):e.refresh_in)||void 0,j=n+D,Se=j+Z,ke=P&&P>0?n+P:void 0;m=Wt(this.homeAccountIdentifier,c,e.access_token,this.clientId,l||t.tenant||"",I.printScopes(),j,Se,this.cryptoObj.base64Decode,ke,e.token_type,s,e.key_id,o.claims,o.requestedClaimsHash)}let C=null;if(e.refresh_token){let I;if(e.refresh_token_expires_in){const D=typeof e.refresh_token_expires_in=="string"?parseInt(e.refresh_token_expires_in,10):e.refresh_token_expires_in;I=n+D,this.performanceClient?.addFields({ntwkRtExpiresOnSeconds:I},o.correlationId)}C=Ei(this.homeAccountIdentifier,c,e.refresh_token,this.clientId,e.foci,s,I)}let E=null;return e.foci&&(E={clientId:this.clientId,environment:c,familyId:e.foci}),{account:u,idToken:d,accessToken:m,refreshToken:C,appMetadata:E}}static async generateAuthenticationResult(e,t,n,o,r,s,a,c,l){let d=f.EMPTY_STRING,u=[],m=null,C,E,I=f.EMPTY_STRING;if(n.accessToken){if(n.accessToken.tokenType===v.POP&&!r.popKid){const j=new Qe(e),{secret:Se,keyId:ke}=n.accessToken;if(!ke)throw p(Dn);d=await j.signPopToken(Se,ke,r)}else d=n.accessToken.secret;u=M.fromString(n.accessToken.target).asArray(),m=Ke(n.accessToken.expiresOn),C=Ke(n.accessToken.extendedExpiresOn),n.accessToken.refreshOn&&(E=Ke(n.accessToken.refreshOn))}n.appMetadata&&(I=n.appMetadata.familyId===Et?Et:"");const D=s?.oid||s?.sub||"",Z=s?.tid||"";c?.spa_accountid&&n.account&&(n.account.nativeAccountId=c?.spa_accountid);const P=n.account?zn(O.getAccountInfo(n.account),void 0,s,n.idToken?.secret):null;return{authority:t.canonicalAuthority,uniqueId:D,tenantId:Z,scopes:u,account:P,idToken:n?.idToken?.secret||"",idTokenClaims:s||{},accessToken:d,fromCache:o,expiresOn:m,extExpiresOn:C,refreshOn:E,correlationId:r.correlationId,requestId:l||f.EMPTY_STRING,familyId:I,tokenType:n.accessToken?.tokenType||f.EMPTY_STRING,state:a?a.userRequestState:f.EMPTY_STRING,cloudGraphHostName:n.account?.cloudGraphHostName||f.EMPTY_STRING,msGraphHost:n.account?.msGraphHost||f.EMPTY_STRING,code:c?.spa_code,fromNativeBroker:!1}}}function ao(i,e,t,n,o,r,s,a,c,l,d,u){u?.verbose("setCachedAccount called");const C=i.getAccountKeys().find(P=>P.startsWith(t));let E=null;C&&(E=i.getAccount(C,o));const I=E||O.createAccount({homeAccountId:t,idTokenClaims:r,clientInfo:s,environment:a,cloudGraphHostName:l?.cloud_graph_host_name,msGraphHost:l?.msgraph_host,nativeAccountId:d},e,n),D=I.tenantProfiles||[],Z=c||I.realm;if(Z&&!D.find(P=>P.tenantId===Z)){const P=xe(t,I.localAccountId,Z,r);D.push(P)}return I.tenantProfiles=D,I}async function Ri(i,e,t){return typeof i=="string"?i:i({clientId:e,tokenEndpoint:t})}class bi extends ro{constructor(e,t){super(e,t),this.includeRedirectUri=!0,this.oidcDefaultScopes=this.config.authOptions.authority.options.OIDCOptions?.defaultScopes}async acquireToken(e,t,n){if(this.performanceClient?.addQueueMeasurement(h.AuthClientAcquireToken,e.correlationId),!e.code)throw p(Mr);const o=$(),r=await g(this.executeTokenRequest.bind(this),h.AuthClientExecuteTokenRequest,this.logger,this.performanceClient,e.correlationId)(this.authority,e),s=r.headers?.[G.X_MS_REQUEST_ID],a=new Pe(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin,this.performanceClient);return a.validateTokenResponse(r.body),g(a.handleServerTokenResponse.bind(a),h.HandleServerTokenResponse,this.logger,this.performanceClient,e.correlationId)(r.body,this.authority,o,e,t,n,void 0,void 0,void 0,s)}getLogoutUri(e){if(!e)throw _(Vr);const t=this.createLogoutUrlQueryString(e);return k.appendQueryString(this.authority.endSessionEndpoint,t)}async executeTokenRequest(e,t){this.performanceClient?.addQueueMeasurement(h.AuthClientExecuteTokenRequest,t.correlationId);const n=this.createTokenQueryParameters(t),o=k.appendQueryString(e.tokenEndpoint,n),r=await g(this.createTokenRequestBody.bind(this),h.AuthClientCreateTokenRequestBody,this.logger,this.performanceClient,t.correlationId)(t);let s;if(t.clientInfo)try{const l=_t(t.clientInfo,this.cryptoUtils.base64Decode);s={credential:`${l.uid}${ot.CLIENT_INFO_SEPARATOR}${l.utid}`,type:ne.HOME_ACCOUNT_ID}}catch(l){this.logger.verbose("Could not parse client info for CCS Header: "+l)}const a=this.createTokenRequestHeaders(s||t.ccsCredential),c=Yt(this.config.authOptions.clientId,t);return g(this.executePostToTokenEndpoint.bind(this),h.AuthorizationCodeClientExecutePostToTokenEndpoint,this.logger,this.performanceClient,t.correlationId)(o,r,a,c,t.correlationId,h.AuthorizationCodeClientExecutePostToTokenEndpoint)}async createTokenRequestBody(e){this.performanceClient?.addQueueMeasurement(h.AuthClientCreateTokenRequestBody,e.correlationId);const t=new Map;if(jn(t,e.embeddedClientId||e.tokenBodyParameters?.[Re]||this.config.authOptions.clientId),this.includeRedirectUri)Yn(t,e.redirectUri);else if(!e.redirectUri)throw _(Gr);if(Wn(t,e.scopes,!0,this.oidcDefaultScopes),sc(t,e.code),Xn(t,this.config.libraryInfo),Zn(t,this.config.telemetry.application),wi(t),this.serverTelemetryManager&&!li(this.config)&&Ii(t,this.serverTelemetryManager),e.codeVerifier&&cc(t,e.codeVerifier),this.config.clientCredentials.clientSecret&&fi(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const r=this.config.clientCredentials.clientAssertion;mi(t,await Ri(r.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),pi(t,r.assertionType)}if(Ci(t,wr.AUTHORIZATION_CODE_GRANT),to(t),e.authenticationScheme===v.POP){const r=new Qe(this.cryptoUtils,this.performanceClient);let s;e.popKid?s=this.cryptoUtils.encodeKid(e.popKid):s=(await g(r.generateCnf.bind(r),h.PopTokenGenerateCnf,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString,no(t,s)}else if(e.authenticationScheme===v.SSH)if(e.sshJwk)Ai(t,e.sshJwk);else throw _(zt);let n;if(e.clientInfo)try{const r=_t(e.clientInfo,this.cryptoUtils.base64Decode);n={credential:`${r.uid}${ot.CLIENT_INFO_SEPARATOR}${r.utid}`,type:ne.HOME_ACCOUNT_ID}}catch(r){this.logger.verbose("Could not parse client info for CCS Header: "+r)}else n=e.ccsCredential;if(this.config.systemOptions.preventCorsPreflight&&n)switch(n.type){case ne.HOME_ACCOUNT_ID:try{const r=He(n.credential);tt(t,r)}catch(r){this.logger.verbose("Could not parse home account ID for CCS Header: "+r)}break;case ne.UPN:Nt(t,n.credential);break}e.embeddedClientId&&$t(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.tokenBodyParameters&&Te(t,e.tokenBodyParameters),e.enableSpaAuthorizationCode&&(!e.tokenBodyParameters||!e.tokenBodyParameters[Vo])&&Te(t,{[Vo]:"1"}),qt(t,e.correlationId,this.performanceClient);const o=e.skipBrokerClaims&&t.has(be)?void 0:this.config.authOptions.clientCapabilities;return(!J.isEmptyObj(e.claims)||o&&o.length>0)&&Jn(t,e.claims,o),rt(t)}createLogoutUrlQueryString(e){const t=new Map;return e.postLogoutRedirectUri&&tc(t,e.postLogoutRedirectUri),e.correlationId&&lt(t,e.correlationId),e.idTokenHint&&nc(t,e.idTokenHint),e.state&&gi(t,e.state),e.logoutHint&&hc(t,e.logoutHint),e.extraQueryParameters&&Te(t,e.extraQueryParameters),this.config.authOptions.instanceAware&&yi(t),rt(t,this.config.authOptions.encodeExtraQueryParams,e.extraQueryParameters)}}const Nc=300;class Mc extends ro{constructor(e,t){super(e,t)}async acquireToken(e,t){this.performanceClient?.addQueueMeasurement(h.RefreshTokenClientAcquireToken,e.correlationId);const n=$(),o=await g(this.executeTokenRequest.bind(this),h.RefreshTokenClientExecuteTokenRequest,this.logger,this.performanceClient,e.correlationId)(e,this.authority),r=o.headers?.[G.X_MS_REQUEST_ID],s=new Pe(this.config.authOptions.clientId,this.cacheManager,this.cryptoUtils,this.logger,this.config.serializableCache,this.config.persistencePlugin);return s.validateTokenResponse(o.body),g(s.handleServerTokenResponse.bind(s),h.HandleServerTokenResponse,this.logger,this.performanceClient,e.correlationId)(o.body,this.authority,n,e,t,void 0,void 0,!0,e.forceCache,r)}async acquireTokenByRefreshToken(e,t){if(!e)throw _(Qr);if(this.performanceClient?.addQueueMeasurement(h.RefreshTokenClientAcquireTokenByRefreshToken,e.correlationId),!e.account)throw p(Mn);if(this.cacheManager.isAppMetadataFOCI(e.account.environment))try{return await g(this.acquireTokenWithCachedRefreshToken.bind(this),h.RefreshTokenClientAcquireTokenWithCachedRefreshToken,this.logger,this.performanceClient,e.correlationId)(e,!0,t)}catch(o){const r=o instanceof oe&&o.errorCode===Ut,s=o instanceof Me&&o.errorCode===xo.INVALID_GRANT_ERROR&&o.subError===xo.CLIENT_MISMATCH_ERROR;if(r||s)return g(this.acquireTokenWithCachedRefreshToken.bind(this),h.RefreshTokenClientAcquireTokenWithCachedRefreshToken,this.logger,this.performanceClient,e.correlationId)(e,!1,t);throw o}return g(this.acquireTokenWithCachedRefreshToken.bind(this),h.RefreshTokenClientAcquireTokenWithCachedRefreshToken,this.logger,this.performanceClient,e.correlationId)(e,!1,t)}async acquireTokenWithCachedRefreshToken(e,t,n){this.performanceClient?.addQueueMeasurement(h.RefreshTokenClientAcquireTokenWithCachedRefreshToken,e.correlationId);const o=W(this.cacheManager.getRefreshToken.bind(this.cacheManager),h.CacheManagerGetRefreshToken,this.logger,this.performanceClient,e.correlationId)(e.account,t,e.correlationId,void 0,this.performanceClient);if(!o)throw Dt(Ut);if(o.expiresOn){const s=e.refreshTokenExpirationOffsetSeconds||Nc;if(this.performanceClient?.addFields({cacheRtExpiresOnSeconds:Number(o.expiresOn),rtOffsetSeconds:s},e.correlationId),Mt(o.expiresOn,s))throw Dt(io)}const r={...e,refreshToken:o.secret,authenticationScheme:e.authenticationScheme||v.BEARER,ccsCredential:{credential:e.account.homeAccountId,type:ne.HOME_ACCOUNT_ID}};try{return await g(this.acquireToken.bind(this),h.RefreshTokenClientAcquireToken,this.logger,this.performanceClient,e.correlationId)(r,n)}catch(s){if(s instanceof oe&&s.subError===Xt){this.logger.verbose("acquireTokenWithRefreshToken: bad refresh token, removing from cache");const a=this.cacheManager.generateCredentialKey(o);this.cacheManager.removeRefreshToken(a,e.correlationId)}throw s}}async executeTokenRequest(e,t){this.performanceClient?.addQueueMeasurement(h.RefreshTokenClientExecuteTokenRequest,e.correlationId);const n=this.createTokenQueryParameters(e),o=k.appendQueryString(t.tokenEndpoint,n),r=await g(this.createTokenRequestBody.bind(this),h.RefreshTokenClientCreateTokenRequestBody,this.logger,this.performanceClient,e.correlationId)(e),s=this.createTokenRequestHeaders(e.ccsCredential),a=Yt(this.config.authOptions.clientId,e);return g(this.executePostToTokenEndpoint.bind(this),h.RefreshTokenClientExecutePostToTokenEndpoint,this.logger,this.performanceClient,e.correlationId)(o,r,s,a,e.correlationId,h.RefreshTokenClientExecutePostToTokenEndpoint)}async createTokenRequestBody(e){this.performanceClient?.addQueueMeasurement(h.RefreshTokenClientCreateTokenRequestBody,e.correlationId);const t=new Map;if(jn(t,e.embeddedClientId||e.tokenBodyParameters?.[Re]||this.config.authOptions.clientId),e.redirectUri&&Yn(t,e.redirectUri),Wn(t,e.scopes,!0,this.config.authOptions.authority.options.OIDCOptions?.defaultScopes),Ci(t,wr.REFRESH_TOKEN_GRANT),to(t),Xn(t,this.config.libraryInfo),Zn(t,this.config.telemetry.application),wi(t),this.serverTelemetryManager&&!li(this.config)&&Ii(t,this.serverTelemetryManager),ac(t,e.refreshToken),this.config.clientCredentials.clientSecret&&fi(t,this.config.clientCredentials.clientSecret),this.config.clientCredentials.clientAssertion){const o=this.config.clientCredentials.clientAssertion;mi(t,await Ri(o.assertion,this.config.authOptions.clientId,e.resourceRequestUri)),pi(t,o.assertionType)}if(e.authenticationScheme===v.POP){const o=new Qe(this.cryptoUtils,this.performanceClient);let r;e.popKid?r=this.cryptoUtils.encodeKid(e.popKid):r=(await g(o.generateCnf.bind(o),h.PopTokenGenerateCnf,this.logger,this.performanceClient,e.correlationId)(e,this.logger)).reqCnfString,no(t,r)}else if(e.authenticationScheme===v.SSH)if(e.sshJwk)Ai(t,e.sshJwk);else throw _(zt);if(this.config.systemOptions.preventCorsPreflight&&e.ccsCredential)switch(e.ccsCredential.type){case ne.HOME_ACCOUNT_ID:try{const o=He(e.ccsCredential.credential);tt(t,o)}catch(o){this.logger.verbose("Could not parse home account ID for CCS Header: "+o)}break;case ne.UPN:Nt(t,e.ccsCredential.credential);break}e.embeddedClientId&&$t(t,this.config.authOptions.clientId,this.config.authOptions.redirectUri),e.tokenBodyParameters&&Te(t,e.tokenBodyParameters),qt(t,e.correlationId,this.performanceClient);const n=e.skipBrokerClaims&&t.has(be)?void 0:this.config.authOptions.clientCapabilities;return(!J.isEmptyObj(e.claims)||n&&n.length>0)&&Jn(t,e.claims,n),rt(t)}}class Uc extends ro{constructor(e,t){super(e,t)}async acquireCachedToken(e){this.performanceClient?.addQueueMeasurement(h.SilentFlowClientAcquireCachedToken,e.correlationId);let t=ve.NOT_APPLICABLE;if(e.forceRefresh||!this.config.cacheOptions.claimsBasedCachingEnabled&&!J.isEmptyObj(e.claims))throw this.setCacheOutcome(ve.FORCE_REFRESH_OR_CLAIMS,e.correlationId),p(ye);if(!e.account)throw p(Mn);const n=e.account.tenantId||Ec(e.authority),o=this.cacheManager.getTokenKeys(),r=this.cacheManager.getAccessToken(e.account,e,o,n);if(r){if(pc(r.cachedAt)||Mt(r.expiresOn,this.config.systemOptions.tokenRenewalOffsetSeconds))throw this.setCacheOutcome(ve.CACHED_ACCESS_TOKEN_EXPIRED,e.correlationId),p(ye);r.refreshOn&&Mt(r.refreshOn,0)&&(t=ve.PROACTIVELY_REFRESHED)}else throw this.setCacheOutcome(ve.NO_CACHED_ACCESS_TOKEN,e.correlationId),p(ye);const s=e.authority||this.authority.getPreferredCache(),a={account:this.cacheManager.getAccount(this.cacheManager.generateAccountKey(e.account),e.correlationId),accessToken:r,idToken:this.cacheManager.getIdToken(e.account,e.correlationId,o,n,this.performanceClient),refreshToken:null,appMetadata:this.cacheManager.readAppMetadataFromCache(s)};return this.setCacheOutcome(t,e.correlationId),this.config.serverTelemetryManager&&this.config.serverTelemetryManager.incrementCacheHits(),[await g(this.generateResultFromCacheRecord.bind(this),h.SilentFlowClientGenerateResultFromCacheRecord,this.logger,this.performanceClient,e.correlationId)(a,e),t]}setCacheOutcome(e,t){this.serverTelemetryManager?.setCacheOutcome(e),this.performanceClient?.addFields({cacheOutcome:e},t),e!==ve.NOT_APPLICABLE&&this.logger.info(`Token refresh is required due to cache outcome: ${e}`)}async generateResultFromCacheRecord(e,t){this.performanceClient?.addQueueMeasurement(h.SilentFlowClientGenerateResultFromCacheRecord,t.correlationId);let n;if(e.idToken&&(n=se(e.idToken.secret,this.config.cryptoInterface.base64Decode)),t.maxAge||t.maxAge===0){const o=n?.auth_time;if(!o)throw p(Nn);oi(o,t.maxAge)}return Pe.generateAuthenticationResult(this.cryptoUtils,this.authority,e,!0,t,n)}}const Dc={sendGetRequestAsync:()=>Promise.reject(p(w)),sendPostRequestAsync:()=>Promise.reject(p(w))};function Lc(i,e,t,n){const o=e.correlationId,r=new Map;jn(r,e.embeddedClientId||e.extraQueryParameters?.[Re]||i.clientId);const s=[...e.scopes||[],...e.extraScopesToConsent||[]];if(Wn(r,s,!0,i.authority.options.OIDCOptions?.defaultScopes),Yn(r,e.redirectUri),lt(r,o),Za(r,e.responseMode),to(r),lc(r),e.prompt&&(rc(r,e.prompt),n?.addFields({prompt:e.prompt},o)),e.domainHint&&(oc(r,e.domainHint),n?.addFields({domainHintFromRequest:!0},o)),e.prompt!==U.SELECT_ACCOUNT)if(e.sid&&e.prompt===U.NONE)t.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request"),Wo(r,e.sid),n?.addFields({sidFromRequest:!0},o);else if(e.account){const c=Fc(e.account);let l=Kc(e.account);if(l&&e.domainHint&&(t.warning('AuthorizationCodeClient.createAuthCodeUrlQueryString: "domainHint" param is set, skipping opaque "login_hint" claim. Please consider not passing domainHint'),l=null),l){t.verbose("createAuthCodeUrlQueryString: login_hint claim present on account"),gt(r,l),n?.addFields({loginHintFromClaim:!0},o);try{const d=He(e.account.homeAccountId);tt(r,d)}catch{t.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}else if(c&&e.prompt===U.NONE){t.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account"),Wo(r,c),n?.addFields({sidFromClaim:!0},o);try{const d=He(e.account.homeAccountId);tt(r,d)}catch{t.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}else if(e.loginHint)t.verbose("createAuthCodeUrlQueryString: Adding login_hint from request"),gt(r,e.loginHint),Nt(r,e.loginHint),n?.addFields({loginHintFromRequest:!0},o);else if(e.account.username){t.verbose("createAuthCodeUrlQueryString: Adding login_hint from account"),gt(r,e.account.username),n?.addFields({loginHintFromUpn:!0},o);try{const d=He(e.account.homeAccountId);tt(r,d)}catch{t.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header")}}}else e.loginHint&&(t.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request"),gt(r,e.loginHint),Nt(r,e.loginHint),n?.addFields({loginHintFromRequest:!0},o));else t.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints");e.nonce&&ic(r,e.nonce),e.state&&gi(r,e.state),e.embeddedClientId&&$t(r,i.clientId,i.redirectUri);const a=e.skipBrokerClaims&&r.has(be)?void 0:i.clientCapabilities;return(e.claims||a&&a.length>0)&&Jn(r,e.claims,a),i.instanceAware&&(!e.extraQueryParameters||!Object.keys(e.extraQueryParameters).includes(In))&&yi(r),r}function co(i,e,t,n){const o=rt(e,t,n);return k.appendQueryString(i.authorizationEndpoint,o)}function Hc(i,e){if(lo(i,e),!i.code)throw p(xr);return i}function lo(i,e){if(!i.state||!e)throw i.state?p(mn,"Cached State"):p(mn,"Server State");let t,n;try{t=decodeURIComponent(i.state)}catch{throw p($e,i.state)}try{n=decodeURIComponent(e)}catch{throw p($e,i.state)}if(t!==n)throw p(br);if(i.error||i.error_description||i.suberror){const o=xc(i);throw _i(i.error,i.error_description,i.suberror)?new oe(i.error||"",i.error_description,i.suberror,i.timestamp||"",i.trace_id||"",i.correlation_id||"",i.claims||"",o):new Me(i.error||"",i.error_description,i.suberror,o)}}function xc(i){const e="code=",t=i.error_uri?.lastIndexOf(e);return t&&t>=0?i.error_uri?.substring(t+e.length):void 0}function Fc(i){return i.idTokenClaims?.sid||null}function Kc(i){return i.loginHint||i.idTokenClaims?.login_hint||null}const nr=",",Pi="|";function Bc(i){const{skus:e,libraryName:t,libraryVersion:n,extensionName:o,extensionVersion:r}=i,s=new Map([[0,[t,n]],[2,[o,r]]]);let a=[];if(e?.length){if(a=e.split(nr),a.length<4)return e}else a=Array.from({length:4},()=>Pi);return s.forEach((c,l)=>{c.length===2&&c[0]?.length&&c[1]?.length&&Gc({skuArr:a,index:l,skuName:c[0],skuVersion:c[1]})}),a.join(nr)}function Gc(i){const{skuArr:e,index:t,skuName:n,skuVersion:o}=i;t>=e.length||(e[t]=[n,o].join(Pi))}class it{constructor(e,t){this.cacheOutcome=ve.NOT_APPLICABLE,this.cacheManager=t,this.apiId=e.apiId,this.correlationId=e.correlationId,this.wrapperSKU=e.wrapperSKU||f.EMPTY_STRING,this.wrapperVer=e.wrapperVer||f.EMPTY_STRING,this.telemetryCacheKey=L.CACHE_KEY+ot.CACHE_KEY_SEPARATOR+e.clientId}generateCurrentRequestHeaderValue(){const e=`${this.apiId}${L.VALUE_SEPARATOR}${this.cacheOutcome}`,t=[this.wrapperSKU,this.wrapperVer],n=this.getNativeBrokerErrorCode();n?.length&&t.push(`broker_error=${n}`);const o=t.join(L.VALUE_SEPARATOR),r=this.getRegionDiscoveryFields(),s=[e,r].join(L.VALUE_SEPARATOR);return[L.SCHEMA_VERSION,s,o].join(L.CATEGORY_SEPARATOR)}generateLastRequestHeaderValue(){const e=this.getLastRequests(),t=it.maxErrorsToSend(e),n=e.failedRequests.slice(0,2*t).join(L.VALUE_SEPARATOR),o=e.errors.slice(0,t).join(L.VALUE_SEPARATOR),r=e.errors.length,s=t<r?L.OVERFLOW_TRUE:L.OVERFLOW_FALSE,a=[r,s].join(L.VALUE_SEPARATOR);return[L.SCHEMA_VERSION,e.cacheHits,n,o,a].join(L.CATEGORY_SEPARATOR)}cacheFailedRequest(e){const t=this.getLastRequests();t.errors.length>=L.MAX_CACHED_ERRORS&&(t.failedRequests.shift(),t.failedRequests.shift(),t.errors.shift()),t.failedRequests.push(this.apiId,this.correlationId),e instanceof Error&&e&&e.toString()?e instanceof R?e.subError?t.errors.push(e.subError):e.errorCode?t.errors.push(e.errorCode):t.errors.push(e.toString()):t.errors.push(e.toString()):t.errors.push(L.UNKNOWN_ERROR),this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t,this.correlationId)}incrementCacheHits(){const e=this.getLastRequests();return e.cacheHits+=1,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e,this.correlationId),e.cacheHits}getLastRequests(){const e={failedRequests:[],errors:[],cacheHits:0};return this.cacheManager.getServerTelemetry(this.telemetryCacheKey)||e}clearTelemetryCache(){const e=this.getLastRequests(),t=it.maxErrorsToSend(e),n=e.errors.length;if(t===n)this.cacheManager.removeItem(this.telemetryCacheKey,this.correlationId);else{const o={failedRequests:e.failedRequests.slice(t*2),errors:e.errors.slice(t),cacheHits:0};this.cacheManager.setServerTelemetry(this.telemetryCacheKey,o,this.correlationId)}}static maxErrorsToSend(e){let t,n=0,o=0;const r=e.errors.length;for(t=0;t<r;t++){const s=e.failedRequests[2*t]||f.EMPTY_STRING,a=e.failedRequests[2*t+1]||f.EMPTY_STRING,c=e.errors[t]||f.EMPTY_STRING;if(o+=s.toString().length+a.toString().length+c.length+3,o<L.MAX_LAST_HEADER_BYTES)n+=1;else break}return n}getRegionDiscoveryFields(){const e=[];return e.push(this.regionUsed||f.EMPTY_STRING),e.push(this.regionSource||f.EMPTY_STRING),e.push(this.regionOutcome||f.EMPTY_STRING),e.join(",")}updateRegionDiscoveryMetadata(e){this.regionUsed=e.region_used,this.regionSource=e.region_source,this.regionOutcome=e.region_outcome}setCacheOutcome(e){this.cacheOutcome=e}setNativeBrokerErrorCode(e){const t=this.getLastRequests();t.nativeBrokerErrorCode=e,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,t,this.correlationId)}getNativeBrokerErrorCode(){return this.getLastRequests().nativeBrokerErrorCode}clearNativeBrokerErrorCode(){const e=this.getLastRequests();delete e.nativeBrokerErrorCode,this.cacheManager.setServerTelemetry(this.telemetryCacheKey,e,this.correlationId)}static makeExtraSkuString(e){return Bc(e)}}const Oi="missing_kid_error",Ni="missing_alg_error";const zc={[Oi]:"The JOSE Header for the requested JWT, JWS or JWK object requires a keyId to be configured as the 'kid' header claim. No 'kid' value was provided.",[Ni]:"The JOSE Header for the requested JWT, JWS or JWK object requires an algorithm to be specified as the 'alg' header claim. No 'alg' value was provided."};class ho extends R{constructor(e,t){super(e,t),this.name="JoseHeaderError",Object.setPrototypeOf(this,ho.prototype)}}function or(i){return new ho(i,zc[i])}class uo{constructor(e){this.typ=e.typ,this.alg=e.alg,this.kid=e.kid}static getShrHeaderString(e){if(!e.kid)throw or(Oi);if(!e.alg)throw or(Ni);const t=new uo({typ:e.typ||Ds.Pop,kid:e.kid,alg:e.alg});return JSON.stringify(t)}}const go="pkce_not_created",fo="ear_jwk_empty",Mi="ear_jwe_empty",wn="crypto_nonexistent",Zt="empty_navigate_uri",Ui="hash_empty_error",mo="no_state_in_hash",Di="hash_does_not_contain_known_properties",Li="unable_to_parse_state",Hi="state_interaction_type_mismatch",xi="interaction_in_progress",Fi="popup_window_error",Ki="empty_window_error",st="user_cancelled",qc="monitor_popup_timeout",Bi="monitor_window_timeout",Gi="redirect_in_iframe",zi="block_iframe_reload",qi="block_nested_popups",$c="iframe_closed_prematurely",en="silent_logout_unsupported",$i="no_account_error",Qc="silent_prompt_value_error",Qi="no_token_request_cache_error",Vi="unable_to_parse_token_request_cache_error",Vc="auth_request_not_set_error",Wc="invalid_cache_type",tn="non_browser_environment",De="database_not_open",Lt="no_network_connectivity",Wi="post_request_failed",ji="get_request_failed",En="failed_to_parse_response",Yi="unable_to_load_token",po="crypto_key_not_found",Ji="auth_code_required",Xi="auth_code_or_nativeAccountId_required",Zi="spa_code_and_nativeAccountId_present",Co="database_unavailable",es="unable_to_acquire_token_from_native_platform",ts="native_handshake_timeout",ns="native_extension_not_installed",yo="native_connection_not_established",nt="uninitialized_public_client_application",os="native_prompt_not_supported",rs="invalid_base64_string",is="invalid_pop_token_request",ss="failed_to_build_headers",as="failed_to_parse_headers",yt="failed_to_decrypt_ear_response",Ht="timed_out";const le="For more visit: aka.ms/msaljs/browser-errors",jc={[go]:"The PKCE code challenge and verifier could not be generated.",[fo]:"No EAR encryption key provided. This is unexpected.",[Mi]:"Server response does not contain ear_jwe property. This is unexpected.",[wn]:"The crypto object or function is not available.",[Zt]:"Navigation URI is empty. Please check stack trace for more info.",[Ui]:`Hash value cannot be processed because it is empty. Please verify that your redirectUri is not clearing the hash. ${le}`,[mo]:"Hash does not contain state. Please verify that the request originated from msal.",[Di]:`Hash does not contain known properites. Please verify that your redirectUri is not changing the hash. ${le}`,[Li]:"Unable to parse state. Please verify that the request originated from msal.",[Hi]:"Hash contains state but the interaction type does not match the caller.",[xi]:`Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API. ${le}`,[Fi]:"Error opening popup window. This can happen if you are using IE or if popups are blocked in the browser.",[Ki]:"window.open returned null or undefined window object.",[st]:"User cancelled the flow.",[qc]:`Token acquisition in popup failed due to timeout. ${le}`,[Bi]:`Token acquisition in iframe failed due to timeout. ${le}`,[Gi]:"Redirects are not supported for iframed or brokered applications. Please ensure you are using MSAL.js in a top frame of the window if using the redirect APIs, or use the popup APIs.",[zi]:`Request was blocked inside an iframe because MSAL detected an authentication response. ${le}`,[qi]:"Request was blocked inside a popup because MSAL detected it was running in a popup.",[$c]:"The iframe being monitored was closed prematurely.",[en]:"Silent logout not supported. Please call logoutRedirect or logoutPopup instead.",[$i]:"No account object provided to acquireTokenSilent and no active account has been set. Please call setActiveAccount or provide an account on the request.",[Qc]:"The value given for the prompt value is not valid for silent requests - must be set to 'none' or 'no_session'.",[Qi]:"No token request found in cache.",[Vi]:"The cached token request could not be parsed.",[Vc]:"Auth Request not set. Please ensure initiateAuthRequest was called from the InteractionHandler",[Wc]:"Invalid cache type",[tn]:"Login and token requests are not supported in non-browser environments.",[De]:"Database is not open!",[Lt]:"No network connectivity. Check your internet connection.",[Wi]:"Network request failed: If the browser threw a CORS error, check that the redirectUri is registered in the Azure App Portal as type 'SPA'",[ji]:"Network request failed. Please check the network trace to determine root cause.",[En]:"Failed to parse network response. Check network trace.",[Yi]:"Error loading token to cache.",[po]:"Cryptographic Key or Keypair not found in browser storage.",[Ji]:"An authorization code must be provided (as the `code` property on the request) to this flow.",[Xi]:"An authorization code or nativeAccountId must be provided to this flow.",[Zi]:"Request cannot contain both spa code and native account id.",[Co]:"IndexedDB, which is required for persistent cryptographic key storage, is unavailable. This may be caused by browser privacy features which block persistent storage in third-party contexts.",[es]:`Unable to acquire token from native platform. ${le}`,[ts]:"Timed out while attempting to establish connection to browser extension",[ns]:"Native extension is not installed. If you think this is a mistake call the initialize function.",[yo]:`Connection to native platform has not been established. Please install a compatible browser extension and run initialize(). ${le}`,[nt]:`You must call and await the initialize function before attempting to call any other MSAL API. ${le}`,[os]:"The provided prompt is not supported by the native platform. This request should be routed to the web based flow.",[rs]:"Invalid base64 encoded string.",[is]:"Invalid PoP token request. The request should not have both a popKid value and signPopToken set to true.",[ss]:"Failed to build request headers object.",[as]:"Failed to parse response headers",[yt]:"Failed to decrypt ear response",[Ht]:"The request timed out."};class ht extends R{constructor(e,t){super(e,jc[e],t),Object.setPrototypeOf(this,ht.prototype),this.name="BrowserAuthError"}}function y(i,e){return new ht(i,e)}const Q={INVALID_GRANT_ERROR:"invalid_grant",POPUP_WIDTH:483,POPUP_HEIGHT:600,POPUP_NAME_PREFIX:"msal",DEFAULT_POLL_INTERVAL_MS:30,MSAL_SKU:"msal.js.browser"},X={CHANNEL_ID:"53ee284d-920a-4b59-9d30-a60315b26836",PREFERRED_EXTENSION_ID:"ppnbnpeolgkicgegkbkbjmhlideopiji",MATS_TELEMETRY:"MATS",MICROSOFT_ENTRA_BROKERID:"MicrosoftEntra",DOM_API_NAME:"DOM API",PLATFORM_DOM_APIS:"get-token-and-sign-out",PLATFORM_DOM_PROVIDER:"PlatformAuthDOMHandler",PLATFORM_EXTENSION_PROVIDER:"PlatformAuthExtensionHandler"},Je={HandshakeRequest:"Handshake",HandshakeResponse:"HandshakeResponse",GetToken:"GetToken",Response:"Response"},x={LocalStorage:"localStorage",SessionStorage:"sessionStorage",MemoryStorage:"memoryStorage"},rr={GET:"GET",POST:"POST"},me={SIGNIN:"signin",SIGNOUT:"signout"},N={ORIGIN_URI:"request.origin",URL_HASH:"urlHash",REQUEST_PARAMS:"request.params",VERIFIER:"code.verifier",INTERACTION_STATUS_KEY:"interaction.status",NATIVE_REQUEST:"request.native"},mt={WRAPPER_SKU:"wrapper.sku",WRAPPER_VER:"wrapper.version"},S={acquireTokenRedirect:861,acquireTokenPopup:862,ssoSilent:863,acquireTokenSilent_authCode:864,handleRedirectPromise:865,acquireTokenByCode:866,acquireTokenSilent_silentFlow:61,logout:961,logoutPopup:962,hydrateCache:963,loadExternalTokens:964},ir={861:"acquireTokenRedirect",862:"acquireTokenPopup",863:"ssoSilent",864:"acquireTokenSilent_authCode",865:"handleRedirectPromise",866:"acquireTokenByCode",61:"acquireTokenSilent_silentFlow",961:"logout",962:"logoutPopup",963:"hydrateCache",964:"loadExternalTokens"},Yc=i=>typeof i=="number"&&i in ir?ir[i]:"unknown";var T;(function(i){i.Redirect="redirect",i.Popup="popup",i.Silent="silent",i.None="none"})(T||(T={}));const sr={scopes:Ve},cs="jwk",Sn="msal.db",Jc=1,Xc=`${Sn}.keys`,B={Default:0,AccessToken:1,AccessTokenAndRefreshToken:2,RefreshToken:3,RefreshTokenAndNetwork:4,Skip:5},Zc=[B.Default,B.Skip,B.RefreshTokenAndNetwork];function pt(i){return encodeURIComponent(at(i).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"))}function Ee(i){return ls(i).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function at(i){return ls(new TextEncoder().encode(i))}function ls(i){const e=Array.from(i,t=>String.fromCodePoint(t)).join("");return btoa(e)}function q(i){return new TextDecoder().decode(Ae(i))}function Ae(i){let e=i.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw y(rs)}const t=atob(e);return Uint8Array.from(t,n=>n.codePointAt(0)||0)}const el="RSASSA-PKCS1-v1_5",je="AES-GCM",hs="HKDF",To="SHA-256",tl=2048,nl=new Uint8Array([1,0,1]),ar="0123456789abcdef",cr=new Uint32Array(1),Ao="raw",ds="encrypt",Io="decrypt",ol="deriveKey",rl="crypto_subtle_undefined",wo={name:el,hash:To,modulusLength:tl,publicExponent:nl};function il(i){if(!window)throw y(tn);if(!window.crypto)throw y(wn);if(!i&&!window.crypto.subtle)throw y(wn,rl)}async function us(i,e,t){e?.addQueueMeasurement(h.Sha256Digest,t);const o=new TextEncoder().encode(i);return window.crypto.subtle.digest(To,o)}function sl(i){return window.crypto.getRandomValues(i)}function dn(){return window.crypto.getRandomValues(cr),cr[0]}function ce(){const i=Date.now(),e=dn()*1024+(dn()&1023),t=new Uint8Array(16),n=Math.trunc(e/2**30),o=e&2**30-1,r=dn();t[0]=i/2**40,t[1]=i/2**32,t[2]=i/2**24,t[3]=i/2**16,t[4]=i/2**8,t[5]=i,t[6]=112|n>>>8,t[7]=n,t[8]=128|o>>>24,t[9]=o>>>16,t[10]=o>>>8,t[11]=o,t[12]=r>>>24,t[13]=r>>>16,t[14]=r>>>8,t[15]=r;let s="";for(let a=0;a<t.length;a++)s+=ar.charAt(t[a]>>>4),s+=ar.charAt(t[a]&15),(a===3||a===5||a===7||a===9)&&(s+="-");return s}async function al(i,e){return window.crypto.subtle.generateKey(wo,i,e)}async function un(i){return window.crypto.subtle.exportKey(cs,i)}async function cl(i,e,t){return window.crypto.subtle.importKey(cs,i,wo,e,t)}async function ll(i,e){return window.crypto.subtle.sign(wo,i,e)}async function Eo(){const i=await gs(),t={alg:"dir",kty:"oct",k:Ee(new Uint8Array(i))};return at(JSON.stringify(t))}async function hl(i){const e=q(i),n=JSON.parse(e).k,o=Ae(n);return window.crypto.subtle.importKey(Ao,o,je,!1,[Io])}async function dl(i,e){const t=e.split(".");if(t.length!==5)throw y(yt,"jwe_length");const n=await hl(i).catch(()=>{throw y(yt,"import_key")});try{const o=new TextEncoder().encode(t[0]),r=Ae(t[2]),s=Ae(t[3]),a=Ae(t[4]),c=a.byteLength*8,l=new Uint8Array(s.length+a.length);l.set(s),l.set(a,s.length);const d=await window.crypto.subtle.decrypt({name:je,iv:r,tagLength:c,additionalData:o},n,l);return new TextDecoder().decode(d)}catch{throw y(yt,"decrypt")}}async function gs(){const i=await window.crypto.subtle.generateKey({name:je,length:256},!0,[ds,Io]);return window.crypto.subtle.exportKey(Ao,i)}async function lr(i){return window.crypto.subtle.importKey(Ao,i,hs,!1,[ol])}async function fs(i,e,t){return window.crypto.subtle.deriveKey({name:hs,salt:e,hash:To,info:new TextEncoder().encode(t)},i,{name:je,length:256},!1,[ds,Io])}async function ul(i,e,t){const n=new TextEncoder().encode(e),o=window.crypto.getRandomValues(new Uint8Array(16)),r=await fs(i,o,t),s=await window.crypto.subtle.encrypt({name:je,iv:new Uint8Array(12)},r,n);return{data:Ee(new Uint8Array(s)),nonce:Ee(o)}}async function hr(i,e,t,n){const o=Ae(n),r=await fs(i,Ae(e),t),s=await window.crypto.subtle.decrypt({name:je,iv:new Uint8Array(12)},r,o);return new TextDecoder().decode(s)}async function ms(i){const e=await us(i),t=new Uint8Array(e);return Ee(t)}const nn="storage_not_supported",ps="stubbed_public_client_application_called",So="in_mem_redirect_unavailable";const Tt={[nn]:"Given storage configuration option was not supported.",[ps]:"Stub instance of Public Client Application was called. If using msal-react, please ensure context is not used without a provider. For more visit: aka.ms/msaljs/browser-errors",[So]:"Redirect cannot be supported. In-memory storage was selected and storeAuthStateInCookie=false, which would cause the library to be unable to handle the incoming hash. If you would like to use the redirect API, please use session/localStorage or set storeAuthStateInCookie=true."};Tt[nn],Tt[ps],Tt[So];class ko extends R{constructor(e,t){super(e,t),this.name="BrowserConfigurationAuthError",Object.setPrototypeOf(this,ko.prototype)}}function vo(i){return new ko(i,Tt[i])}function Cs(i){i.location.hash="",typeof i.history.replaceState=="function"&&i.history.replaceState(null,"",`${i.location.origin}${i.location.pathname}${i.location.search}`)}function gl(i){const e=i.split("#");e.shift(),window.location.hash=e.length>0?e.join("#"):""}function _o(){return window.parent!==window}function fl(){return typeof window<"u"&&!!window.opener&&window.opener!==window&&typeof window.name=="string"&&window.name.indexOf(`${Q.POPUP_NAME_PREFIX}.`)===0}function de(){return typeof window<"u"&&window.location?window.location.href.split("?")[0].split("#")[0]:""}function ml(){const e=new k(window.location.href).getUrlComponents();return`${e.Protocol}//${e.HostNameAndPort}/`}function pl(){if(k.hashContainsKnownProperties(window.location.hash)&&_o())throw y(zi)}function Cl(i){if(_o()&&!i)throw y(Gi)}function yl(){if(fl())throw y(qi)}function ys(){if(typeof window>"u")throw y(tn)}function Ts(i){if(!i)throw y(nt)}function Ro(i){ys(),pl(),yl(),Ts(i)}function dr(i,e){if(Ro(i),Cl(e.system.allowRedirectInIframe),e.cache.cacheLocation===x.MemoryStorage&&!e.cache.storeAuthStateInCookie)throw vo(So)}function As(i){const e=document.createElement("link");e.rel="preconnect",e.href=new URL(i).origin,e.crossOrigin="anonymous",document.head.appendChild(e),window.setTimeout(()=>{try{document.head.removeChild(e)}catch{}},1e4)}function Tl(){return ce()}class xt{navigateInternal(e,t){return xt.defaultNavigateWindow(e,t)}navigateExternal(e,t){return xt.defaultNavigateWindow(e,t)}static defaultNavigateWindow(e,t){return t.noHistory?window.location.replace(e):window.location.assign(e),new Promise((n,o)=>{setTimeout(()=>{o(y(Ht,"failed_to_redirect"))},t.timeout)})}}class Al{async sendGetRequestAsync(e,t){let n,o={},r=0;const s=ur(t);try{n=await fetch(e,{method:rr.GET,headers:s})}catch(a){throw Ze(y(window.navigator.onLine?ji:Lt),void 0,void 0,a)}o=gr(n.headers);try{return r=n.status,{headers:o,body:await n.json(),status:r}}catch(a){throw Ze(y(En),r,o,a)}}async sendPostRequestAsync(e,t){const n=t&&t.body||"",o=ur(t);let r,s=0,a={};try{r=await fetch(e,{method:rr.POST,headers:o,body:n})}catch(c){throw Ze(y(window.navigator.onLine?Wi:Lt),void 0,void 0,c)}a=gr(r.headers);try{return s=r.status,{headers:a,body:await r.json(),status:s}}catch(c){throw Ze(y(En),s,a,c)}}}function ur(i){try{const e=new Headers;if(!(i&&i.headers))return e;const t=i.headers;return Object.entries(t).forEach(([n,o])=>{e.append(n,o)}),e}catch(e){throw Ze(y(ss),void 0,void 0,e)}}function gr(i){try{const e={};return i.forEach((t,n)=>{e[n]=t}),e}catch{throw y(as)}}const Il=6e4,kn=1e4,wl=3e4,Is=2e3;function El({auth:i,cache:e,system:t,telemetry:n},o){const r={clientId:f.EMPTY_STRING,authority:`${f.DEFAULT_AUTHORITY}`,knownAuthorities:[],cloudDiscoveryMetadata:f.EMPTY_STRING,authorityMetadata:f.EMPTY_STRING,redirectUri:typeof window<"u"?de():"",postLogoutRedirectUri:f.EMPTY_STRING,navigateToLoginRequestUrl:!0,clientCapabilities:[],protocolMode:V.AAD,OIDCOptions:{serverResponseType:Gt.FRAGMENT,defaultScopes:[f.OPENID_SCOPE,f.PROFILE_SCOPE,f.OFFLINE_ACCESS_SCOPE]},azureCloudOptions:{azureCloudInstance:xn.None,tenant:f.EMPTY_STRING},skipAuthorityMetadataCache:!1,supportsNestedAppAuth:!1,instanceAware:!1,encodeExtraQueryParams:!1,verifySSO:!1},s={cacheLocation:x.SessionStorage,cacheRetentionDays:5,temporaryCacheLocation:x.SessionStorage,storeAuthStateInCookie:!1,secureCookies:!1,cacheMigrationEnabled:!!(e&&e.cacheLocation===x.LocalStorage),claimsBasedCachingEnabled:!1},a={loggerCallback:()=>{},logLevel:b.Info,piiLoggingEnabled:!1},l={...{...ci,loggerOptions:a,networkClient:o?new Al:Dc,navigationClient:new xt,loadFrameTimeout:0,windowHashTimeout:t?.loadFrameTimeout||Il,iframeHashTimeout:t?.loadFrameTimeout||kn,navigateFrameWait:0,redirectNavigationTimeout:wl,asyncPopups:!1,allowRedirectInIframe:!1,allowPlatformBroker:!1,allowPlatformBrokerWithDOM:!1,nativeBrokerHandshakeTimeout:t?.nativeBrokerHandshakeTimeout||Is,pollIntervalMilliseconds:Q.DEFAULT_POLL_INTERVAL_MS},...t,loggerOptions:t?.loggerOptions||a},d={application:{appName:f.EMPTY_STRING,appVersion:f.EMPTY_STRING},client:new ai};if(i?.protocolMode!==V.OIDC&&i?.OIDCOptions&&new we(l.loggerOptions).warning(JSON.stringify(_(Jr))),i?.protocolMode&&i.protocolMode===V.OIDC&&l?.allowPlatformBroker)throw _(Xr);return{auth:{...r,...i,OIDCOptions:{...r.OIDCOptions,...i?.OIDCOptions}},cache:{...s,...e},system:l,telemetry:{...d,...n}}}const Sl="@azure/msal-browser",Oe="4.30.0";const K="msal",ws="browser",fr="|",F=2,At=2,kl=`${K}.${ws}.log.level`,vl=`${K}.${ws}.log.pii`,mr=`${K}.version`,pr="account.keys",Cr="token.keys";function Be(i=At){return i<1?`${K}.${pr}`:`${K}.${i}.${pr}`}function Ge(i,e=F){return e<1?`${K}.${Cr}.${i}`:`${K}.${e}.${Cr}.${i}`}class bo{static loggerCallback(e,t){switch(e){case b.Error:console.error(t);return;case b.Info:console.info(t);return;case b.Verbose:console.debug(t);return;case b.Warning:console.warn(t);return;default:console.log(t);return}}constructor(e){this.browserEnvironment=typeof window<"u",this.config=El(e,this.browserEnvironment);let t;try{t=window[x.SessionStorage]}catch{}const n=t?.getItem(kl),o=t?.getItem(vl)?.toLowerCase(),r=o==="true"?!0:o==="false"?!1:void 0,s={...this.config.system.loggerOptions},a=n&&Object.keys(b).includes(n)?b[n]:void 0;a&&(s.loggerCallback=bo.loggerCallback,s.logLevel=a),r!==void 0&&(s.piiLoggingEnabled=r),this.logger=new we(s,Sl,Oe),this.available=!1}getConfig(){return this.config}getLogger(){return this.logger}isAvailable(){return this.available}isBrowserEnvironment(){return this.browserEnvironment}}class Ne extends bo{getModuleName(){return Ne.MODULE_NAME}getId(){return Ne.ID}async initialize(){return this.available=typeof window<"u",this.available}}Ne.MODULE_NAME="";Ne.ID="StandardOperatingContext";class _l{constructor(){this.dbName=Sn,this.version=Jc,this.tableName=Xc,this.dbOpen=!1}async open(){return new Promise((e,t)=>{const n=window.indexedDB.open(this.dbName,this.version);n.addEventListener("upgradeneeded",o=>{o.target.result.createObjectStore(this.tableName)}),n.addEventListener("success",o=>{const r=o;this.db=r.target.result,this.dbOpen=!0,e()}),n.addEventListener("error",()=>t(y(Co)))})}closeConnection(){const e=this.db;e&&this.dbOpen&&(e.close(),this.dbOpen=!1)}async validateDbIsOpen(){if(!this.dbOpen)return this.open()}async getItem(e){return await this.validateDbIsOpen(),new Promise((t,n)=>{if(!this.db)return n(y(De));const s=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).get(e);s.addEventListener("success",a=>{const c=a;this.closeConnection(),t(c.target.result)}),s.addEventListener("error",a=>{this.closeConnection(),n(a)})})}async setItem(e,t){return await this.validateDbIsOpen(),new Promise((n,o)=>{if(!this.db)return o(y(De));const a=this.db.transaction([this.tableName],"readwrite").objectStore(this.tableName).put(t,e);a.addEventListener("success",()=>{this.closeConnection(),n()}),a.addEventListener("error",c=>{this.closeConnection(),o(c)})})}async removeItem(e){return await this.validateDbIsOpen(),new Promise((t,n)=>{if(!this.db)return n(y(De));const s=this.db.transaction([this.tableName],"readwrite").objectStore(this.tableName).delete(e);s.addEventListener("success",()=>{this.closeConnection(),t()}),s.addEventListener("error",a=>{this.closeConnection(),n(a)})})}async getKeys(){return await this.validateDbIsOpen(),new Promise((e,t)=>{if(!this.db)return t(y(De));const r=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).getAllKeys();r.addEventListener("success",s=>{const a=s;this.closeConnection(),e(a.target.result)}),r.addEventListener("error",s=>{this.closeConnection(),t(s)})})}async containsKey(e){return await this.validateDbIsOpen(),new Promise((t,n)=>{if(!this.db)return n(y(De));const s=this.db.transaction([this.tableName],"readonly").objectStore(this.tableName).count(e);s.addEventListener("success",a=>{const c=a;this.closeConnection(),t(c.target.result===1)}),s.addEventListener("error",a=>{this.closeConnection(),n(a)})})}async deleteDatabase(){return this.db&&this.dbOpen&&this.closeConnection(),new Promise((e,t)=>{const n=window.indexedDB.deleteDatabase(Sn),o=setTimeout(()=>t(!1),200);n.addEventListener("success",()=>(clearTimeout(o),e(!0))),n.addEventListener("blocked",()=>(clearTimeout(o),e(!0))),n.addEventListener("error",()=>(clearTimeout(o),t(!1)))})}}class on{constructor(){this.cache=new Map}async initialize(){}getItem(e){return this.cache.get(e)||null}getUserData(e){return this.getItem(e)}setItem(e,t){this.cache.set(e,t)}async setUserData(e,t){this.setItem(e,t)}removeItem(e){this.cache.delete(e)}getKeys(){const e=[];return this.cache.forEach((t,n)=>{e.push(n)}),e}containsKey(e){return this.cache.has(e)}clear(){this.cache.clear()}decryptData(){return Promise.resolve(null)}}class Rl{constructor(e){this.inMemoryCache=new on,this.indexedDBCache=new _l,this.logger=e}handleDatabaseAccessError(e){if(e instanceof ht&&e.errorCode===Co)this.logger.error("Could not access persistent storage. This may be caused by browser privacy features which block persistent storage in third-party contexts.");else throw e}async getItem(e){const t=this.inMemoryCache.getItem(e);if(!t)try{return this.logger.verbose("Queried item not found in in-memory cache, now querying persistent storage."),await this.indexedDBCache.getItem(e)}catch(n){this.handleDatabaseAccessError(n)}return t}async setItem(e,t){this.inMemoryCache.setItem(e,t);try{await this.indexedDBCache.setItem(e,t)}catch(n){this.handleDatabaseAccessError(n)}}async removeItem(e){this.inMemoryCache.removeItem(e);try{await this.indexedDBCache.removeItem(e)}catch(t){this.handleDatabaseAccessError(t)}}async getKeys(){const e=this.inMemoryCache.getKeys();if(e.length===0)try{return this.logger.verbose("In-memory cache is empty, now querying persistent storage."),await this.indexedDBCache.getKeys()}catch(t){this.handleDatabaseAccessError(t)}return e}async containsKey(e){const t=this.inMemoryCache.containsKey(e);if(!t)try{return this.logger.verbose("Key not found in in-memory cache, now querying persistent storage."),await this.indexedDBCache.containsKey(e)}catch(n){this.handleDatabaseAccessError(n)}return t}clearInMemory(){this.logger.verbose("Deleting in-memory keystore"),this.inMemoryCache.clear(),this.logger.verbose("In-memory keystore deleted")}async clearPersistent(){try{this.logger.verbose("Deleting persistent keystore");const e=await this.indexedDBCache.deleteDatabase();return e&&this.logger.verbose("Persistent keystore deleted"),e}catch(e){return this.handleDatabaseAccessError(e),!1}}}class ue{constructor(e,t,n){this.logger=e,il(n??!1),this.cache=new Rl(this.logger),this.performanceClient=t}createNewGuid(){return ce()}base64Encode(e){return at(e)}base64Decode(e){return q(e)}base64UrlEncode(e){return pt(e)}encodeKid(e){return this.base64UrlEncode(JSON.stringify({kid:e}))}async getPublicKeyThumbprint(e){const t=this.performanceClient?.startMeasurement(h.CryptoOptsGetPublicKeyThumbprint,e.correlationId),n=await al(ue.EXTRACTABLE,ue.POP_KEY_USAGES),o=await un(n.publicKey),r={e:o.e,kty:o.kty,n:o.n},s=yr(r),a=await this.hashString(s),c=await un(n.privateKey),l=await cl(c,!1,["sign"]);return await this.cache.setItem(a,{privateKey:l,publicKey:n.publicKey,requestMethod:e.resourceRequestMethod,requestUri:e.resourceRequestUri}),t&&t.end({success:!0}),a}async removeTokenBindingKey(e){if(await this.cache.removeItem(e),await this.cache.containsKey(e))throw p(Fr)}async clearKeystore(){this.cache.clearInMemory();try{return await this.cache.clearPersistent(),!0}catch(e){return e instanceof Error?this.logger.error(`Clearing keystore failed with error: ${e.message}`):this.logger.error("Clearing keystore failed with unknown error"),!1}}async signJwt(e,t,n,o){const r=this.performanceClient?.startMeasurement(h.CryptoOptsSignJwt,o),s=await this.cache.getItem(t);if(!s)throw y(po);const a=await un(s.publicKey),c=yr(a),l=pt(JSON.stringify({kid:t})),d=uo.getShrHeaderString({...n?.header,alg:a.alg,kid:l}),u=pt(d);e.cnf={jwk:JSON.parse(c)};const m=pt(JSON.stringify(e)),C=`${u}.${m}`,I=new TextEncoder().encode(C),D=await ll(s.privateKey,I),Z=Ee(new Uint8Array(D)),P=`${C}.${Z}`;return r&&r.end({success:!0}),P}async hashString(e){return ms(e)}}ue.POP_KEY_USAGES=["sign","verify"];ue.EXTRACTABLE=!0;function yr(i){return JSON.stringify(i,Object.keys(i).sort())}const bl=1440*60*1e3,vn={Lax:"Lax",None:"None"};class Es{initialize(){return Promise.resolve()}getItem(e){const t=`${encodeURIComponent(e)}`,n=document.cookie.split(";");for(let o=0;o<n.length;o++){const r=n[o],[s,...a]=decodeURIComponent(r).trim().split("="),c=a.join("=");if(s===t)return c}return""}getUserData(){throw p(w)}setItem(e,t,n,o=!0,r=vn.Lax){let s=`${encodeURIComponent(e)}=${encodeURIComponent(t)};path=/;SameSite=${r};`;if(n){const a=Pl(n);s+=`expires=${a};`}(o||r===vn.None)&&(s+="Secure;"),document.cookie=s}async setUserData(){return Promise.reject(p(w))}removeItem(e){this.setItem(e,"",-1)}getKeys(){const e=document.cookie.split(";"),t=[];return e.forEach(n=>{const o=decodeURIComponent(n).trim().split("=");t.push(o[0])}),t}containsKey(e){return this.getKeys().includes(e)}decryptData(){return Promise.resolve(null)}}function Pl(i){const e=new Date;return new Date(e.getTime()+i*bl).toUTCString()}function fe(i,e){const t=i.getItem(Be(e));return t?JSON.parse(t):[]}function ee(i,e,t){const n=e.getItem(Ge(i,t));if(n){const o=JSON.parse(n);if(o&&o.hasOwnProperty("idToken")&&o.hasOwnProperty("accessToken")&&o.hasOwnProperty("refreshToken"))return o}return{idToken:[],accessToken:[],refreshToken:[]}}function It(i){return i.hasOwnProperty("id")&&i.hasOwnProperty("nonce")&&i.hasOwnProperty("data")}const Tr="msal.cache.encryption",Ol="msal.broadcast.cache";class Nl{constructor(e,t,n){if(!window.localStorage)throw vo(nn);this.memoryStorage=new on,this.initialized=!1,this.clientId=e,this.logger=t,this.performanceClient=n,this.broadcast=new BroadcastChannel(Ol)}async initialize(e){const t=new Es,n=t.getItem(Tr);let o={key:"",id:""};if(n)try{o=JSON.parse(n)}catch{}if(o.key&&o.id){const r=W(Ae,h.Base64Decode,this.logger,this.performanceClient,e)(o.key);this.encryptionCookie={id:o.id,key:await g(lr,h.GenerateHKDF,this.logger,this.performanceClient,e)(r)}}else{const r=ce(),s=await g(gs,h.GenerateBaseKey,this.logger,this.performanceClient,e)(),a=W(Ee,h.UrlEncodeArr,this.logger,this.performanceClient,e)(new Uint8Array(s));this.encryptionCookie={id:r,key:await g(lr,h.GenerateHKDF,this.logger,this.performanceClient,e)(s)};const c={id:r,key:a};t.setItem(Tr,JSON.stringify(c),0,!0,vn.None)}await g(this.importExistingCache.bind(this),h.ImportExistingCache,this.logger,this.performanceClient,e)(e),this.broadcast.addEventListener("message",this.updateCache.bind(this)),this.initialized=!0}getItem(e){return window.localStorage.getItem(e)}getUserData(e){if(!this.initialized)throw y(nt);return this.memoryStorage.getItem(e)}async decryptData(e,t,n){if(!this.initialized||!this.encryptionCookie)throw y(nt);if(t.id!==this.encryptionCookie.id)return this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},n),null;const o=await g(hr,h.Decrypt,this.logger,this.performanceClient,n)(this.encryptionCookie.key,t.nonce,this.getContext(e),t.data);if(!o)return null;try{return{...JSON.parse(o),lastUpdatedAt:t.lastUpdatedAt}}catch{return this.performanceClient.incrementFields({encryptedCacheCorruptionCount:1},n),null}}setItem(e,t){window.localStorage.setItem(e,t)}async setUserData(e,t,n,o,r){if(!this.initialized||!this.encryptionCookie)throw y(nt);if(r)this.setItem(e,t);else{const{data:s,nonce:a}=await g(ul,h.Encrypt,this.logger,this.performanceClient,n)(this.encryptionCookie.key,t,this.getContext(e)),c={id:this.encryptionCookie.id,nonce:a,data:s,lastUpdatedAt:o};this.setItem(e,JSON.stringify(c))}this.memoryStorage.setItem(e,t),this.broadcast.postMessage({key:e,value:t,context:this.getContext(e)})}removeItem(e){this.memoryStorage.containsKey(e)&&(this.memoryStorage.removeItem(e),this.broadcast.postMessage({key:e,value:null,context:this.getContext(e)})),window.localStorage.removeItem(e)}getKeys(){return Object.keys(window.localStorage)}containsKey(e){return window.localStorage.hasOwnProperty(e)}clear(){this.memoryStorage.clear(),fe(this).forEach(n=>this.removeItem(n));const t=ee(this.clientId,this);t.idToken.forEach(n=>this.removeItem(n)),t.accessToken.forEach(n=>this.removeItem(n)),t.refreshToken.forEach(n=>this.removeItem(n)),this.getKeys().forEach(n=>{(n.startsWith(K)||n.indexOf(this.clientId)!==-1)&&this.removeItem(n)})}async importExistingCache(e){if(!this.encryptionCookie)return;let t=fe(this);t=await this.importArray(t,e),t.length?this.setItem(Be(),JSON.stringify(t)):this.removeItem(Be());const n=ee(this.clientId,this);n.idToken=await this.importArray(n.idToken,e),n.accessToken=await this.importArray(n.accessToken,e),n.refreshToken=await this.importArray(n.refreshToken,e),n.idToken.length||n.accessToken.length||n.refreshToken.length?this.setItem(Ge(this.clientId),JSON.stringify(n)):this.removeItem(Ge(this.clientId))}async getItemFromEncryptedCache(e,t){if(!this.encryptionCookie)return null;const n=this.getItem(e);if(!n)return null;let o;try{o=JSON.parse(n)}catch{return null}return It(o)?o.id!==this.encryptionCookie.id?(this.performanceClient.incrementFields({encryptedCacheExpiredCount:1},t),null):(this.performanceClient.incrementFields({encryptedCacheCount:1},t),g(hr,h.Decrypt,this.logger,this.performanceClient,t)(this.encryptionCookie.key,o.nonce,this.getContext(e),o.data)):(this.performanceClient.incrementFields({unencryptedCacheCount:1},t),n)}async importArray(e,t){const n=[],o=[];return e.forEach(r=>{const s=this.getItemFromEncryptedCache(r,t).then(a=>{a?(this.memoryStorage.setItem(r,a),n.push(r)):this.removeItem(r)});o.push(s)}),await Promise.all(o),n}getContext(e){let t="";return e.includes(this.clientId)&&(t=this.clientId),t}updateCache(e){this.logger.trace("Updating internal cache from broadcast event");const t=this.performanceClient.startMeasurement(h.LocalStorageUpdated);t.add({isBackground:!0});const{key:n,value:o,context:r}=e.data;if(!n){this.logger.error("Broadcast event missing key"),t.end({success:!1,errorCode:"noKey"});return}if(r&&r!==this.clientId){this.logger.trace(`Ignoring broadcast event from clientId: ${r}`),t.end({success:!1,errorCode:"contextMismatch"});return}o?(this.memoryStorage.setItem(n,o),this.logger.verbose("Updated item in internal cache")):(this.memoryStorage.removeItem(n),this.logger.verbose("Removed item from internal cache")),t.end({success:!0})}}class Ml{constructor(){if(!window.sessionStorage)throw vo(nn)}async initialize(){}getItem(e){return window.sessionStorage.getItem(e)}getUserData(e){return this.getItem(e)}setItem(e,t){window.sessionStorage.setItem(e,t)}async setUserData(e,t){this.setItem(e,t)}removeItem(e){window.sessionStorage.removeItem(e)}getKeys(){return Object.keys(window.sessionStorage)}containsKey(e){return window.sessionStorage.hasOwnProperty(e)}decryptData(){return Promise.resolve(null)}}const A={INITIALIZE_START:"msal:initializeStart",INITIALIZE_END:"msal:initializeEnd",ACCOUNT_ADDED:"msal:accountAdded",ACCOUNT_REMOVED:"msal:accountRemoved",ACTIVE_ACCOUNT_CHANGED:"msal:activeAccountChanged",LOGIN_START:"msal:loginStart",LOGIN_SUCCESS:"msal:loginSuccess",LOGIN_FAILURE:"msal:loginFailure",ACQUIRE_TOKEN_START:"msal:acquireTokenStart",ACQUIRE_TOKEN_SUCCESS:"msal:acquireTokenSuccess",ACQUIRE_TOKEN_FAILURE:"msal:acquireTokenFailure",ACQUIRE_TOKEN_NETWORK_START:"msal:acquireTokenFromNetworkStart",SSO_SILENT_START:"msal:ssoSilentStart",SSO_SILENT_SUCCESS:"msal:ssoSilentSuccess",SSO_SILENT_FAILURE:"msal:ssoSilentFailure",ACQUIRE_TOKEN_BY_CODE_START:"msal:acquireTokenByCodeStart",ACQUIRE_TOKEN_BY_CODE_SUCCESS:"msal:acquireTokenByCodeSuccess",ACQUIRE_TOKEN_BY_CODE_FAILURE:"msal:acquireTokenByCodeFailure",HANDLE_REDIRECT_START:"msal:handleRedirectStart",HANDLE_REDIRECT_END:"msal:handleRedirectEnd",POPUP_OPENED:"msal:popupOpened",LOGOUT_START:"msal:logoutStart",LOGOUT_SUCCESS:"msal:logoutSuccess",LOGOUT_FAILURE:"msal:logoutFailure",LOGOUT_END:"msal:logoutEnd",RESTORE_FROM_BFCACHE:"msal:restoreFromBFCache",BROKER_CONNECTION_ESTABLISHED:"msal:brokerConnectionEstablished"};function ge(i,e){const t=i.indexOf(e);t>-1&&i.splice(t,1)}class _n extends An{constructor(e,t,n,o,r,s,a){super(e,n,o,r,a),this.cacheConfig=t,this.logger=o,this.internalStorage=new on,this.browserStorage=Ar(e,t.cacheLocation,o,r),this.temporaryCacheStorage=Ar(e,t.temporaryCacheLocation,o,r),this.cookieStorage=new Es,this.eventHandler=s}async initialize(e){this.performanceClient.addFields({cacheLocation:this.cacheConfig.cacheLocation,cacheRetentionDays:this.cacheConfig.cacheRetentionDays},e),await this.browserStorage.initialize(e),await this.migrateExistingCache(e),this.trackVersionChanges(e)}async migrateExistingCache(e){let t=fe(this.browserStorage),n=ee(this.clientId,this.browserStorage);this.performanceClient.addFields({preMigrateAcntCount:t.length,preMigrateATCount:n.accessToken.length,preMigrateITCount:n.idToken.length,preMigrateRTCount:n.refreshToken.length},e);for(let r=0;r<At;r++){const s=r;await this.removeStaleAccounts(r,s,e)}for(let r=0;r<F;r++){const s=r;await this.migrateIdTokens(r,s,e)}const o=this.getKMSIValues();for(let r=0;r<F;r++)await this.migrateAccessTokens(r,o,e),await this.migrateRefreshTokens(r,o,e);t=fe(this.browserStorage),n=ee(this.clientId,this.browserStorage),this.performanceClient.addFields({postMigrateAcntCount:t.length,postMigrateATCount:n.accessToken.length,postMigrateITCount:n.idToken.length,postMigrateRTCount:n.refreshToken.length},e)}async updateOldEntry(e,t){const n=this.browserStorage.getItem(e),o=this.validateAndParseJson(n||"");if(!o)return this.browserStorage.removeItem(e),null;if(!o.lastUpdatedAt)o.lastUpdatedAt=Date.now().toString(),this.setItem(e,JSON.stringify(o),t);else if(Yo(o.lastUpdatedAt,this.cacheConfig.cacheRetentionDays))return this.browserStorage.removeItem(e),this.performanceClient.incrementFields({expiredCacheRemovedCount:1},t),null;const r=It(o)?await this.browserStorage.decryptData(e,o,t):o;return!r||!jt(r)?(this.performanceClient.incrementFields({invalidCacheCount:1},t),null):(Jo(r)||Xo(r))&&r.expiresOn&&Mt(r.expiresOn,Er)?(this.browserStorage.removeItem(e),this.performanceClient.incrementFields({expiredCacheRemovedCount:1},t),null):r}async removeStaleAccounts(e,t,n){const o=fe(this.browserStorage,e);if(o.length!==0){for(const r of[...o]){this.performanceClient.incrementFields({oldAcntCount:1},n);const s=this.browserStorage.getItem(r),a=this.validateAndParseJson(s||"");if(!a){ge(o,r);continue}if(a.lastUpdatedAt)Yo(a.lastUpdatedAt,this.cacheConfig.cacheRetentionDays)&&(await this.removeAccountOldSchema(r,a,t,n),ge(o,r));else{a.lastUpdatedAt=Date.now().toString(),this.setItem(r,JSON.stringify(a),n);continue}}this.setAccountKeys(o,n,e)}}async removeAccountOldSchema(e,t,n,o){const s=(It(t)?await this.browserStorage.decryptData(e,t,o):t)?.homeAccountId;if(s){const a=this.getTokenKeys(n);[...a.idToken].filter(c=>c.includes(s)).forEach(c=>{this.browserStorage.removeItem(c),ge(a.idToken,c)}),[...a.accessToken].filter(c=>c.includes(s)).forEach(c=>{this.browserStorage.removeItem(c),ge(a.accessToken,c)}),[...a.refreshToken].filter(c=>c.includes(s)).forEach(c=>{this.browserStorage.removeItem(c),ge(a.refreshToken,c)}),this.setTokenKeys(a,o,n)}this.performanceClient.incrementFields({expiredAcntRemovedCount:1},o),this.browserStorage.removeItem(e)}getKMSIValues(){const e={},t=this.getTokenKeys().idToken;for(const n of t){const o=this.browserStorage.getUserData(n);if(o){const r=JSON.parse(o),s=se(r.secret,q);s&&(e[r.homeAccountId]=ae(s))}}return e}async migrateIdTokens(e,t,n){const o=ee(this.clientId,this.browserStorage,e);if(o.idToken.length===0)return;const r=ee(this.clientId,this.browserStorage,F),s=fe(this.browserStorage),a=fe(this.browserStorage,t);for(const c of[...o.idToken]){this.performanceClient.incrementFields({oldITCount:1},n);const l=await this.updateOldEntry(c,n);if(!l){ge(o.idToken,c);continue}const d=s.find(P=>P.includes(l.homeAccountId)),u=a.find(P=>P.includes(l.homeAccountId));let m=null;if(d)m=this.getAccount(d,n);else if(u){const P=this.browserStorage.getItem(u),j=this.validateAndParseJson(P||"");m=j&&It(j)?await this.browserStorage.decryptData(u,j,n):j}if(!m){this.performanceClient.incrementFields({skipITMigrateCount:1},n);continue}const C=se(l.secret,q),E=this.generateCredentialKey(l),I=this.getIdTokenCredential(E,n),D=Object.keys(C).includes("signin_state"),Z=I&&Object.keys(se(I.secret,q)||{}).includes("signin_state");if(!I||l.lastUpdatedAt>I.lastUpdatedAt&&(D||!Z)){const P=m.tenantProfiles||[],j=qn(C)||m.realm;if(j&&!P.find(an=>an.tenantId===j)){const an=xe(m.homeAccountId,m.localAccountId,j,C);P.push(an)}m.tenantProfiles=P;const Se=this.generateAccountKey(O.getAccountInfo(m)),ke=ae(C);await this.setUserData(Se,JSON.stringify(m),n,m.lastUpdatedAt,ke),s.includes(Se)||s.push(Se),await this.setUserData(E,JSON.stringify(l),n,l.lastUpdatedAt,ke),this.performanceClient.incrementFields({migratedITCount:1},n),r.idToken.push(E)}}this.setTokenKeys(o,n,e),this.setTokenKeys(r,n),this.setAccountKeys(s,n)}async migrateAccessTokens(e,t,n){const o=ee(this.clientId,this.browserStorage,e);if(o.accessToken.length===0)return;const r=ee(this.clientId,this.browserStorage,F);for(const s of[...o.accessToken]){this.performanceClient.incrementFields({oldATCount:1},n);const a=await this.updateOldEntry(s,n);if(!a){ge(o.accessToken,s);continue}if(!Object.keys(t).includes(a.homeAccountId)){this.performanceClient.incrementFields({skipATMigrateCount:1},n);continue}const c=this.generateCredentialKey(a),l=t[a.homeAccountId];if(!r.accessToken.includes(c))await this.setUserData(c,JSON.stringify(a),n,a.lastUpdatedAt,l),this.performanceClient.incrementFields({migratedATCount:1},n),r.accessToken.push(c);else{const d=this.getAccessTokenCredential(c,n);(!d||a.lastUpdatedAt>d.lastUpdatedAt)&&(await this.setUserData(c,JSON.stringify(a),n,a.lastUpdatedAt,l),this.performanceClient.incrementFields({migratedATCount:1},n))}}this.setTokenKeys(o,n,e),this.setTokenKeys(r,n)}async migrateRefreshTokens(e,t,n){const o=ee(this.clientId,this.browserStorage,e);if(o.refreshToken.length===0)return;const r=ee(this.clientId,this.browserStorage,F);for(const s of[...o.refreshToken]){this.performanceClient.incrementFields({oldRTCount:1},n);const a=await this.updateOldEntry(s,n);if(!a){ge(o.refreshToken,s);continue}if(!Object.keys(t).includes(a.homeAccountId)){this.performanceClient.incrementFields({skipRTMigrateCount:1},n);continue}const c=this.generateCredentialKey(a),l=t[a.homeAccountId];if(!r.refreshToken.includes(c))await this.setUserData(c,JSON.stringify(a),n,a.lastUpdatedAt,l),this.performanceClient.incrementFields({migratedRTCount:1},n),r.refreshToken.push(c);else{const d=this.getRefreshTokenCredential(c,n);(!d||a.lastUpdatedAt>d.lastUpdatedAt)&&(await this.setUserData(c,JSON.stringify(a),n,a.lastUpdatedAt,l),this.performanceClient.incrementFields({migratedRTCount:1},n))}}this.setTokenKeys(o,n,e),this.setTokenKeys(r,n)}trackVersionChanges(e){const t=this.browserStorage.getItem(mr);t&&(this.logger.info(`MSAL.js was last initialized by version: ${t}`),this.performanceClient.addFields({previousLibraryVersion:t},e)),t!==Oe&&this.setItem(mr,Oe,e)}validateAndParseJson(e){if(!e)return null;try{const t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}setItem(e,t,n){const o=new Array(F+1).fill(0),r=[],s=20;for(let a=0;a<=s;a++)try{if(this.browserStorage.setItem(e,t),a>0)for(let c=0;c<=F;c++){const l=o.slice(0,c).reduce((u,m)=>u+m,0);if(l>=a)break;const d=a>l+o[c]?l+o[c]:a;a>l&&o[c]>0&&this.removeAccessTokenKeys(r.slice(l,d),n,c)}break}catch(c){const l=Tn(c);if(l.errorCode===Pt&&a<s){if(!r.length)for(let d=0;d<=F;d++)if(e===Ge(this.clientId,d)){const u=JSON.parse(t).accessToken;r.push(...u),o[d]=u.length}else{const u=this.getTokenKeys(d).accessToken;r.push(...u),o[d]=u.length}if(r.length<=a)throw l;this.removeAccessToken(r[a],n,!1)}else throw l}}async setUserData(e,t,n,o,r){const s=new Array(F+1).fill(0),a=[],c=20;for(let l=0;l<=c;l++)try{if(await g(this.browserStorage.setUserData.bind(this.browserStorage),h.SetUserData,this.logger,this.performanceClient)(e,t,n,o,r),l>0)for(let d=0;d<=F;d++){const u=s.slice(0,d).reduce((C,E)=>C+E,0);if(u>=l)break;const m=l>u+s[d]?u+s[d]:l;l>u&&s[d]>0&&this.removeAccessTokenKeys(a.slice(u,m),n,d)}break}catch(d){const u=Tn(d);if(u.errorCode===Pt&&l<c){if(!a.length)for(let m=0;m<=F;m++){const C=this.getTokenKeys(m).accessToken;a.push(...C),s[m]=C.length}if(a.length<=l)throw u;this.removeAccessToken(a[l],n,!1)}else throw u}}getAccount(e,t){this.logger.trace("BrowserCacheManager.getAccount called");const n=this.browserStorage.getUserData(e);if(!n)return this.removeAccountKeyFromMap(e,t),null;const o=this.validateAndParseJson(n);return!o||!O.isAccountEntity(o)?null:(this.performanceClient.addFields({accountCachedBy:Yc(o.cachedByApiId)},t),An.toObject(new O,o))}async setAccount(e,t,n,o){this.logger.trace("BrowserCacheManager.setAccount called");const r=this.generateAccountKey(O.getAccountInfo(e)),s=Date.now().toString();e.lastUpdatedAt=s,e.cachedByApiId=o,await this.setUserData(r,JSON.stringify(e),t,s,n);const a=this.addAccountKeyToMap(r,t);this.performanceClient.addFields({kmsi:n},t),this.cacheConfig.cacheLocation===x.LocalStorage&&a&&this.eventHandler.emitEvent(A.ACCOUNT_ADDED,void 0,O.getAccountInfo(e))}getAccountKeys(){return fe(this.browserStorage)}setAccountKeys(e,t,n=At){e.length===0?this.removeItem(Be(n)):this.setItem(Be(n),JSON.stringify(e),t)}addAccountKeyToMap(e,t){this.logger.trace("BrowserCacheManager.addAccountKeyToMap called"),this.logger.tracePii(`BrowserCacheManager.addAccountKeyToMap called with key: ${e}`);const n=this.getAccountKeys();return n.indexOf(e)===-1?(n.push(e),this.setItem(Be(),JSON.stringify(n),t),this.logger.verbose("BrowserCacheManager.addAccountKeyToMap account key added"),!0):(this.logger.verbose("BrowserCacheManager.addAccountKeyToMap account key already exists in map"),!1)}removeAccountKeyFromMap(e,t){this.logger.trace("BrowserCacheManager.removeAccountKeyFromMap called"),this.logger.tracePii(`BrowserCacheManager.removeAccountKeyFromMap called with key: ${e}`);const n=this.getAccountKeys(),o=n.indexOf(e);o>-1?(n.splice(o,1),this.setAccountKeys(n,t),this.logger.trace("BrowserCacheManager.removeAccountKeyFromMap account key removed")):this.logger.trace("BrowserCacheManager.removeAccountKeyFromMap key not found in existing map")}removeAccount(e,t){const n=this.getActiveAccount(t);n?.homeAccountId===e.homeAccountId&&n?.environment===e.environment&&this.setActiveAccount(null,t),super.removeAccount(e,t),this.removeAccountKeyFromMap(this.generateAccountKey(e),t),this.browserStorage.getKeys().forEach(o=>{o.includes(e.homeAccountId)&&o.includes(e.environment)&&this.browserStorage.removeItem(o)}),this.cacheConfig.cacheLocation===x.LocalStorage&&this.eventHandler.emitEvent(A.ACCOUNT_REMOVED,void 0,e)}removeIdToken(e,t){super.removeIdToken(e,t);const n=this.getTokenKeys(),o=n.idToken.indexOf(e);o>-1&&(this.logger.info("idToken removed from tokenKeys map"),n.idToken.splice(o,1),this.setTokenKeys(n,t))}removeAccessToken(e,t,n=!0){super.removeAccessToken(e,t),n&&this.removeAccessTokenKeys([e],t)}removeAccessTokenKeys(e,t,n=F){this.logger.trace("removeAccessTokenKey called");const o=this.getTokenKeys(n);let r=0;if(e.forEach(s=>{const a=o.accessToken.indexOf(s);a>-1&&(o.accessToken.splice(a,1),r++)}),r>0){this.logger.info(`removed ${r} accessToken keys from tokenKeys map`),this.setTokenKeys(o,t,n);return}}removeRefreshToken(e,t){super.removeRefreshToken(e,t);const n=this.getTokenKeys(),o=n.refreshToken.indexOf(e);o>-1&&(this.logger.info("refreshToken removed from tokenKeys map"),n.refreshToken.splice(o,1),this.setTokenKeys(n,t))}getTokenKeys(e=F){return ee(this.clientId,this.browserStorage,e)}setTokenKeys(e,t,n=F){if(e.idToken.length===0&&e.accessToken.length===0&&e.refreshToken.length===0){this.removeItem(Ge(this.clientId,n));return}else this.setItem(Ge(this.clientId,n),JSON.stringify(e),t)}getIdTokenCredential(e,t){const n=this.browserStorage.getUserData(e);if(!n)return this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit"),this.removeIdToken(e,t),null;const o=this.validateAndParseJson(n);return!o||!Cc(o)?(this.logger.trace("BrowserCacheManager.getIdTokenCredential: called, no cache hit"),null):(this.logger.trace("BrowserCacheManager.getIdTokenCredential: cache hit"),o)}async setIdTokenCredential(e,t,n){this.logger.trace("BrowserCacheManager.setIdTokenCredential called");const o=this.generateCredentialKey(e),r=Date.now().toString();e.lastUpdatedAt=r,await this.setUserData(o,JSON.stringify(e),t,r,n);const s=this.getTokenKeys();s.idToken.indexOf(o)===-1&&(this.logger.info("BrowserCacheManager: addTokenKey - idToken added to map"),s.idToken.push(o),this.setTokenKeys(s,t))}getAccessTokenCredential(e,t){const n=this.browserStorage.getUserData(e);if(!n)return this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit"),this.removeAccessTokenKeys([e],t),null;const o=this.validateAndParseJson(n);return!o||!Jo(o)?(this.logger.trace("BrowserCacheManager.getAccessTokenCredential: called, no cache hit"),null):(this.logger.trace("BrowserCacheManager.getAccessTokenCredential: cache hit"),o)}async setAccessTokenCredential(e,t,n){this.logger.trace("BrowserCacheManager.setAccessTokenCredential called");const o=this.generateCredentialKey(e),r=Date.now().toString();e.lastUpdatedAt=r,await this.setUserData(o,JSON.stringify(e),t,r,n);const s=this.getTokenKeys(),a=s.accessToken.indexOf(o);a!==-1&&s.accessToken.splice(a,1),this.logger.trace(`access token ${a===-1?"added to":"updated in"} map`),s.accessToken.push(o),this.setTokenKeys(s,t)}getRefreshTokenCredential(e,t){const n=this.browserStorage.getUserData(e);if(!n)return this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit"),this.removeRefreshToken(e,t),null;const o=this.validateAndParseJson(n);return!o||!Xo(o)?(this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: called, no cache hit"),null):(this.logger.trace("BrowserCacheManager.getRefreshTokenCredential: cache hit"),o)}async setRefreshTokenCredential(e,t,n){this.logger.trace("BrowserCacheManager.setRefreshTokenCredential called");const o=this.generateCredentialKey(e),r=Date.now().toString();e.lastUpdatedAt=r,await this.setUserData(o,JSON.stringify(e),t,r,n);const s=this.getTokenKeys();s.refreshToken.indexOf(o)===-1&&(this.logger.info("BrowserCacheManager: addTokenKey - refreshToken added to map"),s.refreshToken.push(o),this.setTokenKeys(s,t))}getAppMetadata(e){const t=this.browserStorage.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit"),null;const n=this.validateAndParseJson(t);return!n||!Ic(e,n)?(this.logger.trace("BrowserCacheManager.getAppMetadata: called, no cache hit"),null):(this.logger.trace("BrowserCacheManager.getAppMetadata: cache hit"),n)}setAppMetadata(e,t){this.logger.trace("BrowserCacheManager.setAppMetadata called");const n=Ac(e);this.setItem(n,JSON.stringify(e),t)}getServerTelemetry(e){const t=this.browserStorage.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getServerTelemetry: called, no cache hit"),null;const n=this.validateAndParseJson(t);return!n||!yc(e,n)?(this.logger.trace("BrowserCacheManager.getServerTelemetry: called, no cache hit"),null):(this.logger.trace("BrowserCacheManager.getServerTelemetry: cache hit"),n)}setServerTelemetry(e,t,n){this.logger.trace("BrowserCacheManager.setServerTelemetry called"),this.setItem(e,JSON.stringify(t),n)}getAuthorityMetadata(e){const t=this.internalStorage.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getAuthorityMetadata: called, no cache hit"),null;const n=this.validateAndParseJson(t);return n&&wc(e,n)?(this.logger.trace("BrowserCacheManager.getAuthorityMetadata: cache hit"),n):null}getAuthorityMetadataKeys(){return this.internalStorage.getKeys().filter(t=>this.isAuthorityMetadata(t))}setWrapperMetadata(e,t){this.internalStorage.setItem(mt.WRAPPER_SKU,e),this.internalStorage.setItem(mt.WRAPPER_VER,t)}getWrapperMetadata(){const e=this.internalStorage.getItem(mt.WRAPPER_SKU)||f.EMPTY_STRING,t=this.internalStorage.getItem(mt.WRAPPER_VER)||f.EMPTY_STRING;return[e,t]}setAuthorityMetadata(e,t){this.logger.trace("BrowserCacheManager.setAuthorityMetadata called"),this.internalStorage.setItem(e,JSON.stringify(t))}getActiveAccount(e){const t=this.generateCacheKey(Ho.ACTIVE_ACCOUNT_FILTERS),n=this.browserStorage.getItem(t);if(!n)return this.logger.trace("BrowserCacheManager.getActiveAccount: No active account filters found"),null;const o=this.validateAndParseJson(n);return o?(this.logger.trace("BrowserCacheManager.getActiveAccount: Active account filters schema found"),this.getAccountInfoFilteredBy({homeAccountId:o.homeAccountId,localAccountId:o.localAccountId,tenantId:o.tenantId},e)):(this.logger.trace("BrowserCacheManager.getActiveAccount: No active account found"),null)}setActiveAccount(e,t){const n=this.generateCacheKey(Ho.ACTIVE_ACCOUNT_FILTERS);if(e){this.logger.verbose("setActiveAccount: Active account set");const o={homeAccountId:e.homeAccountId,localAccountId:e.localAccountId,tenantId:e.tenantId,lastUpdatedAt:$().toString()};this.setItem(n,JSON.stringify(o),t)}else this.logger.verbose("setActiveAccount: No account passed, active account not set"),this.browserStorage.removeItem(n);this.eventHandler.emitEvent(A.ACTIVE_ACCOUNT_CHANGED)}getThrottlingCache(e){const t=this.browserStorage.getItem(e);if(!t)return this.logger.trace("BrowserCacheManager.getThrottlingCache: called, no cache hit"),null;const n=this.validateAndParseJson(t);return!n||!Tc(e,n)?(this.logger.trace("BrowserCacheManager.getThrottlingCache: called, no cache hit"),null):(this.logger.trace("BrowserCacheManager.getThrottlingCache: cache hit"),n)}setThrottlingCache(e,t,n){this.logger.trace("BrowserCacheManager.setThrottlingCache called"),this.setItem(e,JSON.stringify(t),n)}getTemporaryCache(e,t){const n=t?this.generateCacheKey(e):e;if(this.cacheConfig.storeAuthStateInCookie){const r=this.cookieStorage.getItem(n);if(r)return this.logger.trace("BrowserCacheManager.getTemporaryCache: storeAuthStateInCookies set to true, retrieving from cookies"),r}const o=this.temporaryCacheStorage.getItem(n);if(!o){if(this.cacheConfig.cacheLocation===x.LocalStorage){const r=this.browserStorage.getItem(n);if(r)return this.logger.trace("BrowserCacheManager.getTemporaryCache: Temporary cache item found in local storage"),r}return this.logger.trace("BrowserCacheManager.getTemporaryCache: No cache item found in local storage"),null}return this.logger.trace("BrowserCacheManager.getTemporaryCache: Temporary cache item returned"),o}setTemporaryCache(e,t,n){const o=n?this.generateCacheKey(e):e;this.temporaryCacheStorage.setItem(o,t),this.cacheConfig.storeAuthStateInCookie&&(this.logger.trace("BrowserCacheManager.setTemporaryCache: storeAuthStateInCookie set to true, setting item cookie"),this.cookieStorage.setItem(o,t,void 0,this.cacheConfig.secureCookies))}removeItem(e){this.browserStorage.removeItem(e)}removeTemporaryItem(e){this.temporaryCacheStorage.removeItem(e),this.cacheConfig.storeAuthStateInCookie&&(this.logger.trace("BrowserCacheManager.removeItem: storeAuthStateInCookie is true, clearing item cookie"),this.cookieStorage.removeItem(e))}getKeys(){return this.browserStorage.getKeys()}clear(e){this.removeAllAccounts(e),this.removeAppMetadata(e),this.temporaryCacheStorage.getKeys().forEach(t=>{(t.indexOf(K)!==-1||t.indexOf(this.clientId)!==-1)&&this.removeTemporaryItem(t)}),this.browserStorage.getKeys().forEach(t=>{(t.indexOf(K)!==-1||t.indexOf(this.clientId)!==-1)&&this.browserStorage.removeItem(t)}),this.internalStorage.clear()}clearTokensAndKeysWithClaims(e){this.performanceClient.addQueueMeasurement(h.ClearTokensAndKeysWithClaims,e);const t=this.getTokenKeys();let n=0;t.accessToken.forEach(o=>{const r=this.getAccessTokenCredential(o,e);r?.requestedClaimsHash&&o.includes(r.requestedClaimsHash.toLowerCase())&&(this.removeAccessToken(o,e),n++)}),n>0&&this.logger.warning(`${n} access tokens with claims in the cache keys have been removed from the cache.`)}generateCacheKey(e){return J.startsWith(e,K)?e:`${K}.${this.clientId}.${e}`}generateCredentialKey(e){const t=e.credentialType===H.REFRESH_TOKEN&&e.familyId||e.clientId,n=e.tokenType&&e.tokenType.toLowerCase()!==v.BEARER.toLowerCase()?e.tokenType.toLowerCase():"";return[`${K}.${F}`,e.homeAccountId,e.environment,e.credentialType,t,e.realm||"",e.target||"",e.requestedClaimsHash||"",n].join(fr).toLowerCase()}generateAccountKey(e){const t=e.homeAccountId.split(".")[1];return[`${K}.${At}`,e.homeAccountId,e.environment,t||e.tenantId||""].join(fr).toLowerCase()}resetRequestCache(){this.logger.trace("BrowserCacheManager.resetRequestCache called"),this.removeTemporaryItem(this.generateCacheKey(N.REQUEST_PARAMS)),this.removeTemporaryItem(this.generateCacheKey(N.VERIFIER)),this.removeTemporaryItem(this.generateCacheKey(N.ORIGIN_URI)),this.removeTemporaryItem(this.generateCacheKey(N.URL_HASH)),this.removeTemporaryItem(this.generateCacheKey(N.NATIVE_REQUEST)),this.setInteractionInProgress(!1)}cacheAuthorizeRequest(e,t){this.logger.trace("BrowserCacheManager.cacheAuthorizeRequest called");const n=at(JSON.stringify(e));if(this.setTemporaryCache(N.REQUEST_PARAMS,n,!0),t){const o=at(t);this.setTemporaryCache(N.VERIFIER,o,!0)}}getCachedRequest(){this.logger.trace("BrowserCacheManager.getCachedRequest called");const e=this.getTemporaryCache(N.REQUEST_PARAMS,!0);if(!e)throw y(Qi);const t=this.getTemporaryCache(N.VERIFIER,!0);let n,o="";try{n=JSON.parse(q(e)),t&&(o=q(t))}catch(r){throw this.logger.errorPii(`Attempted to parse: ${e}`),this.logger.error(`Parsing cached token request threw with error: ${r}`),y(Vi)}return[n,o]}getCachedNativeRequest(){this.logger.trace("BrowserCacheManager.getCachedNativeRequest called");const e=this.getTemporaryCache(N.NATIVE_REQUEST,!0);if(!e)return this.logger.trace("BrowserCacheManager.getCachedNativeRequest: No cached native request found"),null;const t=this.validateAndParseJson(e);return t||(this.logger.error("BrowserCacheManager.getCachedNativeRequest: Unable to parse native request"),null)}isInteractionInProgress(e){const t=this.getInteractionInProgress()?.clientId;return e?t===this.clientId:!!t}getInteractionInProgress(){const e=`${K}.${N.INTERACTION_STATUS_KEY}`,t=this.getTemporaryCache(e,!1);try{return t?JSON.parse(t):null}catch{return this.logger.error("Cannot parse interaction status. Removing temporary cache items and clearing url hash. Retrying interaction should fix the error"),this.removeTemporaryItem(e),this.resetRequestCache(),Cs(window),null}}setInteractionInProgress(e,t=me.SIGNIN){const n=`${K}.${N.INTERACTION_STATUS_KEY}`;if(e){if(this.getInteractionInProgress())throw y(xi);this.setTemporaryCache(n,JSON.stringify({clientId:this.clientId,type:t}),!1)}else!e&&this.getInteractionInProgress()?.clientId===this.clientId&&this.removeTemporaryItem(n)}async hydrateCache(e,t){const n=Vt(e.account.homeAccountId,e.account.environment,e.idToken,this.clientId,e.tenantId);let o;t.claims&&(o=await this.cryptoImpl.hashString(t.claims));const r=Wt(e.account.homeAccountId,e.account.environment,e.accessToken,this.clientId,e.tenantId,e.scopes.join(" "),e.expiresOn?jo(e.expiresOn):0,e.extExpiresOn?jo(e.extExpiresOn):0,q,void 0,e.tokenType,void 0,t.sshKid,t.claims,o),s={idToken:n,accessToken:r};return this.saveCacheRecord(s,e.correlationId,ae(se(e.idToken,q)),S.hydrateCache)}async saveCacheRecord(e,t,n,o,r){try{await super.saveCacheRecord(e,t,n,o,r)}catch(s){if(s instanceof Fe&&this.performanceClient&&t)try{const a=this.getTokenKeys();this.performanceClient.addFields({cacheRtCount:a.refreshToken.length,cacheIdCount:a.idToken.length,cacheAtCount:a.accessToken.length},t)}catch{}throw s}}}function Ar(i,e,t,n){try{switch(e){case x.LocalStorage:return new Nl(i,t,n);case x.SessionStorage:return new Ml;case x.MemoryStorage:default:break}}catch(o){t.error(o)}return new on}const Ul=(i,e,t,n)=>{const o={cacheLocation:x.MemoryStorage,cacheRetentionDays:5,temporaryCacheLocation:x.MemoryStorage,storeAuthStateInCookie:!1,secureCookies:!1,cacheMigrationEnabled:!1,claimsBasedCachingEnabled:!1};return new _n(i,o,vt,e,t,n)};function Dl(i,e,t,n,o){return i.verbose("getAllAccounts called"),t?e.getAllAccounts(o||{},n):[]}function Ll(i,e,t,n){const o=t.getAccountInfoFilteredBy(i,n);return o?(e.verbose("getAccount: Account matching provided filter found, returning"),o):(e.verbose("getAccount: No matching account found, returning null"),null)}function Hl(i,e,t,n){if(e.trace("getAccountByUsername called"),!i)return e.warning("getAccountByUsername: No username provided"),null;const o=t.getAccountInfoFilteredBy({username:i},n);return o?(e.verbose("getAccountByUsername: Account matching username found, returning"),e.verbosePii(`getAccountByUsername: Returning signed-in accounts matching username: ${i}`),o):(e.verbose("getAccountByUsername: No matching account found, returning null"),null)}function xl(i,e,t,n){if(e.trace("getAccountByHomeId called"),!i)return e.warning("getAccountByHomeId: No homeAccountId provided"),null;const o=t.getAccountInfoFilteredBy({homeAccountId:i},n);return o?(e.verbose("getAccountByHomeId: Account matching homeAccountId found, returning"),e.verbosePii(`getAccountByHomeId: Returning signed-in accounts matching homeAccountId: ${i}`),o):(e.verbose("getAccountByHomeId: No matching account found, returning null"),null)}function Fl(i,e,t,n){if(e.trace("getAccountByLocalId called"),!i)return e.warning("getAccountByLocalId: No localAccountId provided"),null;const o=t.getAccountInfoFilteredBy({localAccountId:i},n);return o?(e.verbose("getAccountByLocalId: Account matching localAccountId found, returning"),e.verbosePii(`getAccountByLocalId: Returning signed-in accounts matching localAccountId: ${i}`),o):(e.verbose("getAccountByLocalId: No matching account found, returning null"),null)}function Kl(i,e,t){e.setActiveAccount(i,t)}function Bl(i,e){return i.getActiveAccount(e)}const Gl="msal.broadcast.event";class zl{constructor(e){this.eventCallbacks=new Map,this.logger=e||new we({}),typeof BroadcastChannel<"u"&&(this.broadcastChannel=new BroadcastChannel(Gl)),this.invokeCrossTabCallbacks=this.invokeCrossTabCallbacks.bind(this)}addEventCallback(e,t,n){if(typeof window<"u"){const o=n||Tl();return this.eventCallbacks.has(o)?(this.logger.error(`Event callback with id: ${o} is already registered. Please provide a unique id or remove the existing callback and try again.`),null):(this.eventCallbacks.set(o,[e,t||[]]),this.logger.verbose(`Event callback registered with id: ${o}`),o)}return null}removeEventCallback(e){this.eventCallbacks.delete(e),this.logger.verbose(`Event callback ${e} removed.`)}emitEvent(e,t,n,o){const r={eventType:e,interactionType:t||null,payload:n||null,error:o||null,timestamp:Date.now()};switch(e){case A.ACCOUNT_ADDED:case A.ACCOUNT_REMOVED:case A.ACTIVE_ACCOUNT_CHANGED:this.broadcastChannel?.postMessage(r);break;default:this.invokeCallbacks(r);break}}invokeCallbacks(e){this.eventCallbacks.forEach(([t,n],o)=>{(n.length===0||n.includes(e.eventType))&&(this.logger.verbose(`Emitting event to callback ${o}: ${e.eventType}`),t.apply(null,[e]))})}invokeCrossTabCallbacks(e){const t=e.data;this.invokeCallbacks(t)}subscribeCrossTab(){this.broadcastChannel?.addEventListener("message",this.invokeCrossTabCallbacks)}unsubscribeCrossTab(){this.broadcastChannel?.removeEventListener("message",this.invokeCrossTabCallbacks)}}class Ss{constructor(e,t,n,o,r,s,a,c,l){this.config=e,this.browserStorage=t,this.browserCrypto=n,this.networkClient=this.config.system.networkClient,this.eventHandler=r,this.navigationClient=s,this.platformAuthProvider=c,this.correlationId=l||ce(),this.logger=o.clone(Q.MSAL_SKU,Oe,this.correlationId),this.performanceClient=a}async clearCacheOnLogout(e,t){if(t)try{this.browserStorage.removeAccount(t,e),this.logger.verbose("Cleared cache items belonging to the account provided in the logout request.")}catch{this.logger.error("Account provided in logout request was not found. Local cache unchanged.")}else try{this.logger.verbose("No account provided in logout request, clearing all cache items.",this.correlationId),this.browserStorage.clear(e),await this.browserCrypto.clearKeystore()}catch{this.logger.error("Attempted to clear all MSAL cache items and failed. Local cache unchanged.")}}getRedirectUri(e){this.logger.verbose("getRedirectUri called");const t=e||this.config.auth.redirectUri;return k.getAbsoluteUrl(t,de())}initializeServerTelemetryManager(e,t){this.logger.verbose("initializeServerTelemetryManager called");const n={clientId:this.config.auth.clientId,correlationId:this.correlationId,apiId:e,forceRefresh:t||!1,wrapperSKU:this.browserStorage.getWrapperMetadata()[0],wrapperVer:this.browserStorage.getWrapperMetadata()[1]};return new it(n,this.browserStorage)}async getDiscoveredAuthority(e){const{account:t}=e,n=e.requestExtraQueryParameters&&e.requestExtraQueryParameters.hasOwnProperty("instance_aware")?e.requestExtraQueryParameters.instance_aware:void 0;this.performanceClient.addQueueMeasurement(h.StandardInteractionClientGetDiscoveredAuthority,this.correlationId);const o={protocolMode:this.config.auth.protocolMode,OIDCOptions:this.config.auth.OIDCOptions,knownAuthorities:this.config.auth.knownAuthorities,cloudDiscoveryMetadata:this.config.auth.cloudDiscoveryMetadata,authorityMetadata:this.config.auth.authorityMetadata,skipAuthorityMetadataCache:this.config.auth.skipAuthorityMetadataCache},r=e.requestAuthority||this.config.auth.authority,s=n?.length?n==="true":this.config.auth.instanceAware,a=t&&s?this.config.auth.authority.replace(k.getDomainFromUrl(r),t.environment):r,c=z.generateAuthority(a,e.requestAzureCloudOptions||this.config.auth.azureCloudOptions),l=await g(oo,h.AuthorityFactoryCreateDiscoveredInstance,this.logger,this.performanceClient,this.correlationId)(c,this.config.system.networkClient,this.browserStorage,o,this.logger,this.correlationId,this.performanceClient);if(t&&!l.isAlias(t.environment))throw _(Zr);return l}}async function Po(i,e,t,n){t.addQueueMeasurement(h.InitializeBaseRequest,i.correlationId);const o=i.authority||e.auth.authority,r=[...i&&i.scopes||[]],s={...i,correlationId:i.correlationId,authority:o,scopes:r};if(!s.authenticationScheme)s.authenticationScheme=v.BEARER,n.verbose(`Authentication Scheme wasn't explicitly set in request, defaulting to "Bearer" request`);else{if(s.authenticationScheme===v.SSH){if(!i.sshJwk)throw _(zt);if(!i.sshKid)throw _(Yr)}n.verbose(`Authentication Scheme set to "${s.authenticationScheme}" as configured in Auth request`)}return e.cache.claimsBasedCachingEnabled&&i.claims&&!J.isEmptyObj(i.claims)&&(s.requestedClaimsHash=await ms(i.claims)),s}async function ql(i,e,t,n,o){n.addQueueMeasurement(h.InitializeSilentRequest,i.correlationId);const r=await g(Po,h.InitializeBaseRequest,o,n,i.correlationId)(i,t,n,o);return{...i,...r,account:e,forceRefresh:i.forceRefresh||!1}}function ks(i,e){let t;const n=i.httpMethod;if(e===V.EAR){if(t=n||_e.POST,t!==_e.POST)throw _(ei)}else t=n||_e.GET;if(i.authorizePostBodyParameters&&t!==_e.POST)throw _(ti);return t}class Ye extends Ss{initializeLogoutRequest(e){this.logger.verbose("initializeLogoutRequest called",e?.correlationId);const t={correlationId:this.correlationId||ce(),...e};if(e)if(e.logoutHint)this.logger.verbose("logoutHint has already been set in logoutRequest");else if(e.account){const n=this.getLogoutHintFromIdTokenClaims(e.account);n&&(this.logger.verbose("Setting logoutHint to login_hint ID Token Claim value for the account provided"),t.logoutHint=n)}else this.logger.verbose("logoutHint was not set and account was not passed into logout request, logoutHint will not be set");else this.logger.verbose("logoutHint will not be set since no logout request was configured");return!e||e.postLogoutRedirectUri!==null?e&&e.postLogoutRedirectUri?(this.logger.verbose("Setting postLogoutRedirectUri to uri set on logout request",t.correlationId),t.postLogoutRedirectUri=k.getAbsoluteUrl(e.postLogoutRedirectUri,de())):this.config.auth.postLogoutRedirectUri===null?this.logger.verbose("postLogoutRedirectUri configured as null and no uri set on request, not passing post logout redirect",t.correlationId):this.config.auth.postLogoutRedirectUri?(this.logger.verbose("Setting postLogoutRedirectUri to configured uri",t.correlationId),t.postLogoutRedirectUri=k.getAbsoluteUrl(this.config.auth.postLogoutRedirectUri,de())):(this.logger.verbose("Setting postLogoutRedirectUri to current page",t.correlationId),t.postLogoutRedirectUri=k.getAbsoluteUrl(de(),de())):this.logger.verbose("postLogoutRedirectUri passed as null, not setting post logout redirect uri",t.correlationId),t}getLogoutHintFromIdTokenClaims(e){const t=e.idTokenClaims;if(t){if(t.login_hint)return t.login_hint;this.logger.verbose("The ID Token Claims tied to the provided account do not contain a login_hint claim, logoutHint will not be added to logout request")}else this.logger.verbose("The provided account does not contain ID Token Claims, logoutHint will not be added to logout request");return null}async createAuthCodeClient(e){this.performanceClient.addQueueMeasurement(h.StandardInteractionClientCreateAuthCodeClient,this.correlationId);const t=await g(this.getClientConfiguration.bind(this),h.StandardInteractionClientGetClientConfiguration,this.logger,this.performanceClient,this.correlationId)(e);return new bi(t,this.performanceClient)}async getClientConfiguration(e){const{serverTelemetryManager:t,requestAuthority:n,requestAzureCloudOptions:o,requestExtraQueryParameters:r,account:s}=e;this.performanceClient.addQueueMeasurement(h.StandardInteractionClientGetClientConfiguration,this.correlationId);const a=e.authority||await g(this.getDiscoveredAuthority.bind(this),h.StandardInteractionClientGetDiscoveredAuthority,this.logger,this.performanceClient,this.correlationId)({requestAuthority:n,requestAzureCloudOptions:o,requestExtraQueryParameters:r,account:s}),c=this.config.system.loggerOptions;return{authOptions:{clientId:this.config.auth.clientId,authority:a,clientCapabilities:this.config.auth.clientCapabilities,redirectUri:this.config.auth.redirectUri},systemOptions:{tokenRenewalOffsetSeconds:this.config.system.tokenRenewalOffsetSeconds,preventCorsPreflight:!0},loggerOptions:{loggerCallback:c.loggerCallback,piiLoggingEnabled:c.piiLoggingEnabled,logLevel:c.logLevel,correlationId:this.correlationId},cacheOptions:{claimsBasedCachingEnabled:this.config.cache.claimsBasedCachingEnabled},cryptoInterface:this.browserCrypto,networkInterface:this.networkClient,storageInterface:this.browserStorage,serverTelemetryManager:t,libraryInfo:{sku:Q.MSAL_SKU,version:Oe,cpu:f.EMPTY_STRING,os:f.EMPTY_STRING},telemetry:this.config.telemetry}}async initializeAuthorizationRequest(e,t){this.performanceClient.addQueueMeasurement(h.StandardInteractionClientInitializeAuthorizationRequest,this.correlationId);const n=this.getRedirectUri(e.redirectUri);new URL(n).origin!==new URL(window.location.href).origin&&(this.logger.warning("The origin of the redirect URI does not match the origin of the current page. This is likely to cause issues with authentication.",this.correlationId),this.performanceClient.addFields({isRedirectUriCrossOrigin:!0},this.correlationId));const o={interactionType:t},r=We.setRequestState(this.browserCrypto,e&&e.state||f.EMPTY_STRING,o),a={...await g(Po,h.InitializeBaseRequest,this.logger,this.performanceClient,this.correlationId)({...e,correlationId:this.correlationId},this.config,this.performanceClient,this.logger),redirectUri:n,state:r,nonce:e.nonce||ce(),responseMode:this.config.auth.OIDCOptions.serverResponseType},c={...a,httpMethod:ks(a,this.config.auth.protocolMode)};if(e.loginHint||e.sid)return c;const l=e.account||this.browserStorage.getActiveAccount(this.correlationId);return l&&(this.logger.verbose("Setting validated request account",this.correlationId),this.logger.verbosePii(`Setting validated request account: ${l.homeAccountId}`,this.correlationId),c.account=l),c}}function $l(i,e){if(!e)return null;try{return We.parseRequestState(i,e).libraryState.meta}catch{throw p($e)}}function ze(i,e,t){const n=Rt(i);if(!n)throw ri(i)?(t.error(`A ${e} is present in the iframe but it does not contain known properties. It's likely that the ${e} has been replaced by code running on the redirectUri page.`),t.errorPii(`The ${e} detected is: ${i}`),y(Di)):(t.error(`The request has returned to the redirectUri but a ${e} is not present. It's likely that the ${e} has been removed or the page has been redirected by code running on the redirectUri page.`),y(Ui));return n}function Ql(i,e,t){if(!i.state)throw y(mo);const n=$l(e,i.state);if(!n)throw y(Li);if(n.interactionType!==t)throw y(Hi)}class vs{constructor(e,t,n,o,r){this.authModule=e,this.browserStorage=t,this.authCodeRequest=n,this.logger=o,this.performanceClient=r}async handleCodeResponse(e,t,n){this.performanceClient.addQueueMeasurement(h.HandleCodeResponse,t.correlationId);let o;try{o=Hc(e,t.state)}catch(r){throw r instanceof Me&&r.subError===st?y(st):r}return g(this.handleCodeResponseFromServer.bind(this),h.HandleCodeResponseFromServer,this.logger,this.performanceClient,t.correlationId)(o,t,n)}async handleCodeResponseFromServer(e,t,n,o=!0){if(this.performanceClient.addQueueMeasurement(h.HandleCodeResponseFromServer,t.correlationId),this.logger.trace("InteractionHandler.handleCodeResponseFromServer called"),this.authCodeRequest.code=e.code,e.cloud_instance_host_name&&await g(this.authModule.updateAuthority.bind(this.authModule),h.UpdateTokenEndpointAuthority,this.logger,this.performanceClient,t.correlationId)(e.cloud_instance_host_name,t.correlationId),o&&(e.nonce=t.nonce||void 0),e.state=t.state,e.client_info)this.authCodeRequest.clientInfo=e.client_info;else{const s=this.createCcsCredentials(t);s&&(this.authCodeRequest.ccsCredential=s)}return await g(this.authModule.acquireToken.bind(this.authModule),h.AuthClientAcquireToken,this.logger,this.performanceClient,t.correlationId)(this.authCodeRequest,n,e)}createCcsCredentials(e){return e.account?{credential:e.account.homeAccountId,type:ne.HOME_ACCOUNT_ID}:e.loginHint?{credential:e.loginHint,type:ne.UPN}:null}}const Vl="ContentError",Wl="PageException",_s="user_switch";const jl="USER_INTERACTION_REQUIRED",Yl="USER_CANCEL",Jl="NO_NETWORK",Xl="DISABLED",Zl="ACCOUNT_UNAVAILABLE",eh="UX_NOT_ALLOWED";const th=-2147186943,nh={[_s]:"User attempted to switch accounts in the native broker, which is not allowed. All new accounts must sign-in through the standard web flow first, please try again."};class ie extends R{constructor(e,t,n){super(e,t),Object.setPrototypeOf(this,ie.prototype),this.name="NativeAuthError",this.ext=n}}function Le(i){if(i.ext&&i.ext.status&&i.ext.status===Xl||i.ext&&i.ext.error&&i.ext.error===th)return!0;switch(i.errorCode){case Vl:case Wl:return!0;default:return!1}}function Ft(i,e,t){if(t&&t.status)switch(t.status){case Zl:return Dt(ki);case jl:return new oe(i,e);case Yl:return y(st);case Jl:return y(Lt);case eh:return Dt(so)}return new ie(i,nh[i]||e,t)}class Rs extends Ye{async acquireToken(e){this.performanceClient.addQueueMeasurement(h.SilentCacheClientAcquireToken,e.correlationId);const t=this.initializeServerTelemetryManager(S.acquireTokenSilent_silentFlow),n=await g(this.getClientConfiguration.bind(this),h.StandardInteractionClientGetClientConfiguration,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:t,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,account:e.account}),o=new Uc(n,this.performanceClient);this.logger.verbose("Silent auth client created");try{const s=(await g(o.acquireCachedToken.bind(o),h.SilentFlowClientAcquireCachedToken,this.logger,this.performanceClient,e.correlationId)(e))[0];return this.performanceClient.addFields({fromCache:!0},e.correlationId),s}catch(r){throw r instanceof ht&&r.errorCode===po&&this.logger.verbose("Signing keypair for bound access token not found. Refreshing bound access token and generating a new crypto keypair."),r}}logout(e){this.logger.verbose("logoutRedirect called");const t=this.initializeLogoutRequest(e);return this.clearCacheOnLogout(t.correlationId,t?.account)}}class wt extends Ss{constructor(e,t,n,o,r,s,a,c,l,d,u,m){super(e,t,n,o,r,s,c,l,m),this.apiId=a,this.accountId=d,this.platformAuthProvider=l,this.nativeStorageManager=u,this.silentCacheClient=new Rs(e,this.nativeStorageManager,n,o,r,s,c,l,m);const C=this.platformAuthProvider.getExtensionName();this.skus=it.makeExtraSkuString({libraryName:Q.MSAL_SKU,libraryVersion:Oe,extensionName:C,extensionVersion:this.platformAuthProvider.getExtensionVersion()})}addRequestSKUs(e){e.extraParameters={...e.extraParameters,[ja]:this.skus}}async acquireToken(e,t){this.performanceClient.addQueueMeasurement(h.NativeInteractionClientAcquireToken,this.correlationId),this.logger.trace("NativeInteractionClient - acquireToken called.");const n=this.performanceClient.startMeasurement(h.NativeInteractionClientAcquireToken,this.correlationId),o=$(),r=this.initializeServerTelemetryManager(this.apiId);try{const s=await this.initializeNativeRequest(e);try{const c=await this.acquireTokensFromCache(this.accountId,s);return n.end({success:!0,isNativeBroker:!1,fromCache:!0}),c}catch(c){if(t===B.AccessToken)throw this.logger.info("MSAL internal Cache does not contain tokens, return error as per cache policy"),n.end({success:!1,brokerErrorCode:"cache_request_failed"}),c;this.logger.info("MSAL internal Cache does not contain tokens, proceed to make a native call")}const a=await this.platformAuthProvider.sendMessage(s);return await this.handleNativeResponse(a,s,o).then(c=>(n.end({success:!0,isNativeBroker:!0,requestId:c.requestId}),r.clearNativeBrokerErrorCode(),c)).catch(c=>{throw n.end({success:!1,errorCode:c.errorCode,subErrorCode:c.subError}),c})}catch(s){throw s instanceof ie&&r.setNativeBrokerErrorCode(s.errorCode),n.end({success:!1}),s}}createSilentCacheRequest(e,t){return{authority:e.authority,correlationId:this.correlationId,scopes:M.fromString(e.scope).asArray(),account:t,forceRefresh:!1}}async acquireTokensFromCache(e,t){if(!e)throw this.logger.warning("NativeInteractionClient:acquireTokensFromCache - No nativeAccountId provided"),p(Cn);const n=this.browserStorage.getBaseAccountInfo({nativeAccountId:e},this.correlationId);if(!n)throw p(Cn);try{const o=this.createSilentCacheRequest(t,n),r=await this.silentCacheClient.acquireToken(o),s={...n,idTokenClaims:r?.idTokenClaims,idToken:r?.idToken};return{...r,account:s}}catch(o){throw o}}async acquireTokenRedirect(e,t){this.logger.trace("NativeInteractionClient - acquireTokenRedirect called.");const{...n}=e;delete n.onRedirectNavigate;const o=await this.initializeNativeRequest(n);try{await this.platformAuthProvider.sendMessage(o)}catch(a){if(a instanceof ie&&(this.initializeServerTelemetryManager(this.apiId).setNativeBrokerErrorCode(a.errorCode),Le(a)))throw a}this.browserStorage.setTemporaryCache(N.NATIVE_REQUEST,JSON.stringify(o),!0);const r={apiId:S.acquireTokenRedirect,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},s=this.config.auth.navigateToLoginRequestUrl?window.location.href:this.getRedirectUri(e.redirectUri);t.end({success:!0}),await this.navigationClient.navigateExternal(s,r)}async handleRedirectPromise(e,t){if(this.logger.trace("NativeInteractionClient - handleRedirectPromise called."),!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null."),null;const n=this.browserStorage.getCachedNativeRequest();if(!n)return this.logger.verbose("NativeInteractionClient - handleRedirectPromise called but there is no cached request, returning null."),e&&t&&e?.addFields({errorCode:"no_cached_request"},t),null;const{prompt:o,...r}=n;o&&this.logger.verbose("NativeInteractionClient - handleRedirectPromise called and prompt was included in the original request, removing prompt from cached request to prevent second interaction with native broker window."),this.browserStorage.removeItem(this.browserStorage.generateCacheKey(N.NATIVE_REQUEST));const s=$();try{this.logger.verbose("NativeInteractionClient - handleRedirectPromise sending message to native broker.");const a=await this.platformAuthProvider.sendMessage(r),c=await this.handleNativeResponse(a,r,s);return this.initializeServerTelemetryManager(this.apiId).clearNativeBrokerErrorCode(),e&&this.correlationId&&this.performanceClient.addFields({isNativeBroker:!0},this.correlationId),c}catch(a){throw a}}logout(){return this.logger.trace("NativeInteractionClient - logout called."),Promise.reject("Logout not implemented yet")}async handleNativeResponse(e,t,n){this.logger.trace("NativeInteractionClient - handleNativeResponse called.");const o=se(e.id_token,q),r=this.createHomeAccountIdentifier(e,o),s=this.browserStorage.getAccountInfoFilteredBy({nativeAccountId:t.accountId},this.correlationId)?.homeAccountId;if(t.extraParameters?.child_client_id&&e.account.id!==t.accountId)this.logger.info("handleNativeServerResponse: Double broker flow detected, ignoring accountId mismatch");else if(r!==s&&e.account.id!==t.accountId)throw Ft(_s);const a=await this.getDiscoveredAuthority({requestAuthority:t.authority}),c=ao(this.browserStorage,a,r,q,this.correlationId,o,e.client_info,void 0,o.tid,void 0,e.account.id,this.logger);e.expires_in=Number(e.expires_in);const l=await this.generateAuthenticationResult(e,t,o,c,a.canonicalAuthority,n);return await this.cacheAccount(c,this.correlationId,ae(o)),await this.cacheNativeTokens(e,t,r,o,e.access_token,l.tenantId,n),l}createHomeAccountIdentifier(e,t){return O.generateHomeAccountId(e.client_info||f.EMPTY_STRING,te.Default,this.logger,this.browserCrypto,t)}generateScopes(e,t){return t?M.fromString(t):M.fromString(e)}async generatePopAccessToken(e,t){if(t.tokenType===v.POP&&t.signPopToken){if(e.shr)return this.logger.trace("handleNativeServerResponse: SHR is enabled in native layer"),e.shr;const n=new Qe(this.browserCrypto),o={resourceRequestMethod:t.resourceRequestMethod,resourceRequestUri:t.resourceRequestUri,shrClaims:t.shrClaims,shrNonce:t.shrNonce};if(!t.keyId)throw p(Dn);return n.signPopToken(e.access_token,t.keyId,o)}else return e.access_token}async generateAuthenticationResult(e,t,n,o,r,s){const a=this.addTelemetryFromNativeResponse(e.properties.MATS),c=this.generateScopes(t.scope,e.scope),l=e.account.properties||{},d=l.UID||n.oid||n.sub||f.EMPTY_STRING,u=l.TenantId||n.tid||f.EMPTY_STRING,m=zn(O.getAccountInfo(o),void 0,n,e.id_token);m.nativeAccountId!==e.account.id&&(m.nativeAccountId=e.account.id);const C=await this.generatePopAccessToken(e,t),E=t.tokenType===v.POP?v.POP:v.BEARER;return{authority:r,uniqueId:d,tenantId:u,scopes:c.asArray(),account:m,idToken:e.id_token,idTokenClaims:n,accessToken:C,fromCache:a?this.isResponseFromCache(a):!1,expiresOn:Ke(s+e.expires_in),tokenType:E,correlationId:this.correlationId,state:e.state,fromNativeBroker:!0}}async cacheAccount(e,t,n){await this.browserStorage.setAccount(e,this.correlationId,n,this.apiId),this.browserStorage.removeAccountContext(O.getAccountInfo(e),t)}cacheNativeTokens(e,t,n,o,r,s,a){const c=Vt(n,t.authority,e.id_token||"",t.clientId,o.tid||""),l=t.tokenType===v.POP?f.SHR_NONCE_VALIDITY:(typeof e.expires_in=="string"?parseInt(e.expires_in,10):e.expires_in)||0,d=a+l,u=this.generateScopes(e.scope,t.scope),m=Wt(n,t.authority,r,t.clientId,o.tid||s,u.printScopes(),d,0,q,void 0,t.tokenType,void 0,t.keyId),C={idToken:c,accessToken:m};return this.nativeStorageManager.saveCacheRecord(C,this.correlationId,ae(o),this.apiId,t.storeInCache)}getExpiresInValue(e,t){return e===v.POP?f.SHR_NONCE_VALIDITY:(typeof t=="string"?parseInt(t,10):t)||0}addTelemetryFromNativeResponse(e){const t=this.getMATSFromResponse(e);return t?(this.performanceClient.addFields({extensionId:this.platformAuthProvider.getExtensionId(),extensionVersion:this.platformAuthProvider.getExtensionVersion(),matsBrokerVersion:t.broker_version,matsAccountJoinOnStart:t.account_join_on_start,matsAccountJoinOnEnd:t.account_join_on_end,matsDeviceJoin:t.device_join,matsPromptBehavior:t.prompt_behavior,matsApiErrorCode:t.api_error_code,matsUiVisible:t.ui_visible,matsSilentCode:t.silent_code,matsSilentBiSubCode:t.silent_bi_sub_code,matsSilentMessage:t.silent_message,matsSilentStatus:t.silent_status,matsHttpStatus:t.http_status,matsHttpEventCount:t.http_event_count},this.correlationId),t):null}getMATSFromResponse(e){if(e)try{return JSON.parse(e)}catch{this.logger.error("NativeInteractionClient - Error parsing MATS telemetry, returning null instead")}return null}isResponseFromCache(e){return typeof e.is_cached>"u"?(this.logger.verbose("NativeInteractionClient - MATS telemetry does not contain field indicating if response was served from cache. Returning false."),!1):!!e.is_cached}async initializeNativeRequest(e){this.logger.trace("NativeInteractionClient - initializeNativeRequest called");const t=await this.getCanonicalAuthority(e),{scopes:n,claims:o,...r}=e,s=new M(n||[]);s.appendScopes(Ve);const a=e.skipBrokerClaims&&e.embeddedClientId?void 0:this.config.auth.clientCapabilities,c=a&&a.length?Ti(o,a):o,l={...r,claims:c,accountId:this.accountId,clientId:this.config.auth.clientId,authority:t.urlString,scope:s.printScopes(),redirectUri:this.getRedirectUri(e.redirectUri),prompt:this.getPrompt(e.prompt),correlationId:this.correlationId,tokenType:e.authenticationScheme,windowTitleSubstring:document.title,extraParameters:{...e.extraQueryParameters,...e.tokenQueryParameters},extendedExpiryToken:!1,keyId:e.popKid};if(l.signPopToken&&e.popKid)throw y(is);if(this.handleExtraBrokerParams(l),l.extraParameters=l.extraParameters||{},l.extraParameters.telemetry=X.MATS_TELEMETRY,e.authenticationScheme===v.POP){const d={resourceRequestUri:e.resourceRequestUri,resourceRequestMethod:e.resourceRequestMethod,shrClaims:e.shrClaims,shrNonce:e.shrNonce},u=new Qe(this.browserCrypto);let m;if(l.keyId)m=this.browserCrypto.base64UrlEncode(JSON.stringify({kid:l.keyId})),l.signPopToken=!1;else{const C=await g(u.generateCnf.bind(u),h.PopTokenGenerateCnf,this.logger,this.performanceClient,this.correlationId)(d,this.logger);m=C.reqCnfString,l.keyId=C.kid,l.signPopToken=!0}l.reqCnf=m}return this.addRequestSKUs(l),l}async getCanonicalAuthority(e){const t=e.authority||this.config.auth.authority;e.account&&await this.getDiscoveredAuthority({requestAuthority:t,requestAzureCloudOptions:e.azureCloudOptions,account:e.account});const n=new k(t);return n.validateAsUri(),n}getPrompt(e){switch(this.apiId){case S.ssoSilent:case S.acquireTokenSilent_silentFlow:return this.logger.trace("initializeNativeRequest: silent request sets prompt to none"),U.NONE}if(!e){this.logger.trace("initializeNativeRequest: prompt was not provided");return}switch(e){case U.NONE:case U.CONSENT:case U.LOGIN:case U.SELECT_ACCOUNT:return this.logger.trace("initializeNativeRequest: prompt is compatible with native flow"),e;default:throw this.logger.trace(`initializeNativeRequest: prompt = ${e} is not compatible with native flow`),y(os)}}handleExtraBrokerParams(e){const t=e.extraParameters&&e.extraParameters.hasOwnProperty(be)&&e.extraParameters.hasOwnProperty(Ot)&&e.extraParameters.hasOwnProperty(Re);if(!e.embeddedClientId&&!t)return;let n="";const o=e.redirectUri;e.embeddedClientId?(e.redirectUri=this.config.auth.redirectUri,n=e.embeddedClientId):e.extraParameters&&(e.redirectUri=e.extraParameters[Ot],n=e.extraParameters[Re]),e.extraParameters={child_client_id:n,child_redirect_uri:o},this.performanceClient?.addFields({embeddedClientId:n,embeddedRedirectUri:o},this.correlationId)}}const oh=new Map([["e","AAD"],["m","MSA"]]);function rh(i){if(!i)return null;try{const t=decodeURIComponent(i).split("|");return t.length<5?null:{accountType:oh.get(t[0]?.trim()||"")||"",error:t[1]?.trim()||"",subError:t[2]?.trim()||"",cloudInstance:t[3]?.trim()||"",callerDataBoundary:t[4]?.trim()||""}}catch{return null}}function bs(i,e,t){const n=rh(i.clientdata);n?.accountType&&t.addFields({accountType:n.accountType},e),n?.error&&t.addFields({serverErrorNo:n.error},e),n?.subError&&t.addFields({serverSubErrorNo:n.subError},e)}async function Oo(i,e,t,n,o){const r=Lc({...i.auth,authority:e},t,n,o);if(Xn(r,{sku:Q.MSAL_SKU,version:Oe,os:"",cpu:""}),i.auth.protocolMode!==V.OIDC&&Zn(r,i.telemetry.application),t.platformBroker&&(ec(r),o.addFields({isPlatformAuthorizeRequest:!0},t.correlationId),t.authenticationScheme===v.POP)){const s=new ue(n,o),a=new Qe(s);let c;t.popKid?c=s.encodeKid(t.popKid):c=(await g(a.generateCnf.bind(a),h.PopTokenGenerateCnf,n,o,t.correlationId)(t,n)).reqCnfString,no(r,c)}return qt(r,t.correlationId,o),r}async function Kt(i,e,t,n,o){if(!t.codeChallenge)throw _(Kn);const r=await g(Oo,h.GetStandardParams,n,o,t.correlationId)(i,e,t,n,o);return Vn(r,Rn.CODE),eo(r,t.codeChallenge,f.S256_CODE_CHALLENGE_METHOD),Te(r,t.extraQueryParameters||{}),co(e,r,i.auth.encodeExtraQueryParams,t.extraQueryParameters)}async function No(i,e,t,n,o,r){if(!n.earJwk)throw y(fo);const s=await Oo(e,t,n,o,r);Vn(s,Rn.IDTOKEN_TOKEN_REFRESHTOKEN),dc(s,n.earJwk),eo(s,n.codeChallenge,f.S256_CODE_CHALLENGE_METHOD);const a=new Map;Te(a,n.extraQueryParameters||{}),lt(a,n.correlationId);const c=co(t,a,e.auth.encodeExtraQueryParams,n.extraQueryParameters);return Ps(i,c,s)}async function Mo(i,e,t,n,o,r){const s=await Oo(e,t,n,o,r);Vn(s,Rn.CODE),eo(s,n.codeChallenge,n.codeChallengeMethod||f.S256_CODE_CHALLENGE_METHOD),uc(s,n.authorizePostBodyParameters||{});const a=new Map;Te(a,n.extraQueryParameters||{}),lt(a,n.correlationId);const c=co(t,a,e.auth.encodeExtraQueryParams,n.extraQueryParameters);return Ps(i,c,s)}function Ps(i,e,t){const n=i.createElement("form");return n.method="post",n.action=e,t.forEach((o,r)=>{const s=i.createElement("input");s.hidden=!0,s.name=r,s.value=o,n.appendChild(s)}),i.body.appendChild(n),n}async function Os(i,e,t,n,o,r,s,a,c,l){if(a.verbose("Account id found, calling WAM for token"),!l)throw y(yo);const d=new ue(a,c),u=new wt(n,o,d,a,s,n.system.navigationClient,t,c,l,e,r,i.correlationId),{userRequestState:m}=We.parseRequestState(d,i.state);return g(u.acquireToken.bind(u),h.NativeInteractionClientAcquireToken,a,c,i.correlationId)({...i,state:m,prompt:void 0})}async function qe(i,e,t,n,o,r,s,a,c,l,d,u){if(re.removeThrottle(s,o.auth.clientId,i),bs(e,i.correlationId,d),e.accountId)return g(Os,h.HandleResponsePlatformBroker,l,d,i.correlationId)(i,e.accountId,n,o,s,a,c,l,d,u);const m={...i,code:e.code||"",codeVerifier:t},C=new vs(r,s,m,l,d);return await g(C.handleCodeResponse.bind(C),h.HandleCodeResponse,l,d,i.correlationId)(e,i,n)}async function Uo(i,e,t,n,o,r,s,a,c,l,d){if(re.removeThrottle(r,n.auth.clientId,i),bs(e,i.correlationId,l),lo(e,i.state),!e.ear_jwe)throw y(Mi);if(!i.earJwk)throw y(fo);const u=JSON.parse(await g(dl,h.DecryptEarResponse,c,l,i.correlationId)(i.earJwk,e.ear_jwe));if(u.accountId)return g(Os,h.HandleResponsePlatformBroker,c,l,i.correlationId)(i,u.accountId,t,n,r,s,a,c,l,d);const m=new Pe(n.auth.clientId,r,new ue(c,l),c,null,null,l);m.validateTokenResponse(u);const C={code:"",state:i.state,nonce:i.nonce,client_info:u.client_info,cloud_graph_host_name:u.cloud_graph_host_name,cloud_instance_host_name:u.cloud_instance_host_name,cloud_instance_name:u.cloud_instance_name,msgraph_host:u.msgraph_host};return await g(m.handleServerTokenResponse.bind(m),h.HandleServerTokenResponse,c,l,i.correlationId)(u,o,$(),i,t,C,void 0,void 0,void 0,void 0)}const ih=32;async function Ie(i,e,t){i.addQueueMeasurement(h.GeneratePkceCodes,t);const n=W(sh,h.GenerateCodeVerifier,e,i,t)(i,e,t),o=await g(ah,h.GenerateCodeChallengeFromVerifier,e,i,t)(n,i,e,t);return{verifier:n,challenge:o}}function sh(i,e,t){try{const n=new Uint8Array(ih);return W(sl,h.GetRandomValues,e,i,t)(n),Ee(n)}catch{throw y(go)}}async function ah(i,e,t,n){e.addQueueMeasurement(h.GenerateCodeChallengeFromVerifier,n);try{const o=await g(us,h.Sha256Digest,t,e,n)(i,e,n);return Ee(new Uint8Array(o))}catch{throw y(go)}}class Bt{constructor(e,t,n,o){this.logger=e,this.handshakeTimeoutMs=t,this.extensionId=o,this.resolvers=new Map,this.handshakeResolvers=new Map,this.messageChannel=new MessageChannel,this.windowListener=this.onWindowMessage.bind(this),this.performanceClient=n,this.handshakeEvent=n.startMeasurement(h.NativeMessageHandlerHandshake),this.platformAuthType=X.PLATFORM_EXTENSION_PROVIDER}async sendMessage(e){this.logger.trace(this.platformAuthType+" - sendMessage called.");const t={method:Je.GetToken,request:e},n={channel:X.CHANNEL_ID,extensionId:this.extensionId,responseId:ce(),body:t};this.logger.trace(this.platformAuthType+" - Sending request to browser extension"),this.logger.tracePii(this.platformAuthType+` - Sending request to browser extension: ${JSON.stringify(n)}`),this.messageChannel.port1.postMessage(n);const o=await new Promise((s,a)=>{this.resolvers.set(n.responseId,{resolve:s,reject:a})});return this.validatePlatformBrokerResponse(o)}static async createProvider(e,t,n){e.trace("PlatformAuthExtensionHandler - createProvider called.");try{const o=new Bt(e,t,n,X.PREFERRED_EXTENSION_ID);return await o.sendHandshakeRequest(),o}catch{const r=new Bt(e,t,n);return await r.sendHandshakeRequest(),r}}async sendHandshakeRequest(){this.logger.trace(this.platformAuthType+" - sendHandshakeRequest called."),window.addEventListener("message",this.windowListener,!1);const e={channel:X.CHANNEL_ID,extensionId:this.extensionId,responseId:ce(),body:{method:Je.HandshakeRequest}};return this.handshakeEvent.add({extensionId:this.extensionId,extensionHandshakeTimeoutMs:this.handshakeTimeoutMs}),this.messageChannel.port1.onmessage=t=>{this.onChannelMessage(t)},window.postMessage(e,window.origin,[this.messageChannel.port2]),new Promise((t,n)=>{this.handshakeResolvers.set(e.responseId,{resolve:t,reject:n}),this.timeoutId=window.setTimeout(()=>{window.removeEventListener("message",this.windowListener,!1),this.messageChannel.port1.close(),this.messageChannel.port2.close(),this.handshakeEvent.end({extensionHandshakeTimedOut:!0,success:!1}),n(y(ts)),this.handshakeResolvers.delete(e.responseId)},this.handshakeTimeoutMs)})}onWindowMessage(e){if(this.logger.trace(this.platformAuthType+" - onWindowMessage called"),e.source!==window)return;const t=e.data;if(!(!t.channel||t.channel!==X.CHANNEL_ID)&&!(t.extensionId&&t.extensionId!==this.extensionId)&&t.body.method===Je.HandshakeRequest){const n=this.handshakeResolvers.get(t.responseId);if(!n){this.logger.trace(this.platformAuthType+`.onWindowMessage - resolver can't be found for request ${t.responseId}`);return}this.logger.verbose(t.extensionId?`Extension with id: ${t.extensionId} not installed`:"No extension installed"),clearTimeout(this.timeoutId),this.messageChannel.port1.close(),this.messageChannel.port2.close(),window.removeEventListener("message",this.windowListener,!1),this.handshakeEvent.end({success:!1,extensionInstalled:!1}),n.reject(y(ns))}}onChannelMessage(e){this.logger.trace(this.platformAuthType+" - onChannelMessage called.");const t=e.data,n=this.resolvers.get(t.responseId),o=this.handshakeResolvers.get(t.responseId);try{const r=t.body.method;if(r===Je.Response){if(!n)return;const s=t.body.response;if(this.logger.trace(this.platformAuthType+" - Received response from browser extension"),this.logger.tracePii(this.platformAuthType+` - Received response from browser extension: ${JSON.stringify(s)}`),s.status!=="Success")n.reject(Ft(s.code,s.description,s.ext));else if(s.result)s.result.code&&s.result.description?n.reject(Ft(s.result.code,s.result.description,s.result.ext)):n.resolve(s.result);else throw fn(kt,"Event does not contain result.");this.resolvers.delete(t.responseId)}else if(r===Je.HandshakeResponse){if(!o){this.logger.trace(this.platformAuthType+`.onChannelMessage - resolver can't be found for request ${t.responseId}`);return}clearTimeout(this.timeoutId),window.removeEventListener("message",this.windowListener,!1),this.extensionId=t.extensionId,this.extensionVersion=t.body.version,this.logger.verbose(this.platformAuthType+` - Received HandshakeResponse from extension: ${this.extensionId}`),this.handshakeEvent.end({extensionInstalled:!0,success:!0}),o.resolve(),this.handshakeResolvers.delete(t.responseId)}}catch(r){this.logger.error("Error parsing response from WAM Extension"),this.logger.errorPii(`Error parsing response from WAM Extension: ${r}`),this.logger.errorPii(`Unable to parse ${e}`),n?n.reject(r):o&&o.reject(r)}}validatePlatformBrokerResponse(e){if(e.hasOwnProperty("access_token")&&e.hasOwnProperty("id_token")&&e.hasOwnProperty("client_info")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scope")&&e.hasOwnProperty("expires_in"))return e;throw fn(kt,"Response missing expected properties.")}getExtensionId(){return this.extensionId}getExtensionVersion(){return this.extensionVersion}getExtensionName(){return this.getExtensionId()===X.PREFERRED_EXTENSION_ID?"chrome":this.getExtensionId()?.length?"unknown":void 0}}class Do{constructor(e,t,n){this.logger=e,this.performanceClient=t,this.correlationId=n,this.platformAuthType=X.PLATFORM_DOM_PROVIDER}static async createProvider(e,t,n){if(e.trace("PlatformAuthDOMHandler: createProvider called"),window.navigator?.platformAuthentication&&(await window.navigator.platformAuthentication.getSupportedContracts(X.MICROSOFT_ENTRA_BROKERID))?.includes(X.PLATFORM_DOM_APIS))return e.trace("Platform auth api available in DOM"),new Do(e,t,n)}getExtensionId(){return X.MICROSOFT_ENTRA_BROKERID}getExtensionVersion(){return""}getExtensionName(){return X.DOM_API_NAME}async sendMessage(e){this.logger.trace(this.platformAuthType+" - Sending request to browser DOM API");try{const t=this.initializePlatformDOMRequest(e),n=await window.navigator.platformAuthentication.executeGetToken(t);return this.validatePlatformBrokerResponse(n)}catch(t){throw this.logger.error(this.platformAuthType+" - executeGetToken DOM API error"),t}}initializePlatformDOMRequest(e){this.logger.trace(this.platformAuthType+" - initializeNativeDOMRequest called");const{accountId:t,clientId:n,authority:o,scope:r,redirectUri:s,correlationId:a,state:c,storeInCache:l,embeddedClientId:d,extraParameters:u,...m}=e,C=this.getDOMExtraParams(m);return{accountId:t,brokerId:this.getExtensionId(),authority:o,clientId:n,correlationId:a||this.correlationId,extraParameters:{...u,...C},isSecurityTokenService:!1,redirectUri:s,scope:r,state:c,storeInCache:l,embeddedClientId:d}}validatePlatformBrokerResponse(e){if(e.hasOwnProperty("isSuccess")){if(e.hasOwnProperty("accessToken")&&e.hasOwnProperty("idToken")&&e.hasOwnProperty("clientInfo")&&e.hasOwnProperty("account")&&e.hasOwnProperty("scopes")&&e.hasOwnProperty("expiresIn"))return this.logger.trace(this.platformAuthType+" - platform broker returned successful and valid response"),this.convertToPlatformBrokerResponse(e);if(e.hasOwnProperty("error")){const t=e;if(t.isSuccess===!1&&t.error&&t.error.code)throw this.logger.trace(this.platformAuthType+" - platform broker returned error response"),Ft(t.error.code,t.error.description,{error:parseInt(t.error.errorCode),protocol_error:t.error.protocolError,status:t.error.status,properties:t.error.properties})}}throw fn(kt,"Response missing expected properties.")}convertToPlatformBrokerResponse(e){return this.logger.trace(this.platformAuthType+" - convertToNativeResponse called"),{access_token:e.accessToken,id_token:e.idToken,client_info:e.clientInfo,account:e.account,expires_in:e.expiresIn,scope:e.scopes,state:e.state||"",properties:e.properties||{},extendedLifetimeToken:e.extendedLifetimeToken??!1,shr:e.proofOfPossessionPayload}}getDOMExtraParams(e){try{const t={};for(const[n,o]of Object.entries(e))o&&(typeof o=="object"?t[n]=JSON.stringify(o):t[n]=String(o));return t}catch(t){return this.logger.error(this.platformAuthType+" - Error stringifying extra parameters"),this.logger.errorPii(this.platformAuthType+" - Error stringifying extra parameters: "+t),{}}}}async function ch(i,e,t,n,o){i.trace("getPlatformAuthProvider called",t),i.trace("Has client allowed platform auth via DOM API: "+o);let r;try{o&&(r=await Do.createProvider(i,e,t)),r||(i.trace("Platform auth via DOM API not available, checking for extension"),r=await Bt.createProvider(i,n||Is,e))}catch(s){i.trace("Platform auth not available",s)}return r}function ct(i,e,t,n){if(e.trace("isPlatformAuthAllowed called"),!i.system.allowPlatformBroker&&i.system.allowPlatformBrokerWithDOM)throw _(ni);if(!i.system.allowPlatformBroker)return e.trace("isPlatformAuthAllowed: allowPlatformBroker is not enabled, returning false"),!1;if(!t)return e.trace("isPlatformAuthAllowed: Platform auth provider is not initialized, returning false"),!1;if(n)switch(n){case v.BEARER:case v.POP:return e.trace("isPlatformAuthAllowed: authenticationScheme is supported, returning true"),!0;default:return e.trace("isPlatformAuthAllowed: authenticationScheme is not supported, returning false"),!1}return!0}class lh extends Ye{constructor(e,t,n,o,r,s,a,c,l,d){super(e,t,n,o,r,s,a,l,d),this.unloadWindow=this.unloadWindow.bind(this),this.nativeStorage=c,this.eventHandler=r}acquireToken(e,t){let n;try{if(n={popupName:this.generatePopupName(e.scopes||Ve,e.authority||this.config.auth.authority),popupWindowAttributes:e.popupWindowAttributes||{},popupWindowParent:e.popupWindowParent??window},this.performanceClient.addFields({isAsyncPopup:this.config.system.asyncPopups},this.correlationId),this.config.system.asyncPopups)return this.logger.verbose("asyncPopups set to true, acquiring token"),this.acquireTokenPopupAsync(e,n,t);{const r={...e,httpMethod:ks(e,this.config.auth.protocolMode)};return this.logger.verbose("asyncPopup set to false, opening popup before acquiring token"),n.popup=this.openSizedPopup("about:blank",n),this.acquireTokenPopupAsync(r,n,t)}}catch(o){return Promise.reject(o)}}logout(e){try{this.logger.verbose("logoutPopup called");const t=this.initializeLogoutRequest(e),n={popupName:this.generateLogoutPopupName(t),popupWindowAttributes:e?.popupWindowAttributes||{},popupWindowParent:e?.popupWindowParent??window},o=e&&e.authority,r=e&&e.mainWindowRedirectUri;return this.config.system.asyncPopups?(this.logger.verbose("asyncPopups set to true"),this.logoutPopupAsync(t,n,o,r)):(this.logger.verbose("asyncPopup set to false, opening popup"),n.popup=this.openSizedPopup("about:blank",n),this.logoutPopupAsync(t,n,o,r))}catch(t){return Promise.reject(t)}}async acquireTokenPopupAsync(e,t,n){this.logger.verbose("acquireTokenPopupAsync called");const o=await g(this.initializeAuthorizationRequest.bind(this),h.StandardInteractionClientInitializeAuthorizationRequest,this.logger,this.performanceClient,this.correlationId)(e,T.Popup);t.popup&&As(o.authority);const r=ct(this.config,this.logger,this.platformAuthProvider,e.authenticationScheme);return o.platformBroker=r,this.config.auth.protocolMode===V.EAR?this.executeEarFlow(o,t,n):this.executeCodeFlow(o,t,n)}async executeCodeFlow(e,t,n){const o=e.correlationId,r=this.initializeServerTelemetryManager(S.acquireTokenPopup),s=n||await g(Ie,h.GeneratePkceCodes,this.logger,this.performanceClient,o)(this.performanceClient,this.logger,o),a={...e,codeChallenge:s.challenge};try{const c=await g(this.createAuthCodeClient.bind(this),h.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,o)({serverTelemetryManager:r,requestAuthority:a.authority,requestAzureCloudOptions:a.azureCloudOptions,requestExtraQueryParameters:a.extraQueryParameters,account:a.account});if(a.httpMethod===_e.POST)return await this.executeCodeFlowWithPost(a,t,c,s.verifier);{const l=await g(Kt,h.GetAuthCodeUrl,this.logger,this.performanceClient,o)(this.config,c.authority,a,this.logger,this.performanceClient),d=this.initiateAuthRequest(l,t);this.eventHandler.emitEvent(A.POPUP_OPENED,T.Popup,{popupWindow:d},null);const u=await this.monitorPopupForHash(d,t.popupWindowParent),m=W(ze,h.DeserializeResponse,this.logger,this.performanceClient,this.correlationId)(u,this.config.auth.OIDCOptions.serverResponseType,this.logger);return await g(qe,h.HandleResponseCode,this.logger,this.performanceClient,o)(e,m,s.verifier,S.acquireTokenPopup,this.config,c,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}}catch(c){throw t.popup?.close(),c instanceof R&&(c.setCorrelationId(this.correlationId),r.cacheFailedRequest(c)),c}}async executeEarFlow(e,t,n){const o=e.correlationId,r=await g(this.getDiscoveredAuthority.bind(this),h.StandardInteractionClientGetDiscoveredAuthority,this.logger,this.performanceClient,o)({requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),s=await g(Eo,h.GenerateEarKey,this.logger,this.performanceClient,o)(),a=n||await g(Ie,h.GeneratePkceCodes,this.logger,this.performanceClient,o)(this.performanceClient,this.logger,o),c={...e,earJwk:s,codeChallenge:a.challenge},l=t.popup||this.openPopup("about:blank",t);(await No(l.document,this.config,r,c,this.logger,this.performanceClient)).submit();const u=await g(this.monitorPopupForHash.bind(this),h.SilentHandlerMonitorIframeForHash,this.logger,this.performanceClient,o)(l,t.popupWindowParent),m=W(ze,h.DeserializeResponse,this.logger,this.performanceClient,this.correlationId)(u,this.config.auth.OIDCOptions.serverResponseType,this.logger);if(!m.ear_jwe&&m.code){const C=await g(this.createAuthCodeClient.bind(this),h.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,o)({serverTelemetryManager:this.initializeServerTelemetryManager(S.acquireTokenPopup),requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account,authority:r});return g(qe,h.HandleResponseCode,this.logger,this.performanceClient,o)(c,m,a.verifier,S.acquireTokenPopup,this.config,C,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}else return g(Uo,h.HandleResponseEar,this.logger,this.performanceClient,o)(c,m,S.acquireTokenPopup,this.config,r,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async executeCodeFlowWithPost(e,t,n,o){const r=e.correlationId,s=await g(this.getDiscoveredAuthority.bind(this),h.StandardInteractionClientGetDiscoveredAuthority,this.logger,this.performanceClient,r)({requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),a=t.popup||this.openPopup("about:blank",t);(await Mo(a.document,this.config,s,e,this.logger,this.performanceClient)).submit();const l=await g(this.monitorPopupForHash.bind(this),h.SilentHandlerMonitorIframeForHash,this.logger,this.performanceClient,r)(a,t.popupWindowParent),d=W(ze,h.DeserializeResponse,this.logger,this.performanceClient,this.correlationId)(l,this.config.auth.OIDCOptions.serverResponseType,this.logger);return g(qe,h.HandleResponseCode,this.logger,this.performanceClient,r)(e,d,o,S.acquireTokenPopup,this.config,n,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async logoutPopupAsync(e,t,n,o){this.logger.verbose("logoutPopupAsync called"),this.eventHandler.emitEvent(A.LOGOUT_START,T.Popup,e);const r=this.initializeServerTelemetryManager(S.logoutPopup);try{await this.clearCacheOnLogout(this.correlationId,e.account);const s=await g(this.createAuthCodeClient.bind(this),h.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:r,requestAuthority:n,account:e.account||void 0});try{s.authority.endSessionEndpoint}catch{if(e.account?.homeAccountId&&e.postLogoutRedirectUri&&s.authority.protocolMode===V.OIDC){if(this.eventHandler.emitEvent(A.LOGOUT_SUCCESS,T.Popup,e),o){const l={apiId:S.logoutPopup,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},d=k.getAbsoluteUrl(o,de());await this.navigationClient.navigateInternal(d,l)}t.popup?.close();return}}const a=s.getLogoutUri(e);this.eventHandler.emitEvent(A.LOGOUT_SUCCESS,T.Popup,e);const c=this.openPopup(a,t);if(this.eventHandler.emitEvent(A.POPUP_OPENED,T.Popup,{popupWindow:c},null),await this.monitorPopupForHash(c,t.popupWindowParent).catch(()=>{}),o){const l={apiId:S.logoutPopup,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},d=k.getAbsoluteUrl(o,de());this.logger.verbose("Redirecting main window to url specified in the request"),this.logger.verbosePii(`Redirecting main window to: ${d}`),await this.navigationClient.navigateInternal(d,l)}else this.logger.verbose("No main window navigation requested")}catch(s){throw t.popup?.close(),s instanceof R&&(s.setCorrelationId(this.correlationId),r.cacheFailedRequest(s)),this.eventHandler.emitEvent(A.LOGOUT_FAILURE,T.Popup,null,s),this.eventHandler.emitEvent(A.LOGOUT_END,T.Popup),s}this.eventHandler.emitEvent(A.LOGOUT_END,T.Popup)}initiateAuthRequest(e,t){if(e)return this.logger.infoPii(`Navigate to: ${e}`),this.openPopup(e,t);throw this.logger.error("Navigate url is empty"),y(Zt)}monitorPopupForHash(e,t){return new Promise((n,o)=>{this.logger.verbose("PopupHandler.monitorPopupForHash - polling started");const r=setInterval(()=>{if(e.closed){this.logger.error("PopupHandler.monitorPopupForHash - window closed"),clearInterval(r),o(y(st));return}let s="";try{s=e.location.href}catch{}if(!s||s==="about:blank")return;clearInterval(r);let a="";const c=this.config.auth.OIDCOptions.serverResponseType;e&&(c===Gt.QUERY?a=e.location.search:a=e.location.hash),this.logger.verbose("PopupHandler.monitorPopupForHash - popup window is on same origin as caller"),n(a)},this.config.system.pollIntervalMilliseconds)}).finally(()=>{this.cleanPopup(e,t)})}openPopup(e,t){try{let n;if(t.popup?(n=t.popup,this.logger.verbosePii(`Navigating popup window to: ${e}`),n.location.assign(e)):typeof t.popup>"u"&&(this.logger.verbosePii(`Opening popup window to: ${e}`),n=this.openSizedPopup(e,t)),!n)throw y(Ki);return n.focus&&n.focus(),this.currentWindow=n,t.popupWindowParent.addEventListener("beforeunload",this.unloadWindow),n}catch(n){throw this.logger.error("error opening popup "+n.message),y(Fi)}}openSizedPopup(e,{popupName:t,popupWindowAttributes:n,popupWindowParent:o}){const r=o.screenLeft?o.screenLeft:o.screenX,s=o.screenTop?o.screenTop:o.screenY,a=o.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,c=o.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;let l=n.popupSize?.width,d=n.popupSize?.height,u=n.popupPosition?.top,m=n.popupPosition?.left;return(!l||l<0||l>a)&&(this.logger.verbose("Default popup window width used. Window width not configured or invalid."),l=Q.POPUP_WIDTH),(!d||d<0||d>c)&&(this.logger.verbose("Default popup window height used. Window height not configured or invalid."),d=Q.POPUP_HEIGHT),(!u||u<0||u>c)&&(this.logger.verbose("Default popup window top position used. Window top not configured or invalid."),u=Math.max(0,c/2-Q.POPUP_HEIGHT/2+s)),(!m||m<0||m>a)&&(this.logger.verbose("Default popup window left position used. Window left not configured or invalid."),m=Math.max(0,a/2-Q.POPUP_WIDTH/2+r)),o.open(e,t,`width=${l}, height=${d}, top=${u}, left=${m}, scrollbars=yes`)}unloadWindow(e){this.currentWindow&&this.currentWindow.close(),e.preventDefault()}cleanPopup(e,t){e.close(),t.removeEventListener("beforeunload",this.unloadWindow)}generatePopupName(e,t){return`${Q.POPUP_NAME_PREFIX}.${this.config.auth.clientId}.${e.join("-")}.${t}.${this.correlationId}`}generateLogoutPopupName(e){const t=e.account&&e.account.homeAccountId;return`${Q.POPUP_NAME_PREFIX}.${this.config.auth.clientId}.${t}.${this.correlationId}`}}function hh(){if(typeof window>"u"||typeof window.performance>"u"||typeof window.performance.getEntriesByType!="function")return;const i=window.performance.getEntriesByType("navigation");return(i.length?i[0]:void 0)?.type}class dh extends Ye{constructor(e,t,n,o,r,s,a,c,l,d){super(e,t,n,o,r,s,a,l,d),this.nativeStorage=c}async acquireToken(e){const t=await g(this.initializeAuthorizationRequest.bind(this),h.StandardInteractionClientInitializeAuthorizationRequest,this.logger,this.performanceClient,this.correlationId)(e,T.Redirect);t.platformBroker=ct(this.config,this.logger,this.platformAuthProvider,e.authenticationScheme);const n=r=>{r.persisted&&(this.logger.verbose("Page was restored from back/forward cache. Clearing temporary cache."),this.browserStorage.resetRequestCache(),this.eventHandler.emitEvent(A.RESTORE_FROM_BFCACHE,T.Redirect))},o=this.getRedirectStartPage(e.redirectStartPage);this.logger.verbosePii(`Redirect start page: ${o}`),this.browserStorage.setTemporaryCache(N.ORIGIN_URI,o,!0),window.addEventListener("pageshow",n);try{this.config.auth.protocolMode===V.EAR?await this.executeEarFlow(t):await this.executeCodeFlow(t,e.onRedirectNavigate)}catch(r){throw r instanceof R&&r.setCorrelationId(this.correlationId),window.removeEventListener("pageshow",n),r}}async executeCodeFlow(e,t){const n=e.correlationId,o=this.initializeServerTelemetryManager(S.acquireTokenRedirect),r=await g(Ie,h.GeneratePkceCodes,this.logger,this.performanceClient,n)(this.performanceClient,this.logger,n),s={...e,codeChallenge:r.challenge};this.browserStorage.cacheAuthorizeRequest(s,r.verifier);try{if(s.httpMethod===_e.POST)return await this.executeCodeFlowWithPost(s);{const a=await g(this.createAuthCodeClient.bind(this),h.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:o,requestAuthority:s.authority,requestAzureCloudOptions:s.azureCloudOptions,requestExtraQueryParameters:s.extraQueryParameters,account:s.account}),c=await g(Kt,h.GetAuthCodeUrl,this.logger,this.performanceClient,e.correlationId)(this.config,a.authority,s,this.logger,this.performanceClient);return await this.initiateAuthRequest(c,t)}}catch(a){throw a instanceof R&&(a.setCorrelationId(this.correlationId),o.cacheFailedRequest(a)),a}}async executeEarFlow(e){const t=e.correlationId,n=await g(this.getDiscoveredAuthority.bind(this),h.StandardInteractionClientGetDiscoveredAuthority,this.logger,this.performanceClient,t)({requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),o=await g(Eo,h.GenerateEarKey,this.logger,this.performanceClient,t)(),r=await g(Ie,h.GeneratePkceCodes,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),s={...e,earJwk:o,codeChallenge:r.challenge};return this.browserStorage.cacheAuthorizeRequest(s,r.verifier),(await No(document,this.config,n,s,this.logger,this.performanceClient)).submit(),new Promise((c,l)=>{setTimeout(()=>{l(y(Ht,"failed_to_redirect"))},this.config.system.redirectNavigationTimeout)})}async executeCodeFlowWithPost(e){const t=e.correlationId,n=await g(this.getDiscoveredAuthority.bind(this),h.StandardInteractionClientGetDiscoveredAuthority,this.logger,this.performanceClient,t)({requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account});return this.browserStorage.cacheAuthorizeRequest(e),(await Mo(document,this.config,n,e,this.logger,this.performanceClient)).submit(),new Promise((r,s)=>{setTimeout(()=>{s(y(Ht,"failed_to_redirect"))},this.config.system.redirectNavigationTimeout)})}async handleRedirectPromise(e="",t,n,o){const r=this.initializeServerTelemetryManager(S.handleRedirectPromise);try{const[s,a]=this.getRedirectResponse(e||"");if(!s)return this.logger.info("handleRedirectPromise did not detect a response as a result of a redirect. Cleaning temporary cache."),this.browserStorage.resetRequestCache(),hh()!=="back_forward"?o.event.errorCode="no_server_response":this.logger.verbose("Back navigation event detected. Muting no_server_response error"),null;const c=this.browserStorage.getTemporaryCache(N.ORIGIN_URI,!0)||f.EMPTY_STRING,l=zo(c),d=zo(window.location.href);if(l===d&&this.config.auth.navigateToLoginRequestUrl)return this.logger.verbose("Current page is loginRequestUrl, handling response"),c.indexOf("#")>-1&&gl(c),await this.handleResponse(s,t,n,r);if(this.config.auth.navigateToLoginRequestUrl){if(!_o()||this.config.system.allowRedirectInIframe){this.browserStorage.setTemporaryCache(N.URL_HASH,a,!0);const u={apiId:S.handleRedirectPromise,timeout:this.config.system.redirectNavigationTimeout,noHistory:!0};let m=!0;if(!c||c==="null"){const C=ml();this.browserStorage.setTemporaryCache(N.ORIGIN_URI,C,!0),this.logger.warning("Unable to get valid login request url from cache, redirecting to home page"),m=await this.navigationClient.navigateInternal(C,u)}else this.logger.verbose(`Navigating to loginRequestUrl: ${c}`),m=await this.navigationClient.navigateInternal(c,u);if(!m)return await this.handleResponse(s,t,n,r)}}else return this.logger.verbose("NavigateToLoginRequestUrl set to false, handling response"),await this.handleResponse(s,t,n,r);return null}catch(s){throw s instanceof R&&(s.setCorrelationId(this.correlationId),r.cacheFailedRequest(s)),s}}getRedirectResponse(e){this.logger.verbose("getRedirectResponseHash called");let t=e;t||(this.config.auth.OIDCOptions.serverResponseType===Gt.QUERY?t=window.location.search:t=window.location.hash);let n=Rt(t);if(n){try{Ql(n,this.browserCrypto,T.Redirect)}catch(r){return r instanceof R&&this.logger.error(`Interaction type validation failed due to ${r.errorCode}: ${r.errorMessage}`),[null,""]}return Cs(window),this.logger.verbose("Hash contains known properties, returning response hash"),[n,t]}const o=this.browserStorage.getTemporaryCache(N.URL_HASH,!0);return this.browserStorage.removeItem(this.browserStorage.generateCacheKey(N.URL_HASH)),o&&(n=Rt(o),n)?(this.logger.verbose("Hash does not contain known properties, returning cached hash"),[n,o]):[null,""]}async handleResponse(e,t,n,o){if(!e.state)throw y(mo);if(e.ear_jwe){const a=await g(this.getDiscoveredAuthority.bind(this),h.StandardInteractionClientGetDiscoveredAuthority,this.logger,this.performanceClient,t.correlationId)({requestAuthority:t.authority,requestAzureCloudOptions:t.azureCloudOptions,requestExtraQueryParameters:t.extraQueryParameters,account:t.account});return g(Uo,h.HandleResponseEar,this.logger,this.performanceClient,t.correlationId)(t,e,S.acquireTokenRedirect,this.config,a,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}const s=await g(this.createAuthCodeClient.bind(this),h.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:o,requestAuthority:t.authority});return g(qe,h.HandleResponseCode,this.logger,this.performanceClient,t.correlationId)(t,e,n,S.acquireTokenRedirect,this.config,s,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async initiateAuthRequest(e,t){if(this.logger.verbose("RedirectHandler.initiateAuthRequest called"),e){this.logger.infoPii(`RedirectHandler.initiateAuthRequest: Navigate to: ${e}`);const n={apiId:S.acquireTokenRedirect,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},o=t||this.config.auth.onRedirectNavigate;if(typeof o=="function")if(this.logger.verbose("RedirectHandler.initiateAuthRequest: Invoking onRedirectNavigate callback"),o(e)!==!1){this.logger.verbose("RedirectHandler.initiateAuthRequest: onRedirectNavigate did not return false, navigating"),await this.navigationClient.navigateExternal(e,n);return}else{this.logger.verbose("RedirectHandler.initiateAuthRequest: onRedirectNavigate returned false, stopping navigation");return}else{this.logger.verbose("RedirectHandler.initiateAuthRequest: Navigating window to navigate url"),await this.navigationClient.navigateExternal(e,n);return}}else throw this.logger.info("RedirectHandler.initiateAuthRequest: Navigate url is empty"),y(Zt)}async logout(e){this.logger.verbose("logoutRedirect called");const t=this.initializeLogoutRequest(e),n=this.initializeServerTelemetryManager(S.logout);try{this.eventHandler.emitEvent(A.LOGOUT_START,T.Redirect,e),await this.clearCacheOnLogout(this.correlationId,t.account);const o={apiId:S.logout,timeout:this.config.system.redirectNavigationTimeout,noHistory:!1},r=await g(this.createAuthCodeClient.bind(this),h.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:n,requestAuthority:e&&e.authority,requestExtraQueryParameters:e?.extraQueryParameters,account:e&&e.account||void 0});if(r.authority.protocolMode===V.OIDC)try{r.authority.endSessionEndpoint}catch{if(t.account?.homeAccountId){this.eventHandler.emitEvent(A.LOGOUT_SUCCESS,T.Redirect,t);return}}const s=r.getLogoutUri(t);if(this.eventHandler.emitEvent(A.LOGOUT_SUCCESS,T.Redirect,t),e&&typeof e.onRedirectNavigate=="function")if(e.onRedirectNavigate(s)!==!1){this.logger.verbose("Logout onRedirectNavigate did not return false, navigating"),this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0,me.SIGNOUT),await this.navigationClient.navigateExternal(s,o);return}else this.browserStorage.setInteractionInProgress(!1),this.logger.verbose("Logout onRedirectNavigate returned false, stopping navigation");else{this.browserStorage.getInteractionInProgress()||this.browserStorage.setInteractionInProgress(!0,me.SIGNOUT),await this.navigationClient.navigateExternal(s,o);return}}catch(o){throw o instanceof R&&(o.setCorrelationId(this.correlationId),n.cacheFailedRequest(o)),this.eventHandler.emitEvent(A.LOGOUT_FAILURE,T.Redirect,null,o),this.eventHandler.emitEvent(A.LOGOUT_END,T.Redirect),o}this.eventHandler.emitEvent(A.LOGOUT_END,T.Redirect)}getRedirectStartPage(e){const t=e||window.location.href;return k.getAbsoluteUrl(t,de())}}async function Ir(i,e,t,n,o){if(e.addQueueMeasurement(h.SilentHandlerInitiateAuthRequest,n),!i)throw t.info("Navigate url is empty"),y(Zt);return o?g(fh,h.SilentHandlerLoadFrame,t,e,n)(i,o,e,n):W(mh,h.SilentHandlerLoadFrameSync,t,e,n)(i)}async function uh(i,e,t,n,o){const r=rn();if(!r.contentDocument)throw"No document associated with iframe!";return(await Mo(r.contentDocument,i,e,t,n,o)).submit(),r}async function gh(i,e,t,n,o){const r=rn();if(!r.contentDocument)throw"No document associated with iframe!";return(await No(r.contentDocument,i,e,t,n,o)).submit(),r}async function gn(i,e,t,n,o,r,s){n.addQueueMeasurement(h.SilentHandlerMonitorIframeForHash,r),n.addFields({iframePollIntervalMs:t,iframeTimeoutMs:e},r);let a=0,c=0;return new Promise((l,d)=>{e<kn&&o.warning(`system.loadFrameTimeout or system.iframeHashTimeout set to lower (${e}ms) than the default (${kn}ms). This may result in timeouts.`);const u=window.setTimeout(()=>{window.clearInterval(m),d(y(Bi))},e),m=window.setInterval(()=>{a++;let C="";const E=i.contentWindow;try{C=E?E.location.href:""}catch{c++}if(!C||C==="about:blank")return;let I="";E&&(s===Gt.QUERY?I=E.location.search:I=E.location.hash),window.clearTimeout(u),window.clearInterval(m),l(I)},t)}).finally(()=>{n.addFields({iframeTickCount:a,crossOriginTickCount:c},r),W(ph,h.RemoveHiddenIframe,o,n,r)(i)})}function fh(i,e,t,n){return t.addQueueMeasurement(h.SilentHandlerLoadFrame,n),new Promise((o,r)=>{const s=rn();window.setTimeout(()=>{if(!s){r("Unable to load iframe");return}s.src=i,o(s)},e)})}function mh(i){const e=rn();return e.src=i,e}function rn(){const i=document.createElement("iframe");return i.className="msalSilentIframe",i.style.visibility="hidden",i.style.position="absolute",i.style.width=i.style.height="0",i.style.border="0",i.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),i.setAttribute("allow","local-network-access *"),document.body.appendChild(i),i}function ph(i){document.body===i.parentNode&&document.body.removeChild(i)}class Ch extends Ye{constructor(e,t,n,o,r,s,a,c,l,d,u){super(e,t,n,o,r,s,c,d,u),this.apiId=a,this.nativeStorage=l}async acquireToken(e){this.performanceClient.addQueueMeasurement(h.SilentIframeClientAcquireToken,e.correlationId),!e.loginHint&&!e.sid&&(!e.account||!e.account.username)&&this.logger.warning("No user hint provided. The authorization server may need more information to complete this request.");const t={...e};t.prompt?t.prompt!==U.NONE&&t.prompt!==U.NO_SESSION&&(this.logger.warning(`SilentIframeClient. Replacing invalid prompt ${t.prompt} with ${U.NONE}`),t.prompt=U.NONE):t.prompt=U.NONE;const n=await g(this.initializeAuthorizationRequest.bind(this),h.StandardInteractionClientInitializeAuthorizationRequest,this.logger,this.performanceClient,e.correlationId)(t,T.Silent);return n.platformBroker=ct(this.config,this.logger,this.platformAuthProvider,n.authenticationScheme),As(n.authority),this.config.auth.protocolMode===V.EAR?this.executeEarFlow(n):this.executeCodeFlow(n)}async executeCodeFlow(e){let t;const n=this.initializeServerTelemetryManager(this.apiId);try{return t=await g(this.createAuthCodeClient.bind(this),h.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:n,requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),await g(this.silentTokenHelper.bind(this),h.SilentIframeClientTokenHelper,this.logger,this.performanceClient,e.correlationId)(t,e)}catch(o){if(o instanceof R&&(o.setCorrelationId(this.correlationId),n.cacheFailedRequest(o)),!t||!(o instanceof R)||o.errorCode!==Q.INVALID_GRANT_ERROR)throw o;return this.performanceClient.addFields({retryError:o.errorCode},this.correlationId),await g(this.silentTokenHelper.bind(this),h.SilentIframeClientTokenHelper,this.logger,this.performanceClient,this.correlationId)(t,e)}}async executeEarFlow(e){const t=e.correlationId,n=await g(this.getDiscoveredAuthority.bind(this),h.StandardInteractionClientGetDiscoveredAuthority,this.logger,this.performanceClient,t)({requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account}),o=await g(Eo,h.GenerateEarKey,this.logger,this.performanceClient,t)(),r=await g(Ie,h.GeneratePkceCodes,this.logger,this.performanceClient,t)(this.performanceClient,this.logger,t),s={...e,earJwk:o,codeChallenge:r.challenge},a=await g(gh,h.SilentHandlerInitiateAuthRequest,this.logger,this.performanceClient,t)(this.config,n,s,this.logger,this.performanceClient),c=this.config.auth.OIDCOptions.serverResponseType,l=await g(gn,h.SilentHandlerMonitorIframeForHash,this.logger,this.performanceClient,t)(a,this.config.system.iframeHashTimeout,this.config.system.pollIntervalMilliseconds,this.performanceClient,this.logger,t,c),d=W(ze,h.DeserializeResponse,this.logger,this.performanceClient,t)(l,c,this.logger);if(!d.ear_jwe&&d.code){const u=await g(this.createAuthCodeClient.bind(this),h.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,t)({serverTelemetryManager:this.initializeServerTelemetryManager(this.apiId),requestAuthority:e.authority,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account,authority:n});return g(qe,h.HandleResponseCode,this.logger,this.performanceClient,t)(s,d,r.verifier,this.apiId,this.config,u,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}else return g(Uo,h.HandleResponseEar,this.logger,this.performanceClient,t)(s,d,this.apiId,this.config,n,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}async verifySso(e){this.performanceClient.addQueueMeasurement(h.SilentIframeClientAcquireToken,e.correlationId);const t={...e};t.prompt||(t.prompt=U.NONE);const n=await g(this.initializeAuthorizationRequest.bind(this),h.StandardInteractionClientInitializeAuthorizationRequest,this.logger,this.performanceClient,e.correlationId)(t,T.Silent),o=await g(this.createAuthCodeClient.bind(this),h.StandardInteractionClientCreateAuthCodeClient,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:this.initializeServerTelemetryManager(this.apiId),requestAuthority:n.authority,requestAzureCloudOptions:n.azureCloudOptions,requestExtraQueryParameters:n.extraQueryParameters,account:n.account}),r=n.correlationId,s=await g(Ie,h.GeneratePkceCodes,this.logger,this.performanceClient,r)(this.performanceClient,this.logger,r),a={...n,codeChallenge:s.challenge},c=await g(Kt,h.GetAuthCodeUrl,this.logger,this.performanceClient,r)(this.config,o.authority,a,this.logger,this.performanceClient),l=await g(Ir,h.SilentHandlerInitiateAuthRequest,this.logger,this.performanceClient,r)(c,this.performanceClient,this.logger,r,this.config.system.navigateFrameWait),d=this.config.auth.OIDCOptions.serverResponseType,u=await g(gn,h.SilentHandlerMonitorIframeForHash,this.logger,this.performanceClient,r)(l,this.config.system.iframeHashTimeout,this.config.system.pollIntervalMilliseconds,this.performanceClient,this.logger,r,d),m=W(ze,h.DeserializeResponse,this.logger,this.performanceClient,r)(u,d,this.logger);return lo(m,n.state),m.code?(this.logger.verbose("SSO verification completed successfully with valid authorization code - skipped token exchange",r),!0):(this.logger.warning("SSO verification response did not contain an authorization code",r),!1)}logout(){return Promise.reject(y(en))}async silentTokenHelper(e,t){const n=t.correlationId;this.performanceClient.addQueueMeasurement(h.SilentIframeClientTokenHelper,n);const o=await g(Ie,h.GeneratePkceCodes,this.logger,this.performanceClient,n)(this.performanceClient,this.logger,n),r={...t,codeChallenge:o.challenge};let s;if(t.httpMethod===_e.POST)s=await g(uh,h.SilentHandlerInitiateAuthRequest,this.logger,this.performanceClient,n)(this.config,e.authority,r,this.logger,this.performanceClient);else{const d=await g(Kt,h.GetAuthCodeUrl,this.logger,this.performanceClient,n)(this.config,e.authority,r,this.logger,this.performanceClient);s=await g(Ir,h.SilentHandlerInitiateAuthRequest,this.logger,this.performanceClient,n)(d,this.performanceClient,this.logger,n,this.config.system.navigateFrameWait)}const a=this.config.auth.OIDCOptions.serverResponseType,c=await g(gn,h.SilentHandlerMonitorIframeForHash,this.logger,this.performanceClient,n)(s,this.config.system.iframeHashTimeout,this.config.system.pollIntervalMilliseconds,this.performanceClient,this.logger,n,a),l=W(ze,h.DeserializeResponse,this.logger,this.performanceClient,n)(c,a,this.logger);return g(qe,h.HandleResponseCode,this.logger,this.performanceClient,n)(t,l,o.verifier,this.apiId,this.config,e,this.browserStorage,this.nativeStorage,this.eventHandler,this.logger,this.performanceClient,this.platformAuthProvider)}}class yh extends Ye{async acquireToken(e){this.performanceClient.addQueueMeasurement(h.SilentRefreshClientAcquireToken,e.correlationId);const t=await g(Po,h.InitializeBaseRequest,this.logger,this.performanceClient,e.correlationId)(e,this.config,this.performanceClient,this.logger),n={...e,...t};e.redirectUri&&(n.redirectUri=this.getRedirectUri(e.redirectUri));const o=this.initializeServerTelemetryManager(S.acquireTokenSilent_silentFlow),r=await this.createRefreshTokenClient({serverTelemetryManager:o,authorityUrl:n.authority,azureCloudOptions:n.azureCloudOptions,account:n.account});return g(r.acquireTokenByRefreshToken.bind(r),h.RefreshTokenClientAcquireTokenByRefreshToken,this.logger,this.performanceClient,e.correlationId)(n,S.acquireTokenSilent_silentFlow).catch(s=>{throw s.setCorrelationId(this.correlationId),o.cacheFailedRequest(s),s})}logout(){return Promise.reject(y(en))}async createRefreshTokenClient(e){const t=await g(this.getClientConfiguration.bind(this),h.StandardInteractionClientGetClientConfiguration,this.logger,this.performanceClient,this.correlationId)({serverTelemetryManager:e.serverTelemetryManager,requestAuthority:e.authorityUrl,requestAzureCloudOptions:e.azureCloudOptions,requestExtraQueryParameters:e.extraQueryParameters,account:e.account});return new Mc(t,this.performanceClient)}}class Th{constructor(e,t,n,o,r){this.isBrowserEnvironment=typeof window<"u",this.config=e,this.storage=t,this.logger=n,this.cryptoObj=o,this.performanceClient=r}async loadExternalTokens(e,t,n){if(!this.isBrowserEnvironment)throw y(tn);const o=e.correlationId||ce(),r=this.performanceClient.startMeasurement(h.LoadExternalTokens,o);try{const s=t.id_token?se(t.id_token,q):void 0,a=ae(s||{}),c={protocolMode:this.config.auth.protocolMode,knownAuthorities:this.config.auth.knownAuthorities,cloudDiscoveryMetadata:this.config.auth.cloudDiscoveryMetadata,authorityMetadata:this.config.auth.authorityMetadata,skipAuthorityMetadataCache:this.config.auth.skipAuthorityMetadataCache},l=e.authority||this.config.auth.authority,d=await oo(z.generateAuthority(l,e.azureCloudOptions),this.config.system.networkClient,this.storage,c,this.logger,o,this.performanceClient),u=await g(this.loadAccount.bind(this),h.LoadAccount,this.logger,this.performanceClient,o)(e,n.clientInfo||t.client_info||"",o,d,s),m=await g(this.loadIdToken.bind(this),h.LoadIdToken,this.logger,this.performanceClient,o)(t,u.homeAccountId,u.environment,u.realm,o,a),C=await g(this.loadAccessToken.bind(this),h.LoadAccessToken,this.logger,this.performanceClient,o)(e,t,u.homeAccountId,u.environment,u.realm,n,o,a),E=await g(this.loadRefreshToken.bind(this),h.LoadRefreshToken,this.logger,this.performanceClient,o)(t,u.homeAccountId,u.environment,o,a);return r.end({success:!0},void 0,O.getAccountInfo(u)),this.generateAuthenticationResult(e,{account:u,idToken:m,accessToken:C,refreshToken:E},d,s)}catch(s){throw r.end({success:!1},s),s}}async loadAccount(e,t,n,o,r){if(this.logger.verbose("TokenCache - loading account"),e.account){const l=O.createFromAccountInfo(e.account);return await this.storage.setAccount(l,n,ae(r||{}),S.loadExternalTokens),l}else if(!t&&!r)throw this.logger.error("TokenCache - if an account is not provided on the request, clientInfo or idToken must be provided instead."),y(Yi);const s=O.generateHomeAccountId(t,o.authorityType,this.logger,this.cryptoObj,r),a=r?.tid,c=ao(this.storage,o,s,q,n,r,t,o.getPreferredCache(),a,void 0,void 0,this.logger);return await this.storage.setAccount(c,n,ae(r||{}),S.loadExternalTokens),c}async loadIdToken(e,t,n,o,r,s){if(!e.id_token)return this.logger.verbose("TokenCache - no id token found in response"),null;this.logger.verbose("TokenCache - loading id token");const a=Vt(t,n,e.id_token,this.config.auth.clientId,o);return await this.storage.setIdTokenCredential(a,r,s),a}async loadAccessToken(e,t,n,o,r,s,a,c){if(t.access_token)if(t.expires_in){if(!t.scope&&(!e.scopes||!e.scopes.length))return this.logger.error("TokenCache - scopes not specified in the request or response. Cannot add token to the cache."),null}else return this.logger.error("TokenCache - no expiration set on the access token. Cannot add it to the cache."),null;else return this.logger.verbose("TokenCache - no access token found in response"),null;this.logger.verbose("TokenCache - loading access token");const l=t.scope?M.fromString(t.scope):new M(e.scopes),d=s.expiresOn||t.expires_in+$(),u=s.extendedExpiresOn||(t.ext_expires_in||t.expires_in)+$(),m=Wt(n,o,t.access_token,this.config.auth.clientId,r,l.printScopes(),d,u,q);return await this.storage.setAccessTokenCredential(m,a,c),m}async loadRefreshToken(e,t,n,o,r){if(!e.refresh_token)return this.logger.verbose("TokenCache - no refresh token found in response"),null;const s=e.refresh_token_expires_in?e.refresh_token_expires_in+$():void 0;this.performanceClient.addFields({extRtExpiresOnSeconds:s},o),this.logger.verbose("TokenCache - loading refresh token");const a=Ei(t,n,e.refresh_token,this.config.auth.clientId,e.foci,void 0,s);return await this.storage.setRefreshTokenCredential(a,o,r),a}generateAuthenticationResult(e,t,n,o){let r="",s=[],a=null,c;t?.accessToken&&(r=t.accessToken.secret,s=M.fromString(t.accessToken.target).asArray(),a=Ke(t.accessToken.expiresOn),c=Ke(t.accessToken.extendedExpiresOn));const l=t.account;return{authority:n?n.canonicalAuthority:"",uniqueId:t.account.localAccountId,tenantId:t.account.realm,scopes:s,account:O.getAccountInfo(l),idToken:t.idToken?.secret||"",idTokenClaims:o||{},accessToken:r,fromCache:!0,expiresOn:a,correlationId:e.correlationId||"",requestId:"",extExpiresOn:c,familyId:t.refreshToken?.familyId||"",tokenType:t?.accessToken?.tokenType||"",state:e.state||"",cloudGraphHostName:l.cloudGraphHostName||"",msGraphHost:l.msGraphHost||"",fromNativeBroker:!1}}}class Ah extends bi{constructor(e){super(e),this.includeRedirectUri=!1}}class Ih extends Ye{constructor(e,t,n,o,r,s,a,c,l,d){super(e,t,n,o,r,s,c,l,d),this.apiId=a}async acquireToken(e){if(!e.code)throw y(Ji);const t=await g(this.initializeAuthorizationRequest.bind(this),h.StandardInteractionClientInitializeAuthorizationRequest,this.logger,this.performanceClient,e.correlationId)(e,T.Silent),n=this.initializeServerTelemetryManager(this.apiId);try{const o={...t,code:e.code},r=await g(this.getClientConfiguration.bind(this),h.StandardInteractionClientGetClientConfiguration,this.logger,this.performanceClient,e.correlationId)({serverTelemetryManager:n,requestAuthority:t.authority,requestAzureCloudOptions:t.azureCloudOptions,requestExtraQueryParameters:t.extraQueryParameters,account:t.account}),s=new Ah(r);this.logger.verbose("Auth code client created");const a=new vs(s,this.browserStorage,o,this.logger,this.performanceClient);return await g(a.handleCodeResponseFromServer.bind(a),h.HandleCodeResponseFromServer,this.logger,this.performanceClient,e.correlationId)({code:e.code,msgraph_host:e.msGraphHost,cloud_graph_host_name:e.cloudGraphHostName,cloud_instance_host_name:e.cloudInstanceHostName},t,this.apiId,!1)}catch(o){throw o instanceof R&&(o.setCorrelationId(this.correlationId),n.cacheFailedRequest(o)),o}}logout(){return Promise.reject(y(en))}}function wh(i,e,t){const n=window.msal?.clientIds||[],o=n.length,r=n.filter(s=>s===i).length;r>1&&t.warning("There is already an instance of MSAL.js in the window with the same client id."),e.add({msalInstanceCount:o,sameClientIdInstanceCount:r})}function Ct(i,e,t){try{Ro(i)}catch(n){throw e.end({success:!1},n,t),n}}class sn{constructor(e){this.operatingContext=e,this.isBrowserEnvironment=this.operatingContext.isBrowserEnvironment(),this.config=e.getConfig(),this.initialized=!1,this.logger=this.operatingContext.getLogger(),this.networkClient=this.config.system.networkClient,this.navigationClient=this.config.system.navigationClient,this.redirectResponse=new Map,this.hybridAuthCodeResponses=new Map,this.performanceClient=this.config.telemetry.client,this.browserCrypto=this.isBrowserEnvironment?new ue(this.logger,this.performanceClient):vt,this.eventHandler=new zl(this.logger),this.browserStorage=this.isBrowserEnvironment?new _n(this.config.auth.clientId,this.config.cache,this.browserCrypto,this.logger,this.performanceClient,this.eventHandler,Sc(this.config.auth)):Ul(this.config.auth.clientId,this.logger,this.performanceClient,this.eventHandler);const t={cacheLocation:x.MemoryStorage,cacheRetentionDays:5,temporaryCacheLocation:x.MemoryStorage,storeAuthStateInCookie:!1,secureCookies:!1,cacheMigrationEnabled:!1,claimsBasedCachingEnabled:!1};this.nativeInternalStorage=new _n(this.config.auth.clientId,t,this.browserCrypto,this.logger,this.performanceClient,this.eventHandler),this.tokenCache=new Th(this.config,this.browserStorage,this.logger,this.browserCrypto,this.performanceClient),this.activeSilentTokenRequests=new Map,this.trackStateChangeWithMeasurement=this.trackStateChangeWithMeasurement.bind(this)}static async createController(e,t){const n=new sn(e);return await n.initialize(t),n}trackStateChange(e,t){e&&(t.type==="visibilitychange"?(this.logger.info("Perf: Visibility change detected"),this.performanceClient.incrementFields({visibilityChangeCount:1},e)):t.type==="online"?(this.logger.info("Perf: Online status change detected"),this.performanceClient.incrementFields({onlineStatusChangeCount:1},e)):t.type==="offline"&&(this.logger.info("Perf: Offline status change detected"),this.performanceClient.incrementFields({onlineStatusChangeCount:1},e)))}async initialize(e,t){if(this.logger.trace("initialize called"),this.initialized){this.logger.info("initialize has already been called, exiting early.");return}if(!this.isBrowserEnvironment){this.logger.info("in non-browser environment, exiting early."),this.initialized=!0,this.eventHandler.emitEvent(A.INITIALIZE_END);return}const n=e?.correlationId||this.getRequestCorrelationId(),o=this.config.system.allowPlatformBroker,r=this.performanceClient.startMeasurement(h.InitializeClientApplication,n);if(this.eventHandler.emitEvent(A.INITIALIZE_START),!t)try{this.logMultipleInstances(r)}catch{}if(await g(this.browserStorage.initialize.bind(this.browserStorage),h.InitializeCache,this.logger,this.performanceClient,n)(n),o)try{this.platformAuthProvider=await ch(this.logger,this.performanceClient,n,this.config.system.nativeBrokerHandshakeTimeout,this.config.system.allowPlatformBrokerWithDOM)}catch(s){this.logger.verbose(s)}this.config.cache.claimsBasedCachingEnabled||(this.logger.verbose("Claims-based caching is disabled. Clearing the previous cache with claims"),W(this.browserStorage.clearTokensAndKeysWithClaims.bind(this.browserStorage),h.ClearTokensAndKeysWithClaims,this.logger,this.performanceClient,n)(n)),this.config.system.asyncPopups&&await this.preGeneratePkceCodes(n),this.initialized=!0,this.eventHandler.emitEvent(A.INITIALIZE_END),r.end({allowPlatformBroker:o,success:!0})}async handleRedirectPromise(e){if(this.logger.verbose("handleRedirectPromise called"),Ts(this.initialized),this.isBrowserEnvironment){const t=e||"";let n=this.redirectResponse.get(t);return typeof n>"u"?(n=this.handleRedirectPromiseInternal(e),this.redirectResponse.set(t,n),this.logger.verbose("handleRedirectPromise has been called for the first time, storing the promise")):this.logger.verbose("handleRedirectPromise has been called previously, returning the result from the first call"),n}return this.logger.verbose("handleRedirectPromise returns null, not browser environment"),null}async handleRedirectPromiseInternal(e){if(!this.browserStorage.isInteractionInProgress(!0))return this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null."),null;if(this.browserStorage.getInteractionInProgress()?.type===me.SIGNOUT)return this.logger.verbose("handleRedirectPromise removing interaction_in_progress flag and returning null after sign-out"),this.browserStorage.setInteractionInProgress(!1),Promise.resolve(null);const n=this.getAllAccounts(),o=this.browserStorage.getCachedNativeRequest(),r=o&&this.platformAuthProvider&&!e;let s;this.eventHandler.emitEvent(A.HANDLE_REDIRECT_START,T.Redirect);let a;try{if(r&&this.platformAuthProvider){s=this.performanceClient.startMeasurement(h.AcquireTokenRedirect,o?.correlationId||""),this.logger.trace("handleRedirectPromise - acquiring token from native platform"),s.add({isPlatformBrokerRequest:!0});const c=new wt(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,S.handleRedirectPromise,this.performanceClient,this.platformAuthProvider,o.accountId,this.nativeInternalStorage,o.correlationId);a=g(c.handleRedirectPromise.bind(c),h.HandleNativeRedirectPromiseMeasurement,this.logger,this.performanceClient,s.event.correlationId)(this.performanceClient,s.event.correlationId)}else{const[c,l]=this.browserStorage.getCachedRequest(),d=c.correlationId;s=this.performanceClient.startMeasurement(h.AcquireTokenRedirect,d),this.logger.trace("handleRedirectPromise - acquiring token from web flow");const u=this.createRedirectClient(d);a=g(u.handleRedirectPromise.bind(u),h.HandleRedirectPromiseMeasurement,this.logger,this.performanceClient,s.event.correlationId)(e,c,l,s)}}catch(c){throw this.browserStorage.resetRequestCache(),c}return a.then(c=>(c?(this.browserStorage.resetRequestCache(),n.length<this.getAllAccounts().length?(this.eventHandler.emitEvent(A.LOGIN_SUCCESS,T.Redirect,c),this.logger.verbose("handleRedirectResponse returned result, login success")):(this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_SUCCESS,T.Redirect,c),this.logger.verbose("handleRedirectResponse returned result, acquire token success")),s.end({success:!0},void 0,c.account),this.verifySsoCapability(c.account,T.Redirect)):s.event.errorCode?s.end({success:!1},void 0):s.discard(),this.eventHandler.emitEvent(A.HANDLE_REDIRECT_END,T.Redirect),c)).catch(c=>{this.browserStorage.resetRequestCache();const l=c;throw n.length>0?this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_FAILURE,T.Redirect,null,l):this.eventHandler.emitEvent(A.LOGIN_FAILURE,T.Redirect,null,l),this.eventHandler.emitEvent(A.HANDLE_REDIRECT_END,T.Redirect),s.end({success:!1},l),c})}async acquireTokenRedirect(e){const t=this.getRequestCorrelationId(e);this.logger.verbose("acquireTokenRedirect called",t);const n=this.performanceClient.startMeasurement(h.AcquireTokenPreRedirect,t);n.add({scenarioId:e.scenarioId});const o=e.onRedirectNavigate;if(o)e.onRedirectNavigate=s=>{const a=typeof o=="function"?o(s):void 0;return n.add({navigateCallbackResult:a!==!1}),n.event=n.end({success:!0},void 0,e.account)||n.event,a};else{const s=this.config.auth.onRedirectNavigate;this.config.auth.onRedirectNavigate=a=>{const c=typeof s=="function"?s(a):void 0;return n.add({navigateCallbackResult:c!==!1}),n.event=n.end({success:!0},void 0,e.account)||n.event,c}}const r=this.getAllAccounts().length>0;try{dr(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0,me.SIGNIN),r?this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_START,T.Redirect,e):this.eventHandler.emitEvent(A.LOGIN_START,T.Redirect,e);let s;return this.platformAuthProvider&&this.canUsePlatformBroker(e)?s=new wt(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,S.acquireTokenRedirect,this.performanceClient,this.platformAuthProvider,this.getNativeAccountId(e),this.nativeInternalStorage,t).acquireTokenRedirect(e,n).catch(c=>{if(n.add({brokerErrorName:c.name,brokerErrorCode:c.errorCode}),c instanceof ie&&Le(c))return this.platformAuthProvider=void 0,this.createRedirectClient(t).acquireToken(e);if(c instanceof oe)return this.logger.verbose("acquireTokenRedirect - Resolving interaction required error thrown by native broker by falling back to web flow"),this.createRedirectClient(t).acquireToken(e);throw c}):s=this.createRedirectClient(t).acquireToken(e),await s}catch(s){throw this.browserStorage.resetRequestCache(),n.event.status===2?this.performanceClient.startMeasurement(h.AcquireTokenRedirect,t).end({success:!1},s,e.account):n.end({success:!1},s,e.account),r?this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_FAILURE,T.Redirect,null,s):this.eventHandler.emitEvent(A.LOGIN_FAILURE,T.Redirect,null,s),s}}acquireTokenPopup(e){const t=this.getRequestCorrelationId(e),n=this.performanceClient.startMeasurement(h.AcquireTokenPopup,t);n.add({scenarioId:e.scenarioId});try{this.logger.verbose("acquireTokenPopup called",t),Ct(this.initialized,n,e.account),this.browserStorage.setInteractionInProgress(!0,me.SIGNIN)}catch(a){return Promise.reject(a)}const o=this.getAllAccounts();o.length>0?this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_START,T.Popup,e):this.eventHandler.emitEvent(A.LOGIN_START,T.Popup,e);let r;const s=this.getPreGeneratedPkceCodes(t);return this.canUsePlatformBroker(e)?(n.add({isPlatformBrokerRequest:!0}),r=this.acquireTokenNative({...e,correlationId:t},S.acquireTokenPopup).then(a=>(n.end({success:!0},void 0,a.account),a)).catch(a=>{if(n.add({brokerErrorName:a.name,brokerErrorCode:a.errorCode}),a instanceof ie&&Le(a))return this.platformAuthProvider=void 0,this.createPopupClient(t).acquireToken(e,s);if(a instanceof oe)return this.logger.verbose("acquireTokenPopup - Resolving interaction required error thrown by native broker by falling back to web flow"),this.createPopupClient(t).acquireToken(e,s);throw a})):r=this.createPopupClient(t).acquireToken(e,s),r.then(a=>(o.length<this.getAllAccounts().length?this.eventHandler.emitEvent(A.LOGIN_SUCCESS,T.Popup,a):this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_SUCCESS,T.Popup,a),n.end({success:!0,accessTokenSize:a.accessToken.length,idTokenSize:a.idToken.length},void 0,a.account),this.verifySsoCapability(a.account,T.Popup),a)).catch(a=>(o.length>0?this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_FAILURE,T.Popup,null,a):this.eventHandler.emitEvent(A.LOGIN_FAILURE,T.Popup,null,a),n.end({success:!1},a,e.account),Promise.reject(a))).finally(async()=>{this.browserStorage.setInteractionInProgress(!1),this.config.system.asyncPopups&&await this.preGeneratePkceCodes(t)})}trackStateChangeWithMeasurement(e){const t=this.ssoSilentMeasurement||this.acquireTokenByCodeAsyncMeasurement;t&&(e.type==="visibilitychange"?(this.logger.info("Perf: Visibility change detected in ",t.event.name),t.increment({visibilityChangeCount:1})):e.type==="online"?(this.logger.info("Perf: Online status change detected in ",t.event.name),t.increment({onlineStatusChangeCount:1})):e.type==="offline"&&(this.logger.info("Perf: Offline status change detected in ",t.event.name),t.increment({onlineStatusChangeCount:1})))}addStateChangeListeners(e){document.addEventListener("visibilitychange",e),window.addEventListener("online",e),window.addEventListener("offline",e)}removeStateChangeListeners(e){document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e),window.removeEventListener("offline",e)}verifySsoCapability(e,t){if(!this.config.auth.verifySSO)return;const n=this.browserCrypto.createNewGuid(),o=this.performanceClient.startMeasurement(h.SsoCapable,n);o.add({parentApi:t}),this.logger.verbose(`SSO capability verification initiated after ${t}`,n),setTimeout(()=>{const r={account:e,correlationId:n};this.createSilentIframeClient(n).verifySso(r).then(a=>{this.logger.verbose(`SSO capability verification completed after ${t}, success: ${a}`,n),o.end({fromCache:!1,success:a},void 0,e)}).catch(a=>{this.logger.warning(`SSO capability verification failed after ${t}: ${a.message}`,n),o.end({fromCache:!1,success:!1},a,e)})},0)}async ssoSilent(e){const t=this.getRequestCorrelationId(e),n={...e,prompt:e.prompt,correlationId:t};this.ssoSilentMeasurement=this.performanceClient.startMeasurement(h.SsoSilent,t),this.ssoSilentMeasurement?.add({scenarioId:e.scenarioId}),Ct(this.initialized,this.ssoSilentMeasurement,e.account),this.ssoSilentMeasurement?.increment({visibilityChangeCount:0,onlineStatusChangeCount:0}),this.addStateChangeListeners(this.trackStateChangeWithMeasurement),this.logger.verbose("ssoSilent called",t),this.eventHandler.emitEvent(A.SSO_SILENT_START,T.Silent,n);let o;return this.canUsePlatformBroker(n)?(this.ssoSilentMeasurement?.add({isPlatformBrokerRequest:!0}),o=this.acquireTokenNative(n,S.ssoSilent).catch(r=>{if(this.ssoSilentMeasurement?.add({brokerErrorName:r.name,brokerErrorCode:r.errorCode}),r instanceof ie&&Le(r))return this.platformAuthProvider=void 0,this.createSilentIframeClient(n.correlationId).acquireToken(n);throw r})):o=this.createSilentIframeClient(n.correlationId).acquireToken(n),o.then(r=>(this.eventHandler.emitEvent(A.SSO_SILENT_SUCCESS,T.Silent,r),this.ssoSilentMeasurement?.end({success:!0,accessTokenSize:r.accessToken.length,idTokenSize:r.idToken.length},void 0,r.account),r)).catch(r=>{throw this.eventHandler.emitEvent(A.SSO_SILENT_FAILURE,T.Silent,null,r),this.ssoSilentMeasurement?.end({success:!1},r,e.account),r}).finally(()=>{this.removeStateChangeListeners(this.trackStateChangeWithMeasurement)})}async acquireTokenByCode(e){const t=this.getRequestCorrelationId(e);this.logger.trace("acquireTokenByCode called",t);const n=this.performanceClient.startMeasurement(h.AcquireTokenByCode,t);Ct(this.initialized,n),this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_BY_CODE_START,T.Silent,e),n.add({scenarioId:e.scenarioId});try{if(e.code&&e.nativeAccountId)throw y(Zi);if(e.code){const o=e.code;let r=this.hybridAuthCodeResponses.get(o);return r?(this.logger.verbose("Existing acquireTokenByCode request found",t),n.discard()):(this.logger.verbose("Initiating new acquireTokenByCode request",t),r=this.acquireTokenByCodeAsync({...e,correlationId:t}).then(s=>(this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_BY_CODE_SUCCESS,T.Silent,s),this.hybridAuthCodeResponses.delete(o),n.end({success:!0,accessTokenSize:s.accessToken.length,idTokenSize:s.idToken.length},void 0,s.account),s)).catch(s=>{throw this.hybridAuthCodeResponses.delete(o),this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_BY_CODE_FAILURE,T.Silent,null,s),n.end({success:!1},s),s}),this.hybridAuthCodeResponses.set(o,r)),await r}else if(e.nativeAccountId)if(this.canUsePlatformBroker(e,e.nativeAccountId)){n.add({isPlatformBrokerRequest:!0});const o=await this.acquireTokenNative({...e,correlationId:t},S.acquireTokenByCode,e.nativeAccountId).catch(r=>{throw r instanceof ie&&Le(r)&&(this.platformAuthProvider=void 0),n.add({brokerErrorName:r.name,brokerErrorCode:r.errorCode}),r});return n.end({success:!0},void 0,o.account),o}else throw y(es);else throw y(Xi)}catch(o){throw this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_BY_CODE_FAILURE,T.Silent,null,o),n.end({success:!1},o),o}}async acquireTokenByCodeAsync(e){return this.logger.trace("acquireTokenByCodeAsync called",e.correlationId),this.acquireTokenByCodeAsyncMeasurement=this.performanceClient.startMeasurement(h.AcquireTokenByCodeAsync,e.correlationId),this.acquireTokenByCodeAsyncMeasurement?.increment({visibilityChangeCount:0,onlineStatusChangeCount:0}),this.addStateChangeListeners(this.trackStateChangeWithMeasurement),await this.createSilentAuthCodeClient(e.correlationId).acquireToken(e).then(o=>(this.acquireTokenByCodeAsyncMeasurement?.end({success:!0,fromCache:o.fromCache}),o)).catch(o=>{throw this.acquireTokenByCodeAsyncMeasurement?.end({success:!1},o),o}).finally(()=>{this.removeStateChangeListeners(this.trackStateChangeWithMeasurement)})}async acquireTokenFromCache(e,t){switch(this.performanceClient.addQueueMeasurement(h.AcquireTokenFromCache,e.correlationId),t){case B.Default:case B.AccessToken:case B.AccessTokenAndRefreshToken:const n=this.createSilentCacheClient(e.correlationId);return g(n.acquireToken.bind(n),h.SilentCacheClientAcquireToken,this.logger,this.performanceClient,e.correlationId)(e);default:throw p(ye)}}async acquireTokenByRefreshToken(e,t){switch(this.performanceClient.addQueueMeasurement(h.AcquireTokenByRefreshToken,e.correlationId),t){case B.Default:case B.AccessTokenAndRefreshToken:case B.RefreshToken:case B.RefreshTokenAndNetwork:const n=this.createSilentRefreshClient(e.correlationId);return g(n.acquireToken.bind(n),h.SilentRefreshClientAcquireToken,this.logger,this.performanceClient,e.correlationId)(e);default:throw p(ye)}}async acquireTokenBySilentIframe(e){this.performanceClient.addQueueMeasurement(h.AcquireTokenBySilentIframe,e.correlationId);const t=this.createSilentIframeClient(e.correlationId);return g(t.acquireToken.bind(t),h.SilentIframeClientAcquireToken,this.logger,this.performanceClient,e.correlationId)(e)}async logout(e){const t=this.getRequestCorrelationId(e);return this.logger.warning("logout API is deprecated and will be removed in msal-browser v3.0.0. Use logoutRedirect instead.",t),this.logoutRedirect({correlationId:t,...e})}async logoutRedirect(e){const t=this.getRequestCorrelationId(e);return dr(this.initialized,this.config),this.browserStorage.setInteractionInProgress(!0,me.SIGNOUT),this.createRedirectClient(t).logout(e)}logoutPopup(e){try{const t=this.getRequestCorrelationId(e);return Ro(this.initialized),this.browserStorage.setInteractionInProgress(!0,me.SIGNOUT),this.createPopupClient(t).logout(e).finally(()=>{this.browserStorage.setInteractionInProgress(!1)})}catch(t){return Promise.reject(t)}}async clearCache(e){if(!this.isBrowserEnvironment){this.logger.info("in non-browser environment, returning early.");return}const t=this.getRequestCorrelationId(e);return this.createSilentCacheClient(t).logout(e)}getAllAccounts(e){const t=this.getRequestCorrelationId();return Dl(this.logger,this.browserStorage,this.isBrowserEnvironment,t,e)}getAccount(e){const t=this.getRequestCorrelationId();return Ll(e,this.logger,this.browserStorage,t)}getAccountByUsername(e){const t=this.getRequestCorrelationId();return Hl(e,this.logger,this.browserStorage,t)}getAccountByHomeId(e){const t=this.getRequestCorrelationId();return xl(e,this.logger,this.browserStorage,t)}getAccountByLocalId(e){const t=this.getRequestCorrelationId();return Fl(e,this.logger,this.browserStorage,t)}setActiveAccount(e){const t=this.getRequestCorrelationId();Kl(e,this.browserStorage,t)}getActiveAccount(){const e=this.getRequestCorrelationId();return Bl(this.browserStorage,e)}async hydrateCache(e,t){this.logger.verbose("hydrateCache called");const n=O.createFromAccountInfo(e.account,e.cloudGraphHostName,e.msGraphHost);return await this.browserStorage.setAccount(n,e.correlationId,ae(e.idTokenClaims),S.hydrateCache),e.fromNativeBroker?(this.logger.verbose("Response was from native broker, storing in-memory"),this.nativeInternalStorage.hydrateCache(e,t)):this.browserStorage.hydrateCache(e,t)}async acquireTokenNative(e,t,n,o){if(this.logger.trace("acquireTokenNative called"),!this.platformAuthProvider)throw y(yo);return new wt(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,t,this.performanceClient,this.platformAuthProvider,n||this.getNativeAccountId(e),this.nativeInternalStorage,e.correlationId).acquireToken(e,o)}canUsePlatformBroker(e,t){if(this.logger.trace("canUsePlatformBroker called"),!this.platformAuthProvider)return this.logger.trace("canUsePlatformBroker: platform broker unavilable, returning false"),!1;if(!ct(this.config,this.logger,this.platformAuthProvider,e.authenticationScheme))return this.logger.trace("canUsePlatformBroker: isBrokerAvailable returned false, returning false"),!1;if(e.prompt)switch(e.prompt){case U.NONE:case U.CONSENT:case U.LOGIN:case U.SELECT_ACCOUNT:this.logger.trace("canUsePlatformBroker: prompt is compatible with platform broker flow");break;default:return this.logger.trace(`canUsePlatformBroker: prompt = ${e.prompt} is not compatible with platform broker flow, returning false`),!1}return!t&&!this.getNativeAccountId(e)?(this.logger.trace("canUsePlatformBroker: nativeAccountId is not available, returning false"),!1):!0}getNativeAccountId(e){const t=e.account||this.getAccount({loginHint:e.loginHint,sid:e.sid})||this.getActiveAccount();return t&&t.nativeAccountId||""}createPopupClient(e){return new lh(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,this.platformAuthProvider,e)}createRedirectClient(e){return new dh(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.nativeInternalStorage,this.platformAuthProvider,e)}createSilentIframeClient(e){return new Ch(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,S.ssoSilent,this.performanceClient,this.nativeInternalStorage,this.platformAuthProvider,e)}createSilentCacheClient(e){return new Rs(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.platformAuthProvider,e)}createSilentRefreshClient(e){return new yh(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,this.performanceClient,this.platformAuthProvider,e)}createSilentAuthCodeClient(e){return new Ih(this.config,this.browserStorage,this.browserCrypto,this.logger,this.eventHandler,this.navigationClient,S.acquireTokenByCode,this.performanceClient,this.platformAuthProvider,e)}addEventCallback(e,t){return this.eventHandler.addEventCallback(e,t)}removeEventCallback(e){this.eventHandler.removeEventCallback(e)}addPerformanceCallback(e){return ys(),this.performanceClient.addPerformanceCallback(e)}removePerformanceCallback(e){return this.performanceClient.removePerformanceCallback(e)}enableAccountStorageEvents(){if(this.config.cache.cacheLocation!==x.LocalStorage){this.logger.info("Account storage events are only available when cacheLocation is set to localStorage");return}this.eventHandler.subscribeCrossTab()}disableAccountStorageEvents(){if(this.config.cache.cacheLocation!==x.LocalStorage){this.logger.info("Account storage events are only available when cacheLocation is set to localStorage");return}this.eventHandler.unsubscribeCrossTab()}getTokenCache(){return this.tokenCache}getLogger(){return this.logger}setLogger(e){this.logger=e}initializeWrapperLibrary(e,t){this.browserStorage.setWrapperMetadata(e,t)}setNavigationClient(e){this.navigationClient=e}getConfiguration(){return this.config}getPerformanceClient(){return this.performanceClient}isBrowserEnv(){return this.isBrowserEnvironment}getRequestCorrelationId(e){return e?.correlationId?e.correlationId:this.isBrowserEnvironment?ce():f.EMPTY_STRING}async loginRedirect(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("loginRedirect called",t),this.acquireTokenRedirect({correlationId:t,...e||sr})}loginPopup(e){const t=this.getRequestCorrelationId(e);return this.logger.verbose("loginPopup called",t),this.acquireTokenPopup({correlationId:t,...e||sr})}async acquireTokenSilent(e){const t=this.getRequestCorrelationId(e),n=this.performanceClient.startMeasurement(h.AcquireTokenSilent,t);n.add({cacheLookupPolicy:e.cacheLookupPolicy,scenarioId:e.scenarioId}),Ct(this.initialized,n,e.account),this.logger.verbose("acquireTokenSilent called",t);const o=e.account||this.getActiveAccount();if(!o)throw y($i);return this.acquireTokenSilentDeduped(e,o,t).then(r=>(n.end({success:!0,fromCache:r.fromCache,accessTokenSize:r.accessToken.length,idTokenSize:r.idToken.length},void 0,r.account),{...r,state:e.state,correlationId:t})).catch(r=>{throw r instanceof R&&r.setCorrelationId(t),n.end({success:!1},r,o),r})}async acquireTokenSilentDeduped(e,t,n){const o=Yt(this.config.auth.clientId,{...e,authority:e.authority||this.config.auth.authority},t.homeAccountId),r=JSON.stringify(o),s=this.activeSilentTokenRequests.get(r);if(typeof s>"u"){this.logger.verbose("acquireTokenSilent called for the first time, storing active request",n),this.performanceClient.addFields({deduped:!1},n);const a=g(this.acquireTokenSilentAsync.bind(this),h.AcquireTokenSilentAsync,this.logger,this.performanceClient,n)({...e,correlationId:n},t);return this.activeSilentTokenRequests.set(r,a),a.finally(()=>{this.activeSilentTokenRequests.delete(r)})}else return this.logger.verbose("acquireTokenSilent has been called previously, returning the result from the first call",n),this.performanceClient.addFields({deduped:!0},n),s}async acquireTokenSilentAsync(e,t){const n=a=>this.trackStateChange(e.correlationId,a);this.performanceClient.addQueueMeasurement(h.AcquireTokenSilentAsync,e.correlationId),this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_START,T.Silent,e),e.correlationId&&this.performanceClient.incrementFields({visibilityChangeCount:0,onlineStatusChangeCount:0},e.correlationId),this.addStateChangeListeners(n);const o=await g(ql,h.InitializeSilentRequest,this.logger,this.performanceClient,e.correlationId)(e,t,this.config,this.performanceClient,this.logger),r=e.cacheLookupPolicy||B.Default;return this.acquireTokenSilentNoIframe(o,r).catch(async a=>{if(Eh(a,r)){const l=`${a.errorCode}${a.subError?`|${a.subError}`:""}`;if(this.performanceClient.addFields({silentRefreshReason:l},o.correlationId),this.activeIframeRequest)if(r!==B.Skip){const[d,u]=this.activeIframeRequest;this.logger.verbose(`Iframe request is already in progress, awaiting resolution for request with correlationId: ${u}`,o.correlationId);const m=this.performanceClient.startMeasurement(h.AwaitConcurrentIframe,o.correlationId);m.add({awaitIframeCorrelationId:u});const C=await d;if(m.end({success:C}),C)return this.logger.verbose(`Parallel iframe request with correlationId: ${u} succeeded. Retrying cache and/or RT redemption`,o.correlationId),this.acquireTokenSilentNoIframe(o,r);throw this.logger.info(`Iframe request with correlationId: ${u} failed. Interaction is required.`),a}else return this.logger.warning("Another iframe request is currently in progress and CacheLookupPolicy is set to Skip. This may result in degraded performance and/or reliability for both calls. Please consider changing the CacheLookupPolicy to take advantage of request queuing and token cache.",o.correlationId),g(this.acquireTokenBySilentIframe.bind(this),h.AcquireTokenBySilentIframe,this.logger,this.performanceClient,o.correlationId)(o);else{let d;return this.activeIframeRequest=[new Promise(u=>{d=u}),o.correlationId],this.logger.verbose("Refresh token expired/invalid or CacheLookupPolicy is set to Skip, attempting acquire token by iframe.",o.correlationId),g(this.acquireTokenBySilentIframe.bind(this),h.AcquireTokenBySilentIframe,this.logger,this.performanceClient,o.correlationId)(o).then(u=>(d(!0),u)).catch(u=>{throw d(!1),u}).finally(()=>{this.activeIframeRequest=void 0})}}else throw a}).then(a=>(this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_SUCCESS,T.Silent,a),this.performanceClient.addFields({fromCache:a.fromCache},e.correlationId),a)).catch(a=>{throw this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_FAILURE,T.Silent,null,a),a}).finally(()=>{this.removeStateChangeListeners(n)})}async acquireTokenSilentNoIframe(e,t){return ct(this.config,this.logger,this.platformAuthProvider,e.authenticationScheme)&&e.account.nativeAccountId?(this.logger.verbose("acquireTokenSilent - attempting to acquire token from native platform"),this.performanceClient.addFields({isPlatformBrokerRequest:!0},e.correlationId),this.acquireTokenNative(e,S.acquireTokenSilent_silentFlow,e.account.nativeAccountId,t).catch(async n=>{throw this.performanceClient.addFields({brokerErrorName:n.name,brokerErrorCode:n.errorCode},e.correlationId),n instanceof ie&&Le(n)?(this.logger.verbose("acquireTokenSilent - native platform unavailable, falling back to web flow"),this.platformAuthProvider=void 0,p(ye)):n})):(this.logger.verbose("acquireTokenSilent - attempting to acquire token from web flow"),t===B.AccessToken&&this.logger.verbose("acquireTokenSilent - cache lookup policy set to AccessToken, attempting to acquire token from local cache"),g(this.acquireTokenFromCache.bind(this),h.AcquireTokenFromCache,this.logger,this.performanceClient,e.correlationId)(e,t).catch(n=>{if(t===B.AccessToken)throw n;return this.eventHandler.emitEvent(A.ACQUIRE_TOKEN_NETWORK_START,T.Silent,e),g(this.acquireTokenByRefreshToken.bind(this),h.AcquireTokenByRefreshToken,this.logger,this.performanceClient,e.correlationId)(e,t)}))}async preGeneratePkceCodes(e){return this.logger.verbose("Generating new PKCE codes"),this.pkceCode=await g(Ie,h.GeneratePkceCodes,this.logger,this.performanceClient,e)(this.performanceClient,this.logger,e),Promise.resolve()}getPreGeneratedPkceCodes(e){this.logger.verbose("Attempting to pick up pre-generated PKCE codes");const t=this.pkceCode?{...this.pkceCode}:void 0;return this.pkceCode=void 0,this.logger.verbose(`${t?"Found":"Did not find"} pre-generated PKCE codes`),this.performanceClient.addFields({usePreGeneratedPkce:!!t},e),t}logMultipleInstances(e){const t=this.config.auth.clientId;if(!window)return;window.msal=window.msal||{},window.msal.clientIds=window.msal.clientIds||[],window.msal.clientIds.length>0&&this.logger.verbose("There is already an instance of MSAL.js in the window."),window.msal.clientIds.push(t),wh(t,e,this.logger)}}function Eh(i,e){const t=!(i instanceof oe&&i.subError!==Xt),n=i.errorCode===Q.INVALID_GRANT_ERROR||i.errorCode===ye,o=t&&n||i.errorCode===Ut||i.errorCode===io,r=Zc.includes(e);return o&&r}async function Sh(i,e){const t=new Ne(i);return await t.initialize(),sn.createController(t,e)}class Ns{static async createPublicClientApplication(e){const t=await Sh(e);return new Ns(e,t)}constructor(e,t){this.isBroker=!1,this.controller=t||new sn(new Ne(e))}async initialize(e){return this.controller.initialize(e,this.isBroker)}async acquireTokenPopup(e){return this.controller.acquireTokenPopup(e)}acquireTokenRedirect(e){return this.controller.acquireTokenRedirect(e)}acquireTokenSilent(e){return this.controller.acquireTokenSilent(e)}acquireTokenByCode(e){return this.controller.acquireTokenByCode(e)}addEventCallback(e,t){return this.controller.addEventCallback(e,t)}removeEventCallback(e){return this.controller.removeEventCallback(e)}addPerformanceCallback(e){return this.controller.addPerformanceCallback(e)}removePerformanceCallback(e){return this.controller.removePerformanceCallback(e)}enableAccountStorageEvents(){this.controller.enableAccountStorageEvents()}disableAccountStorageEvents(){this.controller.disableAccountStorageEvents()}getAccount(e){return this.controller.getAccount(e)}getAccountByHomeId(e){return this.controller.getAccountByHomeId(e)}getAccountByLocalId(e){return this.controller.getAccountByLocalId(e)}getAccountByUsername(e){return this.controller.getAccountByUsername(e)}getAllAccounts(e){return this.controller.getAllAccounts(e)}handleRedirectPromise(e){return this.controller.handleRedirectPromise(e)}loginPopup(e){return this.controller.loginPopup(e)}loginRedirect(e){return this.controller.loginRedirect(e)}logout(e){return this.controller.logout(e)}logoutRedirect(e){return this.controller.logoutRedirect(e)}logoutPopup(e){return this.controller.logoutPopup(e)}ssoSilent(e){return this.controller.ssoSilent(e)}getTokenCache(){return this.controller.getTokenCache()}getLogger(){return this.controller.getLogger()}setLogger(e){this.controller.setLogger(e)}setActiveAccount(e){this.controller.setActiveAccount(e)}getActiveAccount(){return this.controller.getActiveAccount()}initializeWrapperLibrary(e,t){return this.controller.initializeWrapperLibrary(e,t)}setNavigationClient(e){this.controller.setNavigationClient(e)}getConfiguration(){return this.controller.getConfiguration()}async hydrateCache(e,t){return this.controller.hydrateCache(e,t)}clearCache(e){return this.controller.clearCache(e)}}export{Ns as P};