@merit-systems/echo-react-sdk 1.0.4 → 1.0.6

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.
@@ -1,4 +1,4 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react/jsx-runtime"),require("react")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).EchoReactSDK={},e.jsxRuntime,e.React)}(this,(function(e,t,r){"use strict";var n,s=Object.defineProperty,i=(e,t,r)=>((e,t,r)=>t in e?s(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class o extends Error{}function a(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(t)}catch(r){return atob(t)}}o.prototype.name="InvalidTokenError";var c,l,d,u={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},h=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(h||{});(d=h||(h={})).reset=function(){c=3,l=u},d.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");c=e},d.setLogger=function(e){l=e};var p=class e{constructor(e){this._name=e}debug(...t){c>=4&&l.debug(e._format(this._name,this._method),...t)}info(...t){c>=3&&l.info(e._format(this._name,this._method),...t)}warn(...t){c>=2&&l.warn(e._format(this._name,this._method),...t)}error(...t){c>=1&&l.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,r){const n=new e(`${t}.${r}`);return n.debug("begin"),n}static _format(e,t){const r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(t,...r){c>=4&&l.debug(e._format(t),...r)}static info(t,...r){c>=3&&l.info(e._format(t),...r)}static warn(t,...r){c>=2&&l.warn(e._format(t),...r)}static error(t,...r){c>=1&&l.error(e._format(t),...r)}};h.reset();var g=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new o("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new o(`Invalid token specified: missing part #${r+1}`);let s;try{s=a(n)}catch(i){throw new o(`Invalid token specified: invalid base64 for part #${r+1} (${i.message})`)}try{return JSON.parse(s)}catch(i){throw new o(`Invalid token specified: invalid json for part #${r+1} (${i.message})`)}}(e)}catch(t){throw p.error("JwtUtils.decode",t),t}}static async generateSignedJwt(e,t,r){const n=`${_.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${_.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,(new TextEncoder).encode(n));return`${n}.${_.encodeBase64Url(new Uint8Array(s))}`}},f=e=>btoa([...new Uint8Array(e)].map((e=>String.fromCharCode(e))).join("")),m=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(+t^e._randomWord()&15>>+t/4).toString(16))).replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return f(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw p.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const r=(new TextEncoder).encode([e,t].join(":"));return f(r)}static async hash(e,t){const r=(new TextEncoder).encode(t),n=await crypto.subtle.digest(e,r);return new Uint8Array(n)}static async customCalculateJwkThumbprint(t){let r;switch(t.kty){case"RSA":r={e:t.e,kty:t.kty,n:t.n};break;case"EC":r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":r={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":r={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const n=await e.hash("SHA-256",JSON.stringify(r));return e.encodeBase64Url(n)}static async generateDPoPProof({url:t,accessToken:r,httpMethod:n,keyPair:s,nonce:i}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=n?n:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};r&&(o=await e.hash("SHA-256",r),a=e.encodeBase64Url(o),c.ath=a),i&&(c.nonce=i);try{const e=await crypto.subtle.exportKey("jwk",s.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await g.generateSignedJwt(t,c,s.privateKey)}catch(l){throw l instanceof TypeError?new Error(`Error exporting dpop public key: ${l.message}`):l}}static async generateDPoPJkt(t){try{const r=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(r)}catch(r){throw r instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${r.message}`):r}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};m.encodeBase64Url=e=>f(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var _=m,w=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new p(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},y=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find((e=>e<=window.outerWidth/1.618)))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter((([,e])=>null!=e)).map((([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`)).join(",")}},b=class e extends w{constructor(){super(...arguments),this._logger=new p(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const r=this._logger.create("init");t=Math.max(Math.floor(t),1);const n=e.getEpochTime()+t;if(this.expiration===n&&this._timerHandle)return void r.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),r.debug("using duration",t),this._expiration=n;const s=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*s)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},S=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const r=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(r.slice(1))}},v=";",E=class extends Error{constructor(e,t){var r,n,s;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw p.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(r=e.error_description)?r:null,this.error_uri=null!=(n=e.error_uri)?n:null,this.state=e.userState,this.session_state=null!=(s=e.session_state)?s:null,this.url_state=e.url_state}},k=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},x=class{constructor(e){this._logger=new p("AccessTokenEvents"),this._expiringTimer=new b("Access token expiring"),this._expiredTimer=new b("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const r=e.expires_in;if(t.debug("access token present, remaining duration:",r),r>0){let e=r-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const n=r+1;t.debug("registering expired timer, raising in",n,"seconds"),this._expiredTimer.init(n)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},T=class{constructor(e,t,r,n,s){this._callback=e,this._client_id=t,this._intervalInSeconds=n,this._stopOnError=s,this._logger=new p("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const i=new URL(r);this._frame_origin=i.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=i.href}load(){return new Promise((e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)}))}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},R=class{constructor(){this._logger=new p("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},C=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},A=class{constructor(e=[],t=null,r={}){this._jwtHandler=t,this._extraHeaders=r,this._logger=new p("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:r,...n}=t;if(!r)return await fetch(e,n);const s=new AbortController,i=setTimeout((()=>s.abort()),1e3*r);try{return await fetch(e,{...t,signal:s.signal})}catch(o){if(o instanceof DOMException&&"AbortError"===o.name)throw new k("Network timed out");throw o}finally{clearTimeout(i)}}async getJson(e,{token:t,credentials:r,timeoutInSeconds:n}={}){const s=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let o;t&&(s.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this._appendExtraHeaders(i);try{s.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:i,timeoutInSeconds:n,credentials:r})}catch(l){throw s.error("Network Error"),l}s.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find((e=>a.startsWith(e)))&&s.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(l){if(s.error("Error parsing JSON response",l),o.ok)throw l;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(s.error("Error from server:",c),c.error)throw new E(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:n,initCredentials:s,extraHeaders:i}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...i};let c;void 0!==r&&(a.Authorization="Basic "+r),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:n,credentials:s})}catch(h){throw o.error("Network error"),h}o.debug("HTTP response received, status",c.status);const l=c.headers.get("Content-Type");if(l&&!this._contentTypes.find((e=>l.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=l?l:"undefined"}, from URL: ${e}`);const d=await c.text();let u={};if(d)try{u=JSON.parse(d)}catch(h){if(o.error("Error parsing JSON response",h),c.ok)throw h;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",u),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new C(e,`${JSON.stringify(u)}`)}if(u.error)throw new E(u,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(u)}`)}return u}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),r=Object.keys(this._extraHeaders),n=["accept","content-type"],s=["authorization"];0!==r.length&&r.forEach((r=>{if(n.includes(r.toLocaleLowerCase()))return void t.warn("Protected header could not be set",r,n);if(s.includes(r.toLocaleLowerCase())&&Object.keys(e).includes(r))return void t.warn("Header could not be overridden",r,s);const i="function"==typeof this._extraHeaders[r]?this._extraHeaders[r]():this._extraHeaders[r];i&&""!==i&&(e[r]=i)}))}},O=class{constructor(e){this._settings=e,this._logger=new p("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new A(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const r=this._logger.create(`_getMetadataProperty('${e}')`),n=await this.getMetadata();if(r.debug("resolved"),void 0===n[e]){if(!0===t)return void r.warn("Metadata does not contain optional property");r.throw(new Error("Metadata does not contain property "+e))}return n[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const r=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",r),!Array.isArray(r.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=r.keys,this._signingKeys}},N=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new p("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;return await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let r=0;r<e;r++){const e=await this._store.key(r);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},I=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:n,metadataSeed:s,client_id:i,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:l,post_logout_redirect_uri:d,client_authentication:u="client_secret_post",prompt:h,display:p,max_age:g,ui_locales:f,acr_values:m,resource:_,response_mode:w,filterProtocolClaims:y=!0,loadUserInfo:b=!1,requestTimeoutInSeconds:S,staleStateAgeInSeconds:v=900,mergeClaimsStrategy:E={array:"replace"},disablePKCE:k=!1,stateStore:x,revokeTokenAdditionalContentTypes:T,fetchRequestCredentials:C,refreshTokenAllowedScope:A,extraQueryParams:O={},extraTokenParams:I={},extraHeaders:P={},dpop:U,omitScopeWhenRequesting:j=!1}){var L;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=r,this.metadataSeed=s,this.signingKeys=n,this.client_id=i,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=d,this.client_authentication=u,this.prompt=h,this.display=p,this.max_age=g,this.ui_locales=f,this.acr_values=m,this.resource=_,this.response_mode=w,this.filterProtocolClaims=null==y||y,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=v,this.mergeClaimsStrategy=E,this.omitScopeWhenRequesting=j,this.disablePKCE=!!k,this.revokeTokenAdditionalContentTypes=T,this.fetchRequestCredentials=C||"same-origin",this.requestTimeoutInSeconds=S,x)this.stateStore=x;else{const e="undefined"!=typeof window?window.localStorage:new R;this.stateStore=new N({store:e})}if(this.refreshTokenAllowedScope=A,this.extraQueryParams=O,this.extraTokenParams=I,this.extraHeaders=P,this.dpop=U,this.dpop&&!(null==(L=this.dpop)?void 0:L.store))throw new Error("A DPoPStore is required when dpop is enabled")}},P=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new p("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const r=g.decode(e);return t.debug("JWT decoding successful"),r}catch(r){throw t.error("Error parsing JWT response"),r}},this._jsonService=new A(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);const n=await this._jsonService.getJson(r,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",n),n}},U=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new p("TokenClient"),this._jsonService=new A(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:r=this._settings.client_id,client_secret:n=this._settings.client_secret,extraHeaders:s,...i}){const o=this._logger.create("exchangeCode");r||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),i.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[u,h]of Object.entries(i))null!=h&&a.set(u,h);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw o.throw(new Error("A client_secret is required")),null;c=_.generateBasicAuth(r,n);break;case"client_secret_post":a.append("client_id",r),n&&a.append("client_secret",n)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),d}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,scope:n=this._settings.scope,...s}){const i=this._logger.create("exchangeCredentials");t||i.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",n);for(const[d,u]of Object.entries(s))null!=u&&o.set(d,u);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw i.throw(new Error("A client_secret is required")),null;a=_.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r)}const c=await this._metadataService.getTokenEndpoint(!1);i.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return i.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,timeoutInSeconds:n,extraHeaders:s,...i}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),i.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[u,h]of Object.entries(i))Array.isArray(h)?h.forEach((e=>a.append(u,e))):null!=h&&a.set(u,h);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw o.throw(new Error("A client_secret is required")),null;c=_.generateBasicAuth(t,r);break;case"client_secret_post":a.append("client_id",t),r&&a.append("client_secret",r)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const d=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:n,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),d}async revoke(e){var t;const r=this._logger.create("revoke");e.token||r.throw(new Error("A token is required"));const n=await this._metadataService.getRevocationEndpoint(!1);r.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const s=new URLSearchParams;for(const[i,o]of Object.entries(e))null!=o&&s.set(i,o);s.set("client_id",this._settings.client_id),this._settings.client_secret&&s.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(n,{body:s,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),r.debug("got response")}},j=class{constructor(e,t,r){this._settings=e,this._metadataService=t,this._claimsService=r,this._logger=new p("ResponseValidator"),this._userInfoService=new P(this._settings,this._metadataService),this._tokenClient=new U(this._settings,this._metadataService)}async validateSigninResponse(e,t,r){const n=this._logger.create("validateSigninResponse");this._processSigninState(e,t),n.debug("state processed"),await this._processCode(e,t,r),n.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(e,t){const r=this._logger.create("validateCredentialsResponse"),n=e.isOpenId&&!!e.id_token;n&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t,n),r.debug("claims processed")}async validateRefreshResponse(e,t){const r=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),r.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const n=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,n),r.debug("claims processed")}validateSignoutResponse(e,t){const r=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&r.throw(new Error("State does not match")),r.debug("state validated"),e.userState=t.data,e.error)throw r.warn("Response was error",e.error),new E(e)}_processSigninState(e,t){const r=this._logger.create("_processSigninState");if(t.id!==e.state&&r.throw(new Error("State does not match")),t.client_id||r.throw(new Error("No client_id on state")),t.authority||r.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new E(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,r=!0){const n=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void n.debug("not loading user info");n.debug("loading user info");const s=await this._userInfoService.getClaims(e.access_token);n.debug("user info claims received from user info endpoint"),r&&s.sub!==e.profile.sub&&n.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(s)),n.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,r){const n=this._logger.create("_processCode");if(e.code){n.debug("Validating code");const s=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:r,...t.extraTokenParams});Object.assign(e,s)}else n.debug("No code to process")}_validateIdTokenAttributes(e,t){var r;const n=this._logger.create("_validateIdTokenAttributes");n.debug("decoding ID Token JWT");const s=g.decode(null!=(r=e.id_token)?r:"");if(s.sub||n.throw(new Error("ID Token is missing a subject claim")),t){const e=g.decode(t);s.sub!==e.sub&&n.throw(new Error("sub in id_token does not match current sub")),s.auth_time&&s.auth_time!==e.auth_time&&n.throw(new Error("auth_time in id_token does not match original auth_time")),s.azp&&s.azp!==e.azp&&n.throw(new Error("azp in id_token does not match original azp")),!s.azp&&e.azp&&n.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=s}},L=class e{constructor(e){this.id=e.id||_.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=b.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new p("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return p.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,r){const n=p.createStatic("State","clearStaleState"),s=b.getEpochTime()-r,i=await t.getAllKeys();n.debug("got keys",i);for(let a=0;a<i.length;a++){const r=i[a],c=await t.get(r);let l=!1;if(c)try{const t=await e.fromStorageString(c);n.debug("got item from key:",r,t.created),t.created<=s&&(l=!0)}catch(o){n.error("Error parsing state for key:",r,o),l=!0}else n.debug("no item in storage for key:",r),l=!0;l&&(n.debug("removed item for key:",r),t.remove(r))}}},D=class e extends L{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const r=!0===t.code_verifier?_.generateCodeVerifier():t.code_verifier||void 0,n=r?await _.generateCodeChallenge(r):void 0;return new e({...t,code_verifier:r,code_challenge:n})}toStorageString(){return new p("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){p.createStatic("SigninState","fromStorageString");const r=JSON.parse(t);return e.create(r)}},M=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:r,client_id:n,redirect_uri:s,response_type:i,scope:o,state_data:a,response_mode:c,request_type:l,client_secret:d,nonce:u,url_state:h,resource:p,skipUserInfo:g,extraQueryParams:f,extraTokenParams:m,disablePKCE:_,dpopJkt:w,omitScopeWhenRequesting:y,...b}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!n)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!s)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!i)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!r)throw this._logger.error("create: No authority passed"),new Error("authority");const S=await D.create({data:a,request_type:l,url_state:h,code_verifier:!_,client_id:n,authority:r,redirect_uri:s,response_mode:c,client_secret:d,scope:o,extraTokenParams:m,skipUserInfo:g}),E=new URL(t);E.searchParams.append("client_id",n),E.searchParams.append("redirect_uri",s),E.searchParams.append("response_type",i),y||E.searchParams.append("scope",o),u&&E.searchParams.append("nonce",u),w&&E.searchParams.append("dpop_jkt",w);let k=S.id;if(h&&(k=`${k}${v}${h}`),E.searchParams.append("state",k),S.code_challenge&&(E.searchParams.append("code_challenge",S.code_challenge),E.searchParams.append("code_challenge_method","S256")),p){(Array.isArray(p)?p:[p]).forEach((e=>E.searchParams.append("resource",e)))}for(const[e,v]of Object.entries({response_mode:c,...b,...f}))null!=v&&E.searchParams.append(e,v.toString());return new e({url:E.href,state:S})}};M._logger=new p("SigninRequest");var F=M,q=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(v);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(v))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-b.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+b.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},H=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:n,extraQueryParams:s,request_type:i,client_id:o,url_state:a}){if(this._logger=new p("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(r&&c.searchParams.append("id_token_hint",r),o&&c.searchParams.append("client_id",o),n&&(c.searchParams.append("post_logout_redirect_uri",n),t||a)){this.state=new L({data:t,request_type:i,url_state:a});let e=this.state.id;a&&(e=`${e}${v}${a}`),c.searchParams.append("state",e)}for(const[l,d]of Object.entries({...s}))null!=d&&c.searchParams.append(l,d.toString());this.url=c.href}},z=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(v);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(v))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},B=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],W=["sub","iss","aud","exp","iat"],$=class{constructor(e){this._settings=e,this._logger=new p("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:B;for(const r of e)W.includes(r)||delete t[r]}return t}mergeClaims(e,t){const r={...e};for(const[n,s]of Object.entries(t))if(r[n]!==s)if(Array.isArray(r[n])||Array.isArray(s))if("replace"==this._settings.mergeClaimsStrategy.array)r[n]=s;else{const e=Array.isArray(r[n])?r[n]:[r[n]];for(const t of Array.isArray(s)?s:[s])e.includes(t)||e.push(t);r[n]=e}else"object"==typeof r[n]&&"object"==typeof s?r[n]=this.mergeClaims(r[n],s):r[n]=s;return r}},K=class{constructor(e,t){this.keys=e,this.nonce=t}},J=class{constructor(e,t){this._logger=new p("OidcClient"),this.settings=e instanceof I?e:new I(e),this.metadataService=null!=t?t:new O(this.settings),this._claimsService=new $(this.settings),this._validator=new j(this.settings,this.metadataService,this._claimsService),this._tokenClient=new U(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:n,id_token_hint:s,login_hint:i,skipUserInfo:o,nonce:a,url_state:c,response_type:l=this.settings.response_type,scope:d=this.settings.scope,redirect_uri:u=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:p=this.settings.display,max_age:g=this.settings.max_age,ui_locales:f=this.settings.ui_locales,acr_values:m=this.settings.acr_values,resource:_=this.settings.resource,response_mode:w=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams,dpopJkt:S,omitScopeWhenRequesting:v=this.settings.omitScopeWhenRequesting}){const E=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const k=await this.metadataService.getAuthorizationEndpoint();E.debug("Received authorization endpoint",k);const x=await F.create({url:k,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:u,response_type:l,scope:d,state_data:e,url_state:c,prompt:h,display:p,max_age:g,ui_locales:f,id_token_hint:s,login_hint:i,acr_values:m,dpopJkt:S,resource:_,request:t,request_uri:r,extraQueryParams:y,extraTokenParams:b,request_type:n,response_mode:w,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:v});await this.clearStaleState();const T=x.state;return await this.settings.stateStore.set(T.id,T.toStorageString()),x}async readSigninResponseState(e,t=!1){const r=this._logger.create("readSigninResponseState"),n=new q(S.readParams(e,this.settings.response_mode));if(!n.state)throw r.throw(new Error("No state in response")),null;const s=await this.settings.stateStore[t?"remove":"get"](n.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await D.fromStorageString(s),response:n}}async processSigninResponse(e,t,r=!0){const n=this._logger.create("processSigninResponse"),{state:s,response:i}=await this.readSigninResponseState(e,r);if(n.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(i,s,t)}catch(o){if(!(o instanceof C&&this.settings.dpop))throw o;{const e=await this.getDpopProof(this.settings.dpop.store,o.nonce);t.DPoP=e,await this._validator.validateSigninResponse(i,s,t)}}return i}async getDpopProof(e,t){let r,n;return(await e.getAllKeys()).includes(this.settings.client_id)?(n=await e.get(this.settings.client_id),n.nonce!==t&&t&&(n.nonce=t,await e.set(this.settings.client_id,n))):(r=await _.generateDPoPKeys(),n=new K(r,t),await e.set(this.settings.client_id,n)),await _.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:n.keys,nonce:n.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r=!1,extraTokenParams:n={}}){const s=await this._tokenClient.exchangeCredentials({username:e,password:t,...n}),i=new q(new URLSearchParams);return Object.assign(i,s),await this._validator.validateCredentialsResponse(i,r),i}async useRefreshToken({state:e,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,extraTokenParams:i}){var o;const a=this._logger.create("useRefreshToken");let c,l;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);s={...s,DPoP:e}}try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,...i})}catch(u){if(!(u instanceof C&&this.settings.dpop))throw u;s.DPoP=await this.getDpopProof(this.settings.dpop.store,u.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,...i})}const d=new q(new URLSearchParams);return Object.assign(d,l),a.debug("validating response",d),await this._validator.validateRefreshResponse(d,{...e,scope:c}),d}async createSignoutRequest({state:e,id_token_hint:t,client_id:r,request_type:n,url_state:s,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),r||!i||t||(r=this.settings.client_id);const l=new H({url:c,id_token_hint:t,client_id:r,post_logout_redirect_uri:i,state_data:e,extraQueryParams:o,request_type:n,url_state:s});await this.clearStaleState();const d=l.state;return d&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(d.id,d.toStorageString())),l}async readSignoutResponseState(e,t=!1){const r=this._logger.create("readSignoutResponseState"),n=new z(S.readParams(e,this.settings.response_mode));if(!n.state){if(r.debug("No state in response"),n.error)throw r.warn("Response was error:",n.error),new E(n);return{state:void 0,response:n}}const s=await this.settings.stateStore[t?"remove":"get"](n.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await L.fromStorageString(s),response:n}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:r,response:n}=await this.readSignoutResponseState(e,!0);return r?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(n,r)):t.debug("No state from storage; skipping response validation"),n}clearStaleState(){return this._logger.create("clearStaleState"),L.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},G=class{constructor(e){this._userManager=e,this._logger=new p("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const r=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,r.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,r.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){r.debug("initializing check session iframe");const n=this._userManager.settings.client_id,s=this._userManager.settings.checkSessionIntervalInSeconds,i=this._userManager.settings.stopCheckSessionOnError,o=new T(this._callback,n,e,s,i);await o.load(),this._checkSessionIFrame=o,o.start(t)}else r.warn("no check session iframe found in the metadata")}catch(n){r.error("Error from getCheckSessionIframe:",n instanceof Error?n.message:n)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval((async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(r){e.error("error from querySessionStatus",r instanceof Error?r.message:r)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let r=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(r=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),r?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch((e=>{this._logger.error(e)}))}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},V=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-b.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+b.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new p("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return p.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},Y="oidc-client",X=class{constructor(){this._abort=new w("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:r,keepOpen:n}=await new Promise(((r,n)=>{const s=s=>{var i;const o=s.data,a=null!=(i=e.scriptOrigin)?i:window.location.origin;if(s.origin===a&&(null==o?void 0:o.source)===Y){try{const r=S.readParams(o.url,e.response_mode).get("state");if(r||t.warn("no state found in response url"),s.source!==this._window&&r!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}r(o)}};window.addEventListener("message",s,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",s,!1)));const i=new BroadcastChannel(`oidc-client-popup-${e.state}`);i.addEventListener("message",s,!1),this._disposeHandlers.add((()=>i.close())),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),n(e)})))}));return t.debug("got response from window"),this._dispose(),n||this.close(),{url:r}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,r=!1,n=window.location.origin){const s={source:Y,url:t,keepOpen:r},i=new p("_notifyParent");if(e)i.debug("With parent. Using parent.postMessage."),e.postMessage(s,n);else{i.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const r=new BroadcastChannel(`oidc-client-popup-${e}`);r.postMessage(s),r.close()}}},Q={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Z="_blank",ee=60,te=2,re=class extends I{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:r=e.post_logout_redirect_uri,popupWindowFeatures:n=Q,popupWindowTarget:s=Z,redirectMethod:i="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:d=e.redirect_uri,silentRequestTimeoutInSeconds:u,automaticSilentRenew:h=!0,validateSubOnSilentRenew:p=!0,includeIdTokenInSilentRenew:g=!1,monitorSession:f=!1,monitorAnonymousSession:m=!1,checkSessionIntervalInSeconds:_=te,query_status_response_type:w="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:b=["access_token","refresh_token"],revokeTokensOnSignout:S=!1,includeIdTokenInSilentSignout:v=!1,accessTokenExpiringNotificationTimeInSeconds:E=ee,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=r,this.popupWindowFeatures=n,this.popupWindowTarget=s,this.redirectMethod=i,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=d,this.silentRequestTimeoutInSeconds=u||l||10,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=p,this.includeIdTokenInSilentRenew=g,this.monitorSession=f,this.monitorAnonymousSession=m,this.checkSessionIntervalInSeconds=_,this.stopCheckSessionOnError=y,this.query_status_response_type=w,this.revokeTokenTypes=b,this.revokeTokensOnSignout=S,this.includeIdTokenInSilentSignout=v,this.accessTokenExpiringNotificationTimeInSeconds=E,k)this.userStore=k;else{const e="undefined"!=typeof window?window.sessionStorage:new R;this.userStore=new N({store:e})}}},ne=class e extends X{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new p("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout((()=>{this._abort.raise(new k("IFrame timed out without a response"))}),1e3*this._timeoutInSeconds);return this._disposeHandlers.add((()=>clearTimeout(t))),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",(e=>{var t;const r=e.target;null==(t=r.parentNode)||t.removeChild(r),this._abort.raise(new Error("IFrame removed from DOM"))}),!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},se=class{constructor(e){this._settings=e,this._logger=new p("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new ne({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),ne.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},ie=class extends X{constructor({popupWindowTarget:e=Z,popupWindowFeatures:t={},popupSignal:r}){super(),this._logger=new p("PopupWindow");const n=y.center({...Q,...t});this._window=window.open(void 0,e,y.serialize(n)),r&&r.addEventListener("abort",(()=>{var e;this._abort.raise(new Error(null!=(e=r.reason)?e:"Popup aborted"))})),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout((()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))}),1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const r=setInterval((()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),n(),this._disposeHandlers.delete(n))}),500),n=()=>clearInterval(r);return this._disposeHandlers.add(n),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},oe=class{constructor(e){this._settings=e,this._logger=new p("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:r}){return new ie({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:r})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),ie.notifyOpener(e,t)}},ae=class{constructor(e){this._settings=e,this._logger=new p("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var r;this._logger.create("prepare");let n=window.self;"top"===t&&(n=null!=(r=window.top)?r:window.self);const s=n.location[e].bind(n.location);let i;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{i=t}));return s(e.url),await t},close:()=>{this._logger.create("close"),null==i||i(new Error("Redirect aborted")),n.stop()}}}async callback(){}},ce=class extends x{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new p("UserManagerEvents"),this._userLoaded=new w("User loaded"),this._userUnloaded=new w("User unloaded"),this._silentRenewError=new w("Silent renew error"),this._userSignedIn=new w("User signed in"),this._userSignedOut=new w("User signed out"),this._userSessionChanged=new w("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},le=class{constructor(e){this._userManager=e,this._logger=new p("SilentRenewService"),this._isStarted=!1,this._retryTimer=new b("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof k)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},de=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},ue=class{constructor(e,t,r,n){this._logger=new p("UserManager"),this.settings=new re(e),this._client=new J(e),this._redirectNavigator=null!=t?t:new ae(this.settings),this._popupNavigator=null!=r?r:new oe(this.settings),this._iframeNavigator=null!=n?n:new se(this.settings),this._events=new ce(this.settings),this._silentRenewService=new le(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new G(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),r=await this._loadUser();return r?(t.info("user loaded"),await this._events.load(r,e),r):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:r,...n}=e;let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const i=await this._redirectNavigator.prepare({redirectMethod:r});await this._signinStart({request_type:"si:r",dpopJkt:s,...n},i)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),r=await this._signinEnd(e);return r.profile&&r.profile.sub?t.info("success, signed in subject",r.profile.sub):t.info("no subject"),r}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:r=!1}){const n=this._logger.create("signinResourceOwnerCredential"),s=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r,extraTokenParams:this.settings.extraTokenParams});n.debug("got signin response");const i=await this._buildUser(s);return i.profile&&i.profile.sub?n.info("success, signed in subject",i.profile.sub):n.info("no subject"),i}async signinPopup(e={}){var t;const r=this._logger.create("signinPopup");let n;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(n=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:s,popupWindowTarget:i,popupSignal:o,...a}=e,c=this.settings.popup_redirect_uri;c||r.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:i,popupSignal:o}),d=await this._signin({request_type:"si:p",redirect_uri:c,display:"popup",dpopJkt:n,...a},l);return d&&(d.profile&&d.profile.sub?r.info("success, signed in subject",d.profile.sub):r.info("no subject")),d}async signinPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async signinSilent(e={}){var t,r;const n=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:s,...i}=e;let o,a=await this._loadUser();if(null==a?void 0:a.refresh_token){n.debug("using refresh token");const e=new de(a);return await this._useRefreshToken({state:e,redirect_uri:i.redirect_uri,resource:i.resource,extraTokenParams:i.extraTokenParams,timeoutInSeconds:s})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let l;c||n.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(n.debug("subject prior to silent renew:",a.profile.sub),l=a.profile.sub);const d=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});return a=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:o,...i},d,l),a&&((null==(r=a.profile)?void 0:r.sub)?n.info("success, signed in subject",a.profile.sub):n.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),r=new V({...e.state,...t});return await this.storeUser(r),await this._events.load(r),r}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:r}=await this._client.readSignoutResponseState(e);if(r)switch(r.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:r,...n}=e,s=this.settings.silent_redirect_uri;s||t.throw(new Error("No silent_redirect_uri configured"));const i=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r}),a=await this._signinStart({request_type:"si:s",redirect_uri:s,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==i?void 0:i.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...n},o);try{const e={},r=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),r.session_state&&r.profile.sub?(t.info("success for subject",r.profile.sub),{session_state:r.session_state,sub:r.profile.sub}):(t.info("success, user not authenticated"),null)}catch(c){if(this.settings.monitorAnonymousSession&&c instanceof E)switch(c.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:c.session_state}}throw c}}async _signin(e,t,r){const n=await this._signinStart(e,t);return await this._signinEnd(n.url,r)}async _signinStart(e,t){const r=this._logger.create("_signinStart");try{const n=await this._client.createSigninRequest(e);return r.debug("got signin request"),await t.navigate({url:n.url,state:n.state.id,response_mode:n.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(n){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),n}}async _signinEnd(e,t){const r=this._logger.create("_signinEnd"),n=await this._client.processSigninResponse(e,{});r.debug("got signin response");return await this._buildUser(n,t)}async _buildUser(e,t){const r=this._logger.create("_buildUser"),n=new V(e);if(t){if(t!==n.profile.sub)throw r.debug("current user does not match user returned from signin. sub from signin:",n.profile.sub),new E({...e,error:"login_required"});r.debug("current user matches user returned from signin")}return await this.storeUser(n),r.debug("user stored"),await this._events.load(n),n}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:r,...n}=e,s=await this._redirectNavigator.prepare({redirectMethod:r});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...n},s),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),r=await this._signoutEnd(e);return t.info("success"),r}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:r,popupWindowTarget:n,popupSignal:s,...i}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:n,popupSignal:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...i},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async _signout(e,t){const r=await this._signoutStart(e,t);return await this._signoutEnd(r.url)}async _signoutStart(e={},t){var r;const n=this._logger.create("_signoutStart");try{const s=await this._loadUser();n.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(s);const i=e.id_token_hint||s&&s.id_token;i&&(n.debug("setting id_token_hint in signout request"),e.id_token_hint=i),await this.removeUser(),n.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return n.debug("got signout request"),await t.navigate({url:o.url,state:null==(r=o.state)?void 0:r.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(s){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),s}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),r=await this._client.processSignoutResponse(e);return t.debug("got signout response"),r}async signoutSilent(e={}){var t;const r=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:n,...s}=e,i=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:i,...s},a),r.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const r=this._logger.create("_revokeInternal");if(!e)return;const n=t.filter((t=>"string"==typeof e[t]));if(n.length){for(const t of n)await this._client.revokeToken(e[t],t),r.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),r.debug("user stored"),await this._events.load(e)}else r.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),V.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const r=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,r)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,r,n){var s,i;const o=await(null==(i=null==(s=this.settings.dpop)?void 0:s.store)?void 0:i.get(this.settings.client_id));if(o)return await _.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:r,keyPair:o.keys,nonce:n})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const r=await _.generateDPoPKeys();t=new K(r),await e.store.set(this.settings.client_id,t)}return await _.generateDPoPJkt(t.keys)}};
2
- /*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */
3
- const{entries:he,setPrototypeOf:pe,isFrozen:ge,getPrototypeOf:fe,getOwnPropertyDescriptor:me}=Object;let{freeze:_e,seal:we,create:ye}=Object,{apply:be,construct:Se}="undefined"!=typeof Reflect&&Reflect;_e||(_e=function(e){return e}),we||(we=function(e){return e}),be||(be=function(e,t,r){return e.apply(t,r)}),Se||(Se=function(e,t){return new e(...t)});const ve=De(Array.prototype.forEach),Ee=De(Array.prototype.lastIndexOf),ke=De(Array.prototype.pop),xe=De(Array.prototype.push),Te=De(Array.prototype.splice),Re=De(String.prototype.toLowerCase),Ce=De(String.prototype.toString),Ae=De(String.prototype.match),Oe=De(String.prototype.replace),Ne=De(String.prototype.indexOf),Ie=De(String.prototype.trim),Pe=De(Object.prototype.hasOwnProperty),Ue=De(RegExp.prototype.test),je=(Le=TypeError,function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return Se(Le,t)});var Le;function De(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];return be(e,t,n)}}function Me(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Re;pe&&pe(e,null);let n=t.length;for(;n--;){let s=t[n];if("string"==typeof s){const e=r(s);e!==s&&(ge(t)||(t[n]=e),s=e)}e[s]=!0}return e}function Fe(e){for(let t=0;t<e.length;t++){Pe(e,t)||(e[t]=null)}return e}function qe(e){const t=ye(null);for(const[r,n]of he(e)){Pe(e,r)&&(Array.isArray(n)?t[r]=Fe(n):n&&"object"==typeof n&&n.constructor===Object?t[r]=qe(n):t[r]=n)}return t}function He(e,t){for(;null!==e;){const r=me(e,t);if(r){if(r.get)return De(r.get);if("function"==typeof r.value)return De(r.value)}e=fe(e)}return function(){return null}}const ze=_e(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Be=_e(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),We=_e(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),$e=_e(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ke=_e(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Je=_e(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Ge=_e(["#text"]),Ve=_e(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Ye=_e(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Xe=_e(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Qe=_e(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Ze=we(/\{\{[\w\W]*|[\w\W]*\}\}/gm),et=we(/<%[\w\W]*|[\w\W]*%>/gm),tt=we(/\$\{[\w\W]*/gm),rt=we(/^data-[\-\w.\u00B7-\uFFFF]+$/),nt=we(/^aria-[\-\w]+$/),st=we(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),it=we(/^(?:\w+script|data):/i),ot=we(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),at=we(/^html$/i),ct=we(/^[a-z][.\w]*(-[.\w]+)+$/i);var lt=Object.freeze({__proto__:null,ARIA_ATTR:nt,ATTR_WHITESPACE:ot,CUSTOM_ELEMENT:ct,DATA_ATTR:rt,DOCTYPE_NAME:at,ERB_EXPR:et,IS_ALLOWED_URI:st,IS_SCRIPT_OR_DATA:it,MUSTACHE_EXPR:Ze,TMPLIT_EXPR:tt});const dt=1,ut=3,ht=7,pt=8,gt=9;var ft=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"undefined"==typeof window?null:window;const r=t=>e(t);if(r.version="3.2.6",r.removed=[],!t||!t.document||t.document.nodeType!==gt||!t.Element)return r.isSupported=!1,r;let{document:n}=t;const s=n,i=s.currentScript,{DocumentFragment:o,HTMLTemplateElement:a,Node:c,Element:l,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:h,DOMParser:p,trustedTypes:g}=t,f=l.prototype,m=He(f,"cloneNode"),_=He(f,"remove"),w=He(f,"nextSibling"),y=He(f,"childNodes"),b=He(f,"parentNode");if("function"==typeof a){const e=n.createElement("template");e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let S,v="";const{implementation:E,createNodeIterator:k,createDocumentFragment:x,getElementsByTagName:T}=n,{importNode:R}=s;let C={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};r.isSupported="function"==typeof he&&"function"==typeof b&&E&&void 0!==E.createHTMLDocument;const{MUSTACHE_EXPR:A,ERB_EXPR:O,TMPLIT_EXPR:N,DATA_ATTR:I,ARIA_ATTR:P,IS_SCRIPT_OR_DATA:U,ATTR_WHITESPACE:j,CUSTOM_ELEMENT:L}=lt;let{IS_ALLOWED_URI:D}=lt,M=null;const F=Me({},[...ze,...Be,...We,...Ke,...Ge]);let q=null;const H=Me({},[...Ve,...Ye,...Xe,...Qe]);let z=Object.seal(ye(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),B=null,W=null,$=!0,K=!0,J=!1,G=!0,V=!1,Y=!0,X=!1,Q=!1,Z=!1,ee=!1,te=!1,re=!1,ne=!0,se=!1,ie=!0,oe=!1,ae={},ce=null;const le=Me({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let de=null;const ue=Me({},["audio","video","img","source","image","track"]);let pe=null;const ge=Me({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),fe="http://www.w3.org/1998/Math/MathML",me="http://www.w3.org/2000/svg",we="http://www.w3.org/1999/xhtml";let be=we,Se=!1,Le=null;const De=Me({},[fe,me,we],Ce);let Fe=Me({},["mi","mo","mn","ms","mtext"]),Ze=Me({},["annotation-xml"]);const et=Me({},["title","style","font","a","script"]);let tt=null;const rt=["application/xhtml+xml","text/html"];let nt=null,it=null;const ot=n.createElement("form"),ct=function(e){return e instanceof RegExp||e instanceof Function},ft=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!it||it!==e){if(e&&"object"==typeof e||(e={}),e=qe(e),tt=-1===rt.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,nt="application/xhtml+xml"===tt?Ce:Re,M=Pe(e,"ALLOWED_TAGS")?Me({},e.ALLOWED_TAGS,nt):F,q=Pe(e,"ALLOWED_ATTR")?Me({},e.ALLOWED_ATTR,nt):H,Le=Pe(e,"ALLOWED_NAMESPACES")?Me({},e.ALLOWED_NAMESPACES,Ce):De,pe=Pe(e,"ADD_URI_SAFE_ATTR")?Me(qe(ge),e.ADD_URI_SAFE_ATTR,nt):ge,de=Pe(e,"ADD_DATA_URI_TAGS")?Me(qe(ue),e.ADD_DATA_URI_TAGS,nt):ue,ce=Pe(e,"FORBID_CONTENTS")?Me({},e.FORBID_CONTENTS,nt):le,B=Pe(e,"FORBID_TAGS")?Me({},e.FORBID_TAGS,nt):qe({}),W=Pe(e,"FORBID_ATTR")?Me({},e.FORBID_ATTR,nt):qe({}),ae=!!Pe(e,"USE_PROFILES")&&e.USE_PROFILES,$=!1!==e.ALLOW_ARIA_ATTR,K=!1!==e.ALLOW_DATA_ATTR,J=e.ALLOW_UNKNOWN_PROTOCOLS||!1,G=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,V=e.SAFE_FOR_TEMPLATES||!1,Y=!1!==e.SAFE_FOR_XML,X=e.WHOLE_DOCUMENT||!1,ee=e.RETURN_DOM||!1,te=e.RETURN_DOM_FRAGMENT||!1,re=e.RETURN_TRUSTED_TYPE||!1,Z=e.FORCE_BODY||!1,ne=!1!==e.SANITIZE_DOM,se=e.SANITIZE_NAMED_PROPS||!1,ie=!1!==e.KEEP_CONTENT,oe=e.IN_PLACE||!1,D=e.ALLOWED_URI_REGEXP||st,be=e.NAMESPACE||we,Fe=e.MATHML_TEXT_INTEGRATION_POINTS||Fe,Ze=e.HTML_INTEGRATION_POINTS||Ze,z=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&ct(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(z.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&ct(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(z.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(z.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),V&&(K=!1),te&&(ee=!0),ae&&(M=Me({},Ge),q=[],!0===ae.html&&(Me(M,ze),Me(q,Ve)),!0===ae.svg&&(Me(M,Be),Me(q,Ye),Me(q,Qe)),!0===ae.svgFilters&&(Me(M,We),Me(q,Ye),Me(q,Qe)),!0===ae.mathMl&&(Me(M,Ke),Me(q,Xe),Me(q,Qe))),e.ADD_TAGS&&(M===F&&(M=qe(M)),Me(M,e.ADD_TAGS,nt)),e.ADD_ATTR&&(q===H&&(q=qe(q)),Me(q,e.ADD_ATTR,nt)),e.ADD_URI_SAFE_ATTR&&Me(pe,e.ADD_URI_SAFE_ATTR,nt),e.FORBID_CONTENTS&&(ce===le&&(ce=qe(ce)),Me(ce,e.FORBID_CONTENTS,nt)),ie&&(M["#text"]=!0),X&&Me(M,["html","head","body"]),M.table&&(Me(M,["tbody"]),delete B.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw je('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw je('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');S=e.TRUSTED_TYPES_POLICY,v=S.createHTML("")}else void 0===S&&(S=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let r=null;const n="data-tt-policy-suffix";t&&t.hasAttribute(n)&&(r=t.getAttribute(n));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML:e=>e,createScriptURL:e=>e})}catch(i){return console.warn("TrustedTypes policy "+s+" could not be created."),null}}(g,i)),null!==S&&"string"==typeof v&&(v=S.createHTML(""));_e&&_e(e),it=e}},mt=Me({},[...Be,...We,...$e]),_t=Me({},[...Ke,...Je]),wt=function(e){xe(r.removed,{element:e});try{b(e).removeChild(e)}catch(t){_(e)}},yt=function(e,t){try{xe(r.removed,{attribute:t.getAttributeNode(e),from:t})}catch(n){xe(r.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ee||te)try{wt(t)}catch(n){}else try{t.setAttribute(e,"")}catch(n){}},bt=function(e){let t=null,r=null;if(Z)e="<remove></remove>"+e;else{const t=Ae(e,/^[\r\n\t ]+/);r=t&&t[0]}"application/xhtml+xml"===tt&&be===we&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const s=S?S.createHTML(e):e;if(be===we)try{t=(new p).parseFromString(s,tt)}catch(o){}if(!t||!t.documentElement){t=E.createDocument(be,"template",null);try{t.documentElement.innerHTML=Se?v:s}catch(o){}}const i=t.body||t.documentElement;return e&&r&&i.insertBefore(n.createTextNode(r),i.childNodes[0]||null),be===we?T.call(t,X?"html":"body")[0]:X?t.documentElement:i},St=function(e){return k.call(e.ownerDocument||e,e,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},vt=function(e){return e instanceof h&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof u)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},Et=function(e){return"function"==typeof c&&e instanceof c};function kt(e,t,n){ve(e,(e=>{e.call(r,t,n,it)}))}const xt=function(e){let t=null;if(kt(C.beforeSanitizeElements,e,null),vt(e))return wt(e),!0;const n=nt(e.nodeName);if(kt(C.uponSanitizeElement,e,{tagName:n,allowedTags:M}),Y&&e.hasChildNodes()&&!Et(e.firstElementChild)&&Ue(/<[/\w!]/g,e.innerHTML)&&Ue(/<[/\w!]/g,e.textContent))return wt(e),!0;if(e.nodeType===ht)return wt(e),!0;if(Y&&e.nodeType===pt&&Ue(/<[/\w]/g,e.data))return wt(e),!0;if(!M[n]||B[n]){if(!B[n]&&Rt(n)){if(z.tagNameCheck instanceof RegExp&&Ue(z.tagNameCheck,n))return!1;if(z.tagNameCheck instanceof Function&&z.tagNameCheck(n))return!1}if(ie&&!ce[n]){const t=b(e)||e.parentNode,r=y(e)||e.childNodes;if(r&&t){for(let n=r.length-1;n>=0;--n){const s=m(r[n],!0);s.__removalCount=(e.__removalCount||0)+1,t.insertBefore(s,w(e))}}}return wt(e),!0}return e instanceof l&&!function(e){let t=b(e);t&&t.tagName||(t={namespaceURI:be,tagName:"template"});const r=Re(e.tagName),n=Re(t.tagName);return!!Le[e.namespaceURI]&&(e.namespaceURI===me?t.namespaceURI===we?"svg"===r:t.namespaceURI===fe?"svg"===r&&("annotation-xml"===n||Fe[n]):Boolean(mt[r]):e.namespaceURI===fe?t.namespaceURI===we?"math"===r:t.namespaceURI===me?"math"===r&&Ze[n]:Boolean(_t[r]):e.namespaceURI===we?!(t.namespaceURI===me&&!Ze[n])&&!(t.namespaceURI===fe&&!Fe[n])&&!_t[r]&&(et[r]||!mt[r]):!("application/xhtml+xml"!==tt||!Le[e.namespaceURI]))}(e)?(wt(e),!0):"noscript"!==n&&"noembed"!==n&&"noframes"!==n||!Ue(/<\/no(script|embed|frames)/i,e.innerHTML)?(V&&e.nodeType===ut&&(t=e.textContent,ve([A,O,N],(e=>{t=Oe(t,e," ")})),e.textContent!==t&&(xe(r.removed,{element:e.cloneNode()}),e.textContent=t)),kt(C.afterSanitizeElements,e,null),!1):(wt(e),!0)},Tt=function(e,t,r){if(ne&&("id"===t||"name"===t)&&(r in n||r in ot))return!1;if(K&&!W[t]&&Ue(I,t));else if($&&Ue(P,t));else if(!q[t]||W[t]){if(!(Rt(e)&&(z.tagNameCheck instanceof RegExp&&Ue(z.tagNameCheck,e)||z.tagNameCheck instanceof Function&&z.tagNameCheck(e))&&(z.attributeNameCheck instanceof RegExp&&Ue(z.attributeNameCheck,t)||z.attributeNameCheck instanceof Function&&z.attributeNameCheck(t))||"is"===t&&z.allowCustomizedBuiltInElements&&(z.tagNameCheck instanceof RegExp&&Ue(z.tagNameCheck,r)||z.tagNameCheck instanceof Function&&z.tagNameCheck(r))))return!1}else if(pe[t]);else if(Ue(D,Oe(r,j,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Ne(r,"data:")||!de[e]){if(J&&!Ue(U,Oe(r,j,"")));else if(r)return!1}else;return!0},Rt=function(e){return"annotation-xml"!==e&&Ae(e,L)},Ct=function(e){kt(C.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||vt(e))return;const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:q,forceKeepAttr:void 0};let s=t.length;for(;s--;){const o=t[s],{name:a,namespaceURI:c,value:l}=o,d=nt(a),u=l;let h="value"===a?u:Ie(u);if(n.attrName=d,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,kt(C.uponSanitizeAttribute,e,n),h=n.attrValue,!se||"id"!==d&&"name"!==d||(yt(a,e),h="user-content-"+h),Y&&Ue(/((--!?|])>)|<\/(style|title)/i,h)){yt(a,e);continue}if(n.forceKeepAttr)continue;if(!n.keepAttr){yt(a,e);continue}if(!G&&Ue(/\/>/i,h)){yt(a,e);continue}V&&ve([A,O,N],(e=>{h=Oe(h,e," ")}));const p=nt(e.nodeName);if(Tt(p,d,h)){if(S&&"object"==typeof g&&"function"==typeof g.getAttributeType)if(c);else switch(g.getAttributeType(p,d)){case"TrustedHTML":h=S.createHTML(h);break;case"TrustedScriptURL":h=S.createScriptURL(h)}if(h!==u)try{c?e.setAttributeNS(c,a,h):e.setAttribute(a,h),vt(e)?wt(e):ke(r.removed)}catch(i){yt(a,e)}}else yt(a,e)}kt(C.afterSanitizeAttributes,e,null)},At=function e(t){let r=null;const n=St(t);for(kt(C.beforeSanitizeShadowDOM,t,null);r=n.nextNode();)kt(C.uponSanitizeShadowNode,r,null),xt(r),Ct(r),r.content instanceof o&&e(r.content);kt(C.afterSanitizeShadowDOM,t,null)};return r.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,i=null,a=null,l=null;if(Se=!e,Se&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Et(e)){if("function"!=typeof e.toString)throw je("toString is not a function");if("string"!=typeof(e=e.toString()))throw je("dirty is not a string, aborting")}if(!r.isSupported)return e;if(Q||ft(t),r.removed=[],"string"==typeof e&&(oe=!1),oe){if(e.nodeName){const t=nt(e.nodeName);if(!M[t]||B[t])throw je("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)n=bt("\x3c!----\x3e"),i=n.ownerDocument.importNode(e,!0),i.nodeType===dt&&"BODY"===i.nodeName||"HTML"===i.nodeName?n=i:n.appendChild(i);else{if(!ee&&!V&&!X&&-1===e.indexOf("<"))return S&&re?S.createHTML(e):e;if(n=bt(e),!n)return ee?null:re?v:""}n&&Z&&wt(n.firstChild);const d=St(oe?e:n);for(;a=d.nextNode();)xt(a),Ct(a),a.content instanceof o&&At(a.content);if(oe)return e;if(ee){if(te)for(l=x.call(n.ownerDocument);n.firstChild;)l.appendChild(n.firstChild);else l=n;return(q.shadowroot||q.shadowrootmode)&&(l=R.call(s,l,!0)),l}let u=X?n.outerHTML:n.innerHTML;return X&&M["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&Ue(at,n.ownerDocument.doctype.name)&&(u="<!DOCTYPE "+n.ownerDocument.doctype.name+">\n"+u),V&&ve([A,O,N],(e=>{u=Oe(u,e," ")})),S&&re?S.createHTML(u):u},r.setConfig=function(){ft(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Q=!0},r.clearConfig=function(){it=null,Q=!1},r.isValidAttribute=function(e,t,r){it||ft({});const n=nt(e),s=nt(t);return Tt(n,s,r)},r.addHook=function(e,t){"function"==typeof t&&xe(C[e],t)},r.removeHook=function(e,t){if(void 0!==t){const r=Ee(C[e],t);return-1===r?void 0:Te(C[e],r,1)[0]}return ke(C[e])},r.removeHooks=function(e){C[e]=[]},r.removeAllHooks=function(){C={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},r}();const mt=(()=>{if("undefined"!=typeof window)return ft;try{const{JSDOM:e}=require("jsdom"),{window:t}=new e("");return ft(t)}catch(e){return{sanitize:e=>e.replace(/<[^>]*>/g,"")}}})();function _t(e){if(!e)return"";try{let t=mt.sanitize(e,{ALLOWED_TAGS:[],ALLOWED_ATTR:[],KEEP_CONTENT:!0,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,FORCE_BODY:!0});if(!t.trim()){e.replace(/<[^>]*>/g,"").trim()&&(t=e.replace(/<[^>]*>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").trim())}return t.trim().slice(0,1e3)}catch{return e.replace(/<[^>]*>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").trim().slice(0,1e3)}}function wt(e){if(!e)return"";const t=_t(e).match(/^([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/);return t?t[1]??"":""}function yt(e){if(!e)return"";const t=_t(e);try{const e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol?t:""}catch{return""}}function bt(e,t){return function(){return e.apply(t,arguments)}}const{toString:St}=Object.prototype,{getPrototypeOf:vt}=Object,{iterator:Et,toStringTag:kt}=Symbol,xt=(e=>t=>{const r=St.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Tt=e=>(e=e.toLowerCase(),t=>xt(t)===e),Rt=e=>t=>typeof t===e,{isArray:Ct}=Array,At=Rt("undefined");const Ot=Tt("ArrayBuffer");const Nt=Rt("string"),It=Rt("function"),Pt=Rt("number"),Ut=e=>null!==e&&"object"==typeof e,jt=e=>{if("object"!==xt(e))return!1;const t=vt(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||kt in e||Et in e)},Lt=Tt("Date"),Dt=Tt("File"),Mt=Tt("Blob"),Ft=Tt("FileList"),qt=Tt("URLSearchParams"),[Ht,zt,Bt,Wt]=["ReadableStream","Request","Response","Headers"].map(Tt);function $t(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,s;if("object"!=typeof e&&(e=[e]),Ct(e))for(n=0,s=e.length;n<s;n++)t.call(null,e[n],n,e);else{const s=r?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let o;for(n=0;n<i;n++)o=s[n],t.call(null,e[o],o,e)}}function Kt(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,s=r.length;for(;s-- >0;)if(n=r[s],t===n.toLowerCase())return n;return null}const Jt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,Gt=e=>!At(e)&&e!==Jt;const Vt=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&vt(Uint8Array)),Yt=Tt("HTMLFormElement"),Xt=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Qt=Tt("RegExp"),Zt=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};$t(r,((r,s)=>{let i;!1!==(i=t(r,s,e))&&(n[s]=i||r)})),Object.defineProperties(e,n)};const er=Tt("AsyncFunction"),tr=(rr="function"==typeof setImmediate,nr=It(Jt.postMessage),rr?setImmediate:nr?(sr=`axios@${Math.random()}`,ir=[],Jt.addEventListener("message",(({source:e,data:t})=>{e===Jt&&t===sr&&ir.length&&ir.shift()()}),!1),e=>{ir.push(e),Jt.postMessage(sr,"*")}):e=>setTimeout(e));var rr,nr,sr,ir;const or="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Jt):"undefined"!=typeof process&&process.nextTick||tr,ar={isArray:Ct,isArrayBuffer:Ot,isBuffer:function(e){return null!==e&&!At(e)&&null!==e.constructor&&!At(e.constructor)&&It(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||It(e.append)&&("formdata"===(t=xt(e))||"object"===t&&It(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Ot(e.buffer),t},isString:Nt,isNumber:Pt,isBoolean:e=>!0===e||!1===e,isObject:Ut,isPlainObject:jt,isReadableStream:Ht,isRequest:zt,isResponse:Bt,isHeaders:Wt,isUndefined:At,isDate:Lt,isFile:Dt,isBlob:Mt,isRegExp:Qt,isFunction:It,isStream:e=>Ut(e)&&It(e.pipe),isURLSearchParams:qt,isTypedArray:Vt,isFileList:Ft,forEach:$t,merge:function e(){const{caseless:t}=Gt(this)&&this||{},r={},n=(n,s)=>{const i=t&&Kt(r,s)||s;jt(r[i])&&jt(n)?r[i]=e(r[i],n):jt(n)?r[i]=e({},n):Ct(n)?r[i]=n.slice():r[i]=n};for(let s=0,i=arguments.length;s<i;s++)arguments[s]&&$t(arguments[s],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>($t(t,((t,n)=>{r&&It(t)?e[n]=bt(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let s,i,o;const a={};if(t=t||{},null==e)return t;do{for(s=Object.getOwnPropertyNames(e),i=s.length;i-- >0;)o=s[i],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&vt(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:xt,kindOfTest:Tt,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(Ct(e))return e;let t=e.length;if(!Pt(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Et]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:Yt,hasOwnProperty:Xt,hasOwnProp:Xt,reduceDescriptors:Zt,freezeMethods:e=>{Zt(e,((t,r)=>{if(It(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];It(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return Ct(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:Kt,global:Jt,isContextDefined:Gt,isSpecCompliantForm:function(e){return!!(e&&It(e.append)&&"FormData"===e[kt]&&e[Et])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(Ut(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const s=Ct(e)?[]:{};return $t(e,((e,t)=>{const i=r(e,n+1);!At(i)&&(s[t]=i)})),t[n]=void 0,s}}return e};return r(e,0)},isAsyncFn:er,isThenable:e=>e&&(Ut(e)||It(e))&&It(e.then)&&It(e.catch),setImmediate:tr,asap:or,isIterable:e=>null!=e&&It(e[Et])};function cr(e,t,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}ar.inherits(cr,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ar.toJSONObject(this.config),code:this.code,status:this.status}}});const lr=cr.prototype,dr={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{dr[e]={value:e}})),Object.defineProperties(cr,dr),Object.defineProperty(lr,"isAxiosError",{value:!0}),cr.from=(e,t,r,n,s,i)=>{const o=Object.create(lr);return ar.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),cr.call(o,e.message,t,r,n,s),o.cause=e,o.name=e.name,i&&Object.assign(o,i),o};function ur(e){return ar.isPlainObject(e)||ar.isArray(e)}function hr(e){return ar.endsWith(e,"[]")?e.slice(0,-2):e}function pr(e,t,r){return e?e.concat(t).map((function(e,t){return e=hr(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const gr=ar.toFlatObject(ar,{},null,(function(e){return/^is[A-Z]/.test(e)}));function fr(e,t,r){if(!ar.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=ar.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!ar.isUndefined(t[e])}))).metaTokens,s=r.visitor||l,i=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&ar.isSpecCompliantForm(t);if(!ar.isFunction(s))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(ar.isDate(e))return e.toISOString();if(ar.isBoolean(e))return e.toString();if(!a&&ar.isBlob(e))throw new cr("Blob is not supported. Use a Buffer instead.");return ar.isArrayBuffer(e)||ar.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,r,s){let a=e;if(e&&!s&&"object"==typeof e)if(ar.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(ar.isArray(e)&&function(e){return ar.isArray(e)&&!e.some(ur)}(e)||(ar.isFileList(e)||ar.endsWith(r,"[]"))&&(a=ar.toArray(e)))return r=hr(r),a.forEach((function(e,n){!ar.isUndefined(e)&&null!==e&&t.append(!0===o?pr([r],n,i):null===o?r:r+"[]",c(e))})),!1;return!!ur(e)||(t.append(pr(s,r,i),c(e)),!1)}const d=[],u=Object.assign(gr,{defaultVisitor:l,convertValue:c,isVisitable:ur});if(!ar.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!ar.isUndefined(r)){if(-1!==d.indexOf(r))throw Error("Circular reference detected in "+n.join("."));d.push(r),ar.forEach(r,(function(r,i){!0===(!(ar.isUndefined(r)||null===r)&&s.call(t,r,ar.isString(i)?i.trim():i,n,u))&&e(r,n?n.concat(i):[i])})),d.pop()}}(e),t}function mr(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function _r(e,t){this._pairs=[],e&&fr(e,this,t)}const wr=_r.prototype;function yr(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function br(e,t,r){if(!t)return e;const n=r&&r.encode||yr;ar.isFunction(r)&&(r={serialize:r});const s=r&&r.serialize;let i;if(i=s?s(t,r):ar.isURLSearchParams(t)?t.toString():new _r(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}wr.append=function(e,t){this._pairs.push([e,t])},wr.toString=function(e){const t=e?function(t){return e.call(this,t,mr)}:mr;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class Sr{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ar.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}const vr={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Er={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:_r,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},kr="undefined"!=typeof window&&"undefined"!=typeof document,xr="object"==typeof navigator&&navigator||void 0,Tr=kr&&(!xr||["ReactNative","NativeScript","NS"].indexOf(xr.product)<0),Rr="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Cr=kr&&window.location.href||"http://localhost",Ar={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:kr,hasStandardBrowserEnv:Tr,hasStandardBrowserWebWorkerEnv:Rr,navigator:xr,origin:Cr},Symbol.toStringTag,{value:"Module"})),...Er};function Or(e){function t(e,r,n,s){let i=e[s++];if("__proto__"===i)return!0;const o=Number.isFinite(+i),a=s>=e.length;if(i=!i&&ar.isArray(n)?n.length:i,a)return ar.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!o;n[i]&&ar.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],s)&&ar.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const s=r.length;let i;for(n=0;n<s;n++)i=r[n],t[i]=e[i];return t}(n[i])),!o}if(ar.isFormData(e)&&ar.isFunction(e.entries)){const r={};return ar.forEachEntry(e,((e,n)=>{t(function(e){return ar.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const Nr={transitional:vr,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,s=ar.isObject(e);s&&ar.isHTMLForm(e)&&(e=new FormData(e));if(ar.isFormData(e))return n?JSON.stringify(Or(e)):e;if(ar.isArrayBuffer(e)||ar.isBuffer(e)||ar.isStream(e)||ar.isFile(e)||ar.isBlob(e)||ar.isReadableStream(e))return e;if(ar.isArrayBufferView(e))return e.buffer;if(ar.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return fr(e,new Ar.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return Ar.isNode&&ar.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=ar.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return fr(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return s||n?(t.setContentType("application/json",!1),function(e,t,r){if(ar.isString(e))try{return(t||JSON.parse)(e),ar.trim(e)}catch(n){if("SyntaxError"!==n.name)throw n}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Nr.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(ar.isResponse(e)||ar.isReadableStream(e))return e;if(e&&ar.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(s){if(r){if("SyntaxError"===s.name)throw cr.from(s,cr.ERR_BAD_RESPONSE,this,null,this.response);throw s}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ar.classes.FormData,Blob:Ar.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ar.forEach(["delete","get","head","post","put","patch"],(e=>{Nr.headers[e]={}}));const Ir=ar.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Pr=Symbol("internals");function Ur(e){return e&&String(e).trim().toLowerCase()}function jr(e){return!1===e||null==e?e:ar.isArray(e)?e.map(jr):String(e)}function Lr(e,t,r,n,s){return ar.isFunction(n)?n.call(this,t,r):(s&&(t=r),ar.isString(t)?ar.isString(n)?-1!==t.indexOf(n):ar.isRegExp(n)?n.test(t):void 0:void 0)}let Dr=class{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function s(e,t,r){const s=Ur(t);if(!s)throw new Error("header name must be a non-empty string");const i=ar.findKey(n,s);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=jr(e))}const i=(e,t)=>ar.forEach(e,((e,r)=>s(e,r,t)));if(ar.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(ar.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i((e=>{const t={};let r,n,s;return e&&e.split("\n").forEach((function(e){s=e.indexOf(":"),r=e.substring(0,s).trim().toLowerCase(),n=e.substring(s+1).trim(),!r||t[r]&&Ir[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if(ar.isObject(e)&&ar.isIterable(e)){let r,n,s={};for(const t of e){if(!ar.isArray(t))throw TypeError("Object iterator must return a key-value pair");s[n=t[0]]=(r=s[n])?ar.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}i(s,t)}else null!=e&&s(t,e,r);return this}get(e,t){if(e=Ur(e)){const r=ar.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(ar.isFunction(t))return t.call(this,e,r);if(ar.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Ur(e)){const r=ar.findKey(this,e);return!(!r||void 0===this[r]||t&&!Lr(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function s(e){if(e=Ur(e)){const s=ar.findKey(r,e);!s||t&&!Lr(0,r[s],s,t)||(delete r[s],n=!0)}}return ar.isArray(e)?e.forEach(s):s(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const s=t[r];e&&!Lr(0,this[s],s,e,!0)||(delete this[s],n=!0)}return n}normalize(e){const t=this,r={};return ar.forEach(this,((n,s)=>{const i=ar.findKey(r,s);if(i)return t[i]=jr(n),void delete t[s];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(s):String(s).trim();o!==s&&delete t[s],t[o]=jr(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return ar.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&ar.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[Pr]=this[Pr]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=Ur(e);t[n]||(!function(e,t){const r=ar.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,s){return this[n].call(this,t,e,r,s)},configurable:!0})}))}(r,e),t[n]=!0)}return ar.isArray(e)?e.forEach(n):n(e),this}};function Mr(e,t){const r=this||Nr,n=t||r,s=Dr.from(n.headers);let i=n.data;return ar.forEach(e,(function(e){i=e.call(r,i,s.normalize(),t?t.status:void 0)})),s.normalize(),i}function Fr(e){return!(!e||!e.__CANCEL__)}function qr(e,t,r){cr.call(this,null==e?"canceled":e,cr.ERR_CANCELED,t,r),this.name="CanceledError"}function Hr(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new cr("Request failed with status code "+r.status,[cr.ERR_BAD_REQUEST,cr.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}Dr.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ar.reduceDescriptors(Dr.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),ar.freezeMethods(Dr),ar.inherits(qr,cr,{__CANCEL__:!0});const zr=(e,t,r=3)=>{let n=0;const s=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let s,i=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=n[o];s||(s=c),r[i]=a,n[i]=c;let d=o,u=0;for(;d!==i;)u+=r[d++],d%=e;if(i=(i+1)%e,i===o&&(o=(o+1)%e),c-s<t)return;const h=l&&c-l;return h?Math.round(1e3*u/h):void 0}}(50,250);return function(e,t){let r,n,s=0,i=1e3/t;const o=(t,i=Date.now())=>{s=i,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-s;a>=i?o(e,t):(r=e,n||(n=setTimeout((()=>{n=null,o(r)}),i-a)))},()=>r&&o(r)]}((r=>{const i=r.loaded,o=r.lengthComputable?r.total:void 0,a=i-n,c=s(a);n=i;e({loaded:i,total:o,progress:o?i/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&i<=o?(o-i)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})}),r)},Br=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},Wr=e=>(...t)=>ar.asap((()=>e(...t))),$r=Ar.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Ar.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Ar.origin),Ar.navigator&&/(msie|trident)/i.test(Ar.navigator.userAgent)):()=>!0,Kr=Ar.hasStandardBrowserEnv?{write(e,t,r,n,s,i){const o=[e+"="+encodeURIComponent(t)];ar.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),ar.isString(n)&&o.push("path="+n),ar.isString(s)&&o.push("domain="+s),!0===i&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Jr(e,t,r){let n=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Gr=e=>e instanceof Dr?{...e}:e;function Vr(e,t){t=t||{};const r={};function n(e,t,r,n){return ar.isPlainObject(e)&&ar.isPlainObject(t)?ar.merge.call({caseless:n},e,t):ar.isPlainObject(t)?ar.merge({},t):ar.isArray(t)?t.slice():t}function s(e,t,r,s){return ar.isUndefined(t)?ar.isUndefined(e)?void 0:n(void 0,e,0,s):n(e,t,0,s)}function i(e,t){if(!ar.isUndefined(t))return n(void 0,t)}function o(e,t){return ar.isUndefined(t)?ar.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,s,i){return i in t?n(r,s):i in e?n(void 0,r):void 0}const c={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>s(Gr(e),Gr(t),0,!0)};return ar.forEach(Object.keys(Object.assign({},e,t)),(function(n){const i=c[n]||s,o=i(e[n],t[n],n);ar.isUndefined(o)&&i!==a||(r[n]=o)})),r}const Yr=e=>{const t=Vr({},e);let r,{data:n,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=Dr.from(a),t.url=br(Jr(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),ar.isFormData(n))if(Ar.hasStandardBrowserEnv||Ar.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(Ar.hasStandardBrowserEnv&&(s&&ar.isFunction(s)&&(s=s(t)),s||!1!==s&&$r(t.url))){const e=i&&o&&Kr.read(o);e&&a.set(i,e)}return t},Xr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=Yr(e);let s=n.data;const i=Dr.from(n.headers).normalize();let o,a,c,l,d,{responseType:u,onUploadProgress:h,onDownloadProgress:p}=n;function g(){l&&l(),d&&d(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let f=new XMLHttpRequest;function m(){if(!f)return;const n=Dr.from("getAllResponseHeaders"in f&&f.getAllResponseHeaders());Hr((function(e){t(e),g()}),(function(e){r(e),g()}),{data:u&&"text"!==u&&"json"!==u?f.response:f.responseText,status:f.status,statusText:f.statusText,headers:n,config:e,request:f}),f=null}f.open(n.method.toUpperCase(),n.url,!0),f.timeout=n.timeout,"onloadend"in f?f.onloadend=m:f.onreadystatechange=function(){f&&4===f.readyState&&(0!==f.status||f.responseURL&&0===f.responseURL.indexOf("file:"))&&setTimeout(m)},f.onabort=function(){f&&(r(new cr("Request aborted",cr.ECONNABORTED,e,f)),f=null)},f.onerror=function(){r(new cr("Network Error",cr.ERR_NETWORK,e,f)),f=null},f.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const s=n.transitional||vr;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new cr(t,s.clarifyTimeoutError?cr.ETIMEDOUT:cr.ECONNABORTED,e,f)),f=null},void 0===s&&i.setContentType(null),"setRequestHeader"in f&&ar.forEach(i.toJSON(),(function(e,t){f.setRequestHeader(t,e)})),ar.isUndefined(n.withCredentials)||(f.withCredentials=!!n.withCredentials),u&&"json"!==u&&(f.responseType=n.responseType),p&&([c,d]=zr(p,!0),f.addEventListener("progress",c)),h&&f.upload&&([a,l]=zr(h),f.upload.addEventListener("progress",a),f.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(o=t=>{f&&(r(!t||t.type?new qr(null,e,f):t),f.abort(),f=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const _=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);_&&-1===Ar.protocols.indexOf(_)?r(new cr("Unsupported protocol "+_+":",cr.ERR_BAD_REQUEST,e)):f.send(s||null)}))},Qr=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const s=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof cr?t:new qr(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,s(new cr(`timeout ${t} of ms exceeded`,cr.ETIMEDOUT))}),t);const o=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(s):e.removeEventListener("abort",s)})),e=null)};e.forEach((e=>e.addEventListener("abort",s)));const{signal:a}=n;return a.unsubscribe=()=>ar.asap(o),a}},Zr=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,s=0;for(;s<r;)n=s+t,yield e.slice(s,n),s=n},en=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},tn=(e,t,r,n)=>{const s=async function*(e,t){for await(const r of en(e))yield*Zr(r,t)}(e,t);let i,o=0,a=e=>{i||(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await s.next();if(t)return a(),void e.close();let i=n.byteLength;if(r){let e=o+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(t){throw a(t),t}},cancel:e=>(a(e),s.return())},{highWaterMark:2})},rn="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,nn=rn&&"function"==typeof ReadableStream,sn=rn&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),on=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},an=nn&&on((()=>{let e=!1;const t=new Request(Ar.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),cn=nn&&on((()=>ar.isReadableStream(new Response("").body))),ln={stream:cn&&(e=>e.body)};var dn;rn&&(dn=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!ln[e]&&(ln[e]=ar.isFunction(dn[e])?t=>t[e]():(t,r)=>{throw new cr(`Response type '${e}' is not supported`,cr.ERR_NOT_SUPPORT,r)})})));const un=async(e,t)=>{const r=ar.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(ar.isBlob(e))return e.size;if(ar.isSpecCompliantForm(e)){const t=new Request(Ar.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return ar.isArrayBufferView(e)||ar.isArrayBuffer(e)?e.byteLength:(ar.isURLSearchParams(e)&&(e+=""),ar.isString(e)?(await sn(e)).byteLength:void 0)})(t):r},hn={http:null,xhr:Xr,fetch:rn&&(async e=>{let{url:t,method:r,data:n,signal:s,cancelToken:i,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:d,withCredentials:u="same-origin",fetchOptions:h}=Yr(e);l=l?(l+"").toLowerCase():"text";let p,g=Qr([s,i&&i.toAbortSignal()],o);const f=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let m;try{if(c&&an&&"get"!==r&&"head"!==r&&0!==(m=await un(d,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(ar.isFormData(n)&&(e=r.headers.get("content-type"))&&d.setContentType(e),r.body){const[e,t]=Br(m,zr(Wr(c)));n=tn(r.body,65536,e,t)}}ar.isString(u)||(u=u?"include":"omit");const s="credentials"in Request.prototype;p=new Request(t,{...h,signal:g,method:r.toUpperCase(),headers:d.normalize().toJSON(),body:n,duplex:"half",credentials:s?u:void 0});let i=await fetch(p,h);const o=cn&&("stream"===l||"response"===l);if(cn&&(a||o&&f)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=ar.toFiniteNumber(i.headers.get("content-length")),[r,n]=a&&Br(t,zr(Wr(a),!0))||[];i=new Response(tn(i.body,65536,r,(()=>{n&&n(),f&&f()})),e)}l=l||"text";let _=await ln[ar.findKey(ln,l)||"text"](i,e);return!o&&f&&f(),await new Promise(((t,r)=>{Hr(t,r,{data:_,headers:Dr.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:p})}))}catch(_){if(f&&f(),_&&"TypeError"===_.name&&/Load failed|fetch/i.test(_.message))throw Object.assign(new cr("Network Error",cr.ERR_NETWORK,e,p),{cause:_.cause||_});throw cr.from(_,_&&_.code,e,p)}})};ar.forEach(hn,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}}));const pn=e=>`- ${e}`,gn=e=>ar.isFunction(e)||null===e||!1===e,fn=e=>{e=ar.isArray(e)?e:[e];const{length:t}=e;let r,n;const s={};for(let i=0;i<t;i++){let t;if(r=e[i],n=r,!gn(r)&&(n=hn[(t=String(r)).toLowerCase()],void 0===n))throw new cr(`Unknown adapter '${t}'`);if(n)break;s[t||"#"+i]=n}if(!n){const e=Object.entries(s).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new cr("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(pn).join("\n"):" "+pn(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function mn(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new qr(null,e)}function _n(e){mn(e),e.headers=Dr.from(e.headers),e.data=Mr.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return fn(e.adapter||Nr.adapter)(e).then((function(t){return mn(e),t.data=Mr.call(e,e.transformResponse,t),t.headers=Dr.from(t.headers),t}),(function(t){return Fr(t)||(mn(e),t&&t.response&&(t.response.data=Mr.call(e,e.transformResponse,t.response),t.response.headers=Dr.from(t.response.headers))),Promise.reject(t)}))}const wn="1.10.0",yn={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{yn[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const bn={};yn.transitional=function(e,t,r){function n(e,t){return"[Axios v"+wn+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,s,i)=>{if(!1===e)throw new cr(n(s," has been removed"+(t?" in "+t:"")),cr.ERR_DEPRECATED);return t&&!bn[s]&&(bn[s]=!0,console.warn(n(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,s,i)}},yn.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const Sn={assertOptions:function(e,t,r){if("object"!=typeof e)throw new cr("options must be an object",cr.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const i=n[s],o=t[i];if(o){const t=e[i],r=void 0===t||o(t,i,e);if(!0!==r)throw new cr("option "+i+" must be "+r,cr.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new cr("Unknown option "+i,cr.ERR_BAD_OPTION)}},validators:yn},vn=Sn.validators;let En=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Sr,response:new Sr}}async request(e,t){try{return await this._request(e,t)}catch(r){if(r instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{r.stack?t&&!String(r.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(r.stack+="\n"+t):r.stack=t}catch(n){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Vr(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:s}=t;void 0!==r&&Sn.assertOptions(r,{silentJSONParsing:vn.transitional(vn.boolean),forcedJSONParsing:vn.transitional(vn.boolean),clarifyTimeoutError:vn.transitional(vn.boolean)},!1),null!=n&&(ar.isFunction(n)?t.paramsSerializer={serialize:n}:Sn.assertOptions(n,{encode:vn.function,serialize:vn.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Sn.assertOptions(t,{baseUrl:vn.spelling("baseURL"),withXsrfToken:vn.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=s&&ar.merge(s.common,s[t.method]);s&&ar.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete s[e]})),t.headers=Dr.concat(i,s);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let l;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let d,u=0;if(!a){const e=[_n.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),d=e.length,l=Promise.resolve(t);u<d;)l=l.then(e[u++],e[u++]);return l}d=o.length;let h=t;for(u=0;u<d;){const e=o[u++],t=o[u++];try{h=e(h)}catch(p){t.call(this,p);break}}try{l=_n.call(this,h)}catch(p){return Promise.reject(p)}for(u=0,d=c.length;u<d;)l=l.then(c[u++],c[u++]);return l}getUri(e){return br(Jr((e=Vr(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};ar.forEach(["delete","get","head","options"],(function(e){En.prototype[e]=function(t,r){return this.request(Vr(r||{},{method:e,url:t,data:(r||{}).data}))}})),ar.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,s){return this.request(Vr(s||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}En.prototype[e]=t(),En.prototype[e+"Form"]=t(!0)}));const kn={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(kn).forEach((([e,t])=>{kn[t]=e}));const xn=function e(t){const r=new En(t),n=bt(En.prototype.request,r);return ar.extend(n,En.prototype,r,{allOwnKeys:!0}),ar.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(Vr(t,r))},n}(Nr);xn.Axios=En,xn.CanceledError=qr,xn.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,s){r.reason||(r.reason=new qr(e,n,s),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e((function(e){t=e})),cancel:t}}},xn.isCancel=Fr,xn.VERSION=wn,xn.toFormData=fr,xn.AxiosError=cr,xn.Cancel=xn.CanceledError,xn.all=function(e){return Promise.all(e)},xn.spread=function(e){return function(t){return e.apply(null,t)}},xn.isAxiosError=function(e){return ar.isObject(e)&&!0===e.isAxiosError},xn.mergeConfig=Vr,xn.AxiosHeaders=Dr,xn.formToJSON=e=>Or(ar.isHTMLForm(e)?new FormData(e):e),xn.getAdapter=fn,xn.HttpStatusCode=kn,xn.default=xn;const{Axios:Tn,AxiosError:Rn,CanceledError:Cn,isCancel:An,CancelToken:On,VERSION:Nn,all:In,Cancel:Pn,isAxiosError:Un,spread:jn,toFormData:Ln,AxiosHeaders:Dn,HttpStatusCode:Mn,formToJSON:Fn,getAdapter:qn,mergeConfig:Hn}=xn;var zn={baseUrl:"undefined"!=typeof process&&(null==(n=process.env)?void 0:n.ECHO_BASE_URL)||"https://echo.merit.systems"};var Bn=class{constructor(e){var t;i(this,"http"),i(this,"config"),this.config=(t=e,{...zn,...t}),this.http=xn.create({baseURL:this.config.baseUrl,timeout:3e4}),this.http.interceptors.request.use((async e=>{const t=this.config.apiKey||process.env.ECHO_API_KEY;return t&&(e.headers.Authorization=`Bearer ${t}`),e})),this.http.interceptors.response.use((e=>e),(e=>{var t;if(401===(null==(t=e.response)?void 0:t.status))throw new Error('Unauthorized. Invalid or expired API key. Please run "echo-cli login" to authenticate.');throw e}))}async getBalance(){try{return(await this.http.get("/api/v1/balance")).data}catch(e){throw this.handleError(e,"Failed to fetch balance")}}async getFreeBalance(e){try{const t={echoAppId:e};return(await this.http.post("/api/v1/balance/free",t)).data}catch(t){throw this.handleError(t,"Failed to fetch free tier balance")}}async createPaymentLink(e){try{return(await this.http.post("/api/v1/stripe/payment-link",e)).data}catch(t){throw this.handleError(t,"Failed to create payment link")}}async getPaymentUrl(e,t,r){const n={amount:e,description:t||"Echo Credits"};r&&(n.successUrl=r);return(await this.createPaymentLink(n)).paymentLink.url}getAppUrl(e){return`${this.config.baseUrl}/apps/${e}`}async listEchoApps(){try{return(await this.http.get("/api/v1/apps")).data.apps}catch(e){throw this.handleError(e,"Failed to fetch Echo apps")}}async getEchoApp(e){try{return(await this.http.get(`/api/v1/apps/${e}`)).data}catch(t){throw this.handleError(t,"Failed to fetch Echo app")}}async getUserInfo(){try{return(await this.http.get("/api/v1/user")).data}catch(e){throw this.handleError(e,"Failed to fetch user info")}}async getSupportedModels(){try{return(await this.http.get("/api/v1/supported-models")).data}catch(e){throw this.handleError(e,"Failed to fetch supported models")}}async listSupportedModels(){return(await this.getSupportedModels()).models}async getSupportedModelsByProvider(){return(await this.getSupportedModels()).models_by_provider}async registerReferralCode(e,t){const r={echoAppId:e,code:t};return(await this.http.post("/api/v1/user/referral",r).catch((e=>{throw this.handleError(e,"Failed to register referral code")}))).data}handleError(e,t){var r,n;return(null==(n=null==(r=e.response)?void 0:r.data)?void 0:n.error)?new Error(`${t}: ${e.response.data.error}`):e.message?new Error(`${t}: ${e.message}`):new Error(t)}};const Wn=r.createContext(void 0);function $n(){const e=r.useContext(Wn);if(!e)throw new Error("useEcho must be used within an EchoProvider");return e}const Kn=({className:e="",width:r=16,height:n=16,variant:s="light"})=>{const i="dark"===s?"#DFE2D9":"#232323";return t.jsxs("svg",{id:"Layer_1","data-name":"Layer 1",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 226.03 261",className:e,width:r,height:n,"aria-label":"Echo Logo",children:[t.jsx("defs",{children:t.jsx("style",{children:`\n .cls-1 {\n fill: none;\n }\n .cls-3 {\n fill: #7f0404;\n }\n .cls-4 {\n fill: ${i};\n }\n .cls-5 {\n fill: #a50404;\n }\n .cls-6 {\n fill: #cd0202;\n opacity: .9;\n }\n `})}),t.jsx("polygon",{className:"cls-6",points:"59.23 99.45 59.23 161.55 113.02 192.61 113.02 130.5 59.23 99.45"}),t.jsx("polygon",{className:"cls-5",points:"113.02 68.39 113.02 68.39 59.23 99.45 113.02 130.5 166.8 99.45 113.02 68.39"}),t.jsx("polygon",{className:"cls-3",points:"166.8 99.45 113.02 130.5 113.02 192.61 113.02 192.61 166.8 161.55 166.8 99.45"}),t.jsxs("g",{children:[t.jsx("path",{className:"cls-4",d:"m113.02,196.41l-57.08-32.95v-65.91l57.08-32.95,57.08,32.95v65.91l-57.08,32.95Zm-52.53-35.58l52.53,30.33,52.53-30.33v-60.66l-52.53-30.33-52.53,30.33v60.66Z"}),t.jsx("path",{className:"cls-4",d:"m113.02,261L0,195.75V65.25L113.02,0l113.02,65.25v130.5l-113.02,65.25ZM6.82,191.81l106.2,61.31,106.2-61.31v-122.62L113.02,7.88,6.82,69.19v122.62Z"}),t.jsx("rect",{className:"cls-4",x:"111.88",y:"3.94",width:"2.27",height:"63.28"}),t.jsx("rect",{className:"cls-4",x:"-.83",y:"176.82",width:"63.28",height:"2.27",transform:"translate(-84.84 39.24) rotate(-29.99)"}),t.jsx("rect",{className:"cls-4",x:"194.08",y:"146.32",width:"2.27",height:"63.28",transform:"translate(-56.51 258.05) rotate(-60)"}),t.jsx("rect",{className:"cls-4",x:"111.88",y:"130.5",width:"2.27",height:"126.56"}),t.jsx("rect",{className:"cls-4",x:"104.54",y:"97.72",width:"126.56",height:"2.27",transform:"translate(-26.95 97.14) rotate(-29.99)"}),t.jsx("rect",{className:"cls-4",x:"57.08",y:"35.58",width:"2.27",height:"126.56",transform:"translate(-56.51 99.84) rotate(-60)"})]})]})};const Jn=({onAddCredits:e,onCancel:n,isProcessing:s})=>{const[i,o]=r.useState(""),a=r.useRef(null);r.useEffect((()=>{a.current&&a.current.focus()}),[]);const c=""!==i&&Number(i)>0;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx("span",{style:{fontSize:"14px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"$"}),t.jsx("input",{ref:a,type:"number",placeholder:"0.00",value:i,onChange:e=>o(e.target.value),style:{width:"96px",textAlign:"right",padding:"8px 12px",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",outline:"none",backgroundColor:"#ffffff"},min:"1",step:"0.01"})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx("button",{onClick:n,style:{padding:"8px 12px",backgroundColor:"transparent",color:"#6b7280",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif",textDecoration:"none"},onMouseEnter:e=>{e.currentTarget.style.color="#111827"},onMouseLeave:e=>{e.currentTarget.style.color="#6b7280"},children:"Cancel"}),t.jsx("button",{onClick:()=>{const t=Number(i);t>0&&e(t)},disabled:s||!c,style:{padding:"8px 16px",backgroundColor:s||!c?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"500",cursor:s||!c?"not-allowed":"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{!s&&c&&(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{!s&&c&&(e.currentTarget.style.backgroundColor="#dc2626")},children:s?"Processing...":"Add Credits"})]})]})};e.EchoProvider=function({config:e,children:n}){const[s,i]=r.useState(null),[o,a]=r.useState(null),[c,l]=r.useState(null),[d,u]=r.useState(!0),[h,p]=r.useState(null),[g,f]=r.useState(null),[m,_]=r.useState(null),[w,y]=r.useState(!1);r.useEffect((()=>{y(!0)}),[]),r.useEffect((()=>{if(!w)return;const t=window.__echoUserManager;if(t)return void _(t);const r=e.apiUrl||"https://echo.merit.systems",n={authority:r,client_id:e.appId,redirect_uri:e.redirectUri||window.location.origin,scope:e.scope||"llm:invoke offline_access",automaticSilentRenew:!0,accessTokenExpiringNotificationTimeInSeconds:60,silentRequestTimeoutInSeconds:10,silent_redirect_uri:e.redirectUri||window.location.origin,includeIdTokenInSilentRenew:!1,validateSubOnSilentRenew:!0,loadUserInfo:!0,metadata:{authorization_endpoint:`${r}/api/oauth/authorize`,token_endpoint:`${r}/api/oauth/token`,userinfo_endpoint:`${r}/api/oauth/userinfo`,issuer:r},userStore:new N({store:window.localStorage})},s=new ue(n);window.__echoUserManager=s,_(s)}),[w,e.appId,e.apiUrl,e.redirectUri,e.scope]);const b=null!==s,S=r.useCallback((t=>new Bn({baseUrl:e.apiUrl||"https://echo.merit.systems",apiKey:t})),[e.apiUrl]),v=async e=>{const t=e.profile,r=function(e){return{name:_t(e.name),email:wt(e.email),picture:yt(e.picture)}}({name:(null==t?void 0:t.name)||(null==t?void 0:t.given_name)||(null==t?void 0:t.preferred_username)||(null==t?void 0:t.email)||"User",email:(null==t?void 0:t.email)||(null==t?void 0:t.preferred_username)||"",picture:(null==t?void 0:t.picture)||""});return{id:(null==t?void 0:t.sub)||(null==t?void 0:t.user_id)||(null==t?void 0:t.id)||"unknown",email:r.email,name:r.name||"User",picture:r.picture}},E=r.useCallback((async e=>{try{p(null);const t=await v(e);i(t),f(e.access_token);const r=S(e.access_token);await k(r)}catch(t){const e=t instanceof Error?t.message:"Failed to load user data";p(e),console.error("Error loading user data:",t)}}),[S]),k=r.useCallback((async t=>{try{const r=await t.getBalance(),n=await t.getFreeBalance(e.appId);a({totalPaid:r.totalPaid,totalSpent:r.totalSpent,balance:r.balance}),l(n)}catch(r){console.error("Error loading balance:",r)}}),[]),x=r.useCallback((async()=>{try{i(null),a(null),f(null),p(null),m&&await m.removeUser()}catch(e){console.warn("Error clearing auth state:",e)}}),[m]),T=r.useCallback((async(e,t,r)=>{if(!m)throw new Error("UserManager not initialized");const n=await m.getUser();if(!(null==n?void 0:n.access_token))throw new Error("Not authenticated");try{p(null);const s=S(n.access_token);return await s.getPaymentUrl(e,t||"Echo Credits",r)}catch(s){const e=s instanceof Error?s.message:"Failed to create payment link";throw p(e),new Error(e)}}),[m,S]);r.useEffect((()=>{(async()=>{if(w){if(m)try{u(!0),p(null);const e=await m.getUser();if(!window.location.search.includes("code=")||e&&!e.expired)e&&!e.expired&&await E(e);else{console.log("Authenticating with code");const e=await m.signinRedirectCallback();await E(e),window.history.replaceState({},document.title,window.location.pathname)}window.location.search.includes("code=")&&e&&!e.expired&&window.history.replaceState({},document.title,window.location.pathname)}catch(e){const t=e instanceof Error?e.message:"Authentication initialization failed";p(t),console.error("Auth initialization error:",e)}finally{u(!1)}}else u(!1)})()}),[w,m,E]),function({appId:e,client:t,onSuccess:n,onError:s}){r.useEffect((()=>{(async()=>{if("undefined"==typeof window)return;const r=new URLSearchParams(window.location.search),i=r.get("referralCode");if(!i)return;const o=await t.registerReferralCode(e,i);o&&(r.delete("referralCode"),window.history.replaceState({},"",`${window.location.pathname}${r.toString()?`?${r.toString()}`:""}`),o.success?null==n||n():null==s||s(o.message))})()}),[e,t,n,s])}({appId:e.appId,client:S(g||"")}),r.useEffect((()=>{if(!m)return;const e=e=>{E(e)};return m.events.addUserLoaded(e),()=>{m.events.removeUserLoaded(e)}}),[m,E,x]);const R={user:s,balance:o,freeTierBalance:c,isAuthenticated:b,isLoading:d,error:h,token:g,signIn:async()=>{if(!m)throw new Error("UserManager not initialized");await m.signinRedirect()},signOut:async()=>{try{if(!m)throw new Error("UserManager not initialized");i(null),a(null),f(null),p(null),await m.removeUser(),await m.signoutRedirect()}catch(e){console.warn("Sign out redirect failed:",e)}},refreshBalance:async()=>{if(!m)return;const e=await m.getUser();if(null==e?void 0:e.access_token){const t=S(e.access_token);await k(t)}},createPaymentLink:T,getToken:async()=>{if(!m)throw new Error("UserManager not initialized");const e=await m.getUser();return(null==e?void 0:e.access_token)||null},clearAuth:x};return t.jsx(Wn.Provider,{value:R,children:n})},e.EchoSignIn=function({onSuccess:e,onError:n,className:s="",children:i}){const{signIn:o,isAuthenticated:a,isLoading:c,user:l,error:d}=$n(),[u,h]=r.useState(!1);r.useEffect((()=>{a&&l&&e&&e(l)}),[a,l,e]),r.useEffect((()=>{d&&n&&n(new Error(d))}),[d,n]);const p=async()=>{try{await o()}catch(e){n&&n(e instanceof Error?e:new Error("Sign in failed"))}};return a?t.jsx("div",{className:`echo-signin-success ${s}`,children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",backgroundColor:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:"8px",color:"#334155",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",fontWeight:"800",width:"fit-content"},children:[t.jsx(Kn,{width:16,height:16,variant:"light"}),t.jsxs("span",{children:["Signed in as ",_t((null==l?void 0:l.name)||(null==l?void 0:l.email))]})]})}):t.jsxs("div",{className:`echo-signin ${s}`,children:[i?t.jsx("div",{onClick:p,style:{cursor:"pointer"},children:i}):t.jsxs("button",{onClick:p,disabled:c,className:"echo-signin-button",style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 20px",backgroundColor:c?"#f3f4f6":u?"#f1f5f9":"#ffffff",color:c?"#9ca3af":"#09090b",border:"1px solid #e5e7eb",borderRadius:"8px",cursor:c?"not-allowed":"pointer",fontSize:"14px",fontWeight:"800",fontFamily:"HelveticaNowDisplay, sans-serif",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",backdropFilter:"blur(8px)"},onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),children:[t.jsx(Kn,{width:16,height:16,variant:"light"}),t.jsx("span",{children:c?"Signing in...":"Sign in"})]}),d&&t.jsx("div",{className:"echo-signin-error",style:{marginTop:"12px",display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",fontWeight:"800",width:"fit-content"},children:t.jsx("span",{children:d})})]})},e.EchoTokenPurchase=function({amount:e=100,onPurchaseComplete:n,onError:s,className:i="",children:o}){const{createPaymentLink:a,isAuthenticated:c,balance:l,freeTierBalance:d,refreshBalance:u}=$n(),[h,p]=r.useState(!1),[g,f]=r.useState(null),[m,_]=r.useState(!1),[w,y]=r.useState(!1),b=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e),S=()=>{var e;return((null==(e=null==d?void 0:d.userSpendInfo)?void 0:e.amountLeft)||0)+((null==l?void 0:l.balance)||0)},v=async e=>{if(!c){const e=new Error("Please sign in to purchase tokens");return f(e.message),void(s&&s(e))}try{p(!0),f(null);const t=await a(e);await async function(e,t={}){const{onComplete:r,onCancel:n,onError:s}=t,i=yt(e);if(!i){const e=new Error("Invalid payment URL provided");throw null==s||s(e),e}try{const e=window.open(i,"echo-payment","width=600,height=700,scrollbars=yes,resizable=yes");return e&&!e.closed?new Promise((t=>{const s=()=>{try{if(e.closed)return null==r||r(),void t();setTimeout(s,1e3)}catch{null==r||r(),t()}};s(),setTimeout((()=>{e.close(),null==n||n(),t()}),6e5)})):confirm("Payment will open in a new tab. Click OK to continue, or Cancel to abort.")?(sessionStorage.setItem("echo_payment_flow","true"),window.location.href=i,new Promise((e=>{const t=()=>{"completed"===sessionStorage.getItem("echo_payment_flow")&&(sessionStorage.removeItem("echo_payment_flow"),null==r||r(),window.removeEventListener("focus",t),e())};window.addEventListener("focus",t),setTimeout((()=>{window.removeEventListener("focus",t),sessionStorage.removeItem("echo_payment_flow"),null==n||n(),e()}),18e5)}))):(null==n||n(),Promise.resolve())}catch(o){const e=o instanceof Error?o:new Error("Payment flow failed");throw null==s||s(e),e}}(t,{onComplete:async()=>{try{await u(),_(!1),y(!1),n&&l&&n(l)}catch(e){const t=e instanceof Error?e:new Error("Failed to refresh balance");f(t.message),s&&s(t)}finally{p(!1)}},onCancel:()=>{p(!1)},onError:e=>{f(e.message),s&&s(e),p(!1)}})}catch(t){const e=t instanceof Error?t:new Error("Failed to create payment link");f(e.message),s&&s(e),p(!1)}},E=()=>{_(!1),y(!1),f(null)};if(!c)return t.jsx("div",{className:`echo-token-purchase ${i}`,children:t.jsx("div",{className:"echo-token-purchase-unauthorized",style:{padding:"12px",backgroundColor:"#fef3c7",color:"#92400e",borderRadius:"8px",fontSize:"14px"},children:"Please sign in to purchase tokens"})});const k=()=>{const[e,n]=r.useState(!1);return t.jsxs("button",{onClick:()=>_(!0),className:`echo-token-purchase-compact ${i}`,style:{display:"flex",alignItems:"center",gap:"8px",padding:"10px 12px",borderRadius:"8px",backgroundColor:e?"#f1f5f9":"#ffffff",border:"1px solid #e5e7eb",color:"#09090b",fontSize:"14px",fontWeight:"800",cursor:"pointer",backdropFilter:"blur(8px)",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",height:"40px",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),children:[t.jsx(Kn,{width:16,height:16,variant:"light"}),t.jsx("span",{children:b(S())}),t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:e?"#dc2626":"#6b7280",transition:"color 0.2s ease"},children:[t.jsx("path",{d:"M7 7h10v10"}),t.jsx("path",{d:"M7 17 17 7"})]})]})},x=()=>t.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"16px"},onClick:e=>{e.target===e.currentTarget&&E()},children:t.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"0",width:"100%",maxWidth:"450px",maxHeight:"90vh",overflow:"hidden",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",flexDirection:"column",minHeight:"320px"},children:[t.jsx("div",{style:{padding:"24px 24px 0 24px",marginBottom:"24px"},children:t.jsx("h2",{style:{fontSize:"18px",fontWeight:"500",color:"#111827",margin:0,fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Credits"})}),t.jsxs("div",{style:{marginBottom:"24px",padding:"0 24px",flex:"1 1 0%",display:"flex",flexDirection:"column"},children:[d&&t.jsxs("div",{style:{marginBottom:"20px"},children:[t.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 4px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Free Tier Available"}),t.jsx("p",{style:{fontSize:"24px",fontWeight:"600",color:"#111827",margin:"0 0 8px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:b(S())}),d.userSpendInfo&&d.userSpendInfo.spendLimit&&t.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:[t.jsxs("div",{style:{marginBottom:"6px"},children:[b(d.userSpendInfo.amountSpent)," ","of"," ",b(d.userSpendInfo.amountLeft+d.userSpendInfo.amountSpent)," ","used"]}),t.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#f3f4f6",borderRadius:"2px",overflow:"hidden"},children:t.jsx("div",{style:{width:`${Math.min(100,d.userSpendInfo.amountSpent/d.userSpendInfo.spendLimit*100)}%`,height:"100%",backgroundColor:"#dc2626"}})})]})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsxs("div",{style:{flex:"1 1 0%",minWidth:"0"},children:[t.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 4px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Paid Credits Balance"}),t.jsx("p",{style:{fontSize:"30px",fontWeight:"700",color:"#111827",margin:0,fontFamily:"HelveticaNowDisplay, sans-serif"},children:l?b(l.balance):"$0.00"})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"12px"},children:w?t.jsx(Jn,{onAddCredits:v,onCancel:()=>y(!1),isProcessing:h}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>v(10),disabled:h,style:{padding:"10px 24px",backgroundColor:h?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"500",cursor:h?"not-allowed":"pointer",transition:"background-color 0.2s ease",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{h||(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{h||(e.currentTarget.style.backgroundColor="#dc2626")},children:h?"Processing...":"Add $10 Credits"}),t.jsx("button",{onClick:()=>y(!0),style:{fontSize:"14px",color:"#6b7280",backgroundColor:"transparent",border:"none",textDecoration:"underline",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.color="#111827"},onMouseLeave:e=>{e.currentTarget.style.color="#6b7280"},children:"Choose different amount"})]})})]})]}),g&&t.jsx("div",{style:{margin:"0 24px 16px 24px",padding:"8px 12px",backgroundColor:"#fee2e2",color:"#dc2626",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif"},children:g}),t.jsx("div",{style:{padding:"16px 24px 24px 24px",display:"flex",justifyContent:"flex-end",marginTop:"auto"},children:t.jsx("button",{onClick:E,style:{padding:"8px 16px",backgroundColor:"#f3f4f6",color:"#374151",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#e5e7eb"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#f3f4f6"},children:"Close"})})]})});return t.jsxs(t.Fragment,{children:[o?t.jsx("div",{onClick:()=>_(!0),style:{cursor:"pointer"},children:o}):t.jsx(k,{}),m&&t.jsx(x,{})]})},e.Logo=Kn,e.useEcho=$n,e.useEchoOpenAI=function(e={}){const{baseURL:t="https://echo.router.merit.systems",enabled:n=!0}=e,{token:s,isAuthenticated:i}=$n(),[o,a]=r.useState(void 0),[c,l]=r.useState(null),[d,u]=r.useState(!1),h=r.useRef(null);return r.useEffect((()=>{if(h.current&&h.current.abort(),!n||!s||!i)return a(void 0),l(null),void u(!1);return(async()=>{const e=new AbortController;h.current=e,u(!0),l(null);try{if(e.signal.aborted)return;const{default:r}=await import("openai");if(e.signal.aborted)return;const n=new r({apiKey:s,baseURL:t,dangerouslyAllowBrowser:!0});e.signal.aborted||a(n)}catch(r){if(!e.signal.aborted){const e=r instanceof Error?r.message:"Failed to load OpenAI";e.includes("Cannot resolve module")||e.includes("Module not found")||e.includes("openai")?l("OpenAI package not found. Please install it with: pnpm add openai"):l(`Failed to initialize OpenAI client: ${e}`),console.error("Error loading OpenAI:",r),a(void 0)}}finally{e.signal.aborted||u(!1)}})(),()=>{h.current&&h.current.abort()}}),[s,i,t,n]),{openai:o,isReady:void 0!==o&&!d,error:c,isLoading:d}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react/jsx-runtime"),require("react")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).EchoReactSDK={},e.jsxRuntime,e.React)}(this,(function(e,t,r){"use strict";var n,s=Object.defineProperty,i=(e,t,r)=>((e,t,r)=>t in e?s(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);class o extends Error{}function a(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let r=t.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r})))}(t)}catch(r){return atob(t)}}o.prototype.name="InvalidTokenError";var c,l,u,d={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},h=(e=>(e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG",e))(h||{});(u=h||(h={})).reset=function(){c=3,l=d},u.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");c=e},u.setLogger=function(e){l=e};var p=class e{constructor(e){this._name=e}debug(...t){c>=4&&l.debug(e._format(this._name,this._method),...t)}info(...t){c>=3&&l.info(e._format(this._name,this._method),...t)}warn(...t){c>=2&&l.warn(e._format(this._name,this._method),...t)}error(...t){c>=1&&l.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,r){const n=new e(`${t}.${r}`);return n.debug("begin"),n}static _format(e,t){const r=`[${e}]`;return t?`${r} ${t}:`:r}static debug(t,...r){c>=4&&l.debug(e._format(t),...r)}static info(t,...r){c>=3&&l.info(e._format(t),...r)}static warn(t,...r){c>=2&&l.warn(e._format(t),...r)}static error(t,...r){c>=1&&l.error(e._format(t),...r)}};h.reset();var f=class{static decode(e){try{return function(e,t){if("string"!=typeof e)throw new o("Invalid token specified: must be a string");t||(t={});const r=!0===t.header?0:1,n=e.split(".")[r];if("string"!=typeof n)throw new o(`Invalid token specified: missing part #${r+1}`);let s;try{s=a(n)}catch(tn){throw new o(`Invalid token specified: invalid base64 for part #${r+1} (${tn.message})`)}try{return JSON.parse(s)}catch(tn){throw new o(`Invalid token specified: invalid json for part #${r+1} (${tn.message})`)}}(e)}catch(t){throw p.error("JwtUtils.decode",t),t}}static async generateSignedJwt(e,t,r){const n=`${_.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${_.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,s=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},r,(new TextEncoder).encode(n));return`${n}.${_.encodeBase64Url(new Uint8Array(s))}`}},g=e=>btoa([...new Uint8Array(e)].map((e=>String.fromCharCode(e))).join("")),m=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(+t^e._randomWord()&15>>+t/4).toString(16))).replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return g(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw p.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const r=(new TextEncoder).encode([e,t].join(":"));return g(r)}static async hash(e,t){const r=(new TextEncoder).encode(t),n=await crypto.subtle.digest(e,r);return new Uint8Array(n)}static async customCalculateJwkThumbprint(t){let r;switch(t.kty){case"RSA":r={e:t.e,kty:t.kty,n:t.n};break;case"EC":r={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":r={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":r={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const n=await e.hash("SHA-256",JSON.stringify(r));return e.encodeBase64Url(n)}static async generateDPoPProof({url:t,accessToken:r,httpMethod:n,keyPair:s,nonce:i}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=n?n:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};r&&(o=await e.hash("SHA-256",r),a=e.encodeBase64Url(o),c.ath=a),i&&(c.nonce=i);try{const e=await crypto.subtle.exportKey("jwk",s.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await f.generateSignedJwt(t,c,s.privateKey)}catch(l){throw l instanceof TypeError?new Error(`Error exporting dpop public key: ${l.message}`):l}}static async generateDPoPJkt(t){try{const r=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(r)}catch(r){throw r instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${r.message}`):r}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};m.encodeBase64Url=e=>g(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var _=m,w=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new p(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},y=class{static center({...e}){var t;return null==e.width&&(e.width=null!=(t=[800,720,600,480].find((e=>e<=window.outerWidth/1.618)))?t:360),null!=e.left||(e.left=Math.max(0,Math.round(window.screenX+(window.outerWidth-e.width)/2))),null!=e.height&&(null!=e.top||(e.top=Math.max(0,Math.round(window.screenY+(window.outerHeight-e.height)/2)))),e}static serialize(e){return Object.entries(e).filter((([,e])=>null!=e)).map((([e,t])=>`${e}=${"boolean"!=typeof t?t:t?"yes":"no"}`)).join(",")}},b=class e extends w{constructor(){super(...arguments),this._logger=new p(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const r=this._logger.create("init");t=Math.max(Math.floor(t),1);const n=e.getEpochTime()+t;if(this.expiration===n&&this._timerHandle)return void r.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),r.debug("using duration",t),this._expiration=n;const s=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*s)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},S=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const r=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(r.slice(1))}},v=";",E=class extends Error{constructor(e,t){var r,n,s;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw p.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(r=e.error_description)?r:null,this.error_uri=null!=(n=e.error_uri)?n:null,this.state=e.userState,this.session_state=null!=(s=e.session_state)?s:null,this.url_state=e.url_state}},k=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},R=class{constructor(e){this._logger=new p("AccessTokenEvents"),this._expiringTimer=new b("Access token expiring"),this._expiredTimer=new b("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const r=e.expires_in;if(t.debug("access token present, remaining duration:",r),r>0){let e=r-this._expiringNotificationTimeInSeconds;e<=0&&(e=1),t.debug("registering expiring timer, raising in",e,"seconds"),this._expiringTimer.init(e)}else t.debug("canceling existing expiring timer because we're past expiration."),this._expiringTimer.cancel();const n=r+1;t.debug("registering expired timer, raising in",n,"seconds"),this._expiredTimer.init(n)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},T=class{constructor(e,t,r,n,s){this._callback=e,this._client_id=t,this._intervalInSeconds=n,this._stopOnError=s,this._logger=new p("CheckSessionIFrame"),this._timer=null,this._session_state=null,this._message=e=>{e.origin===this._frame_origin&&e.source===this._frame.contentWindow&&("error"===e.data?(this._logger.error("error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===e.data?(this._logger.debug("changed message from check session op iframe"),this.stop(),this._callback()):this._logger.debug(e.data+" message from check session op iframe"))};const i=new URL(r);this._frame_origin=i.origin,this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="fixed",this._frame.style.left="-1000px",this._frame.style.top="0",this._frame.width="0",this._frame.height="0",this._frame.src=i.href}load(){return new Promise((e=>{this._frame.onload=()=>{e()},window.document.body.appendChild(this._frame),window.addEventListener("message",this._message,!1)}))}start(e){if(this._session_state===e)return;this._logger.create("start"),this.stop(),this._session_state=e;const t=()=>{this._frame.contentWindow&&this._session_state&&this._frame.contentWindow.postMessage(this._client_id+" "+this._session_state,this._frame_origin)};t(),this._timer=setInterval(t,1e3*this._intervalInSeconds)}stop(){this._logger.create("stop"),this._session_state=null,this._timer&&(clearInterval(this._timer),this._timer=null)}},x=class{constructor(){this._logger=new p("InMemoryWebStorage"),this._data={}}clear(){this._logger.create("clear"),this._data={}}getItem(e){return this._logger.create(`getItem('${e}')`),this._data[e]}setItem(e,t){this._logger.create(`setItem('${e}')`),this._data[e]=t}removeItem(e){this._logger.create(`removeItem('${e}')`),delete this._data[e]}get length(){return Object.getOwnPropertyNames(this._data).length}key(e){return Object.getOwnPropertyNames(this._data)[e]}},O=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},A=class{constructor(e=[],t=null,r={}){this._jwtHandler=t,this._extraHeaders=r,this._logger=new p("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:r,...n}=t;if(!r)return await fetch(e,n);const s=new AbortController,i=setTimeout((()=>s.abort()),1e3*r);try{return await fetch(e,{...t,signal:s.signal})}catch(o){if(o instanceof DOMException&&"AbortError"===o.name)throw new k("Network timed out");throw o}finally{clearTimeout(i)}}async getJson(e,{token:t,credentials:r,timeoutInSeconds:n}={}){const s=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let o;t&&(s.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this._appendExtraHeaders(i);try{s.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:i,timeoutInSeconds:n,credentials:r})}catch(l){throw s.error("Network Error"),l}s.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find((e=>a.startsWith(e)))&&s.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(l){if(s.error("Error parsing JSON response",l),o.ok)throw l;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(s.error("Error from server:",c),c.error)throw new E(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:r,timeoutInSeconds:n,initCredentials:s,extraHeaders:i}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...i};let c;void 0!==r&&(a.Authorization="Basic "+r),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:n,credentials:s})}catch(h){throw o.error("Network error"),h}o.debug("HTTP response received, status",c.status);const l=c.headers.get("Content-Type");if(l&&!this._contentTypes.find((e=>l.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=l?l:"undefined"}, from URL: ${e}`);const u=await c.text();let d={};if(u)try{d=JSON.parse(u)}catch(h){if(o.error("Error parsing JSON response",h),c.ok)throw h;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",d),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new O(e,`${JSON.stringify(d)}`)}if(d.error)throw new E(d,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(d)}`)}return d}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),r=Object.keys(this._extraHeaders),n=["accept","content-type"],s=["authorization"];0!==r.length&&r.forEach((r=>{if(n.includes(r.toLocaleLowerCase()))return void t.warn("Protected header could not be set",r,n);if(s.includes(r.toLocaleLowerCase())&&Object.keys(e).includes(r))return void t.warn("Header could not be overridden",r,s);const i="function"==typeof this._extraHeaders[r]?this._extraHeaders[r]():this._extraHeaders[r];i&&""!==i&&(e[r]=i)}))}},C=class{constructor(e){this._settings=e,this._logger=new p("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new A(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const r=this._logger.create(`_getMetadataProperty('${e}')`),n=await this.getMetadata();if(r.debug("resolved"),void 0===n[e]){if(!0===t)return void r.warn("Metadata does not contain optional property");r.throw(new Error("Metadata does not contain property "+e))}return n[e]}async getSigningKeys(){const e=this._logger.create("getSigningKeys");if(this._signingKeys)return e.debug("returning signingKeys from cache"),this._signingKeys;const t=await this.getKeysEndpoint(!1);e.debug("got jwks_uri",t);const r=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",r),!Array.isArray(r.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=r.keys,this._signingKeys}},N=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new p("WebStorageStateStore"),this._store=t,this._prefix=e}async set(e,t){this._logger.create(`set('${e}')`),e=this._prefix+e,await this._store.setItem(e,t)}async get(e){this._logger.create(`get('${e}')`),e=this._prefix+e;return await this._store.getItem(e)}async remove(e){this._logger.create(`remove('${e}')`),e=this._prefix+e;const t=await this._store.getItem(e);return await this._store.removeItem(e),t}async getAllKeys(){this._logger.create("getAllKeys");const e=await this._store.length,t=[];for(let r=0;r<e;r++){const e=await this._store.key(r);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},P=class{constructor({authority:e,metadataUrl:t,metadata:r,signingKeys:n,metadataSeed:s,client_id:i,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:l,post_logout_redirect_uri:u,client_authentication:d="client_secret_post",prompt:h,display:p,max_age:f,ui_locales:g,acr_values:m,resource:_,response_mode:w,filterProtocolClaims:y=!0,loadUserInfo:b=!1,requestTimeoutInSeconds:S,staleStateAgeInSeconds:v=900,mergeClaimsStrategy:E={array:"replace"},disablePKCE:k=!1,stateStore:R,revokeTokenAdditionalContentTypes:T,fetchRequestCredentials:O,refreshTokenAllowedScope:A,extraQueryParams:C={},extraTokenParams:P={},extraHeaders:I={},dpop:U,omitScopeWhenRequesting:j=!1}){var L;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=r,this.metadataSeed=s,this.signingKeys=n,this.client_id=i,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=l,this.post_logout_redirect_uri=u,this.client_authentication=d,this.prompt=h,this.display=p,this.max_age=f,this.ui_locales=g,this.acr_values=m,this.resource=_,this.response_mode=w,this.filterProtocolClaims=null==y||y,this.loadUserInfo=!!b,this.staleStateAgeInSeconds=v,this.mergeClaimsStrategy=E,this.omitScopeWhenRequesting=j,this.disablePKCE=!!k,this.revokeTokenAdditionalContentTypes=T,this.fetchRequestCredentials=O||"same-origin",this.requestTimeoutInSeconds=S,R)this.stateStore=R;else{const e="undefined"!=typeof window?window.localStorage:new x;this.stateStore=new N({store:e})}if(this.refreshTokenAllowedScope=A,this.extraQueryParams=C,this.extraTokenParams=P,this.extraHeaders=I,this.dpop=U,this.dpop&&!(null==(L=this.dpop)?void 0:L.store))throw new Error("A DPoPStore is required when dpop is enabled")}},I=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new p("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const r=f.decode(e);return t.debug("JWT decoding successful"),r}catch(r){throw t.error("Error parsing JWT response"),r}},this._jsonService=new A(void 0,this._getClaimsFromJwt,this._settings.extraHeaders)}async getClaims(e){const t=this._logger.create("getClaims");e||this._logger.throw(new Error("No token passed"));const r=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",r);const n=await this._jsonService.getJson(r,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",n),n}},U=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new p("TokenClient"),this._jsonService=new A(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:r=this._settings.client_id,client_secret:n=this._settings.client_secret,extraHeaders:s,...i}){const o=this._logger.create("exchangeCode");r||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),i.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[d,h]of Object.entries(i))null!=h&&a.set(d,h);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==n)throw o.throw(new Error("A client_secret is required")),null;c=_.generateBasicAuth(r,n);break;case"client_secret_post":a.append("client_id",r),n&&a.append("client_secret",n)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const u=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),u}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,scope:n=this._settings.scope,...s}){const i=this._logger.create("exchangeCredentials");t||i.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",n);for(const[u,d]of Object.entries(s))null!=d&&o.set(u,d);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw i.throw(new Error("A client_secret is required")),null;a=_.generateBasicAuth(t,r);break;case"client_secret_post":o.append("client_id",t),r&&o.append("client_secret",r)}const c=await this._metadataService.getTokenEndpoint(!1);i.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return i.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:r=this._settings.client_secret,timeoutInSeconds:n,extraHeaders:s,...i}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),i.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[d,h]of Object.entries(i))Array.isArray(h)?h.forEach((e=>a.append(d,e))):null!=h&&a.set(d,h);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==r)throw o.throw(new Error("A client_secret is required")),null;c=_.generateBasicAuth(t,r);break;case"client_secret_post":a.append("client_id",t),r&&a.append("client_secret",r)}const l=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const u=await this._jsonService.postForm(l,{body:a,basicAuth:c,timeoutInSeconds:n,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:s});return o.debug("got response"),u}async revoke(e){var t;const r=this._logger.create("revoke");e.token||r.throw(new Error("A token is required"));const n=await this._metadataService.getRevocationEndpoint(!1);r.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const s=new URLSearchParams;for(const[i,o]of Object.entries(e))null!=o&&s.set(i,o);s.set("client_id",this._settings.client_id),this._settings.client_secret&&s.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(n,{body:s,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),r.debug("got response")}},j=class{constructor(e,t,r){this._settings=e,this._metadataService=t,this._claimsService=r,this._logger=new p("ResponseValidator"),this._userInfoService=new I(this._settings,this._metadataService),this._tokenClient=new U(this._settings,this._metadataService)}async validateSigninResponse(e,t,r){const n=this._logger.create("validateSigninResponse");this._processSigninState(e,t),n.debug("state processed"),await this._processCode(e,t,r),n.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),n.debug("claims processed")}async validateCredentialsResponse(e,t){const r=this._logger.create("validateCredentialsResponse"),n=e.isOpenId&&!!e.id_token;n&&this._validateIdTokenAttributes(e),r.debug("tokens validated"),await this._processClaims(e,t,n),r.debug("claims processed")}async validateRefreshResponse(e,t){const r=this._logger.create("validateRefreshResponse");e.userState=t.data,null!=e.session_state||(e.session_state=t.session_state),null!=e.scope||(e.scope=t.scope),e.isOpenId&&e.id_token&&(this._validateIdTokenAttributes(e,t.id_token),r.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const n=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,n),r.debug("claims processed")}validateSignoutResponse(e,t){const r=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&r.throw(new Error("State does not match")),r.debug("state validated"),e.userState=t.data,e.error)throw r.warn("Response was error",e.error),new E(e)}_processSigninState(e,t){const r=this._logger.create("_processSigninState");if(t.id!==e.state&&r.throw(new Error("State does not match")),t.client_id||r.throw(new Error("No client_id on state")),t.authority||r.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&r.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&r.throw(new Error("client_id mismatch on settings vs. signin state")),r.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw r.warn("Response was error",e.error),new E(e);t.code_verifier&&!e.code&&r.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,r=!0){const n=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void n.debug("not loading user info");n.debug("loading user info");const s=await this._userInfoService.getClaims(e.access_token);n.debug("user info claims received from user info endpoint"),r&&s.sub!==e.profile.sub&&n.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(s)),n.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,r){const n=this._logger.create("_processCode");if(e.code){n.debug("Validating code");const s=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:r,...t.extraTokenParams});Object.assign(e,s)}else n.debug("No code to process")}_validateIdTokenAttributes(e,t){var r;const n=this._logger.create("_validateIdTokenAttributes");n.debug("decoding ID Token JWT");const s=f.decode(null!=(r=e.id_token)?r:"");if(s.sub||n.throw(new Error("ID Token is missing a subject claim")),t){const e=f.decode(t);s.sub!==e.sub&&n.throw(new Error("sub in id_token does not match current sub")),s.auth_time&&s.auth_time!==e.auth_time&&n.throw(new Error("auth_time in id_token does not match original auth_time")),s.azp&&s.azp!==e.azp&&n.throw(new Error("azp in id_token does not match original azp")),!s.azp&&e.azp&&n.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=s}},L=class e{constructor(e){this.id=e.id||_.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=b.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new p("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return p.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,r){const n=p.createStatic("State","clearStaleState"),s=b.getEpochTime()-r,i=await t.getAllKeys();n.debug("got keys",i);for(let a=0;a<i.length;a++){const r=i[a],c=await t.get(r);let l=!1;if(c)try{const t=await e.fromStorageString(c);n.debug("got item from key:",r,t.created),t.created<=s&&(l=!0)}catch(o){n.error("Error parsing state for key:",r,o),l=!0}else n.debug("no item in storage for key:",r),l=!0;l&&(n.debug("removed item for key:",r),t.remove(r))}}},D=class e extends L{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const r=!0===t.code_verifier?_.generateCodeVerifier():t.code_verifier||void 0,n=r?await _.generateCodeChallenge(r):void 0;return new e({...t,code_verifier:r,code_challenge:n})}toStorageString(){return new p("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){p.createStatic("SigninState","fromStorageString");const r=JSON.parse(t);return e.create(r)}},F=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:r,client_id:n,redirect_uri:s,response_type:i,scope:o,state_data:a,response_mode:c,request_type:l,client_secret:u,nonce:d,url_state:h,resource:p,skipUserInfo:f,extraQueryParams:g,extraTokenParams:m,disablePKCE:_,dpopJkt:w,omitScopeWhenRequesting:y,...b}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!n)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!s)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!i)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!r)throw this._logger.error("create: No authority passed"),new Error("authority");const S=await D.create({data:a,request_type:l,url_state:h,code_verifier:!_,client_id:n,authority:r,redirect_uri:s,response_mode:c,client_secret:u,scope:o,extraTokenParams:m,skipUserInfo:f}),E=new URL(t);E.searchParams.append("client_id",n),E.searchParams.append("redirect_uri",s),E.searchParams.append("response_type",i),y||E.searchParams.append("scope",o),d&&E.searchParams.append("nonce",d),w&&E.searchParams.append("dpop_jkt",w);let k=S.id;if(h&&(k=`${k}${v}${h}`),E.searchParams.append("state",k),S.code_challenge&&(E.searchParams.append("code_challenge",S.code_challenge),E.searchParams.append("code_challenge_method","S256")),p){(Array.isArray(p)?p:[p]).forEach((e=>E.searchParams.append("resource",e)))}for(const[e,v]of Object.entries({response_mode:c,...b,...g}))null!=v&&E.searchParams.append(e,v.toString());return new e({url:E.href,state:S})}};F._logger=new p("SigninRequest");var M=F,q=class{constructor(e){if(this.access_token="",this.token_type="",this.profile={},this.state=e.get("state"),this.session_state=e.get("session_state"),this.state){const e=decodeURIComponent(this.state).split(v);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(v))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri"),this.code=e.get("code")}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-b.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+b.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},B=class{constructor({url:e,state_data:t,id_token_hint:r,post_logout_redirect_uri:n,extraQueryParams:s,request_type:i,client_id:o,url_state:a}){if(this._logger=new p("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(r&&c.searchParams.append("id_token_hint",r),o&&c.searchParams.append("client_id",o),n&&(c.searchParams.append("post_logout_redirect_uri",n),t||a)){this.state=new L({data:t,request_type:i,url_state:a});let e=this.state.id;a&&(e=`${e}${v}${a}`),c.searchParams.append("state",e)}for(const[l,u]of Object.entries({...s}))null!=u&&c.searchParams.append(l,u.toString());this.url=c.href}},H=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(v);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(v))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},z=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],W=["sub","iss","aud","exp","iat"],$=class{constructor(e){this._settings=e,this._logger=new p("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:z;for(const r of e)W.includes(r)||delete t[r]}return t}mergeClaims(e,t){const r={...e};for(const[n,s]of Object.entries(t))if(r[n]!==s)if(Array.isArray(r[n])||Array.isArray(s))if("replace"==this._settings.mergeClaimsStrategy.array)r[n]=s;else{const e=Array.isArray(r[n])?r[n]:[r[n]];for(const t of Array.isArray(s)?s:[s])e.includes(t)||e.push(t);r[n]=e}else"object"==typeof r[n]&&"object"==typeof s?r[n]=this.mergeClaims(r[n],s):r[n]=s;return r}},K=class{constructor(e,t){this.keys=e,this.nonce=t}},J=class{constructor(e,t){this._logger=new p("OidcClient"),this.settings=e instanceof P?e:new P(e),this.metadataService=null!=t?t:new C(this.settings),this._claimsService=new $(this.settings),this._validator=new j(this.settings,this.metadataService,this._claimsService),this._tokenClient=new U(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:r,request_type:n,id_token_hint:s,login_hint:i,skipUserInfo:o,nonce:a,url_state:c,response_type:l=this.settings.response_type,scope:u=this.settings.scope,redirect_uri:d=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:p=this.settings.display,max_age:f=this.settings.max_age,ui_locales:g=this.settings.ui_locales,acr_values:m=this.settings.acr_values,resource:_=this.settings.resource,response_mode:w=this.settings.response_mode,extraQueryParams:y=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams,dpopJkt:S,omitScopeWhenRequesting:v=this.settings.omitScopeWhenRequesting}){const E=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const k=await this.metadataService.getAuthorizationEndpoint();E.debug("Received authorization endpoint",k);const R=await M.create({url:k,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:d,response_type:l,scope:u,state_data:e,url_state:c,prompt:h,display:p,max_age:f,ui_locales:g,id_token_hint:s,login_hint:i,acr_values:m,dpopJkt:S,resource:_,request:t,request_uri:r,extraQueryParams:y,extraTokenParams:b,request_type:n,response_mode:w,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:v});await this.clearStaleState();const T=R.state;return await this.settings.stateStore.set(T.id,T.toStorageString()),R}async readSigninResponseState(e,t=!1){const r=this._logger.create("readSigninResponseState"),n=new q(S.readParams(e,this.settings.response_mode));if(!n.state)throw r.throw(new Error("No state in response")),null;const s=await this.settings.stateStore[t?"remove":"get"](n.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await D.fromStorageString(s),response:n}}async processSigninResponse(e,t,r=!0){const n=this._logger.create("processSigninResponse"),{state:s,response:i}=await this.readSigninResponseState(e,r);if(n.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(i,s,t)}catch(o){if(!(o instanceof O&&this.settings.dpop))throw o;{const e=await this.getDpopProof(this.settings.dpop.store,o.nonce);t.DPoP=e,await this._validator.validateSigninResponse(i,s,t)}}return i}async getDpopProof(e,t){let r,n;return(await e.getAllKeys()).includes(this.settings.client_id)?(n=await e.get(this.settings.client_id),n.nonce!==t&&t&&(n.nonce=t,await e.set(this.settings.client_id,n))):(r=await _.generateDPoPKeys(),n=new K(r,t),await e.set(this.settings.client_id,n)),await _.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:n.keys,nonce:n.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r=!1,extraTokenParams:n={}}){const s=await this._tokenClient.exchangeCredentials({username:e,password:t,...n}),i=new q(new URLSearchParams);return Object.assign(i,s),await this._validator.validateCredentialsResponse(i,r),i}async useRefreshToken({state:e,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,extraTokenParams:i}){var o;const a=this._logger.create("useRefreshToken");let c,l;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);s={...s,DPoP:e}}try{l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,...i})}catch(d){if(!(d instanceof O&&this.settings.dpop))throw d;s.DPoP=await this.getDpopProof(this.settings.dpop.store,d.nonce),l=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:r,timeoutInSeconds:n,extraHeaders:s,...i})}const u=new q(new URLSearchParams);return Object.assign(u,l),a.debug("validating response",u),await this._validator.validateRefreshResponse(u,{...e,scope:c}),u}async createSignoutRequest({state:e,id_token_hint:t,client_id:r,request_type:n,url_state:s,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),r||!i||t||(r=this.settings.client_id);const l=new B({url:c,id_token_hint:t,client_id:r,post_logout_redirect_uri:i,state_data:e,extraQueryParams:o,request_type:n,url_state:s});await this.clearStaleState();const u=l.state;return u&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(u.id,u.toStorageString())),l}async readSignoutResponseState(e,t=!1){const r=this._logger.create("readSignoutResponseState"),n=new H(S.readParams(e,this.settings.response_mode));if(!n.state){if(r.debug("No state in response"),n.error)throw r.warn("Response was error:",n.error),new E(n);return{state:void 0,response:n}}const s=await this.settings.stateStore[t?"remove":"get"](n.state);if(!s)throw r.throw(new Error("No matching state found in storage")),null;return{state:await L.fromStorageString(s),response:n}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:r,response:n}=await this.readSignoutResponseState(e,!0);return r?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(n,r)):t.debug("No state from storage; skipping response validation"),n}clearStaleState(){return this._logger.create("clearStaleState"),L.clearStaleState(this.settings.stateStore,this.settings.staleStateAgeInSeconds)}async revokeToken(e,t){return this._logger.create("revokeToken"),await this._tokenClient.revoke({token:e,token_type_hint:t})}},V=class{constructor(e){this._userManager=e,this._logger=new p("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const r=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,r.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,r.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){r.debug("initializing check session iframe");const n=this._userManager.settings.client_id,s=this._userManager.settings.checkSessionIntervalInSeconds,i=this._userManager.settings.stopCheckSessionOnError,o=new T(this._callback,n,e,s,i);await o.load(),this._checkSessionIFrame=o,o.start(t)}else r.warn("no check session iframe found in the metadata")}catch(n){r.error("Error from getCheckSessionIframe:",n instanceof Error?n.message:n)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval((async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(r){e.error("error from querySessionStatus",r instanceof Error?r.message:r)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let r=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(r=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),r?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch((e=>{this._logger.error(e)}))}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},G=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-b.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+b.getEpochTime())}get expired(){const e=this.expires_in;if(void 0!==e)return e<=0}get scopes(){var e,t;return null!=(t=null==(e=this.scope)?void 0:e.split(" "))?t:[]}toStorageString(){return new p("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return p.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},X="oidc-client",Q=class{constructor(){this._abort=new w("Window navigation aborted"),this._disposeHandlers=new Set,this._window=null}async navigate(e){const t=this._logger.create("navigate");if(!this._window)throw new Error("Attempted to navigate on a disposed window");t.debug("setting URL in window"),this._window.location.replace(e.url);const{url:r,keepOpen:n}=await new Promise(((r,n)=>{const s=s=>{var i;const o=s.data,a=null!=(i=e.scriptOrigin)?i:window.location.origin;if(s.origin===a&&(null==o?void 0:o.source)===X){try{const r=S.readParams(o.url,e.response_mode).get("state");if(r||t.warn("no state found in response url"),s.source!==this._window&&r!==e.state)return}catch{this._dispose(),n(new Error("Invalid response from window"))}r(o)}};window.addEventListener("message",s,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",s,!1)));const i=new BroadcastChannel(`oidc-client-popup-${e.state}`);i.addEventListener("message",s,!1),this._disposeHandlers.add((()=>i.close())),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),n(e)})))}));return t.debug("got response from window"),this._dispose(),n||this.close(),{url:r}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,r=!1,n=window.location.origin){const s={source:X,url:t,keepOpen:r},i=new p("_notifyParent");if(e)i.debug("With parent. Using parent.postMessage."),e.postMessage(s,n);else{i.debug("No parent. Using BroadcastChannel.");const e=new URL(t).searchParams.get("state");if(!e)throw new Error("No parent and no state in URL. Can't complete notification.");const r=new BroadcastChannel(`oidc-client-popup-${e}`);r.postMessage(s),r.close()}}},Y={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Z="_blank",ee=60,te=2,re=class extends P{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:r=e.post_logout_redirect_uri,popupWindowFeatures:n=Y,popupWindowTarget:s=Z,redirectMethod:i="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:l,silent_redirect_uri:u=e.redirect_uri,silentRequestTimeoutInSeconds:d,automaticSilentRenew:h=!0,validateSubOnSilentRenew:p=!0,includeIdTokenInSilentRenew:f=!1,monitorSession:g=!1,monitorAnonymousSession:m=!1,checkSessionIntervalInSeconds:_=te,query_status_response_type:w="code",stopCheckSessionOnError:y=!0,revokeTokenTypes:b=["access_token","refresh_token"],revokeTokensOnSignout:S=!1,includeIdTokenInSilentSignout:v=!1,accessTokenExpiringNotificationTimeInSeconds:E=ee,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=r,this.popupWindowFeatures=n,this.popupWindowTarget=s,this.redirectMethod=i,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=u,this.silentRequestTimeoutInSeconds=d||l||10,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=p,this.includeIdTokenInSilentRenew=f,this.monitorSession=g,this.monitorAnonymousSession=m,this.checkSessionIntervalInSeconds=_,this.stopCheckSessionOnError=y,this.query_status_response_type=w,this.revokeTokenTypes=b,this.revokeTokensOnSignout=S,this.includeIdTokenInSilentSignout=v,this.accessTokenExpiringNotificationTimeInSeconds=E,k)this.userStore=k;else{const e="undefined"!=typeof window?window.sessionStorage:new x;this.userStore=new N({store:e})}}},ne=class e extends Q{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new p("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout((()=>{this._abort.raise(new k("IFrame timed out without a response"))}),1e3*this._timeoutInSeconds);return this._disposeHandlers.add((()=>clearTimeout(t))),await super.navigate(e)}close(){var e;this._frame&&(this._frame.parentNode&&(this._frame.addEventListener("load",(e=>{var t;const r=e.target;null==(t=r.parentNode)||t.removeChild(r),this._abort.raise(new Error("IFrame removed from DOM"))}),!0),null==(e=this._frame.contentWindow)||e.location.replace("about:blank")),this._frame=null),this._window=null}static notifyParent(e,t){return super._notifyParent(window.parent,e,!1,t)}},se=class{constructor(e){this._settings=e,this._logger=new p("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new ne({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),ne.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},ie=class extends Q{constructor({popupWindowTarget:e=Z,popupWindowFeatures:t={},popupSignal:r}){super(),this._logger=new p("PopupWindow");const n=y.center({...Y,...t});this._window=window.open(void 0,e,y.serialize(n)),r&&r.addEventListener("abort",(()=>{var e;this._abort.raise(new Error(null!=(e=r.reason)?e:"Popup aborted"))})),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout((()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))}),1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const r=setInterval((()=>{this._window&&!this._window.closed||(this._logger.debug("Popup closed by user or isolated by redirect"),n(),this._disposeHandlers.delete(n))}),500),n=()=>clearInterval(r);return this._disposeHandlers.add(n),await super.navigate(e)}close(){this._window&&(this._window.closed||(this._window.close(),this._abort.raise(new Error("Popup closed")))),this._window=null}static notifyOpener(e,t){super._notifyParent(window.opener,e,t),t||window.opener||window.close()}},oe=class{constructor(e){this._settings=e,this._logger=new p("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:r}){return new ie({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:r})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),ie.notifyOpener(e,t)}},ae=class{constructor(e){this._settings=e,this._logger=new p("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var r;this._logger.create("prepare");let n=window.self;"top"===t&&(n=null!=(r=window.top)?r:window.self);const s=n.location[e].bind(n.location);let i;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{i=t}));return s(e.url),await t},close:()=>{this._logger.create("close"),null==i||i(new Error("Redirect aborted")),n.stop()}}}async callback(){}},ce=class extends R{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new p("UserManagerEvents"),this._userLoaded=new w("User loaded"),this._userUnloaded=new w("User unloaded"),this._silentRenewError=new w("Silent renew error"),this._userSignedIn=new w("User signed in"),this._userSignedOut=new w("User signed out"),this._userSessionChanged=new w("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},le=class{constructor(e){this._userManager=e,this._logger=new p("SilentRenewService"),this._isStarted=!1,this._retryTimer=new b("Retry Silent Renew"),this._tokenExpiring=async()=>{const e=this._logger.create("_tokenExpiring");try{await this._userManager.signinSilent(),e.debug("silent token renewal successful")}catch(t){if(t instanceof k)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},ue=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},de=class{constructor(e,t,r,n){this._logger=new p("UserManager"),this.settings=new re(e),this._client=new J(e),this._redirectNavigator=null!=t?t:new ae(this.settings),this._popupNavigator=null!=r?r:new oe(this.settings),this._iframeNavigator=null!=n?n:new se(this.settings),this._events=new ce(this.settings),this._silentRenewService=new le(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new V(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),r=await this._loadUser();return r?(t.info("user loaded"),await this._events.load(r,e),r):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:r,...n}=e;let s;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(s=await this.generateDPoPJkt(this.settings.dpop));const i=await this._redirectNavigator.prepare({redirectMethod:r});await this._signinStart({request_type:"si:r",dpopJkt:s,...n},i)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),r=await this._signinEnd(e);return r.profile&&r.profile.sub?t.info("success, signed in subject",r.profile.sub):t.info("no subject"),r}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:r=!1}){const n=this._logger.create("signinResourceOwnerCredential"),s=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:r,extraTokenParams:this.settings.extraTokenParams});n.debug("got signin response");const i=await this._buildUser(s);return i.profile&&i.profile.sub?n.info("success, signed in subject",i.profile.sub):n.info("no subject"),i}async signinPopup(e={}){var t;const r=this._logger.create("signinPopup");let n;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(n=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:s,popupWindowTarget:i,popupSignal:o,...a}=e,c=this.settings.popup_redirect_uri;c||r.throw(new Error("No popup_redirect_uri configured"));const l=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:i,popupSignal:o}),u=await this._signin({request_type:"si:p",redirect_uri:c,display:"popup",dpopJkt:n,...a},l);return u&&(u.profile&&u.profile.sub?r.info("success, signed in subject",u.profile.sub):r.info("no subject")),u}async signinPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async signinSilent(e={}){var t,r;const n=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:s,...i}=e;let o,a=await this._loadUser();if(null==a?void 0:a.refresh_token){n.debug("using refresh token");const e=new ue(a);return await this._useRefreshToken({state:e,redirect_uri:i.redirect_uri,resource:i.resource,extraTokenParams:i.extraTokenParams,timeoutInSeconds:s})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let l;c||n.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(n.debug("subject prior to silent renew:",a.profile.sub),l=a.profile.sub);const u=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});return a=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:o,...i},u,l),a&&((null==(r=a.profile)?void 0:r.sub)?n.info("success, signed in subject",a.profile.sub):n.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),r=new G({...e.state,...t});return await this.storeUser(r),await this._events.load(r),r}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:r}=await this._client.readSignoutResponseState(e);if(r)switch(r.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:r,...n}=e,s=this.settings.silent_redirect_uri;s||t.throw(new Error("No silent_redirect_uri configured"));const i=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:r}),a=await this._signinStart({request_type:"si:s",redirect_uri:s,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==i?void 0:i.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...n},o);try{const e={},r=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),r.session_state&&r.profile.sub?(t.info("success for subject",r.profile.sub),{session_state:r.session_state,sub:r.profile.sub}):(t.info("success, user not authenticated"),null)}catch(c){if(this.settings.monitorAnonymousSession&&c instanceof E)switch(c.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:c.session_state}}throw c}}async _signin(e,t,r){const n=await this._signinStart(e,t);return await this._signinEnd(n.url,r)}async _signinStart(e,t){const r=this._logger.create("_signinStart");try{const n=await this._client.createSigninRequest(e);return r.debug("got signin request"),await t.navigate({url:n.url,state:n.state.id,response_mode:n.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(n){throw r.debug("error after preparing navigator, closing navigator window"),t.close(),n}}async _signinEnd(e,t){const r=this._logger.create("_signinEnd"),n=await this._client.processSigninResponse(e,{});r.debug("got signin response");return await this._buildUser(n,t)}async _buildUser(e,t){const r=this._logger.create("_buildUser"),n=new G(e);if(t){if(t!==n.profile.sub)throw r.debug("current user does not match user returned from signin. sub from signin:",n.profile.sub),new E({...e,error:"login_required"});r.debug("current user matches user returned from signin")}return await this.storeUser(n),r.debug("user stored"),await this._events.load(n),n}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:r,...n}=e,s=await this._redirectNavigator.prepare({redirectMethod:r});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...n},s),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),r=await this._signoutEnd(e);return t.info("success"),r}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:r,popupWindowTarget:n,popupSignal:s,...i}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:r,popupWindowTarget:n,popupSignal:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...i},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const r=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),r.info("success")}async _signout(e,t){const r=await this._signoutStart(e,t);return await this._signoutEnd(r.url)}async _signoutStart(e={},t){var r;const n=this._logger.create("_signoutStart");try{const s=await this._loadUser();n.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(s);const i=e.id_token_hint||s&&s.id_token;i&&(n.debug("setting id_token_hint in signout request"),e.id_token_hint=i),await this.removeUser(),n.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return n.debug("got signout request"),await t.navigate({url:o.url,state:null==(r=o.state)?void 0:r.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(s){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),s}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),r=await this._client.processSignoutResponse(e);return t.debug("got signout response"),r}async signoutSilent(e={}){var t;const r=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:n,...s}=e,i=this.settings.includeIdTokenInSilentSignout?null==(t=await this._loadUser())?void 0:t.id_token:void 0,o=this.settings.popup_post_logout_redirect_uri,a=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:i,...s},a),r.info("success")}async signoutSilentCallback(e=window.location.href){const t=this._logger.create("signoutSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async revokeTokens(e){const t=await this._loadUser();await this._revokeInternal(t,e)}async _revokeInternal(e,t=this.settings.revokeTokenTypes){const r=this._logger.create("_revokeInternal");if(!e)return;const n=t.filter((t=>"string"==typeof e[t]));if(n.length){for(const t of n)await this._client.revokeToken(e[t],t),r.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),r.debug("user stored"),await this._events.load(e)}else r.debug("no need to revoke due to no token(s)")}startSilentRenew(){this._logger.create("startSilentRenew"),this._silentRenewService.start()}stopSilentRenew(){this._silentRenewService.stop()}get _userStoreKey(){return`user:${this.settings.authority}:${this.settings.client_id}`}async _loadUser(){const e=this._logger.create("_loadUser"),t=await this.settings.userStore.get(this._userStoreKey);return t?(e.debug("user storageString loaded"),G.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const r=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,r)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,r,n){var s,i;const o=await(null==(i=null==(s=this.settings.dpop)?void 0:s.store)?void 0:i.get(this.settings.client_id));if(o)return await _.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:r,keyPair:o.keys,nonce:n})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const r=await _.generateDPoPKeys();t=new K(r),await e.store.set(this.settings.client_id,t)}return await _.generateDPoPJkt(t.keys)}},he=r.createContext(void 0);he.displayName="AuthContext";var pe={isLoading:!0,isAuthenticated:!1},fe=(e,t)=>{switch(t.type){case"INITIALISED":case"USER_LOADED":return{...e,user:t.user,isLoading:!1,isAuthenticated:!!t.user&&!t.user.expired,error:void 0};case"USER_SIGNED_OUT":case"USER_UNLOADED":return{...e,user:void 0,isAuthenticated:!1};case"NAVIGATOR_INIT":return{...e,isLoading:!0,activeNavigator:t.method};case"NAVIGATOR_CLOSE":return{...e,isLoading:!1,activeNavigator:void 0};case"ERROR":{const r=t.error;return r.toString=()=>`${r.name}: ${r.message}`,{...e,isLoading:!1,error:r}}default:{const r=new TypeError(`unknown type ${t.type}`),n={name:r.name,message:r.message,innerError:r,stack:r.stack,source:"unknown",toString:()=>`${n.name}: ${n.message}`};return{...e,isLoading:!1,error:n}}}},ge=ye("signinCallback","Sign-in failed"),me=ye("signoutCallback","Sign-out failed"),_e=ye("renewSilent","Renew silent failed");function we(e,t){return{name:be(e,"name",(()=>"Error")),message:be(e,"message",(()=>t)),stack:be(e,"stack",(()=>(new Error).stack)),innerError:e}}function ye(e,t){return r=>({...we(r,t),source:e})}function be(e,t,r){if(e&&"object"==typeof e){const r=e[t];if("string"==typeof r)return r}return r()}var Se=["clearStaleState","querySessionStatus","revokeTokens","startSilentRenew","stopSilentRenew"],ve=["signinPopup","signinSilent","signinRedirect","signinResourceOwnerCredentials","signoutPopup","signoutRedirect","signoutSilent"],Ee=e=>()=>{throw new Error(`UserManager#${e} was called from an unsupported context. If this is a server-rendered page, defer this call with useEffect() or pass a custom UserManager implementation.`)},ke="undefined"==typeof window?null:de,Re=e=>{const{children:t,onSigninCallback:n,skipSigninCallback:s,matchSignoutCallback:i,onSignoutCallback:o,onRemoveUser:a,userManager:c=null,...l}=e,[u]=r.useState((()=>null!=c?c:ke?new ke(l):{settings:l})),[d,h]=r.useReducer(fe,pe),p=r.useMemo((()=>Object.assign({settings:u.settings,events:u.events},Object.fromEntries(Se.map((e=>{var t,r;return[e,null!=(r=null==(t=u[e])?void 0:t.bind(u))?r:Ee(e)]}))),Object.fromEntries(ve.map((e=>[e,u[e]?async t=>{h({type:"NAVIGATOR_INIT",method:e});try{return await u[e](t)}catch(r){return h({type:"ERROR",error:{...we(r,`Unknown error while executing ${e}(...).`),source:e,args:t}}),null}finally{h({type:"NAVIGATOR_CLOSE"})}}:Ee(e)]))))),[u]),f=r.useRef(!1);r.useEffect((()=>{u&&!f.current&&(f.current=!0,(async()=>{try{let e=null;((e=window.location)=>{let t=new URLSearchParams(e.search);return!!((t.get("code")||t.get("error"))&&t.get("state")||(t=new URLSearchParams(e.hash.replace("#","?")),(t.get("code")||t.get("error"))&&t.get("state")))})()&&!s&&(e=await u.signinCallback(),n&&await n(e)),e=e||await u.getUser(),h({type:"INITIALISED",user:e})}catch(e){h({type:"ERROR",error:ge(e)})}try{if(i&&i(u.settings)){const e=await u.signoutCallback();o&&await o(e)}}catch(e){h({type:"ERROR",error:me(e)})}})())}),[u,s,n,o,i]),r.useEffect((()=>{if(!u)return;const e=e=>{h({type:"USER_LOADED",user:e})};u.events.addUserLoaded(e);const t=()=>{h({type:"USER_UNLOADED"})};u.events.addUserUnloaded(t);const r=()=>{h({type:"USER_SIGNED_OUT"})};u.events.addUserSignedOut(r);const n=e=>{h({type:"ERROR",error:_e(e)})};return u.events.addSilentRenewError(n),()=>{u.events.removeUserLoaded(e),u.events.removeUserUnloaded(t),u.events.removeUserSignedOut(r),u.events.removeSilentRenewError(n)}}),[u]);const g=r.useCallback((async()=>{await u.removeUser(),a&&await a()}),[u,a]),m=r.useMemo((()=>({...d,...p,removeUser:g})),[d,p,g]);return r.createElement(he.Provider,{value:m},t)},Te=()=>{const e=r.useContext(he);return e||console.warn("AuthProvider context is undefined, please verify you are calling useAuth() as child of a <AuthProvider> component."),e};function xe(e,t){return function(){return e.apply(t,arguments)}}const{toString:Oe}=Object.prototype,{getPrototypeOf:Ae}=Object,{iterator:Ce,toStringTag:Ne}=Symbol,Pe=(e=>t=>{const r=Oe.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Ie=e=>(e=e.toLowerCase(),t=>Pe(t)===e),Ue=e=>t=>typeof t===e,{isArray:je}=Array,Le=Ue("undefined");const De=Ie("ArrayBuffer");const Fe=Ue("string"),Me=Ue("function"),qe=Ue("number"),Be=e=>null!==e&&"object"==typeof e,He=e=>{if("object"!==Pe(e))return!1;const t=Ae(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Ne in e||Ce in e)},ze=Ie("Date"),We=Ie("File"),$e=Ie("Blob"),Ke=Ie("FileList"),Je=Ie("URLSearchParams"),[Ve,Ge,Xe,Qe]=["ReadableStream","Request","Response","Headers"].map(Ie);function Ye(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,s;if("object"!=typeof e&&(e=[e]),je(e))for(n=0,s=e.length;n<s;n++)t.call(null,e[n],n,e);else{const s=r?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let o;for(n=0;n<i;n++)o=s[n],t.call(null,e[o],o,e)}}function Ze(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,s=r.length;for(;s-- >0;)if(n=r[s],t===n.toLowerCase())return n;return null}const et="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,tt=e=>!Le(e)&&e!==et;const rt=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Ae(Uint8Array)),nt=Ie("HTMLFormElement"),st=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),it=Ie("RegExp"),ot=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};Ye(r,((r,s)=>{let i;!1!==(i=t(r,s,e))&&(n[s]=i||r)})),Object.defineProperties(e,n)};const at=Ie("AsyncFunction"),ct=(lt="function"==typeof setImmediate,ut=Me(et.postMessage),lt?setImmediate:ut?(dt=`axios@${Math.random()}`,ht=[],et.addEventListener("message",(({source:e,data:t})=>{e===et&&t===dt&&ht.length&&ht.shift()()}),!1),e=>{ht.push(e),et.postMessage(dt,"*")}):e=>setTimeout(e));var lt,ut,dt,ht;const pt="undefined"!=typeof queueMicrotask?queueMicrotask.bind(et):"undefined"!=typeof process&&process.nextTick||ct,ft={isArray:je,isArrayBuffer:De,isBuffer:function(e){return null!==e&&!Le(e)&&null!==e.constructor&&!Le(e.constructor)&&Me(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Me(e.append)&&("formdata"===(t=Pe(e))||"object"===t&&Me(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&De(e.buffer),t},isString:Fe,isNumber:qe,isBoolean:e=>!0===e||!1===e,isObject:Be,isPlainObject:He,isReadableStream:Ve,isRequest:Ge,isResponse:Xe,isHeaders:Qe,isUndefined:Le,isDate:ze,isFile:We,isBlob:$e,isRegExp:it,isFunction:Me,isStream:e=>Be(e)&&Me(e.pipe),isURLSearchParams:Je,isTypedArray:rt,isFileList:Ke,forEach:Ye,merge:function e(){const{caseless:t}=tt(this)&&this||{},r={},n=(n,s)=>{const i=t&&Ze(r,s)||s;He(r[i])&&He(n)?r[i]=e(r[i],n):He(n)?r[i]=e({},n):je(n)?r[i]=n.slice():r[i]=n};for(let s=0,i=arguments.length;s<i;s++)arguments[s]&&Ye(arguments[s],n);return r},extend:(e,t,r,{allOwnKeys:n}={})=>(Ye(t,((t,n)=>{r&&Me(t)?e[n]=xe(t,r):e[n]=t}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,n)=>{let s,i,o;const a={};if(t=t||{},null==e)return t;do{for(s=Object.getOwnPropertyNames(e),i=s.length;i-- >0;)o=s[i],n&&!n(o,e,t)||a[o]||(t[o]=e[o],a[o]=!0);e=!1!==r&&Ae(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:Pe,kindOfTest:Ie,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(je(e))return e;let t=e.length;if(!qe(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Ce]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:nt,hasOwnProperty:st,hasOwnProp:st,reduceDescriptors:ot,freezeMethods:e=>{ot(e,((t,r)=>{if(Me(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];Me(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return je(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:Ze,global:et,isContextDefined:tt,isSpecCompliantForm:function(e){return!!(e&&Me(e.append)&&"FormData"===e[Ne]&&e[Ce])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(Be(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const s=je(e)?[]:{};return Ye(e,((e,t)=>{const i=r(e,n+1);!Le(i)&&(s[t]=i)})),t[n]=void 0,s}}return e};return r(e,0)},isAsyncFn:at,isThenable:e=>e&&(Be(e)||Me(e))&&Me(e.then)&&Me(e.catch),setImmediate:ct,asap:pt,isIterable:e=>null!=e&&Me(e[Ce])};function gt(e,t,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}ft.inherits(gt,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ft.toJSONObject(this.config),code:this.code,status:this.status}}});const mt=gt.prototype,_t={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{_t[e]={value:e}})),Object.defineProperties(gt,_t),Object.defineProperty(mt,"isAxiosError",{value:!0}),gt.from=(e,t,r,n,s,i)=>{const o=Object.create(mt);return ft.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),gt.call(o,e.message,t,r,n,s),o.cause=e,o.name=e.name,i&&Object.assign(o,i),o};function wt(e){return ft.isPlainObject(e)||ft.isArray(e)}function yt(e){return ft.endsWith(e,"[]")?e.slice(0,-2):e}function bt(e,t,r){return e?e.concat(t).map((function(e,t){return e=yt(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const St=ft.toFlatObject(ft,{},null,(function(e){return/^is[A-Z]/.test(e)}));function vt(e,t,r){if(!ft.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=ft.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!ft.isUndefined(t[e])}))).metaTokens,s=r.visitor||l,i=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&ft.isSpecCompliantForm(t);if(!ft.isFunction(s))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(ft.isDate(e))return e.toISOString();if(ft.isBoolean(e))return e.toString();if(!a&&ft.isBlob(e))throw new gt("Blob is not supported. Use a Buffer instead.");return ft.isArrayBuffer(e)||ft.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,r,s){let a=e;if(e&&!s&&"object"==typeof e)if(ft.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(ft.isArray(e)&&function(e){return ft.isArray(e)&&!e.some(wt)}(e)||(ft.isFileList(e)||ft.endsWith(r,"[]"))&&(a=ft.toArray(e)))return r=yt(r),a.forEach((function(e,n){!ft.isUndefined(e)&&null!==e&&t.append(!0===o?bt([r],n,i):null===o?r:r+"[]",c(e))})),!1;return!!wt(e)||(t.append(bt(s,r,i),c(e)),!1)}const u=[],d=Object.assign(St,{defaultVisitor:l,convertValue:c,isVisitable:wt});if(!ft.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!ft.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),ft.forEach(r,(function(r,i){!0===(!(ft.isUndefined(r)||null===r)&&s.call(t,r,ft.isString(i)?i.trim():i,n,d))&&e(r,n?n.concat(i):[i])})),u.pop()}}(e),t}function Et(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function kt(e,t){this._pairs=[],e&&vt(e,this,t)}const Rt=kt.prototype;function Tt(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function xt(e,t,r){if(!t)return e;const n=r&&r.encode||Tt;ft.isFunction(r)&&(r={serialize:r});const s=r&&r.serialize;let i;if(i=s?s(t,r):ft.isURLSearchParams(t)?t.toString():new kt(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}Rt.append=function(e,t){this._pairs.push([e,t])},Rt.toString=function(e){const t=e?function(t){return e.call(this,t,Et)}:Et;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class Ot{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ft.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}const At={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ct={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:kt,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Nt="undefined"!=typeof window&&"undefined"!=typeof document,Pt="object"==typeof navigator&&navigator||void 0,It=Nt&&(!Pt||["ReactNative","NativeScript","NS"].indexOf(Pt.product)<0),Ut="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,jt=Nt&&window.location.href||"http://localhost",Lt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Nt,hasStandardBrowserEnv:It,hasStandardBrowserWebWorkerEnv:Ut,navigator:Pt,origin:jt},Symbol.toStringTag,{value:"Module"})),...Ct};function Dt(e){function t(e,r,n,s){let i=e[s++];if("__proto__"===i)return!0;const o=Number.isFinite(+i),a=s>=e.length;if(i=!i&&ft.isArray(n)?n.length:i,a)return ft.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!o;n[i]&&ft.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],s)&&ft.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const s=r.length;let i;for(n=0;n<s;n++)i=r[n],t[i]=e[i];return t}(n[i])),!o}if(ft.isFormData(e)&&ft.isFunction(e.entries)){const r={};return ft.forEachEntry(e,((e,n)=>{t(function(e){return ft.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const Ft={transitional:At,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,s=ft.isObject(e);s&&ft.isHTMLForm(e)&&(e=new FormData(e));if(ft.isFormData(e))return n?JSON.stringify(Dt(e)):e;if(ft.isArrayBuffer(e)||ft.isBuffer(e)||ft.isStream(e)||ft.isFile(e)||ft.isBlob(e)||ft.isReadableStream(e))return e;if(ft.isArrayBufferView(e))return e.buffer;if(ft.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return vt(e,new Lt.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return Lt.isNode&&ft.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=ft.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return vt(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return s||n?(t.setContentType("application/json",!1),function(e,t,r){if(ft.isString(e))try{return(t||JSON.parse)(e),ft.trim(e)}catch(tn){if("SyntaxError"!==tn.name)throw tn}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Ft.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(ft.isResponse(e)||ft.isReadableStream(e))return e;if(e&&ft.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(tn){if(r){if("SyntaxError"===tn.name)throw gt.from(tn,gt.ERR_BAD_RESPONSE,this,null,this.response);throw tn}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Lt.classes.FormData,Blob:Lt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ft.forEach(["delete","get","head","post","put","patch"],(e=>{Ft.headers[e]={}}));const Mt=ft.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),qt=Symbol("internals");function Bt(e){return e&&String(e).trim().toLowerCase()}function Ht(e){return!1===e||null==e?e:ft.isArray(e)?e.map(Ht):String(e)}function zt(e,t,r,n,s){return ft.isFunction(n)?n.call(this,t,r):(s&&(t=r),ft.isString(t)?ft.isString(n)?-1!==t.indexOf(n):ft.isRegExp(n)?n.test(t):void 0:void 0)}let Wt=class{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function s(e,t,r){const s=Bt(t);if(!s)throw new Error("header name must be a non-empty string");const i=ft.findKey(n,s);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=Ht(e))}const i=(e,t)=>ft.forEach(e,((e,r)=>s(e,r,t)));if(ft.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(ft.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i((e=>{const t={};let r,n,s;return e&&e.split("\n").forEach((function(e){s=e.indexOf(":"),r=e.substring(0,s).trim().toLowerCase(),n=e.substring(s+1).trim(),!r||t[r]&&Mt[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if(ft.isObject(e)&&ft.isIterable(e)){let r,n,s={};for(const t of e){if(!ft.isArray(t))throw TypeError("Object iterator must return a key-value pair");s[n=t[0]]=(r=s[n])?ft.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}i(s,t)}else null!=e&&s(t,e,r);return this}get(e,t){if(e=Bt(e)){const r=ft.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(ft.isFunction(t))return t.call(this,e,r);if(ft.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Bt(e)){const r=ft.findKey(this,e);return!(!r||void 0===this[r]||t&&!zt(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function s(e){if(e=Bt(e)){const s=ft.findKey(r,e);!s||t&&!zt(0,r[s],s,t)||(delete r[s],n=!0)}}return ft.isArray(e)?e.forEach(s):s(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const s=t[r];e&&!zt(0,this[s],s,e,!0)||(delete this[s],n=!0)}return n}normalize(e){const t=this,r={};return ft.forEach(this,((n,s)=>{const i=ft.findKey(r,s);if(i)return t[i]=Ht(n),void delete t[s];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(s):String(s).trim();o!==s&&delete t[s],t[o]=Ht(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return ft.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&ft.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[qt]=this[qt]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=Bt(e);t[n]||(!function(e,t){const r=ft.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,s){return this[n].call(this,t,e,r,s)},configurable:!0})}))}(r,e),t[n]=!0)}return ft.isArray(e)?e.forEach(n):n(e),this}};function $t(e,t){const r=this||Ft,n=t||r,s=Wt.from(n.headers);let i=n.data;return ft.forEach(e,(function(e){i=e.call(r,i,s.normalize(),t?t.status:void 0)})),s.normalize(),i}function Kt(e){return!(!e||!e.__CANCEL__)}function Jt(e,t,r){gt.call(this,null==e?"canceled":e,gt.ERR_CANCELED,t,r),this.name="CanceledError"}function Vt(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new gt("Request failed with status code "+r.status,[gt.ERR_BAD_REQUEST,gt.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}Wt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ft.reduceDescriptors(Wt.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),ft.freezeMethods(Wt),ft.inherits(Jt,gt,{__CANCEL__:!0});const Gt=(e,t,r=3)=>{let n=0;const s=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let s,i=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=n[o];s||(s=c),r[i]=a,n[i]=c;let u=o,d=0;for(;u!==i;)d+=r[u++],u%=e;if(i=(i+1)%e,i===o&&(o=(o+1)%e),c-s<t)return;const h=l&&c-l;return h?Math.round(1e3*d/h):void 0}}(50,250);return function(e,t){let r,n,s=0,i=1e3/t;const o=(t,i=Date.now())=>{s=i,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-s;a>=i?o(e,t):(r=e,n||(n=setTimeout((()=>{n=null,o(r)}),i-a)))},()=>r&&o(r)]}((r=>{const i=r.loaded,o=r.lengthComputable?r.total:void 0,a=i-n,c=s(a);n=i;e({loaded:i,total:o,progress:o?i/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&i<=o?(o-i)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})}),r)},Xt=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},Qt=e=>(...t)=>ft.asap((()=>e(...t))),Yt=Lt.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Lt.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Lt.origin),Lt.navigator&&/(msie|trident)/i.test(Lt.navigator.userAgent)):()=>!0,Zt=Lt.hasStandardBrowserEnv?{write(e,t,r,n,s,i){const o=[e+"="+encodeURIComponent(t)];ft.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),ft.isString(n)&&o.push("path="+n),ft.isString(s)&&o.push("domain="+s),!0===i&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function er(e,t,r){let n=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const tr=e=>e instanceof Wt?{...e}:e;function rr(e,t){t=t||{};const r={};function n(e,t,r,n){return ft.isPlainObject(e)&&ft.isPlainObject(t)?ft.merge.call({caseless:n},e,t):ft.isPlainObject(t)?ft.merge({},t):ft.isArray(t)?t.slice():t}function s(e,t,r,s){return ft.isUndefined(t)?ft.isUndefined(e)?void 0:n(void 0,e,0,s):n(e,t,0,s)}function i(e,t){if(!ft.isUndefined(t))return n(void 0,t)}function o(e,t){return ft.isUndefined(t)?ft.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,s,i){return i in t?n(r,s):i in e?n(void 0,r):void 0}const c={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>s(tr(e),tr(t),0,!0)};return ft.forEach(Object.keys(Object.assign({},e,t)),(function(n){const i=c[n]||s,o=i(e[n],t[n],n);ft.isUndefined(o)&&i!==a||(r[n]=o)})),r}const nr=e=>{const t=rr({},e);let r,{data:n,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=Wt.from(a),t.url=xt(er(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),ft.isFormData(n))if(Lt.hasStandardBrowserEnv||Lt.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(Lt.hasStandardBrowserEnv&&(s&&ft.isFunction(s)&&(s=s(t)),s||!1!==s&&Yt(t.url))){const e=i&&o&&Zt.read(o);e&&a.set(i,e)}return t},sr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=nr(e);let s=n.data;const i=Wt.from(n.headers).normalize();let o,a,c,l,u,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=n;function f(){l&&l(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function m(){if(!g)return;const n=Wt.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());Vt((function(e){t(e),f()}),(function(e){r(e),f()}),{data:d&&"text"!==d&&"json"!==d?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:n,config:e,request:g}),g=null}g.open(n.method.toUpperCase(),n.url,!0),g.timeout=n.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(r(new gt("Request aborted",gt.ECONNABORTED,e,g)),g=null)},g.onerror=function(){r(new gt("Network Error",gt.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const s=n.transitional||At;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new gt(t,s.clarifyTimeoutError?gt.ETIMEDOUT:gt.ECONNABORTED,e,g)),g=null},void 0===s&&i.setContentType(null),"setRequestHeader"in g&&ft.forEach(i.toJSON(),(function(e,t){g.setRequestHeader(t,e)})),ft.isUndefined(n.withCredentials)||(g.withCredentials=!!n.withCredentials),d&&"json"!==d&&(g.responseType=n.responseType),p&&([c,u]=Gt(p,!0),g.addEventListener("progress",c)),h&&g.upload&&([a,l]=Gt(h),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(o=t=>{g&&(r(!t||t.type?new Jt(null,e,g):t),g.abort(),g=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const _=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);_&&-1===Lt.protocols.indexOf(_)?r(new gt("Unsupported protocol "+_+":",gt.ERR_BAD_REQUEST,e)):g.send(s||null)}))},ir=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const s=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof gt?t:new Jt(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,s(new gt(`timeout ${t} of ms exceeded`,gt.ETIMEDOUT))}),t);const o=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(s):e.removeEventListener("abort",s)})),e=null)};e.forEach((e=>e.addEventListener("abort",s)));const{signal:a}=n;return a.unsubscribe=()=>ft.asap(o),a}},or=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,s=0;for(;s<r;)n=s+t,yield e.slice(s,n),s=n},ar=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},cr=(e,t,r,n)=>{const s=async function*(e,t){for await(const r of ar(e))yield*or(r,t)}(e,t);let i,o=0,a=e=>{i||(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await s.next();if(t)return a(),void e.close();let i=n.byteLength;if(r){let e=o+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(t){throw a(t),t}},cancel:e=>(a(e),s.return())},{highWaterMark:2})},lr="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,ur=lr&&"function"==typeof ReadableStream,dr=lr&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),hr=(e,...t)=>{try{return!!e(...t)}catch(tn){return!1}},pr=ur&&hr((()=>{let e=!1;const t=new Request(Lt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),fr=ur&&hr((()=>ft.isReadableStream(new Response("").body))),gr={stream:fr&&(e=>e.body)};var mr;lr&&(mr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!gr[e]&&(gr[e]=ft.isFunction(mr[e])?t=>t[e]():(t,r)=>{throw new gt(`Response type '${e}' is not supported`,gt.ERR_NOT_SUPPORT,r)})})));const _r=async(e,t)=>{const r=ft.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(ft.isBlob(e))return e.size;if(ft.isSpecCompliantForm(e)){const t=new Request(Lt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return ft.isArrayBufferView(e)||ft.isArrayBuffer(e)?e.byteLength:(ft.isURLSearchParams(e)&&(e+=""),ft.isString(e)?(await dr(e)).byteLength:void 0)})(t):r},wr={http:null,xhr:sr,fetch:lr&&(async e=>{let{url:t,method:r,data:n,signal:s,cancelToken:i,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:u,withCredentials:d="same-origin",fetchOptions:h}=nr(e);l=l?(l+"").toLowerCase():"text";let p,f=ir([s,i&&i.toAbortSignal()],o);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&pr&&"get"!==r&&"head"!==r&&0!==(m=await _r(u,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(ft.isFormData(n)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=Xt(m,Gt(Qt(c)));n=cr(r.body,65536,e,t)}}ft.isString(d)||(d=d?"include":"omit");const s="credentials"in Request.prototype;p=new Request(t,{...h,signal:f,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:s?d:void 0});let i=await fetch(p,h);const o=fr&&("stream"===l||"response"===l);if(fr&&(a||o&&g)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=ft.toFiniteNumber(i.headers.get("content-length")),[r,n]=a&&Xt(t,Gt(Qt(a),!0))||[];i=new Response(cr(i.body,65536,r,(()=>{n&&n(),g&&g()})),e)}l=l||"text";let _=await gr[ft.findKey(gr,l)||"text"](i,e);return!o&&g&&g(),await new Promise(((t,r)=>{Vt(t,r,{data:_,headers:Wt.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:p})}))}catch(_){if(g&&g(),_&&"TypeError"===_.name&&/Load failed|fetch/i.test(_.message))throw Object.assign(new gt("Network Error",gt.ERR_NETWORK,e,p),{cause:_.cause||_});throw gt.from(_,_&&_.code,e,p)}})};ft.forEach(wr,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(tn){}Object.defineProperty(e,"adapterName",{value:t})}}));const yr=e=>`- ${e}`,br=e=>ft.isFunction(e)||null===e||!1===e,Sr=e=>{e=ft.isArray(e)?e:[e];const{length:t}=e;let r,n;const s={};for(let i=0;i<t;i++){let t;if(r=e[i],n=r,!br(r)&&(n=wr[(t=String(r)).toLowerCase()],void 0===n))throw new gt(`Unknown adapter '${t}'`);if(n)break;s[t||"#"+i]=n}if(!n){const e=Object.entries(s).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new gt("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(yr).join("\n"):" "+yr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function vr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Jt(null,e)}function Er(e){vr(e),e.headers=Wt.from(e.headers),e.data=$t.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Sr(e.adapter||Ft.adapter)(e).then((function(t){return vr(e),t.data=$t.call(e,e.transformResponse,t),t.headers=Wt.from(t.headers),t}),(function(t){return Kt(t)||(vr(e),t&&t.response&&(t.response.data=$t.call(e,e.transformResponse,t.response),t.response.headers=Wt.from(t.response.headers))),Promise.reject(t)}))}const kr="1.10.0",Rr={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Rr[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Tr={};Rr.transitional=function(e,t,r){function n(e,t){return"[Axios v"+kr+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,s,i)=>{if(!1===e)throw new gt(n(s," has been removed"+(t?" in "+t:"")),gt.ERR_DEPRECATED);return t&&!Tr[s]&&(Tr[s]=!0,console.warn(n(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,s,i)}},Rr.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const xr={assertOptions:function(e,t,r){if("object"!=typeof e)throw new gt("options must be an object",gt.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const i=n[s],o=t[i];if(o){const t=e[i],r=void 0===t||o(t,i,e);if(!0!==r)throw new gt("option "+i+" must be "+r,gt.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new gt("Unknown option "+i,gt.ERR_BAD_OPTION)}},validators:Rr},Or=xr.validators;let Ar=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Ot,response:new Ot}}async request(e,t){try{return await this._request(e,t)}catch(r){if(r instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{r.stack?t&&!String(r.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(r.stack+="\n"+t):r.stack=t}catch(tn){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=rr(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:s}=t;void 0!==r&&xr.assertOptions(r,{silentJSONParsing:Or.transitional(Or.boolean),forcedJSONParsing:Or.transitional(Or.boolean),clarifyTimeoutError:Or.transitional(Or.boolean)},!1),null!=n&&(ft.isFunction(n)?t.paramsSerializer={serialize:n}:xr.assertOptions(n,{encode:Or.function,serialize:Or.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),xr.assertOptions(t,{baseUrl:Or.spelling("baseURL"),withXsrfToken:Or.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=s&&ft.merge(s.common,s[t.method]);s&&ft.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete s[e]})),t.headers=Wt.concat(i,s);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let l;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let u,d=0;if(!a){const e=[Er.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),u=e.length,l=Promise.resolve(t);d<u;)l=l.then(e[d++],e[d++]);return l}u=o.length;let h=t;for(d=0;d<u;){const e=o[d++],t=o[d++];try{h=e(h)}catch(p){t.call(this,p);break}}try{l=Er.call(this,h)}catch(p){return Promise.reject(p)}for(d=0,u=c.length;d<u;)l=l.then(c[d++],c[d++]);return l}getUri(e){return xt(er((e=rr(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};ft.forEach(["delete","get","head","options"],(function(e){Ar.prototype[e]=function(t,r){return this.request(rr(r||{},{method:e,url:t,data:(r||{}).data}))}})),ft.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,s){return this.request(rr(s||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Ar.prototype[e]=t(),Ar.prototype[e+"Form"]=t(!0)}));const Cr={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Cr).forEach((([e,t])=>{Cr[t]=e}));const Nr=function e(t){const r=new Ar(t),n=xe(Ar.prototype.request,r);return ft.extend(n,Ar.prototype,r,{allOwnKeys:!0}),ft.extend(n,r,null,{allOwnKeys:!0}),n.create=function(r){return e(rr(t,r))},n}(Ft);Nr.Axios=Ar,Nr.CanceledError=Jt,Nr.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,s){r.reason||(r.reason=new Jt(e,n,s),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e((function(e){t=e})),cancel:t}}},Nr.isCancel=Kt,Nr.VERSION=kr,Nr.toFormData=vt,Nr.AxiosError=gt,Nr.Cancel=Nr.CanceledError,Nr.all=function(e){return Promise.all(e)},Nr.spread=function(e){return function(t){return e.apply(null,t)}},Nr.isAxiosError=function(e){return ft.isObject(e)&&!0===e.isAxiosError},Nr.mergeConfig=rr,Nr.AxiosHeaders=Wt,Nr.formToJSON=e=>Dt(ft.isHTMLForm(e)?new FormData(e):e),Nr.getAdapter=Sr,Nr.HttpStatusCode=Cr,Nr.default=Nr;const{Axios:Pr,AxiosError:Ir,CanceledError:Ur,isCancel:jr,CancelToken:Lr,VERSION:Dr,all:Fr,Cancel:Mr,isAxiosError:qr,spread:Br,toFormData:Hr,AxiosHeaders:zr,HttpStatusCode:Wr,formToJSON:$r,getAdapter:Kr,mergeConfig:Jr}=Nr;var Vr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Gr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Xr,Qr,Yr={exports:{}};
2
+ /*! Axios v1.10.0 Copyright (c) 2025 Matt Zabriskie and contributors */function Zr(){if(Qr)return Xr;function e(e,t){return function(){return e.apply(t,arguments)}}Qr=1;const{toString:t}=Object.prototype,{getPrototypeOf:r}=Object,{iterator:n,toStringTag:s}=Symbol,i=(e=>r=>{const n=t.call(r);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),o=e=>(e=e.toLowerCase(),t=>i(t)===e),a=e=>t=>typeof t===e,{isArray:c}=Array,l=a("undefined");const u=o("ArrayBuffer");const d=a("string"),h=a("function"),p=a("number"),f=e=>null!==e&&"object"==typeof e,g=e=>{if("object"!==i(e))return!1;const t=r(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||s in e||n in e)},m=o("Date"),_=o("File"),w=o("Blob"),y=o("FileList"),b=o("URLSearchParams"),[S,v,E,k]=["ReadableStream","Request","Response","Headers"].map(o);function R(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,s;if("object"!=typeof e&&(e=[e]),c(e))for(n=0,s=e.length;n<s;n++)t.call(null,e[n],n,e);else{const s=r?Object.getOwnPropertyNames(e):Object.keys(e),i=s.length;let o;for(n=0;n<i;n++)o=s[n],t.call(null,e[o],o,e)}}function T(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,s=r.length;for(;s-- >0;)if(n=r[s],t===n.toLowerCase())return n;return null}const x="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:Vr,O=e=>!l(e)&&e!==x;const A=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&r(Uint8Array)),C=o("HTMLFormElement"),N=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),P=o("RegExp"),I=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};R(r,((r,s)=>{let i;!1!==(i=t(r,s,e))&&(n[s]=i||r)})),Object.defineProperties(e,n)};const U=o("AsyncFunction"),j=((e,t)=>e?setImmediate:t?((e,t)=>(x.addEventListener("message",(({source:r,data:n})=>{r===x&&n===e&&t.length&&t.shift()()}),!1),r=>{t.push(r),x.postMessage(e,"*")}))(`axios@${Math.random()}`,[]):e=>setTimeout(e))("function"==typeof setImmediate,h(x.postMessage)),L="undefined"!=typeof queueMicrotask?queueMicrotask.bind(x):"undefined"!=typeof process&&process.nextTick||j;var D={isArray:c,isArrayBuffer:u,isBuffer:function(e){return null!==e&&!l(e)&&null!==e.constructor&&!l(e.constructor)&&h(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||h(e.append)&&("formdata"===(t=i(e))||"object"===t&&h(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&u(e.buffer),t},isString:d,isNumber:p,isBoolean:e=>!0===e||!1===e,isObject:f,isPlainObject:g,isReadableStream:S,isRequest:v,isResponse:E,isHeaders:k,isUndefined:l,isDate:m,isFile:_,isBlob:w,isRegExp:P,isFunction:h,isStream:e=>f(e)&&h(e.pipe),isURLSearchParams:b,isTypedArray:A,isFileList:y,forEach:R,merge:function e(){const{caseless:t}=O(this)&&this||{},r={},n=(n,s)=>{const i=t&&T(r,s)||s;g(r[i])&&g(n)?r[i]=e(r[i],n):g(n)?r[i]=e({},n):c(n)?r[i]=n.slice():r[i]=n};for(let s=0,i=arguments.length;s<i;s++)arguments[s]&&R(arguments[s],n);return r},extend:(t,r,n,{allOwnKeys:s}={})=>(R(r,((r,s)=>{n&&h(r)?t[s]=e(r,n):t[s]=r}),{allOwnKeys:s}),t),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,n,s)=>{let i,o,a;const c={};if(t=t||{},null==e)return t;do{for(i=Object.getOwnPropertyNames(e),o=i.length;o-- >0;)a=i[o],s&&!s(a,e,t)||c[a]||(t[a]=e[a],c[a]=!0);e=!1!==n&&r(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:i,kindOfTest:o,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray:e=>{if(!e)return null;if(c(e))return e;let t=e.length;if(!p(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[n]).call(e);let s;for(;(s=r.next())&&!s.done;){const r=s.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm:C,hasOwnProperty:N,hasOwnProp:N,reduceDescriptors:I,freezeMethods:e=>{I(e,((t,r)=>{if(h(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];h(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))}))},toObjectSet:(e,t)=>{const r={},n=e=>{e.forEach((e=>{r[e]=!0}))};return c(e)?n(e):n(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:T,global:x,isContextDefined:O,isSpecCompliantForm:function(e){return!!(e&&h(e.append)&&"FormData"===e[s]&&e[n])},toJSONObject:e=>{const t=new Array(10),r=(e,n)=>{if(f(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const s=c(e)?[]:{};return R(e,((e,t)=>{const i=r(e,n+1);!l(i)&&(s[t]=i)})),t[n]=void 0,s}}return e};return r(e,0)},isAsyncFn:U,isThenable:e=>e&&(f(e)||h(e))&&h(e.then)&&h(e.catch),setImmediate:j,asap:L,isIterable:e=>null!=e&&h(e[n])};function F(e,t,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}D.inherits(F,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:D.toJSONObject(this.config),code:this.code,status:this.status}}});const M=F.prototype,q={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach((e=>{q[e]={value:e}})),Object.defineProperties(F,q),Object.defineProperty(M,"isAxiosError",{value:!0}),F.from=(e,t,r,n,s,i)=>{const o=Object.create(M);return D.toFlatObject(e,o,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),F.call(o,e.message,t,r,n,s),o.cause=e,o.name=e.name,i&&Object.assign(o,i),o};function B(e){return D.isPlainObject(e)||D.isArray(e)}function H(e){return D.endsWith(e,"[]")?e.slice(0,-2):e}function z(e,t,r){return e?e.concat(t).map((function(e,t){return e=H(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const W=D.toFlatObject(D,{},null,(function(e){return/^is[A-Z]/.test(e)}));function $(e,t,r){if(!D.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=D.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!D.isUndefined(t[e])}))).metaTokens,s=r.visitor||l,i=r.dots,o=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&D.isSpecCompliantForm(t);if(!D.isFunction(s))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(D.isDate(e))return e.toISOString();if(D.isBoolean(e))return e.toString();if(!a&&D.isBlob(e))throw new F("Blob is not supported. Use a Buffer instead.");return D.isArrayBuffer(e)||D.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,r,s){let a=e;if(e&&!s&&"object"==typeof e)if(D.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(D.isArray(e)&&function(e){return D.isArray(e)&&!e.some(B)}(e)||(D.isFileList(e)||D.endsWith(r,"[]"))&&(a=D.toArray(e)))return r=H(r),a.forEach((function(e,n){!D.isUndefined(e)&&null!==e&&t.append(!0===o?z([r],n,i):null===o?r:r+"[]",c(e))})),!1;return!!B(e)||(t.append(z(s,r,i),c(e)),!1)}const u=[],d=Object.assign(W,{defaultVisitor:l,convertValue:c,isVisitable:B});if(!D.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!D.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+n.join("."));u.push(r),D.forEach(r,(function(r,i){!0===(!(D.isUndefined(r)||null===r)&&s.call(t,r,D.isString(i)?i.trim():i,n,d))&&e(r,n?n.concat(i):[i])})),u.pop()}}(e),t}function K(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function J(e,t){this._pairs=[],e&&$(e,this,t)}const V=J.prototype;function G(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function X(e,t,r){if(!t)return e;const n=r&&r.encode||G;D.isFunction(r)&&(r={serialize:r});const s=r&&r.serialize;let i;if(i=s?s(t,r):D.isURLSearchParams(t)?t.toString():new J(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}V.append=function(e,t){this._pairs.push([e,t])},V.toString=function(e){const t=e?function(t){return e.call(this,t,K)}:K;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var Q=class{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){D.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},Y={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Z={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:J,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const ee="undefined"!=typeof window&&"undefined"!=typeof document,te="object"==typeof navigator&&navigator||void 0,re=ee&&(!te||["ReactNative","NativeScript","NS"].indexOf(te.product)<0),ne="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,se=ee&&window.location.href||"http://localhost";var ie={...Object.freeze({__proto__:null,hasBrowserEnv:ee,hasStandardBrowserWebWorkerEnv:ne,hasStandardBrowserEnv:re,navigator:te,origin:se}),...Z};function oe(e){function t(e,r,n,s){let i=e[s++];if("__proto__"===i)return!0;const o=Number.isFinite(+i),a=s>=e.length;if(i=!i&&D.isArray(n)?n.length:i,a)return D.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!o;n[i]&&D.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],s)&&D.isArray(n[i])&&(n[i]=function(e){const t={},r=Object.keys(e);let n;const s=r.length;let i;for(n=0;n<s;n++)i=r[n],t[i]=e[i];return t}(n[i])),!o}if(D.isFormData(e)&&D.isFunction(e.entries)){const r={};return D.forEachEntry(e,((e,n)=>{t(function(e){return D.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,r,0)})),r}return null}const ae={transitional:Y,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,s=D.isObject(e);s&&D.isHTMLForm(e)&&(e=new FormData(e));if(D.isFormData(e))return n?JSON.stringify(oe(e)):e;if(D.isArrayBuffer(e)||D.isBuffer(e)||D.isStream(e)||D.isFile(e)||D.isBlob(e)||D.isReadableStream(e))return e;if(D.isArrayBufferView(e))return e.buffer;if(D.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return $(e,new ie.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return ie.isNode&&D.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=D.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return $(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return s||n?(t.setContentType("application/json",!1),function(e,t,r){if(D.isString(e))try{return(t||JSON.parse)(e),D.trim(e)}catch(tn){if("SyntaxError"!==tn.name)throw tn}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||ae.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(D.isResponse(e)||D.isReadableStream(e))return e;if(e&&D.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(tn){if(r){if("SyntaxError"===tn.name)throw F.from(tn,F.ERR_BAD_RESPONSE,this,null,this.response);throw tn}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ie.classes.FormData,Blob:ie.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};D.forEach(["delete","get","head","post","put","patch"],(e=>{ae.headers[e]={}}));var ce=ae;const le=D.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const ue=Symbol("internals");function de(e){return e&&String(e).trim().toLowerCase()}function he(e){return!1===e||null==e?e:D.isArray(e)?e.map(he):String(e)}function pe(e,t,r,n,s){return D.isFunction(n)?n.call(this,t,r):(s&&(t=r),D.isString(t)?D.isString(n)?-1!==t.indexOf(n):D.isRegExp(n)?n.test(t):void 0:void 0)}class fe{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function s(e,t,r){const s=de(t);if(!s)throw new Error("header name must be a non-empty string");const i=D.findKey(n,s);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=he(e))}const i=(e,t)=>D.forEach(e,((e,r)=>s(e,r,t)));if(D.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(D.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i((e=>{const t={};let r,n,s;return e&&e.split("\n").forEach((function(e){s=e.indexOf(":"),r=e.substring(0,s).trim().toLowerCase(),n=e.substring(s+1).trim(),!r||t[r]&&le[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t})(e),t);else if(D.isObject(e)&&D.isIterable(e)){let r,n,s={};for(const t of e){if(!D.isArray(t))throw TypeError("Object iterator must return a key-value pair");s[n=t[0]]=(r=s[n])?D.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}i(s,t)}else null!=e&&s(t,e,r);return this}get(e,t){if(e=de(e)){const r=D.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}(e);if(D.isFunction(t))return t.call(this,e,r);if(D.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=de(e)){const r=D.findKey(this,e);return!(!r||void 0===this[r]||t&&!pe(0,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function s(e){if(e=de(e)){const s=D.findKey(r,e);!s||t&&!pe(0,r[s],s,t)||(delete r[s],n=!0)}}return D.isArray(e)?e.forEach(s):s(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const s=t[r];e&&!pe(0,this[s],s,e,!0)||(delete this[s],n=!0)}return n}normalize(e){const t=this,r={};return D.forEach(this,((n,s)=>{const i=D.findKey(r,s);if(i)return t[i]=he(n),void delete t[s];const o=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(s):String(s).trim();o!==s&&delete t[s],t[o]=he(n),r[o]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return D.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&D.isArray(r)?r.join(", "):r)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach((e=>r.set(e))),r}static accessor(e){const t=(this[ue]=this[ue]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=de(e);t[n]||(!function(e,t){const r=D.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,s){return this[n].call(this,t,e,r,s)},configurable:!0})}))}(r,e),t[n]=!0)}return D.isArray(e)?e.forEach(n):n(e),this}}fe.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),D.reduceDescriptors(fe.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),D.freezeMethods(fe);var ge=fe;function me(e,t){const r=this||ce,n=t||r,s=ge.from(n.headers);let i=n.data;return D.forEach(e,(function(e){i=e.call(r,i,s.normalize(),t?t.status:void 0)})),s.normalize(),i}function _e(e){return!(!e||!e.__CANCEL__)}function we(e,t,r){F.call(this,null==e?"canceled":e,F.ERR_CANCELED,t,r),this.name="CanceledError"}function ye(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new F("Request failed with status code "+r.status,[F.ERR_BAD_REQUEST,F.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}D.inherits(we,F,{__CANCEL__:!0});const be=(e,t,r=3)=>{let n=0;const s=function(e,t){e=e||10;const r=new Array(e),n=new Array(e);let s,i=0,o=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=n[o];s||(s=c),r[i]=a,n[i]=c;let u=o,d=0;for(;u!==i;)d+=r[u++],u%=e;if(i=(i+1)%e,i===o&&(o=(o+1)%e),c-s<t)return;const h=l&&c-l;return h?Math.round(1e3*d/h):void 0}}(50,250);return function(e,t){let r,n,s=0,i=1e3/t;const o=(t,i=Date.now())=>{s=i,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-s;a>=i?o(e,t):(r=e,n||(n=setTimeout((()=>{n=null,o(r)}),i-a)))},()=>r&&o(r)]}((r=>{const i=r.loaded,o=r.lengthComputable?r.total:void 0,a=i-n,c=s(a);n=i;e({loaded:i,total:o,progress:o?i/o:void 0,bytes:a,rate:c||void 0,estimated:c&&o&&i<=o?(o-i)/c:void 0,event:r,lengthComputable:null!=o,[t?"download":"upload"]:!0})}),r)},Se=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},ve=e=>(...t)=>D.asap((()=>e(...t)));var Ee=ie.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,ie.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(ie.origin),ie.navigator&&/(msie|trident)/i.test(ie.navigator.userAgent)):()=>!0,ke=ie.hasStandardBrowserEnv?{write(e,t,r,n,s,i){const o=[e+"="+encodeURIComponent(t)];D.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),D.isString(n)&&o.push("path="+n),D.isString(s)&&o.push("domain="+s),!0===i&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Re(e,t,r){let n=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(n||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Te=e=>e instanceof ge?{...e}:e;function xe(e,t){t=t||{};const r={};function n(e,t,r,n){return D.isPlainObject(e)&&D.isPlainObject(t)?D.merge.call({caseless:n},e,t):D.isPlainObject(t)?D.merge({},t):D.isArray(t)?t.slice():t}function s(e,t,r,s){return D.isUndefined(t)?D.isUndefined(e)?void 0:n(void 0,e,0,s):n(e,t,0,s)}function i(e,t){if(!D.isUndefined(t))return n(void 0,t)}function o(e,t){return D.isUndefined(t)?D.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function a(r,s,i){return i in t?n(r,s):i in e?n(void 0,r):void 0}const c={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(e,t,r)=>s(Te(e),Te(t),0,!0)};return D.forEach(Object.keys(Object.assign({},e,t)),(function(n){const i=c[n]||s,o=i(e[n],t[n],n);D.isUndefined(o)&&i!==a||(r[n]=o)})),r}var Oe=e=>{const t=xe({},e);let r,{data:n,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:o,headers:a,auth:c}=t;if(t.headers=a=ge.from(a),t.url=X(Re(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),D.isFormData(n))if(ie.hasStandardBrowserEnv||ie.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(ie.hasStandardBrowserEnv&&(s&&D.isFunction(s)&&(s=s(t)),s||!1!==s&&Ee(t.url))){const e=i&&o&&ke.read(o);e&&a.set(i,e)}return t};var Ae="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const n=Oe(e);let s=n.data;const i=ge.from(n.headers).normalize();let o,a,c,l,u,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=n;function f(){l&&l(),u&&u(),n.cancelToken&&n.cancelToken.unsubscribe(o),n.signal&&n.signal.removeEventListener("abort",o)}let g=new XMLHttpRequest;function m(){if(!g)return;const n=ge.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());ye((function(e){t(e),f()}),(function(e){r(e),f()}),{data:d&&"text"!==d&&"json"!==d?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:n,config:e,request:g}),g=null}g.open(n.method.toUpperCase(),n.url,!0),g.timeout=n.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(r(new F("Request aborted",F.ECONNABORTED,e,g)),g=null)},g.onerror=function(){r(new F("Network Error",F.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const s=n.transitional||Y;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new F(t,s.clarifyTimeoutError?F.ETIMEDOUT:F.ECONNABORTED,e,g)),g=null},void 0===s&&i.setContentType(null),"setRequestHeader"in g&&D.forEach(i.toJSON(),(function(e,t){g.setRequestHeader(t,e)})),D.isUndefined(n.withCredentials)||(g.withCredentials=!!n.withCredentials),d&&"json"!==d&&(g.responseType=n.responseType),p&&([c,u]=be(p,!0),g.addEventListener("progress",c)),h&&g.upload&&([a,l]=be(h),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(o=t=>{g&&(r(!t||t.type?new we(null,e,g):t),g.abort(),g=null)},n.cancelToken&&n.cancelToken.subscribe(o),n.signal&&(n.signal.aborted?o():n.signal.addEventListener("abort",o)));const _=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(n.url);_&&-1===ie.protocols.indexOf(_)?r(new F("Unsupported protocol "+_+":",F.ERR_BAD_REQUEST,e)):g.send(s||null)}))};var Ce=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const s=function(e){if(!r){r=!0,o();const t=e instanceof Error?e:this.reason;n.abort(t instanceof F?t:new we(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,s(new F(`timeout ${t} of ms exceeded`,F.ETIMEDOUT))}),t);const o=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(s):e.removeEventListener("abort",s)})),e=null)};e.forEach((e=>e.addEventListener("abort",s)));const{signal:a}=n;return a.unsubscribe=()=>D.asap(o),a}};const Ne=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,s=0;for(;s<r;)n=s+t,yield e.slice(s,n),s=n},Pe=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},Ie=(e,t,r,n)=>{const s=async function*(e,t){for await(const r of Pe(e))yield*Ne(r,t)}(e,t);let i,o=0,a=e=>{i||(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await s.next();if(t)return a(),void e.close();let i=n.byteLength;if(r){let e=o+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(t){throw a(t),t}},cancel:e=>(a(e),s.return())},{highWaterMark:2})},Ue="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,je=Ue&&"function"==typeof ReadableStream,Le=Ue&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),De=(e,...t)=>{try{return!!e(...t)}catch(tn){return!1}},Fe=je&&De((()=>{let e=!1;const t=new Request(ie.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),Me=je&&De((()=>D.isReadableStream(new Response("").body))),qe={stream:Me&&(e=>e.body)};Ue&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach((t=>{!qe[t]&&(qe[t]=D.isFunction(e[t])?e=>e[t]():(e,r)=>{throw new F(`Response type '${t}' is not supported`,F.ERR_NOT_SUPPORT,r)})}))})(new Response);const Be=async(e,t)=>{const r=D.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(D.isBlob(e))return e.size;if(D.isSpecCompliantForm(e)){const t=new Request(ie.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return D.isArrayBufferView(e)||D.isArrayBuffer(e)?e.byteLength:(D.isURLSearchParams(e)&&(e+=""),D.isString(e)?(await Le(e)).byteLength:void 0)})(t):r};const He={http:null,xhr:Ae,fetch:Ue&&(async e=>{let{url:t,method:r,data:n,signal:s,cancelToken:i,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:u,withCredentials:d="same-origin",fetchOptions:h}=Oe(e);l=l?(l+"").toLowerCase():"text";let p,f=Ce([s,i&&i.toAbortSignal()],o);const g=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let m;try{if(c&&Fe&&"get"!==r&&"head"!==r&&0!==(m=await Be(u,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(D.isFormData(n)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=Se(m,be(ve(c)));n=Ie(r.body,65536,e,t)}}D.isString(d)||(d=d?"include":"omit");const s="credentials"in Request.prototype;p=new Request(t,{...h,signal:f,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:s?d:void 0});let i=await fetch(p,h);const o=Me&&("stream"===l||"response"===l);if(Me&&(a||o&&g)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=D.toFiniteNumber(i.headers.get("content-length")),[r,n]=a&&Se(t,be(ve(a),!0))||[];i=new Response(Ie(i.body,65536,r,(()=>{n&&n(),g&&g()})),e)}l=l||"text";let _=await qe[D.findKey(qe,l)||"text"](i,e);return!o&&g&&g(),await new Promise(((t,r)=>{ye(t,r,{data:_,headers:ge.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:p})}))}catch(_){if(g&&g(),_&&"TypeError"===_.name&&/Load failed|fetch/i.test(_.message))throw Object.assign(new F("Network Error",F.ERR_NETWORK,e,p),{cause:_.cause||_});throw F.from(_,_&&_.code,e,p)}})};D.forEach(He,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(tn){}Object.defineProperty(e,"adapterName",{value:t})}}));const ze=e=>`- ${e}`,We=e=>D.isFunction(e)||null===e||!1===e;var $e=e=>{e=D.isArray(e)?e:[e];const{length:t}=e;let r,n;const s={};for(let i=0;i<t;i++){let t;if(r=e[i],n=r,!We(r)&&(n=He[(t=String(r)).toLowerCase()],void 0===n))throw new F(`Unknown adapter '${t}'`);if(n)break;s[t||"#"+i]=n}if(!n){const e=Object.entries(s).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new F("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(ze).join("\n"):" "+ze(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n};function Ke(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new we(null,e)}function Je(e){Ke(e),e.headers=ge.from(e.headers),e.data=me.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return $e(e.adapter||ce.adapter)(e).then((function(t){return Ke(e),t.data=me.call(e,e.transformResponse,t),t.headers=ge.from(t.headers),t}),(function(t){return _e(t)||(Ke(e),t&&t.response&&(t.response.data=me.call(e,e.transformResponse,t.response),t.response.headers=ge.from(t.response.headers))),Promise.reject(t)}))}const Ve="1.10.0",Ge={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Ge[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const Xe={};Ge.transitional=function(e,t,r){function n(e,t){return"[Axios v"+Ve+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,s,i)=>{if(!1===e)throw new F(n(s," has been removed"+(t?" in "+t:"")),F.ERR_DEPRECATED);return t&&!Xe[s]&&(Xe[s]=!0,console.warn(n(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,s,i)}},Ge.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};var Qe={assertOptions:function(e,t,r){if("object"!=typeof e)throw new F("options must be an object",F.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const i=n[s],o=t[i];if(o){const t=e[i],r=void 0===t||o(t,i,e);if(!0!==r)throw new F("option "+i+" must be "+r,F.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new F("Unknown option "+i,F.ERR_BAD_OPTION)}},validators:Ge};const Ye=Qe.validators;class Ze{constructor(e){this.defaults=e||{},this.interceptors={request:new Q,response:new Q}}async request(e,t){try{return await this._request(e,t)}catch(r){if(r instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{r.stack?t&&!String(r.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(r.stack+="\n"+t):r.stack=t}catch(tn){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=xe(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:s}=t;void 0!==r&&Qe.assertOptions(r,{silentJSONParsing:Ye.transitional(Ye.boolean),forcedJSONParsing:Ye.transitional(Ye.boolean),clarifyTimeoutError:Ye.transitional(Ye.boolean)},!1),null!=n&&(D.isFunction(n)?t.paramsSerializer={serialize:n}:Qe.assertOptions(n,{encode:Ye.function,serialize:Ye.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Qe.assertOptions(t,{baseUrl:Ye.spelling("baseURL"),withXsrfToken:Ye.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=s&&D.merge(s.common,s[t.method]);s&&D.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete s[e]})),t.headers=ge.concat(i,s);const o=[];let a=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,o.unshift(e.fulfilled,e.rejected))}));const c=[];let l;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let u,d=0;if(!a){const e=[Je.bind(this),void 0];for(e.unshift.apply(e,o),e.push.apply(e,c),u=e.length,l=Promise.resolve(t);d<u;)l=l.then(e[d++],e[d++]);return l}u=o.length;let h=t;for(d=0;d<u;){const e=o[d++],t=o[d++];try{h=e(h)}catch(p){t.call(this,p);break}}try{l=Je.call(this,h)}catch(p){return Promise.reject(p)}for(d=0,u=c.length;d<u;)l=l.then(c[d++],c[d++]);return l}getUri(e){return X(Re((e=xe(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}D.forEach(["delete","get","head","options"],(function(e){Ze.prototype[e]=function(t,r){return this.request(xe(r||{},{method:e,url:t,data:(r||{}).data}))}})),D.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,s){return this.request(xe(s||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Ze.prototype[e]=t(),Ze.prototype[e+"Form"]=t(!0)}));var et=Ze;class tt{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,s){r.reason||(r.reason=new we(e,n,s),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new tt((function(t){e=t})),cancel:e}}}var rt=tt;const nt={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(nt).forEach((([e,t])=>{nt[t]=e}));var st=nt;const it=function t(r){const n=new et(r),s=e(et.prototype.request,n);return D.extend(s,et.prototype,n,{allOwnKeys:!0}),D.extend(s,n,null,{allOwnKeys:!0}),s.create=function(e){return t(xe(r,e))},s}(ce);return it.Axios=et,it.CanceledError=we,it.CancelToken=rt,it.isCancel=_e,it.VERSION=Ve,it.toFormData=$,it.AxiosError=F,it.Cancel=it.CanceledError,it.all=function(e){return Promise.all(e)},it.spread=function(e){return function(t){return e.apply(null,t)}},it.isAxiosError=function(e){return D.isObject(e)&&!0===e.isAxiosError},it.mergeConfig=xe,it.AxiosHeaders=ge,it.formToJSON=e=>oe(D.isHTMLForm(e)?new FormData(e):e),it.getAdapter=$e,it.HttpStatusCode=st,it.default=it,Xr=it}var en,tn;const rn=Gr((en||(en=1,Yr.exports=(tn=Zr(),function(){var e={593:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.resendFailedRequest=t.getRetryInstance=t.unsetCache=t.createRequestQueueInterceptor=t.createRefreshCall=t.shouldInterceptError=t.mergeOptions=t.defaultOptions=void 0;const n=r(300);t.defaultOptions={statusCodes:[401],pauseInstanceWhileRefreshing:!1},t.mergeOptions=function(e,t){return Object.assign(Object.assign(Object.assign({},e),{pauseInstanceWhileRefreshing:t.skipWhileRefreshing}),t)},t.shouldInterceptError=function(e,t,r,n){var s,i;return!(!e||(null===(s=e.config)||void 0===s?void 0:s.skipAuthRefresh)||!(t.interceptNetworkError&&!e.response&&0===e.request.status||e.response&&((null==t?void 0:t.shouldRefresh)?t.shouldRefresh(e):null===(i=t.statusCodes)||void 0===i?void 0:i.includes(parseInt(e.response.status))))||(e.response||(e.response={config:e.config}),t.pauseInstanceWhileRefreshing&&n.skipInstances.includes(r)))},t.createRefreshCall=function(e,t,r){return r.refreshCall||(r.refreshCall=t(e),"function"==typeof r.refreshCall.then)?r.refreshCall:(console.warn("axios-auth-refresh requires `refreshTokenCall` to return a promise."),Promise.reject())},t.createRequestQueueInterceptor=function(e,t,r){return void 0===t.requestQueueInterceptorId&&(t.requestQueueInterceptorId=e.interceptors.request.use((e=>t.refreshCall.catch((()=>{throw new n.default.Cancel("Request call failed")})).then((()=>r.onRetry?r.onRetry(e):e))))),t.requestQueueInterceptorId},t.unsetCache=function(e,t){e.interceptors.request.eject(t.requestQueueInterceptorId),t.requestQueueInterceptorId=void 0,t.refreshCall=void 0,t.skipInstances=t.skipInstances.filter((t=>t!==e))},t.getRetryInstance=function(e,t){return t.retryInstance||e},t.resendFailedRequest=function(e,t){return e.config.skipAuthRefresh=!0,t(e.response.config)}},300:function(e){e.exports=tn}},t={};function r(n){var s=t[n];if(void 0!==s)return s.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}var n={};return function(){var e=n;Object.defineProperty(e,"__esModule",{value:!0});const t=r(593);e.default=function(e,r,n={}){if("function"!=typeof r)throw new Error("axios-auth-refresh requires `refreshAuthCall` to be a function that returns a promise.");const s={skipInstances:[],refreshCall:void 0,requestQueueInterceptorId:void 0};return e.interceptors.response.use((e=>e),(i=>{if(n=(0,t.mergeOptions)(t.defaultOptions,n),!(0,t.shouldInterceptError)(i,n,e,s))return Promise.reject(i);n.pauseInstanceWhileRefreshing&&s.skipInstances.push(e);const o=(0,t.createRefreshCall)(i,r,s);return(0,t.createRequestQueueInterceptor)(e,s,n),o.catch((e=>Promise.reject(e))).then((()=>(0,t.resendFailedRequest)(i,(0,t.getRetryInstance)(e,n)))).finally((()=>(0,t.unsetCache)(e,s)))}))}}(),n}())),Yr.exports));var nn=class{constructor(e){this.apiKey=e}async getAccessToken(){return this.apiKey}async refreshToken(){return Promise.resolve()}},sn=class{constructor(e){i(this,"getTokenFn"),i(this,"refreshTokenFn"),i(this,"onRefreshErrorFn"),this.getTokenFn=e.getTokenFn,this.refreshTokenFn=e.refreshTokenFn,this.onRefreshErrorFn=e.onRefreshErrorFn}async getAccessToken(){return this.getTokenFn()}async refreshToken(){return this.refreshTokenFn()}onRefreshError(e){this.onRefreshErrorFn&&this.onRefreshErrorFn(e)}},on={baseUrl:"undefined"!=typeof process&&(null==(n=process.env)?void 0:n.ECHO_BASE_URL)||"https://echo.merit.systems"};var an=class e extends Error{constructor(t,r,n){super(r),i(this,"code"),i(this,"details"),i(this,"statusCode"),i(this,"endpoint"),i(this,"originalError"),this.name="EchoError",this.code=t,void 0!==(null==n?void 0:n.details)&&(this.details=n.details),void 0!==(null==n?void 0:n.statusCode)&&(this.statusCode=n.statusCode),void 0!==(null==n?void 0:n.endpoint)&&(this.endpoint=n.endpoint),void 0!==(null==n?void 0:n.originalError)&&(this.originalError=n.originalError),Error.captureStackTrace&&Error.captureStackTrace(this,e)}},cn=class extends an{constructor(e,t,r,n,s){const i={};void 0!==n&&(i.details=n),void 0!==r&&(i.statusCode=r),void 0!==s&&(i.endpoint=s),super(e,t,i),this.name="EchoApiError"}},ln=class extends an{constructor(e,t,r){const n={originalError:t};void 0!==r&&(n.endpoint=r),super("NETWORK_ERROR",e,n),this.name="EchoNetworkError"}},un=class extends an{constructor(e,t,r){const n={};void 0!==r&&(n.endpoint=r),super("TIMEOUT_ERROR",e,n),i(this,"timeout"),this.name="EchoTimeoutError",this.timeout=t}},dn="UNAUTHORIZED",hn="TOKEN_EXPIRED",pn="INVALID_TOKEN",fn="BAD_REQUEST",gn="NOT_FOUND",mn="RATE_LIMITED",_n="INSUFFICIENT_BALANCE",wn="VALIDATION_ERROR",yn="NETWORK_ERROR",bn="TIMEOUT_ERROR",Sn="SERVER_ERROR",vn="SERVICE_UNAVAILABLE";function En(e,t,r){if(e&&"object"==typeof e&&"isAxiosError"in e){const n=e;if("ECONNABORTED"===n.code)return new un("Request timeout"+(t?` while ${t}`:""),3e4,r);if(!n.response)return new ln("Network error"+(t?` while ${t}`:""),n,r);const s=n.response.status,i=n.response.data;let o,a;const c=(null==i?void 0:i.error)||(null==i?void 0:i.message);switch(s){case 401:o=dn,a=c||"Authentication required. Please sign in again.";break;case 403:o=pn,a=c||"Access denied. Your session may have expired.";break;case 404:o=gn,a=c||"Resource not found";break;case 429:o=mn,a=c||"Too many requests. Please try again later.";break;case 400:o=fn,a=c||"Invalid request";break;case 402:o=_n,a=c||"Insufficient balance. Please add credits to continue.";break;case 422:o=wn,a=c||"Validation failed";break;case 503:o=vn,a=c||"Service temporarily unavailable. Please try again.";break;default:o=Sn,a=c||"An unexpected error occurred"}return new cn(o,t?`Failed to ${t}: ${a}`:a,s,(null==i?void 0:i.details)||(null==i?void 0:i.error_description),r)}return e instanceof Error?new ln(e.message||"Unknown error"+(t?` while ${t}`:""),e,r):"string"==typeof e?new cn(Sn,e,void 0,void 0,r):new cn(Sn,"Unknown error"+(t?` while ${t}`:""),void 0,String(e),r)}function kn(e){switch(e.code){case dn:case hn:case pn:return"Please sign in to continue";case _n:return"Insufficient balance. Please add credits to your account.";case mn:return"Too many requests. Please wait a moment and try again.";case yn:return"Connection failed. Please check your internet connection.";case bn:return"Request timed out. Please try again.";case vn:return"Service is temporarily unavailable. Please try again later.";case gn:return e.message||"The requested resource was not found.";case wn:return e.message||"Please check your input and try again.";default:return e.message||"An unexpected error occurred. Please try again."}}var Rn=class{constructor(e){this.http=e}async handleRequest(e,t,r){try{return(await e()).data}catch(n){throw En(n,t,r)}}handleError(e,t,r){throw En(e,t,r)}},Tn=class extends Rn{constructor(e,t){super(e),this.baseUrl=t}async listEchoApps(){return(await this.handleRequest((()=>this.http.get("/api/v1/apps")),"listing Echo apps","/api/v1/apps")).apps}async getEchoApp(e){return this.handleRequest((()=>this.http.get(`/api/v1/apps/${e}`)),"fetching Echo app",`/api/v1/apps/${e}`)}getAppUrl(e){return`${this.baseUrl}/apps/${e}`}},xn=class extends Rn{constructor(e){super(e)}async getBalance(){return this.handleRequest((()=>this.http.get("/api/v1/balance")),"fetching balance","/api/v1/balance")}async getFreeBalance(e){const t={echoAppId:e};return this.handleRequest((()=>this.http.post("/api/v1/balance/free",t)),"fetching free tier balance","/api/v1/balance/free")}},On=class extends Rn{constructor(e){super(e)}async getSupportedModels(){return this.handleRequest((()=>this.http.get("/api/v1/supported-models")),"fetching supported models","/api/v1/supported-models")}async listSupportedModels(){try{return(await this.getSupportedModels()).models}catch(e){throw this.handleError(e,"listing supported models")}}async getSupportedModelsByProvider(){try{return(await this.getSupportedModels()).models_by_provider}catch(e){throw this.handleError(e,"getting models by provider")}}},An=class extends Rn{constructor(e){super(e)}async createPaymentLink(e){return this.handleRequest((()=>this.http.post("/api/v1/stripe/payment-link",e)),"creating payment link","/api/v1/stripe/payment-link")}async getPaymentUrl(e,t,r){const n={amount:e,description:t||"Echo Credits"};r&&(n.successUrl=r);try{return(await this.createPaymentLink(n)).paymentLink.url}catch(s){throw this.handleError(s,"getting payment URL")}}},Cn=class extends Rn{constructor(e){super(e)}async getUserInfo(){return this.handleRequest((()=>this.http.get("/api/v1/user")),"fetching user info","/api/v1/user")}async registerReferralCode(e,t){const r={echoAppId:e,code:t};return this.handleRequest((()=>this.http.post("/api/v1/user/referral",r)),"registering referral code","/api/v1/user/referral")}},Nn=class{constructor(e){var t;if(i(this,"http"),i(this,"config"),i(this,"tokenProvider"),i(this,"balance"),i(this,"payments"),i(this,"apps"),i(this,"users"),i(this,"models"),this.config=(t=e,{...on,...t}),null==e?void 0:e.tokenProvider)this.tokenProvider=e.tokenProvider;else{const e=this.config.apiKey||process.env.ECHO_API_KEY;if(!e)throw new Error("No API key or token provider provided");this.tokenProvider=new nn(e)}this.http=Nr.create({baseURL:this.config.baseUrl,timeout:3e4}),this.http.interceptors.request.use((async e=>{const t=await this.tokenProvider.getAccessToken();return t&&(e.headers.Authorization=`Bearer ${t}`),e}));rn(this.http,(async e=>{try{await this.tokenProvider.refreshToken();const t=await this.tokenProvider.getAccessToken();return t&&(e.response.config.headers.Authorization=`Bearer ${t}`),Promise.resolve()}catch(t){return this.tokenProvider.onRefreshError&&this.tokenProvider.onRefreshError(t),Promise.reject(t)}}),{statusCodes:[401],pauseInstanceWhileRefreshing:!0}),this.balance=new xn(this.http),this.payments=new An(this.http),this.apps=new Tn(this.http,this.config.baseUrl),this.users=new Cn(this.http),this.models=new On(this.http)}};function Pn({apiUrl:e}){var t;const n=Te(),[s,i]=r.useState(null);return r.useEffect((()=>{var t;if(!(null==(t=n.user)?void 0:t.access_token))return void i(null);const r=new sn({getTokenFn:()=>{var e;return Promise.resolve((null==(e=n.user)?void 0:e.access_token)||null)},refreshTokenFn:async()=>{await n.signinSilent()},onRefreshErrorFn:e=>{console.error("Token refresh failed:",e),n.signoutSilent()}}),s=new Nn({baseUrl:e,tokenProvider:r});return i(s),()=>{i(null)}}),[e,null==(t=n.user)?void 0:t.access_token,n.signinSilent,n.signoutSilent]),s}const In=r.createContext(null);function Un({config:e,children:n}){var s,i,o;const a=Te(),c=a.user,l=c?function(e){return{id:e.profile.sub||"",email:e.profile.email||"",name:e.profile.name||e.profile.preferred_username||"",picture:e.profile.picture||""}}(c):null,u=e.apiUrl||"https://echo.merit.systems",d=(null==(s=a.user)?void 0:s.access_token)||null,h=Pn({apiUrl:u}),{balance:p,freeTierBalance:f,refreshBalance:g,error:m,isLoading:_}=function(e,t){const[n,s]=r.useState(null),[i,o]=r.useState(null),[a,c]=r.useState(null),[l,u]=r.useState(!1),d=r.useCallback((async()=>{if(!e)throw new Error("Not authenticated");u(!0);try{const[r,n]=await Promise.all([e.balance.getBalance(),e.balance.getFreeBalance(t)]);s(r),o(n),c(null)}catch(r){const e=En(r,"refreshing balance"),t=kn(e);throw c(t),e}finally{u(!1)}}),[e,t]);return r.useEffect((()=>{e&&t?d().catch((e=>{console.error("Error loading initial balance:",e)})):(s(null),o(null),c(null))}),[e,t,d]),{balance:n,freeTierBalance:i,error:a,isLoading:l,refreshBalance:d}}(h,e.appId),{createPaymentLink:w,error:y,isLoading:b}=function(e){const[t,n]=r.useState(null),[s,i]=r.useState(!1);return{createPaymentLink:r.useCallback((async(t,r,s)=>{if(!e)throw new Error("Not authenticated");i(!0);try{const i=await e.payments.createPaymentLink({amount:t,description:r||"Echo Credits",successUrl:s||window.location.origin});return n(null),i.paymentLink.url}catch(o){const e=En(o,"creating payment link"),t=kn(e);throw n(t),e}finally{i(!1)}}),[e]),error:t,isLoading:s}}(h),S=r.useCallback((async()=>{try{await a.removeUser()}catch(e){console.error("Error during auth cleanup:",e)}}),[a.removeUser]),v=r.useCallback((async()=>{var e;return(null==(e=a.user)?void 0:e.access_token)||null}),[null==(i=a.user)?void 0:i.access_token]),E=(null==(o=a.error)?void 0:o.message)||m||y||null,k=a.isLoading||_||b,R={user:l||null,rawUser:c,balance:p,freeTierBalance:f,isAuthenticated:a.isAuthenticated,isLoading:k,error:E,token:d,echoClient:h,signIn:a.signinRedirect,signOut:S,refreshBalance:g,createPaymentLink:w,getToken:v,clearAuth:S};return t.jsx(In.Provider,{value:R,children:n})}function jn(){const e=r.useContext(In);if(!e)throw new Error("useEcho must be used within an EchoProvider");return e}
3
+ /*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */const{entries:Ln,setPrototypeOf:Dn,isFrozen:Fn,getPrototypeOf:Mn,getOwnPropertyDescriptor:qn}=Object;let{freeze:Bn,seal:Hn,create:zn}=Object,{apply:Wn,construct:$n}="undefined"!=typeof Reflect&&Reflect;Bn||(Bn=function(e){return e}),Hn||(Hn=function(e){return e}),Wn||(Wn=function(e,t,r){return e.apply(t,r)}),$n||($n=function(e,t){return new e(...t)});const Kn=as(Array.prototype.forEach),Jn=as(Array.prototype.lastIndexOf),Vn=as(Array.prototype.pop),Gn=as(Array.prototype.push),Xn=as(Array.prototype.splice),Qn=as(String.prototype.toLowerCase),Yn=as(String.prototype.toString),Zn=as(String.prototype.match),es=as(String.prototype.replace),ts=as(String.prototype.indexOf),rs=as(String.prototype.trim),ns=as(Object.prototype.hasOwnProperty),ss=as(RegExp.prototype.test),is=(os=TypeError,function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return $n(os,t)});var os;function as(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var r=arguments.length,n=new Array(r>1?r-1:0),s=1;s<r;s++)n[s-1]=arguments[s];return Wn(e,t,n)}}function cs(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Qn;Dn&&Dn(e,null);let n=t.length;for(;n--;){let s=t[n];if("string"==typeof s){const e=r(s);e!==s&&(Fn(t)||(t[n]=e),s=e)}e[s]=!0}return e}function ls(e){for(let t=0;t<e.length;t++){ns(e,t)||(e[t]=null)}return e}function us(e){const t=zn(null);for(const[r,n]of Ln(e)){ns(e,r)&&(Array.isArray(n)?t[r]=ls(n):n&&"object"==typeof n&&n.constructor===Object?t[r]=us(n):t[r]=n)}return t}function ds(e,t){for(;null!==e;){const r=qn(e,t);if(r){if(r.get)return as(r.get);if("function"==typeof r.value)return as(r.value)}e=Mn(e)}return function(){return null}}const hs=Bn(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),ps=Bn(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),fs=Bn(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),gs=Bn(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),ms=Bn(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),_s=Bn(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ws=Bn(["#text"]),ys=Bn(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),bs=Bn(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Ss=Bn(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),vs=Bn(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Es=Hn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),ks=Hn(/<%[\w\W]*|[\w\W]*%>/gm),Rs=Hn(/\$\{[\w\W]*/gm),Ts=Hn(/^data-[\-\w.\u00B7-\uFFFF]+$/),xs=Hn(/^aria-[\-\w]+$/),Os=Hn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),As=Hn(/^(?:\w+script|data):/i),Cs=Hn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ns=Hn(/^html$/i),Ps=Hn(/^[a-z][.\w]*(-[.\w]+)+$/i);var Is=Object.freeze({__proto__:null,ARIA_ATTR:xs,ATTR_WHITESPACE:Cs,CUSTOM_ELEMENT:Ps,DATA_ATTR:Ts,DOCTYPE_NAME:Ns,ERB_EXPR:ks,IS_ALLOWED_URI:Os,IS_SCRIPT_OR_DATA:As,MUSTACHE_EXPR:Es,TMPLIT_EXPR:Rs});const Us=1,js=3,Ls=7,Ds=8,Fs=9;var Ms=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"undefined"==typeof window?null:window;const r=t=>e(t);if(r.version="3.2.6",r.removed=[],!t||!t.document||t.document.nodeType!==Fs||!t.Element)return r.isSupported=!1,r;let{document:n}=t;const s=n,i=s.currentScript,{DocumentFragment:o,HTMLTemplateElement:a,Node:c,Element:l,NodeFilter:u,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:h,DOMParser:p,trustedTypes:f}=t,g=l.prototype,m=ds(g,"cloneNode"),_=ds(g,"remove"),w=ds(g,"nextSibling"),y=ds(g,"childNodes"),b=ds(g,"parentNode");if("function"==typeof a){const e=n.createElement("template");e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let S,v="";const{implementation:E,createNodeIterator:k,createDocumentFragment:R,getElementsByTagName:T}=n,{importNode:x}=s;let O={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};r.isSupported="function"==typeof Ln&&"function"==typeof b&&E&&void 0!==E.createHTMLDocument;const{MUSTACHE_EXPR:A,ERB_EXPR:C,TMPLIT_EXPR:N,DATA_ATTR:P,ARIA_ATTR:I,IS_SCRIPT_OR_DATA:U,ATTR_WHITESPACE:j,CUSTOM_ELEMENT:L}=Is;let{IS_ALLOWED_URI:D}=Is,F=null;const M=cs({},[...hs,...ps,...fs,...ms,...ws]);let q=null;const B=cs({},[...ys,...bs,...Ss,...vs]);let H=Object.seal(zn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),z=null,W=null,$=!0,K=!0,J=!1,V=!0,G=!1,X=!0,Q=!1,Y=!1,Z=!1,ee=!1,te=!1,re=!1,ne=!0,se=!1,ie=!0,oe=!1,ae={},ce=null;const le=cs({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let ue=null;const de=cs({},["audio","video","img","source","image","track"]);let he=null;const pe=cs({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),fe="http://www.w3.org/1998/Math/MathML",ge="http://www.w3.org/2000/svg",me="http://www.w3.org/1999/xhtml";let _e=me,we=!1,ye=null;const be=cs({},[fe,ge,me],Yn);let Se=cs({},["mi","mo","mn","ms","mtext"]),ve=cs({},["annotation-xml"]);const Ee=cs({},["title","style","font","a","script"]);let ke=null;const Re=["application/xhtml+xml","text/html"];let Te=null,xe=null;const Oe=n.createElement("form"),Ae=function(e){return e instanceof RegExp||e instanceof Function},Ce=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!xe||xe!==e){if(e&&"object"==typeof e||(e={}),e=us(e),ke=-1===Re.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Te="application/xhtml+xml"===ke?Yn:Qn,F=ns(e,"ALLOWED_TAGS")?cs({},e.ALLOWED_TAGS,Te):M,q=ns(e,"ALLOWED_ATTR")?cs({},e.ALLOWED_ATTR,Te):B,ye=ns(e,"ALLOWED_NAMESPACES")?cs({},e.ALLOWED_NAMESPACES,Yn):be,he=ns(e,"ADD_URI_SAFE_ATTR")?cs(us(pe),e.ADD_URI_SAFE_ATTR,Te):pe,ue=ns(e,"ADD_DATA_URI_TAGS")?cs(us(de),e.ADD_DATA_URI_TAGS,Te):de,ce=ns(e,"FORBID_CONTENTS")?cs({},e.FORBID_CONTENTS,Te):le,z=ns(e,"FORBID_TAGS")?cs({},e.FORBID_TAGS,Te):us({}),W=ns(e,"FORBID_ATTR")?cs({},e.FORBID_ATTR,Te):us({}),ae=!!ns(e,"USE_PROFILES")&&e.USE_PROFILES,$=!1!==e.ALLOW_ARIA_ATTR,K=!1!==e.ALLOW_DATA_ATTR,J=e.ALLOW_UNKNOWN_PROTOCOLS||!1,V=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,G=e.SAFE_FOR_TEMPLATES||!1,X=!1!==e.SAFE_FOR_XML,Q=e.WHOLE_DOCUMENT||!1,ee=e.RETURN_DOM||!1,te=e.RETURN_DOM_FRAGMENT||!1,re=e.RETURN_TRUSTED_TYPE||!1,Z=e.FORCE_BODY||!1,ne=!1!==e.SANITIZE_DOM,se=e.SANITIZE_NAMED_PROPS||!1,ie=!1!==e.KEEP_CONTENT,oe=e.IN_PLACE||!1,D=e.ALLOWED_URI_REGEXP||Os,_e=e.NAMESPACE||me,Se=e.MATHML_TEXT_INTEGRATION_POINTS||Se,ve=e.HTML_INTEGRATION_POINTS||ve,H=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Ae(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(H.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Ae(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(H.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(H.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),G&&(K=!1),te&&(ee=!0),ae&&(F=cs({},ws),q=[],!0===ae.html&&(cs(F,hs),cs(q,ys)),!0===ae.svg&&(cs(F,ps),cs(q,bs),cs(q,vs)),!0===ae.svgFilters&&(cs(F,fs),cs(q,bs),cs(q,vs)),!0===ae.mathMl&&(cs(F,ms),cs(q,Ss),cs(q,vs))),e.ADD_TAGS&&(F===M&&(F=us(F)),cs(F,e.ADD_TAGS,Te)),e.ADD_ATTR&&(q===B&&(q=us(q)),cs(q,e.ADD_ATTR,Te)),e.ADD_URI_SAFE_ATTR&&cs(he,e.ADD_URI_SAFE_ATTR,Te),e.FORBID_CONTENTS&&(ce===le&&(ce=us(ce)),cs(ce,e.FORBID_CONTENTS,Te)),ie&&(F["#text"]=!0),Q&&cs(F,["html","head","body"]),F.table&&(cs(F,["tbody"]),delete z.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw is('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw is('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');S=e.TRUSTED_TYPES_POLICY,v=S.createHTML("")}else void 0===S&&(S=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let r=null;const n="data-tt-policy-suffix";t&&t.hasAttribute(n)&&(r=t.getAttribute(n));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML:e=>e,createScriptURL:e=>e})}catch(i){return console.warn("TrustedTypes policy "+s+" could not be created."),null}}(f,i)),null!==S&&"string"==typeof v&&(v=S.createHTML(""));Bn&&Bn(e),xe=e}},Ne=cs({},[...ps,...fs,...gs]),Pe=cs({},[...ms,..._s]),Ie=function(e){Gn(r.removed,{element:e});try{b(e).removeChild(e)}catch(t){_(e)}},Ue=function(e,t){try{Gn(r.removed,{attribute:t.getAttributeNode(e),from:t})}catch(n){Gn(r.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ee||te)try{Ie(t)}catch(n){}else try{t.setAttribute(e,"")}catch(n){}},je=function(e){let t=null,r=null;if(Z)e="<remove></remove>"+e;else{const t=Zn(e,/^[\r\n\t ]+/);r=t&&t[0]}"application/xhtml+xml"===ke&&_e===me&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const s=S?S.createHTML(e):e;if(_e===me)try{t=(new p).parseFromString(s,ke)}catch(o){}if(!t||!t.documentElement){t=E.createDocument(_e,"template",null);try{t.documentElement.innerHTML=we?v:s}catch(o){}}const i=t.body||t.documentElement;return e&&r&&i.insertBefore(n.createTextNode(r),i.childNodes[0]||null),_e===me?T.call(t,Q?"html":"body")[0]:Q?t.documentElement:i},Le=function(e){return k.call(e.ownerDocument||e,e,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},De=function(e){return e instanceof h&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof d)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},Fe=function(e){return"function"==typeof c&&e instanceof c};function Me(e,t,n){Kn(e,(e=>{e.call(r,t,n,xe)}))}const qe=function(e){let t=null;if(Me(O.beforeSanitizeElements,e,null),De(e))return Ie(e),!0;const n=Te(e.nodeName);if(Me(O.uponSanitizeElement,e,{tagName:n,allowedTags:F}),X&&e.hasChildNodes()&&!Fe(e.firstElementChild)&&ss(/<[/\w!]/g,e.innerHTML)&&ss(/<[/\w!]/g,e.textContent))return Ie(e),!0;if(e.nodeType===Ls)return Ie(e),!0;if(X&&e.nodeType===Ds&&ss(/<[/\w]/g,e.data))return Ie(e),!0;if(!F[n]||z[n]){if(!z[n]&&He(n)){if(H.tagNameCheck instanceof RegExp&&ss(H.tagNameCheck,n))return!1;if(H.tagNameCheck instanceof Function&&H.tagNameCheck(n))return!1}if(ie&&!ce[n]){const t=b(e)||e.parentNode,r=y(e)||e.childNodes;if(r&&t){for(let n=r.length-1;n>=0;--n){const s=m(r[n],!0);s.__removalCount=(e.__removalCount||0)+1,t.insertBefore(s,w(e))}}}return Ie(e),!0}return e instanceof l&&!function(e){let t=b(e);t&&t.tagName||(t={namespaceURI:_e,tagName:"template"});const r=Qn(e.tagName),n=Qn(t.tagName);return!!ye[e.namespaceURI]&&(e.namespaceURI===ge?t.namespaceURI===me?"svg"===r:t.namespaceURI===fe?"svg"===r&&("annotation-xml"===n||Se[n]):Boolean(Ne[r]):e.namespaceURI===fe?t.namespaceURI===me?"math"===r:t.namespaceURI===ge?"math"===r&&ve[n]:Boolean(Pe[r]):e.namespaceURI===me?!(t.namespaceURI===ge&&!ve[n])&&!(t.namespaceURI===fe&&!Se[n])&&!Pe[r]&&(Ee[r]||!Ne[r]):!("application/xhtml+xml"!==ke||!ye[e.namespaceURI]))}(e)?(Ie(e),!0):"noscript"!==n&&"noembed"!==n&&"noframes"!==n||!ss(/<\/no(script|embed|frames)/i,e.innerHTML)?(G&&e.nodeType===js&&(t=e.textContent,Kn([A,C,N],(e=>{t=es(t,e," ")})),e.textContent!==t&&(Gn(r.removed,{element:e.cloneNode()}),e.textContent=t)),Me(O.afterSanitizeElements,e,null),!1):(Ie(e),!0)},Be=function(e,t,r){if(ne&&("id"===t||"name"===t)&&(r in n||r in Oe))return!1;if(K&&!W[t]&&ss(P,t));else if($&&ss(I,t));else if(!q[t]||W[t]){if(!(He(e)&&(H.tagNameCheck instanceof RegExp&&ss(H.tagNameCheck,e)||H.tagNameCheck instanceof Function&&H.tagNameCheck(e))&&(H.attributeNameCheck instanceof RegExp&&ss(H.attributeNameCheck,t)||H.attributeNameCheck instanceof Function&&H.attributeNameCheck(t))||"is"===t&&H.allowCustomizedBuiltInElements&&(H.tagNameCheck instanceof RegExp&&ss(H.tagNameCheck,r)||H.tagNameCheck instanceof Function&&H.tagNameCheck(r))))return!1}else if(he[t]);else if(ss(D,es(r,j,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==ts(r,"data:")||!ue[e]){if(J&&!ss(U,es(r,j,"")));else if(r)return!1}else;return!0},He=function(e){return"annotation-xml"!==e&&Zn(e,L)},ze=function(e){Me(O.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||De(e))return;const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:q,forceKeepAttr:void 0};let s=t.length;for(;s--;){const o=t[s],{name:a,namespaceURI:c,value:l}=o,u=Te(a),d=l;let h="value"===a?d:rs(d);if(n.attrName=u,n.attrValue=h,n.keepAttr=!0,n.forceKeepAttr=void 0,Me(O.uponSanitizeAttribute,e,n),h=n.attrValue,!se||"id"!==u&&"name"!==u||(Ue(a,e),h="user-content-"+h),X&&ss(/((--!?|])>)|<\/(style|title)/i,h)){Ue(a,e);continue}if(n.forceKeepAttr)continue;if(!n.keepAttr){Ue(a,e);continue}if(!V&&ss(/\/>/i,h)){Ue(a,e);continue}G&&Kn([A,C,N],(e=>{h=es(h,e," ")}));const p=Te(e.nodeName);if(Be(p,u,h)){if(S&&"object"==typeof f&&"function"==typeof f.getAttributeType)if(c);else switch(f.getAttributeType(p,u)){case"TrustedHTML":h=S.createHTML(h);break;case"TrustedScriptURL":h=S.createScriptURL(h)}if(h!==d)try{c?e.setAttributeNS(c,a,h):e.setAttribute(a,h),De(e)?Ie(e):Vn(r.removed)}catch(i){Ue(a,e)}}else Ue(a,e)}Me(O.afterSanitizeAttributes,e,null)},We=function e(t){let r=null;const n=Le(t);for(Me(O.beforeSanitizeShadowDOM,t,null);r=n.nextNode();)Me(O.uponSanitizeShadowNode,r,null),qe(r),ze(r),r.content instanceof o&&e(r.content);Me(O.afterSanitizeShadowDOM,t,null)};return r.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,i=null,a=null,l=null;if(we=!e,we&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Fe(e)){if("function"!=typeof e.toString)throw is("toString is not a function");if("string"!=typeof(e=e.toString()))throw is("dirty is not a string, aborting")}if(!r.isSupported)return e;if(Y||Ce(t),r.removed=[],"string"==typeof e&&(oe=!1),oe){if(e.nodeName){const t=Te(e.nodeName);if(!F[t]||z[t])throw is("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)n=je("\x3c!----\x3e"),i=n.ownerDocument.importNode(e,!0),i.nodeType===Us&&"BODY"===i.nodeName||"HTML"===i.nodeName?n=i:n.appendChild(i);else{if(!ee&&!G&&!Q&&-1===e.indexOf("<"))return S&&re?S.createHTML(e):e;if(n=je(e),!n)return ee?null:re?v:""}n&&Z&&Ie(n.firstChild);const u=Le(oe?e:n);for(;a=u.nextNode();)qe(a),ze(a),a.content instanceof o&&We(a.content);if(oe)return e;if(ee){if(te)for(l=R.call(n.ownerDocument);n.firstChild;)l.appendChild(n.firstChild);else l=n;return(q.shadowroot||q.shadowrootmode)&&(l=x.call(s,l,!0)),l}let d=Q?n.outerHTML:n.innerHTML;return Q&&F["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&ss(Ns,n.ownerDocument.doctype.name)&&(d="<!DOCTYPE "+n.ownerDocument.doctype.name+">\n"+d),G&&Kn([A,C,N],(e=>{d=es(d,e," ")})),S&&re?S.createHTML(d):d},r.setConfig=function(){Ce(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),Y=!0},r.clearConfig=function(){xe=null,Y=!1},r.isValidAttribute=function(e,t,r){xe||Ce({});const n=Te(e),s=Te(t);return Be(n,s,r)},r.addHook=function(e,t){"function"==typeof t&&Gn(O[e],t)},r.removeHook=function(e,t){if(void 0!==t){const r=Jn(O[e],t);return-1===r?void 0:Xn(O[e],r,1)[0]}return Vn(O[e])},r.removeHooks=function(e){O[e]=[]},r.removeAllHooks=function(){O={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},r}();const qs=(()=>{if("undefined"!=typeof window)return Ms;try{const{JSDOM:e}=require("jsdom"),{window:t}=new e("");return Ms(t)}catch{return{sanitize:e=>String(e||"").replace(/<[^>]*>/g,"")}}})();function Bs(e){if(!e)return"";const t=String(e);try{let e=qs.sanitize(t,{ALLOWED_TAGS:[],ALLOWED_ATTR:[],KEEP_CONTENT:!0,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,FORCE_BODY:!0});if(!e.trim()&&t){t.replace(/<[^>]*>/g,"").trim()&&(e=t.replace(/<[^>]*>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").trim())}return e.trim().slice(0,1e3)}catch{return t.replace(/<[^>]*>/g,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").trim().slice(0,1e3)}}async function Hs(e,t={}){const{onComplete:r,onCancel:n,onError:s}=t,i=function(e){if(!e)return"";const t=Bs(e);try{const e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol?t:""}catch{return""}}(e);if(!i){const e=new Error("Invalid payment URL provided");throw null==s||s(e),e}try{const e=window.open(i,"echo-payment","width=600,height=700,scrollbars=yes,resizable=yes");if(e&&!e.closed)return new Promise((t=>{const s=()=>{try{if(e.closed)return null==r||r(),void t();setTimeout(s,1e3)}catch{null==r||r(),t()}};s(),setTimeout((()=>{e.close(),null==n||n(),t()}),6e5)}));return confirm("Payment will open in a new tab. Click OK to continue, or Cancel to abort.")?(sessionStorage.setItem("echo_payment_flow","true"),window.location.href=i,new Promise((e=>{const t=()=>{"completed"===sessionStorage.getItem("echo_payment_flow")&&(sessionStorage.removeItem("echo_payment_flow"),null==r||r(),window.removeEventListener("focus",t),e())};window.addEventListener("focus",t),setTimeout((()=>{window.removeEventListener("focus",t),sessionStorage.removeItem("echo_payment_flow"),null==n||n(),e()}),18e5)}))):(null==n||n(),Promise.resolve())}catch(o){const e=o instanceof Error?o:new Error("Payment flow failed");throw null==s||s(e),e}}const zs=({className:e="",width:r=16,height:n=16,variant:s="light"})=>{const i="dark"===s?"#DFE2D9":"#232323";return t.jsxs("svg",{id:"Layer_1","data-name":"Layer 1",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 226.03 261",className:e,width:r,height:n,"aria-label":"Echo Logo",children:[t.jsx("defs",{children:t.jsx("style",{children:`\n .cls-1 {\n fill: none;\n }\n .cls-3 {\n fill: #7f0404;\n }\n .cls-4 {\n fill: ${i};\n }\n .cls-5 {\n fill: #a50404;\n }\n .cls-6 {\n fill: #cd0202;\n opacity: .9;\n }\n `})}),t.jsx("polygon",{className:"cls-6",points:"59.23 99.45 59.23 161.55 113.02 192.61 113.02 130.5 59.23 99.45"}),t.jsx("polygon",{className:"cls-5",points:"113.02 68.39 113.02 68.39 59.23 99.45 113.02 130.5 166.8 99.45 113.02 68.39"}),t.jsx("polygon",{className:"cls-3",points:"166.8 99.45 113.02 130.5 113.02 192.61 113.02 192.61 166.8 161.55 166.8 99.45"}),t.jsxs("g",{children:[t.jsx("path",{className:"cls-4",d:"m113.02,196.41l-57.08-32.95v-65.91l57.08-32.95,57.08,32.95v65.91l-57.08,32.95Zm-52.53-35.58l52.53,30.33,52.53-30.33v-60.66l-52.53-30.33-52.53,30.33v60.66Z"}),t.jsx("path",{className:"cls-4",d:"m113.02,261L0,195.75V65.25L113.02,0l113.02,65.25v130.5l-113.02,65.25ZM6.82,191.81l106.2,61.31,106.2-61.31v-122.62L113.02,7.88,6.82,69.19v122.62Z"}),t.jsx("rect",{className:"cls-4",x:"111.88",y:"3.94",width:"2.27",height:"63.28"}),t.jsx("rect",{className:"cls-4",x:"-.83",y:"176.82",width:"63.28",height:"2.27",transform:"translate(-84.84 39.24) rotate(-29.99)"}),t.jsx("rect",{className:"cls-4",x:"194.08",y:"146.32",width:"2.27",height:"63.28",transform:"translate(-56.51 258.05) rotate(-60)"}),t.jsx("rect",{className:"cls-4",x:"111.88",y:"130.5",width:"2.27",height:"126.56"}),t.jsx("rect",{className:"cls-4",x:"104.54",y:"97.72",width:"126.56",height:"2.27",transform:"translate(-26.95 97.14) rotate(-29.99)"}),t.jsx("rect",{className:"cls-4",x:"57.08",y:"35.58",width:"2.27",height:"126.56",transform:"translate(-56.51 99.84) rotate(-60)"})]})]})};const Ws=({onAddCredits:e,onCancel:n,isProcessing:s})=>{const[i,o]=r.useState(""),a=r.useRef(null);r.useEffect((()=>{a.current&&a.current.focus()}),[]);const c=""!==i&&Number(i)>0;return t.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:"8px"},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx("span",{style:{fontSize:"14px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"$"}),t.jsx("input",{ref:a,type:"number",placeholder:"0.00",value:i,onChange:e=>o(e.target.value),style:{width:"96px",textAlign:"right",padding:"8px 12px",border:"1px solid #e5e7eb",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",outline:"none",backgroundColor:"#ffffff"},min:"1",step:"0.01"})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t.jsx("button",{onClick:n,style:{padding:"8px 12px",backgroundColor:"transparent",color:"#6b7280",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif",textDecoration:"none"},onMouseEnter:e=>{e.currentTarget.style.color="#111827"},onMouseLeave:e=>{e.currentTarget.style.color="#6b7280"},children:"Cancel"}),t.jsx("button",{onClick:()=>{const t=Number(i);t>0&&e(t)},disabled:s||!c,style:{padding:"8px 16px",backgroundColor:s||!c?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"500",cursor:s||!c?"not-allowed":"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{!s&&c&&(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{!s&&c&&(e.currentTarget.style.backgroundColor="#dc2626")},children:s?"Processing...":"Add Credits"})]})]})};e.EchoProvider=function({config:e,children:n}){const[s,i]=r.useState(!1);if(r.useEffect((()=>{i(!0)}),[]),!s)return null;const o=e.apiUrl||"https://echo.merit.systems",a={userManager:"undefined"!=typeof window&&window.__echoUserManager||new de({authority:o,client_id:e.appId,redirect_uri:e.redirectUri||window.location.origin,scope:e.scope||"llm:invoke offline_access",silentRequestTimeoutInSeconds:10,silent_redirect_uri:e.redirectUri||window.location.origin,includeIdTokenInSilentRenew:!1,validateSubOnSilentRenew:!0,loadUserInfo:!0,metadata:{authorization_endpoint:`${o}/api/oauth/authorize`,token_endpoint:`${o}/api/oauth/token`,userinfo_endpoint:`${o}/api/oauth/userinfo`,issuer:o,jwks_uri:`${o}/.well-known/jwks.json`,end_session_endpoint:`${o}/api/oauth/logout`},userStore:new N({store:window.localStorage})}),onSigninCallback:()=>{window.location.search.includes("code=")&&window.history.replaceState({},document.title,window.location.pathname)}};return t.jsx(Re,{...a,children:t.jsx(Un,{config:e,children:n})})},e.EchoSignIn=function({onSuccess:e,onError:n,className:s="",children:i}){const{signIn:o,isAuthenticated:a,isLoading:c,user:l,error:u}=jn(),[d,h]=r.useState(!1);r.useEffect((()=>{a&&l&&e&&e(l)}),[a,l,e]),r.useEffect((()=>{u&&n&&n(new Error(u))}),[u,n]);const p=async()=>{try{await o()}catch(e){n&&n(e instanceof Error?e:new Error("Sign in failed"))}};return a?t.jsx("div",{className:`echo-signin-success ${s}`,children:t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",backgroundColor:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:"8px",color:"#334155",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",fontWeight:"800",width:"fit-content"},children:[t.jsx(zs,{width:16,height:16,variant:"light"}),t.jsxs("span",{children:["Signed in as ",Bs((null==l?void 0:l.name)||(null==l?void 0:l.email))]})]})}):t.jsxs("div",{className:`echo-signin ${s}`,children:[i?t.jsx("div",{onClick:p,style:{cursor:"pointer"},children:i}):t.jsxs("button",{onClick:p,disabled:c,className:"echo-signin-button",style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 20px",backgroundColor:c?"#f3f4f6":d?"#f1f5f9":"#ffffff",color:c?"#9ca3af":"#09090b",border:"1px solid #e2e8f0",borderRadius:"8px",cursor:c?"not-allowed":"pointer",fontSize:"14px",fontWeight:"800",fontFamily:"HelveticaNowDisplay, sans-serif",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",backdropFilter:"blur(8px)"},onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),children:[t.jsx(zs,{width:16,height:16,variant:"light"}),t.jsx("span",{children:c?"Signing in...":"Sign in"})]}),u&&t.jsx("div",{className:"echo-signin-error",style:{marginTop:"12px",display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",backgroundColor:"#fef2f2",border:"1px solid #fecaca",borderRadius:"8px",color:"#dc2626",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif",fontWeight:"800",width:"fit-content"},children:t.jsx("span",{children:u})})]})},e.EchoTokenPurchase=function({onPurchaseComplete:e,onError:n,className:s="",children:i}){const{createPaymentLink:o,isAuthenticated:a,balance:c,freeTierBalance:l,refreshBalance:u}=jn(),[d,h]=r.useState(!1),[p,f]=r.useState(null),[g,m]=r.useState(!1),[_,w]=r.useState(!1),y=e=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e),b=()=>{var e;return((null==(e=null==l?void 0:l.userSpendInfo)?void 0:e.amountLeft)||0)+((null==c?void 0:c.balance)||0)},S=async t=>{if(!a){const e=new Error("Please sign in to purchase tokens");return f(e.message),void(n&&n(e))}try{h(!0),f(null);const r=await o(t);await Hs(r,{onComplete:async()=>{try{await u(),m(!1),w(!1),e&&c&&e(c)}catch(t){const e=t instanceof Error?t:new Error("Failed to refresh balance");f(e.message),n&&n(e)}finally{h(!1)}},onCancel:()=>{h(!1)},onError:e=>{f(e.message),n&&n(e),h(!1)}})}catch(r){const e=r instanceof Error?r:new Error("Failed to create payment link");f(e.message),n&&n(e),h(!1)}},v=()=>{m(!1),w(!1),f(null)};if(!a)return t.jsx("div",{className:`echo-token-purchase ${s}`,children:t.jsx("div",{className:"echo-token-purchase-unauthorized",style:{padding:"12px",backgroundColor:"#fef3c7",color:"#92400e",borderRadius:"8px",fontSize:"14px"},children:"Please sign in to purchase tokens"})});const E=()=>{const[e,n]=r.useState(!1);return t.jsxs("button",{onClick:()=>m(!0),className:`echo-token-purchase-compact ${s}`,style:{display:"flex",alignItems:"center",gap:"8px",padding:"10px 12px",borderRadius:"8px",backgroundColor:e?"#f1f5f9":"#ffffff",border:"1px solid #e5e7eb",color:"#09090b",fontSize:"14px",fontWeight:"800",cursor:"pointer",backdropFilter:"blur(8px)",transition:"all 0.2s ease",boxShadow:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",height:"40px",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),children:[t.jsx(zs,{width:16,height:16,variant:"light"}),t.jsx("span",{children:y(b())}),t.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:e?"#dc2626":"#6b7280",transition:"color 0.2s ease"},children:[t.jsx("path",{d:"M7 7h10v10"}),t.jsx("path",{d:"M7 17 17 7"})]})]})},k=()=>t.jsx("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3,padding:"16px"},onClick:e=>{e.target===e.currentTarget&&v()},children:t.jsxs("div",{style:{backgroundColor:"#ffffff",borderRadius:"12px",border:"1px solid #e5e7eb",padding:"0",width:"100%",maxWidth:"450px",maxHeight:"90vh",overflow:"hidden",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",flexDirection:"column",minHeight:"320px"},children:[t.jsx("div",{style:{padding:"16px 16px 0 16px",marginBottom:"12px"},children:t.jsx("h2",{style:{fontSize:"18px",fontWeight:"500",color:"#111827",margin:0,fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Credits"})}),t.jsxs("div",{style:{padding:"0 16px",marginBottom:"16px"},children:[t.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 4px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Total Available"}),t.jsx("p",{style:{fontSize:"28px",fontWeight:"700",color:"#111827",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:y(((null==c?void 0:c.balance)||0)+b())}),t.jsxs("div",{style:{marginBottom:"8px"},children:[l&&b()>0&&t.jsxs("div",{style:{marginBottom:"8px"},children:[t.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",alignItems:"center",gap:"6px",marginBottom:"4px"},children:[t.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#ef4444"}}),t.jsxs("span",{children:[y(b())," Free Tier",l.userSpendInfo&&l.userSpendInfo.spendLimit&&t.jsxs("span",{style:{color:"#9ca3af",marginLeft:"8px"},children:[y(l.userSpendInfo.amountSpent)," ","of"," ",y(l.userSpendInfo.amountLeft+l.userSpendInfo.amountSpent)," ","used"]})]})]}),l.userSpendInfo&&l.userSpendInfo.spendLimit&&t.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden",marginBottom:"4px",border:"1px solid #d1d5db"},children:t.jsx("div",{style:{width:`${Math.min(100,l.userSpendInfo.amountSpent/(l.userSpendInfo.spendLimit||1)*100)}%`,height:"100%",backgroundColor:"#dc2626"}})})]}),c&&c.balance>0&&t.jsxs("div",{style:{fontSize:"12px",color:"#6b7280",fontFamily:"HelveticaNowDisplay, sans-serif",display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#3b82f6"}}),y(c.balance)," Paid Credits"]})]})]}),t.jsxs("div",{style:{padding:"0 16px 16px 16px",borderTop:"1px solid #f3f4f6",paddingTop:"16px"},children:[t.jsx("p",{style:{fontSize:"14px",color:"#6b7280",margin:"0 0 12px 0",fontFamily:"HelveticaNowDisplay, sans-serif"},children:"Add Credits"}),_?t.jsx(Ws,{onAddCredits:S,onCancel:()=>w(!1),isProcessing:d}):t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[t.jsx("button",{onClick:()=>S(10),disabled:d,style:{width:"100%",padding:"12px 16px",backgroundColor:d?"#9ca3af":"#dc2626",color:"white",border:"none",borderRadius:"6px",fontSize:"14px",fontWeight:"600",cursor:d?"not-allowed":"pointer",transition:"background-color 0.2s ease",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{d||(e.currentTarget.style.backgroundColor="#b91c1c")},onMouseLeave:e=>{d||(e.currentTarget.style.backgroundColor="#dc2626")},children:d?"Processing...":"Add $10 Credits"}),t.jsx("button",{onClick:()=>w(!0),style:{width:"100%",padding:"8px 16px",fontSize:"14px",color:"#6b7280",backgroundColor:"transparent",border:"1px solid #e5e7eb",borderRadius:"6px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.color="#111827",e.currentTarget.style.borderColor="#d1d5db"},onMouseLeave:e=>{e.currentTarget.style.color="#6b7280",e.currentTarget.style.borderColor="#e5e7eb"},children:"Choose different amount"})]})]}),p&&t.jsx("div",{style:{margin:"0 16px 12px 16px",padding:"8px 12px",backgroundColor:"#fee2e2",color:"#dc2626",borderRadius:"6px",fontSize:"14px",fontFamily:"HelveticaNowDisplay, sans-serif"},children:p}),t.jsx("div",{style:{padding:"12px 16px",display:"flex",justifyContent:"flex-end",borderTop:"1px solid #f3f4f6"},children:t.jsx("button",{onClick:v,style:{padding:"8px 16px",backgroundColor:"#f3f4f6",color:"#374151",border:"none",borderRadius:"6px",fontSize:"14px",cursor:"pointer",fontFamily:"HelveticaNowDisplay, sans-serif"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor="#e5e7eb"},onMouseLeave:e=>{e.currentTarget.style.backgroundColor="#f3f4f6"},children:"Close"})})]})});return t.jsxs(t.Fragment,{children:[i?t.jsx("div",{onClick:()=>m(!0),style:{cursor:"pointer"},children:i}):t.jsx(E,{}),g&&t.jsx(k,{})]})},e.Logo=zs,e.useEcho=jn,e.useEchoClient=Pn,e.useEchoOpenAI=function(e={}){const{baseURL:t="https://echo.router.merit.systems",enabled:n=!0}=e,{token:s,isAuthenticated:i}=jn(),[o,a]=r.useState(void 0),[c,l]=r.useState(null),[u,d]=r.useState(!1),h=r.useRef(null);return r.useEffect((()=>{if(h.current&&h.current.abort(),!n||!s||!i)return a(void 0),l(null),void d(!1);return(async()=>{const e=new AbortController;h.current=e,d(!0),l(null);try{if(e.signal.aborted)return;const{default:r}=await import("openai");if(e.signal.aborted)return;const n=new r({apiKey:s,baseURL:t,dangerouslyAllowBrowser:!0});e.signal.aborted||a(n)}catch(r){if(!e.signal.aborted){const e=r instanceof Error?r.message:"Failed to load OpenAI";e.includes("Cannot resolve module")||e.includes("Module not found")||e.includes("openai")?l("OpenAI package not found. Please install it with: pnpm add openai"):l(`Failed to initialize OpenAI client: ${e}`),console.error("Error loading OpenAI:",r),a(void 0)}}finally{e.signal.aborted||d(!1)}})(),()=>{h.current&&h.current.abort()}}),[s,i,t,n]),{openai:o,isReady:void 0!==o&&!u,error:c,isLoading:u}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}));
4
4
  //# sourceMappingURL=echo-react-sdk.umd.js.map