diff --git a/demo-app/auth-js/index.html b/demo-app/auth-js/index.html
new file mode 100644
index 0000000..114ec15
--- /dev/null
+++ b/demo-app/auth-js/index.html
@@ -0,0 +1,30 @@
+
+
+
+
+
+ demo-app | auth-js
+
+
+
+
+
+
+
+
+
+
+
diff --git a/demo-app/auth-js/main.8c554cfcbfa5594a.js b/demo-app/auth-js/main.8c554cfcbfa5594a.js
deleted file mode 100644
index 688fe85..0000000
--- a/demo-app/auth-js/main.8c554cfcbfa5594a.js
+++ /dev/null
@@ -1 +0,0 @@
-(()=>{var e={436:function(e,t,n){var s;e.exports=(s=s||function(e,t){var s;if("undefined"!=typeof window&&window.crypto&&(s=window.crypto),"undefined"!=typeof self&&self.crypto&&(s=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(s=globalThis.crypto),!s&&"undefined"!=typeof window&&window.msCrypto&&(s=window.msCrypto),!s&&"undefined"!=typeof global&&global.crypto&&(s=global.crypto),!s)try{s=n(366)}catch(m){}var i=function(){if(s){if("function"==typeof s.getRandomValues)try{return s.getRandomValues(new Uint32Array(1))[0]}catch(m){}if("function"==typeof s.randomBytes)try{return s.randomBytes(4).readInt32LE()}catch(m){}}throw new Error("Native crypto module could not be used to get secure random number.")},r=Object.create||function(){function e(){}return function(t){var n;return e.prototype=t,n=new e,e.prototype=null,n}}(),o={},a=o.lib={},c=a.Base={extend:function(e){var t=r(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},l=a.WordArray=c.extend({init:function(e,n){e=this.words=e||[],this.sigBytes=n!=t?n:4*e.length},toString:function(e){return(e||u).stringify(this)},concat:function(e){var t=this.words,n=e.words,s=this.sigBytes,i=e.sigBytes;if(this.clamp(),s%4)for(var r=0;r>>2]>>>24-r%4*8&255;t[s+r>>>2]|=o<<24-(s+r)%4*8}else for(var a=0;a>>2]=n[a>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=c.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],n=0;n>>2]>>>24-i%4*8&255;s.push((r>>>4).toString(16)),s.push((15&r).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>3]|=parseInt(e.substr(s,2),16)<<24-s%8*4;return new l.init(n,t/2)}},h=d.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,s=[],i=0;i>>2]>>>24-i%4*8&255;s.push(String.fromCharCode(r))}return s.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>2]|=(255&e.charCodeAt(s))<<24-s%4*8;return new l.init(n,t)}},p=d.Utf8={stringify:function(e){try{return decodeURIComponent(escape(h.stringify(e)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse:function(e){return h.parse(unescape(encodeURIComponent(e)))}},g=a.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new l.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=p.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n,s=this._data,i=s.words,r=s.sigBytes,o=this.blockSize,a=r/(4*o),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,d=e.min(4*c,r);if(c){for(var u=0;u>>6-o%4*2;i[r>>>2]|=a<<24-r%4*8,r++}return t.create(i,r)}e.enc.Base64={stringify:function(e){var t=e.words,n=e.sigBytes,s=this._map;e.clamp();for(var i=[],r=0;r>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,a=0;a<4&&r+.75*a>>6*(3-a)&63));var c=s.charAt(64);if(c)for(;i.length%4;)i.push(c);return i.join("")},parse:function(e){var t=e.length,s=this._map,i=this._reverseMap;if(!i){i=this._reverseMap=[];for(var r=0;r>>7)^(g<<14|g>>>18)^g>>>3,m=l[p-2],f=(m<<15|m>>>17)^(m<<13|m>>>19)^m>>>10;l[p]=_+l[p-7]+f+l[p-16]}var w=s&i^s&r^i&r,v=(s<<30|s>>>2)^(s<<19|s>>>13)^(s<<10|s>>>22),b=h+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&d^~a&u)+c[p]+l[p];h=u,u=d,d=a,a=o+b|0,o=r,r=i,i=s,s=b+(v+w)|0}n[0]=n[0]+s|0,n[1]=n[1]+i|0,n[2]=n[2]+r|0,n[3]=n[3]+o|0,n[4]=n[4]+a|0,n[5]=n[5]+d|0,n[6]=n[6]+u|0,n[7]=n[7]+h|0},_doFinalize:function(){var t=this._data,n=t.words,s=8*this._nDataBytes,i=8*t.sigBytes;return n[i>>>5]|=128<<24-i%32,n[14+(i+64>>>9<<4)]=e.floor(s/4294967296),n[15+(i+64>>>9<<4)]=s,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=r._createHelper(d),t.HmacSHA256=r._createHmacHelper(d)}(Math),s.SHA256)},566:(e,t,n)=>{"use strict";n.d(t,{A:()=>c});var s=n(753);e=n.hmd(e);var i="object"==typeof exports&&exports&&!exports.nodeType&&exports,r=i&&e&&!e.nodeType&&e,o=r&&r.exports===i?s.A.Buffer:void 0,a=o?o.allocUnsafe:void 0;const c=function(e,t){if(t)return e.slice();var n=e.length,s=a?a(n):new e.constructor(n);return e.copy(s),s}},724:(e,t,n)=>{"use strict";n.d(t,{A:()=>s});const s="object"==typeof global&&global&&global.Object===Object&&global},485:(e,t,n)=>{"use strict";n.d(t,{A:()=>a});var s=n(724);e=n.hmd(e);var i="object"==typeof exports&&exports&&!exports.nodeType&&exports,r=i&&e&&!e.nodeType&&e,o=r&&r.exports===i&&s.A.process;const a=function(){try{var e=r&&r.require&&r.require("util").types;return e||o&&o.binding&&o.binding("util")}catch(t){}}()},753:(e,t,n)=>{"use strict";n.d(t,{A:()=>r});var s=n(724),i="object"==typeof self&&self&&self.Object===Object&&self;const r=s.A||i||Function("return this")()},160:(e,t,n)=>{"use strict";n.d(t,{A:()=>c});var s=n(753);const i=function(){return!1};e=n.hmd(e);var r="object"==typeof exports&&exports&&!exports.nodeType&&exports,o=r&&e&&!e.nodeType&&e,a=o&&o.exports===r?s.A.Buffer:void 0;const c=(a?a.isBuffer:void 0)||i},366:()=>{}},t={};function n(s){var i=t[s];if(void 0!==i)return i.exports;var r=t[s]={id:s,loaded:!1,exports:{}};return e[s].call(r.exports,r,r.exports,n),r.loaded=!0,r.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var s in t)n.o(t,s)&&!n.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},n.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var t="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(t){var n=String(t).replace(/=+$/,"");if(n.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var s,i,r=0,o=0,a="";i=n.charAt(o++);~i&&(s=r%4?64*s+i:i,r++%4)?a+=String.fromCharCode(255&s>>(-2*r&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return a};function s(e){var n=e.replace(/-/g,"+").replace(/_/g,"/");switch(n.length%4){case 0:break;case 2:n+="==";break;case 3:n+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(t(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(n)}catch(e){return t(n)}}function i(e){this.message=e}i.prototype=new Error,i.prototype.name="InvalidTokenError";const r=function(e,t){if("string"!=typeof e)throw new i("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(s(e.split(".")[n]))}catch(e){throw new i("Invalid token specified: "+e.message)}};var o;class AuthUtils{}o=AuthUtils,AuthUtils.isCordova=()=>!!(window.cordova||window.phonegap||window.PhoneGap),AuthUtils.isCapacitor=()=>{var e;return!(null==(e=window.Capacitor)||!e.isNativePlatform())},AuthUtils.isNativeMobile=()=>o.isCapacitor()||o.isCordova(),AuthUtils.decodeJwt=e=>{try{return e?r(e):e}catch(t){return console.warn("[@badisi/auth-js] Access token was not decoded as it is not a valid JWT."),e}},AuthUtils.isUrlMatching=(e,t)=>{if(void 0!==t){const n=new URL(e,"http://test"),s=new URL(t,"http://test");if(""!==s.pathname&&"/"!==s.pathname&&!n.pathname.includes(s.pathname))return!1;if("http://test"!==s.origin&&(n.protocol!==s.protocol||n.origin!==s.origin||!`${n.origin}${n.pathname}}`.includes(`${s.origin}${s.pathname}`)))return!1;let i=!0;return s.searchParams.forEach(((e,t)=>{n.searchParams.getAll(t).includes(e)||(i=!1)})),i}return!1},AuthUtils.getBaseUrl=()=>{var e;const t=document.baseURI||(null==(e=document.querySelector("base"))?void 0:e.href)||location.origin;return t.endsWith("/")?t:`${t}/`},AuthUtils.stringToURL=e=>{try{return new URL(e)}catch(t){const n=e.startsWith("/")?e.substring(1,e.length):e;return new URL(`${o.getBaseUrl()}${n}`)}};const a=document.createElement("template");a.innerHTML='\n \n \n \n \n \n';class AppElement extends HTMLElement{constructor(){var e;super(),this.demoAppMainEl=void 0,this.demoAppPlaygroundEl=void 0,this.demoAppDebugEl=void 0,this.authManagerSubs=[],this.listeners=[],this.attachShadow({mode:"open"}),null==(e=this.shadowRoot)||e.appendChild(document.importNode(a.content,!0))}connectedCallback(){this.demoAppMainEl=this.shadowRoot.querySelector("demo-app-main"),this.demoAppPlaygroundEl=this.shadowRoot.querySelector("demo-app-playground"),this.demoAppDebugEl=this.shadowRoot.querySelector("demo-app-debug"),this.listenForHeaderEvents(),this.listenForPlaygroundEvents(),this.listenForAuthChanges()}disconnectedCallback(){this.authManagerSubs.forEach((e=>e.unsubscribe())),this.listeners.forEach((e=>e()))}async callPrivateApi(e,t){if(window.authManager&&e){var n;const s=null!=(n=await window.authManager.getAccessToken())?n:"",i=new XMLHttpRequest;i.onreadystatechange=()=>{if(4===i.readyState){var e;let s;try{var t;s=JSON.parse(null!=(t=i.responseText)?t:"")}catch(n){s=`${i.status} ${i.statusText}`}null==(e=this.demoAppPlaygroundEl)||e.setApiStatus(s,200!==i.status)}},i.open("GET",e,!0),i.setRequestHeader("Authorization",`Bearer ${s}`),null==t||t.split(";").forEach((e=>{if(e){var t,n;const s=e.split(":");i.setRequestHeader(null==(t=s[0])?void 0:t.trim(),(null==(n=s[1])?void 0:n.trim())||"")}})),i.send()}}refreshInfo(e,t){if(window.authManager&&this.demoAppMainEl&&this.demoAppDebugEl)switch(e){case"renewing":this.demoAppMainEl.isRenewing=t;break;case"authenticated":this.demoAppMainEl.isAuthenticated=t,this.demoAppDebugEl.isAuthenticated=t;break;case"userSession":this.demoAppDebugEl.userSession=t;break;case"accessToken":this.demoAppDebugEl.accessToken=t,this.demoAppDebugEl.accessTokenDecoded=AuthUtils.decodeJwt(t);break;case"idToken":this.demoAppDebugEl.idToken=t,this.demoAppDebugEl.idTokenDecoded=AuthUtils.decodeJwt(t);break;case"userProfile":this.demoAppDebugEl.userProfile=t}}listenForAuthChanges(){const e=window.authManager;e&&this.authManagerSubs.push(e.onRenewingChanged((e=>this.refreshInfo("renewing",e))),e.onAuthenticatedChanged((e=>this.refreshInfo("authenticated",e))),e.onUserSessionChanged((e=>this.refreshInfo("userSession",e))),e.onAccessTokenChanged((e=>this.refreshInfo("accessToken",e))),e.onIdTokenChanged((e=>this.refreshInfo("idToken",e))),e.onUserProfileChanged((e=>this.refreshInfo("userProfile",e))))}listenForPlaygroundEvents(){if(this.demoAppPlaygroundEl){const e=e=>{var t,n;this.callPrivateApi(null==(t=e.detail)?void 0:t.url,null==(n=e.detail)?void 0:n.headers)};this.demoAppPlaygroundEl.addEventListener("api",e),this.listeners.push((()=>{var t;return null==(t=this.demoAppPlaygroundEl)?void 0:t.removeEventListener("api",e)}))}}listenForHeaderEvents(){const e=window.authManager;if(e&&this.demoAppMainEl){const t=()=>{e.login()};this.demoAppMainEl.addEventListener("login",t);const n=()=>{e.logout({redirectUrl:"/"}).then((()=>{var e;const t=document.baseURI||(null==(e=document.querySelector("base"))?void 0:e.href)||location.origin;location.href=t.endsWith("/")?t:`${t}/`}))};this.demoAppMainEl.addEventListener("logout",n);const s=()=>{e.renew()};this.demoAppMainEl.addEventListener("silentRenew",s),this.listeners.push((()=>{var e;return null==(e=this.demoAppMainEl)?void 0:e.removeEventListener("login",t)}),(()=>{var e;return null==(e=this.demoAppMainEl)?void 0:e.removeEventListener("logout",n)}),(()=>{var e;return null==(e=this.demoAppMainEl)?void 0:e.removeEventListener("silentRenew",s)}))}}}customElements.define("app-root",AppElement);function c(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var l=0;function d(e){return"__private_"+l+++"_"+e}const u=function(){this.__data__=[],this.size=0};const h=function(e,t){return e===t||e!=e&&t!=t};const p=function(e,t){for(var n=e.length;n--;)if(h(e[n][0],t))return n;return-1};var g=Array.prototype.splice;const _=function(e){var t=this.__data__,n=p(t,e);return!(n<0)&&(n==t.length-1?t.pop():g.call(t,n,1),--this.size,!0)};const m=function(e){var t=this.__data__,n=p(t,e);return n<0?void 0:t[n][1]};const f=function(e){return p(this.__data__,e)>-1};const w=function(e,t){var n=this.__data__,s=p(n,e);return s<0?(++this.size,n.push([e,t])):n[s][1]=t,this};function v(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t-1&&e%1==0&&e<=9007199254740991};const Fe=function(e){return null!=e&&ze(e.length)&&!M(e)};const Je=function(e){return Me(e)&&Fe(e)};var Ke=n(160),Ve=Function.prototype,Ge=Object.prototype,Qe=Ve.toString,Xe=Ge.hasOwnProperty,Ye=Qe.call(Object);const Ze=function(e){if(!Me(e)||"[object Object]"!=L(e))return!1;var t=Oe(e);if(null===t)return!0;var n=Xe.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&Qe.call(n)==Ye};var et={};et["[object Float32Array]"]=et["[object Float64Array]"]=et["[object Int8Array]"]=et["[object Int16Array]"]=et["[object Int32Array]"]=et["[object Uint8Array]"]=et["[object Uint8ClampedArray]"]=et["[object Uint16Array]"]=et["[object Uint32Array]"]=!0,et["[object Arguments]"]=et["[object Array]"]=et["[object ArrayBuffer]"]=et["[object Boolean]"]=et["[object DataView]"]=et["[object Date]"]=et["[object Error]"]=et["[object Function]"]=et["[object Map]"]=et["[object Number]"]=et["[object Object]"]=et["[object RegExp]"]=et["[object Set]"]=et["[object String]"]=et["[object WeakMap]"]=!1;const tt=function(e){return Me(e)&&ze(e.length)&&!!et[L(e)]};const nt=function(e){return function(t){return e(t)}};var st=n(485),it=st.A&&st.A.isTypedArray;const rt=it?nt(it):tt;const ot=function(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]};var at=Object.prototype.hasOwnProperty;const ct=function(e,t,n){var s=e[t];at.call(e,t)&&h(s,n)&&(void 0!==n||t in e)||ke(e,t,n)};const lt=function(e,t,n,s){var i=!n;n||(n={});for(var r=-1,o=t.length;++r-1&&e%1==0&&e0){if(++t>=800)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}(Tt);const Pt=function(e,t){return At(xt(e,t,St),e+"")};const Rt=function(e,t,n){if(!N(n))return!1;var s=typeof t;return!!("number"==s?Fe(n)&&ht(t,n.length):"string"==s&&t in n)&&h(n[t],e)};const It=function(e){return Pt((function(t,n){var s=-1,i=n.length,r=i>1?n[i-1]:void 0,o=i>2?n[2]:void 0;for(r=e.length>3&&"function"==typeof r?(i--,r):void 0,o&&Rt(n[0],n[1],o)&&(r=i<3?void 0:r,i=1),t=Object(t);++s{},info:()=>{},warn:()=>{},error:()=>{}},Ft=(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))(Ft||{});(Lt=Ft||(Ft={})).reset=function(){Ot=3,jt=zt},Lt.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");Ot=e},Lt.setLogger=function(e){jt=e};var Jt=class{constructor(e){this._name=e}debug(...e){Ot>=4&&jt.debug(Jt._format(this._name,this._method),...e)}info(...e){Ot>=3&&jt.info(Jt._format(this._name,this._method),...e)}warn(...e){Ot>=2&&jt.warn(Jt._format(this._name,this._method),...e)}error(...e){Ot>=1&&jt.error(Jt._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){const n=new Jt(`${e}.${t}`);return n.debug("begin"),n}static _format(e,t){const n=`[${e}]`;return t?`${n} ${t}:`:n}static debug(e,...t){Ot>=4&&jt.debug(Jt._format(e),...t)}static info(e,...t){Ot>=3&&jt.info(Jt._format(e),...t)}static warn(e,...t){Ot>=2&&jt.warn(Jt._format(e),...t)}static error(e,...t){Ot>=1&&jt.error(Jt._format(e),...t)}};Ft.reset();var Kt,Vt,Gt,Qt=class{static _randomWord(){return Mt().lib.WordArray.random(1).words[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>(+e^Qt._randomWord()&15>>+e/4).toString(16))).replace(/-/g,"")}static generateCodeVerifier(){return Qt.generateUUIDv4()+Qt.generateUUIDv4()+Qt.generateUUIDv4()}static generateCodeChallenge(e){try{const t=Ht()(e);return $t().stringify(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw Jt.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const n=Bt().parse([e,t].join(":"));return $t().stringify(n)}},Xt=class{constructor(e){this._name=e,this._logger=new Jt(`Event('${this._name}')`),this._callbacks=[]}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)}raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)t(...e)}},Yt=class{static decode(e){try{return r(e)}catch(t){throw Jt.error("JwtUtils.decode",t),t}}},Zt=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(",")}},en=class extends Xt{constructor(){super(...arguments),this._logger=new Jt(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-en.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=en.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const t=this._logger.create("init");e=Math.max(Math.floor(e),1);const n=en.getEpochTime()+e;if(this.expiration===n&&this._timerHandle)return void t.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),t.debug("using duration",e),this._expiration=n;const s=Math.min(e,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)}},tn=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const n=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(n.slice(1))}},nn=class extends Error{constructor(e,t){var n,s,i;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw Jt.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(n=e.error_description)?n:null,this.error_uri=null!=(s=e.error_uri)?s:null,this.state=e.userState,this.session_state=null!=(i=e.session_state)?i:null,this.url_state=e.url_state}},sn=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},rn=class{constructor(e){this._logger=new Jt("AccessTokenEvents"),this._expiringTimer=new en("Access token expiring"),this._expiredTimer=new en("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const n=e.expires_in;if(t.debug("access token present, remaining duration:",n),n>0){let e=n-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 s=n+1;t.debug("registering expired timer, raising in",s,"seconds"),this._expiredTimer.init(s)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}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)}},on=class{constructor(e,t,n,s,i){this._callback=e,this._client_id=t,this._intervalInSeconds=s,this._stopOnError=i,this._logger=new Jt("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 r=new URL(n);this._frame_origin=r.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=r.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)}},an=class{constructor(){this._logger=new Jt("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]}},cn=class{constructor(e=[],t=null,n={}){this._jwtHandler=t,this._extraHeaders=n,this._logger=new Jt("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:n,...s}=t;if(!n)return await fetch(e,s);const i=new AbortController,r=setTimeout((()=>i.abort()),1e3*n);try{return await fetch(e,{...t,signal:i.signal})}catch(o){if(o instanceof DOMException&&"AbortError"===o.name)throw new sn("Network timed out");throw o}finally{clearTimeout(r)}}async getJson(e,{token:t,credentials:n}={}){const s=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let r;t&&(s.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this.appendExtraHeaders(i);try{s.debug("url:",e),r=await this.fetchWithTimeout(e,{method:"GET",headers:i,credentials:n})}catch(c){throw s.error("Network Error"),c}s.debug("HTTP response received, status",r.status);const o=r.headers.get("Content-Type");if(o&&!this._contentTypes.find((e=>o.startsWith(e)))&&s.throw(new Error(`Invalid response Content-Type: ${null!=o?o:"undefined"}, from URL: ${e}`)),r.ok&&this._jwtHandler&&(null==o?void 0:o.startsWith("application/jwt")))return await this._jwtHandler(await r.text());let a;try{a=await r.json()}catch(c){if(s.error("Error parsing JSON response",c),r.ok)throw c;throw new Error(`${r.statusText} (${r.status})`)}if(!r.ok){if(s.error("Error from server:",a),a.error)throw new nn(a);throw new Error(`${r.statusText} (${r.status}): ${JSON.stringify(a)}`)}return a}async postForm(e,{body:t,basicAuth:n,timeoutInSeconds:s,initCredentials:i}){const r=this._logger.create("postForm"),o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};let a;void 0!==n&&(o.Authorization="Basic "+n),this.appendExtraHeaders(o);try{r.debug("url:",e),a=await this.fetchWithTimeout(e,{method:"POST",headers:o,body:t,timeoutInSeconds:s,credentials:i})}catch(u){throw r.error("Network error"),u}r.debug("HTTP response received, status",a.status);const c=a.headers.get("Content-Type");if(c&&!this._contentTypes.find((e=>c.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=c?c:"undefined"}, from URL: ${e}`);const l=await a.text();let d={};if(l)try{d=JSON.parse(l)}catch(u){if(r.error("Error parsing JSON response",u),a.ok)throw u;throw new Error(`${a.statusText} (${a.status})`)}if(!a.ok){if(r.error("Error from server:",d),d.error)throw new nn(d,t);throw new Error(`${a.statusText} (${a.status}): ${JSON.stringify(d)}`)}return d}appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),n=Object.keys(this._extraHeaders),s=["authorization","accept","content-type"];0!==n.length&&n.forEach((n=>{if(s.includes(n.toLocaleLowerCase()))return void t.warn("Protected header could not be overridden",n,s);const i="function"==typeof this._extraHeaders[n]?this._extraHeaders[n]():this._extraHeaders[n];i&&""!==i&&(e[n]=i)}))}},ln=class{constructor(e){this._settings=e,this._logger=new Jt("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new cn(["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});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},this._settings.metadataSeed,t),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 n=this._logger.create(`_getMetadataProperty('${e}')`),s=await this.getMetadata();if(n.debug("resolved"),void 0===s[e]){if(!0===t)return void n.warn("Metadata does not contain optional property");n.throw(new Error("Metadata does not contain property "+e))}return s[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 n=await this._jsonService.getJson(t);if(e.debug("got key set",n),!Array.isArray(n.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=n.keys,this._signingKeys}},dn=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new Jt("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 n=0;n{const t=this._logger.create("_getClaimsFromJwt");try{const n=Yt.decode(e);return t.debug("JWT decoding successful"),n}catch(n){throw t.error("Error parsing JWT response"),n}},this._jsonService=new cn(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 n=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",n);const s=await this._jsonService.getJson(n,{token:e,credentials:this._settings.fetchRequestCredentials});return t.debug("got claims",s),s}},pn=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new Jt("TokenClient"),this._jsonService=new cn(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:s=this._settings.client_secret,...i}){const r=this._logger.create("exchangeCode");n||r.throw(new Error("A client_id is required")),t||r.throw(new Error("A redirect_uri is required")),i.code||r.throw(new Error("A code is required"));const o=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[d,u]of Object.entries(i))null!=u&&o.set(d,u);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw r.throw(new Error("A client_secret is required")),null;a=Qt.generateBasicAuth(n,s);break;case"client_secret_post":o.append("client_id",n),s&&o.append("client_secret",s)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,scope:s=this._settings.scope,...i}){const r=this._logger.create("exchangeCredentials");t||r.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e,scope:s});for(const[d,u]of Object.entries(i))null!=u&&o.set(d,u);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!n)throw r.throw(new Error("A client_secret is required")),null;a=Qt.generateBasicAuth(t,n);break;case"client_secret_post":o.append("client_id",t),n&&o.append("client_secret",n)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:s,...i}){const r=this._logger.create("exchangeRefreshToken");t||r.throw(new Error("A client_id is required")),i.refresh_token||r.throw(new Error("A refresh_token is required"));const o=new URLSearchParams({grant_type:e});for(const[d,u]of Object.entries(i))Array.isArray(u)?u.forEach((e=>o.append(d,e))):null!=u&&o.set(d,u);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!n)throw r.throw(new Error("A client_secret is required")),null;a=Qt.generateBasicAuth(t,n);break;case"client_secret_post":o.append("client_id",t),n&&o.append("client_secret",n)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:s,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async revoke(e){var t;const n=this._logger.create("revoke");e.token||n.throw(new Error("A token is required"));const s=await this._metadataService.getRevocationEndpoint(!1);n.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const i=new URLSearchParams;for(const[r,o]of Object.entries(e))null!=o&&i.set(r,o);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(s,{body:i}),n.debug("got response")}},gn=class{constructor(e,t,n){this._settings=e,this._metadataService=t,this._claimsService=n,this._logger=new Jt("ResponseValidator"),this._userInfoService=new hn(this._settings,this._metadataService),this._tokenClient=new pn(this._settings,this._metadataService)}async validateSigninResponse(e,t){const n=this._logger.create("validateSigninResponse");this._processSigninState(e,t),n.debug("state processed"),await this._processCode(e,t),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 n=this._logger.create("validateCredentialsResponse");e.isOpenId&&e.id_token&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,t,e.isOpenId),n.debug("claims processed")}async validateRefreshResponse(e,t){const n=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),n.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const s=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,s),n.debug("claims processed")}validateSignoutResponse(e,t){const n=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&n.throw(new Error("State does not match")),n.debug("state validated"),e.userState=t.data,e.error)throw n.warn("Response was error",e.error),new nn(e)}_processSigninState(e,t){const n=this._logger.create("_processSigninState");if(t.id!==e.state&&n.throw(new Error("State does not match")),t.client_id||n.throw(new Error("No client_id on state")),t.authority||n.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&n.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&n.throw(new Error("client_id mismatch on settings vs. signin state")),n.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw n.warn("Response was error",e.error),new nn(e);t.code_verifier&&!e.code&&n.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,n=!0){const s=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void s.debug("not loading user info");s.debug("loading user info");const i=await this._userInfoService.getClaims(e.access_token);s.debug("user info claims received from user info endpoint"),n&&i.sub!==e.profile.sub&&s.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(i)),s.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t){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,...t.extraTokenParams});Object.assign(e,s)}else n.debug("No code to process")}_validateIdTokenAttributes(e,t){var n;const s=this._logger.create("_validateIdTokenAttributes");s.debug("decoding ID Token JWT");const i=Yt.decode(null!=(n=e.id_token)?n:"");if(i.sub||s.throw(new Error("ID Token is missing a subject claim")),t){const e=Yt.decode(t);i.sub!==e.sub&&s.throw(new Error("sub in id_token does not match current sub")),i.auth_time&&i.auth_time!==e.auth_time&&s.throw(new Error("auth_time in id_token does not match original auth_time")),i.azp&&i.azp!==e.azp&&s.throw(new Error("azp in id_token does not match original azp")),!i.azp&&e.azp&&s.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=i}},_n=class{constructor(e){this.id=e.id||Qt.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=en.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new Jt("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(e){return Jt.createStatic("State","fromStorageString"),new _n(JSON.parse(e))}static async clearStaleState(e,t){const n=Jt.createStatic("State","clearStaleState"),s=en.getEpochTime()-t,i=await e.getAllKeys();n.debug("got keys",i);for(let o=0;ow.searchParams.append("resource",e)))}for(const[b,y]of Object.entries({response_mode:a,...f,...g}))null!=y&&w.searchParams.append(b,y.toString());this.url=w.href}},wn=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(";");this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(";"))}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-en.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+en.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},vn=class{constructor({url:e,state_data:t,id_token_hint:n,post_logout_redirect_uri:s,extraQueryParams:i,request_type:r,client_id:o}){if(this._logger=new Jt("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const a=new URL(e);n&&a.searchParams.append("id_token_hint",n),o&&a.searchParams.append("client_id",o),s&&(a.searchParams.append("post_logout_redirect_uri",s),t&&(this.state=new _n({data:t,request_type:r}),a.searchParams.append("state",this.state.id)));for(const[c,l]of Object.entries({...i}))null!=l&&a.searchParams.append(c,l.toString());this.url=a.href}},bn=class{constructor(e){this.state=e.get("state"),this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},yn=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],Sn=["sub","iss","aud","exp","iat"],kn=class{constructor(e){this._settings=e,this._logger=new Jt("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:yn;for(const n of e)Sn.includes(n)||delete t[n]}return t}mergeClaims(e,t){const n={...e};for(const[s,i]of Object.entries(t))for(const e of Array.isArray(i)?i:[i]){const t=n[s];void 0===t?n[s]=e:Array.isArray(t)?t.includes(e)||t.push(e):n[s]!==e&&("object"==typeof e&&this._settings.mergeClaims?n[s]=this.mergeClaims(t,e):n[s]=[t,e])}return n}},En=class{constructor(e,t){this._logger=new Jt("OidcClient"),this.settings=e instanceof un?e:new un(e),this.metadataService=null!=t?t:new ln(this.settings),this._claimsService=new kn(this.settings),this._validator=new gn(this.settings,this.metadataService,this._claimsService),this._tokenClient=new pn(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:n,request_type:s,id_token_hint:i,login_hint:r,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:_=this.settings.ui_locales,acr_values:m=this.settings.acr_values,resource:f=this.settings.resource,response_mode:w=this.settings.response_mode,extraQueryParams:v=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams}){const y=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const S=await this.metadataService.getAuthorizationEndpoint();y.debug("Received authorization endpoint",S);const k=new fn({url:S,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:_,id_token_hint:i,login_hint:r,acr_values:m,resource:f,request:t,request_uri:n,extraQueryParams:v,extraTokenParams:b,request_type:s,response_mode:w,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE});await this.clearStaleState();const E=k.state;return await this.settings.stateStore.set(E.id,E.toStorageString()),k}async readSigninResponseState(e,t=!1){const n=this._logger.create("readSigninResponseState"),s=new wn(tn.readParams(e,this.settings.response_mode));if(!s.state)throw n.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[t?"remove":"get"](s.state);if(!i)throw n.throw(new Error("No matching state found in storage")),null;return{state:mn.fromStorageString(i),response:s}}async processSigninResponse(e){const t=this._logger.create("processSigninResponse"),{state:n,response:s}=await this.readSigninResponseState(e,!0);return t.debug("received state from storage; validating response"),await this._validator.validateSigninResponse(s,n),s}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n=!1,extraTokenParams:s={}}){const i=await this._tokenClient.exchangeCredentials({username:e,password:t,...s}),r=new wn(new URLSearchParams);return Object.assign(r,i),await this._validator.validateCredentialsResponse(r,n),r}async useRefreshToken({state:e,timeoutInSeconds:t}){var n;const s=this._logger.create("useRefreshToken");let i;if(void 0===this.settings.refreshTokenAllowedScope)i=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");i=((null==(n=e.scope)?void 0:n.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}const r=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,resource:e.resource,scope:i,timeoutInSeconds:t}),o=new wn(new URLSearchParams);return Object.assign(o,r),s.debug("validating response",o),await this._validator.validateRefreshResponse(o,{...e,scope:i}),o}async createSignoutRequest({state:e,id_token_hint:t,client_id:n,request_type:s,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:r=this.settings.extraQueryParams}={}){const o=this._logger.create("createSignoutRequest"),a=await this.metadataService.getEndSessionEndpoint();if(!a)throw o.throw(new Error("No end session endpoint")),null;o.debug("Received end session endpoint",a),n||!i||t||(n=this.settings.client_id);const c=new vn({url:a,id_token_hint:t,client_id:n,post_logout_redirect_uri:i,state_data:e,extraQueryParams:r,request_type:s});await this.clearStaleState();const l=c.state;return l&&(o.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),c}async readSignoutResponseState(e,t=!1){const n=this._logger.create("readSignoutResponseState"),s=new bn(tn.readParams(e,this.settings.response_mode));if(!s.state){if(n.debug("No state in response"),s.error)throw n.warn("Response was error:",s.error),new nn(s);return{state:void 0,response:s}}const i=await this.settings.stateStore[t?"remove":"get"](s.state);if(!i)throw n.throw(new Error("No matching state found in storage")),null;return{state:_n.fromStorageString(i),response:s}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:n,response:s}=await this.readSignoutResponseState(e,!0);return n?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(s,n)):t.debug("No state from storage; skipping response validation"),s}clearStaleState(){return this._logger.create("clearStaleState"),_n.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})}},xn=class{constructor(e){this._userManager=e,this._logger=new Jt("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const n=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,this._sid=e.profile.sid,n.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,this._sid=void 0,n.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){n.debug("initializing check session iframe");const s=this._userManager.settings.client_id,i=this._userManager.settings.checkSessionIntervalInSeconds,r=this._userManager.settings.stopCheckSessionOnError,o=new on(this._callback,s,e,i,r);await o.load(),this._checkSessionIFrame=o,o.start(t)}else n.warn("no check session iframe found in the metadata")}catch(s){n.error("Error from getCheckSessionIframe:",s instanceof Error?s.message:s)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._sid=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&&e.sid?{sub:e.sub,sid:e.sid}:null};this._start(t)}}catch(n){e.error("error from querySessionStatus",n instanceof Error?n.message:n)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let n=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(n=!1,this._checkSessionIFrame.start(t.session_state),t.sid===this._sid?e.debug("same sub still logged in at OP, restarting check session iframe; session_state",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),this._userManager.events._raiseUserSessionChanged())):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),n?this._sub?this._userManager.events._raiseUserSignedOut():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),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&&e.sid?{sub:e.sub,sid:e.sid}:null};this._start(t)}}}},Cn=class{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-en.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+en.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 Jt("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(e){return Jt.createStatic("User","fromStorageString"),new Cn(JSON.parse(e))}},Tn="oidc-client",Un=class{constructor(){this._abort=new Xt("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:n,keepOpen:s}=await new Promise(((n,s)=>{const i=i=>{var r;const o=i.data,a=null!=(r=e.scriptOrigin)?r:window.location.origin;if(i.origin===a&&(null==o?void 0:o.source)===Tn){try{const n=tn.readParams(o.url,e.response_mode).get("state");if(n||t.warn("no state found in response url"),i.source!==this._window&&n!==e.state)return}catch(c){this._dispose(),s(new Error("Invalid response from window"))}n(o)}};window.addEventListener("message",i,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",i,!1))),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),s(e)})))}));return t.debug("got response from window"),this._dispose(),s||this.close(),{url:n}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,n=!1,s=window.location.origin){e.postMessage({source:Tn,url:t,keepOpen:n},s)}},An={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},Pn="_blank",Rn=60,In=2,On=10,jn=class extends un{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:n=e.post_logout_redirect_uri,popupWindowFeatures:s=An,popupWindowTarget:i=Pn,redirectMethod:r="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,silent_redirect_uri:l=e.redirect_uri,silentRequestTimeoutInSeconds:d=On,automaticSilentRenew:u=!0,validateSubOnSilentRenew:h=!0,includeIdTokenInSilentRenew:p=!1,monitorSession:g=!1,monitorAnonymousSession:_=!1,checkSessionIntervalInSeconds:m=In,query_status_response_type:f="code",stopCheckSessionOnError:w=!0,revokeTokenTypes:v=["access_token","refresh_token"],revokeTokensOnSignout:b=!1,includeIdTokenInSilentSignout:y=!1,accessTokenExpiringNotificationTimeInSeconds:S=Rn,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=n,this.popupWindowFeatures=s,this.popupWindowTarget=i,this.redirectMethod=r,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=l,this.silentRequestTimeoutInSeconds=d,this.automaticSilentRenew=u,this.validateSubOnSilentRenew=h,this.includeIdTokenInSilentRenew=p,this.monitorSession=g,this.monitorAnonymousSession=_,this.checkSessionIntervalInSeconds=m,this.stopCheckSessionOnError=w,this.query_status_response_type=f,this.revokeTokenTypes=v,this.revokeTokensOnSignout=b,this.includeIdTokenInSilentSignout=y,this.accessTokenExpiringNotificationTimeInSeconds=S,k)this.userStore=k;else{const e="undefined"!=typeof window?window.sessionStorage:new an;this.userStore=new dn({store:e})}}},Ln=class extends Un{constructor({silentRequestTimeoutInSeconds:e=On}){super(),this._logger=new Jt("IFrameWindow"),this._timeoutInSeconds=e,this._frame=Ln.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 sn("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 n=e.target;null==(t=n.parentNode)||t.removeChild(n),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)}},Nn=class{constructor(e){this._settings=e,this._logger=new Jt("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new Ln({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),Ln.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},Mn=class extends Un{constructor({popupWindowTarget:e=Pn,popupWindowFeatures:t={}}){super(),this._logger=new Jt("PopupWindow");const n=Zt.center({...An,...t});this._window=window.open(void 0,e,Zt.serialize(n)),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 n=setInterval((()=>{this._window&&!this._window.closed||this._abort.raise(new Error("Popup closed by user"))}),500);return this._disposeHandlers.add((()=>clearInterval(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){if(!window.opener)throw new Error("No window.opener. Can't complete notification.");return super._notifyParent(window.opener,e,t)}},qn=class{constructor(e){this._settings=e,this._logger=new Jt("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget}){return new Mn({popupWindowFeatures:e,popupWindowTarget:t})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),Mn.notifyOpener(e,t)}},Hn=class{constructor(e){this._settings=e,this._logger=new Jt("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var n;this._logger.create("prepare");let s=window.self;"top"===t&&(s=null!=(n=window.top)?n:window.self);const i=s.location[e].bind(s.location);let r;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{r=t}));return i(e.url),await t},close:()=>{this._logger.create("close"),null==r||r(new Error("Redirect aborted")),s.stop()}}}async callback(){}},Wn=class extends rn{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new Jt("UserManagerEvents"),this._userLoaded=new Xt("User loaded"),this._userUnloaded=new Xt("User unloaded"),this._silentRenewError=new Xt("Silent renew error"),this._userSignedIn=new Xt("User signed in"),this._userSignedOut=new Xt("User signed out"),this._userSessionChanged=new Xt("User session changed")}load(e,t=!0){super.load(e),t&&this._userLoaded.raise(e)}unload(){super.unload(),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)}_raiseSilentRenewError(e){this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}_raiseUserSignedIn(){this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}_raiseUserSignedOut(){this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}_raiseUserSessionChanged(){this._userSessionChanged.raise()}},$n=class{constructor(e){this._userManager=e,this._logger=new Jt("SilentRenewService"),this._isStarted=!1,this._retryTimer=new en("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 sn)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),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)}},Dn=class{constructor(e,t){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.resource=t,this.data=e.state}},Bn=class{constructor(e,t,n,s){this._logger=new Jt("UserManager"),this.settings=new jn(e),this._client=new En(e),this._redirectNavigator=null!=t?t:new Hn(this.settings),this._popupNavigator=null!=n?n:new qn(this.settings),this._iframeNavigator=null!=s?s:new Nn(this.settings),this._events=new Wn(this.settings),this._silentRenewService=new $n(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new xn(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(){const e=this._logger.create("getUser"),t=await this._loadUser();return t?(e.info("user loaded"),this._events.load(t,!1),t):(e.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"),this._events.unload()}async signinRedirect(e={}){this._logger.create("signinRedirect");const{redirectMethod:t,...n}=e,s=await this._redirectNavigator.prepare({redirectMethod:t});await this._signinStart({request_type:"si:r",...n},s)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),n=await this._signinEnd(e);return n.profile&&n.profile.sub?t.info("success, signed in subject",n.profile.sub):t.info("no subject"),n}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:n=!1}){const s=this._logger.create("signinResourceOwnerCredential"),i=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n,extraTokenParams:this.settings.extraTokenParams});s.debug("got signin response");const r=await this._buildUser(i);return r.profile&&r.profile.sub?s.info("success, signed in subject",r.profile.sub):s.info("no subject"),r}async signinPopup(e={}){const t=this._logger.create("signinPopup"),{popupWindowFeatures:n,popupWindowTarget:s,...i}=e,r=this.settings.popup_redirect_uri;r||t.throw(new Error("No popup_redirect_uri configured"));const o=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:s}),a=await this._signin({request_type:"si:p",redirect_uri:r,display:"popup",...i},o);return a&&(a.profile&&a.profile.sub?t.info("success, signed in subject",a.profile.sub):t.info("no subject")),a}async signinPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async signinSilent(e={}){var t;const n=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:s,resource:i,...r}=e;let o=await this._loadUser();if(null==o?void 0:o.refresh_token){n.debug("using refresh token");const e=new Dn(o,i);return await this._useRefreshToken(e)}const a=this.settings.silent_redirect_uri;let c;a||n.throw(new Error("No silent_redirect_uri configured")),o&&this.settings.validateSubOnSilentRenew&&(n.debug("subject prior to silent renew:",o.profile.sub),c=o.profile.sub);const l=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});return o=await this._signin({request_type:"si:s",redirect_uri:a,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==o?void 0:o.id_token:void 0,...r},l,c),o&&((null==(t=o.profile)?void 0:t.sub)?n.info("success, signed in subject",o.profile.sub):n.info("no subject")),o}async _useRefreshToken(e){const t=await this._client.useRefreshToken({state:e,timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds}),n=new Cn({...e,...t});return await this.storeUser(n),this._events.load(n),n}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":return await this.signinPopupCallback(e);case"si:s":return await this.signinSilentCallback(e);default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:n}=await this._client.readSignoutResponseState(e);if(n)switch(n.request_type){case"so:r":await this.signoutRedirectCallback(e);break;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:n,...s}=e,i=this.settings.silent_redirect_uri;i||t.throw(new Error("No silent_redirect_uri configured"));const r=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n}),a=await this._signinStart({request_type:"si:s",redirect_uri:i,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==r?void 0:r.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...s},o);try{const e=await this._client.processSigninResponse(a.url);return t.debug("got signin response"),e.session_state&&e.profile.sub?(t.info("success for subject",e.profile.sub),{session_state:e.session_state,sub:e.profile.sub,sid:e.profile.sid}):(t.info("success, user not authenticated"),null)}catch(c){if(this.settings.monitorAnonymousSession&&c instanceof nn)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,n){const s=await this._signinStart(e,t);return await this._signinEnd(s.url,n)}async _signinStart(e,t){const n=this._logger.create("_signinStart");try{const s=await this._client.createSigninRequest(e);return n.debug("got signin request"),await t.navigate({url:s.url,state:s.state.id,response_mode:s.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(s){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),s}}async _signinEnd(e,t){const n=this._logger.create("_signinEnd"),s=await this._client.processSigninResponse(e);n.debug("got signin response");return await this._buildUser(s,t)}async _buildUser(e,t){const n=this._logger.create("_buildUser"),s=new Cn(e);if(t){if(t!==s.profile.sub)throw n.debug("current user does not match user returned from signin. sub from signin:",s.profile.sub),new nn({...e,error:"login_required"});n.debug("current user matches user returned from signin")}return await this.storeUser(s),n.debug("user stored"),this._events.load(s),s}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:n,...s}=e,i=await this._redirectNavigator.prepare({redirectMethod:n});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...s},i),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),n=await this._signoutEnd(e);return t.info("success"),n}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:n,popupWindowTarget:s,...i}=e,r=this.settings.popup_post_logout_redirect_uri,o=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:r,state:null==r?void 0:{},...i},o),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async _signout(e,t){const n=await this._signoutStart(e,t);return await this._signoutEnd(n.url)}async _signoutStart(e={},t){var n;const s=this._logger.create("_signoutStart");try{const i=await this._loadUser();s.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(i);const r=e.id_token_hint||i&&i.id_token;r&&(s.debug("setting id_token_hint in signout request"),e.id_token_hint=r),await this.removeUser(),s.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return s.debug("got signout request"),await t.navigate({url:o.url,state:null==(n=o.state)?void 0:n.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(i){throw s.debug("error after preparing navigator, closing navigator window"),t.close(),i}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),n=await this._client.processSignoutResponse(e);return t.debug("got signout response"),n}async signoutSilent(e={}){var t;const n=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:s,...i}=e,r=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:s});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:r,...i},a),n.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 n=this._logger.create("_revokeInternal");if(!e)return;const s=t.filter((t=>"string"==typeof e[t]));if(s.length){for(const t of s)await this._client.revokeToken(e[t],t),n.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),n.debug("user stored"),this._events.load(e)}else n.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"),Cn.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const n=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,n)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey)}async clearStaleState(){await this._client.clearStaleState()}};class AuthManager{}class AuthSubscriptions{constructor(){this.subscribers=[],this.lastNotifiedValue=void 0}add(e){return this.subscribers.push(e),this.lastNotifiedValue&&e(...this.lastNotifiedValue),{unsubscribe:()=>this.unsubscribe(e)}}notify(...e){this.lastNotifiedValue=e,this.subscribers.forEach((t=>{t(...e)}))}unsubscribe(e){if(e){const t=this.subscribers.indexOf(e);-1!==t&&this.subscribers.splice(t,1)}else this.subscribers=[]}}const zn=window.localStorage,Fn=null==(Kt=window.Capacitor)||null==(Kt=Kt.Plugins)?void 0:Kt.Storage,Jn=null==(Vt=window.Capacitor)||null==(Vt=Vt.Plugins)?void 0:Vt.Preferences,Kn=null==(Gt=window.Capacitor)||null==(Gt=Gt.Plugins)?void 0:Gt.SecureStoragePlugin;class MobileStorage{constructor(){if(this._logger=new Jt("MobileStorage"),!Kn){let e="[@badisi/auth-js] This application is currently using an unsafe storage.\n\n";e+="\u24d8 Please follow the recommended guide and use `capacitor-secure-storage-plugin` instead.",console.warn(e)}Kn?this._logger.debug("Using `capacitor-secure-storage-plugin` implementation"):Jn?this._logger.debug("Using `@capacitor/preferences` implementation"):Fn?this._logger.debug("Using `@capacitor/storage` implementation"):this._logger.debug("Using `localStorage` implementation")}get length(){return async function(){return Kn?(await Kn.keys()).value.length:Jn?(await Jn.keys()).keys.length:Fn?(await Fn.keys()).keys.length:zn.length}()}async key(e){return Kn?(await Kn.keys()).value[e]:Jn?(await Jn.keys()).keys[e]:Fn?(await Fn.keys()).keys[e]:zn.key(e)}async clear(){this._logger.create("clear"),Kn?await Kn.clear():Jn?await Jn.clear():Fn?await Fn.clear():zn.clear()}async getItem(e){if(this._logger.create(`getItem('${e}')`),!Kn)return Jn?(await Jn.get({key:e})).value:Fn?(await Fn.get({key:e})).value:zn.getItem(e);try{return(await Kn.get({key:e})).value}catch(t){return null}}async setItem(e,t){this._logger.create(`setItem('${e}')`),Kn?await Kn.set({key:e,value:t}):Jn?await Jn.set({key:e,value:t}):Fn?await Fn.set({key:e,value:t}):zn.setItem(e,t)}async removeItem(e){if(this._logger.create(`removeItem('${e}')`),Kn)try{await Kn.remove({key:e})}catch(t){}else Jn?await Jn.remove({key:e}):Fn?await Fn.remove({key:e}):zn.removeItem(e)}}let Vn=function(e){return e.REDIRECT="REDIRECT",e.POPUP="POPUP",e}({});class UserSession{constructor(){this.expired=void 0,this.expires_in=void 0,this.expires_at=void 0}static deserialize(e){const t=new UserSession,n=Object.keys(t);for(const s of n)t[s]=e[s];return t}}function Gn(e,t){if(null==e)return{};var n,s,i={},r=Object.keys(e);for(s=0;s=0||(i[n]=e[n]);return i}var Qn,Xn;const Yn=null==(Qn=window.Capacitor)||null==(Qn=Qn.Plugins)?void 0:Qn.App,Zn=null==(Xn=window.Capacitor)||null==(Xn=Xn.Plugins)?void 0:Xn.Browser;class MobileWindow{constructor(e,t){if(this.redirectUrl=e,this.params=t,this._logger=new Jt("MobileWindow"),this.capacitorAppUrlOpenHandle=void 0,this.capacitorBrowserFinishedHandle=void 0,this.originalHandleOpenURL=window.handleOpenURL,this.timer=void 0,this.navigateLogger=void 0,this._resolve=void 0,this._reject=void 0,this._isClosed=!0,this._receivedResult=!1,!AuthUtils.isCapacitor()&&!AuthUtils.isCordova()){let e="[@badisi/auth-js] Required core dependency not found.\n\n";e+="\u24d8 Please follow the recommended guide and install either `Capacitor` or `Cordova` dependency.",console.error(e)}if(!Zn){let e="[@badisi/auth-js] Required plugin not found.\n\n";e+="\u24d8 Please follow the recommended guide and install either `@badisi/capacitor-browsertab` or `@capacitor/browser` plugin.",console.error(e)}Zn&&this._logger.debug("Using `@capacitor/browser` implementation")}async navigate(e){return this.navigateLogger=this._logger.create("navigate"),this.navigateLogger.debug("url",e.url),this._isClosed=!1,this._receivedResult=!1,new Promise(((t,n)=>{this._resolve=t,this._reject=n,this.installCustomUrlSchemeHandler().then((()=>{Zn&&this.useCapacitorBrowser(e)}))}))}async close(){const e=this._logger.create("close");this._isClosed||await(null==Zn?void 0:Zn.close().catch((t=>e.error(t)))),e.debug("success")}async cleanup(){var e,t;const n=this._logger.create("cleanup");window.handleOpenURL=this.originalHandleOpenURL,await(null==(e=this.capacitorBrowserFinishedHandle)?void 0:e.remove()),await(null==(t=this.capacitorAppUrlOpenHandle)?void 0:t.remove()),clearTimeout(this.timer),n.debug("success")}async onError(e){var t,n;null==(t=this.navigateLogger)||t.error("error response:",e),await this.close(),await this.cleanup(),null==(n=this._reject)||n.call(this,new Error(e)),this._receivedResult=!0}async onSuccess(e){var t,n;null==(t=this.navigateLogger)||t.debug("successful response:",e),await this.close(),await this.cleanup(),null==(n=this._resolve)||n.call(this,{url:e}),this._receivedResult=!0}async useCapacitorBrowser(e){this.capacitorBrowserFinishedHandle=await(null==Zn?void 0:Zn.addListener("browserFinished",(()=>{this._isClosed=!0,setTimeout((()=>{var e;this._receivedResult||(this.cleanup(),null==(e=this._reject)||e.call(this,"Capacitor browser closed by user"))}),1e3)}))),await(null==Zn?void 0:Zn.open({url:e.url,toolbarColor:this.params.mobileWindowToolbarColor,presentationStyle:this.params.mobileWindowPresentationStyle,width:this.params.mobileWindowWidth,height:this.params.mobileWindowWidth}))}async useBrowserTab(e){}async installCustomUrlSchemeHandler(){const e=this._logger.create("installCustomUrlSchemeHandler");this.timer=setTimeout((()=>{this.onError("Installing custom url scheme handler, timed out without a response")}),1e4),await this.cleanup(),AuthUtils.isCapacitor()?(e.debug("listening to Capacitor `appUrlOpen` event"),this.capacitorAppUrlOpenHandle=await(null==Yn||null==Yn.addListener?void 0:Yn.addListener("appUrlOpen",(({url:e})=>{AuthUtils.isUrlMatching(e,this.redirectUrl)&&this.onSuccess(e)})))):AuthUtils.isCordova()&&(e.debug("waiting for Cordova `handleOpenURL` callback"),window.handleOpenURL=e=>{var t;null==(t=this.originalHandleOpenURL)||t.call(this,e),AuthUtils.isUrlMatching(e,this.redirectUrl)&&this.onSuccess(e)}),e.debug("success")}}class MobileNavigator{constructor(){this._logger=new Jt("MobileNavigator")}prepare(e,t){return this._logger.create("prepare"),new MobileWindow(e,t)}}const es=["mobileWindowToolbarColor","mobileWindowPresentationStyle","mobileWindowWidth","mobileWindowHeight"],ts=["mobileWindowToolbarColor","mobileWindowPresentationStyle","mobileWindowWidth","mobileWindowHeight"];var ns=d("mobileNavigator");class OidcUserManager extends Bn{constructor(e){super(Object.assign({authority:e.authorityUrl,client_id:e.clientId,scope:e.scope,loadUserInfo:e.loadUserInfo,automaticSilentRenew:e.automaticSilentRenew},e.internal)),this.libSettings=e,Object.defineProperty(this,ns,{writable:!0,value:void 0}),c(this,ns)[ns]=new MobileNavigator}async signoutMobile(e={}){var t,n,s,i;const r=this._logger.create("signout"),{mobileWindowToolbarColor:o,mobileWindowPresentationStyle:a,mobileWindowWidth:l,mobileWindowHeight:d}=e,u=Gn(e,es),h={mobileWindowToolbarColor:null!=o?o:null==(t=this.libSettings.internal)?void 0:t.mobileWindowToolbarColor,mobileWindowPresentationStyle:null!=a?a:null==(n=this.libSettings.internal)?void 0:n.mobileWindowPresentationStyle,mobileWindowWidth:null!=l?l:null==(s=this.libSettings.internal)?void 0:s.mobileWindowWidth,mobileWindowHeight:null!=d?d:null==(i=this.libSettings.internal)?void 0:i.mobileWindowHeight},p=c(this,ns)[ns].prepare(this.settings.post_logout_redirect_uri,h);await this._signout(Object.assign({request_type:"so:m",post_logout_redirect_uri:this.settings.post_logout_redirect_uri},u),p),r.info("success")}async signinMobile(e={}){var t,n,s,i,r;const o=this._logger.create("signin"),{mobileWindowToolbarColor:a,mobileWindowPresentationStyle:l,mobileWindowWidth:d,mobileWindowHeight:u}=e,h=Gn(e,ts),p={mobileWindowToolbarColor:null!=a?a:null==(t=this.libSettings.internal)?void 0:t.mobileWindowToolbarColor,mobileWindowPresentationStyle:null!=l?l:null==(n=this.libSettings.internal)?void 0:n.mobileWindowPresentationStyle,mobileWindowWidth:null!=d?d:null==(s=this.libSettings.internal)?void 0:s.mobileWindowWidth,mobileWindowHeight:null!=u?u:null==(i=this.libSettings.internal)?void 0:i.mobileWindowHeight},g=c(this,ns)[ns].prepare(this.settings.redirect_uri,p),_=await this._signin(Object.assign({request_type:"si:m",redirect_uri:this.settings.redirect_uri},h),g);null!=_&&null!=(r=_.profile)&&r.sub?o.info("success, signed in subject",_.profile.sub):o.info("no subject")}}const ss="auth-js:oidc_manager:redirect_url",is={loginRequired:!1,retrieveUserSession:!0,loadUserInfo:!1,automaticSilentRenew:!0,desktopNavigationType:Vn.REDIRECT,scope:"openid profile email phone",logLevel:Ft.NONE,internal:{response_type:"code",redirect_uri:"?oidc-callback=login",post_logout_redirect_uri:"?oidc-callback=logout",popup_redirect_uri:"oidc/callback/popup_redirect.html",popup_post_logout_redirect_uri:"oidc/callback/popup_redirect.html",silent_redirect_uri:"oidc/callback/silent_redirect.html",mobileWindowPresentationStyle:"popover"}};var rs=d("idTokenSubs"),os=d("accessTokenSubs"),as=d("userProfileSubs"),cs=d("userSessionSubs"),ls=d("authenticatedSubs"),ds=d("renewingSubs"),us=d("redirectSubs"),hs=d("userManagerSubs"),ps=d("idToken"),gs=d("accessToken"),_s=d("userProfile"),ms=d("userSession"),fs=d("isAuthenticated"),ws=d("isRenewing"),vs=d("userManager"),bs=d("settings"),ys=d("user"),Ss=d("assertNotInInceptionLoop"),ks=d("waitForRenew"),Es=d("postLogoutVerification"),xs=d("notifyRenew"),Cs=d("runSyncOrAsync"),Ts=d("redirect"),Us=d("removeUser"),As=d("signinSilent"),Ps=d("callSignin"),Rs=d("callSignout");class OIDCAuthManager extends AuthManager{constructor(...e){super(...e),Object.defineProperty(this,Rs,{value:$s}),Object.defineProperty(this,Ps,{value:Ws}),Object.defineProperty(this,As,{value:Hs}),Object.defineProperty(this,Us,{value:qs}),Object.defineProperty(this,Ts,{value:Ms}),Object.defineProperty(this,Cs,{value:Ns}),Object.defineProperty(this,xs,{value:Ls}),Object.defineProperty(this,Es,{value:js}),Object.defineProperty(this,ks,{value:Os}),Object.defineProperty(this,Ss,{value:Is}),Object.defineProperty(this,rs,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,os,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,as,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,cs,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,ls,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,ds,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,us,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,hs,{writable:!0,value:[]}),Object.defineProperty(this,ps,{writable:!0,value:void 0}),Object.defineProperty(this,gs,{writable:!0,value:void 0}),Object.defineProperty(this,_s,{writable:!0,value:void 0}),Object.defineProperty(this,ms,{writable:!0,value:void 0}),Object.defineProperty(this,fs,{writable:!0,value:!1}),Object.defineProperty(this,ws,{writable:!0,value:!1}),Object.defineProperty(this,vs,{writable:!0,value:void 0}),Object.defineProperty(this,bs,{writable:!0,value:is}),Object.defineProperty(this,ys,{writable:!0,value:void 0})}set user(e){c(this,ys)[ys]!==e&&(c(this,ys)[ys]=e,c(this,ps)[ps]=e?e.id_token:void 0,c(this,gs)[gs]=e?e.access_token:void 0,c(this,_s)[_s]=null!=e&&e.profile?e.profile:void 0,c(this,ms)[ms]=e?UserSession.deserialize(e):void 0,c(this,fs)[fs]=!(!e||e.expired),c(this,rs)[rs].notify(c(this,ps)[ps]),c(this,os)[os].notify(c(this,gs)[gs]),c(this,as)[as].notify(c(this,_s)[_s]),c(this,cs)[cs].notify(c(this,ms)[ms]),c(this,ls)[ls].notify(c(this,fs)[fs]))}async init(e){var t,n,s,i,r,o,a,l,d,u=this;Ft.setLevel(null!=(t=null!=(n=e.logLevel)?n:is.logLevel)?t:Ft.NONE),Ft.setLogger(console);const h=AuthUtils.isNativeMobile(),p=h?`${e.mobileScheme}://localhost/`:AuthUtils.getBaseUrl();if(c(this,bs)[bs]=It({},is,{internal:{userStore:new dn({store:h?new MobileStorage:new an}),redirect_uri:`${p}${null==(s=is.internal)?void 0:s.redirect_uri}`,post_logout_redirect_uri:`${p}${null==(i=is.internal)?void 0:i.post_logout_redirect_uri}`,popup_redirect_uri:`${p}${null==(r=is.internal)?void 0:r.popup_redirect_uri}`,popup_post_logout_redirect_uri:`${p}${null==(o=is.internal)?void 0:o.popup_post_logout_redirect_uri}`,silent_redirect_uri:`${p}${null==(a=is.internal)?void 0:a.silent_redirect_uri}`}},e),c(this,vs)[vs]=new OidcUserManager(c(this,bs)[bs]),c(this,hs)[hs].push(c(this,vs)[vs].events.addUserLoaded((e=>{this.user=e})),c(this,vs)[vs].events.addUserUnloaded((()=>{c(this,ys)[ys]&&(this.user=null,c(this,bs)[bs].loginRequired&&location.reload())})),c(this,vs)[vs].events.addSilentRenewError((async function(){await c(u,Us)[Us]()}))),c(this,Ss)[Ss](),AuthUtils.isUrlMatching(location.href,null==(l=c(this,bs)[bs].internal)?void 0:l.redirect_uri))await c(this,Cs)[Cs]((async function(){const e=sessionStorage.getItem(ss);await c(u,Ps)[Ps]((()=>c(u,vs)[vs].signinRedirectCallback(location.href)),e),sessionStorage.removeItem(ss)}));else if(AuthUtils.isUrlMatching(location.href,null==(d=c(this,bs)[bs].internal)?void 0:d.post_logout_redirect_uri))await c(this,Cs)[Cs]((async function(){const e=sessionStorage.getItem(ss);await c(u,Rs)[Rs]((()=>c(u,vs)[vs].signoutRedirectCallback(location.href)),e),sessionStorage.removeItem(ss)}));else if(c(this,bs)[bs].retrieveUserSession||c(this,bs)[bs].loginRequired){var g;const e=async function(){await c(u,Cs)[Cs]((()=>c(u,As)[As]().catch((async function(e){const{error:t,message:n}=e;if(c(u,bs)[bs].loginRequired&&(null!=t&&t.includes("_required")||null!=n&&n.includes("_required")))await u.login();else if(console.error("[OIDCAuthManager] User's session cannot be retrieved:",e.message),c(u,ls)[ls].notify(!1),c(u,bs)[bs].loginRequired)throw e}))))},t=await(null==(g=c(this,vs)[vs])?void 0:g.getUser());!t||t.expired?!h&&c(this,bs)[bs].retrieveUserSession?await e():c(this,bs)[bs].loginRequired?await this.login():this.user=null:this.user=t}else this.user=null}async logout(e){var t,n;const s=null!=(t=null==e?void 0:e.redirectUrl)?t:location.href;var i;if(AuthUtils.isNativeMobile())await c(this,Rs)[Rs]((()=>c(this,vs)[vs].signoutMobile(e)),s);else switch(null!=(i=null==e?void 0:e.desktopNavigationType)?i:c(this,bs)[bs].desktopNavigationType){case Vn.POPUP:await c(this,Rs)[Rs]((()=>c(this,vs)[vs].signoutPopup(e)),s);break;case Vn.REDIRECT:default:sessionStorage.setItem(ss,s),await(null==(n=c(this,vs)[vs])?void 0:n.signoutRedirect(e))}}async login(e){var t,n;const s=null!=(t=null==e?void 0:e.redirectUrl)?t:location.href;var i;if(AuthUtils.isNativeMobile())await c(this,Ps)[Ps]((()=>c(this,vs)[vs].signinMobile(e)),s);else switch(null!=(i=null==e?void 0:e.desktopNavigationType)?i:c(this,bs)[bs].desktopNavigationType){case Vn.POPUP:await c(this,Ps)[Ps]((()=>c(this,vs)[vs].signinPopup(e)),s);break;case Vn.REDIRECT:default:sessionStorage.setItem(ss,s),await(null==(n=c(this,vs)[vs])?void 0:n.signinRedirect(e))}return c(this,fs)[fs]}async renew(e){return c(this,As)[As](e).catch((e=>console.error(e)))}getSettings(){return c(this,bs)[bs]}isRenewing(){return c(this,ws)[ws]}async isAuthenticated(){return await c(this,ks)[ks]("isAuthenticated()"),c(this,fs)[fs]}async getUserProfile(){return await c(this,ks)[ks]("getUserProfile()"),c(this,_s)[_s]}async getUserSession(){return await c(this,ks)[ks]("getUserSession()"),c(this,ms)[ms]}async getIdToken(){return await c(this,ks)[ks]("getIdToken()"),c(this,ps)[ps]}async getIdTokenDecoded(){return await c(this,ks)[ks]("getIdTokenDecoded()"),AuthUtils.decodeJwt(c(this,ps)[ps])}async getAccessToken(){return await c(this,ks)[ks]("getAccessToken()"),c(this,gs)[gs]}async getAccessTokenDecoded(){return await c(this,ks)[ks]("getAccessTokenDecoded()"),AuthUtils.decodeJwt(c(this,gs)[gs])}destroy(){c(this,rs)[rs].unsubscribe(),c(this,os)[os].unsubscribe(),c(this,as)[as].unsubscribe(),c(this,cs)[cs].unsubscribe(),c(this,ls)[ls].unsubscribe(),c(this,ds)[ds].unsubscribe(),c(this,us)[us].unsubscribe(),c(this,hs)[hs].forEach((e=>e()))}onIdTokenChanged(e){return c(this,rs)[rs].add(e)}onAccessTokenChanged(e){return c(this,os)[os].add(e)}onUserProfileChanged(e){return c(this,as)[as].add(e)}onUserSessionChanged(e){return c(this,cs)[cs].add(e)}onAuthenticatedChanged(e){return c(this,ls)[ls].add(e)}onRenewingChanged(e){return c(this,ds)[ds].add(e)}onRedirect(e){return c(this,us)[us].add(e)}}function Is(){var e,t;[null==(e=c(this,bs)[bs].internal)?void 0:e.silent_redirect_uri,null==(t=c(this,bs)[bs].internal)?void 0:t.popup_redirect_uri].forEach((e=>{var t;const n=null==(t=new RegExp(/^.*\/(.*).html$/gm).exec(null!=e?e:""))?void 0:t[1],s=new Error(`[OIDCAuthManager] ${null!=e?e:"redirect uri"} was not found.`);if(s.stack=void 0,AuthUtils.isUrlMatching(location.href,e))throw s.message+="\n\n\u24d8 This usually means you forgot to include the redirect html files in your application assets.",s;if(location.href.includes(`/${n}.html`))throw s.message+="\n\n\u24d8 This usually means your redirect urls are misconfigured.",s}))}async function Os(e){const t=Date.now();for(;c(this,ws)[ws];){if(Date.now()>t+5e3){console.warn("[@badisi/auth-js]",`\`${e}\``,"timed out waiting for renew to finish.");break}await new Promise((e=>setTimeout(e,100)))}}function js(e){const t=AuthUtils.stringToURL(null!=e?e:"/");c(this,bs)[bs].loginRequired&&location.origin===t.origin&&location.reload()}function Ls(e){c(this,ws)[ws]=e,c(this,ds)[ds].notify(e)}async function Ns(e){c(this,bs)[bs].loginRequired?await e():e()}async function Ms(e,t){t&&(console.error(t),await c(this,Us)[Us]());const n=AuthUtils.stringToURL(null!=e?e:"/");location.origin===n.origin?(history.replaceState(history.state,"",n.href),c(this,us)[us].notify(n)):location.href=n.href}async function qs(){var e,t;this.user=null,await Promise.all([null==(e=c(this,vs)[vs])?void 0:e.clearStaleState(),null==(t=c(this,vs)[vs])?void 0:t.removeUser()])}async function Hs(e){c(this,xs)[xs](!0);try{var t;await(null==(t=c(this,vs)[vs])?void 0:t.signinSilent(e))}catch(n){throw await c(this,Us)[Us](),n}finally{c(this,xs)[xs](!1)}}async function Ws(e,t){try{c(this,xs)[xs](!0),await e().catch((e=>{var t;throw"Attempted to navigate on a disposed window"===(null==(t=e)?void 0:t.message)&&((e=new Error("[OIDCAuthManager] Attempted to navigate on a disposed window.")).stack=void 0,e.message+="\n\n\u24d8 This may be due to an ad blocker."),e})),await c(this,Ts)[Ts](t)}catch(n){throw await c(this,Ts)[Ts]("/",n),n}finally{c(this,xs)[xs](!1)}}async function $s(e,t){try{await e().catch((e=>{var t;throw"Attempted to navigate on a disposed window"===(null==(t=e)?void 0:t.message)&&((e=new Error("[OIDCAuthManager] Attempted to navigate on a disposed window.")).stack=void 0,e.message+="\n\n\u24d8 This may be due to an ad blocker."),e})),await c(this,Ts)[Ts](t),await c(this,Us)[Us]()}catch(n){throw t="/",await c(this,Ts)[Ts](t,n),n}finally{c(this,Es)[Es](t)}}const Ds=(e=>e.CapacitorPlatforms=(e=>{const t=new Map;t.set("web",{name:"web"});const n=e.CapacitorPlatforms||{currentPlatform:{name:"web"},platforms:t};return n.addPlatform=(e,t)=>{n.platforms.set(e,t)},n.setPlatform=e=>{n.platforms.has(e)&&(n.currentPlatform=n.platforms.get(e))},n})(e))("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{});Ds.addPlatform,Ds.setPlatform;var Bs;!function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"}(Bs||(Bs={}));class CapacitorException extends Error{constructor(e,t,n){super(e),this.message=e,this.code=t,this.data=n}}const zs=e=>{var t,n,s,i,r;const o=e.CapacitorCustomPlatform||null,a=e.Capacitor||{},c=a.Plugins=a.Plugins||{},l=e.CapacitorPlatforms,d=(null===(t=null==l?void 0:l.currentPlatform)||void 0===t?void 0:t.getPlatform)||(()=>null!==o?o.name:(e=>{var t,n;return(null==e?void 0:e.androidBridge)?"android":(null===(n=null===(t=null==e?void 0:e.webkit)||void 0===t?void 0:t.messageHandlers)||void 0===n?void 0:n.bridge)?"ios":"web"})(e)),u=(null===(n=null==l?void 0:l.currentPlatform)||void 0===n?void 0:n.isNativePlatform)||(()=>"web"!==d()),h=(null===(s=null==l?void 0:l.currentPlatform)||void 0===s?void 0:s.isPluginAvailable)||(e=>{const t=g.get(e);return!!(null==t?void 0:t.platforms.has(d()))||!!p(e)}),p=(null===(i=null==l?void 0:l.currentPlatform)||void 0===i?void 0:i.getPluginHeader)||(e=>{var t;return null===(t=a.PluginHeaders)||void 0===t?void 0:t.find((t=>t.name===e))}),g=new Map,_=(null===(r=null==l?void 0:l.currentPlatform)||void 0===r?void 0:r.registerPlugin)||((e,t={})=>{const n=g.get(e);if(n)return console.warn(`Capacitor plugin "${e}" already registered. Cannot register plugins twice.`),n.proxy;const s=d(),i=p(e);let r;const l=n=>{let c;const l=(...l)=>{const d=(async()=>(!r&&s in t?r=r="function"==typeof t[s]?await t[s]():t[s]:null!==o&&!r&&"web"in t&&(r=r="function"==typeof t.web?await t.web():t.web),r))().then((t=>{const r=((t,n)=>{var r,o;if(!i){if(t)return null===(o=t[n])||void 0===o?void 0:o.bind(t);throw new CapacitorException(`"${e}" plugin is not implemented on ${s}`,Bs.Unimplemented)}{const s=null==i?void 0:i.methods.find((e=>n===e.name));if(s)return"promise"===s.rtype?t=>a.nativePromise(e,n.toString(),t):(t,s)=>a.nativeCallback(e,n.toString(),t,s);if(t)return null===(r=t[n])||void 0===r?void 0:r.bind(t)}})(t,n);if(r){const e=r(...l);return c=null==e?void 0:e.remove,e}throw new CapacitorException(`"${e}.${n}()" is not implemented on ${s}`,Bs.Unimplemented)}));return"addListener"===n&&(d.remove=async()=>c()),d};return l.toString=()=>`${n.toString()}() { [capacitor code] }`,Object.defineProperty(l,"name",{value:n,writable:!1,configurable:!1}),l},u=l("addListener"),h=l("removeListener"),_=(e,t)=>{const n=u({eventName:e},t),s=async()=>{const s=await n;h({eventName:e,callbackId:s},t)},i=new Promise((e=>n.then((()=>e({remove:s})))));return i.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await s()},i},m=new Proxy({},{get(e,t){switch(t){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return i?_:u;case"removeListener":return h;default:return l(t)}}});return c[e]=m,g.set(e,{name:e,proxy:m,platforms:new Set([...Object.keys(t),...i?[s]:[]])}),m});return a.convertFileSrc||(a.convertFileSrc=e=>e),a.getPlatform=d,a.handleError=t=>e.console.error(t),a.isNativePlatform=u,a.isPluginAvailable=h,a.pluginMethodNoop=(e,t,n)=>Promise.reject(`${n} does not have an implementation of "${t}".`),a.registerPlugin=_,a.Exception=CapacitorException,a.DEBUG=!!a.DEBUG,a.isLoggingEnabled=!!a.isLoggingEnabled,a.platform=a.getPlatform(),a.isNative=a.isNativePlatform(),a},Fs=(e=>e.Capacitor=zs(e))("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}),Js=Fs.registerPlugin;Fs.Plugins;class WebPlugin{constructor(e){this.listeners={},this.windowListeners={},e&&(console.warn(`Capacitor WebPlugin "${e.name}" config object was deprecated in v3 and will be removed in v4.`),this.config=e)}addListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t);const n=this.windowListeners[e];n&&!n.registered&&this.addWindowListener(n);const s=async()=>this.removeListener(e,t),i=Promise.resolve({remove:s});return Object.defineProperty(i,"remove",{value:async()=>{console.warn("Using addListener() without 'await' is deprecated."),await s()}}),i}async removeAllListeners(){this.listeners={};for(const e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,t){const n=this.listeners[e];n&&n.forEach((e=>e(t)))}hasListeners(e){return!!this.listeners[e].length}registerWindowListener(e,t){this.windowListeners[t]={registered:!1,windowEventName:e,pluginEventName:t,handler:e=>{this.notifyListeners(t,e)}}}unimplemented(e="not implemented"){return new Fs.Exception(e,Bs.Unimplemented)}unavailable(e="not available"){return new Fs.Exception(e,Bs.Unavailable)}async removeListener(e,t){const n=this.listeners[e];if(!n)return;const s=n.indexOf(t);this.listeners[e].splice(s,1),this.listeners[e].length||this.removeWindowListener(this.windowListeners[e])}addWindowListener(e){window.addEventListener(e.windowEventName,e.handler),e.registered=!0}removeWindowListener(e){e&&(window.removeEventListener(e.windowEventName,e.handler),e.registered=!1)}}const Ks=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Vs=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class CapacitorCookiesPluginWeb extends WebPlugin{async getCookies(){const e=document.cookie,t={};return e.split(";").forEach((e=>{if(e.length<=0)return;let[n,s]=e.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");n=Vs(n).trim(),s=Vs(s).trim(),t[n]=s})),t}async setCookie(e){try{const t=Ks(e.key),n=Ks(e.value),s=`; expires=${(e.expires||"").replace("expires=","")}`,i=(e.path||"/").replace("path=",""),r=null!=e.url&&e.url.length>0?`domain=${e.url}`:"";document.cookie=`${t}=${n||""}${s}; path=${i}; ${r};`}catch(t){return Promise.reject(t)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(t){return Promise.reject(t)}}async clearCookies(){try{const e=document.cookie.split(";")||[];for(const t of e)document.cookie=t.replace(/^ +/,"").replace(/=.*/,`=;expires=${(new Date).toUTCString()};path=/`)}catch(e){return Promise.reject(e)}}async clearAllCookies(){try{await this.clearCookies()}catch(e){return Promise.reject(e)}}}Js("CapacitorCookies",{web:()=>new CapacitorCookiesPluginWeb});const Gs=(e,t={})=>{const n=Object.assign({method:e.method||"GET",headers:e.headers},t),s=((e={})=>{const t=Object.keys(e);return Object.keys(e).map((e=>e.toLocaleLowerCase())).reduce(((n,s,i)=>(n[s]=e[t[i]],n)),{})})(e.headers)["content-type"]||"";if("string"==typeof e.data)n.body=e.data;else if(s.includes("application/x-www-form-urlencoded")){const t=new URLSearchParams;for(const[n,s]of Object.entries(e.data||{}))t.set(n,s);n.body=t.toString()}else if(s.includes("multipart/form-data")||e.data instanceof FormData){const t=new FormData;if(e.data instanceof FormData)e.data.forEach(((e,n)=>{t.append(n,e)}));else for(const n of Object.keys(e.data))t.append(n,e.data[n]);n.body=t;const s=new Headers(n.headers);s.delete("content-type"),n.headers=s}else(s.includes("application/json")||"object"==typeof e.data)&&(n.body=JSON.stringify(e.data));return n};class CapacitorHttpPluginWeb extends WebPlugin{async request(e){const t=Gs(e,e.webFetchExtra),n=((e,t=!0)=>e?Object.entries(e).reduce(((e,n)=>{const[s,i]=n;let r,o;return Array.isArray(i)?(o="",i.forEach((e=>{r=t?encodeURIComponent(e):e,o+=`${s}=${r}&`})),o.slice(0,-1)):(r=t?encodeURIComponent(i):i,o=`${s}=${r}`),`${e}&${o}`}),"").substr(1):null)(e.params,e.shouldEncodeUrlParams),s=n?`${e.url}?${n}`:e.url,i=await fetch(s,t),r=i.headers.get("content-type")||"";let o,a,{responseType:c="text"}=i.ok?e:{};switch(r.includes("application/json")&&(c="json"),c){case"arraybuffer":case"blob":a=await i.blob(),o=await(async e=>new Promise(((t,n)=>{const s=new FileReader;s.onload=()=>{const e=s.result;t(e.indexOf(",")>=0?e.split(",")[1]:e)},s.onerror=e=>n(e),s.readAsDataURL(e)})))(a);break;case"json":o=await i.json();break;default:o=await i.text()}const l={};return i.headers.forEach(((e,t)=>{l[t]=e})),{data:o,headers:l,status:i.status,url:i.url}}async get(e){return this.request(Object.assign(Object.assign({},e),{method:"GET"}))}async post(e){return this.request(Object.assign(Object.assign({},e),{method:"POST"}))}async put(e){return this.request(Object.assign(Object.assign({},e),{method:"PUT"}))}async patch(e){return this.request(Object.assign(Object.assign({},e),{method:"PATCH"}))}async delete(e){return this.request(Object.assign(Object.assign({},e),{method:"DELETE"}))}}Js("CapacitorHttp",{web:()=>new CapacitorHttpPluginWeb});const Qs='\n .flex {\n flex: 1;\n }\n\n .hidden {\n display: none !important;\n }\n\n .row {\n display: flex;\n flex-direction: row;\n }\n\n .column {\n display: flex;\n flex-direction: column;\n }\n\n .card {\n border: 1px solid rgba(0, 0, 0, 0.12);\n border-radius: 4px;\n background-color: white;\n margin: 12px 6px;\n }\n\n .card .card-status {\n display: block;\n width: 10px;\n height: 10px;\n border-radius: 50%;\n margin-left: 8px;\n background-color: #f2f2f2;\n }\n .card .card-status.error {\n background-color: #ef5350;\n }\n .card .card-status.success {\n background-color: #66bb6a;\n }\n\n .card .card-title {\n padding: 16px;\n font-size: 20px;\n font-weight: 500;\n color: rgba(0, 0, 0, 0.87);\n align-items: center;\n }\n\n .card .box {\n height: 200px;\n border-top: 1px solid lightgray;\n word-break: break-all;\n overflow: auto;\n background-color: #f2f2f2;\n padding: 12px;\n }\n .card .box pre {\n margin: 0;\n }\n\n .card .card-actions {\n padding: 0 14px 8px 14px;\n min-height: 50px;\n }\n .card .card-actions .input {\n display: flex;\n align-items: center;\n }\n .card .card-actions .input:not(:last-child) {\n margin-bottom: 8px;\n }\n .card .card-actions .input label {\n width: 125px;\n text-align: right;\n margin-right: 14px;\n }\n .card .card-actions .input input {\n padding: 4px;\n }\n\n .json-key {\n color: rgb(124, 77, 255);\n }\n\n .json-value {\n color: rgb(67, 122, 237);\n }\n\n .json-string {\n color: rgb(83, 160, 83);\n }\n\n .json-date {\n color: rgb(200, 56, 198);\n }\n\n input {\n color: #5e35b1;\n padding: 10px;\n border: 1px solid #0000001f;\n border-radius: 4px;\n font-size: 14px;\n }\n\n input:invalid {\n border-color: #f44336;\n }\n\n input[type="checkbox"] {\n margin-right: 10px;\n }\n\n select {\n color: #5e35b1;\n padding: 8px 6px;\n border: 1px solid #0000001f;\n border-radius: 4px;\n }\n\n @media only screen and (max-width: 600px) {\n :host {\n padding: 0 !important;\n padding-bottom: 24px !important;\n }\n\n :host .card {\n border-left: 0;\n border-right: 0;\n border-radius: 0;\n margin: 0;\n margin-bottom: 6px;\n }\n }\n',Xs=(e,t=[])=>e?JSON.stringify(e,null,2).replace(/&/g,"&").replace(/\\"/g,""").replace(//g,">").replace(/^( *)("[\w-]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/gm,((e,n,s,i,r)=>{let o=n||"";const a=s?s.replace(/[": ]/g,""):void 0;if(a&&(o+=`${a} : `),i&&(o+=`${i} `,a&&t.includes(a))){const e=new Date(1e3*Number(i)),t=`${e.toDateString()}, ${e.toLocaleTimeString()}`;t&&(o+=` (${t}) `)}return o+(r||"")})):"",Ys=document.createElement("template");Ys.innerHTML=`\n \n\n \n`;class DemoAppHeaderElement extends HTMLElement{constructor(){var e;super(),this.listeners=[],this.implSelectEl=void 0,this.statusEl=void 0,this.versionEl=void 0,this.loginButtonEl=void 0,this.logoutButtonEl=void 0,this.silentRenewButtonEl=void 0,this.attachShadow({mode:"open"}),null==(e=this.shadowRoot)||e.appendChild(document.importNode(Ys.content,!0)),this.implSelectEl=this.shadowRoot.querySelector("#implementation-select"),this.statusEl=this.shadowRoot.querySelector(".status"),this.versionEl=this.shadowRoot.querySelector(".version"),this.loginButtonEl=this.shadowRoot.querySelector("#login-button"),this.logoutButtonEl=this.shadowRoot.querySelector("#logout-button"),this.silentRenewButtonEl=this.shadowRoot.querySelector("#silent-renew-button")}set isRenewing(e){this.statusEl&&this.statusEl.classList[e?"add":"remove"]("loading")}set isAuthenticated(e){this.statusEl&&null!==e&&(this.statusEl.classList.remove("loading"),this.statusEl.title=e?"Authenticated":"Not authenticated",this.statusEl.classList[e?"add":"remove"]("authenticated"),this.statusEl.classList[e?"remove":"add"]("not-authenticated"))}connectedCallback(){if(window.location.href.includes(":4200")){const e=document.createElement("option");e.textContent="localhost",this.implSelectEl.appendChild(e)}else{window.appSettings.getImplementations().forEach((e=>{const t=document.createElement("option");t.value=String(e.label),t.textContent=e.label,this.implSelectEl.appendChild(t)}));const e=()=>{window.location.href=window.appSettings.getImplementations()[this.implSelectEl.selectedIndex].demoUrl};this.implSelectEl.addEventListener("change",e),this.listeners.push((()=>this.implSelectEl.removeEventListener("change",e)))}const e=()=>{var e;null==(e=this.shadowRoot)||null==(e=e.querySelector("header .title .tip"))||e.remove(),window.appSettings.setShowTip(!1)};window.appSettings.get().showTip?(this.implSelectEl.addEventListener("click",e,{once:!0}),this.listeners.push((()=>this.implSelectEl.removeEventListener("click",e)))):e(),this.refreshImplementation(),this.addEventListeners()}disconnectedCallback(){this.listeners.forEach((e=>e()))}addEventListeners(){var e,t,n;const s=()=>this.dispatchEvent(new Event("login",{bubbles:!0,composed:!0}));null==(e=this.loginButtonEl)||e.addEventListener("click",s);const i=()=>this.dispatchEvent(new Event("logout",{bubbles:!0,composed:!0}));null==(t=this.logoutButtonEl)||t.addEventListener("click",i);const r=()=>this.dispatchEvent(new Event("silentRenew",{bubbles:!0,composed:!0}));null==(n=this.silentRenewButtonEl)||n.addEventListener("click",r),this.listeners.push((()=>{var e;return null==(e=this.loginButtonEl)?void 0:e.removeEventListener("click",s)}),(()=>{var e;return null==(e=this.logoutButtonEl)?void 0:e.removeEventListener("click",i)}),(()=>{var e;return null==(e=this.silentRenewButtonEl)?void 0:e.removeEventListener("click",r)}))}refreshImplementation(){const e=window.appSettings.getImplementations();if(window.location.href.includes(":4200"))this.implSelectEl.selectedIndex=0,this.versionEl.innerHTML="@localhost ";else{const t=e.findIndex((e=>window.location.href.includes(e.demoUrl))),n=-1!==t?e[t]:e[0];this.implSelectEl.selectedIndex=-1!==t?t:0,this.versionEl.innerHTML=n.version}}}window.customElements.define("demo-app-header",DemoAppHeaderElement);const Zs=document.createElement("template");Zs.innerHTML=`\n \n\n \n \n \n \n
\n`;class DemoAppMainElement extends HTMLElement{constructor(){var e;super(),this.listeners=[],this.tabsContentEl=void 0,this.demoAppHeaderEl=void 0,this.tabs=[],this.views=[],this.currentTabIndex=-1,this.attachShadow({mode:"open"}),null==(e=this.shadowRoot)||e.appendChild(document.importNode(Zs.content,!0)),this.tabsContentEl=this.shadowRoot.querySelector(".tabs-content"),this.demoAppHeaderEl=this.shadowRoot.querySelector("demo-app-header")}set isRenewing(e){this.demoAppHeaderEl.isRenewing=e}set isAuthenticated(e){this.demoAppHeaderEl.isAuthenticated=e}connectedCallback(){this.drawTabs(),this.showView(window.appSettings?window.appSettings.get().currentTabIndex:0)}disconnectedCallback(){this.listeners.forEach((e=>e()))}drawTabs(){const e=this.shadowRoot.querySelector("#views"),t=this.shadowRoot.querySelector("#tabs");e&&t&&(this.views=e.assignedElements(),this.views.forEach(((e,n)=>{e.style.display="none";const s=document.createElement("a");s.textContent=e.getAttribute("tabLabel")||"?";const i=()=>this.showView(n);s.addEventListener("click",i),this.listeners.push((()=>s.removeEventListener("click",i))),t.appendChild(s),this.tabs.push(s)})))}showView(e){var t;this.currentTabIndex!==e&&(this.currentTabIndex=e,this.tabs.forEach(((t,n)=>{t.classList[n!==e?"remove":"add"]("selected")})),this.views.forEach(((t,n)=>{t.style.display=n!==e?"none":"flex"})),null==(t=this.tabsContentEl)||t.scrollTo(0,0),window.appSettings.setCurrentTabIndex(e))}}window.customElements.define("demo-app-main",DemoAppMainElement);const ei=document.createElement("template");ei.innerHTML=`\n \n\n \n
\n
\n
\n
\n Url \n \n
\n
\n Custom headers \n \n
\n
\n
GET \n
\n
\n
\n\n \n`;class DemoAppPlaygroundElement extends HTMLElement{constructor(){var e;super(),this.listeners=[],this.apiStatusEl=void 0,this.apiResponseEl=void 0,this.apiUrlEl=void 0,this.apiHeadersEl=void 0,this.attachShadow({mode:"open"}),null==(e=this.shadowRoot)||e.appendChild(document.importNode(ei.content,!0)),this.apiStatusEl=this.shadowRoot.querySelector("#api-status"),this.apiResponseEl=this.shadowRoot.querySelector("#api-response"),this.apiUrlEl=this.shadowRoot.querySelector("#api-url-input"),this.apiHeadersEl=this.shadowRoot.querySelector("#api-headers-input")}connectedCallback(){var e,t,n;const s=null==(e=this.shadowRoot)?void 0:e.querySelector("#api-get-button"),i=()=>{const e=new CustomEvent("api",{bubbles:!0,composed:!0,detail:{url:this.apiUrlEl.value,headers:this.apiHeadersEl.value}});return this.dispatchEvent(e)};null==s||s.addEventListener("click",i);const r=()=>this.saveSettings({privateApiUrl:this.apiUrlEl.value});null==(t=this.apiUrlEl)||t.addEventListener("input",r);const o=()=>this.saveSettings({privateApiHeaders:this.apiHeadersEl.value});null==(n=this.apiHeadersEl)||n.addEventListener("input",o),this.listeners.push((()=>null==s?void 0:s.removeEventListener("click",i)),(()=>{var e;return null==(e=this.apiUrlEl)?void 0:e.removeEventListener("input",r)}),(()=>{var e;return null==(e=this.apiHeadersEl)?void 0:e.removeEventListener("input",o)}));const{otherSettings:a}=window.appSettings.getCurrentUserSettings();this.apiUrlEl.value=null==a?void 0:a.privateApiUrl,this.apiHeadersEl.value=null==a?void 0:a.privateApiHeaders}disconnectedCallback(){this.listeners.forEach((e=>e()))}setApiStatus(e,t){this.apiStatusEl.classList.remove(t?"success":"error"),this.apiStatusEl.classList.add(t?"error":"success"),this.apiResponseEl.innerHTML=Xs(e)}saveSettings(e){const t=window.appSettings.getCurrentUserSettings();t.otherSettings=Object.assign({},t.otherSettings,e),window.appSettings.addOrUpdateUserSettings(t)}}window.customElements.define("demo-app-playground",DemoAppPlaygroundElement);const ti=document.createElement("template");ti.innerHTML=`\n \n\n \n
\n
Authenticated
\n
\n \n
\n
\n\n
\n
User session
\n
\n \n
\n
\n\n
\n
Access token
\n
\n \n \n
\n
\n\n
\n
Id token
\n
\n \n \n
\n
\n\n
\n
User profile
\n
\n \n
\n
\n
\n`;class DemoAppDebugElement extends HTMLElement{constructor(){var e;super(),this.attachShadow({mode:"open"}),null==(e=this.shadowRoot)||e.appendChild(document.importNode(ti.content,!0)),this.isAuthenticated=!1,this.userSession=void 0,this.accessToken=void 0,this.accessTokenDecoded=void 0,this.idToken=void 0,this.idTokenDecoded=void 0,this.userProfile=void 0}set isAuthenticated(e){null!==e&&this.update("#isAuthenticated",e)}set userSession(e){this.update("#userSession",Xs(e,["expires_at"]))}set accessToken(e){this.update("#accessToken",e)}set accessTokenDecoded(e){const t="string"!=typeof e?Xs(e,["exp","iat","auth_time"]):"(no decoded info as it is not a JWT token)";this.update("#accessTokenDecoded",t)}set idToken(e){this.update("#idToken",e)}set idTokenDecoded(e){this.update("#idTokenDecoded",Xs(e,["exp","iat","auth_time"]))}set userProfile(e){this.update("#userProfile",Xs(e))}update(e,t){var n;const s=null==(n=this.shadowRoot)?void 0:n.querySelector(e);var i,r;s&&(null==t||""===t?null==(i=s.closest(".info"))||i.classList.add("hidden"):(null==(r=s.closest(".info"))||r.classList.remove("hidden"),s.innerHTML=String(t)))}}window.customElements.define("demo-app-debug",DemoAppDebugElement);const ni=document.createElement("template");ni.innerHTML=`\n \n\n \n\n \n SAVE \n CANCEL \n
\n\n \n`;class DemoAppSettingsElement extends HTMLElement{constructor(){var e;super(),this.listeners=[],this.formEl=void 0,this.formContentEl=void 0,this.selectEl=void 0,this.settingsNameEl=void 0,this.formIsDirty=!1,this.formIsNew=!1,this.attachShadow({mode:"open"}),null==(e=this.shadowRoot)||e.appendChild(document.importNode(ni.content,!0))}connectedCallback(){var e,t,n,s,i;this.formEl=this.shadowRoot.querySelector("form"),this.formContentEl=this.shadowRoot.querySelector(".form-content"),this.selectEl=this.shadowRoot.querySelector("#settings-select"),this.settingsNameEl=this.shadowRoot.querySelector("#settingsName");const r=e=>{this.formIsDirty||"settings-select"===e.target.id||(this.formIsDirty=!0,this.classList.add("dirty"))};this.formEl.addEventListener("input",r),this.listeners.push((()=>this.formEl.removeEventListener("input",r))),this.refreshSelect();const o=()=>this.loadSettings(this.selectEl.value);null==(e=this.selectEl)||e.addEventListener("change",o),this.listeners.push((()=>this.selectEl.removeEventListener("change",o)));const a=null==(t=this.shadowRoot)?void 0:t.querySelector("#add-settings-button"),c=()=>this.add();null==a||a.addEventListener("click",c),this.listeners.push((()=>null==a?void 0:a.removeEventListener("click",c)));const l=null==(n=this.shadowRoot)?void 0:n.querySelector("#delete-settings-button"),d=()=>this.delete();null==l||l.addEventListener("click",d),this.listeners.push((()=>null==l?void 0:l.removeEventListener("click",d)));const u=null==(s=this.shadowRoot)?void 0:s.querySelector("#save-settings-button"),h=()=>this.saveAndReload();null==u||u.addEventListener("click",h),this.listeners.push((()=>null==u?void 0:u.removeEventListener("click",h)));const p=null==(i=this.shadowRoot)?void 0:i.querySelector("#cancel-settings-button"),g=()=>this.cancel();null==p||p.addEventListener("click",g),this.listeners.push((()=>null==p?void 0:p.removeEventListener("click",g))),this.refreshFormContent(window.appSettings.getCurrentUserSettings())}disconnectedCallback(){this.listeners.forEach((e=>e()))}loadSettings(e){window.appSettings.setCurrentUserSettings(e),location.reload()}add(){const e="New settings",t=document.createElement("option");t.selected=!0,t.value=e,t.textContent=e,this.selectEl.appendChild(t),this.formIsNew=!0,this.formIsDirty=!0,this.classList.add("dirty"),this.refreshFormContent({name:e,librarySettings:{}})}delete(){window.appSettings.deleteCurrentUserSettings(),location.reload()}cancel(){this.formIsNew=!1,this.formIsDirty=!1,this.classList.remove("dirty"),this.refreshSelect(),this.refreshFormContent(window.appSettings.getCurrentUserSettings())}setPathValue(e,t,n){const s=t.split(".");s.reduce(((e,t,i)=>(i===s.length-1?e[t]=n:Object.prototype.hasOwnProperty.call(e,t)||(e[t]={}),e[t])),e)}getPathValue(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:e),e)}refreshSelect(){this.selectEl.innerHTML="";const{userSettings:e,currentUserSettingsId:t}=window.appSettings.get();e.sort(((e,t)=>e.name.localeCompare(t.name))).forEach((e=>{const n=document.createElement("option");n.selected=e.name===t,n.value=String(e.name),n.textContent=e.name,this.selectEl.appendChild(n)}))}refreshFormContent(e){this.formContentEl.innerHTML="";const{librarySettingsDefinition:t}=window.appSettings.get(),{name:n,librarySettings:s}=e;this.settingsNameEl.value=n,t.sort(((e,t)=>(t._sortIndex||0)-(e._sortIndex||0))).forEach((e=>{var t;const n=document.createElement("div");this.formContentEl.prepend(n);const i=document.createElement("label");i.htmlFor=e.name.replace(".",""),i.textContent=`${e.label}${e.required?" *":""}`;const r=document.createElement("list"===e.type?"select":"input");switch(r.id=e.name.replace(".",""),r.name=e.name.replace(".",""),r.required=!0===e.required,e.type){case"boolean":r.checked=this.getPathValue(s,e.name),r.type="checkbox",n.appendChild(r),n.appendChild(i);break;case"list":null==(t=e.values)||t.forEach((e=>{const t=document.createElement("option");t.value=String(e.value),t.textContent=e.label,r.appendChild(t)})),r.value=this.getPathValue(s,e.name),r.classList.add("flex"),n.classList.add("input","column"),n.appendChild(i),n.appendChild(r);break;default:{const t=this.getPathValue(s,e.name);"json"===e.type?r.value=t?JSON.stringify(t):"":r.value=null!=t?t:"",n.classList.add("input","column"),n.appendChild(i),n.appendChild(r);break}}}))}saveAndReload(){if(this.formEl.reportValidity()){const{librarySettingsDefinition:e}=window.appSettings.get(),t=this.formIsNew?{name:"",librarySettings:{}}:window.appSettings.getCurrentUserSettings();t.name=this.settingsNameEl.value,e.forEach((e=>{var n;const s=null==(n=this.shadowRoot)?void 0:n.querySelector(`#${e.name.replace(".","")}`);let i;switch(e.type){case"boolean":i=s.checked;break;case"list":default:i=s.value;break;case"json":try{const e=s.value;e&&""!==e.trim()&&(i=JSON.parse(e))}catch(r){console.error(r)}}this.setPathValue(t.librarySettings,e.name,i)})),window.appSettings.addOrUpdateUserSettings(t),this.formIsNew&&window.appSettings.setCurrentUserSettings(t.name),location.reload()}}}window.customElements.define("demo-app-settings",DemoAppSettingsElement);const si=JSON.parse('{"UU":"@badisi/auth-js","rE":"0.0.0-semantically-released","TB":"https://github.com/Badisi/auth-js/tree/main/projects/auth-js"}'),ii=JSON.parse('{"UU":"@badisi/ngx-auth","TB":"https://github.com/Badisi/auth-js/tree/main/projects/ngx-auth"}');const ri=[{name:"authorityUrl",label:"Authority url",type:"string",required:!0},{name:"clientId",label:"Client id",type:"string",required:!0},{name:"mobileScheme",label:"Custom mobile scheme name",type:"string"},{name:"scope",label:"Scope",type:"string"},{name:"internal.extraQueryParams",label:"Extra query params",type:"json"},{name:"desktopNavigationType",label:"Desktop navigation type",type:"list",values:[{label:"REDIRECT",value:Vn.REDIRECT},{label:"POPUP",value:Vn.POPUP}]},{name:"logLevel",label:"Log level",type:"list",values:[{label:"NONE",value:Ft.NONE},{label:"ERROR",value:Ft.ERROR},{label:"WARN",value:Ft.WARN},{label:"INFO",value:Ft.INFO},{label:"DEBUG",value:Ft.DEBUG}]},{name:"loginRequired",label:"Login required",type:"boolean"},{name:"retrieveUserSession",label:"Retrieve user's session",type:"boolean"},{name:"loadUserInfo",label:"Load user's info",type:"boolean"},{name:"automaticSilentRenew",label:"Automatic silent renew",type:"boolean"}],oi=[...ri,{name:"automaticLoginOn401",label:"Automatic login on 401",type:"boolean"},{name:"automaticInjectToken",label:"Automatic inject token",type:"boolean"}];oi.splice(3,0,{name:"authGuardRedirectUrl",label:"AuthGuard redirect url",type:"string"});const ai=(e=!1)=>{const t=[{name:"Auth0",otherSettings:{privateApiUrl:"https://dev-fijd1e9x.us.auth0.com/api/v2/users/auth0|631b171682c639d40cb84d5c",privateApiHeaders:""},librarySettings:{authorityUrl:"https://dev-fijd1e9x.us.auth0.com",clientId:"kRVVEnAWKMpxxpcodl0TqLXfIHgQvmmt",mobileScheme:"demo-app",scope:"openid profile email phone offline_access read:current_user",internal:{extraQueryParams:{audience:"https://dev-fijd1e9x.us.auth0.com/api/v2/"}},desktopNavigationType:Vn.REDIRECT,logLevel:Ft.NONE,loginRequired:!1,retrieveUserSession:!0,loadUserInfo:!0,automaticSilentRenew:!0}},{name:"Zitadel",otherSettings:{privateApiUrl:"",privateApiHeaders:""},librarySettings:{authorityUrl:"https://auth-js-0pdipf.zitadel.cloud",clientId:"178200751804317953@demo-app",mobileScheme:"demo-app",scope:"openid profile email phone offline_access",desktopNavigationType:Vn.REDIRECT,logLevel:Ft.NONE,loginRequired:!1,retrieveUserSession:!0,loadUserInfo:!0,automaticSilentRenew:!0}}];return e||t.push({name:"Keycloak (local)",otherSettings:{privateApiUrl:"/api/my-api",privateApiHeaders:""},librarySettings:{authorityUrl:"http://localhost:8080/auth/realms/demo",clientId:"demo-app",mobileScheme:"demo-app",scope:"openid profile email phone",desktopNavigationType:Vn.REDIRECT,logLevel:Ft.NONE,loginRequired:!1,retrieveUserSession:!0,loadUserInfo:!0,automaticSilentRenew:!0}}),t},ci=new class DemoAppSettings{constructor(e,t){this.storageKey=e,this.defaultAppSettings=t,this.implementations=[{label:"VanillaJS",demoUrl:"https://badisi.github.io/auth-js/demo-app/auth-js",version:`${si.UU}@main `},{label:"Angular",demoUrl:"https://badisi.github.io/auth-js/demo-app/ngx-auth",version:`${ii.UU}@main `}],this.defaultAppSettings.librarySettingsDefinition.forEach(((e,t)=>e._sortIndex=t))}getImplementations(){return this.implementations}setShowTip(e){const t=this.get();t.showTip=e,this.saveAppSettings(t)}setCurrentTabIndex(e){const t=this.get();t.currentTabIndex=e,this.saveAppSettings(t)}addOrUpdateUserSettings(e){const t=this.get(),n=t.userSettings.findIndex((t=>t.name===e.name));-1!==n?t.userSettings[n]=e:t.userSettings.push(e),this.saveAppSettings(t)}deleteCurrentUserSettings(){const e=this.get(),{name:t}=this.getCurrentUserSettings(),n=e.userSettings.findIndex((e=>e.name===t));-1!==n&&(e.userSettings.splice(n,1),delete e.currentUserSettingsId,this.saveAppSettings(e))}setCurrentUserSettings(e){const t=this.get();-1!==t.userSettings.findIndex((t=>t.name===e))&&(t.currentUserSettingsId=e,this.saveAppSettings(t))}getCurrentUserSettings(){const e=this.get(),t=e.userSettings.findIndex((t=>t.name===e.currentUserSettingsId));return-1!==t?e.userSettings[t]:e.userSettings.sort(((e,t)=>e.name.localeCompare(t.name)))[0]}get(){const e=sessionStorage.getItem(this.storageKey);if(e){const t=Object.assign({},this.defaultAppSettings,JSON.parse(e));return this.defaultAppSettings.userSettings.forEach((e=>{t.userSettings.find((t=>t.name===e.name))||t.userSettings.push(e)})),t}return Object.assign({},this.defaultAppSettings)}saveAppSettings(e){delete e.librarySettingsDefinition,sessionStorage.setItem(this.storageKey,JSON.stringify(e))}}(`auth-js:${si.rE}:demo-app:settings`,{showTip:!0,currentTabIndex:0,userSettings:ai(!0),librarySettingsDefinition:ri});(()=>{window.appSettings=ci;const e=document.createElement("div");e.innerHTML="Loading...",document.body.appendChild(e),(async e=>await(async(e,t)=>{const n=new t;return await n.init(e),n})(e,OIDCAuthManager))(ci.getCurrentUserSettings().librarySettings).then((t=>{window.authManager=t,e.replaceWith(document.createElement("app-root"))})).catch((t=>{var n;console.error(t),e.innerHTML=`${t.message}Login `,null==(n=document.body.querySelector("#loginButton"))||n.addEventListener("click",(()=>location.reload()),{once:!0})}))})()})()})();
\ No newline at end of file
diff --git a/demo-app/auth-js/main.b8a77a848194a17d.js b/demo-app/auth-js/main.b8a77a848194a17d.js
new file mode 100644
index 0000000..81e8514
--- /dev/null
+++ b/demo-app/auth-js/main.b8a77a848194a17d.js
@@ -0,0 +1 @@
+(self.webpackChunk=self.webpackChunk||[]).push([[792],{179:(e,t,n)=>{"use strict";function s(e){this.message=e}s.prototype=new Error,s.prototype.name="InvalidCharacterError";var i="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new s("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,i,r=0,o=0,a="";i=t.charAt(o++);~i&&(n=r%4?64*n+i:i,r++%4)?a+=String.fromCharCode(255&n>>(-2*r&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return a};function r(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(i(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return i(t)}}function o(e){this.message=e}o.prototype=new Error,o.prototype.name="InvalidTokenError";const a=function(e,t){if("string"!=typeof e)throw new o("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(r(e.split(".")[n]))}catch(e){throw new o("Invalid token specified: "+e.message)}};var c;class AuthUtils{}c=AuthUtils,AuthUtils.isCordova=()=>!!(window.cordova||window.phonegap||window.PhoneGap),AuthUtils.isCapacitor=()=>{var e;return!(null==(e=window.Capacitor)||!e.isNativePlatform())},AuthUtils.isNativeMobile=()=>c.isCapacitor()||c.isCordova(),AuthUtils.decodeJwt=e=>{try{return e?a(e):e}catch(t){return console.warn("[@badisi/auth-js] Access token was not decoded as it is not a valid JWT."),e}},AuthUtils.isUrlMatching=(e,t)=>{if(void 0!==t){const n=new URL(e,"http://test"),s=new URL(t,"http://test");if(""!==s.pathname&&"/"!==s.pathname&&!n.pathname.includes(s.pathname))return!1;if("http://test"!==s.origin&&(n.protocol!==s.protocol||n.origin!==s.origin||!`${n.origin}${n.pathname}}`.includes(`${s.origin}${s.pathname}`)))return!1;let i=!0;return s.searchParams.forEach(((e,t)=>{n.searchParams.getAll(t).includes(e)||(i=!1)})),i}return!1},AuthUtils.getBaseUrl=()=>{var e;const t=document.baseURI||(null==(e=document.querySelector("base"))?void 0:e.href)||location.origin;return t.endsWith("/")?t:`${t}/`},AuthUtils.stringToURL=e=>{try{return new URL(e)}catch(t){const n=e.startsWith("/")?e.substring(1,e.length):e;return new URL(`${c.getBaseUrl()}${n}`)}};const l=document.createElement("template");l.innerHTML='\n \n \n \n \n \n';class AppElement extends HTMLElement{constructor(){var e;super(),this.demoAppMainEl=void 0,this.demoAppPlaygroundEl=void 0,this.demoAppDebugEl=void 0,this.authManagerSubs=[],this.listeners=[],this.attachShadow({mode:"open"}),null==(e=this.shadowRoot)||e.appendChild(document.importNode(l.content,!0))}connectedCallback(){this.demoAppMainEl=this.shadowRoot.querySelector("demo-app-main"),this.demoAppPlaygroundEl=this.shadowRoot.querySelector("demo-app-playground"),this.demoAppDebugEl=this.shadowRoot.querySelector("demo-app-debug"),this.listenForHeaderEvents(),this.listenForPlaygroundEvents(),this.listenForAuthChanges()}disconnectedCallback(){this.authManagerSubs.forEach((e=>e.unsubscribe())),this.listeners.forEach((e=>e()))}async callPrivateApi(e,t){if(window.authManager&&e){var n;const s=null!=(n=await window.authManager.getAccessToken())?n:"",i=new XMLHttpRequest;i.onreadystatechange=()=>{if(4===i.readyState){var e;let s;try{var t;s=JSON.parse(null!=(t=i.responseText)?t:"")}catch(n){s=`${i.status} ${i.statusText}`}null==(e=this.demoAppPlaygroundEl)||e.setApiStatus(s,200!==i.status)}},i.open("GET",e,!0),i.setRequestHeader("Authorization",`Bearer ${s}`),null==t||t.split(";").forEach((e=>{if(e){var t,n;const s=e.split(":");i.setRequestHeader(null==(t=s[0])?void 0:t.trim(),(null==(n=s[1])?void 0:n.trim())||"")}})),i.send()}}refreshInfo(e,t){if(window.authManager&&this.demoAppMainEl&&this.demoAppDebugEl)switch(e){case"renewing":this.demoAppMainEl.isRenewing=t;break;case"authenticated":this.demoAppMainEl.isAuthenticated=t,this.demoAppDebugEl.isAuthenticated=t;break;case"userSession":this.demoAppDebugEl.userSession=t;break;case"accessToken":this.demoAppDebugEl.accessToken=t,this.demoAppDebugEl.accessTokenDecoded=AuthUtils.decodeJwt(t);break;case"idToken":this.demoAppDebugEl.idToken=t,this.demoAppDebugEl.idTokenDecoded=AuthUtils.decodeJwt(t);break;case"userProfile":this.demoAppDebugEl.userProfile=t}}listenForAuthChanges(){const e=window.authManager;e&&this.authManagerSubs.push(e.onRenewingChanged((e=>this.refreshInfo("renewing",e))),e.onAuthenticatedChanged((e=>this.refreshInfo("authenticated",e))),e.onUserSessionChanged((e=>this.refreshInfo("userSession",e))),e.onAccessTokenChanged((e=>this.refreshInfo("accessToken",e))),e.onIdTokenChanged((e=>this.refreshInfo("idToken",e))),e.onUserProfileChanged((e=>this.refreshInfo("userProfile",e))))}listenForPlaygroundEvents(){if(this.demoAppPlaygroundEl){const e=e=>{var t,n;this.callPrivateApi(null==(t=e.detail)?void 0:t.url,null==(n=e.detail)?void 0:n.headers)};this.demoAppPlaygroundEl.addEventListener("api",e),this.listeners.push((()=>{var t;return null==(t=this.demoAppPlaygroundEl)?void 0:t.removeEventListener("api",e)}))}}listenForHeaderEvents(){const e=window.authManager;if(e&&this.demoAppMainEl){const t=()=>{e.login()};this.demoAppMainEl.addEventListener("login",t);const n=()=>{e.logout({redirectUrl:"/"}).then((()=>{var e;const t=document.baseURI||(null==(e=document.querySelector("base"))?void 0:e.href)||location.origin;location.href=t.endsWith("/")?t:`${t}/`}))};this.demoAppMainEl.addEventListener("logout",n);const s=()=>{e.renew()};this.demoAppMainEl.addEventListener("silentRenew",s),this.listeners.push((()=>{var e;return null==(e=this.demoAppMainEl)?void 0:e.removeEventListener("login",t)}),(()=>{var e;return null==(e=this.demoAppMainEl)?void 0:e.removeEventListener("logout",n)}),(()=>{var e;return null==(e=this.demoAppMainEl)?void 0:e.removeEventListener("silentRenew",s)}))}}}customElements.define("app-root",AppElement);function d(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var u=0;function h(e){return"__private_"+u+++"_"+e}const p=function(){this.__data__=[],this.size=0};const g=function(e,t){return e===t||e!=e&&t!=t};const _=function(e,t){for(var n=e.length;n--;)if(g(e[n][0],t))return n;return-1};var f=Array.prototype.splice;const m=function(e){var t=this.__data__,n=_(t,e);return!(n<0)&&(n==t.length-1?t.pop():f.call(t,n,1),--this.size,!0)};const w=function(e){var t=this.__data__,n=_(t,e);return n<0?void 0:t[n][1]};const v=function(e){return _(this.__data__,e)>-1};const b=function(e,t){var n=this.__data__,s=_(n,e);return s<0?(++this.size,n.push([e,t])):n[s][1]=t,this};function y(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t-1&&e%1==0&&e<=9007199254740991};const Ke=function(e){return null!=e&&Je(e.length)&&!H(e)};const Ve=function(e){return He(e)&&Ke(e)};var Ge=n(160),Qe=Function.prototype,Xe=Object.prototype,Ye=Qe.toString,Ze=Xe.hasOwnProperty,et=Ye.call(Object);const tt=function(e){if(!He(e)||"[object Object]"!=M(e))return!1;var t=Le(e);if(null===t)return!0;var n=Ze.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&Ye.call(n)==et};var nt={};nt["[object Float32Array]"]=nt["[object Float64Array]"]=nt["[object Int8Array]"]=nt["[object Int16Array]"]=nt["[object Int32Array]"]=nt["[object Uint8Array]"]=nt["[object Uint8ClampedArray]"]=nt["[object Uint16Array]"]=nt["[object Uint32Array]"]=!0,nt["[object Arguments]"]=nt["[object Array]"]=nt["[object ArrayBuffer]"]=nt["[object Boolean]"]=nt["[object DataView]"]=nt["[object Date]"]=nt["[object Error]"]=nt["[object Function]"]=nt["[object Map]"]=nt["[object Number]"]=nt["[object Object]"]=nt["[object RegExp]"]=nt["[object Set]"]=nt["[object String]"]=nt["[object WeakMap]"]=!1;const st=function(e){return He(e)&&Je(e.length)&&!!nt[M(e)]};const it=function(e){return function(t){return e(t)}};var rt=n(485),ot=rt.A&&rt.A.isTypedArray;const at=ot?it(ot):st;const ct=function(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]};var lt=Object.prototype.hasOwnProperty;const dt=function(e,t,n){var s=e[t];lt.call(e,t)&&g(s,n)&&(void 0!==n||t in e)||xe(e,t,n)};const ut=function(e,t,n,s){var i=!n;n||(n={});for(var r=-1,o=t.length;++r-1&&e%1==0&&e0){if(++t>=800)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}(At);const It=function(e,t){return Rt(Tt(e,t,Et),e+"")};const Ot=function(e,t,n){if(!q(n))return!1;var s=typeof t;return!!("number"==s?Ke(n)&>(t,n.length):"string"==s&&t in n)&&g(n[t],e)};const jt=function(e){return It((function(t,n){var s=-1,i=n.length,r=i>1?n[i-1]:void 0,o=i>2?n[2]:void 0;for(r=e.length>3&&"function"==typeof r?(i--,r):void 0,o&&Ot(n[0],n[1],o)&&(r=i<3?void 0:r,i=1),t=Object(t);++s{},info:()=>{},warn:()=>{},error:()=>{}},Kt=(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))(Kt||{});(Mt=Kt||(Kt={})).reset=function(){Lt=3,Nt=Jt},Mt.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");Lt=e},Mt.setLogger=function(e){Nt=e};var Vt=class{constructor(e){this._name=e}debug(...e){Lt>=4&&Nt.debug(Vt._format(this._name,this._method),...e)}info(...e){Lt>=3&&Nt.info(Vt._format(this._name,this._method),...e)}warn(...e){Lt>=2&&Nt.warn(Vt._format(this._name,this._method),...e)}error(...e){Lt>=1&&Nt.error(Vt._format(this._name,this._method),...e)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(e,t){const n=new Vt(`${e}.${t}`);return n.debug("begin"),n}static _format(e,t){const n=`[${e}]`;return t?`${n} ${t}:`:n}static debug(e,...t){Lt>=4&&Nt.debug(Vt._format(e),...t)}static info(e,...t){Lt>=3&&Nt.info(Vt._format(e),...t)}static warn(e,...t){Lt>=2&&Nt.warn(Vt._format(e),...t)}static error(e,...t){Lt>=1&&Nt.error(Vt._format(e),...t)}};Kt.reset();var Gt,Qt,Xt,Yt=class{static _randomWord(){return Ht().lib.WordArray.random(1).words[0]}static generateUUIDv4(){return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>(+e^Yt._randomWord()&15>>+e/4).toString(16))).replace(/-/g,"")}static generateCodeVerifier(){return Yt.generateUUIDv4()+Yt.generateUUIDv4()+Yt.generateUUIDv4()}static generateCodeChallenge(e){try{const t=$t()(e);return Bt().stringify(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(t){throw Vt.error("CryptoUtils.generateCodeChallenge",t),t}}static generateBasicAuth(e,t){const n=Ft().parse([e,t].join(":"));return Bt().stringify(n)}},Zt=class{constructor(e){this._name=e,this._logger=new Vt(`Event('${this._name}')`),this._callbacks=[]}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)}raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)t(...e)}},en=class{static decode(e){try{return a(e)}catch(t){throw Vt.error("JwtUtils.decode",t),t}}},tn=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(",")}},nn=class extends Zt{constructor(){super(...arguments),this._logger=new Vt(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const e=this._expiration-nn.getEpochTime();this._logger.debug("timer completes in",e),this._expiration<=nn.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(e){const t=this._logger.create("init");e=Math.max(Math.floor(e),1);const n=nn.getEpochTime()+e;if(this.expiration===n&&this._timerHandle)return void t.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),t.debug("using duration",e),this._expiration=n;const s=Math.min(e,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)}},sn=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const n=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(n.slice(1))}},rn=class extends Error{constructor(e,t){var n,s,i;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw Vt.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(n=e.error_description)?n:null,this.error_uri=null!=(s=e.error_uri)?s:null,this.state=e.userState,this.session_state=null!=(i=e.session_state)?i:null,this.url_state=e.url_state}},on=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},an=class{constructor(e){this._logger=new Vt("AccessTokenEvents"),this._expiringTimer=new nn("Access token expiring"),this._expiredTimer=new nn("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const n=e.expires_in;if(t.debug("access token present, remaining duration:",n),n>0){let e=n-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 s=n+1;t.debug("registering expired timer, raising in",s,"seconds"),this._expiredTimer.init(s)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}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)}},cn=class{constructor(e,t,n,s,i){this._callback=e,this._client_id=t,this._intervalInSeconds=s,this._stopOnError=i,this._logger=new Vt("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 r=new URL(n);this._frame_origin=r.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=r.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)}},ln=class{constructor(){this._logger=new Vt("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]}},dn=class{constructor(e=[],t=null,n={}){this._jwtHandler=t,this._extraHeaders=n,this._logger=new Vt("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:n,...s}=t;if(!n)return await fetch(e,s);const i=new AbortController,r=setTimeout((()=>i.abort()),1e3*n);try{return await fetch(e,{...t,signal:i.signal})}catch(o){if(o instanceof DOMException&&"AbortError"===o.name)throw new on("Network timed out");throw o}finally{clearTimeout(r)}}async getJson(e,{token:t,credentials:n}={}){const s=this._logger.create("getJson"),i={Accept:this._contentTypes.join(", ")};let r;t&&(s.debug("token passed, setting Authorization header"),i.Authorization="Bearer "+t),this.appendExtraHeaders(i);try{s.debug("url:",e),r=await this.fetchWithTimeout(e,{method:"GET",headers:i,credentials:n})}catch(c){throw s.error("Network Error"),c}s.debug("HTTP response received, status",r.status);const o=r.headers.get("Content-Type");if(o&&!this._contentTypes.find((e=>o.startsWith(e)))&&s.throw(new Error(`Invalid response Content-Type: ${null!=o?o:"undefined"}, from URL: ${e}`)),r.ok&&this._jwtHandler&&(null==o?void 0:o.startsWith("application/jwt")))return await this._jwtHandler(await r.text());let a;try{a=await r.json()}catch(c){if(s.error("Error parsing JSON response",c),r.ok)throw c;throw new Error(`${r.statusText} (${r.status})`)}if(!r.ok){if(s.error("Error from server:",a),a.error)throw new rn(a);throw new Error(`${r.statusText} (${r.status}): ${JSON.stringify(a)}`)}return a}async postForm(e,{body:t,basicAuth:n,timeoutInSeconds:s,initCredentials:i}){const r=this._logger.create("postForm"),o={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded"};let a;void 0!==n&&(o.Authorization="Basic "+n),this.appendExtraHeaders(o);try{r.debug("url:",e),a=await this.fetchWithTimeout(e,{method:"POST",headers:o,body:t,timeoutInSeconds:s,credentials:i})}catch(u){throw r.error("Network error"),u}r.debug("HTTP response received, status",a.status);const c=a.headers.get("Content-Type");if(c&&!this._contentTypes.find((e=>c.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=c?c:"undefined"}, from URL: ${e}`);const l=await a.text();let d={};if(l)try{d=JSON.parse(l)}catch(u){if(r.error("Error parsing JSON response",u),a.ok)throw u;throw new Error(`${a.statusText} (${a.status})`)}if(!a.ok){if(r.error("Error from server:",d),d.error)throw new rn(d,t);throw new Error(`${a.statusText} (${a.status}): ${JSON.stringify(d)}`)}return d}appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),n=Object.keys(this._extraHeaders),s=["authorization","accept","content-type"];0!==n.length&&n.forEach((n=>{if(s.includes(n.toLocaleLowerCase()))return void t.warn("Protected header could not be overridden",n,s);const i="function"==typeof this._extraHeaders[n]?this._extraHeaders[n]():this._extraHeaders[n];i&&""!==i&&(e[n]=i)}))}},un=class{constructor(e){this._settings=e,this._logger=new Vt("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new dn(["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});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},this._settings.metadataSeed,t),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 n=this._logger.create(`_getMetadataProperty('${e}')`),s=await this.getMetadata();if(n.debug("resolved"),void 0===s[e]){if(!0===t)return void n.warn("Metadata does not contain optional property");n.throw(new Error("Metadata does not contain property "+e))}return s[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 n=await this._jsonService.getJson(t);if(e.debug("got key set",n),!Array.isArray(n.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=n.keys,this._signingKeys}},hn=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new Vt("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 n=0;n{const t=this._logger.create("_getClaimsFromJwt");try{const n=en.decode(e);return t.debug("JWT decoding successful"),n}catch(n){throw t.error("Error parsing JWT response"),n}},this._jsonService=new dn(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 n=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",n);const s=await this._jsonService.getJson(n,{token:e,credentials:this._settings.fetchRequestCredentials});return t.debug("got claims",s),s}},_n=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new Vt("TokenClient"),this._jsonService=new dn(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:n=this._settings.client_id,client_secret:s=this._settings.client_secret,...i}){const r=this._logger.create("exchangeCode");n||r.throw(new Error("A client_id is required")),t||r.throw(new Error("A redirect_uri is required")),i.code||r.throw(new Error("A code is required"));const o=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[d,u]of Object.entries(i))null!=u&&o.set(d,u);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!s)throw r.throw(new Error("A client_secret is required")),null;a=Yt.generateBasicAuth(n,s);break;case"client_secret_post":o.append("client_id",n),s&&o.append("client_secret",s)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,scope:s=this._settings.scope,...i}){const r=this._logger.create("exchangeCredentials");t||r.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e,scope:s});for(const[d,u]of Object.entries(i))null!=u&&o.set(d,u);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!n)throw r.throw(new Error("A client_secret is required")),null;a=Yt.generateBasicAuth(t,n);break;case"client_secret_post":o.append("client_id",t),n&&o.append("client_secret",n)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:n=this._settings.client_secret,timeoutInSeconds:s,...i}){const r=this._logger.create("exchangeRefreshToken");t||r.throw(new Error("A client_id is required")),i.refresh_token||r.throw(new Error("A refresh_token is required"));const o=new URLSearchParams({grant_type:e});for(const[d,u]of Object.entries(i))Array.isArray(u)?u.forEach((e=>o.append(d,e))):null!=u&&o.set(d,u);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(!n)throw r.throw(new Error("A client_secret is required")),null;a=Yt.generateBasicAuth(t,n);break;case"client_secret_post":o.append("client_id",t),n&&o.append("client_secret",n)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const l=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:s,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),l}async revoke(e){var t;const n=this._logger.create("revoke");e.token||n.throw(new Error("A token is required"));const s=await this._metadataService.getRevocationEndpoint(!1);n.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const i=new URLSearchParams;for(const[r,o]of Object.entries(e))null!=o&&i.set(r,o);i.set("client_id",this._settings.client_id),this._settings.client_secret&&i.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(s,{body:i}),n.debug("got response")}},fn=class{constructor(e,t,n){this._settings=e,this._metadataService=t,this._claimsService=n,this._logger=new Vt("ResponseValidator"),this._userInfoService=new gn(this._settings,this._metadataService),this._tokenClient=new _n(this._settings,this._metadataService)}async validateSigninResponse(e,t){const n=this._logger.create("validateSigninResponse");this._processSigninState(e,t),n.debug("state processed"),await this._processCode(e,t),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 n=this._logger.create("validateCredentialsResponse");e.isOpenId&&e.id_token&&this._validateIdTokenAttributes(e),n.debug("tokens validated"),await this._processClaims(e,t,e.isOpenId),n.debug("claims processed")}async validateRefreshResponse(e,t){const n=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),n.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const s=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,s),n.debug("claims processed")}validateSignoutResponse(e,t){const n=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&n.throw(new Error("State does not match")),n.debug("state validated"),e.userState=t.data,e.error)throw n.warn("Response was error",e.error),new rn(e)}_processSigninState(e,t){const n=this._logger.create("_processSigninState");if(t.id!==e.state&&n.throw(new Error("State does not match")),t.client_id||n.throw(new Error("No client_id on state")),t.authority||n.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&n.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&n.throw(new Error("client_id mismatch on settings vs. signin state")),n.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw n.warn("Response was error",e.error),new rn(e);t.code_verifier&&!e.code&&n.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,n=!0){const s=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void s.debug("not loading user info");s.debug("loading user info");const i=await this._userInfoService.getClaims(e.access_token);s.debug("user info claims received from user info endpoint"),n&&i.sub!==e.profile.sub&&s.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(i)),s.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t){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,...t.extraTokenParams});Object.assign(e,s)}else n.debug("No code to process")}_validateIdTokenAttributes(e,t){var n;const s=this._logger.create("_validateIdTokenAttributes");s.debug("decoding ID Token JWT");const i=en.decode(null!=(n=e.id_token)?n:"");if(i.sub||s.throw(new Error("ID Token is missing a subject claim")),t){const e=en.decode(t);i.sub!==e.sub&&s.throw(new Error("sub in id_token does not match current sub")),i.auth_time&&i.auth_time!==e.auth_time&&s.throw(new Error("auth_time in id_token does not match original auth_time")),i.azp&&i.azp!==e.azp&&s.throw(new Error("azp in id_token does not match original azp")),!i.azp&&e.azp&&s.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=i}},mn=class{constructor(e){this.id=e.id||Yt.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=nn.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new Vt("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(e){return Vt.createStatic("State","fromStorageString"),new mn(JSON.parse(e))}static async clearStaleState(e,t){const n=Vt.createStatic("State","clearStaleState"),s=nn.getEpochTime()-t,i=await e.getAllKeys();n.debug("got keys",i);for(let o=0;ow.searchParams.append("resource",e)))}for(const[b,y]of Object.entries({response_mode:a,...m,...g}))null!=y&&w.searchParams.append(b,y.toString());this.url=w.href}},bn=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(";");this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(";"))}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-nn.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+nn.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},yn=class{constructor({url:e,state_data:t,id_token_hint:n,post_logout_redirect_uri:s,extraQueryParams:i,request_type:r,client_id:o}){if(this._logger=new Vt("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const a=new URL(e);n&&a.searchParams.append("id_token_hint",n),o&&a.searchParams.append("client_id",o),s&&(a.searchParams.append("post_logout_redirect_uri",s),t&&(this.state=new mn({data:t,request_type:r}),a.searchParams.append("state",this.state.id)));for(const[c,l]of Object.entries({...i}))null!=l&&a.searchParams.append(c,l.toString());this.url=a.href}},Sn=class{constructor(e){this.state=e.get("state"),this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},kn=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],En=["sub","iss","aud","exp","iat"],xn=class{constructor(e){this._settings=e,this._logger=new Vt("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:kn;for(const n of e)En.includes(n)||delete t[n]}return t}mergeClaims(e,t){const n={...e};for(const[s,i]of Object.entries(t))for(const e of Array.isArray(i)?i:[i]){const t=n[s];void 0===t?n[s]=e:Array.isArray(t)?t.includes(e)||t.push(e):n[s]!==e&&("object"==typeof e&&this._settings.mergeClaims?n[s]=this.mergeClaims(t,e):n[s]=[t,e])}return n}},Cn=class{constructor(e,t){this._logger=new Vt("OidcClient"),this.settings=e instanceof pn?e:new pn(e),this.metadataService=null!=t?t:new un(this.settings),this._claimsService=new xn(this.settings),this._validator=new fn(this.settings,this.metadataService,this._claimsService),this._tokenClient=new _n(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:n,request_type:s,id_token_hint:i,login_hint:r,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:_=this.settings.ui_locales,acr_values:f=this.settings.acr_values,resource:m=this.settings.resource,response_mode:w=this.settings.response_mode,extraQueryParams:v=this.settings.extraQueryParams,extraTokenParams:b=this.settings.extraTokenParams}){const y=this._logger.create("createSigninRequest");if("code"!==l)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const S=await this.metadataService.getAuthorizationEndpoint();y.debug("Received authorization endpoint",S);const k=new vn({url:S,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:_,id_token_hint:i,login_hint:r,acr_values:f,resource:m,request:t,request_uri:n,extraQueryParams:v,extraTokenParams:b,request_type:s,response_mode:w,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE});await this.clearStaleState();const E=k.state;return await this.settings.stateStore.set(E.id,E.toStorageString()),k}async readSigninResponseState(e,t=!1){const n=this._logger.create("readSigninResponseState"),s=new bn(sn.readParams(e,this.settings.response_mode));if(!s.state)throw n.throw(new Error("No state in response")),null;const i=await this.settings.stateStore[t?"remove":"get"](s.state);if(!i)throw n.throw(new Error("No matching state found in storage")),null;return{state:wn.fromStorageString(i),response:s}}async processSigninResponse(e){const t=this._logger.create("processSigninResponse"),{state:n,response:s}=await this.readSigninResponseState(e,!0);return t.debug("received state from storage; validating response"),await this._validator.validateSigninResponse(s,n),s}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n=!1,extraTokenParams:s={}}){const i=await this._tokenClient.exchangeCredentials({username:e,password:t,...s}),r=new bn(new URLSearchParams);return Object.assign(r,i),await this._validator.validateCredentialsResponse(r,n),r}async useRefreshToken({state:e,timeoutInSeconds:t}){var n;const s=this._logger.create("useRefreshToken");let i;if(void 0===this.settings.refreshTokenAllowedScope)i=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");i=((null==(n=e.scope)?void 0:n.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}const r=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,resource:e.resource,scope:i,timeoutInSeconds:t}),o=new bn(new URLSearchParams);return Object.assign(o,r),s.debug("validating response",o),await this._validator.validateRefreshResponse(o,{...e,scope:i}),o}async createSignoutRequest({state:e,id_token_hint:t,client_id:n,request_type:s,post_logout_redirect_uri:i=this.settings.post_logout_redirect_uri,extraQueryParams:r=this.settings.extraQueryParams}={}){const o=this._logger.create("createSignoutRequest"),a=await this.metadataService.getEndSessionEndpoint();if(!a)throw o.throw(new Error("No end session endpoint")),null;o.debug("Received end session endpoint",a),n||!i||t||(n=this.settings.client_id);const c=new yn({url:a,id_token_hint:t,client_id:n,post_logout_redirect_uri:i,state_data:e,extraQueryParams:r,request_type:s});await this.clearStaleState();const l=c.state;return l&&(o.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),c}async readSignoutResponseState(e,t=!1){const n=this._logger.create("readSignoutResponseState"),s=new Sn(sn.readParams(e,this.settings.response_mode));if(!s.state){if(n.debug("No state in response"),s.error)throw n.warn("Response was error:",s.error),new rn(s);return{state:void 0,response:s}}const i=await this.settings.stateStore[t?"remove":"get"](s.state);if(!i)throw n.throw(new Error("No matching state found in storage")),null;return{state:mn.fromStorageString(i),response:s}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:n,response:s}=await this.readSignoutResponseState(e,!0);return n?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(s,n)):t.debug("No state from storage; skipping response validation"),s}clearStaleState(){return this._logger.create("clearStaleState"),mn.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})}},Tn=class{constructor(e){this._userManager=e,this._logger=new Vt("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const n=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,this._sid=e.profile.sid,n.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,this._sid=void 0,n.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){n.debug("initializing check session iframe");const s=this._userManager.settings.client_id,i=this._userManager.settings.checkSessionIntervalInSeconds,r=this._userManager.settings.stopCheckSessionOnError,o=new cn(this._callback,s,e,i,r);await o.load(),this._checkSessionIFrame=o,o.start(t)}else n.warn("no check session iframe found in the metadata")}catch(s){n.error("Error from getCheckSessionIframe:",s instanceof Error?s.message:s)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._sid=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&&e.sid?{sub:e.sub,sid:e.sid}:null};this._start(t)}}catch(n){e.error("error from querySessionStatus",n instanceof Error?n.message:n)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let n=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(n=!1,this._checkSessionIFrame.start(t.session_state),t.sid===this._sid?e.debug("same sub still logged in at OP, restarting check session iframe; session_state",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),this._userManager.events._raiseUserSessionChanged())):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),n?this._sub?this._userManager.events._raiseUserSignedOut():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),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&&e.sid?{sub:e.sub,sid:e.sid}:null};this._start(t)}}}},Un=class{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-nn.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+nn.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 Vt("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(e){return Vt.createStatic("User","fromStorageString"),new Un(JSON.parse(e))}},An="oidc-client",Pn=class{constructor(){this._abort=new Zt("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:n,keepOpen:s}=await new Promise(((n,s)=>{const i=i=>{var r;const o=i.data,a=null!=(r=e.scriptOrigin)?r:window.location.origin;if(i.origin===a&&(null==o?void 0:o.source)===An){try{const n=sn.readParams(o.url,e.response_mode).get("state");if(n||t.warn("no state found in response url"),i.source!==this._window&&n!==e.state)return}catch(c){this._dispose(),s(new Error("Invalid response from window"))}n(o)}};window.addEventListener("message",i,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",i,!1))),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),s(e)})))}));return t.debug("got response from window"),this._dispose(),s||this.close(),{url:n}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,n=!1,s=window.location.origin){e.postMessage({source:An,url:t,keepOpen:n},s)}},Rn={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},In="_blank",On=60,jn=2,Ln=10,Nn=class extends pn{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:n=e.post_logout_redirect_uri,popupWindowFeatures:s=Rn,popupWindowTarget:i=In,redirectMethod:r="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,silent_redirect_uri:l=e.redirect_uri,silentRequestTimeoutInSeconds:d=Ln,automaticSilentRenew:u=!0,validateSubOnSilentRenew:h=!0,includeIdTokenInSilentRenew:p=!1,monitorSession:g=!1,monitorAnonymousSession:_=!1,checkSessionIntervalInSeconds:f=jn,query_status_response_type:m="code",stopCheckSessionOnError:w=!0,revokeTokenTypes:v=["access_token","refresh_token"],revokeTokensOnSignout:b=!1,includeIdTokenInSilentSignout:y=!1,accessTokenExpiringNotificationTimeInSeconds:S=On,userStore:k}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=n,this.popupWindowFeatures=s,this.popupWindowTarget=i,this.redirectMethod=r,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=l,this.silentRequestTimeoutInSeconds=d,this.automaticSilentRenew=u,this.validateSubOnSilentRenew=h,this.includeIdTokenInSilentRenew=p,this.monitorSession=g,this.monitorAnonymousSession=_,this.checkSessionIntervalInSeconds=f,this.stopCheckSessionOnError=w,this.query_status_response_type=m,this.revokeTokenTypes=v,this.revokeTokensOnSignout=b,this.includeIdTokenInSilentSignout=y,this.accessTokenExpiringNotificationTimeInSeconds=S,k)this.userStore=k;else{const e="undefined"!=typeof window?window.sessionStorage:new ln;this.userStore=new hn({store:e})}}},Mn=class extends Pn{constructor({silentRequestTimeoutInSeconds:e=Ln}){super(),this._logger=new Vt("IFrameWindow"),this._timeoutInSeconds=e,this._frame=Mn.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 on("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 n=e.target;null==(t=n.parentNode)||t.removeChild(n),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)}},qn=class{constructor(e){this._settings=e,this._logger=new Vt("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new Mn({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),Mn.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},Hn=class extends Pn{constructor({popupWindowTarget:e=In,popupWindowFeatures:t={}}){super(),this._logger=new Vt("PopupWindow");const n=tn.center({...Rn,...t});this._window=window.open(void 0,e,tn.serialize(n)),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 n=setInterval((()=>{this._window&&!this._window.closed||this._abort.raise(new Error("Popup closed by user"))}),500);return this._disposeHandlers.add((()=>clearInterval(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){if(!window.opener)throw new Error("No window.opener. Can't complete notification.");return super._notifyParent(window.opener,e,t)}},Wn=class{constructor(e){this._settings=e,this._logger=new Vt("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget}){return new Hn({popupWindowFeatures:e,popupWindowTarget:t})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),Hn.notifyOpener(e,t)}},$n=class{constructor(e){this._settings=e,this._logger=new Vt("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var n;this._logger.create("prepare");let s=window.self;"top"===t&&(s=null!=(n=window.top)?n:window.self);const i=s.location[e].bind(s.location);let r;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{r=t}));return i(e.url),await t},close:()=>{this._logger.create("close"),null==r||r(new Error("Redirect aborted")),s.stop()}}}async callback(){}},Dn=class extends an{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new Vt("UserManagerEvents"),this._userLoaded=new Zt("User loaded"),this._userUnloaded=new Zt("User unloaded"),this._silentRenewError=new Zt("Silent renew error"),this._userSignedIn=new Zt("User signed in"),this._userSignedOut=new Zt("User signed out"),this._userSessionChanged=new Zt("User session changed")}load(e,t=!0){super.load(e),t&&this._userLoaded.raise(e)}unload(){super.unload(),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)}_raiseSilentRenewError(e){this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}_raiseUserSignedIn(){this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}_raiseUserSignedOut(){this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}_raiseUserSessionChanged(){this._userSessionChanged.raise()}},Bn=class{constructor(e){this._userManager=e,this._logger=new Vt("SilentRenewService"),this._isStarted=!1,this._retryTimer=new nn("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 on)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),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)}},zn=class{constructor(e,t){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.resource=t,this.data=e.state}},Fn=class{constructor(e,t,n,s){this._logger=new Vt("UserManager"),this.settings=new Nn(e),this._client=new Cn(e),this._redirectNavigator=null!=t?t:new $n(this.settings),this._popupNavigator=null!=n?n:new Wn(this.settings),this._iframeNavigator=null!=s?s:new qn(this.settings),this._events=new Dn(this.settings),this._silentRenewService=new Bn(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new Tn(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(){const e=this._logger.create("getUser"),t=await this._loadUser();return t?(e.info("user loaded"),this._events.load(t,!1),t):(e.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"),this._events.unload()}async signinRedirect(e={}){this._logger.create("signinRedirect");const{redirectMethod:t,...n}=e,s=await this._redirectNavigator.prepare({redirectMethod:t});await this._signinStart({request_type:"si:r",...n},s)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),n=await this._signinEnd(e);return n.profile&&n.profile.sub?t.info("success, signed in subject",n.profile.sub):t.info("no subject"),n}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:n=!1}){const s=this._logger.create("signinResourceOwnerCredential"),i=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:n,extraTokenParams:this.settings.extraTokenParams});s.debug("got signin response");const r=await this._buildUser(i);return r.profile&&r.profile.sub?s.info("success, signed in subject",r.profile.sub):s.info("no subject"),r}async signinPopup(e={}){const t=this._logger.create("signinPopup"),{popupWindowFeatures:n,popupWindowTarget:s,...i}=e,r=this.settings.popup_redirect_uri;r||t.throw(new Error("No popup_redirect_uri configured"));const o=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:s}),a=await this._signin({request_type:"si:p",redirect_uri:r,display:"popup",...i},o);return a&&(a.profile&&a.profile.sub?t.info("success, signed in subject",a.profile.sub):t.info("no subject")),a}async signinPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async signinSilent(e={}){var t;const n=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:s,resource:i,...r}=e;let o=await this._loadUser();if(null==o?void 0:o.refresh_token){n.debug("using refresh token");const e=new zn(o,i);return await this._useRefreshToken(e)}const a=this.settings.silent_redirect_uri;let c;a||n.throw(new Error("No silent_redirect_uri configured")),o&&this.settings.validateSubOnSilentRenew&&(n.debug("subject prior to silent renew:",o.profile.sub),c=o.profile.sub);const l=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s});return o=await this._signin({request_type:"si:s",redirect_uri:a,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==o?void 0:o.id_token:void 0,...r},l,c),o&&((null==(t=o.profile)?void 0:t.sub)?n.info("success, signed in subject",o.profile.sub):n.info("no subject")),o}async _useRefreshToken(e){const t=await this._client.useRefreshToken({state:e,timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds}),n=new Un({...e,...t});return await this.storeUser(n),this._events.load(n),n}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":return await this.signinPopupCallback(e);case"si:s":return await this.signinSilentCallback(e);default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:n}=await this._client.readSignoutResponseState(e);if(n)switch(n.request_type){case"so:r":await this.signoutRedirectCallback(e);break;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:n,...s}=e,i=this.settings.silent_redirect_uri;i||t.throw(new Error("No silent_redirect_uri configured"));const r=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n}),a=await this._signinStart({request_type:"si:s",redirect_uri:i,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==r?void 0:r.id_token:void 0,response_type:this.settings.query_status_response_type,scope:"openid",skipUserInfo:!0,...s},o);try{const e=await this._client.processSigninResponse(a.url);return t.debug("got signin response"),e.session_state&&e.profile.sub?(t.info("success for subject",e.profile.sub),{session_state:e.session_state,sub:e.profile.sub,sid:e.profile.sid}):(t.info("success, user not authenticated"),null)}catch(c){if(this.settings.monitorAnonymousSession&&c instanceof rn)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,n){const s=await this._signinStart(e,t);return await this._signinEnd(s.url,n)}async _signinStart(e,t){const n=this._logger.create("_signinStart");try{const s=await this._client.createSigninRequest(e);return n.debug("got signin request"),await t.navigate({url:s.url,state:s.state.id,response_mode:s.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(s){throw n.debug("error after preparing navigator, closing navigator window"),t.close(),s}}async _signinEnd(e,t){const n=this._logger.create("_signinEnd"),s=await this._client.processSigninResponse(e);n.debug("got signin response");return await this._buildUser(s,t)}async _buildUser(e,t){const n=this._logger.create("_buildUser"),s=new Un(e);if(t){if(t!==s.profile.sub)throw n.debug("current user does not match user returned from signin. sub from signin:",s.profile.sub),new rn({...e,error:"login_required"});n.debug("current user matches user returned from signin")}return await this.storeUser(s),n.debug("user stored"),this._events.load(s),s}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:n,...s}=e,i=await this._redirectNavigator.prepare({redirectMethod:n});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...s},i),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),n=await this._signoutEnd(e);return t.info("success"),n}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:n,popupWindowTarget:s,...i}=e,r=this.settings.popup_post_logout_redirect_uri,o=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:s});await this._signout({request_type:"so:p",post_logout_redirect_uri:r,state:null==r?void 0:{},...i},o),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const n=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),n.info("success")}async _signout(e,t){const n=await this._signoutStart(e,t);return await this._signoutEnd(n.url)}async _signoutStart(e={},t){var n;const s=this._logger.create("_signoutStart");try{const i=await this._loadUser();s.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(i);const r=e.id_token_hint||i&&i.id_token;r&&(s.debug("setting id_token_hint in signout request"),e.id_token_hint=r),await this.removeUser(),s.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return s.debug("got signout request"),await t.navigate({url:o.url,state:null==(n=o.state)?void 0:n.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(i){throw s.debug("error after preparing navigator, closing navigator window"),t.close(),i}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),n=await this._client.processSignoutResponse(e);return t.debug("got signout response"),n}async signoutSilent(e={}){var t;const n=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:s,...i}=e,r=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:s});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:r,...i},a),n.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 n=this._logger.create("_revokeInternal");if(!e)return;const s=t.filter((t=>"string"==typeof e[t]));if(s.length){for(const t of s)await this._client.revokeToken(e[t],t),n.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),n.debug("user stored"),this._events.load(e)}else n.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"),Un.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const n=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,n)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey)}async clearStaleState(){await this._client.clearStaleState()}};class AuthManager{}class AuthSubscriptions{constructor(){this.subscribers=[],this.lastNotifiedValue=void 0}add(e){return this.subscribers.push(e),this.lastNotifiedValue&&e(...this.lastNotifiedValue),{unsubscribe:()=>this.unsubscribe(e)}}notify(...e){this.lastNotifiedValue=e,this.subscribers.forEach((t=>{t(...e)}))}unsubscribe(e){if(e){const t=this.subscribers.indexOf(e);-1!==t&&this.subscribers.splice(t,1)}else this.subscribers=[]}}const Jn=window.localStorage,Kn=null==(Gt=window.Capacitor)||null==(Gt=Gt.Plugins)?void 0:Gt.Storage,Vn=null==(Qt=window.Capacitor)||null==(Qt=Qt.Plugins)?void 0:Qt.Preferences,Gn=null==(Xt=window.Capacitor)||null==(Xt=Xt.Plugins)?void 0:Xt.SecureStoragePlugin;class MobileStorage{constructor(){if(this._logger=new Vt("MobileStorage"),!Gn){let e="[@badisi/auth-js] This application is currently using an unsafe storage.\n\n";e+="\u24d8 Please follow the recommended guide and use `capacitor-secure-storage-plugin` instead.",console.warn(e)}Gn?this._logger.debug("Using `capacitor-secure-storage-plugin` implementation"):Vn?this._logger.debug("Using `@capacitor/preferences` implementation"):Kn?this._logger.debug("Using `@capacitor/storage` implementation"):this._logger.debug("Using `localStorage` implementation")}get length(){return async function(){return Gn?(await Gn.keys()).value.length:Vn?(await Vn.keys()).keys.length:Kn?(await Kn.keys()).keys.length:Jn.length}()}async key(e){return Gn?(await Gn.keys()).value[e]:Vn?(await Vn.keys()).keys[e]:Kn?(await Kn.keys()).keys[e]:Jn.key(e)}async clear(){this._logger.create("clear"),Gn?await Gn.clear():Vn?await Vn.clear():Kn?await Kn.clear():Jn.clear()}async getItem(e){if(this._logger.create(`getItem('${e}')`),!Gn)return Vn?(await Vn.get({key:e})).value:Kn?(await Kn.get({key:e})).value:Jn.getItem(e);try{return(await Gn.get({key:e})).value}catch(t){return null}}async setItem(e,t){this._logger.create(`setItem('${e}')`),Gn?await Gn.set({key:e,value:t}):Vn?await Vn.set({key:e,value:t}):Kn?await Kn.set({key:e,value:t}):Jn.setItem(e,t)}async removeItem(e){if(this._logger.create(`removeItem('${e}')`),Gn)try{await Gn.remove({key:e})}catch(t){}else Vn?await Vn.remove({key:e}):Kn?await Kn.remove({key:e}):Jn.removeItem(e)}}let Qn=function(e){return e.REDIRECT="REDIRECT",e.POPUP="POPUP",e}({});class UserSession{constructor(){this.expired=void 0,this.expires_in=void 0,this.expires_at=void 0}static deserialize(e){const t=new UserSession,n=Object.keys(t);for(const s of n)t[s]=e[s];return t}}function Xn(e,t){if(null==e)return{};var n={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(t.includes(s))continue;n[s]=e[s]}return n}var Yn,Zn;const es=null==(Yn=window.Capacitor)||null==(Yn=Yn.Plugins)?void 0:Yn.App,ts=null==(Zn=window.Capacitor)||null==(Zn=Zn.Plugins)?void 0:Zn.Browser;class MobileWindow{constructor(e,t){if(this.redirectUrl=e,this.params=t,this._logger=new Vt("MobileWindow"),this.capacitorAppUrlOpenHandle=void 0,this.capacitorBrowserFinishedHandle=void 0,this.originalHandleOpenURL=window.handleOpenURL,this.timer=void 0,this.navigateLogger=void 0,this._resolve=void 0,this._reject=void 0,this._isClosed=!0,this._receivedResult=!1,!AuthUtils.isCapacitor()&&!AuthUtils.isCordova()){let e="[@badisi/auth-js] Required core dependency not found.\n\n";e+="\u24d8 Please follow the recommended guide and install either `Capacitor` or `Cordova` dependency.",console.error(e)}if(!ts){let e="[@badisi/auth-js] Required plugin not found.\n\n";e+="\u24d8 Please follow the recommended guide and install either `@badisi/capacitor-browsertab` or `@capacitor/browser` plugin.",console.error(e)}ts&&this._logger.debug("Using `@capacitor/browser` implementation")}async navigate(e){return this.navigateLogger=this._logger.create("navigate"),this.navigateLogger.debug("url",e.url),this._isClosed=!1,this._receivedResult=!1,new Promise(((t,n)=>{this._resolve=t,this._reject=n,this.installCustomUrlSchemeHandler().then((()=>{ts&&this.useCapacitorBrowser(e)}))}))}async close(){const e=this._logger.create("close");this._isClosed||await(null==ts?void 0:ts.close().catch((t=>e.error(t)))),e.debug("success")}async cleanup(){var e,t;const n=this._logger.create("cleanup");window.handleOpenURL=this.originalHandleOpenURL,await(null==(e=this.capacitorBrowserFinishedHandle)?void 0:e.remove()),await(null==(t=this.capacitorAppUrlOpenHandle)?void 0:t.remove()),clearTimeout(this.timer),n.debug("success")}async onError(e){var t,n;null==(t=this.navigateLogger)||t.error("error response:",e),await this.close(),await this.cleanup(),null==(n=this._reject)||n.call(this,new Error(e)),this._receivedResult=!0}async onSuccess(e){var t,n;null==(t=this.navigateLogger)||t.debug("successful response:",e),await this.close(),await this.cleanup(),null==(n=this._resolve)||n.call(this,{url:e}),this._receivedResult=!0}async useCapacitorBrowser(e){this.capacitorBrowserFinishedHandle=await(null==ts?void 0:ts.addListener("browserFinished",(()=>{this._isClosed=!0,setTimeout((()=>{var e;this._receivedResult||(this.cleanup(),null==(e=this._reject)||e.call(this,"Capacitor browser closed by user"))}),1e3)}))),await(null==ts?void 0:ts.open({url:e.url,toolbarColor:this.params.mobileWindowToolbarColor,presentationStyle:this.params.mobileWindowPresentationStyle,width:this.params.mobileWindowWidth,height:this.params.mobileWindowWidth}))}async useBrowserTab(e){}async installCustomUrlSchemeHandler(){const e=this._logger.create("installCustomUrlSchemeHandler");this.timer=setTimeout((()=>{this.onError("Installing custom url scheme handler, timed out without a response")}),1e4),await this.cleanup(),AuthUtils.isCapacitor()?(e.debug("listening to Capacitor `appUrlOpen` event"),this.capacitorAppUrlOpenHandle=await(null==es||null==es.addListener?void 0:es.addListener("appUrlOpen",(({url:e})=>{AuthUtils.isUrlMatching(e,this.redirectUrl)&&this.onSuccess(e)})))):AuthUtils.isCordova()&&(e.debug("waiting for Cordova `handleOpenURL` callback"),window.handleOpenURL=e=>{var t;null==(t=this.originalHandleOpenURL)||t.call(this,e),AuthUtils.isUrlMatching(e,this.redirectUrl)&&this.onSuccess(e)}),e.debug("success")}}class MobileNavigator{constructor(){this._logger=new Vt("MobileNavigator")}prepare(e,t){return this._logger.create("prepare"),new MobileWindow(e,t)}}const ns=["mobileWindowToolbarColor","mobileWindowPresentationStyle","mobileWindowWidth","mobileWindowHeight"],ss=["mobileWindowToolbarColor","mobileWindowPresentationStyle","mobileWindowWidth","mobileWindowHeight"];var is=h("mobileNavigator");class OidcUserManager extends Fn{constructor(e){super(Object.assign({authority:e.authorityUrl,client_id:e.clientId,scope:e.scope,loadUserInfo:e.loadUserInfo,automaticSilentRenew:e.automaticSilentRenew},e.internal)),this.libSettings=e,Object.defineProperty(this,is,{writable:!0,value:void 0}),d(this,is)[is]=new MobileNavigator}async signoutMobile(e={}){var t,n,s,i;const r=this._logger.create("signout"),{mobileWindowToolbarColor:o,mobileWindowPresentationStyle:a,mobileWindowWidth:c,mobileWindowHeight:l}=e,u=Xn(e,ns),h={mobileWindowToolbarColor:null!=o?o:null==(t=this.libSettings.internal)?void 0:t.mobileWindowToolbarColor,mobileWindowPresentationStyle:null!=a?a:null==(n=this.libSettings.internal)?void 0:n.mobileWindowPresentationStyle,mobileWindowWidth:null!=c?c:null==(s=this.libSettings.internal)?void 0:s.mobileWindowWidth,mobileWindowHeight:null!=l?l:null==(i=this.libSettings.internal)?void 0:i.mobileWindowHeight},p=d(this,is)[is].prepare(this.settings.post_logout_redirect_uri,h);await this._signout(Object.assign({request_type:"so:m",post_logout_redirect_uri:this.settings.post_logout_redirect_uri},u),p),r.info("success")}async signinMobile(e={}){var t,n,s,i,r;const o=this._logger.create("signin"),{mobileWindowToolbarColor:a,mobileWindowPresentationStyle:c,mobileWindowWidth:l,mobileWindowHeight:u}=e,h=Xn(e,ss),p={mobileWindowToolbarColor:null!=a?a:null==(t=this.libSettings.internal)?void 0:t.mobileWindowToolbarColor,mobileWindowPresentationStyle:null!=c?c:null==(n=this.libSettings.internal)?void 0:n.mobileWindowPresentationStyle,mobileWindowWidth:null!=l?l:null==(s=this.libSettings.internal)?void 0:s.mobileWindowWidth,mobileWindowHeight:null!=u?u:null==(i=this.libSettings.internal)?void 0:i.mobileWindowHeight},g=d(this,is)[is].prepare(this.settings.redirect_uri,p),_=await this._signin(Object.assign({request_type:"si:m",redirect_uri:this.settings.redirect_uri},h),g);null!=_&&null!=(r=_.profile)&&r.sub?o.info("success, signed in subject",_.profile.sub):o.info("no subject")}}const rs="auth-js:oidc_manager:redirect_url",os={loginRequired:!1,retrieveUserSession:!0,loadUserInfo:!1,automaticSilentRenew:!0,desktopNavigationType:Qn.REDIRECT,scope:"openid profile email phone",logLevel:Kt.NONE,internal:{response_type:"code",redirect_uri:"?oidc-callback=login",post_logout_redirect_uri:"?oidc-callback=logout",popup_redirect_uri:"oidc/callback/popup_redirect.html",popup_post_logout_redirect_uri:"oidc/callback/popup_redirect.html",silent_redirect_uri:"oidc/callback/silent_redirect.html",mobileWindowPresentationStyle:"popover"}};var as=h("idTokenSubs"),cs=h("accessTokenSubs"),ls=h("userProfileSubs"),ds=h("userSessionSubs"),us=h("authenticatedSubs"),hs=h("renewingSubs"),ps=h("redirectSubs"),gs=h("userManagerSubs"),_s=h("idToken"),fs=h("accessToken"),ms=h("userProfile"),ws=h("userSession"),vs=h("isAuthenticated"),bs=h("isRenewing"),ys=h("userManager"),Ss=h("settings"),ks=h("user"),Es=h("assertNotInInceptionLoop"),xs=h("waitForRenew"),Cs=h("postLogoutVerification"),Ts=h("notifyRenew"),Us=h("runSyncOrAsync"),As=h("redirect"),Ps=h("removeUser"),Rs=h("signinSilent"),Is=h("callSignin"),Os=h("callSignout");class OIDCAuthManager extends AuthManager{constructor(...e){super(...e),Object.defineProperty(this,Os,{value:Bs}),Object.defineProperty(this,Is,{value:Ds}),Object.defineProperty(this,Rs,{value:$s}),Object.defineProperty(this,Ps,{value:Ws}),Object.defineProperty(this,As,{value:Hs}),Object.defineProperty(this,Us,{value:qs}),Object.defineProperty(this,Ts,{value:Ms}),Object.defineProperty(this,Cs,{value:Ns}),Object.defineProperty(this,xs,{value:Ls}),Object.defineProperty(this,Es,{value:js}),Object.defineProperty(this,as,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,cs,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,ls,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,ds,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,us,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,hs,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,ps,{writable:!0,value:new AuthSubscriptions}),Object.defineProperty(this,gs,{writable:!0,value:[]}),Object.defineProperty(this,_s,{writable:!0,value:void 0}),Object.defineProperty(this,fs,{writable:!0,value:void 0}),Object.defineProperty(this,ms,{writable:!0,value:void 0}),Object.defineProperty(this,ws,{writable:!0,value:void 0}),Object.defineProperty(this,vs,{writable:!0,value:!1}),Object.defineProperty(this,bs,{writable:!0,value:!1}),Object.defineProperty(this,ys,{writable:!0,value:void 0}),Object.defineProperty(this,Ss,{writable:!0,value:os}),Object.defineProperty(this,ks,{writable:!0,value:void 0})}set user(e){d(this,ks)[ks]!==e&&(d(this,ks)[ks]=e,d(this,_s)[_s]=e?e.id_token:void 0,d(this,fs)[fs]=e?e.access_token:void 0,d(this,ms)[ms]=null!=e&&e.profile?e.profile:void 0,d(this,ws)[ws]=e?UserSession.deserialize(e):void 0,d(this,vs)[vs]=!(!e||e.expired),d(this,as)[as].notify(d(this,_s)[_s]),d(this,cs)[cs].notify(d(this,fs)[fs]),d(this,ls)[ls].notify(d(this,ms)[ms]),d(this,ds)[ds].notify(d(this,ws)[ws]),d(this,us)[us].notify(d(this,vs)[vs]))}async init(e){var t,n,s,i,r,o,a,c,l,u=this;Kt.setLevel(null!=(t=null!=(n=e.logLevel)?n:os.logLevel)?t:Kt.NONE),Kt.setLogger(console);const h=AuthUtils.isNativeMobile(),p=h?`${e.mobileScheme}://localhost/`:AuthUtils.getBaseUrl();if(d(this,Ss)[Ss]=jt({},os,{internal:{userStore:new hn({store:h?new MobileStorage:new ln}),redirect_uri:`${p}${null==(s=os.internal)?void 0:s.redirect_uri}`,post_logout_redirect_uri:`${p}${null==(i=os.internal)?void 0:i.post_logout_redirect_uri}`,popup_redirect_uri:`${p}${null==(r=os.internal)?void 0:r.popup_redirect_uri}`,popup_post_logout_redirect_uri:`${p}${null==(o=os.internal)?void 0:o.popup_post_logout_redirect_uri}`,silent_redirect_uri:`${p}${null==(a=os.internal)?void 0:a.silent_redirect_uri}`}},e),d(this,ys)[ys]=new OidcUserManager(d(this,Ss)[Ss]),d(this,gs)[gs].push(d(this,ys)[ys].events.addUserLoaded((e=>{this.user=e})),d(this,ys)[ys].events.addUserUnloaded((()=>{d(this,ks)[ks]&&(this.user=null,d(this,Ss)[Ss].loginRequired&&location.reload())})),d(this,ys)[ys].events.addSilentRenewError((async function(){await d(u,Ps)[Ps]()}))),d(this,Es)[Es](),AuthUtils.isUrlMatching(location.href,null==(c=d(this,Ss)[Ss].internal)?void 0:c.redirect_uri))await d(this,Us)[Us]((async function(){const e=sessionStorage.getItem(rs);await d(u,Is)[Is]((()=>d(u,ys)[ys].signinRedirectCallback(location.href)),e),sessionStorage.removeItem(rs)}));else if(AuthUtils.isUrlMatching(location.href,null==(l=d(this,Ss)[Ss].internal)?void 0:l.post_logout_redirect_uri))await d(this,Us)[Us]((async function(){const e=sessionStorage.getItem(rs);await d(u,Os)[Os]((()=>d(u,ys)[ys].signoutRedirectCallback(location.href)),e),sessionStorage.removeItem(rs)}));else if(d(this,Ss)[Ss].retrieveUserSession||d(this,Ss)[Ss].loginRequired){var g;const e=await(null==(g=d(this,ys)[ys])?void 0:g.getUser());!e||e.expired?!h&&d(this,Ss)[Ss].retrieveUserSession?await d(this,Us)[Us]((()=>d(this,Rs)[Rs]().catch((async function(e){const{error:t,message:n}=e;if(d(u,Ss)[Ss].loginRequired&&(null!=t&&t.includes("_required")||null!=n&&n.includes("_required")))await u.login();else if(console.error("[OIDCAuthManager] User's session cannot be retrieved:",e.message),d(u,us)[us].notify(!1),d(u,Ss)[Ss].loginRequired)throw e})))):d(this,Ss)[Ss].loginRequired?await this.login():this.user=null:this.user=e}else this.user=null}async logout(e){var t,n;const s=null!=(t=null==e?void 0:e.redirectUrl)?t:location.href;var i;if(AuthUtils.isNativeMobile())await d(this,Os)[Os]((()=>d(this,ys)[ys].signoutMobile(e)),s);else switch(null!=(i=null==e?void 0:e.desktopNavigationType)?i:d(this,Ss)[Ss].desktopNavigationType){case Qn.POPUP:await d(this,Os)[Os]((()=>d(this,ys)[ys].signoutPopup(e)),s);break;case Qn.REDIRECT:default:sessionStorage.setItem(rs,s),await(null==(n=d(this,ys)[ys])?void 0:n.signoutRedirect(e))}}async login(e){var t,n;const s=null!=(t=null==e?void 0:e.redirectUrl)?t:location.href;var i;if(AuthUtils.isNativeMobile())await d(this,Is)[Is]((()=>d(this,ys)[ys].signinMobile(e)),s);else switch(null!=(i=null==e?void 0:e.desktopNavigationType)?i:d(this,Ss)[Ss].desktopNavigationType){case Qn.POPUP:await d(this,Is)[Is]((()=>d(this,ys)[ys].signinPopup(e)),s);break;case Qn.REDIRECT:default:sessionStorage.setItem(rs,s),await(null==(n=d(this,ys)[ys])?void 0:n.signinRedirect(e))}return d(this,vs)[vs]}async renew(e){return d(this,Rs)[Rs](e).catch((e=>console.error(e)))}getSettings(){return d(this,Ss)[Ss]}isRenewing(){return d(this,bs)[bs]}async isAuthenticated(){return await d(this,xs)[xs]("isAuthenticated()"),d(this,vs)[vs]}async getUserProfile(){return await d(this,xs)[xs]("getUserProfile()"),d(this,ms)[ms]}async getUserSession(){return await d(this,xs)[xs]("getUserSession()"),d(this,ws)[ws]}async getIdToken(){return await d(this,xs)[xs]("getIdToken()"),d(this,_s)[_s]}async getIdTokenDecoded(){return await d(this,xs)[xs]("getIdTokenDecoded()"),AuthUtils.decodeJwt(d(this,_s)[_s])}async getAccessToken(){return await d(this,xs)[xs]("getAccessToken()"),d(this,fs)[fs]}async getAccessTokenDecoded(){return await d(this,xs)[xs]("getAccessTokenDecoded()"),AuthUtils.decodeJwt(d(this,fs)[fs])}destroy(){d(this,as)[as].unsubscribe(),d(this,cs)[cs].unsubscribe(),d(this,ls)[ls].unsubscribe(),d(this,ds)[ds].unsubscribe(),d(this,us)[us].unsubscribe(),d(this,hs)[hs].unsubscribe(),d(this,ps)[ps].unsubscribe(),d(this,gs)[gs].forEach((e=>e()))}onIdTokenChanged(e){return d(this,as)[as].add(e)}onAccessTokenChanged(e){return d(this,cs)[cs].add(e)}onUserProfileChanged(e){return d(this,ls)[ls].add(e)}onUserSessionChanged(e){return d(this,ds)[ds].add(e)}onAuthenticatedChanged(e){return d(this,us)[us].add(e)}onRenewingChanged(e){return d(this,hs)[hs].add(e)}onRedirect(e){return d(this,ps)[ps].add(e)}}function js(){var e,t;[null==(e=d(this,Ss)[Ss].internal)?void 0:e.silent_redirect_uri,null==(t=d(this,Ss)[Ss].internal)?void 0:t.popup_redirect_uri].forEach((e=>{var t;const n=null==(t=new RegExp(/^.*\/(.*).html$/gm).exec(null!=e?e:""))?void 0:t[1],s=new Error(`[OIDCAuthManager] ${null!=e?e:"redirect uri"} was not found.`);if(s.stack=void 0,AuthUtils.isUrlMatching(location.href,e))throw s.message+="\n\n\u24d8 This usually means you forgot to include the redirect html files in your application assets.",s;if(location.href.includes(`/${n}.html`))throw s.message+="\n\n\u24d8 This usually means your redirect urls are misconfigured.",s}))}async function Ls(e){const t=Date.now();for(;d(this,bs)[bs];){if(Date.now()>t+5e3){console.warn("[@badisi/auth-js]",`\`${e}\``,"timed out waiting for renew to finish.");break}await new Promise((e=>setTimeout(e,100)))}}function Ns(e){const t=AuthUtils.stringToURL(null!=e?e:"/");d(this,Ss)[Ss].loginRequired&&location.origin===t.origin&&location.reload()}function Ms(e){d(this,bs)[bs]=e,d(this,hs)[hs].notify(e)}async function qs(e){d(this,Ss)[Ss].loginRequired?await e():e()}async function Hs(e,t){t&&(console.error(t),await d(this,Ps)[Ps]());const n=AuthUtils.stringToURL(null!=e?e:"/");location.origin===n.origin?(history.replaceState(history.state,"",n.href),d(this,ps)[ps].notify(n)):location.href=n.href}async function Ws(){var e,t;this.user=null,await Promise.all([null==(e=d(this,ys)[ys])?void 0:e.clearStaleState(),null==(t=d(this,ys)[ys])?void 0:t.removeUser()])}async function $s(e){d(this,Ts)[Ts](!0);try{var t;await(null==(t=d(this,ys)[ys])?void 0:t.signinSilent(e))}catch(n){throw await d(this,Ps)[Ps](),n}finally{d(this,Ts)[Ts](!1)}}async function Ds(e,t){try{d(this,Ts)[Ts](!0),await e().catch((e=>{var t;throw"Attempted to navigate on a disposed window"===(null==(t=e)?void 0:t.message)&&((e=new Error("[OIDCAuthManager] Attempted to navigate on a disposed window.")).stack=void 0,e.message+="\n\n\u24d8 This may be due to an ad blocker."),e})),await d(this,As)[As](t)}catch(n){throw await d(this,As)[As]("/",n),n}finally{d(this,Ts)[Ts](!1)}}async function Bs(e,t){try{await e().catch((e=>{var t;throw"Attempted to navigate on a disposed window"===(null==(t=e)?void 0:t.message)&&((e=new Error("[OIDCAuthManager] Attempted to navigate on a disposed window.")).stack=void 0,e.message+="\n\n\u24d8 This may be due to an ad blocker."),e})),await d(this,As)[As](t),await d(this,Ps)[Ps]()}catch(n){throw t="/",await d(this,As)[As](t,n),n}finally{d(this,Cs)[Cs](t)}}const zs=(e=>e.CapacitorPlatforms=(e=>{const t=new Map;t.set("web",{name:"web"});const n=e.CapacitorPlatforms||{currentPlatform:{name:"web"},platforms:t};return n.addPlatform=(e,t)=>{n.platforms.set(e,t)},n.setPlatform=e=>{n.platforms.has(e)&&(n.currentPlatform=n.platforms.get(e))},n})(e))("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{});zs.addPlatform,zs.setPlatform;var Fs;!function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"}(Fs||(Fs={}));class CapacitorException extends Error{constructor(e,t,n){super(e),this.message=e,this.code=t,this.data=n}}const Js=e=>{var t,n,s,i,r;const o=e.CapacitorCustomPlatform||null,a=e.Capacitor||{},c=a.Plugins=a.Plugins||{},l=e.CapacitorPlatforms,d=(null===(t=null==l?void 0:l.currentPlatform)||void 0===t?void 0:t.getPlatform)||(()=>null!==o?o.name:(e=>{var t,n;return(null==e?void 0:e.androidBridge)?"android":(null===(n=null===(t=null==e?void 0:e.webkit)||void 0===t?void 0:t.messageHandlers)||void 0===n?void 0:n.bridge)?"ios":"web"})(e)),u=(null===(n=null==l?void 0:l.currentPlatform)||void 0===n?void 0:n.isNativePlatform)||(()=>"web"!==d()),h=(null===(s=null==l?void 0:l.currentPlatform)||void 0===s?void 0:s.isPluginAvailable)||(e=>{const t=g.get(e);return!!(null==t?void 0:t.platforms.has(d()))||!!p(e)}),p=(null===(i=null==l?void 0:l.currentPlatform)||void 0===i?void 0:i.getPluginHeader)||(e=>{var t;return null===(t=a.PluginHeaders)||void 0===t?void 0:t.find((t=>t.name===e))}),g=new Map,_=(null===(r=null==l?void 0:l.currentPlatform)||void 0===r?void 0:r.registerPlugin)||((e,t={})=>{const n=g.get(e);if(n)return console.warn(`Capacitor plugin "${e}" already registered. Cannot register plugins twice.`),n.proxy;const s=d(),i=p(e);let r;const l=n=>{let c;const l=(...l)=>{const d=(async()=>(!r&&s in t?r=r="function"==typeof t[s]?await t[s]():t[s]:null!==o&&!r&&"web"in t&&(r=r="function"==typeof t.web?await t.web():t.web),r))().then((t=>{const r=((t,n)=>{var r,o;if(!i){if(t)return null===(o=t[n])||void 0===o?void 0:o.bind(t);throw new CapacitorException(`"${e}" plugin is not implemented on ${s}`,Fs.Unimplemented)}{const s=null==i?void 0:i.methods.find((e=>n===e.name));if(s)return"promise"===s.rtype?t=>a.nativePromise(e,n.toString(),t):(t,s)=>a.nativeCallback(e,n.toString(),t,s);if(t)return null===(r=t[n])||void 0===r?void 0:r.bind(t)}})(t,n);if(r){const e=r(...l);return c=null==e?void 0:e.remove,e}throw new CapacitorException(`"${e}.${n}()" is not implemented on ${s}`,Fs.Unimplemented)}));return"addListener"===n&&(d.remove=async()=>c()),d};return l.toString=()=>`${n.toString()}() { [capacitor code] }`,Object.defineProperty(l,"name",{value:n,writable:!1,configurable:!1}),l},u=l("addListener"),h=l("removeListener"),_=(e,t)=>{const n=u({eventName:e},t),s=async()=>{const s=await n;h({eventName:e,callbackId:s},t)},i=new Promise((e=>n.then((()=>e({remove:s})))));return i.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await s()},i},f=new Proxy({},{get(e,t){switch(t){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return i?_:u;case"removeListener":return h;default:return l(t)}}});return c[e]=f,g.set(e,{name:e,proxy:f,platforms:new Set([...Object.keys(t),...i?[s]:[]])}),f});return a.convertFileSrc||(a.convertFileSrc=e=>e),a.getPlatform=d,a.handleError=t=>e.console.error(t),a.isNativePlatform=u,a.isPluginAvailable=h,a.pluginMethodNoop=(e,t,n)=>Promise.reject(`${n} does not have an implementation of "${t}".`),a.registerPlugin=_,a.Exception=CapacitorException,a.DEBUG=!!a.DEBUG,a.isLoggingEnabled=!!a.isLoggingEnabled,a.platform=a.getPlatform(),a.isNative=a.isNativePlatform(),a},Ks=(e=>e.Capacitor=Js(e))("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}),Vs=Ks.registerPlugin;Ks.Plugins;class WebPlugin{constructor(e){this.listeners={},this.windowListeners={},e&&(console.warn(`Capacitor WebPlugin "${e.name}" config object was deprecated in v3 and will be removed in v4.`),this.config=e)}addListener(e,t){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(t);const n=this.windowListeners[e];n&&!n.registered&&this.addWindowListener(n);const s=async()=>this.removeListener(e,t),i=Promise.resolve({remove:s});return Object.defineProperty(i,"remove",{value:async()=>{console.warn("Using addListener() without 'await' is deprecated."),await s()}}),i}async removeAllListeners(){this.listeners={};for(const e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,t){const n=this.listeners[e];n&&n.forEach((e=>e(t)))}hasListeners(e){return!!this.listeners[e].length}registerWindowListener(e,t){this.windowListeners[t]={registered:!1,windowEventName:e,pluginEventName:t,handler:e=>{this.notifyListeners(t,e)}}}unimplemented(e="not implemented"){return new Ks.Exception(e,Fs.Unimplemented)}unavailable(e="not available"){return new Ks.Exception(e,Fs.Unavailable)}async removeListener(e,t){const n=this.listeners[e];if(!n)return;const s=n.indexOf(t);this.listeners[e].splice(s,1),this.listeners[e].length||this.removeWindowListener(this.windowListeners[e])}addWindowListener(e){window.addEventListener(e.windowEventName,e.handler),e.registered=!0}removeWindowListener(e){e&&(window.removeEventListener(e.windowEventName,e.handler),e.registered=!1)}}const Gs=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Qs=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class CapacitorCookiesPluginWeb extends WebPlugin{async getCookies(){const e=document.cookie,t={};return e.split(";").forEach((e=>{if(e.length<=0)return;let[n,s]=e.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");n=Qs(n).trim(),s=Qs(s).trim(),t[n]=s})),t}async setCookie(e){try{const t=Gs(e.key),n=Gs(e.value),s=`; expires=${(e.expires||"").replace("expires=","")}`,i=(e.path||"/").replace("path=",""),r=null!=e.url&&e.url.length>0?`domain=${e.url}`:"";document.cookie=`${t}=${n||""}${s}; path=${i}; ${r};`}catch(t){return Promise.reject(t)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(t){return Promise.reject(t)}}async clearCookies(){try{const e=document.cookie.split(";")||[];for(const t of e)document.cookie=t.replace(/^ +/,"").replace(/=.*/,`=;expires=${(new Date).toUTCString()};path=/`)}catch(e){return Promise.reject(e)}}async clearAllCookies(){try{await this.clearCookies()}catch(e){return Promise.reject(e)}}}Vs("CapacitorCookies",{web:()=>new CapacitorCookiesPluginWeb});const Xs=(e,t={})=>{const n=Object.assign({method:e.method||"GET",headers:e.headers},t),s=((e={})=>{const t=Object.keys(e);return Object.keys(e).map((e=>e.toLocaleLowerCase())).reduce(((n,s,i)=>(n[s]=e[t[i]],n)),{})})(e.headers)["content-type"]||"";if("string"==typeof e.data)n.body=e.data;else if(s.includes("application/x-www-form-urlencoded")){const t=new URLSearchParams;for(const[n,s]of Object.entries(e.data||{}))t.set(n,s);n.body=t.toString()}else if(s.includes("multipart/form-data")||e.data instanceof FormData){const t=new FormData;if(e.data instanceof FormData)e.data.forEach(((e,n)=>{t.append(n,e)}));else for(const n of Object.keys(e.data))t.append(n,e.data[n]);n.body=t;const s=new Headers(n.headers);s.delete("content-type"),n.headers=s}else(s.includes("application/json")||"object"==typeof e.data)&&(n.body=JSON.stringify(e.data));return n};class CapacitorHttpPluginWeb extends WebPlugin{async request(e){const t=Xs(e,e.webFetchExtra),n=((e,t=!0)=>e?Object.entries(e).reduce(((e,n)=>{const[s,i]=n;let r,o;return Array.isArray(i)?(o="",i.forEach((e=>{r=t?encodeURIComponent(e):e,o+=`${s}=${r}&`})),o.slice(0,-1)):(r=t?encodeURIComponent(i):i,o=`${s}=${r}`),`${e}&${o}`}),"").substr(1):null)(e.params,e.shouldEncodeUrlParams),s=n?`${e.url}?${n}`:e.url,i=await fetch(s,t),r=i.headers.get("content-type")||"";let o,a,{responseType:c="text"}=i.ok?e:{};switch(r.includes("application/json")&&(c="json"),c){case"arraybuffer":case"blob":a=await i.blob(),o=await(async e=>new Promise(((t,n)=>{const s=new FileReader;s.onload=()=>{const e=s.result;t(e.indexOf(",")>=0?e.split(",")[1]:e)},s.onerror=e=>n(e),s.readAsDataURL(e)})))(a);break;case"json":o=await i.json();break;default:o=await i.text()}const l={};return i.headers.forEach(((e,t)=>{l[t]=e})),{data:o,headers:l,status:i.status,url:i.url}}async get(e){return this.request(Object.assign(Object.assign({},e),{method:"GET"}))}async post(e){return this.request(Object.assign(Object.assign({},e),{method:"POST"}))}async put(e){return this.request(Object.assign(Object.assign({},e),{method:"PUT"}))}async patch(e){return this.request(Object.assign(Object.assign({},e),{method:"PATCH"}))}async delete(e){return this.request(Object.assign(Object.assign({},e),{method:"DELETE"}))}}Vs("CapacitorHttp",{web:()=>new CapacitorHttpPluginWeb});const Ys='\n .flex {\n flex: 1;\n }\n\n .hidden {\n display: none !important;\n }\n\n .row {\n display: flex;\n flex-direction: row;\n }\n\n .column {\n display: flex;\n flex-direction: column;\n }\n\n .card {\n border: 1px solid rgba(0, 0, 0, 0.12);\n border-radius: 4px;\n background-color: white;\n margin: 12px 6px;\n }\n\n .card .card-status {\n display: block;\n width: 10px;\n height: 10px;\n border-radius: 50%;\n margin-left: 8px;\n background-color: #f2f2f2;\n }\n .card .card-status.error {\n background-color: #ef5350;\n }\n .card .card-status.success {\n background-color: #66bb6a;\n }\n\n .card .card-title {\n padding: 16px;\n font-size: 20px;\n font-weight: 500;\n color: rgba(0, 0, 0, 0.87);\n align-items: center;\n }\n\n .card .box {\n height: 200px;\n border-top: 1px solid lightgray;\n word-break: break-all;\n overflow: auto;\n background-color: #f2f2f2;\n padding: 12px;\n }\n .card .box pre {\n margin: 0;\n }\n\n .card .card-actions {\n padding: 0 14px 8px 14px;\n min-height: 50px;\n }\n .card .card-actions .input {\n display: flex;\n align-items: center;\n }\n .card .card-actions .input:not(:last-child) {\n margin-bottom: 8px;\n }\n .card .card-actions .input label {\n width: 125px;\n text-align: right;\n margin-right: 14px;\n }\n .card .card-actions .input input {\n padding: 4px;\n }\n\n .json-key {\n color: rgb(124, 77, 255);\n }\n\n .json-value {\n color: rgb(67, 122, 237);\n }\n\n .json-string {\n color: rgb(83, 160, 83);\n }\n\n .json-date {\n color: rgb(200, 56, 198);\n }\n\n input {\n color: #5e35b1;\n padding: 10px;\n border: 1px solid #0000001f;\n border-radius: 4px;\n font-size: 14px;\n }\n\n input:invalid {\n border-color: #f44336;\n }\n\n input[type="checkbox"] {\n margin-right: 10px;\n }\n\n select {\n color: #5e35b1;\n padding: 8px 6px;\n border: 1px solid #0000001f;\n border-radius: 4px;\n }\n\n @media only screen and (max-width: 600px) {\n :host {\n padding: 0 !important;\n padding-bottom: 24px !important;\n }\n\n :host .card {\n border-left: 0;\n border-right: 0;\n border-radius: 0;\n margin: 0;\n margin-bottom: 6px;\n }\n }\n',Zs=(e,t=[])=>e?JSON.stringify(e,null,2).replace(/&/g,"&").replace(/\\"/g,""").replace(//g,">").replace(/^( *)("[\w-]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/gm,((e,n,s,i,r)=>{let o=n||"";const a=s?s.replace(/[": ]/g,""):void 0;if(a&&(o+=`${a} : `),i&&(o+=`${i} `,a&&t.includes(a))){const e=new Date(1e3*Number(i)),t=`${e.toDateString()}, ${e.toLocaleTimeString()}`;t&&(o+=` (${t}) `)}return o+(r||"")})):"",ei=document.createElement("template");ei.innerHTML=`\n \n\n \n`;class DemoAppHeaderElement extends HTMLElement{constructor(){var e;super(),this.listeners=[],this.implSelectEl=void 0,this.statusEl=void 0,this.versionEl=void 0,this.loginButtonEl=void 0,this.logoutButtonEl=void 0,this.silentRenewButtonEl=void 0,this.attachShadow({mode:"open"}),null==(e=this.shadowRoot)||e.appendChild(document.importNode(ei.content,!0)),this.implSelectEl=this.shadowRoot.querySelector("#implementation-select"),this.statusEl=this.shadowRoot.querySelector(".status"),this.versionEl=this.shadowRoot.querySelector(".version"),this.loginButtonEl=this.shadowRoot.querySelector("#login-button"),this.logoutButtonEl=this.shadowRoot.querySelector("#logout-button"),this.silentRenewButtonEl=this.shadowRoot.querySelector("#silent-renew-button")}set isRenewing(e){this.statusEl&&this.statusEl.classList[e?"add":"remove"]("loading")}set isAuthenticated(e){this.statusEl&&null!==e&&(this.statusEl.classList.remove("loading"),this.statusEl.title=e?"Authenticated":"Not authenticated",this.statusEl.classList[e?"add":"remove"]("authenticated"),this.statusEl.classList[e?"remove":"add"]("not-authenticated"))}connectedCallback(){if(window.location.href.includes(":4200")){const e=document.createElement("option");e.textContent="localhost",this.implSelectEl.appendChild(e)}else{window.appSettings.getImplementations().forEach((e=>{const t=document.createElement("option");t.value=String(e.label),t.textContent=e.label,this.implSelectEl.appendChild(t)}));const e=()=>{window.location.href=window.appSettings.getImplementations()[this.implSelectEl.selectedIndex].demoUrl};this.implSelectEl.addEventListener("change",e),this.listeners.push((()=>this.implSelectEl.removeEventListener("change",e)))}const e=()=>{var e;null==(e=this.shadowRoot)||null==(e=e.querySelector("header .title .tip"))||e.remove(),window.appSettings.setShowTip(!1)};window.appSettings.get().showTip?(this.implSelectEl.addEventListener("click",e,{once:!0}),this.listeners.push((()=>this.implSelectEl.removeEventListener("click",e)))):e(),this.refreshImplementation(),this.addEventListeners()}disconnectedCallback(){this.listeners.forEach((e=>e()))}addEventListeners(){var e,t,n;const s=()=>this.dispatchEvent(new Event("login",{bubbles:!0,composed:!0}));null==(e=this.loginButtonEl)||e.addEventListener("click",s);const i=()=>this.dispatchEvent(new Event("logout",{bubbles:!0,composed:!0}));null==(t=this.logoutButtonEl)||t.addEventListener("click",i);const r=()=>this.dispatchEvent(new Event("silentRenew",{bubbles:!0,composed:!0}));null==(n=this.silentRenewButtonEl)||n.addEventListener("click",r),this.listeners.push((()=>{var e;return null==(e=this.loginButtonEl)?void 0:e.removeEventListener("click",s)}),(()=>{var e;return null==(e=this.logoutButtonEl)?void 0:e.removeEventListener("click",i)}),(()=>{var e;return null==(e=this.silentRenewButtonEl)?void 0:e.removeEventListener("click",r)}))}refreshImplementation(){const e=window.appSettings.getImplementations();if(window.location.href.includes(":4200"))this.implSelectEl.selectedIndex=0,this.versionEl.innerHTML="@localhost ";else{const t=e.findIndex((e=>window.location.href.includes(e.demoUrl))),n=-1!==t?e[t]:e[0];this.implSelectEl.selectedIndex=-1!==t?t:0,this.versionEl.innerHTML=n.version}}}window.customElements.define("demo-app-header",DemoAppHeaderElement);const ti=document.createElement("template");ti.innerHTML=`\n \n\n \n \n \n \n
\n`;class DemoAppMainElement extends HTMLElement{constructor(){var e;super(),this.listeners=[],this.tabsContentEl=void 0,this.demoAppHeaderEl=void 0,this.tabs=[],this.views=[],this.currentTabIndex=-1,this.attachShadow({mode:"open"}),null==(e=this.shadowRoot)||e.appendChild(document.importNode(ti.content,!0)),this.tabsContentEl=this.shadowRoot.querySelector(".tabs-content"),this.demoAppHeaderEl=this.shadowRoot.querySelector("demo-app-header")}set isRenewing(e){this.demoAppHeaderEl.isRenewing=e}set isAuthenticated(e){this.demoAppHeaderEl.isAuthenticated=e}connectedCallback(){this.drawTabs(),this.showView(window.appSettings?window.appSettings.get().currentTabIndex:0)}disconnectedCallback(){this.listeners.forEach((e=>e()))}drawTabs(){const e=this.shadowRoot.querySelector("#views"),t=this.shadowRoot.querySelector("#tabs");e&&t&&(this.views=e.assignedElements(),this.views.forEach(((e,n)=>{e.style.display="none";const s=document.createElement("a");s.textContent=e.getAttribute("tabLabel")||"?";const i=()=>this.showView(n);s.addEventListener("click",i),this.listeners.push((()=>s.removeEventListener("click",i))),t.appendChild(s),this.tabs.push(s)})))}showView(e){var t;this.currentTabIndex!==e&&(this.currentTabIndex=e,this.tabs.forEach(((t,n)=>{t.classList[n!==e?"remove":"add"]("selected")})),this.views.forEach(((t,n)=>{t.style.display=n!==e?"none":"flex"})),null==(t=this.tabsContentEl)||t.scrollTo(0,0),window.appSettings.setCurrentTabIndex(e))}}window.customElements.define("demo-app-main",DemoAppMainElement);const ni=document.createElement("template");ni.innerHTML=`\n \n\n \n
\n
\n
\n
\n Url \n \n
\n
\n Custom headers \n \n
\n
\n
GET \n
\n
\n
\n\n \n`;class DemoAppPlaygroundElement extends HTMLElement{constructor(){var e;super(),this.listeners=[],this.apiStatusEl=void 0,this.apiResponseEl=void 0,this.apiUrlEl=void 0,this.apiHeadersEl=void 0,this.attachShadow({mode:"open"}),null==(e=this.shadowRoot)||e.appendChild(document.importNode(ni.content,!0)),this.apiStatusEl=this.shadowRoot.querySelector("#api-status"),this.apiResponseEl=this.shadowRoot.querySelector("#api-response"),this.apiUrlEl=this.shadowRoot.querySelector("#api-url-input"),this.apiHeadersEl=this.shadowRoot.querySelector("#api-headers-input")}connectedCallback(){var e,t,n;const s=null==(e=this.shadowRoot)?void 0:e.querySelector("#api-get-button"),i=()=>{const e=new CustomEvent("api",{bubbles:!0,composed:!0,detail:{url:this.apiUrlEl.value,headers:this.apiHeadersEl.value}});return this.dispatchEvent(e)};null==s||s.addEventListener("click",i);const r=()=>this.saveSettings({privateApiUrl:this.apiUrlEl.value});null==(t=this.apiUrlEl)||t.addEventListener("input",r);const o=()=>this.saveSettings({privateApiHeaders:this.apiHeadersEl.value});null==(n=this.apiHeadersEl)||n.addEventListener("input",o),this.listeners.push((()=>null==s?void 0:s.removeEventListener("click",i)),(()=>{var e;return null==(e=this.apiUrlEl)?void 0:e.removeEventListener("input",r)}),(()=>{var e;return null==(e=this.apiHeadersEl)?void 0:e.removeEventListener("input",o)}));const{otherSettings:a}=window.appSettings.getCurrentUserSettings();this.apiUrlEl.value=null==a?void 0:a.privateApiUrl,this.apiHeadersEl.value=null==a?void 0:a.privateApiHeaders}disconnectedCallback(){this.listeners.forEach((e=>e()))}setApiStatus(e,t){this.apiStatusEl.classList.remove(t?"success":"error"),this.apiStatusEl.classList.add(t?"error":"success"),this.apiResponseEl.innerHTML=Zs(e)}saveSettings(e){const t=window.appSettings.getCurrentUserSettings();t.otherSettings=Object.assign({},t.otherSettings,e),window.appSettings.addOrUpdateUserSettings(t)}}window.customElements.define("demo-app-playground",DemoAppPlaygroundElement);const si=document.createElement("template");si.innerHTML=`\n \n\n \n
\n
Authenticated
\n
\n \n
\n
\n\n
\n
User session
\n
\n \n
\n
\n\n
\n
Access token
\n
\n \n \n
\n
\n\n
\n
Id token
\n
\n \n \n
\n
\n\n
\n
User profile
\n
\n \n
\n
\n
\n`;class DemoAppDebugElement extends HTMLElement{constructor(){var e;super(),this.attachShadow({mode:"open"}),null==(e=this.shadowRoot)||e.appendChild(document.importNode(si.content,!0)),this.isAuthenticated=!1,this.userSession=void 0,this.accessToken=void 0,this.accessTokenDecoded=void 0,this.idToken=void 0,this.idTokenDecoded=void 0,this.userProfile=void 0}set isAuthenticated(e){null!==e&&this.update("#isAuthenticated",e)}set userSession(e){this.update("#userSession",Zs(e,["expires_at"]))}set accessToken(e){this.update("#accessToken",e)}set accessTokenDecoded(e){const t="string"!=typeof e?Zs(e,["exp","iat","auth_time"]):"(no decoded info as it is not a JWT token)";this.update("#accessTokenDecoded",t)}set idToken(e){this.update("#idToken",e)}set idTokenDecoded(e){this.update("#idTokenDecoded",Zs(e,["exp","iat","auth_time"]))}set userProfile(e){this.update("#userProfile",Zs(e))}update(e,t){var n;const s=null==(n=this.shadowRoot)?void 0:n.querySelector(e);var i,r;s&&(null==t||""===t?null==(i=s.closest(".info"))||i.classList.add("hidden"):(null==(r=s.closest(".info"))||r.classList.remove("hidden"),s.innerHTML=String(t)))}}window.customElements.define("demo-app-debug",DemoAppDebugElement);const ii=document.createElement("template");ii.innerHTML=`\n \n\n \n\n \n SAVE \n CANCEL \n
\n\n \n`;class DemoAppSettingsElement extends HTMLElement{constructor(){var e;super(),this.listeners=[],this.formEl=void 0,this.formContentEl=void 0,this.selectEl=void 0,this.settingsNameEl=void 0,this.formIsDirty=!1,this.formIsNew=!1,this.attachShadow({mode:"open"}),null==(e=this.shadowRoot)||e.appendChild(document.importNode(ii.content,!0))}connectedCallback(){var e,t,n,s,i;this.formEl=this.shadowRoot.querySelector("form"),this.formContentEl=this.shadowRoot.querySelector(".form-content"),this.selectEl=this.shadowRoot.querySelector("#settings-select"),this.settingsNameEl=this.shadowRoot.querySelector("#settingsName");const r=e=>{this.formIsDirty||"settings-select"===e.target.id||(this.formIsDirty=!0,this.classList.add("dirty"))};this.formEl.addEventListener("input",r),this.listeners.push((()=>this.formEl.removeEventListener("input",r))),this.refreshSelect();const o=()=>this.loadSettings(this.selectEl.value);null==(e=this.selectEl)||e.addEventListener("change",o),this.listeners.push((()=>this.selectEl.removeEventListener("change",o)));const a=null==(t=this.shadowRoot)?void 0:t.querySelector("#add-settings-button"),c=()=>this.add();null==a||a.addEventListener("click",c),this.listeners.push((()=>null==a?void 0:a.removeEventListener("click",c)));const l=null==(n=this.shadowRoot)?void 0:n.querySelector("#delete-settings-button"),d=()=>this.delete();null==l||l.addEventListener("click",d),this.listeners.push((()=>null==l?void 0:l.removeEventListener("click",d)));const u=null==(s=this.shadowRoot)?void 0:s.querySelector("#save-settings-button"),h=()=>this.saveAndReload();null==u||u.addEventListener("click",h),this.listeners.push((()=>null==u?void 0:u.removeEventListener("click",h)));const p=null==(i=this.shadowRoot)?void 0:i.querySelector("#cancel-settings-button"),g=()=>this.cancel();null==p||p.addEventListener("click",g),this.listeners.push((()=>null==p?void 0:p.removeEventListener("click",g))),this.refreshFormContent(window.appSettings.getCurrentUserSettings())}disconnectedCallback(){this.listeners.forEach((e=>e()))}loadSettings(e){window.appSettings.setCurrentUserSettings(e),location.reload()}add(){const e="New settings",t=document.createElement("option");t.selected=!0,t.value=e,t.textContent=e,this.selectEl.appendChild(t),this.formIsNew=!0,this.formIsDirty=!0,this.classList.add("dirty"),this.refreshFormContent({name:e,librarySettings:{}})}delete(){window.appSettings.deleteCurrentUserSettings(),location.reload()}cancel(){this.formIsNew=!1,this.formIsDirty=!1,this.classList.remove("dirty"),this.refreshSelect(),this.refreshFormContent(window.appSettings.getCurrentUserSettings())}setPathValue(e,t,n){const s=t.split(".");s.reduce(((e,t,i)=>(i===s.length-1?e[t]=n:Object.prototype.hasOwnProperty.call(e,t)||(e[t]={}),e[t])),e)}getPathValue(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:e),e)}refreshSelect(){this.selectEl.innerHTML="";const{userSettings:e,currentUserSettingsId:t}=window.appSettings.get();e.sort(((e,t)=>e.name.localeCompare(t.name))).forEach((e=>{const n=document.createElement("option");n.selected=e.name===t,n.value=String(e.name),n.textContent=e.name,this.selectEl.appendChild(n)}))}refreshFormContent(e){this.formContentEl.innerHTML="";const{librarySettingsDefinition:t}=window.appSettings.get(),{name:n,librarySettings:s}=e;this.settingsNameEl.value=n,t.sort(((e,t)=>(t._sortIndex||0)-(e._sortIndex||0))).forEach((e=>{var t;const n=document.createElement("div");this.formContentEl.prepend(n);const i=document.createElement("label");i.htmlFor=e.name.replace(".",""),i.textContent=`${e.label}${e.required?" *":""}`;const r=document.createElement("list"===e.type?"select":"input");switch(r.id=e.name.replace(".",""),r.name=e.name.replace(".",""),r.required=!0===e.required,e.type){case"boolean":r.checked=this.getPathValue(s,e.name),r.type="checkbox",n.appendChild(r),n.appendChild(i);break;case"list":null==(t=e.values)||t.forEach((e=>{const t=document.createElement("option");t.value=String(e.value),t.textContent=e.label,r.appendChild(t)})),r.value=this.getPathValue(s,e.name),r.classList.add("flex"),n.classList.add("input","column"),n.appendChild(i),n.appendChild(r);break;default:{const t=this.getPathValue(s,e.name);"json"===e.type?r.value=t?JSON.stringify(t):"":r.value=null!=t?t:"",n.classList.add("input","column"),n.appendChild(i),n.appendChild(r);break}}}))}saveAndReload(){if(this.formEl.reportValidity()){const{librarySettingsDefinition:e}=window.appSettings.get(),t=this.formIsNew?{name:"",librarySettings:{}}:window.appSettings.getCurrentUserSettings();t.name=this.settingsNameEl.value,e.forEach((e=>{var n;const s=null==(n=this.shadowRoot)?void 0:n.querySelector(`#${e.name.replace(".","")}`);let i;switch(e.type){case"boolean":i=s.checked;break;case"list":default:i=s.value;break;case"json":try{const e=s.value;e&&""!==e.trim()&&(i=JSON.parse(e))}catch(r){console.error(r)}}this.setPathValue(t.librarySettings,e.name,i)})),window.appSettings.addOrUpdateUserSettings(t),this.formIsNew&&window.appSettings.setCurrentUserSettings(t.name),location.reload()}}}window.customElements.define("demo-app-settings",DemoAppSettingsElement);const ri=JSON.parse('{"UU":"@badisi/auth-js","rE":"0.0.0-semantically-released","TB":"https://github.com/Badisi/auth-js/tree/main/projects/auth-js"}'),oi=JSON.parse('{"UU":"@badisi/ngx-auth","TB":"https://github.com/Badisi/auth-js/tree/main/projects/ngx-auth"}');const ai=[{name:"authorityUrl",label:"Authority url",type:"string",required:!0},{name:"clientId",label:"Client id",type:"string",required:!0},{name:"mobileScheme",label:"Custom mobile scheme name",type:"string"},{name:"scope",label:"Scope",type:"string"},{name:"internal.extraQueryParams",label:"Extra query params",type:"json"},{name:"desktopNavigationType",label:"Desktop navigation type",type:"list",values:[{label:"REDIRECT",value:Qn.REDIRECT},{label:"POPUP",value:Qn.POPUP}]},{name:"logLevel",label:"Log level",type:"list",values:[{label:"NONE",value:Kt.NONE},{label:"ERROR",value:Kt.ERROR},{label:"WARN",value:Kt.WARN},{label:"INFO",value:Kt.INFO},{label:"DEBUG",value:Kt.DEBUG}]},{name:"loginRequired",label:"Login required",type:"boolean"},{name:"retrieveUserSession",label:"Retrieve user's session",type:"boolean"},{name:"loadUserInfo",label:"Load user's info",type:"boolean"},{name:"automaticSilentRenew",label:"Automatic silent renew",type:"boolean"}],ci=[...ai,{name:"automaticLoginOn401",label:"Automatic login on 401",type:"boolean"},{name:"automaticInjectToken",label:"Automatic inject token",type:"boolean"}];ci.splice(3,0,{name:"authGuardRedirectUrl",label:"AuthGuard redirect url",type:"string"});const li=(e=!1)=>{const t=[{name:"Auth0",otherSettings:{privateApiUrl:"https://dev-fijd1e9x.us.auth0.com/api/v2/users/auth0|631b171682c639d40cb84d5c",privateApiHeaders:""},librarySettings:{authorityUrl:"https://dev-fijd1e9x.us.auth0.com",clientId:"kRVVEnAWKMpxxpcodl0TqLXfIHgQvmmt",mobileScheme:"demo-app",scope:"openid profile email phone offline_access read:current_user",internal:{extraQueryParams:{audience:"https://dev-fijd1e9x.us.auth0.com/api/v2/"}},desktopNavigationType:Qn.REDIRECT,logLevel:Kt.NONE,loginRequired:!1,retrieveUserSession:!0,loadUserInfo:!0,automaticSilentRenew:!0}},{name:"Zitadel",otherSettings:{privateApiUrl:"",privateApiHeaders:""},librarySettings:{authorityUrl:"https://auth-js-0pdipf.zitadel.cloud",clientId:"178200751804317953@demo-app",mobileScheme:"demo-app",scope:"openid profile email phone offline_access",desktopNavigationType:Qn.REDIRECT,logLevel:Kt.NONE,loginRequired:!1,retrieveUserSession:!0,loadUserInfo:!0,automaticSilentRenew:!0}}];return e||t.push({name:"Keycloak (local)",otherSettings:{privateApiUrl:"/api/my-api",privateApiHeaders:""},librarySettings:{authorityUrl:"http://localhost:8080/auth/realms/demo",clientId:"demo-app",mobileScheme:"demo-app",scope:"openid profile email phone",desktopNavigationType:Qn.REDIRECT,logLevel:Kt.NONE,loginRequired:!1,retrieveUserSession:!0,loadUserInfo:!0,automaticSilentRenew:!0}}),t},di=new class DemoAppSettings{constructor(e,t){this.storageKey=e,this.defaultAppSettings=t,this.implementations=[{label:"VanillaJS",demoUrl:"https://badisi.github.io/auth-js/demo-app/auth-js",version:`${ri.UU}@main `},{label:"Angular",demoUrl:"https://badisi.github.io/auth-js/demo-app/ngx-auth",version:`${oi.UU}@main `}],this.defaultAppSettings.librarySettingsDefinition.forEach(((e,t)=>e._sortIndex=t))}getImplementations(){return this.implementations}setShowTip(e){const t=this.get();t.showTip=e,this.saveAppSettings(t)}setCurrentTabIndex(e){const t=this.get();t.currentTabIndex=e,this.saveAppSettings(t)}addOrUpdateUserSettings(e){const t=this.get(),n=t.userSettings.findIndex((t=>t.name===e.name));-1!==n?t.userSettings[n]=e:t.userSettings.push(e),this.saveAppSettings(t)}deleteCurrentUserSettings(){const e=this.get(),{name:t}=this.getCurrentUserSettings(),n=e.userSettings.findIndex((e=>e.name===t));-1!==n&&(e.userSettings.splice(n,1),delete e.currentUserSettingsId,this.saveAppSettings(e))}setCurrentUserSettings(e){const t=this.get();-1!==t.userSettings.findIndex((t=>t.name===e))&&(t.currentUserSettingsId=e,this.saveAppSettings(t))}getCurrentUserSettings(){const e=this.get(),t=e.userSettings.findIndex((t=>t.name===e.currentUserSettingsId));return-1!==t?e.userSettings[t]:e.userSettings.sort(((e,t)=>e.name.localeCompare(t.name)))[0]}get(){const e=sessionStorage.getItem(this.storageKey);if(e){const t=Object.assign({},this.defaultAppSettings,JSON.parse(e));return this.defaultAppSettings.userSettings.forEach((e=>{t.userSettings.find((t=>t.name===e.name))||t.userSettings.push(e)})),t}return Object.assign({},this.defaultAppSettings)}saveAppSettings(e){delete e.librarySettingsDefinition,sessionStorage.setItem(this.storageKey,JSON.stringify(e))}}(`auth-js:${ri.rE}:demo-app:settings`,{showTip:!0,currentTabIndex:0,userSettings:li(!0),librarySettingsDefinition:ai});(()=>{window.appSettings=di;const e=document.createElement("div");e.innerHTML="Loading...",document.body.appendChild(e),(async e=>await(async(e,t)=>{const n=new t;return await n.init(e),n})(e,OIDCAuthManager))(di.getCurrentUserSettings().librarySettings).then((t=>{window.authManager=t,e.replaceWith(document.createElement("app-root"))})).catch((t=>{var n;console.error(t),e.innerHTML=`${t.message}Login `,null==(n=document.body.querySelector("#loginButton"))||n.addEventListener("click",(()=>location.reload()),{once:!0})}))})()},436:function(e,t,n){var s;e.exports=(s=s||function(e,t){var s;if("undefined"!=typeof window&&window.crypto&&(s=window.crypto),"undefined"!=typeof self&&self.crypto&&(s=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(s=globalThis.crypto),!s&&"undefined"!=typeof window&&window.msCrypto&&(s=window.msCrypto),!s&&"undefined"!=typeof global&&global.crypto&&(s=global.crypto),!s)try{s=n(366)}catch(f){}var i=function(){if(s){if("function"==typeof s.getRandomValues)try{return s.getRandomValues(new Uint32Array(1))[0]}catch(f){}if("function"==typeof s.randomBytes)try{return s.randomBytes(4).readInt32LE()}catch(f){}}throw new Error("Native crypto module could not be used to get secure random number.")},r=Object.create||function(){function e(){}return function(t){var n;return e.prototype=t,n=new e,e.prototype=null,n}}(),o={},a=o.lib={},c=a.Base={extend:function(e){var t=r(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},l=a.WordArray=c.extend({init:function(e,n){e=this.words=e||[],this.sigBytes=n!=t?n:4*e.length},toString:function(e){return(e||u).stringify(this)},concat:function(e){var t=this.words,n=e.words,s=this.sigBytes,i=e.sigBytes;if(this.clamp(),s%4)for(var r=0;r>>2]>>>24-r%4*8&255;t[s+r>>>2]|=o<<24-(s+r)%4*8}else for(var a=0;a>>2]=n[a>>>2];return this.sigBytes+=i,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=c.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],n=0;n>>2]>>>24-i%4*8&255;s.push((r>>>4).toString(16)),s.push((15&r).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>3]|=parseInt(e.substr(s,2),16)<<24-s%8*4;return new l.init(n,t/2)}},h=d.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,s=[],i=0;i>>2]>>>24-i%4*8&255;s.push(String.fromCharCode(r))}return s.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s>>2]|=(255&e.charCodeAt(s))<<24-s%4*8;return new l.init(n,t)}},p=d.Utf8={stringify:function(e){try{return decodeURIComponent(escape(h.stringify(e)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse:function(e){return h.parse(unescape(encodeURIComponent(e)))}},g=a.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new l.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=p.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n,s=this._data,i=s.words,r=s.sigBytes,o=this.blockSize,a=r/(4*o),c=(a=t?e.ceil(a):e.max((0|a)-this._minBufferSize,0))*o,d=e.min(4*c,r);if(c){for(var u=0;u>>6-o%4*2;i[r>>>2]|=a<<24-r%4*8,r++}return t.create(i,r)}e.enc.Base64={stringify:function(e){var t=e.words,n=e.sigBytes,s=this._map;e.clamp();for(var i=[],r=0;r>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,a=0;a<4&&r+.75*a>>6*(3-a)&63));var c=s.charAt(64);if(c)for(;i.length%4;)i.push(c);return i.join("")},parse:function(e){var t=e.length,s=this._map,i=this._reverseMap;if(!i){i=this._reverseMap=[];for(var r=0;r>>7)^(g<<14|g>>>18)^g>>>3,f=l[p-2],m=(f<<15|f>>>17)^(f<<13|f>>>19)^f>>>10;l[p]=_+l[p-7]+m+l[p-16]}var w=s&i^s&r^i&r,v=(s<<30|s>>>2)^(s<<19|s>>>13)^(s<<10|s>>>22),b=h+((a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25))+(a&d^~a&u)+c[p]+l[p];h=u,u=d,d=a,a=o+b|0,o=r,r=i,i=s,s=b+(v+w)|0}n[0]=n[0]+s|0,n[1]=n[1]+i|0,n[2]=n[2]+r|0,n[3]=n[3]+o|0,n[4]=n[4]+a|0,n[5]=n[5]+d|0,n[6]=n[6]+u|0,n[7]=n[7]+h|0},_doFinalize:function(){var t=this._data,n=t.words,s=8*this._nDataBytes,i=8*t.sigBytes;return n[i>>>5]|=128<<24-i%32,n[14+(i+64>>>9<<4)]=e.floor(s/4294967296),n[15+(i+64>>>9<<4)]=s,t.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=r._createHelper(d),t.HmacSHA256=r._createHmacHelper(d)}(Math),s.SHA256)},566:(e,t,n)=>{"use strict";n.d(t,{A:()=>c});var s=n(753);e=n.hmd(e);var i="object"==typeof exports&&exports&&!exports.nodeType&&exports,r=i&&e&&!e.nodeType&&e,o=r&&r.exports===i?s.A.Buffer:void 0,a=o?o.allocUnsafe:void 0;const c=function(e,t){if(t)return e.slice();var n=e.length,s=a?a(n):new e.constructor(n);return e.copy(s),s}},724:(e,t,n)=>{"use strict";n.d(t,{A:()=>s});const s="object"==typeof global&&global&&global.Object===Object&&global},485:(e,t,n)=>{"use strict";n.d(t,{A:()=>a});var s=n(724);e=n.hmd(e);var i="object"==typeof exports&&exports&&!exports.nodeType&&exports,r=i&&e&&!e.nodeType&&e,o=r&&r.exports===i&&s.A.process;const a=function(){try{var e=r&&r.require&&r.require("util").types;return e||o&&o.binding&&o.binding("util")}catch(t){}}()},753:(e,t,n)=>{"use strict";n.d(t,{A:()=>r});var s=n(724),i="object"==typeof self&&self&&self.Object===Object&&self;const r=s.A||i||Function("return this")()},160:(e,t,n)=>{"use strict";n.d(t,{A:()=>c});var s=n(753);const i=function(){return!1};e=n.hmd(e);var r="object"==typeof exports&&exports&&!exports.nodeType&&exports,o=r&&e&&!e.nodeType&&e,a=o&&o.exports===r?s.A.Buffer:void 0;const c=(a?a.isBuffer:void 0)||i},366:()=>{}},e=>{var t;t=179,e(e.s=t)}]);
\ No newline at end of file
diff --git a/demo-app/auth-js/runtime.1af42e8fcde6888f.js b/demo-app/auth-js/runtime.1af42e8fcde6888f.js
new file mode 100644
index 0000000..e114a9a
--- /dev/null
+++ b/demo-app/auth-js/runtime.1af42e8fcde6888f.js
@@ -0,0 +1 @@
+(()=>{"use strict";var e,r={},o={};function t(e){var n=o[e];if(void 0!==n)return n.exports;var a=o[e]={id:e,loaded:!1,exports:{}};return r[e].call(a.exports,a,a.exports,t),a.loaded=!0,a.exports}t.m=r,e=[],t.O=(r,o,n,a)=>{if(!o){var s=1/0;for(p=0;p=a)&&Object.keys(t.O).every((e=>t.O[e](o[i])))?o.splice(i--,1):(l=!1,a0&&e[p-1][2]>a;p--)e[p]=e[p-1];e[p]=[o,n,a]},t.n=e=>{var r=e&&e.__esModule?()=>e.default:()=>e;return t.d(r,{a:r}),r},t.d=(e,r)=>{for(var o in r)t.o(r,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:r[o]})},t.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),t.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),(()=>{var e={121:0};t.O.j=r=>0===e[r];var r=(r,o)=>{var n,a,[s,l,i]=o,d=0;if(s.some((r=>0!==e[r]))){for(n in l)t.o(l,n)&&(t.m[n]=l[n]);if(i)var p=i(t)}for(r&&r(o);d{}},s=>{var e;e=737,s(s.s=e)}]);
\ No newline at end of file
diff --git a/demo-app/ngx-auth/3rdpartylicenses.txt b/demo-app/ngx-auth/3rdpartylicenses.txt
index 0842bcb..532e530 100644
--- a/demo-app/ngx-auth/3rdpartylicenses.txt
+++ b/demo-app/ngx-auth/3rdpartylicenses.txt
@@ -13,32 +13,6 @@ MIT
@angular/router
MIT
-@babel/runtime
-MIT
-MIT License
-
-Copyright (c) 2014-present Sebastian McKenzie and other contributors
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-
@badisi/auth-js
GPL-3.0-only
@@ -608,7 +582,7 @@ zone.js
MIT
The MIT License
-Copyright (c) 2010-2023 Google LLC. https://angular.io/license
+Copyright (c) 2010-2024 Google LLC. https://angular.io/license
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/demo-app/ngx-auth/998.e0dbcb6f14904117.js b/demo-app/ngx-auth/998.7d2c96e76000cb11.js
similarity index 90%
rename from demo-app/ngx-auth/998.e0dbcb6f14904117.js
rename to demo-app/ngx-auth/998.7d2c96e76000cb11.js
index 2cfbe75..6d6b449 100644
--- a/demo-app/ngx-auth/998.e0dbcb6f14904117.js
+++ b/demo-app/ngx-auth/998.7d2c96e76000cb11.js
@@ -1 +1 @@
-"use strict";(self.webpackChunkdemo_app_ngx_auth=self.webpackChunkdemo_app_ngx_auth||[]).push([[998],{1998:(c,s,e)=>{e.r(s),e.d(s,{PageComponent:()=>l});var t=e(4438),o=e(8540);let l=(()=>{class n{constructor(){this.title="",this.route=(0,t.WQX)(o.nX)}ngOnInit(){this.title=this.route.snapshot.data.title}static#t=this.\u0275fac=function(a){return new(a||n)};static#e=this.\u0275cmp=t.VBU({type:n,selectors:[["app-page"]],standalone:!0,features:[t.aNF],decls:2,vars:1,template:function(a,u){1&a&&(t.j41(0,"h2"),t.EFF(1),t.k0s()),2&a&&(t.R7$(),t.JRh(u.title))},styles:["[_nghost-%COMP%]{display:flex;justify-content:center;align-items:center;height:100%;color:#bdbdbd}"]})}return n})()}}]);
\ No newline at end of file
+"use strict";(self.webpackChunkdemo_app_ngx_auth=self.webpackChunkdemo_app_ngx_auth||[]).push([[998],{1998:(c,s,e)=>{e.r(s),e.d(s,{PageComponent:()=>l});var t=e(3953),o=e(8540);let l=(()=>{class n{constructor(){this.title="",this.route=(0,t.WQX)(o.nX)}ngOnInit(){this.title=this.route.snapshot.data.title}static#t=this.\u0275fac=function(a){return new(a||n)};static#e=this.\u0275cmp=t.VBU({type:n,selectors:[["app-page"]],standalone:!0,features:[t.aNF],decls:2,vars:1,template:function(a,u){1&a&&(t.j41(0,"h2"),t.EFF(1),t.k0s()),2&a&&(t.R7$(),t.JRh(u.title))},styles:["[_nghost-%COMP%]{display:flex;justify-content:center;align-items:center;height:100%;color:#bdbdbd}"]})}return n})()}}]);
\ No newline at end of file
diff --git a/demo-app/ngx-auth/index.html b/demo-app/ngx-auth/index.html
index b3d2b6f..226367a 100644
--- a/demo-app/ngx-auth/index.html
+++ b/demo-app/ngx-auth/index.html
@@ -8,7 +8,7 @@
-
+
@@ -21,6 +21,6 @@
}
}
-
+