@descope/web-js-sdk 1.27.2 → 1.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,4 +1,4 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Descope=t()}(this,(function(){"use strict";const e=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,o)=>{var r;return n[o]=[].concat((null===(r=e.hooks)||void 0===r?void 0:r[o])||[]).concat((null==t?void 0:t[o])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},t=async e=>{if(!(null==e?void 0:e.ok))return{};const t=await(null==e?void 0:e.clone().json());return(null==t?void 0:t.authInfo)||t||{}},n=async e=>{const n=await t(e);return(null==n?void 0:n.user)||((null==n?void 0:n.hasOwnProperty("userId"))?n:void 0)},o="undefined"!=typeof localStorage,r=(e,t)=>o&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),i=e=>o&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),s=e=>o&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e));var a=function(){return a=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},a.apply(this,arguments)};function c(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}"function"==typeof SuppressedError&&SuppressedError;class l extends Error{}function u(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return atob(t)}}function d(e,t){if("string"!=typeof e)throw new l("Invalid token specified: must be a string");t||(t={});const n=!0===t.header?0:1,o=e.split(".")[n];if("string"!=typeof o)throw new l(`Invalid token specified: missing part #${n+1}`);let r;try{r=u(o)}catch(e){throw new l(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(r)}catch(e){throw new l(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}l.prototype.name="InvalidTokenError";var p="/v1/auth/accesskey/exchange",g="/v1/auth/otp/verify",f="/v1/auth/otp/signin",h="/v1/auth/otp/signup",v={email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},m="/v1/auth/otp/signup-in",b="/v1/auth/magiclink/verify",w="/v1/auth/magiclink/signin",y="/v1/auth/magiclink/signup",k={email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},I="/v1/auth/magiclink/signup-in",O="/v1/auth/enchantedlink/verify",j="/v1/auth/enchantedlink/signin",S="/v1/auth/enchantedlink/signup",U="/v1/auth/enchantedlink/pending-session",R={email:"/v1/auth/enchantedlink/update/email"},P="/v1/auth/enchantedlink/signup-in",x="/v1/auth/oauth/authorize",C="/v1/auth/oauth/exchange",T="v1/auth/oauth/native/start",E="v1/auth/oauth/native/finish",$="/v1/auth/saml/authorize",A="/v1/auth/saml/exchange",D="/v1/auth/totp/verify",q="/v1/auth/totp/signup",L="/v1/auth/totp/update",_="/v1/auth/notp/whatsapp/signin",N="/v1/auth/notp/whatsapp/signup",M="/v1/auth/notp/whatsapp/signup-in",J="/v1/auth/notp/pending-session",K={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},H={start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},V={start:"/v1/auth/webauthn/signup-in/start"},B={start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"},F="/v1/auth/password/signup",z="/v1/auth/password/signin",Z="/v1/auth/password/reset",G="/v1/auth/password/update",Y="/v1/auth/password/replace",X="/v1/auth/password/policy",Q="/v1/auth/refresh",W="/v1/auth/tenant/select",ee="/v1/auth/logout",te="/v1/auth/logoutall",ne="/v1/auth/me",oe="/v1/auth/me/tenants",re="/v1/auth/me/history",ie="/v1/flow/start",se="/v1/flow/next";const ae="<region>",ce=`https://api.${ae}descope.com`,le=6e5,ue="dct",de=()=>{const e={};return{headers(t){const n="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(n),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}};let pe;const ge=()=>{if(pe)return pe;const e=new Date,t=`${e.getUTCFullYear().toString()}-${(e.getUTCMonth()+1).toString().padStart(2,"0")}-${e.getUTCDate().toString().padStart(2,"0")}-${e.getUTCHours().toString().padStart(2,"0")}:${e.getUTCMinutes().toString().padStart(2,"0")}:${e.getUTCSeconds().toString().padStart(2,"0")}:${e.getUTCMilliseconds().toString()}`,n=Math.floor(1e3+9e3*Math.random());return pe=`${t}-${n}`,pe};var fe,he;(he=fe||(fe={})).get="GET",he.delete="DELETE",he.post="POST",he.put="PUT",he.patch="PATCH";const ve=({path:e,baseUrl:t,queryParams:n,projectId:o})=>{const r=o.slice(1,-27);t=t.replace(ae,r?r+".":"");let i=e?`${t.replace(/\/$/,"")}/${null==e?void 0:e.replace(/^\//,"")}`:t;if(n){const e=Object.keys(n);e.forEach(((t,o)=>{i=`${i}${0===o?"?":""}${t}=${encodeURIComponent(n[t])}${o===e.length-1?"":"&"}`}))}return i},me=(...e)=>new Headers(e.reduce(((e,t)=>{const n=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return n.reduce(((t,[n,o])=>(e[n]=o,e)),e),e}),{})),be={"Content-Type":"application/json"},we=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},ye=e=>{const t={"x-descope-sdk-session-id":ge(),"x-descope-sdk-name":"core-js","x-descope-sdk-version":"2.39.0"};return e&&(t["x-descope-refresh-cookie-name"]=e),t},ke=e=>{try{e=JSON.parse(e)}catch(e){return!1}return"object"==typeof e&&null!==e},Ie=({baseUrl:e,projectId:t,baseConfig:n,refreshCookieName:o,logger:r,hooks:i,cookiePolicy:s,fetch:a})=>{const c=((e,t)=>{const n=(e=>async(...t)=>{const n=await e(...t),o=await n.text();return n.text=()=>Promise.resolve(o),n.json=()=>Promise.resolve(JSON.parse(o)),n.clone=()=>n,n})(t||fetch);return n||null==e||e.warn("Fetch is not defined, you will not be able to send http requests, if you are running in a test, make sure fetch is defined globally"),e?async(...t)=>{if(!n)throw Error("Cannot send http request, fetch is not defined, if you are running in a test, make sure fetch is defined globally");e.log((e=>de().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const o=await n(...t);return e[o.ok?"log":"error"](await(async e=>{const t=await e.text();return de().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(o)),o}:n})(r,a),l=async r=>{var a;const l=(null==i?void 0:i.beforeRequest)?i.beforeRequest(r):r,{path:u,body:d,headers:p,queryParams:g,method:f,token:h}=l,v=(e=>void 0===e?void 0:JSON.stringify(e))(d),m={headers:me(we(t,h),ye(o),(null==n?void 0:n.baseHeaders)||{},ke(v)?be:{},p),method:f,body:v};null!==s&&(m.credentials=s||"include");const b=await c(ve({path:u,baseUrl:e,queryParams:g,projectId:t}),m);if((null==i?void 0:i.afterRequest)&&await i.afterRequest(r,null==b?void 0:b.clone()),null==i?void 0:i.transformResponse){const e=await b.json(),t=((null===(a=b.headers)||void 0===a?void 0:a.get("set-cookie"))||"").split(";").reduce(((e,t)=>{const[n,o]=t.split("=");return Object.assign(Object.assign({},e),{[n.trim()]:o})}),{}),n=Object.assign(Object.assign({},b),{json:()=>Promise.resolve(e),cookies:t});return n.clone=()=>n,i.transformResponse(n)}return b};return{get:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:fe.get,token:o}),post:(e,t,{headers:n,queryParams:o,token:r}={})=>l({path:e,headers:n,queryParams:o,body:t,method:fe.post,token:r}),patch:(e,t,{headers:n,queryParams:o,token:r}={})=>l({path:e,headers:n,queryParams:o,body:t,method:fe.patch,token:r}),put:(e,t,{headers:n,queryParams:o,token:r}={})=>l({path:e,headers:n,queryParams:o,body:t,method:fe.put,token:r}),delete:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:fe.delete,token:o}),hooks:i,buildUrl:(n,o)=>ve({projectId:t,baseUrl:e,path:n,queryParams:o})}};var Oe=429;function je(e,t,n){var o;let r=Se(e);if(t){if(!(null==r?void 0:r.tenants)&&(null==r?void 0:r[ue])===t)return(null==r?void 0:r[n])||[];r=null===(o=null==r?void 0:r.tenants)||void 0===o?void 0:o[t]}const i=null==r?void 0:r[n];return Array.isArray(i)?i:[]}function Se(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return d(e)}function Ue(e){const{exp:t}=Se(e);return(new Date).getTime()/1e3>t}function Re(e){let t=Se(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function Pe(e,t){return je(e,t,"permissions")}function xe(e,t){return je(e,t,"roles")}const Ce=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function Te(e,t){var n;const o=await e,r={code:o.status,ok:o.ok,response:o},i=await o.clone().json();return o.ok?r.data=i:(r.error=i,o.status===Oe&&Object.assign(r.error,{retryAfter:Number.parseInt(null===(n=o.headers)||void 0===n?void 0:n.get("retry-after"))||0})),r}function Ee(e){var t;return(null===(t=Se(e))||void 0===t?void 0:t[ue])||""}const $e=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),Ae=(e,t)=>(n=t)=>t=>{const o=e.filter((e=>e(t)));return!(o.length<e.length)&&(n?n.replace("{val}",t):o.join(" OR "))},De=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),qe=e=>t=>e.test(t),Le=qe(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),_e=qe(/^\+[1-9]{1}[0-9]{3,14}$/),Ne=$e(Le,'"{val}" is not a valid email'),Me=$e(_e,'"{val}" is not a valid phone number'),Je=$e((e=>e.length>=1),"Minimum length is 1");const Ke=$e((e=>"string"==typeof e),"Input is not a string"),He=$e((e=>Array.isArray(e)),"Input is not an array"),Ve=$e((e=>"boolean"==typeof e),"Input is not a boolean"),Be=$e((e=>void 0===e),"Input is defined"),Fe=Ae([Ke(),Be()],"Input is not a string or undefined"),ze=Ae([He(),Ve()],"Input is not an array or boolean"),Ze=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>De(...e).validate(n[t]))),t(...n)),Ge=e=>[Ke(`"${e}" must be a string`)],Ye=e=>[Ke(`"${e}" must be a string`),Je(`"${e}" must not be empty`)],Xe=e=>[Ke(`"${e}" must be a string`),Ne()],Qe=e=>[Ke(`"${e}" must be a string`),Me()],We=Ze(Ye("accessKey")),et=e=>({exchange:We(((t,n)=>Te(e.post(p,{loginOptions:n},{token:t}))))}),tt=(e,t,n)=>(t.forEach((t=>{const o=t.split(".");let r=o.shift(),i=e;for(;o.length>0;){if(i=i[r],!r||!i)throw Error(`Invalid path "${t}", "${r}" is missing or has no value`);r=o.shift()}if("function"!=typeof i[r])throw Error(`"${t}" is not a function`);const s=i[r];i[r]=n(s)})),e),nt=({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||le,le)});var ot,rt;!function(e){e.sms="sms",e.voice="voice",e.whatsapp="whatsapp"}(ot||(ot={})),function(e){e.email="email"}(rt||(rt={}));const it=Object.assign(Object.assign({},ot),rt);var st;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(st||(st={}));const at=Ye("loginId"),ct=Ze(Ye("token")),lt=Ze(at),ut=Ze(Ye("pendingRef")),dt=Ze(at,Xe("email")),pt=e=>({verify:ct((t=>Te(e.post(O,{token:t})))),signIn:lt(((t,n,o,r)=>Te(e.post(Ce(j,it.email),{loginId:t,URI:n,loginOptions:o},{token:r})))),signUpOrIn:lt(((t,n,o)=>Te(e.post(Ce(P,it.email),{loginId:t,URI:n,loginOptions:o})))),signUp:lt(((t,n,o,r)=>Te(e.post(Ce(S,it.email),{loginId:t,URI:n,user:o,loginOptions:r})))),waitForSession:ut(((t,n)=>new Promise((o=>{const{pollingIntervalMs:r,timeoutMs:i}=nt(n);let s;const a=setInterval((async()=>{const n=await e.post(U,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),o(Te(Promise.resolve(n))))}),r);s=setTimeout((()=>{o({error:{errorDescription:`Session polling timeout exceeded: ${i}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),i)})))),update:{email:dt(((t,n,o,r,i)=>Te(e.post(R.email,Object.assign({loginId:t,email:n,URI:o},i),{token:r}))))}}),gt=Ze(Ye("flowId")),ft=Ze(Ye("executionId"),Ye("stepId"),Ye("interactionId")),ht=e=>({start:gt(((t,n,o,r,i,s,a)=>Te(e.post(ie,{flowId:t,options:n,conditionInteractionId:o,interactionId:r,componentsVersion:i,flowVersions:s,input:a})))),next:ft(((t,n,o,r,i,s)=>Te(e.post(se,{executionId:t,stepId:n,interactionId:o,version:r,componentsVersion:i,input:s}))))}),vt=Ye("loginId"),mt=Ze(Ye("token")),bt=Ze(vt),wt=Ze(vt,Qe("phone")),yt=Ze(vt,Xe("email")),kt=Object.keys(it).filter((e=>e!==ot.voice)),It=e=>({verify:mt((t=>Te(e.post(b,{token:t})))),signIn:kt.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:bt(((t,o,r,i)=>Te(e.post(Ce(w,n),{loginId:t,URI:o,loginOptions:r},{token:i}))))})),{}),signUp:kt.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:bt(((t,o,r,i)=>Te(e.post(Ce(y,n),{loginId:t,URI:o,user:r,loginOptions:i}))))})),{}),signUpOrIn:kt.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:bt(((t,o,r)=>Te(e.post(Ce(I,n),{loginId:t,URI:o,loginOptions:r}))))})),{}),update:{email:yt(((t,n,o,r,i)=>Te(e.post(k.email,Object.assign({loginId:t,email:n,URI:o},i),{token:r})))),phone:Object.keys(ot).filter((e=>e!==ot.voice)).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:wt(((t,o,r,i,s)=>Te(e.post(Ce(k.phone,n),Object.assign({loginId:t,phone:o,URI:r},s),{token:i}))))})),{})}});var Ot;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple",e.discord="discord",e.linkedin="linkedin",e.slack="slack"}(Ot||(Ot={}));const jt=Ze(Ye("code")),St=e=>({start:Object.assign(((t,n,o,r)=>Te(e.post(x,o||{},{queryParams:Object.assign({provider:t},n&&{redirectURL:n}),token:r}))),Object.keys(Ot).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,o,r)=>Te(e.post(x,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:r}))})),{})),exchange:jt((t=>Te(e.post(C,{code:t})))),startNative:(t,n,o)=>Te(e.post(T,{provider:t,loginOptions:n,implicit:o})),finishNative:(t,n,o,r,i)=>Te(e.post(E,{provider:t,stateId:n,user:o,code:r,idToken:i}))}),Ut=Ye("loginId"),Rt=Ze(Ut,Ye("code")),Pt=Ze(Ut),xt=Ze(Ut,Qe("phone")),Ct=Ze(Ut,Xe("email")),Tt=e=>({verify:Object.keys(it).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Rt(((t,o)=>Te(e.post(Ce(g,n),{code:o,loginId:t}))))})),{}),signIn:Object.keys(it).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Pt(((t,o,r)=>Te(e.post(Ce(f,n),{loginId:t,loginOptions:o},{token:r}))))})),{}),signUp:Object.keys(it).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Pt(((t,o,r)=>Te(e.post(Ce(h,n),{loginId:t,user:o,loginOptions:r}))))})),{}),signUpOrIn:Object.keys(it).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Pt(((t,o)=>Te(e.post(Ce(m,n),{loginId:t,loginOptions:o}))))})),{}),update:{email:Ct(((t,n,o,r)=>Te(e.post(v.email,Object.assign({loginId:t,email:n},r),{token:o})))),phone:Object.keys(ot).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:xt(((t,o,r,i)=>Te(e.post(Ce(v.phone,n),Object.assign({loginId:t,phone:o},i),{token:r}))))})),{})}}),Et=Ze(Ye("tenant")),$t=Ze(Ye("code")),At=e=>({start:Et(((t,n,o,r,i)=>Te(e.post($,o||{},Object.assign({queryParams:Object.assign(Object.assign({tenant:t},n&&{redirectURL:n}),i&&{ssoId:i})},r&&{token:r}))))),exchange:$t((t=>Te(e.post(A,{code:t}))))}),Dt=Ye("loginId"),qt=Ze(Dt,Ye("code")),Lt=Ze(Dt),_t=Ze(Dt),Nt=e=>({signUp:Lt(((t,n)=>Te(e.post(q,{loginId:t,user:n})))),verify:qt(((t,n,o,r)=>Te(e.post(D,{loginId:t,code:n,loginOptions:o},{token:r})))),update:_t(((t,n)=>Te(e.post(L,{loginId:t},{token:n}))))}),Mt=Ye("loginId"),Jt=Ye("newPassword"),Kt=Ze(Mt,Ye("password")),Ht=Ze(Mt),Vt=Ze(Mt,Jt),Bt=Ze(Mt,Ye("oldPassword"),Jt),Ft=e=>({signUp:Kt(((t,n,o,r)=>Te(e.post(F,{loginId:t,password:n,user:o,loginOptions:r})))),signIn:Kt(((t,n,o)=>Te(e.post(z,{loginId:t,password:n,loginOptions:o})))),sendReset:Ht(((t,n,o)=>Te(e.post(Z,{loginId:t,redirectUrl:n,templateOptions:o})))),update:Vt(((t,n,o)=>Te(e.post(G,{loginId:t,newPassword:n},{token:o})))),replace:Bt(((t,n,o)=>Te(e.post(Y,{loginId:t,oldPassword:n,newPassword:o})))),policy:()=>Te(e.get(X))}),zt=Ge("loginId"),Zt=Ye("loginId"),Gt=Ye("origin"),Yt=Ze(Zt,Gt,Ye("name")),Xt=Ze(Zt,Gt),Qt=Ze(zt,Gt),Wt=Ze(Zt,Gt,Ye("token")),en=Ze(Ye("transactionId"),Ye("response")),tn=e=>({signUp:{start:Yt(((t,n,o,r)=>Te(e.post(K.start,{user:{loginId:t,name:o},origin:n,passkeyOptions:r})))),finish:en(((t,n)=>Te(e.post(K.finish,{transactionId:t,response:n}))))},signIn:{start:Qt(((t,n,o,r,i)=>Te(e.post(H.start,{loginId:t,origin:n,loginOptions:o,passkeyOptions:i},{token:r})))),finish:en(((t,n)=>Te(e.post(H.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:Xt(((t,n,o)=>Te(e.post(V.start,{loginId:t,origin:n,passkeyOptions:o}))))},update:{start:Wt(((t,n,o,r)=>Te(e.post(B.start,{loginId:t,origin:n,passkeyOptions:r},{token:o})))),finish:en(((t,n)=>Te(e.post(B.finish,{transactionId:t,response:n}))))}}),nn=Ge("loginId"),on=Ze(nn),rn=Ze(Ye("pendingRef")),sn=e=>({signUpOrIn:on(((t,n)=>Te(e.post(M,{loginId:t,loginOptions:n})))),signUp:on(((t,n,o)=>Te(e.post(N,{loginId:t,user:n,loginOptions:o})))),signIn:on(((t,n,o)=>Te(e.post(_,{loginId:t,loginOptions:n},{token:o})))),waitForSession:rn(((t,n)=>new Promise((o=>{const{pollingIntervalMs:r,timeoutMs:i}=nt(n);let s;const a=setInterval((async()=>{const n=await e.post(J,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),o(Te(Promise.resolve(n))))}),r);s=setTimeout((()=>{o({error:{errorDescription:`Session polling timeout exceeded: ${i}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),i)}))))}),an=Ze(Ye("token")),cn=Ze([Fe('"token" must be string or undefined')]);var ln,un=Ze([(ln=Ye("projectId"),$e(((e,t)=>n=>De(...t).validate(((e,t)=>{const n=(Array.isArray(t)?t.join("."):String(t)).replace(/\[\\?("|')?(\w|d)+\\?("|')?\]/g,((e,t,n)=>"."+n)).split("."),o=n.length;let r=0,i=e===Object(e)?e:void 0;for(;null!=i&&r<o;)i=i[n[r++]];return r&&r===o&&void 0!==i?i:void 0})(n,e)))("projectId",ln))())])((e=>{var t;return(({projectId:e,logger:t,baseUrl:n,hooks:o,cookiePolicy:r,baseHeaders:i={},refreshCookieName:s,fetch:a})=>{return c=Ie({baseUrl:n||ce,projectId:e,logger:t,hooks:o,cookiePolicy:r,baseConfig:{baseHeaders:i},refreshCookieName:s,fetch:a}),{accessKey:et(c),otp:Tt(c),magicLink:It(c),enchantedLink:pt(c),oauth:St(c),saml:At(c),totp:Nt(c),notp:sn(c),webauthn:tn(c),password:Ft(c),flow:ht(c),refresh:cn(((e,t)=>Te(c.post(Q,{},{token:e,queryParams:t})))),selectTenant:Ze([Ke("tenantId")],[Fe('"token" must be string or undefined')])(((e,t)=>Te(c.post(W,{tenant:e},{token:t})))),logout:cn((e=>Te(c.post(ee,{},{token:e})))),logoutAll:cn((e=>Te(c.post(te,{},{token:e})))),me:cn((e=>Te(c.get(ne,{token:e})))),myTenants:Ze([ze('"tenants" must a string array or a boolean')],[Fe('"token" must be string or undefined')])(((e,t)=>{const n={};return"boolean"==typeof e?n.dct=e:n.ids=e,Te(c.post(oe,n,{token:t}))})),history:cn((e=>Te(c.get(re,{token:e})))),isJwtExpired:an(Ue),getTenants:an(Re),getJwtPermissions:an(Pe),getJwtRoles:an(xe),getCurrentTenant:an(Ee),httpClient:c};var c})(Object.assign(Object.assign({},e),{hooks:{beforeRequest:t=>{var n;const o=[].concat((null===(n=e.hooks)||void 0===n?void 0:n.beforeRequest)||[]);return null==o?void 0:o.reduce(((e,t)=>t(e)),t)},afterRequest:async(t,n)=>{var o;const r=[].concat((null===(o=e.hooks)||void 0===o?void 0:o.afterRequest)||[]);0!=r.length&&(await Promise.allSettled(null==r?void 0:r.map((e=>e(t,null==n?void 0:n.clone()))))).forEach((t=>{var n;return"rejected"===t.status&&(null===(n=e.logger)||void 0===n?void 0:n.error(t.reason))}))},transformResponse:null===(t=e.hooks)||void 0===t?void 0:t.transformResponse}}))})),dn=Object.assign(un,{DeliveryMethods:it});const pn=(...e)=>{console.debug(...e)},gn="undefined"!=typeof window,fn=Math.pow(2,31)-1,hn=e=>{let t=((n=e)?n.getTime()-(new Date).getTime():0)-2e4;var n;return t>fn&&(pn(`Timeout is too large (${t}ms), setting it to ${fn}ms`),t=fn),t};
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Descope=t()}(this,(function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,s=1,i=arguments.length;s<i;s++)for(var n in t=arguments[s])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},e.apply(this,arguments)};function t(e,t){var s={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(s[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++)t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(s[i[n]]=e[i[n]])}return s}"function"==typeof SuppressedError&&SuppressedError;class s extends Error{}function i(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let s=t.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s})))}(t)}catch(e){return atob(t)}}function n(e,t){if("string"!=typeof e)throw new s("Invalid token specified: must be a string");t||(t={});const n=!0===t.header?0:1,r=e.split(".")[n];if("string"!=typeof r)throw new s(`Invalid token specified: missing part #${n+1}`);let o;try{o=i(r)}catch(e){throw new s(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(o)}catch(e){throw new s(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}s.prototype.name="InvalidTokenError";const r=e=>{try{return n(e).exp}catch(e){return null}},o=e=>{const{refresh_expire_in:t,refresh_token:s}=e;return t?Math.floor(Date.now()/1e3)+t:r(s)},a=e=>{const{expires_in:t,expires_at:s,access_token:i}=e;return s||(t?Math.floor(Date.now()/1e3)+t:i?r(i):void 0)},c=(e,t)=>{var s;return["beforeRequest","afterRequest"].reduce(((s,i)=>{var n;return s[i]=[].concat((null===(n=e.hooks)||void 0===n?void 0:n[i])||[]).concat((null==t?void 0:t[i])||[]),s}),null!==(s=e.hooks)&&void 0!==s?s:e.hooks={}),e},d=async e=>{if(!(null==e?void 0:e.ok))return{};const s=await(null==e?void 0:e.clone().json());return(e=>{const{access_token:s,id_token:i,refresh_token:n,refresh_expire_in:r}=e,c=t(e,["access_token","id_token","refresh_token","refresh_expire_in"]);return Object.assign({sessionJwt:e.sessionJwt||s,idToken:i,refreshJwt:e.refreshJwt||n,sessionExpiration:e.sessionExpiration||a(e),cookieExpiration:e.cookieExpiration||o(e)},c)})((null==s?void 0:s.authInfo)||s||{})},l=async e=>{const t=await d(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)},u="undefined"!=typeof localStorage,h=(e,t)=>u&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),g=e=>u&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),p=e=>u&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e));var _={accessKey:{exchange:"/v1/auth/accesskey/exchange"},otp:{verify:"/v1/auth/otp/verify",signIn:"/v1/auth/otp/signin",signUp:"/v1/auth/otp/signup",update:{email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},signUpOrIn:"/v1/auth/otp/signup-in"},magicLink:{verify:"/v1/auth/magiclink/verify",signIn:"/v1/auth/magiclink/signin",signUp:"/v1/auth/magiclink/signup",update:{email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},signUpOrIn:"/v1/auth/magiclink/signup-in"},enchantedLink:{verify:"/v1/auth/enchantedlink/verify",signIn:"/v1/auth/enchantedlink/signin",signUp:"/v1/auth/enchantedlink/signup",session:"/v1/auth/enchantedlink/pending-session",update:{email:"/v1/auth/enchantedlink/update/email"},signUpOrIn:"/v1/auth/enchantedlink/signup-in"},oauth:{start:"/v1/auth/oauth/authorize",exchange:"/v1/auth/oauth/exchange",startNative:"v1/auth/oauth/native/start",finishNative:"v1/auth/oauth/native/finish",oneTap:{getOneTapClientId:"/v1/auth/onetap/clientid/{provider}",exchangeOneTapIDToken:"/v1/auth/onetap/idtoken/exchange",verifyOneTapIDToken:"/v1/auth/onetap/idtoken/verify"}},saml:{start:"/v1/auth/saml/authorize",exchange:"/v1/auth/saml/exchange"},totp:{verify:"/v1/auth/totp/verify",signUp:"/v1/auth/totp/signup",update:"/v1/auth/totp/update"},notp:{signIn:"/v1/auth/notp/whatsapp/signin",signUp:"/v1/auth/notp/whatsapp/signup",signUpOrIn:"/v1/auth/notp/whatsapp/signup-in",session:"/v1/auth/notp/pending-session"},webauthn:{signUp:{start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},signIn:{start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},signUpOrIn:{start:"/v1/auth/webauthn/signup-in/start"},update:{start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"}},password:{signUp:"/v1/auth/password/signup",signIn:"/v1/auth/password/signin",sendReset:"/v1/auth/password/reset",update:"/v1/auth/password/update",replace:"/v1/auth/password/replace",policy:"/v1/auth/password/policy"},refresh:"/v1/auth/refresh",selectTenant:"/v1/auth/tenant/select",logout:"/v1/auth/logout",logoutAll:"/v1/auth/logoutall",me:"/v1/auth/me",myTenants:"/v1/auth/me/tenants",history:"/v1/auth/me/history",flow:{start:"/v1/flow/start",next:"/v1/flow/next"}};const w="<region>",f=`https://api.${w}descope.com`,m=6e5,v="dct",y=()=>{const e={};return{headers(t){const s="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(s),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}};let S;const k=()=>{if(S)return S;const e=new Date,t=`${e.getUTCFullYear().toString()}-${(e.getUTCMonth()+1).toString().padStart(2,"0")}-${e.getUTCDate().toString().padStart(2,"0")}-${e.getUTCHours().toString().padStart(2,"0")}:${e.getUTCMinutes().toString().padStart(2,"0")}:${e.getUTCSeconds().toString().padStart(2,"0")}:${e.getUTCMilliseconds().toString()}`,s=Math.floor(1e3+9e3*Math.random());return S=`${t}-${s}`,S};var b,I;(I=b||(b={})).get="GET",I.delete="DELETE",I.post="POST",I.put="PUT",I.patch="PATCH";const T=({path:e,baseUrl:t,queryParams:s,projectId:i})=>{const n=i.slice(1,-27);t=t.replace(w,n?n+".":"");let r=e?`${t.replace(/\/$/,"")}/${null==e?void 0:e.replace(/^\//,"")}`:t;if(s){const e=Object.keys(s);e.forEach(((t,i)=>{r=`${r}${0===i?"?":""}${t}=${encodeURIComponent(s[t])}${i===e.length-1?"":"&"}`}))}return r},O=(...e)=>new Headers(e.reduce(((e,t)=>{const s=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return s.reduce(((t,[s,i])=>(e[s]=i,e)),e),e}),{})),x={"Content-Type":"application/json"},E=(e,t="")=>{let s=e;return t&&(s=s+":"+t),{Authorization:`Bearer ${s}`}},U=e=>{const t={"x-descope-sdk-session-id":k(),"x-descope-sdk-name":"core-js","x-descope-sdk-version":"2.40.0"};return e&&(t["x-descope-refresh-cookie-name"]=e),t},R=e=>{try{e=JSON.parse(e)}catch(e){return!1}return"object"==typeof e&&null!==e},P=({baseUrl:e,projectId:t,baseConfig:s,refreshCookieName:i,logger:n,hooks:r,cookiePolicy:o,fetch:a})=>{const c=((e,t)=>{const s=(e=>async(...t)=>{const s=await e(...t),i=await s.text();return s.text=()=>Promise.resolve(i),s.json=()=>Promise.resolve(JSON.parse(i)),s.clone=()=>s,s})(t||fetch);return s||null==e||e.warn("Fetch is not defined, you will not be able to send http requests, if you are running in a test, make sure fetch is defined globally"),e?async(...t)=>{if(!s)throw Error("Cannot send http request, fetch is not defined, if you are running in a test, make sure fetch is defined globally");e.log((e=>y().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const i=await s(...t);return e[i.ok?"log":"error"](await(async e=>{const t=await e.text();return y().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(i)),i}:s})(n,a),d=async n=>{var a;const d=(null==r?void 0:r.beforeRequest)?r.beforeRequest(n):n,{path:l,body:u,headers:h,queryParams:g,method:p,token:_}=d,w=(e=>void 0===e?void 0:JSON.stringify(e))(u),f={headers:O(E(t,_),U(i),(null==s?void 0:s.baseHeaders)||{},R(w)?x:{},h),method:p,body:w};null!==o&&(f.credentials=o||"include");const m=await c(T({path:l,baseUrl:e,queryParams:g,projectId:t}),f);if((null==r?void 0:r.afterRequest)&&await r.afterRequest(n,null==m?void 0:m.clone()),null==r?void 0:r.transformResponse){const e=await m.json(),t=((null===(a=m.headers)||void 0===a?void 0:a.get("set-cookie"))||"").split(";").reduce(((e,t)=>{const[s,i]=t.split("=");return Object.assign(Object.assign({},e),{[s.trim()]:i})}),{}),s=Object.assign(Object.assign({},m),{json:()=>Promise.resolve(e),cookies:t});return s.clone=()=>s,r.transformResponse(s)}return m};return{get:(e,{headers:t,queryParams:s,token:i}={})=>d({path:e,headers:t,queryParams:s,body:void 0,method:b.get,token:i}),post:(e,t,{headers:s,queryParams:i,token:n}={})=>d({path:e,headers:s,queryParams:i,body:t,method:b.post,token:n}),patch:(e,t,{headers:s,queryParams:i,token:n}={})=>d({path:e,headers:s,queryParams:i,body:t,method:b.patch,token:n}),put:(e,t,{headers:s,queryParams:i,token:n}={})=>d({path:e,headers:s,queryParams:i,body:t,method:b.put,token:n}),delete:(e,{headers:t,queryParams:s,token:i}={})=>d({path:e,headers:t,queryParams:s,body:void 0,method:b.delete,token:i}),hooks:r,buildUrl:(s,i)=>T({projectId:t,baseUrl:e,path:s,queryParams:i})}};var C=429;function j(e,t,s){var i;let n=A(e);if(t){if(!(null==n?void 0:n.tenants)&&(null==n?void 0:n[v])===t)return(null==n?void 0:n[s])||[];n=null===(i=null==n?void 0:n.tenants)||void 0===i?void 0:i[t]}const r=null==n?void 0:n[s];return Array.isArray(r)?r:[]}function A(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return n(e)}function q(e){const{exp:t}=A(e);return(new Date).getTime()/1e3>t}function N(e){let t=A(e);const s=Object.keys(null==t?void 0:t.tenants);return Array.isArray(s)?s:[]}function $(e,t){return j(e,t,"permissions")}function M(e,t){return j(e,t,"roles")}const D=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function L(e,t){var s;const i=await e,n={code:i.status,ok:i.ok,response:i},r=await i.clone().json();return i.ok?n.data=r:(n.error=r,i.status===C&&Object.assign(n.error,{retryAfter:Number.parseInt(null===(s=i.headers)||void 0===s?void 0:s.get("retry-after"))||0})),n}function H(e){var t;return(null===(t=A(e))||void 0===t?void 0:t[v])||""}const J=(e,t)=>(s=t)=>t=>!e(t)&&s.replace("{val}",t),K=(e,t)=>(s=t)=>t=>{const i=e.filter((e=>e(t)));return!(i.length<e.length)&&(s?s.replace("{val}",t):i.join(" OR "))},W=(...e)=>({validate:t=>(e.forEach((e=>{const s=e(t);if(s)throw new Error(s)})),!0)}),F=e=>t=>e.test(t),z=F(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),B=F(/^\+[1-9]{1}[0-9]{3,14}$/),V=J(z,'"{val}" is not a valid email'),Q=J(B,'"{val}" is not a valid phone number'),G=J((e=>e.length>=1),"Minimum length is 1");const Z=J((e=>"string"==typeof e),"Input is not a string"),Y=J((e=>Array.isArray(e)),"Input is not an array"),X=J((e=>"boolean"==typeof e),"Input is not a boolean"),ee=J((e=>void 0===e),"Input is defined"),te=K([Z(),ee()],"Input is not a string or undefined"),se=K([Y(),X()],"Input is not an array or boolean"),ie=(...e)=>t=>(...s)=>(e.forEach(((e,t)=>W(...e).validate(s[t]))),t(...s)),ne=e=>[Z(`"${e}" must be a string`)],re=e=>[te(`"${e}" must be string or undefined`)],oe=e=>[Z(`"${e}" must be a string`),G(`"${e}" must not be empty`)],ae=e=>[Z(`"${e}" must be a string`),V()],ce=e=>[Z(`"${e}" must be a string`),Q()],de=ie(oe("accessKey")),le=e=>({exchange:de(((t,s)=>L(e.post(_.accessKey.exchange,{loginOptions:s},{token:t}))))}),ue=(e,t,s)=>(t.forEach((t=>{const i=t.split(".");let n=i.shift(),r=e;for(;i.length>0;){if(r=r[n],!n||!r)throw Error(`Invalid path "${t}", "${n}" is missing or has no value`);n=i.shift()}if("function"!=typeof r[n])throw Error(`"${t}" is not a function`);const o=r[n];r[n]=s(o)})),e),he=({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||m,m)});var ge,pe;!function(e){e.sms="sms",e.voice="voice",e.whatsapp="whatsapp"}(ge||(ge={})),function(e){e.email="email"}(pe||(pe={}));const _e=Object.assign(Object.assign({},ge),pe);var we;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(we||(we={}));const fe=oe("loginId"),me=ie(oe("token")),ve=ie(fe),ye=ie(oe("pendingRef")),Se=ie(fe,ae("email")),ke=e=>({verify:me((t=>L(e.post(_.enchantedLink.verify,{token:t})))),signIn:ve(((t,s,i,n)=>L(e.post(D(_.enchantedLink.signIn,_e.email),{loginId:t,URI:s,loginOptions:i},{token:n})))),signUpOrIn:ve(((t,s,i)=>L(e.post(D(_.enchantedLink.signUpOrIn,_e.email),{loginId:t,URI:s,loginOptions:i})))),signUp:ve(((t,s,i,n)=>L(e.post(D(_.enchantedLink.signUp,_e.email),{loginId:t,URI:s,user:i,loginOptions:n})))),waitForSession:ye(((t,s)=>new Promise((i=>{const{pollingIntervalMs:n,timeoutMs:r}=he(s);let o;const a=setInterval((async()=>{const s=await e.post(_.enchantedLink.session,{pendingRef:t});s.ok&&(clearInterval(a),o&&clearTimeout(o),i(L(Promise.resolve(s))))}),n);o=setTimeout((()=>{i({error:{errorDescription:`Session polling timeout exceeded: ${r}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),r)})))),update:{email:Se(((t,s,i,n,r)=>L(e.post(_.enchantedLink.update.email,Object.assign({loginId:t,email:s,URI:i},r),{token:n}))))}}),be=ie(oe("flowId")),Ie=ie(oe("executionId"),oe("stepId"),oe("interactionId")),Te=e=>({start:be(((t,s,i,n,r,o,a)=>L(e.post(_.flow.start,{flowId:t,options:s,conditionInteractionId:i,interactionId:n,componentsVersion:r,flowVersions:o,input:a})))),next:Ie(((t,s,i,n,r,o)=>L(e.post(_.flow.next,{executionId:t,stepId:s,interactionId:i,version:n,componentsVersion:r,input:o}))))}),Oe=oe("loginId"),xe=ie(oe("token")),Ee=ie(Oe),Ue=ie(Oe,ce("phone")),Re=ie(Oe,ae("email")),Pe=Object.keys(_e).filter((e=>e!==ge.voice)),Ce=e=>({verify:xe((t=>L(e.post(_.magicLink.verify,{token:t})))),signIn:Pe.reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Ee(((t,i,n,r)=>L(e.post(D(_.magicLink.signIn,s),{loginId:t,URI:i,loginOptions:n},{token:r}))))})),{}),signUp:Pe.reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Ee(((t,i,n,r)=>L(e.post(D(_.magicLink.signUp,s),{loginId:t,URI:i,user:n,loginOptions:r}))))})),{}),signUpOrIn:Pe.reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Ee(((t,i,n)=>L(e.post(D(_.magicLink.signUpOrIn,s),{loginId:t,URI:i,loginOptions:n}))))})),{}),update:{email:Re(((t,s,i,n,r)=>L(e.post(_.magicLink.update.email,Object.assign({loginId:t,email:s,URI:i},r),{token:n})))),phone:Object.keys(ge).filter((e=>e!==ge.voice)).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Ue(((t,i,n,r,o)=>L(e.post(D(_.magicLink.update.phone,s),Object.assign({loginId:t,phone:i,URI:n},o),{token:r}))))})),{})}});var je;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple",e.discord="discord",e.linkedin="linkedin",e.slack="slack"}(je||(je={}));const Ae=ie(oe("code")),qe=e=>({start:Object.assign(((t,s,i,n)=>L(e.post(_.oauth.start,i||{},{queryParams:Object.assign({provider:t},s&&{redirectURL:s}),token:n}))),Object.keys(je).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:(t,i,n)=>L(e.post(_.oauth.start,i||{},{queryParams:Object.assign({provider:s},t&&{redirectURL:t}),token:n}))})),{})),exchange:Ae((t=>L(e.post(_.oauth.exchange,{code:t})))),startNative:(t,s,i)=>L(e.post(_.oauth.startNative,{provider:t,loginOptions:s,implicit:i})),finishNative:(t,s,i,n,r)=>L(e.post(_.oauth.finishNative,{provider:t,stateId:s,user:i,code:n,idToken:r})),getOneTapClientId:t=>L(e.get(_.oauth.oneTap.getOneTapClientId.replace("{provider}",t))),verifyOneTapIDToken:(t,s,i,n)=>L(e.post(_.oauth.oneTap.verifyOneTapIDToken,{provider:t,idToken:s,nonce:i,loginOptions:n})),exchangeOneTapIDToken:(t,s,i,n)=>L(e.post(_.oauth.oneTap.exchangeOneTapIDToken,{provider:t,idToken:s,nonce:i,loginOptions:n}))}),Ne=oe("loginId"),$e=ie(Ne,oe("code")),Me=ie(Ne),De=ie(Ne,ce("phone")),Le=ie(Ne,ae("email")),He=e=>({verify:Object.keys(_e).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:$e(((t,i)=>L(e.post(D(_.otp.verify,s),{code:i,loginId:t}))))})),{}),signIn:Object.keys(_e).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Me(((t,i,n)=>L(e.post(D(_.otp.signIn,s),{loginId:t,loginOptions:i},{token:n}))))})),{}),signUp:Object.keys(_e).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Me(((t,i,n)=>L(e.post(D(_.otp.signUp,s),{loginId:t,user:i,loginOptions:n}))))})),{}),signUpOrIn:Object.keys(_e).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Me(((t,i)=>L(e.post(D(_.otp.signUpOrIn,s),{loginId:t,loginOptions:i}))))})),{}),update:{email:Le(((t,s,i,n)=>L(e.post(_.otp.update.email,Object.assign({loginId:t,email:s},n),{token:i})))),phone:Object.keys(ge).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:De(((t,i,n,r)=>L(e.post(D(_.otp.update.phone,s),Object.assign({loginId:t,phone:i},r),{token:n}))))})),{})}}),Je=ie(oe("tenant")),Ke=ie(oe("code")),We=e=>({start:Je(((t,s,i,n,r)=>L(e.post(_.saml.start,i||{},Object.assign({queryParams:Object.assign(Object.assign({tenant:t},s&&{redirectURL:s}),r&&{ssoId:r})},n&&{token:n}))))),exchange:Ke((t=>L(e.post(_.saml.exchange,{code:t}))))}),Fe=oe("loginId"),ze=ie(Fe,oe("code")),Be=ie(Fe),Ve=ie(Fe),Qe=e=>({signUp:Be(((t,s)=>L(e.post(_.totp.signUp,{loginId:t,user:s})))),verify:ze(((t,s,i,n)=>L(e.post(_.totp.verify,{loginId:t,code:s,loginOptions:i},{token:n})))),update:Ve(((t,s)=>L(e.post(_.totp.update,{loginId:t},{token:s}))))}),Ge=oe("loginId"),Ze=oe("newPassword"),Ye=ie(Ge,oe("password")),Xe=ie(Ge),et=ie(Ge,Ze),tt=ie(Ge,oe("oldPassword"),Ze),st=e=>({signUp:Ye(((t,s,i,n)=>L(e.post(_.password.signUp,{loginId:t,password:s,user:i,loginOptions:n})))),signIn:Ye(((t,s,i)=>L(e.post(_.password.signIn,{loginId:t,password:s,loginOptions:i})))),sendReset:Xe(((t,s,i)=>L(e.post(_.password.sendReset,{loginId:t,redirectUrl:s,templateOptions:i})))),update:et(((t,s,i)=>L(e.post(_.password.update,{loginId:t,newPassword:s},{token:i})))),replace:tt(((t,s,i)=>L(e.post(_.password.replace,{loginId:t,oldPassword:s,newPassword:i})))),policy:()=>L(e.get(_.password.policy))}),it=ne("loginId"),nt=oe("loginId"),rt=oe("origin"),ot=ie(nt,rt,oe("name")),at=ie(nt,rt),ct=ie(it,rt),dt=ie(nt,rt,re("token")),lt=ie(oe("transactionId"),oe("response")),ut=e=>({signUp:{start:ot(((t,s,i,n)=>L(e.post(_.webauthn.signUp.start,{user:{loginId:t,name:i},origin:s,passkeyOptions:n})))),finish:lt(((t,s)=>L(e.post(_.webauthn.signUp.finish,{transactionId:t,response:s}))))},signIn:{start:ct(((t,s,i,n,r)=>L(e.post(_.webauthn.signIn.start,{loginId:t,origin:s,loginOptions:i,passkeyOptions:r},{token:n})))),finish:lt(((t,s)=>L(e.post(_.webauthn.signIn.finish,{transactionId:t,response:s}))))},signUpOrIn:{start:at(((t,s,i)=>L(e.post(_.webauthn.signUpOrIn.start,{loginId:t,origin:s,passkeyOptions:i}))))},update:{start:dt(((t,s,i,n)=>L(e.post(_.webauthn.update.start,{loginId:t,origin:s,passkeyOptions:n},{token:i})))),finish:lt(((t,s)=>L(e.post(_.webauthn.update.finish,{transactionId:t,response:s}))))}}),ht=ne("loginId"),gt=ie(ht),pt=ie(oe("pendingRef")),_t=e=>({signUpOrIn:gt(((t,s)=>L(e.post(_.notp.signUpOrIn,{loginId:t,loginOptions:s})))),signUp:gt(((t,s,i)=>L(e.post(_.notp.signUp,{loginId:t,user:s,loginOptions:i})))),signIn:gt(((t,s,i)=>L(e.post(_.notp.signIn,{loginId:t,loginOptions:s},{token:i})))),waitForSession:pt(((t,s)=>new Promise((i=>{const{pollingIntervalMs:n,timeoutMs:r}=he(s);let o;const a=setInterval((async()=>{const s=await e.post(_.notp.session,{pendingRef:t});s.ok&&(clearInterval(a),o&&clearTimeout(o),i(L(Promise.resolve(s))))}),n);o=setTimeout((()=>{i({error:{errorDescription:`Session polling timeout exceeded: ${r}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),r)}))))}),wt=ie(oe("token")),ft=ie(re("token"));var mt,vt=ie([(mt=oe("projectId"),J(((e,t)=>s=>W(...t).validate(((e,t)=>{const s=(Array.isArray(t)?t.join("."):String(t)).replace(/\[\\?("|')?(\w|d)+\\?("|')?\]/g,((e,t,s)=>"."+s)).split("."),i=s.length;let n=0,r=e===Object(e)?e:void 0;for(;null!=r&&n<i;)r=r[s[n++]];return n&&n===i&&void 0!==r?r:void 0})(s,e)))("projectId",mt))())])((e=>t=>{var s;return e(Object.assign(Object.assign({},t),{hooks:{beforeRequest:e=>{var s;const i=[].concat((null===(s=t.hooks)||void 0===s?void 0:s.beforeRequest)||[]);return null==i?void 0:i.reduce(((e,t)=>t(e)),e)},afterRequest:async(e,s)=>{var i;const n=[].concat((null===(i=t.hooks)||void 0===i?void 0:i.afterRequest)||[]);0!=n.length&&(await Promise.allSettled(null==n?void 0:n.map((t=>t(e,null==s?void 0:s.clone()))))).forEach((e=>{var s;return"rejected"===e.status&&(null===(s=t.logger)||void 0===s?void 0:s.error(e.reason))}))},transformResponse:null===(s=t.hooks)||void 0===s?void 0:s.transformResponse}}))})((({projectId:e,logger:t,baseUrl:s,hooks:i,cookiePolicy:n,baseHeaders:r={},refreshCookieName:o,fetch:a})=>{return c=P({baseUrl:s||f,projectId:e,logger:t,hooks:i,cookiePolicy:n,baseConfig:{baseHeaders:r},refreshCookieName:o,fetch:a}),{accessKey:le(c),otp:He(c),magicLink:Ce(c),enchantedLink:ke(c),oauth:qe(c),saml:We(c),totp:Qe(c),notp:_t(c),webauthn:ut(c),password:st(c),flow:Te(c),refresh:ft(((e,t)=>L(c.post(_.refresh,{},{token:e,queryParams:t})))),selectTenant:ie([Z("tenantId")],[te('"token" must be string or undefined')])(((e,t)=>L(c.post(_.selectTenant,{tenant:e},{token:t})))),logout:ft((e=>L(c.post(_.logout,{},{token:e})))),logoutAll:ft((e=>L(c.post(_.logoutAll,{},{token:e})))),me:ft((e=>L(c.get(_.me,{token:e})))),myTenants:ie([se('"tenants" must a string array or a boolean')],[te('"token" must be string or undefined')])(((e,t)=>{const s={};return"boolean"==typeof e?s.dct=e:s.ids=e,L(c.post(_.myTenants,s,{token:t}))})),history:ft((e=>L(c.get(_.history,{token:e})))),isJwtExpired:wt(q),getTenants:wt(N),getJwtPermissions:wt($),getJwtRoles:wt(M),getCurrentTenant:wt(H),httpClient:c};var c}))),yt=Object.assign(vt,{DeliveryMethods:_e});const St=(...e)=>{console.debug(...e)},kt="3.2.0",bt="undefined"!=typeof window,It=Math.pow(2,31)-1,Tt=`https://descopecdn.com/npm/oidc-client-ts@${kt}/dist/browser/oidc-client-ts.min.js`,Ot=`https://cdn.jsdelivr.net/npm/oidc-client-ts@${kt}/dist/browser/oidc-client-ts.min.js`,xt=e=>{let t=((s=e)?s.getTime()-(new Date).getTime():0)-2e4;var s;return t>It&&(St(`Timeout is too large (${t}ms), setting it to ${It}ms`),t=It),t};
2
2
  /*! js-cookie v3.0.5 | MIT */
3
- function vn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)e[o]=n[o]}return e}var mn=function e(t,n){function o(e,o,r){if("undefined"!=typeof document){"number"==typeof(r=vn({},n,r)).expires&&(r.expires=new Date(Date.now()+864e5*r.expires)),r.expires&&(r.expires=r.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var s in r)r[s]&&(i+="; "+s,!0!==r[s]&&(i+="="+r[s].split(";")[0]));return document.cookie=e+"="+t.write(o,e)+i}}return Object.create({set:o,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],o={},r=0;r<n.length;r++){var i=n[r].split("="),s=i.slice(1).join("=");try{var a=decodeURIComponent(i[0]);if(o[a]=t.read(s,a),e===a)break}catch(e){}}return e?o[e]:o}},remove:function(e,t){o(e,"",vn({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,vn({},this.attributes,t))},withConverter:function(t){return e(vn({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const bn="DS",wn="DSR";function yn(e,t,{cookiePath:n,cookieDomain:o,cookieExpiration:r,cookieSameSite:i="Strict",cookieSecure:s=!0}){if(t){const a=new Date(1e3*r),c=function(e){const t=window.location.hostname.split("."),n=e.split(".");return t.slice(-n.length).join(".")===e}(o);mn.set(e,t,{path:n,domain:c?o:void 0,expires:a,sameSite:i,secure:s})}}function kn(e=""){return i(`${e}${wn}`)||""}function In(e=""){return mn.get(bn)||i(`${e}${bn}`)||""}function On(e=""){s(`${e}${wn}`),s(`${e}${bn}`),mn.remove(bn)}const jn=gn&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",Sn="vsid",Un="vrid";var Rn={default:"endpoint"},Pn="Blocked by CSP",xn="The endpoint parameter is not a valid URL",Cn="Failed to load the JS script of the agent",Tn="9319";function En(e,t){var n,o,r,i,s,a=[],c=(n=function(e){var t=function(e,t,n){if(n||2===arguments.length)for(var o,r=0,i=t.length;r<i;r++)!o&&r in t||(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}([],e,!0);return{current:function(){return t[0]},postpone:function(){var e=t.shift();void 0!==e&&t.push(e)},exclude:function(){t.shift()}}}(e),i=0,o=function(){return Math.random()*Math.min(3e3,100*Math.pow(2,i++))},r=new Set,[n.current(),function(e,t){var i,s=t instanceof Error?t.message:"";if(s===Pn||s===xn)n.exclude(),i=0;else if(s===Tn)n.exclude();else if(s===Cn){var a=Date.now()-e.getTime()<50,c=n.current();c&&a&&!r.has(c)&&(r.add(c),i=0),n.postpone()}else n.postpone();var l=n.current();return void 0===l?void 0:[l,null!=i?i:e.getTime()+o()-Date.now()]}]),l=c[0],u=c[1];if(void 0===l)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var d=function(e){var n=new Date,o=function(t){return a.push({url:e,startedAt:n,finishedAt:new Date,error:t})},r=t(e);return r.then((function(){return o()}),o),r.catch((function(e){if(null!=s||(s=e),a.length>=5)throw s;var t=u(n,e);if(!t)throw s;var o,r=t[0],i=t[1];return(o=i,new Promise((function(e){return setTimeout(e,o)}))).then((function(){return d(r)}))}))};return d(l).then((function(e){return[e,a]}))}var $n="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",An=$n;function Dn(e){var t;e.scriptUrlPattern;var n=e.token,o=e.apiKey,r=void 0===o?n:o,i=c(e,["scriptUrlPattern","token","apiKey"]),s=null!==(t=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(e,"scriptUrlPattern"))&&void 0!==t?t:$n,l=function(){var e=[],t=function(){e.push({time:new Date,state:document.visibilityState})},n=function(e,t,n,o){return e.addEventListener(t,n,o),function(){return e.removeEventListener(t,n,o)}}(document,"visibilitychange",t);return t(),[e,n]}(),u=l[0],d=l[1];return Promise.resolve().then((function(){if(!r||"string"!=typeof r)throw new Error("API key required");var e=function(e,t){return(Array.isArray(e)?e:[e]).map((function(e){return function(e,t){var n=encodeURIComponent;return e.replace(/<[^<>]+>/g,(function(e){return"<version>"===e?"3":"<apiKey>"===e?n(t):"<loaderVersion>"===e?n("3.11.6"):e}))}(String(e),t)}))}(s,r);return En(e,qn)})).catch((function(e){throw d(),function(e){return e instanceof Error&&e.message===Tn?new Error(Cn):e}(e)})).then((function(e){var t=e[0],n=e[1];return d(),t.load(a(a({},i),{ldi:{attempts:n,visibilityStates:u}}))}))}function qn(e){return function(e,t,n){var o,r=document,i="securitypolicyviolation",s=function(t){var n=new URL(e,location.href),r=t.blockedURI;r!==n.href&&r!==n.protocol.slice(0,-1)&&r!==n.origin||(o=t,a())};r.addEventListener(i,s);var a=function(){return r.removeEventListener(i,s)};return Promise.resolve().then(t).then((function(e){return a(),e}),(function(e){return new Promise((function(e){var t=new MessageChannel;t.port1.onmessage=function(){return e()},t.port2.postMessage(null)})).then((function(){if(a(),o)return n(o);throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,n){if(function(e){if(URL.prototype)try{return new URL(e,location.href),!1}catch(e){if(e instanceof Error&&"TypeError"===e.name)return!0;throw e}}(e))throw new Error(xn);var o=document.createElement("script"),r=function(){var e;return null===(e=o.parentNode)||void 0===e?void 0:e.removeChild(o)},i=document.head||document.getElementsByTagName("head")[0];o.onload=function(){r(),t()},o.onerror=function(){r(),n(new Error(Cn))},o.async=!0,o.src=e,i.appendChild(o)}))}(e)}),(function(){throw new Error(Pn)})).then(Ln)}function Ln(){var e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n,o=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==o?void 0:o.configurable)?delete e[t]:o&&!o.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error(Tn);return n}const _n=(e=!1)=>{const t=localStorage.getItem("fp");if(!t)return null;const n=JSON.parse(t);return(new Date).getTime()>n.expiry&&!e?null:n.value},Nn=async(e,t=jn)=>{try{if(_n())return;const n=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),o=new URL(t);o.pathname="/fXj8gt3x8VulJBna/x96Emn69oZwcd7I6";const r=new URL(t);r.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const i=r.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",s=Dn({apiKey:e,endpoint:[o.toString(),Rn],scriptUrlPattern:[i,An]}),a=await s,{requestId:c}=await a.get({linkedId:n}),l=((e,t)=>({[Sn]:e,[Un]:t}))(n,c);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem("fp",JSON.stringify(t))})(l)}catch(e){console.warn("Could not load fingerprint",e)}},Mn=e=>{const t=_n(!0);return t&&e.body&&(e.body.fpData=t),e},Jn="dls_last_user_login_id",Kn="dls_last_user_display_name",Hn=()=>i(Jn),Vn=()=>i(Kn),Bn=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,r=Hn(),i=Vn();r&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=r,o.lastAuth.name=i);return await e(...t)},Fn=e=>t=>async(...n)=>{const o=await t(...n);return e||(s(Jn),s(Kn)),o};function zn(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const Zn=e=>t=>async(...n)=>{const o=await t(...n);return On(e),o};async function Gn(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=to(n.publicKey.challenge),n.publicKey.user.id=to(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=to(e.id)})),n}(e),n=await navigator.credentials.create(t);return o=n,JSON.stringify({id:o.id,rawId:no(o.rawId),type:o.type,response:{attestationObject:no(o.response.attestationObject),clientDataJSON:no(o.response.clientDataJSON)}});var o}async function Yn(e){const t=Wn(e);return eo(await navigator.credentials.get(t))}async function Xn(e,t){const n=Wn(e);n.signal=t.signal,n.mediation="conditional";return eo(await navigator.credentials.get(n))}async function Qn(e=!1){if(!gn)return Promise.resolve(!1);const t=!!(window.PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function Wn(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=to(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=to(e.id)})),n}function eo(e){return JSON.stringify({id:e.id,rawId:no(e.rawId),type:e.type,response:{authenticatorData:no(e.response.authenticatorData),clientDataJSON:no(e.response.clientDataJSON),signature:no(e.response.signature),userHandle:e.response.userHandle?no(e.response.userHandle):void 0}})}function to(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function no(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var oo,ro=(oo=e=>({async signUp(t,n,o){const r=await e.webauthn.signUp.start(t,window.location.origin,n,o);if(!r.ok)return r;const i=await Gn(r.data.options);return await e.webauthn.signUp.finish(r.data.transactionId,i)},async signIn(t,n){const o=await e.webauthn.signIn.start(t,window.location.origin,void 0,void 0,n);if(!o.ok)return o;const r=await Yn(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,r)},async signUpOrIn(t,n){var o;const r=await e.webauthn.signUpOrIn.start(t,window.location.origin,n);if(!r.ok)return r;if(null===(o=r.data)||void 0===o?void 0:o.create){const t=await Gn(r.data.options);return await e.webauthn.signUp.finish(r.data.transactionId,t)}{const t=await Yn(r.data.options);return await e.webauthn.signIn.finish(r.data.transactionId,t)}},async update(t,n,o){const r=await e.webauthn.update.start(t,window.location.origin,n,o);if(!r.ok)return r;const i=await Gn(r.data.options);return await e.webauthn.update.finish(r.data.transactionId,i)},helpers:{create:Gn,get:Yn,isSupported:Qn,conditional:Xn}}),(...e)=>{const t=oo(...e);return Object.assign(t.signUp,e[0].webauthn.signUp),Object.assign(t.signIn,e[0].webauthn.signIn),Object.assign(t.signUpOrIn,e[0].webauthn.signUpOrIn),Object.assign(t.update,e[0].webauthn.update),t});const io={config:"/fedcm/config"},so=(e,t)=>({async oneTap(t,n,o,r,i){const s=null!=t?t:"google",a=await e.oauth.startNative(s,o,!0);if(!a.ok)return a;const{clientId:c,stateId:l,nonce:u}=a.data,d=await async function(){return new Promise(((e,t)=>{if(window.google)return void e(window.google.accounts.id);let n=document.getElementById("google-gsi-client-script");n||(n=document.createElement("script"),document.head.appendChild(n),n.async=!0,n.defer=!0,n.id="google-gsi-client-script",n.src="https://accounts.google.com/gsi/client"),n.onload=function(){window.google?e(window.google.accounts.id):t("Failed to load Google GSI client script - not loaded properly")},n.onerror=function(){t("Failed to load Google GSI client script - failed to load")}}))}();return new Promise((t=>{var o,a;d.initialize(Object.assign(Object.assign({},n),{itp_support:null===(o=null==n?void 0:n.itp_support)||void 0===o||o,use_fedcm_for_prompt:null===(a=null==n?void 0:n.use_fedcm_for_prompt)||void 0===a||a,client_id:c,callback:n=>{t(e.oauth.finishNative(s,l,"","",n.credential))},nonce:u})),d.prompt((e=>{var t,n;if(i&&(null==e?void 0:e.isDismissedMoment())){const n=null===(t=e.getDismissedReason)||void 0===t?void 0:t.call(e);null==i||i(n)}else if(r&&(null==e?void 0:e.isSkippedMoment())){const t=null===(n=e.getSkippedReason)||void 0===n?void 0:n.call(e);null==r||r(t)}else;}))}))},async launch(n){var o;const r={identity:{context:n||"signin",providers:[{configURL:e.httpClient.buildUrl(t+io.config),clientId:t}]}},i=await(null===(o=navigator.credentials)||void 0===o?void 0:o.get(r));return e.refresh(i.token)},isSupported:()=>gn&&"IdentityCredential"in window,async isLoggedIn(n){var o;const r=e.httpClient.buildUrl(t+io.config);try{const e={identity:{context:n||"signin",providers:[{configURL:r,clientId:t}]}},i=await(null===(o=navigator.credentials)||void 0===o?void 0:o.get(e));return!!i&&!!i.token}catch(e){return!1}}});var ao=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await Qn(),o=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n},startOptionsVersion:1});return t[1]=o,e.flow.start(...t)}});const co=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((t=>n=>{var{fpKey:o,fpLoad:r}=n,i=c(n,["fpKey","fpLoad"]);return gn?(o&&r&&Nn(o).catch((()=>null)),t(e(i,{beforeRequest:Mn}))):t(i)}),(n=>o=>{var{autoRefresh:r}=o,i=c(o,["autoRefresh"]);if(!r)return n(i);const{clearAllTimers:s,setTimer:a}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let l,u;gn&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&l&&new Date>l&&(pn("Expiration time passed, refreshing session"),p.refresh(kn()||u))}));const p=n(e(i,{afterRequest:async(e,n)=>{const{refreshJwt:o,sessionJwt:r,sessionExpiration:i}=await t(n);if(401===(null==n?void 0:n.status))pn("Received 401, canceling all timers"),s();else if(r||i){if(l=((e,t)=>{if(t)return new Date(1e3*t);pn("Could not extract expiration time from session token, trying to decode the token");try{const t=d(e);if(t.exp)return new Date(1e3*t.exp)}catch(e){return null}})(r,i),!l)return void pn("Could not extract expiration time from session token");u=o;const e=hn(l);if(s(),e<=2e4)return void pn("Session is too close to expiration, not setting refresh timer");const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});pn(`Setting refresh timer for ${t}. (${e}ms)`),a((()=>{pn("Refreshing session due to timer"),p.refresh(kn()||o)}),e)}}}));return tt(p,["logout","logoutAll"],(e=>async(...t)=>{const n=await e(...t);return pn("Clearing all timers"),s(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.27.2"},t.baseHeaders)}))),(o=>r=>{const i=zn(),s=zn(),a=zn(),c=o(e(r,{afterRequest:async(e,o)=>{if(401===(null==o?void 0:o.status))s.pub(null),a.pub(null),i.pub(null);else{const e=await n(o);e&&a.pub(e);const{sessionJwt:r,sessionExpiration:c}=await t(o);r&&s.pub(r),(c||r)&&i.pub(c||42)}}})),l=tt(c,["logout","logoutAll"],(e=>async(...t)=>{const n=await e(...t);return s.pub(null),a.pub(null),i.pub(null),n}));return Object.assign(l,{onSessionTokenChange:s.sub,onUserChange:a.sub,onIsAuthenticatedChange:e=>i.sub((t=>{e(!!t)}))})}),(t=>o=>{var{storeLastAuthenticatedUser:i=!0,keepLastAuthenticatedUserAfterLogout:s=!1}=o,a=c(o,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!i)return Object.assign(t(a),{getLastUserLoginId:Hn,getLastUserDisplayName:Vn});const l=t(e(a,{afterRequest:async(e,t)=>{var o;const i=await n(t),s=null===(o=null==i?void 0:i.loginIds)||void 0===o?void 0:o[0],a=null==i?void 0:i.name;s&&((e=>{r(Jn,e)})(s),(e=>{r(Kn,e)})(a))}}));let u=tt(l,["flow.start"],Bn);return u=tt(u,["logout","logoutAll"],Fn(s)),Object.assign(u,{getLastUserLoginId:Hn,getLastUserDisplayName:Vn})}),(n=>o=>{var{persistTokens:i,sessionTokenViaCookie:s,storagePrefix:a}=o,l=c(o,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!i||!gn)return n(l);const u=n(e(l,{beforeRequest:(d=a,e=>Object.assign(e,{token:e.token||kn(d)})),afterRequest:async(e,n)=>{const o=/^\/v\d+\/mgmt\//.test(e.path);401===(null==n?void 0:n.status)?o||On(a):((e={},t,n)=>{var o,{refreshJwt:i,sessionJwt:s}=e,a=c(e,["refreshJwt","sessionJwt"]);if(void 0===t&&(t=!1),void 0===n&&(n=""),i&&r(`${n}${wn}`,i),s)if(t){const e=t.sameSite||"Strict",n=null===(o=t.secure)||void 0===o||o;yn(bn,s,Object.assign(Object.assign({},a),{cookieSameSite:e,cookieSecure:n}))}else r(`${n}${bn}`,s)})(await t(n),s,a)}}));var d;const p=tt(u,["logout","logoutAll"],Zn(a));return Object.assign(p,{getRefreshToken:()=>kn(a),getSessionToken:()=>In(a)})}))(((...e)=>{const t=dn(...e);return Object.assign(Object.assign({},t),{refresh:e=>{const n=In(),o=kn();return t.refresh(e,{dcs:n?"t":"f",dcr:o?"t":"f"})},flow:ao(t),webauthn:ro(t),fedcm:so(t,e[0].projectId)})}));return co.REFRESH_TOKEN_KEY=wn,co.SESSION_TOKEN_KEY=bn,co}));
3
+ function Et(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)e[i]=s[i]}return e}var Ut=function e(t,s){function i(e,i,n){if("undefined"!=typeof document){"number"==typeof(n=Et({},s,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var r="";for(var o in n)n[o]&&(r+="; "+o,!0!==n[o]&&(r+="="+n[o].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+r}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var s=document.cookie?document.cookie.split("; "):[],i={},n=0;n<s.length;n++){var r=s[n].split("="),o=r.slice(1).join("=");try{var a=decodeURIComponent(r[0]);if(i[a]=t.read(o,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",Et({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,Et({},this.attributes,t))},withConverter:function(t){return e(Et({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(s)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const Rt="DS",Pt="DSR",Ct="DSI";function jt(e,t,s){if(t){const{cookieDomain:i,cookiePath:n,cookieSameSite:r,cookieExpiration:o,cookieSecure:a}=s,c=new Date(1e3*o),d=function(e){const t=window.location.hostname.split("."),s=e.split(".");return t.slice(-s.length).join(".")===e}(i);Ut.set(e,t,{path:n,domain:d?i:void 0,expires:c,sameSite:r,secure:a})}}function At(e=""){return g(`${e}${Pt}`)||""}function qt(e=""){return Ut.get(Rt)||g(`${e}${Rt}`)||""}function Nt(e=""){return g(`${e}${Ct}`)||""}function $t(e=""){p(`${e}${Pt}`),p(`${e}${Rt}`),p(`${e}${Ct}`),Ut.remove(Rt)}const Mt=bt&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://api.descope.com",Dt="vsid",Lt="vrid";var Ht={default:"endpoint"},Jt="Blocked by CSP",Kt="The endpoint parameter is not a valid URL",Wt="Failed to load the JS script of the agent",Ft="9319";function zt(e,t){var s,i,n,r,o,a=[],c=(s=function(e){var t=function(e,t,s){if(s||2===arguments.length)for(var i,n=0,r=t.length;n<r;n++)!i&&n in t||(i||(i=Array.prototype.slice.call(t,0,n)),i[n]=t[n]);return e.concat(i||Array.prototype.slice.call(t))}([],e,!0);return{current:function(){return t[0]},postpone:function(){var e=t.shift();void 0!==e&&t.push(e)},exclude:function(){t.shift()}}}(e),r=0,i=function(){return Math.random()*Math.min(3e3,100*Math.pow(2,r++))},n=new Set,[s.current(),function(e,t){var r,o=t instanceof Error?t.message:"";if(o===Jt||o===Kt)s.exclude(),r=0;else if(o===Ft)s.exclude();else if(o===Wt){var a=Date.now()-e.getTime()<50,c=s.current();c&&a&&!n.has(c)&&(n.add(c),r=0),s.postpone()}else s.postpone();var d=s.current();return void 0===d?void 0:[d,null!=r?r:e.getTime()+i()-Date.now()]}]),d=c[0],l=c[1];if(void 0===d)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var u=function(e){var s=new Date,i=function(t){return a.push({url:e,startedAt:s,finishedAt:new Date,error:t})},n=t(e);return n.then((function(){return i()}),i),n.catch((function(e){if(null!=o||(o=e),a.length>=5)throw o;var t=l(s,e);if(!t)throw o;var i,n=t[0],r=t[1];return(i=r,new Promise((function(e){return setTimeout(e,i)}))).then((function(){return u(n)}))}))};return u(d).then((function(e){return[e,a]}))}var Bt="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",Vt=Bt;function Qt(s){var i;s.scriptUrlPattern;var n=s.token,r=s.apiKey,o=void 0===r?n:r,a=t(s,["scriptUrlPattern","token","apiKey"]),c=null!==(i=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(s,"scriptUrlPattern"))&&void 0!==i?i:Bt,d=function(){var e=[],t=function(){e.push({time:new Date,state:document.visibilityState})},s=function(e,t,s,i){return e.addEventListener(t,s,i),function(){return e.removeEventListener(t,s,i)}}(document,"visibilitychange",t);return t(),[e,s]}(),l=d[0],u=d[1];return Promise.resolve().then((function(){if(!o||"string"!=typeof o)throw new Error("API key required");var e=function(e,t){return(Array.isArray(e)?e:[e]).map((function(e){return function(e,t){var s=encodeURIComponent;return e.replace(/<[^<>]+>/g,(function(e){return"<version>"===e?"3":"<apiKey>"===e?s(t):"<loaderVersion>"===e?s("3.11.6"):e}))}(String(e),t)}))}(c,o);return zt(e,Gt)})).catch((function(e){throw u(),function(e){return e instanceof Error&&e.message===Ft?new Error(Wt):e}(e)})).then((function(t){var s=t[0],i=t[1];return u(),s.load(e(e({},a),{ldi:{attempts:i,visibilityStates:l}}))}))}function Gt(e){return function(e,t,s){var i,n=document,r="securitypolicyviolation",o=function(t){var s=new URL(e,location.href),n=t.blockedURI;n!==s.href&&n!==s.protocol.slice(0,-1)&&n!==s.origin||(i=t,a())};n.addEventListener(r,o);var a=function(){return n.removeEventListener(r,o)};return Promise.resolve().then(t).then((function(e){return a(),e}),(function(e){return new Promise((function(e){var t=new MessageChannel;t.port1.onmessage=function(){return e()},t.port2.postMessage(null)})).then((function(){if(a(),i)return s(i);throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,s){if(function(e){if(URL.prototype)try{return new URL(e,location.href),!1}catch(e){if(e instanceof Error&&"TypeError"===e.name)return!0;throw e}}(e))throw new Error(Kt);var i=document.createElement("script"),n=function(){var e;return null===(e=i.parentNode)||void 0===e?void 0:e.removeChild(i)},r=document.head||document.getElementsByTagName("head")[0];i.onload=function(){n(),t()},i.onerror=function(){n(),s(new Error(Wt))},i.async=!0,i.src=e,r.appendChild(i)}))}(e)}),(function(){throw new Error(Jt)})).then(Zt)}function Zt(){var e=window,t="__fpjs_p_l_b",s=e[t];if(function(e,t){var s,i=null===(s=Object.getOwnPropertyDescriptor)||void 0===s?void 0:s.call(Object,e,t);(null==i?void 0:i.configurable)?delete e[t]:i&&!i.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==s?void 0:s.load))throw new Error(Ft);return s}const Yt=(e=!1)=>{const t=localStorage.getItem("fp");if(!t)return null;const s=JSON.parse(t);return(new Date).getTime()>s.expiry&&!e?null:s.value},Xt=async(e,t=Mt)=>{try{if(Yt())return;const s=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),i=new URL(t);i.pathname="/fXj8gt3x8VulJBna/x96Emn69oZwcd7I6";const n=new URL(t);n.pathname="/fXj8gt3x8VulJBna/w78aRZnnDZ3Aqw0I";const r=n.toString()+"?apiKey=<apiKey>&version=<version>&loaderVersion=<loaderVersion>",o=Qt({apiKey:e,endpoint:[i.toString(),Ht],scriptUrlPattern:[r,Vt]}),a=await o,{requestId:c}=await a.get({linkedId:s}),d=((e,t)=>({[Dt]:e,[Lt]:t}))(s,c);(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem("fp",JSON.stringify(t))})(d)}catch(e){console.warn("Could not load fingerprint",e)}},es=e=>{const t=Yt(!0);return t&&e.body&&(e.body.fpData=t),e},ts="dls_last_user_login_id",ss="dls_last_user_display_name",is=()=>g(ts),ns=()=>g(ss),rs=e=>async(...t)=>{var s;t[1]=t[1]||{};const[,i={}]=t,n=is(),r=ns();n&&(null!==(s=i.lastAuth)&&void 0!==s||(i.lastAuth={}),i.lastAuth.loginId=n,i.lastAuth.name=r);return await e(...t)},os=e=>t=>async(...s)=>{const i=await t(...s);return e||(p(ts),p(ss)),i};function as(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const s=e.push(t)-1;return()=>e.splice(s,1)}}}const cs=e=>t=>async(...s)=>{const i=await t(...s);return $t(e),i};async function ds(e){const t=function(e){var t;const s=JSON.parse(e);return s.publicKey.challenge=_s(s.publicKey.challenge),s.publicKey.user.id=_s(s.publicKey.user.id),null===(t=s.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=_s(e.id)})),s}(e),s=await navigator.credentials.create(t);return i=s,JSON.stringify({id:i.id,rawId:ws(i.rawId),type:i.type,response:{attestationObject:ws(i.response.attestationObject),clientDataJSON:ws(i.response.clientDataJSON)}});var i}async function ls(e){const t=gs(e);return ps(await navigator.credentials.get(t))}async function us(e,t){const s=gs(e);s.signal=t.signal,s.mediation="conditional";return ps(await navigator.credentials.get(s))}async function hs(e=!1){if(!bt)return Promise.resolve(!1);const t=!!(window.PublicKeyCredential&&navigator.credentials&&navigator.credentials.create&&navigator.credentials.get);return t&&e&&PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():t}function gs(e){var t;const s=JSON.parse(e);return s.publicKey.challenge=_s(s.publicKey.challenge),null===(t=s.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=_s(e.id)})),s}function ps(e){return JSON.stringify({id:e.id,rawId:ws(e.rawId),type:e.type,response:{authenticatorData:ws(e.response.authenticatorData),clientDataJSON:ws(e.response.clientDataJSON),signature:ws(e.response.signature),userHandle:e.response.userHandle?ws(e.response.userHandle):void 0}})}function _s(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function ws(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var fs,ms=(fs=e=>({async signUp(t,s,i){const n=await e.webauthn.signUp.start(t,window.location.origin,s,i);if(!n.ok)return n;const r=await ds(n.data.options);return await e.webauthn.signUp.finish(n.data.transactionId,r)},async signIn(t,s){const i=await e.webauthn.signIn.start(t,window.location.origin,void 0,void 0,s);if(!i.ok)return i;const n=await ls(i.data.options);return await e.webauthn.signIn.finish(i.data.transactionId,n)},async signUpOrIn(t,s){var i;const n=await e.webauthn.signUpOrIn.start(t,window.location.origin,s);if(!n.ok)return n;if(null===(i=n.data)||void 0===i?void 0:i.create){const t=await ds(n.data.options);return await e.webauthn.signUp.finish(n.data.transactionId,t)}{const t=await ls(n.data.options);return await e.webauthn.signIn.finish(n.data.transactionId,t)}},async update(t,s,i){const n=await e.webauthn.update.start(t,window.location.origin,s,i);if(!n.ok)return n;const r=await ds(n.data.options);return await e.webauthn.update.finish(n.data.transactionId,r)},helpers:{create:ds,get:ls,isSupported:hs,conditional:us}}),(...e)=>{const t=fs(...e);return Object.assign(t.signUp,e[0].webauthn.signUp),Object.assign(t.signIn,e[0].webauthn.signIn),Object.assign(t.signUpOrIn,e[0].webauthn.signUpOrIn),Object.assign(t.update,e[0].webauthn.update),t});const vs={config:"/fedcm/config"},ys=()=>{if(window.crypto&&window.crypto.getRandomValues){const e=new Uint8Array(16);return window.crypto.getRandomValues(e),Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("")}return Math.random().toString(36).substring(2)};async function Ss(e,t){var s,i,n;try{const n=await async function(e,t="google",s,i,n){const r=ys(),o=await async function(){return new Promise(((e,t)=>{if(window.google)return void e(window.google.accounts.id);let s=document.getElementById("google-gsi-client-script");s||(s=document.createElement("script"),document.head.appendChild(s),s.async=!0,s.defer=!0,s.id="google-gsi-client-script",s.src="https://accounts.google.com/gsi/client"),s.onload=function(){window.google?e(window.google.accounts.id):t("Failed to load Google GSI client script - not loaded properly")},s.onerror=function(){t("Failed to load Google GSI client script - failed to load")}}))}(),a=await e.oauth.getOneTapClientId(t);if(!a.ok)throw new Error("Failed to get OneTap client ID for provider "+t);const c=a.data.clientId;return new Promise((e=>{var a,d;const l=s=>{e({provider:t,nonce:r,credential:null==s?void 0:s.credential})};o.initialize(Object.assign(Object.assign({},s),{itp_support:null===(a=null==s?void 0:s.itp_support)||void 0===a||a,use_fedcm_for_prompt:null===(d=null==s?void 0:s.use_fedcm_for_prompt)||void 0===d||d,client_id:c,callback:l,nonce:r})),o.prompt((e=>{var t,s;if(n&&(null==e?void 0:e.isDismissedMoment())){const s=null===(t=e.getDismissedReason)||void 0===t?void 0:t.call(e);return null==n||n(s),void l()}if(i&&(null==e?void 0:e.isSkippedMoment())){const t=null===(s=e.getSkippedReason)||void 0===s?void 0:s.call(e);return null==i||i(t),void l()}}))}))}(e,t.provider,t.oneTapConfig,t.onSkipped,t.onDismissed);if(!n.credential)return null;if(null==t?void 0:t.onCodeReceived){const i=await e.oauth.verifyOneTapIDToken(n.provider,n.credential,n.nonce,null==t?void 0:t.loginOptions);if(!i.ok||!i.data)throw new Error("Failed to verify OneTap client ID for provider "+n.provider);null===(s=null==t?void 0:t.onCodeReceived)||void 0===s||s.call(t,i.data.code)}else{const s=await e.oauth.exchangeOneTapIDToken(n.provider,n.credential,n.nonce,null==t?void 0:t.loginOptions);if(!s.ok||!s.data)throw new Error("Failed to exchange OneTap client ID for provider "+n.provider);null===(i=null==t?void 0:t.onAuthenticated)||void 0===i||i.call(t,s.data)}}catch(e){null===(n=null==t?void 0:t.onFailed)||void 0===n||n.call(t,e)}}var ks=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const s=await hs(),i=Object.assign(Object.assign({location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:s},startOptionsVersion:1});return t[1]=i,e.flow.start(...t)}});let bs;const Is=(e,t)=>new Promise(((s,i)=>{if(!e.length)return i(new Error("No URLs provided to loadScriptWithFallback"));const n=t();if(n)return s(n);const r=e.shift(),o=document.createElement("script");o.src=r,o.id=(e=>{let t=0;for(let s=0;s<e.length;s++)t=(t<<5)-t+e.charCodeAt(s),t|=0;return Math.abs(t).toString(16)})(r),o.onload=()=>{const e=t();if(e)return s(e);throw new Error("Could not get entry after loading script from URL")},o.addEventListener("error",(()=>{Is(e,t),o.setAttribute("data-error","true")})),document.body.appendChild(o)}));const Ts=async(e,t,s)=>{bs||(bs=(async()=>{try{return Promise.resolve().then((function(){return Pi}))}catch(e){return Is([Tt,Ot],(()=>window.oidc))}})());const{OidcClient:i,WebStorageStateStore:n}=await bs;if(!i)throw new Error("oidc-client-ts is not installed. Please install it by running `npm install oidc-client-ts`");const r=t,o=(null==s?void 0:s.redirectUri)||window.location.href,a=(null==s?void 0:s.scope)||"openid email roles descope.custom_claims offline_access",c=`${r}_user`;let d=e.httpClient.buildUrl(t);(null==s?void 0:s.applicationId)&&(d=`${d}/${s.applicationId}`);const l={authority:d,client_id:t,redirect_uri:o,response_type:"code",scope:a,stateStore:new n({store:window.localStorage,prefix:r}),loadUserInfo:!0,fetchRequestCredentials:"same-origin"};return(null==s?void 0:s.redirectUri)&&(l.redirect_uri=s.redirectUri),(null==s?void 0:s.scope)&&(l.scope=s.scope),{client:new i(l),stateUserKey:c}},Os=(e,t,s)=>{const i=async()=>{let i,n;return i&&n||({client:i,stateUserKey:n}=await Ts(e,t,s)),{client:i,stateUserKey:n}},n=async(t="")=>{var s;const{client:n,stateUserKey:r}=await i(),o=await n.processSigninResponse(t||window.location.href);var a;return await(null===(s=e.httpClient.hooks)||void 0===s?void 0:s.afterRequest({},new Response(JSON.stringify(o)))),window.localStorage.setItem(r,JSON.stringify({id_token:(a=o).id_token,session_state:a.session_state,profile:a.profile})),(()=>{const e=new URL(window.location.href);e.searchParams.delete("code"),e.searchParams.delete("state"),window.history.replaceState({},document.title,e.toString())})(),o};return{loginWithRedirect:async(e={},t=!1)=>{const{client:s}=await i(),n=await s.createSigninRequest(e),{url:r}=n;return t||(window.location.href=r),{ok:!0,data:n}},finishLogin:n,finishLoginIfNeed:async(e="")=>{if(window.location.search.includes("code")&&window.location.search.includes("state"))return await n(e)},refreshToken:async t=>{var s;const{client:n,stateUserKey:r}=await i(),o=(e=>{const t=window.localStorage.getItem(e);return t?JSON.parse(t):null})(r);if(!o)throw new Error("User not found in storage to refresh token");let a=t;if(!a){const t={};e.httpClient.hooks.beforeRequest(t),a=t.token}const c=await n.useRefreshToken({state:{refresh_token:a,session_state:o.session_state,profile:o.profile}});return await(null===(s=e.httpClient.hooks)||void 0===s?void 0:s.afterRequest({},new Response(JSON.stringify(c)))),c},logout:async(e,t=!1)=>{const{client:s,stateUserKey:n}=await i();e||(e={}),e.id_token_hint=e.id_token_hint||Nt(),e.post_logout_redirect_uri=e.post_logout_redirect_uri||window.location.href;const r=await s.createSignoutRequest(e),{url:o}=r;return window.localStorage.removeItem(n),t||window.location.replace(o),r}}},xs=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>s=>{var{fpKey:i,fpLoad:n}=s,r=t(s,["fpKey","fpLoad"]);return bt?(i&&n&&Xt(i).catch((()=>null)),e(c(r,{beforeRequest:es}))):e(r)}),(e=>s=>{var{autoRefresh:i}=s,r=t(s,["autoRefresh"]);if(!i)return e(r);const{clearAllTimers:o,setTimer:a}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,s)=>{e.push(setTimeout(t,s))}}})();let l,u;bt&&document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&l&&new Date>l&&(St("Expiration time passed, refreshing session"),h.refresh(At()||u))}));const h=e(c(r,{afterRequest:async(e,t)=>{const{sessionJwt:s,refreshJwt:i,sessionExpiration:r}=await d(t);if(401===(null==t?void 0:t.status))St("Received 401, canceling all timers"),o();else if(s||r){if(l=((e,t)=>{if(t)return new Date(1e3*t);St("Could not extract expiration time from session token, trying to decode the token");try{const t=n(e);if(t.exp)return new Date(1e3*t.exp)}catch(e){return null}})(s,r),!l)return void St("Could not extract expiration time from session token");u=i;const e=xt(l);if(o(),e<=2e4)return void St("Session is too close to expiration, not setting refresh timer");const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});St(`Setting refresh timer for ${t}. (${e}ms)`),a((()=>{St("Refreshing session due to timer"),h.refresh(At()||i)}),e)}}}));return ue(h,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const s=await e(...t);return St("Clearing all timers"),o(),s}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.29.0"},t.baseHeaders)}))),(e=>t=>{const s=as(),i=as(),n=as(),r=e(c(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))i.pub(null),n.pub(null),s.pub(null);else{const e=await l(t);e&&n.pub(e);const{sessionJwt:r,sessionExpiration:o}=await d(t);r&&i.pub(r),(o||r)&&s.pub(o||42)}}})),o=ue(r,["logout","logoutAll","oidc.logout"],(e=>async(...t)=>{const r=await e(...t);return i.pub(null),n.pub(null),s.pub(null),r}));return Object.assign(o,{onSessionTokenChange:i.sub,onUserChange:n.sub,onIsAuthenticatedChange:e=>s.sub((t=>{e(!!t)}))})}),(e=>s=>{var{storeLastAuthenticatedUser:i=!0,keepLastAuthenticatedUserAfterLogout:n=!1}=s,r=t(s,["storeLastAuthenticatedUser","keepLastAuthenticatedUserAfterLogout"]);if(!i)return Object.assign(e(r),{getLastUserLoginId:is,getLastUserDisplayName:ns});const o=e(c(r,{afterRequest:async(e,t)=>{var s;const i=await l(t),n=null===(s=null==i?void 0:i.loginIds)||void 0===s?void 0:s[0],r=null==i?void 0:i.name;n&&((e=>{h(ts,e)})(n),(e=>{h(ss,e)})(r))}}));let a=ue(o,["flow.start"],rs);return a=ue(a,["logout","logoutAll"],os(n)),Object.assign(a,{getLastUserLoginId:is,getLastUserDisplayName:ns})}),(e=>s=>{var{persistTokens:i,sessionTokenViaCookie:n,storagePrefix:r}=s,o=t(s,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!i||!bt)return e(o);const a=e(c(o,{beforeRequest:(l=r,e=>Object.assign(e,{token:e.token||At(l)})),afterRequest:async(e,t)=>{const s=/^\/v\d+\/mgmt\//.test(e.path);401===(null==t?void 0:t.status)?s||$t(r):((e={},t=!1,s="")=>{var i;const{sessionJwt:n,refreshJwt:r}=e;if(r&&h(`${s}${Pt}`,r),n)if(t){const s=t.sameSite||"Strict",r=null===(i=t.secure)||void 0===i||i;jt(Rt,n,Object.assign(Object.assign({},e),{cookieSameSite:s,cookieSecure:r}))}else h(`${s}${Rt}`,n);e.idToken&&h(`${s}${Ct}`,e.idToken)})(await d(t),n,r)}}));var l;const u=ue(a,["logout","logoutAll","oidc.logout"],cs(r));return Object.assign(u,{getRefreshToken:()=>At(r),getSessionToken:()=>qt(r),getIdToken:()=>Nt(r)})}))((e=>{const t=yt(e),s=Os(t,e.projectId,e.oidcConfig);return Object.assign(Object.assign({},t),{refresh:async i=>{if(e.oidcConfig)try{return await s.refreshToken(i),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161001",errorDescription:e.toString()}})}const n=qt(),r=At();return t.refresh(i,{dcs:n?"t":"f",dcr:r?"t":"f"})},logout:async i=>{if(e.oidcConfig)try{return await s.logout({id_token_hint:i}),Promise.resolve({ok:!0})}catch(e){return Promise.resolve({ok:!1,error:{errorCode:"J161000",errorDescription:e.toString()}})}return t.logout(i)},flow:ks(t),webauthn:ms(t),fedcm:(i=t,n=e.projectId,{onetap:{requestExchangeCode(e){Ss(i,e)},requestAuthentication(e){Ss(i,e)}},oneTap(e,t,s,n,r){Ss(i,{provider:e,oneTapConfig:t,loginOptions:s,onSkipped:n,onDismissed:r})},async launch(e){var t;const s={identity:{context:e||"signin",providers:[{configURL:i.httpClient.buildUrl(n+vs.config),clientId:n}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(s));return i.refresh(r.token)},isSupported:()=>bt&&"IdentityCredential"in window,async isLoggedIn(e){var t;const s=i.httpClient.buildUrl(n+vs.config);try{const i={identity:{context:e||"signin",providers:[{configURL:s,clientId:n}]}},r=await(null===(t=navigator.credentials)||void 0===t?void 0:t.get(i));return!!r&&!!r.token}catch(e){return!1}}}),oidc:s});var i,n}));xs.REFRESH_TOKEN_KEY=Pt,xs.SESSION_TOKEN_KEY=Rt;var Es,Us,Rs,Ps={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},Cs=(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))(Cs||{});(Rs=Cs||(Cs={})).reset=function(){Es=3,Us=Ps},Rs.setLevel=function(e){if(!(0<=e&&e<=4))throw new Error("Invalid log level");Es=e},Rs.setLogger=function(e){Us=e};var js=class e{constructor(e){this._name=e}debug(...t){Es>=4&&Us.debug(e._format(this._name,this._method),...t)}info(...t){Es>=3&&Us.info(e._format(this._name,this._method),...t)}warn(...t){Es>=2&&Us.warn(e._format(this._name,this._method),...t)}error(...t){Es>=1&&Us.error(e._format(this._name,this._method),...t)}throw(e){throw this.error(e),e}create(e){const t=Object.create(this);return t._method=e,t.debug("begin"),t}static createStatic(t,s){const i=new e(`${t}.${s}`);return i.debug("begin"),i}static _format(e,t){const s=`[${e}]`;return t?`${s} ${t}:`:s}static debug(t,...s){Es>=4&&Us.debug(e._format(t),...s)}static info(t,...s){Es>=3&&Us.info(e._format(t),...s)}static warn(t,...s){Es>=2&&Us.warn(e._format(t),...s)}static error(t,...s){Es>=1&&Us.error(e._format(t),...s)}};Cs.reset();var As=class{static decode(e){try{return n(e)}catch(e){throw js.error("JwtUtils.decode",e),e}}static async generateSignedJwt(e,t,s){const i=`${$s.encodeBase64Url((new TextEncoder).encode(JSON.stringify(e)))}.${$s.encodeBase64Url((new TextEncoder).encode(JSON.stringify(t)))}`,n=await window.crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},s,(new TextEncoder).encode(i));return`${i}.${$s.encodeBase64Url(new Uint8Array(n))}`}},qs=e=>btoa([...new Uint8Array(e)].map((e=>String.fromCharCode(e))).join("")),Ns=class e{static _randomWord(){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}static generateUUIDv4(){const t="10000000-1000-4000-8000-100000000000".replace(/[018]/g,(t=>(+t^e._randomWord()&15>>+t/4).toString(16)));return t.replace(/-/g,"")}static generateCodeVerifier(){return e.generateUUIDv4()+e.generateUUIDv4()+e.generateUUIDv4()}static async generateCodeChallenge(e){if(!crypto.subtle)throw new Error("Crypto.subtle is available only in secure contexts (HTTPS).");try{const t=(new TextEncoder).encode(e),s=await crypto.subtle.digest("SHA-256",t);return qs(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}catch(e){throw js.error("CryptoUtils.generateCodeChallenge",e),e}}static generateBasicAuth(e,t){const s=(new TextEncoder).encode([e,t].join(":"));return qs(s)}static async hash(e,t){const s=(new TextEncoder).encode(t),i=await crypto.subtle.digest(e,s);return new Uint8Array(i)}static async customCalculateJwkThumbprint(t){let s;switch(t.kty){case"RSA":s={e:t.e,kty:t.kty,n:t.n};break;case"EC":s={crv:t.crv,kty:t.kty,x:t.x,y:t.y};break;case"OKP":s={crv:t.crv,kty:t.kty,x:t.x};break;case"oct":s={crv:t.k,kty:t.kty};break;default:throw new Error("Unknown jwk type")}const i=await e.hash("SHA-256",JSON.stringify(s));return e.encodeBase64Url(i)}static async generateDPoPProof({url:t,accessToken:s,httpMethod:i,keyPair:n,nonce:r}){let o,a;const c={jti:window.crypto.randomUUID(),htm:null!=i?i:"GET",htu:t,iat:Math.floor(Date.now()/1e3)};s&&(o=await e.hash("SHA-256",s),a=e.encodeBase64Url(o),c.ath=a),r&&(c.nonce=r);try{const e=await crypto.subtle.exportKey("jwk",n.publicKey),t={alg:"ES256",typ:"dpop+jwt",jwk:{crv:e.crv,kty:e.kty,x:e.x,y:e.y}};return await As.generateSignedJwt(t,c,n.privateKey)}catch(e){throw e instanceof TypeError?new Error(`Error exporting dpop public key: ${e.message}`):e}}static async generateDPoPJkt(t){try{const s=await crypto.subtle.exportKey("jwk",t.publicKey);return await e.customCalculateJwkThumbprint(s)}catch(e){throw e instanceof TypeError?new Error(`Could not retrieve dpop keys from storage: ${e.message}`):e}}static async generateDPoPKeys(){return await window.crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!1,["sign","verify"])}};Ns.encodeBase64Url=e=>qs(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var $s=Ns,Ms=class{constructor(e){this._name=e,this._callbacks=[],this._logger=new js(`Event('${this._name}')`)}addHandler(e){return this._callbacks.push(e),()=>this.removeHandler(e)}removeHandler(e){const t=this._callbacks.lastIndexOf(e);t>=0&&this._callbacks.splice(t,1)}async raise(...e){this._logger.debug("raise:",...e);for(const t of this._callbacks)await t(...e)}},Ds=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(",")}},Ls=class e extends Ms{constructor(){super(...arguments),this._logger=new js(`Timer('${this._name}')`),this._timerHandle=null,this._expiration=0,this._callback=()=>{const t=this._expiration-e.getEpochTime();this._logger.debug("timer completes in",t),this._expiration<=e.getEpochTime()&&(this.cancel(),super.raise())}}static getEpochTime(){return Math.floor(Date.now()/1e3)}init(t){const s=this._logger.create("init");t=Math.max(Math.floor(t),1);const i=e.getEpochTime()+t;if(this.expiration===i&&this._timerHandle)return void s.debug("skipping since already initialized for expiration at",this.expiration);this.cancel(),s.debug("using duration",t),this._expiration=i;const n=Math.min(t,5);this._timerHandle=setInterval(this._callback,1e3*n)}get expiration(){return this._expiration}cancel(){this._logger.create("cancel"),this._timerHandle&&(clearInterval(this._timerHandle),this._timerHandle=null)}},Hs=class{static readParams(e,t="query"){if(!e)throw new TypeError("Invalid URL");const s=new URL(e,"http://127.0.0.1")["fragment"===t?"hash":"search"];return new URLSearchParams(s.slice(1))}},Js=";",Ks=class extends Error{constructor(e,t){var s,i,n;if(super(e.error_description||e.error||""),this.form=t,this.name="ErrorResponse",!e.error)throw js.error("ErrorResponse","No error passed"),new Error("No error passed");this.error=e.error,this.error_description=null!=(s=e.error_description)?s:null,this.error_uri=null!=(i=e.error_uri)?i:null,this.state=e.userState,this.session_state=null!=(n=e.session_state)?n:null,this.url_state=e.url_state}},Ws=class extends Error{constructor(e){super(e),this.name="ErrorTimeout"}},Fs=class{constructor(e){this._logger=new js("AccessTokenEvents"),this._expiringTimer=new Ls("Access token expiring"),this._expiredTimer=new Ls("Access token expired"),this._expiringNotificationTimeInSeconds=e.expiringNotificationTimeInSeconds}async load(e){const t=this._logger.create("load");if(e.access_token&&void 0!==e.expires_in){const s=e.expires_in;if(t.debug("access token present, remaining duration:",s),s>0){let e=s-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 i=s+1;t.debug("registering expired timer, raising in",i,"seconds"),this._expiredTimer.init(i)}else this._expiringTimer.cancel(),this._expiredTimer.cancel()}async unload(){this._logger.debug("unload: canceling existing access token timers"),this._expiringTimer.cancel(),this._expiredTimer.cancel()}addAccessTokenExpiring(e){return this._expiringTimer.addHandler(e)}removeAccessTokenExpiring(e){this._expiringTimer.removeHandler(e)}addAccessTokenExpired(e){return this._expiredTimer.addHandler(e)}removeAccessTokenExpired(e){this._expiredTimer.removeHandler(e)}},zs=class{constructor(e,t,s,i,n){this._callback=e,this._client_id=t,this._intervalInSeconds=i,this._stopOnError=n,this._logger=new js("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(s);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)}},Bs=class{constructor(){this._logger=new js("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]}},Vs=class extends Error{constructor(e,t){super(t),this.name="ErrorDPoPNonce",this.nonce=e}},Qs=class{constructor(e=[],t=null,s={}){this._jwtHandler=t,this._extraHeaders=s,this._logger=new js("JsonService"),this._contentTypes=[],this._contentTypes.push(...e,"application/json"),t&&this._contentTypes.push("application/jwt")}async fetchWithTimeout(e,t={}){const{timeoutInSeconds:s,...i}=t;if(!s)return await fetch(e,i);const n=new AbortController,r=setTimeout((()=>n.abort()),1e3*s);try{return await fetch(e,{...t,signal:n.signal})}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw new Ws("Network timed out");throw e}finally{clearTimeout(r)}}async getJson(e,{token:t,credentials:s,timeoutInSeconds:i}={}){const n=this._logger.create("getJson"),r={Accept:this._contentTypes.join(", ")};let o;t&&(n.debug("token passed, setting Authorization header"),r.Authorization="Bearer "+t),this._appendExtraHeaders(r);try{n.debug("url:",e),o=await this.fetchWithTimeout(e,{method:"GET",headers:r,timeoutInSeconds:i,credentials:s})}catch(e){throw n.error("Network Error"),e}n.debug("HTTP response received, status",o.status);const a=o.headers.get("Content-Type");if(a&&!this._contentTypes.find((e=>a.startsWith(e)))&&n.throw(new Error(`Invalid response Content-Type: ${null!=a?a:"undefined"}, from URL: ${e}`)),o.ok&&this._jwtHandler&&(null==a?void 0:a.startsWith("application/jwt")))return await this._jwtHandler(await o.text());let c;try{c=await o.json()}catch(e){if(n.error("Error parsing JSON response",e),o.ok)throw e;throw new Error(`${o.statusText} (${o.status})`)}if(!o.ok){if(n.error("Error from server:",c),c.error)throw new Ks(c);throw new Error(`${o.statusText} (${o.status}): ${JSON.stringify(c)}`)}return c}async postForm(e,{body:t,basicAuth:s,timeoutInSeconds:i,initCredentials:n,extraHeaders:r}){const o=this._logger.create("postForm"),a={Accept:this._contentTypes.join(", "),"Content-Type":"application/x-www-form-urlencoded",...r};let c;void 0!==s&&(a.Authorization="Basic "+s),this._appendExtraHeaders(a);try{o.debug("url:",e),c=await this.fetchWithTimeout(e,{method:"POST",headers:a,body:t,timeoutInSeconds:i,credentials:n})}catch(e){throw o.error("Network error"),e}o.debug("HTTP response received, status",c.status);const d=c.headers.get("Content-Type");if(d&&!this._contentTypes.find((e=>d.startsWith(e))))throw new Error(`Invalid response Content-Type: ${null!=d?d:"undefined"}, from URL: ${e}`);const l=await c.text();let u={};if(l)try{u=JSON.parse(l)}catch(e){if(o.error("Error parsing JSON response",e),c.ok)throw e;throw new Error(`${c.statusText} (${c.status})`)}if(!c.ok){if(o.error("Error from server:",u),c.headers.has("dpop-nonce")){const e=c.headers.get("dpop-nonce");throw new Vs(e,`${JSON.stringify(u)}`)}if(u.error)throw new Ks(u,t);throw new Error(`${c.statusText} (${c.status}): ${JSON.stringify(u)}`)}return u}_appendExtraHeaders(e){const t=this._logger.create("appendExtraHeaders"),s=Object.keys(this._extraHeaders),i=["accept","content-type"],n=["authorization"];0!==s.length&&s.forEach((s=>{if(i.includes(s.toLocaleLowerCase()))return void t.warn("Protected header could not be set",s,i);if(n.includes(s.toLocaleLowerCase())&&Object.keys(e).includes(s))return void t.warn("Header could not be overridden",s,n);const r="function"==typeof this._extraHeaders[s]?this._extraHeaders[s]():this._extraHeaders[s];r&&""!==r&&(e[s]=r)}))}},Gs=class{constructor(e){this._settings=e,this._logger=new js("MetadataService"),this._signingKeys=null,this._metadata=null,this._metadataUrl=this._settings.metadataUrl,this._jsonService=new Qs(["application/jwk-set+json"],null,this._settings.extraHeaders),this._settings.signingKeys&&(this._logger.debug("using signingKeys from settings"),this._signingKeys=this._settings.signingKeys),this._settings.metadata&&(this._logger.debug("using metadata from settings"),this._metadata=this._settings.metadata),this._settings.fetchRequestCredentials&&(this._logger.debug("using fetchRequestCredentials from settings"),this._fetchRequestCredentials=this._settings.fetchRequestCredentials)}resetSigningKeys(){this._signingKeys=null}async getMetadata(){const e=this._logger.create("getMetadata");if(this._metadata)return e.debug("using cached values"),this._metadata;if(!this._metadataUrl)throw e.throw(new Error("No authority or metadataUrl configured on settings")),null;e.debug("getting metadata from",this._metadataUrl);const t=await this._jsonService.getJson(this._metadataUrl,{credentials:this._fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return e.debug("merging remote JSON with seed metadata"),this._metadata=Object.assign({},t,this._settings.metadataSeed),this._metadata}getIssuer(){return this._getMetadataProperty("issuer")}getAuthorizationEndpoint(){return this._getMetadataProperty("authorization_endpoint")}getUserInfoEndpoint(){return this._getMetadataProperty("userinfo_endpoint")}getTokenEndpoint(e=!0){return this._getMetadataProperty("token_endpoint",e)}getCheckSessionIframe(){return this._getMetadataProperty("check_session_iframe",!0)}getEndSessionEndpoint(){return this._getMetadataProperty("end_session_endpoint",!0)}getRevocationEndpoint(e=!0){return this._getMetadataProperty("revocation_endpoint",e)}getKeysEndpoint(e=!0){return this._getMetadataProperty("jwks_uri",e)}async _getMetadataProperty(e,t=!1){const s=this._logger.create(`_getMetadataProperty('${e}')`),i=await this.getMetadata();if(s.debug("resolved"),void 0===i[e]){if(!0===t)return void s.warn("Metadata does not contain optional property");s.throw(new Error("Metadata does not contain property "+e))}return i[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 s=await this._jsonService.getJson(t,{timeoutInSeconds:this._settings.requestTimeoutInSeconds});if(e.debug("got key set",s),!Array.isArray(s.keys))throw e.throw(new Error("Missing keys on keyset")),null;return this._signingKeys=s.keys,this._signingKeys}},Zs=class{constructor({prefix:e="oidc.",store:t=localStorage}={}){this._logger=new js("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 s=0;s<e;s++){const e=await this._store.key(s);e&&0===e.indexOf(this._prefix)&&t.push(e.substr(this._prefix.length))}return t}},Ys=class{constructor({authority:e,metadataUrl:t,metadata:s,signingKeys:i,metadataSeed:n,client_id:r,client_secret:o,response_type:a="code",scope:c="openid",redirect_uri:d,post_logout_redirect_uri:l,client_authentication:u="client_secret_post",prompt:h,display:g,max_age:p,ui_locales:_,acr_values:w,resource:f,response_mode:m,filterProtocolClaims:v=!0,loadUserInfo:y=!1,requestTimeoutInSeconds:S,staleStateAgeInSeconds:k=900,mergeClaimsStrategy:b={array:"replace"},disablePKCE:I=!1,stateStore:T,revokeTokenAdditionalContentTypes:O,fetchRequestCredentials:x,refreshTokenAllowedScope:E,extraQueryParams:U={},extraTokenParams:R={},extraHeaders:P={},dpop:C,omitScopeWhenRequesting:j=!1}){var A;if(this.authority=e,t?this.metadataUrl=t:(this.metadataUrl=e,e&&(this.metadataUrl.endsWith("/")||(this.metadataUrl+="/"),this.metadataUrl+=".well-known/openid-configuration")),this.metadata=s,this.metadataSeed=n,this.signingKeys=i,this.client_id=r,this.client_secret=o,this.response_type=a,this.scope=c,this.redirect_uri=d,this.post_logout_redirect_uri=l,this.client_authentication=u,this.prompt=h,this.display=g,this.max_age=p,this.ui_locales=_,this.acr_values=w,this.resource=f,this.response_mode=m,this.filterProtocolClaims=null==v||v,this.loadUserInfo=!!y,this.staleStateAgeInSeconds=k,this.mergeClaimsStrategy=b,this.omitScopeWhenRequesting=j,this.disablePKCE=!!I,this.revokeTokenAdditionalContentTypes=O,this.fetchRequestCredentials=x||"same-origin",this.requestTimeoutInSeconds=S,T)this.stateStore=T;else{const e="undefined"!=typeof window?window.localStorage:new Bs;this.stateStore=new Zs({store:e})}if(this.refreshTokenAllowedScope=E,this.extraQueryParams=U,this.extraTokenParams=R,this.extraHeaders=P,this.dpop=C,this.dpop&&!(null==(A=this.dpop)?void 0:A.store))throw new Error("A DPoPStore is required when dpop is enabled")}},Xs=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new js("UserInfoService"),this._getClaimsFromJwt=async e=>{const t=this._logger.create("_getClaimsFromJwt");try{const s=As.decode(e);return t.debug("JWT decoding successful"),s}catch(e){throw t.error("Error parsing JWT response"),e}},this._jsonService=new Qs(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 s=await this._metadataService.getUserInfoEndpoint();t.debug("got userinfo url",s);const i=await this._jsonService.getJson(s,{token:e,credentials:this._settings.fetchRequestCredentials,timeoutInSeconds:this._settings.requestTimeoutInSeconds});return t.debug("got claims",i),i}},ei=class{constructor(e,t){this._settings=e,this._metadataService=t,this._logger=new js("TokenClient"),this._jsonService=new Qs(this._settings.revokeTokenAdditionalContentTypes,null,this._settings.extraHeaders)}async exchangeCode({grant_type:e="authorization_code",redirect_uri:t=this._settings.redirect_uri,client_id:s=this._settings.client_id,client_secret:i=this._settings.client_secret,extraHeaders:n,...r}){const o=this._logger.create("exchangeCode");s||o.throw(new Error("A client_id is required")),t||o.throw(new Error("A redirect_uri is required")),r.code||o.throw(new Error("A code is required"));const a=new URLSearchParams({grant_type:e,redirect_uri:t});for(const[e,t]of Object.entries(r))null!=t&&a.set(e,t);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==i)throw o.throw(new Error("A client_secret is required")),null;c=$s.generateBasicAuth(s,i);break;case"client_secret_post":a.append("client_id",s),i&&a.append("client_secret",i)}const d=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:n});return o.debug("got response"),l}async exchangeCredentials({grant_type:e="password",client_id:t=this._settings.client_id,client_secret:s=this._settings.client_secret,scope:i=this._settings.scope,...n}){const r=this._logger.create("exchangeCredentials");t||r.throw(new Error("A client_id is required"));const o=new URLSearchParams({grant_type:e});this._settings.omitScopeWhenRequesting||o.set("scope",i);for(const[e,t]of Object.entries(n))null!=t&&o.set(e,t);let a;switch(this._settings.client_authentication){case"client_secret_basic":if(null==s)throw r.throw(new Error("A client_secret is required")),null;a=$s.generateBasicAuth(t,s);break;case"client_secret_post":o.append("client_id",t),s&&o.append("client_secret",s)}const c=await this._metadataService.getTokenEndpoint(!1);r.debug("got token endpoint");const d=await this._jsonService.postForm(c,{body:o,basicAuth:a,timeoutInSeconds:this._settings.requestTimeoutInSeconds,initCredentials:this._settings.fetchRequestCredentials});return r.debug("got response"),d}async exchangeRefreshToken({grant_type:e="refresh_token",client_id:t=this._settings.client_id,client_secret:s=this._settings.client_secret,timeoutInSeconds:i,extraHeaders:n,...r}){const o=this._logger.create("exchangeRefreshToken");t||o.throw(new Error("A client_id is required")),r.refresh_token||o.throw(new Error("A refresh_token is required"));const a=new URLSearchParams({grant_type:e});for(const[e,t]of Object.entries(r))Array.isArray(t)?t.forEach((t=>a.append(e,t))):null!=t&&a.set(e,t);let c;switch(this._settings.client_authentication){case"client_secret_basic":if(null==s)throw o.throw(new Error("A client_secret is required")),null;c=$s.generateBasicAuth(t,s);break;case"client_secret_post":a.append("client_id",t),s&&a.append("client_secret",s)}const d=await this._metadataService.getTokenEndpoint(!1);o.debug("got token endpoint");const l=await this._jsonService.postForm(d,{body:a,basicAuth:c,timeoutInSeconds:i,initCredentials:this._settings.fetchRequestCredentials,extraHeaders:n});return o.debug("got response"),l}async revoke(e){var t;const s=this._logger.create("revoke");e.token||s.throw(new Error("A token is required"));const i=await this._metadataService.getRevocationEndpoint(!1);s.debug(`got revocation endpoint, revoking ${null!=(t=e.token_type_hint)?t:"default token type"}`);const n=new URLSearchParams;for(const[t,s]of Object.entries(e))null!=s&&n.set(t,s);n.set("client_id",this._settings.client_id),this._settings.client_secret&&n.set("client_secret",this._settings.client_secret),await this._jsonService.postForm(i,{body:n,timeoutInSeconds:this._settings.requestTimeoutInSeconds}),s.debug("got response")}},ti=class{constructor(e,t,s){this._settings=e,this._metadataService=t,this._claimsService=s,this._logger=new js("ResponseValidator"),this._userInfoService=new Xs(this._settings,this._metadataService),this._tokenClient=new ei(this._settings,this._metadataService)}async validateSigninResponse(e,t,s){const i=this._logger.create("validateSigninResponse");this._processSigninState(e,t),i.debug("state processed"),await this._processCode(e,t,s),i.debug("code processed"),e.isOpenId&&this._validateIdTokenAttributes(e),i.debug("tokens validated"),await this._processClaims(e,null==t?void 0:t.skipUserInfo,e.isOpenId),i.debug("claims processed")}async validateCredentialsResponse(e,t){const s=this._logger.create("validateCredentialsResponse");e.isOpenId&&e.id_token&&this._validateIdTokenAttributes(e),s.debug("tokens validated"),await this._processClaims(e,t,e.isOpenId),s.debug("claims processed")}async validateRefreshResponse(e,t){const s=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),s.debug("ID Token validated")),e.id_token||(e.id_token=t.id_token,e.profile=t.profile);const i=e.isOpenId&&!!e.id_token;await this._processClaims(e,!1,i),s.debug("claims processed")}validateSignoutResponse(e,t){const s=this._logger.create("validateSignoutResponse");if(t.id!==e.state&&s.throw(new Error("State does not match")),s.debug("state validated"),e.userState=t.data,e.error)throw s.warn("Response was error",e.error),new Ks(e)}_processSigninState(e,t){const s=this._logger.create("_processSigninState");if(t.id!==e.state&&s.throw(new Error("State does not match")),t.client_id||s.throw(new Error("No client_id on state")),t.authority||s.throw(new Error("No authority on state")),this._settings.authority!==t.authority&&s.throw(new Error("authority mismatch on settings vs. signin state")),this._settings.client_id&&this._settings.client_id!==t.client_id&&s.throw(new Error("client_id mismatch on settings vs. signin state")),s.debug("state validated"),e.userState=t.data,e.url_state=t.url_state,null!=e.scope||(e.scope=t.scope),e.error)throw s.warn("Response was error",e.error),new Ks(e);t.code_verifier&&!e.code&&s.throw(new Error("Expected code in response"))}async _processClaims(e,t=!1,s=!0){const i=this._logger.create("_processClaims");if(e.profile=this._claimsService.filterProtocolClaims(e.profile),t||!this._settings.loadUserInfo||!e.access_token)return void i.debug("not loading user info");i.debug("loading user info");const n=await this._userInfoService.getClaims(e.access_token);i.debug("user info claims received from user info endpoint"),s&&n.sub!==e.profile.sub&&i.throw(new Error("subject from UserInfo response does not match subject in ID Token")),e.profile=this._claimsService.mergeClaims(e.profile,this._claimsService.filterProtocolClaims(n)),i.debug("user info claims received, updated profile:",e.profile)}async _processCode(e,t,s){const i=this._logger.create("_processCode");if(e.code){i.debug("Validating code");const n=await this._tokenClient.exchangeCode({client_id:t.client_id,client_secret:t.client_secret,code:e.code,redirect_uri:t.redirect_uri,code_verifier:t.code_verifier,extraHeaders:s,...t.extraTokenParams});Object.assign(e,n)}else i.debug("No code to process")}_validateIdTokenAttributes(e,t){var s;const i=this._logger.create("_validateIdTokenAttributes");i.debug("decoding ID Token JWT");const n=As.decode(null!=(s=e.id_token)?s:"");if(n.sub||i.throw(new Error("ID Token is missing a subject claim")),t){const e=As.decode(t);n.sub!==e.sub&&i.throw(new Error("sub in id_token does not match current sub")),n.auth_time&&n.auth_time!==e.auth_time&&i.throw(new Error("auth_time in id_token does not match original auth_time")),n.azp&&n.azp!==e.azp&&i.throw(new Error("azp in id_token does not match original azp")),!n.azp&&e.azp&&i.throw(new Error("azp not in id_token, but present in original id_token"))}e.profile=n}},si=class e{constructor(e){this.id=e.id||$s.generateUUIDv4(),this.data=e.data,e.created&&e.created>0?this.created=e.created:this.created=Ls.getEpochTime(),this.request_type=e.request_type,this.url_state=e.url_state}toStorageString(){return new js("State").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state})}static fromStorageString(t){return js.createStatic("State","fromStorageString"),Promise.resolve(new e(JSON.parse(t)))}static async clearStaleState(t,s){const i=js.createStatic("State","clearStaleState"),n=Ls.getEpochTime()-s,r=await t.getAllKeys();i.debug("got keys",r);for(let s=0;s<r.length;s++){const o=r[s],a=await t.get(o);let c=!1;if(a)try{const t=await e.fromStorageString(a);i.debug("got item from key:",o,t.created),t.created<=n&&(c=!0)}catch(e){i.error("Error parsing state for key:",o,e),c=!0}else i.debug("no item in storage for key:",o),c=!0;c&&(i.debug("removed item for key:",o),t.remove(o))}}},ii=class e extends si{constructor(e){super(e),this.code_verifier=e.code_verifier,this.code_challenge=e.code_challenge,this.authority=e.authority,this.client_id=e.client_id,this.redirect_uri=e.redirect_uri,this.scope=e.scope,this.client_secret=e.client_secret,this.extraTokenParams=e.extraTokenParams,this.response_mode=e.response_mode,this.skipUserInfo=e.skipUserInfo}static async create(t){const s=!0===t.code_verifier?$s.generateCodeVerifier():t.code_verifier||void 0,i=s?await $s.generateCodeChallenge(s):void 0;return new e({...t,code_verifier:s,code_challenge:i})}toStorageString(){return new js("SigninState").create("toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,request_type:this.request_type,url_state:this.url_state,code_verifier:this.code_verifier,authority:this.authority,client_id:this.client_id,redirect_uri:this.redirect_uri,scope:this.scope,client_secret:this.client_secret,extraTokenParams:this.extraTokenParams,response_mode:this.response_mode,skipUserInfo:this.skipUserInfo})}static fromStorageString(t){js.createStatic("SigninState","fromStorageString");const s=JSON.parse(t);return e.create(s)}},ni=class e{constructor(e){this.url=e.url,this.state=e.state}static async create({url:t,authority:s,client_id:i,redirect_uri:n,response_type:r,scope:o,state_data:a,response_mode:c,request_type:d,client_secret:l,nonce:u,url_state:h,resource:g,skipUserInfo:p,extraQueryParams:_,extraTokenParams:w,disablePKCE:f,dpopJkt:m,omitScopeWhenRequesting:v,...y}){if(!t)throw this._logger.error("create: No url passed"),new Error("url");if(!i)throw this._logger.error("create: No client_id passed"),new Error("client_id");if(!n)throw this._logger.error("create: No redirect_uri passed"),new Error("redirect_uri");if(!r)throw this._logger.error("create: No response_type passed"),new Error("response_type");if(!o)throw this._logger.error("create: No scope passed"),new Error("scope");if(!s)throw this._logger.error("create: No authority passed"),new Error("authority");const S=await ii.create({data:a,request_type:d,url_state:h,code_verifier:!f,client_id:i,authority:s,redirect_uri:n,response_mode:c,client_secret:l,scope:o,extraTokenParams:w,skipUserInfo:p}),k=new URL(t);k.searchParams.append("client_id",i),k.searchParams.append("redirect_uri",n),k.searchParams.append("response_type",r),v||k.searchParams.append("scope",o),u&&k.searchParams.append("nonce",u),m&&k.searchParams.append("dpop_jkt",m);let b=S.id;if(h&&(b=`${b}${Js}${h}`),k.searchParams.append("state",b),S.code_challenge&&(k.searchParams.append("code_challenge",S.code_challenge),k.searchParams.append("code_challenge_method","S256")),g){(Array.isArray(g)?g:[g]).forEach((e=>k.searchParams.append("resource",e)))}for(const[e,t]of Object.entries({response_mode:c,...y,..._}))null!=t&&k.searchParams.append(e,t.toString());return new e({url:k.href,state:S})}};ni._logger=new js("SigninRequest");var ri=ni,oi=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(Js);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Js))}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-Ls.getEpochTime()}set expires_in(e){"string"==typeof e&&(e=Number(e)),void 0!==e&&e>=0&&(this.expires_at=Math.floor(e)+Ls.getEpochTime())}get isOpenId(){var e;return(null==(e=this.scope)?void 0:e.split(" ").includes("openid"))||!!this.id_token}},ai=class{constructor({url:e,state_data:t,id_token_hint:s,post_logout_redirect_uri:i,extraQueryParams:n,request_type:r,client_id:o,url_state:a}){if(this._logger=new js("SignoutRequest"),!e)throw this._logger.error("ctor: No url passed"),new Error("url");const c=new URL(e);if(s&&c.searchParams.append("id_token_hint",s),o&&c.searchParams.append("client_id",o),i&&(c.searchParams.append("post_logout_redirect_uri",i),t||a)){this.state=new si({data:t,request_type:r,url_state:a});let e=this.state.id;a&&(e=`${e}${Js}${a}`),c.searchParams.append("state",e)}for(const[e,t]of Object.entries({...n}))null!=t&&c.searchParams.append(e,t.toString());this.url=c.href}},ci=class{constructor(e){if(this.state=e.get("state"),this.state){const e=decodeURIComponent(this.state).split(Js);this.state=e[0],e.length>1&&(this.url_state=e.slice(1).join(Js))}this.error=e.get("error"),this.error_description=e.get("error_description"),this.error_uri=e.get("error_uri")}},di=["nbf","jti","auth_time","nonce","acr","amr","azp","at_hash"],li=["sub","iss","aud","exp","iat"],ui=class{constructor(e){this._settings=e,this._logger=new js("ClaimsService")}filterProtocolClaims(e){const t={...e};if(this._settings.filterProtocolClaims){let e;e=Array.isArray(this._settings.filterProtocolClaims)?this._settings.filterProtocolClaims:di;for(const s of e)li.includes(s)||delete t[s]}return t}mergeClaims(e,t){const s={...e};for(const[e,i]of Object.entries(t))if(s[e]!==i)if(Array.isArray(s[e])||Array.isArray(i))if("replace"==this._settings.mergeClaimsStrategy.array)s[e]=i;else{const t=Array.isArray(s[e])?s[e]:[s[e]];for(const e of Array.isArray(i)?i:[i])t.includes(e)||t.push(e);s[e]=t}else"object"==typeof s[e]&&"object"==typeof i?s[e]=this.mergeClaims(s[e],i):s[e]=i;return s}},hi=class{constructor(e,t){this.keys=e,this.nonce=t}},gi=class{constructor(e,t){this._logger=new js("OidcClient"),this.settings=e instanceof Ys?e:new Ys(e),this.metadataService=null!=t?t:new Gs(this.settings),this._claimsService=new ui(this.settings),this._validator=new ti(this.settings,this.metadataService,this._claimsService),this._tokenClient=new ei(this.settings,this.metadataService)}async createSigninRequest({state:e,request:t,request_uri:s,request_type:i,id_token_hint:n,login_hint:r,skipUserInfo:o,nonce:a,url_state:c,response_type:d=this.settings.response_type,scope:l=this.settings.scope,redirect_uri:u=this.settings.redirect_uri,prompt:h=this.settings.prompt,display:g=this.settings.display,max_age:p=this.settings.max_age,ui_locales:_=this.settings.ui_locales,acr_values:w=this.settings.acr_values,resource:f=this.settings.resource,response_mode:m=this.settings.response_mode,extraQueryParams:v=this.settings.extraQueryParams,extraTokenParams:y=this.settings.extraTokenParams,dpopJkt:S,omitScopeWhenRequesting:k=this.settings.omitScopeWhenRequesting}){const b=this._logger.create("createSigninRequest");if("code"!==d)throw new Error("Only the Authorization Code flow (with PKCE) is supported");const I=await this.metadataService.getAuthorizationEndpoint();b.debug("Received authorization endpoint",I);const T=await ri.create({url:I,authority:this.settings.authority,client_id:this.settings.client_id,redirect_uri:u,response_type:d,scope:l,state_data:e,url_state:c,prompt:h,display:g,max_age:p,ui_locales:_,id_token_hint:n,login_hint:r,acr_values:w,dpopJkt:S,resource:f,request:t,request_uri:s,extraQueryParams:v,extraTokenParams:y,request_type:i,response_mode:m,client_secret:this.settings.client_secret,skipUserInfo:o,nonce:a,disablePKCE:this.settings.disablePKCE,omitScopeWhenRequesting:k});await this.clearStaleState();const O=T.state;return await this.settings.stateStore.set(O.id,O.toStorageString()),T}async readSigninResponseState(e,t=!1){const s=this._logger.create("readSigninResponseState"),i=new oi(Hs.readParams(e,this.settings.response_mode));if(!i.state)throw s.throw(new Error("No state in response")),null;const n=await this.settings.stateStore[t?"remove":"get"](i.state);if(!n)throw s.throw(new Error("No matching state found in storage")),null;return{state:await ii.fromStorageString(n),response:i}}async processSigninResponse(e,t,s=!0){const i=this._logger.create("processSigninResponse"),{state:n,response:r}=await this.readSigninResponseState(e,s);if(i.debug("received state from storage; validating response"),this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);t={...t,DPoP:e}}try{await this._validator.validateSigninResponse(r,n,t)}catch(e){if(!(e instanceof Vs&&this.settings.dpop))throw e;{const s=await this.getDpopProof(this.settings.dpop.store,e.nonce);t.DPoP=s,await this._validator.validateSigninResponse(r,n,t)}}return r}async getDpopProof(e,t){let s,i;return(await e.getAllKeys()).includes(this.settings.client_id)?(i=await e.get(this.settings.client_id),i.nonce!==t&&t&&(i.nonce=t,await e.set(this.settings.client_id,i))):(s=await $s.generateDPoPKeys(),i=new hi(s,t),await e.set(this.settings.client_id,i)),await $s.generateDPoPProof({url:await this.metadataService.getTokenEndpoint(!1),httpMethod:"POST",keyPair:i.keys,nonce:i.nonce})}async processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:s=!1,extraTokenParams:i={}}){const n=await this._tokenClient.exchangeCredentials({username:e,password:t,...i}),r=new oi(new URLSearchParams);return Object.assign(r,n),await this._validator.validateCredentialsResponse(r,s),r}async useRefreshToken({state:e,redirect_uri:t,resource:s,timeoutInSeconds:i,extraHeaders:n,extraTokenParams:r}){var o;const a=this._logger.create("useRefreshToken");let c,d;if(void 0===this.settings.refreshTokenAllowedScope)c=e.scope;else{const t=this.settings.refreshTokenAllowedScope.split(" ");c=((null==(o=e.scope)?void 0:o.split(" "))||[]).filter((e=>t.includes(e))).join(" ")}if(this.settings.dpop&&this.settings.dpop.store){const e=await this.getDpopProof(this.settings.dpop.store);n={...n,DPoP:e}}try{d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:s,timeoutInSeconds:i,extraHeaders:n,...r})}catch(o){if(!(o instanceof Vs&&this.settings.dpop))throw o;n.DPoP=await this.getDpopProof(this.settings.dpop.store,o.nonce),d=await this._tokenClient.exchangeRefreshToken({refresh_token:e.refresh_token,scope:c,redirect_uri:t,resource:s,timeoutInSeconds:i,extraHeaders:n,...r})}const l=new oi(new URLSearchParams);return Object.assign(l,d),a.debug("validating response",l),await this._validator.validateRefreshResponse(l,{...e,scope:c}),l}async createSignoutRequest({state:e,id_token_hint:t,client_id:s,request_type:i,url_state:n,post_logout_redirect_uri:r=this.settings.post_logout_redirect_uri,extraQueryParams:o=this.settings.extraQueryParams}={}){const a=this._logger.create("createSignoutRequest"),c=await this.metadataService.getEndSessionEndpoint();if(!c)throw a.throw(new Error("No end session endpoint")),null;a.debug("Received end session endpoint",c),s||!r||t||(s=this.settings.client_id);const d=new ai({url:c,id_token_hint:t,client_id:s,post_logout_redirect_uri:r,state_data:e,extraQueryParams:o,request_type:i,url_state:n});await this.clearStaleState();const l=d.state;return l&&(a.debug("Signout request has state to persist"),await this.settings.stateStore.set(l.id,l.toStorageString())),d}async readSignoutResponseState(e,t=!1){const s=this._logger.create("readSignoutResponseState"),i=new ci(Hs.readParams(e,this.settings.response_mode));if(!i.state){if(s.debug("No state in response"),i.error)throw s.warn("Response was error:",i.error),new Ks(i);return{state:void 0,response:i}}const n=await this.settings.stateStore[t?"remove":"get"](i.state);if(!n)throw s.throw(new Error("No matching state found in storage")),null;return{state:await si.fromStorageString(n),response:i}}async processSignoutResponse(e){const t=this._logger.create("processSignoutResponse"),{state:s,response:i}=await this.readSignoutResponseState(e,!0);return s?(t.debug("Received state from storage; validating response"),this._validator.validateSignoutResponse(i,s)):t.debug("No state from storage; skipping response validation"),i}clearStaleState(){return this._logger.create("clearStaleState"),si.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})}},pi=class{constructor(e){this._userManager=e,this._logger=new js("SessionMonitor"),this._start=async e=>{const t=e.session_state;if(!t)return;const s=this._logger.create("_start");if(e.profile?(this._sub=e.profile.sub,s.debug("session_state",t,", sub",this._sub)):(this._sub=void 0,s.debug("session_state",t,", anonymous user")),this._checkSessionIFrame)this._checkSessionIFrame.start(t);else try{const e=await this._userManager.metadataService.getCheckSessionIframe();if(e){s.debug("initializing check session iframe");const i=this._userManager.settings.client_id,n=this._userManager.settings.checkSessionIntervalInSeconds,r=this._userManager.settings.stopCheckSessionOnError,o=new zs(this._callback,i,e,n,r);await o.load(),this._checkSessionIFrame=o,o.start(t)}else s.warn("no check session iframe found in the metadata")}catch(e){s.error("Error from getCheckSessionIframe:",e instanceof Error?e.message:e)}},this._stop=()=>{const e=this._logger.create("_stop");if(this._sub=void 0,this._checkSessionIFrame&&this._checkSessionIFrame.stop(),this._userManager.settings.monitorAnonymousSession){const t=setInterval((async()=>{clearInterval(t);try{const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}catch(t){e.error("error from querySessionStatus",t instanceof Error?t.message:t)}}),1e3)}},this._callback=async()=>{const e=this._logger.create("_callback");try{const t=await this._userManager.querySessionStatus();let s=!0;t&&this._checkSessionIFrame?t.sub===this._sub?(s=!1,this._checkSessionIFrame.start(t.session_state),e.debug("same sub still logged in at OP, session state has changed, restarting check session iframe; session_state",t.session_state),await this._userManager.events._raiseUserSessionChanged()):e.debug("different subject signed into OP",t.sub):e.debug("subject no longer signed into OP"),s?this._sub?await this._userManager.events._raiseUserSignedOut():await this._userManager.events._raiseUserSignedIn():e.debug("no change in session detected, no event to raise")}catch(t){this._sub&&(e.debug("Error calling queryCurrentSigninSession; raising signed out event",t),await this._userManager.events._raiseUserSignedOut())}},e||this._logger.throw(new Error("No user manager passed")),this._userManager.events.addUserLoaded(this._start),this._userManager.events.addUserUnloaded(this._stop),this._init().catch((e=>{this._logger.error(e)}))}async _init(){this._logger.create("_init");const e=await this._userManager.getUser();if(e)this._start(e);else if(this._userManager.settings.monitorAnonymousSession){const e=await this._userManager.querySessionStatus();if(e){const t={session_state:e.session_state,profile:e.sub?{sub:e.sub}:null};this._start(t)}}}},_i=class e{constructor(e){var t;this.id_token=e.id_token,this.session_state=null!=(t=e.session_state)?t:null,this.access_token=e.access_token,this.refresh_token=e.refresh_token,this.token_type=e.token_type,this.scope=e.scope,this.profile=e.profile,this.expires_at=e.expires_at,this.state=e.userState,this.url_state=e.url_state}get expires_in(){if(void 0!==this.expires_at)return this.expires_at-Ls.getEpochTime()}set expires_in(e){void 0!==e&&(this.expires_at=Math.floor(e)+Ls.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 js("User").create("toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,refresh_token:this.refresh_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})}static fromStorageString(t){return js.createStatic("User","fromStorageString"),new e(JSON.parse(t))}},wi="oidc-client",fi=class{constructor(){this._abort=new Ms("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:s,keepOpen:i}=await new Promise(((s,i)=>{const n=n=>{var r;const o=n.data,a=null!=(r=e.scriptOrigin)?r:window.location.origin;if(n.origin===a&&(null==o?void 0:o.source)===wi){try{const s=Hs.readParams(o.url,e.response_mode).get("state");if(s||t.warn("no state found in response url"),n.source!==this._window&&s!==e.state)return}catch{this._dispose(),i(new Error("Invalid response from window"))}s(o)}};window.addEventListener("message",n,!1),this._disposeHandlers.add((()=>window.removeEventListener("message",n,!1))),this._disposeHandlers.add(this._abort.addHandler((e=>{this._dispose(),i(e)})))}));return t.debug("got response from window"),this._dispose(),i||this.close(),{url:s}}_dispose(){this._logger.create("_dispose");for(const e of this._disposeHandlers)e();this._disposeHandlers.clear()}static _notifyParent(e,t,s=!1,i=window.location.origin){e.postMessage({source:wi,url:t,keepOpen:s},i)}},mi={location:!1,toolbar:!1,height:640,closePopupWindowAfterInSeconds:-1},vi="_blank",yi=60,Si=2,ki=class extends Ys{constructor(e){const{popup_redirect_uri:t=e.redirect_uri,popup_post_logout_redirect_uri:s=e.post_logout_redirect_uri,popupWindowFeatures:i=mi,popupWindowTarget:n=vi,redirectMethod:r="assign",redirectTarget:o="self",iframeNotifyParentOrigin:a=e.iframeNotifyParentOrigin,iframeScriptOrigin:c=e.iframeScriptOrigin,requestTimeoutInSeconds:d,silent_redirect_uri:l=e.redirect_uri,silentRequestTimeoutInSeconds:u,automaticSilentRenew:h=!0,validateSubOnSilentRenew:g=!0,includeIdTokenInSilentRenew:p=!1,monitorSession:_=!1,monitorAnonymousSession:w=!1,checkSessionIntervalInSeconds:f=Si,query_status_response_type:m="code",stopCheckSessionOnError:v=!0,revokeTokenTypes:y=["access_token","refresh_token"],revokeTokensOnSignout:S=!1,includeIdTokenInSilentSignout:k=!1,accessTokenExpiringNotificationTimeInSeconds:b=yi,userStore:I}=e;if(super(e),this.popup_redirect_uri=t,this.popup_post_logout_redirect_uri=s,this.popupWindowFeatures=i,this.popupWindowTarget=n,this.redirectMethod=r,this.redirectTarget=o,this.iframeNotifyParentOrigin=a,this.iframeScriptOrigin=c,this.silent_redirect_uri=l,this.silentRequestTimeoutInSeconds=u||d||10,this.automaticSilentRenew=h,this.validateSubOnSilentRenew=g,this.includeIdTokenInSilentRenew=p,this.monitorSession=_,this.monitorAnonymousSession=w,this.checkSessionIntervalInSeconds=f,this.stopCheckSessionOnError=v,this.query_status_response_type=m,this.revokeTokenTypes=y,this.revokeTokensOnSignout=S,this.includeIdTokenInSilentSignout=k,this.accessTokenExpiringNotificationTimeInSeconds=b,I)this.userStore=I;else{const e="undefined"!=typeof window?window.sessionStorage:new Bs;this.userStore=new Zs({store:e})}}},bi=class e extends fi{constructor({silentRequestTimeoutInSeconds:t=10}){super(),this._logger=new js("IFrameWindow"),this._timeoutInSeconds=t,this._frame=e.createHiddenIframe(),this._window=this._frame.contentWindow}static createHiddenIframe(){const e=window.document.createElement("iframe");return e.style.visibility="hidden",e.style.position="fixed",e.style.left="-1000px",e.style.top="0",e.width="0",e.height="0",window.document.body.appendChild(e),e}async navigate(e){this._logger.debug("navigate: Using timeout of:",this._timeoutInSeconds);const t=setTimeout((()=>{this._abort.raise(new Ws("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 s=e.target;null==(t=s.parentNode)||t.removeChild(s),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)}},Ii=class{constructor(e){this._settings=e,this._logger=new js("IFrameNavigator")}async prepare({silentRequestTimeoutInSeconds:e=this._settings.silentRequestTimeoutInSeconds}){return new bi({silentRequestTimeoutInSeconds:e})}async callback(e){this._logger.create("callback"),bi.notifyParent(e,this._settings.iframeNotifyParentOrigin)}},Ti=class extends fi{constructor({popupWindowTarget:e=vi,popupWindowFeatures:t={},popupSignal:s}){super(),this._logger=new js("PopupWindow");const i=Ds.center({...mi,...t});this._window=window.open(void 0,e,Ds.serialize(i)),s&&s.addEventListener("abort",(()=>{var e;this._abort.raise(new Error(null!=(e=s.reason)?e:"Popup aborted"))})),t.closePopupWindowAfterInSeconds&&t.closePopupWindowAfterInSeconds>0&&setTimeout((()=>{this._window&&"boolean"==typeof this._window.closed&&!this._window.closed?this.close():this._abort.raise(new Error("Popup blocked by user"))}),1e3*t.closePopupWindowAfterInSeconds)}async navigate(e){var t;null==(t=this._window)||t.focus();const s=setInterval((()=>{this._window&&!this._window.closed||this._abort.raise(new Error("Popup closed by user"))}),500);return this._disposeHandlers.add((()=>clearInterval(s))),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)}},Oi=class{constructor(e){this._settings=e,this._logger=new js("PopupNavigator")}async prepare({popupWindowFeatures:e=this._settings.popupWindowFeatures,popupWindowTarget:t=this._settings.popupWindowTarget,popupSignal:s}){return new Ti({popupWindowFeatures:e,popupWindowTarget:t,popupSignal:s})}async callback(e,{keepOpen:t=!1}){this._logger.create("callback"),Ti.notifyOpener(e,t)}},xi=class{constructor(e){this._settings=e,this._logger=new js("RedirectNavigator")}async prepare({redirectMethod:e=this._settings.redirectMethod,redirectTarget:t=this._settings.redirectTarget}){var s;this._logger.create("prepare");let i=window.self;"top"===t&&(i=null!=(s=window.top)?s:window.self);const n=i.location[e].bind(i.location);let r;return{navigate:async e=>{this._logger.create("navigate");const t=new Promise(((e,t)=>{r=t}));return n(e.url),await t},close:()=>{this._logger.create("close"),null==r||r(new Error("Redirect aborted")),i.stop()}}}async callback(){}},Ei=class extends Fs{constructor(e){super({expiringNotificationTimeInSeconds:e.accessTokenExpiringNotificationTimeInSeconds}),this._logger=new js("UserManagerEvents"),this._userLoaded=new Ms("User loaded"),this._userUnloaded=new Ms("User unloaded"),this._silentRenewError=new Ms("Silent renew error"),this._userSignedIn=new Ms("User signed in"),this._userSignedOut=new Ms("User signed out"),this._userSessionChanged=new Ms("User session changed")}async load(e,t=!0){await super.load(e),t&&await this._userLoaded.raise(e)}async unload(){await super.unload(),await this._userUnloaded.raise()}addUserLoaded(e){return this._userLoaded.addHandler(e)}removeUserLoaded(e){return this._userLoaded.removeHandler(e)}addUserUnloaded(e){return this._userUnloaded.addHandler(e)}removeUserUnloaded(e){return this._userUnloaded.removeHandler(e)}addSilentRenewError(e){return this._silentRenewError.addHandler(e)}removeSilentRenewError(e){return this._silentRenewError.removeHandler(e)}async _raiseSilentRenewError(e){await this._silentRenewError.raise(e)}addUserSignedIn(e){return this._userSignedIn.addHandler(e)}removeUserSignedIn(e){this._userSignedIn.removeHandler(e)}async _raiseUserSignedIn(){await this._userSignedIn.raise()}addUserSignedOut(e){return this._userSignedOut.addHandler(e)}removeUserSignedOut(e){this._userSignedOut.removeHandler(e)}async _raiseUserSignedOut(){await this._userSignedOut.raise()}addUserSessionChanged(e){return this._userSessionChanged.addHandler(e)}removeUserSessionChanged(e){this._userSessionChanged.removeHandler(e)}async _raiseUserSessionChanged(){await this._userSessionChanged.raise()}},Ui=class{constructor(e){this._userManager=e,this._logger=new js("SilentRenewService"),this._isStarted=!1,this._retryTimer=new Ls("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 Ws)return e.warn("ErrorTimeout from signinSilent:",t,"retry in 5s"),void this._retryTimer.init(5);e.error("Error from signinSilent:",t),await this._userManager.events._raiseSilentRenewError(t)}}}async start(){const e=this._logger.create("start");if(!this._isStarted){this._isStarted=!0,this._userManager.events.addAccessTokenExpiring(this._tokenExpiring),this._retryTimer.addHandler(this._tokenExpiring);try{await this._userManager.getUser()}catch(t){e.error("getUser error",t)}}}stop(){this._isStarted&&(this._retryTimer.cancel(),this._retryTimer.removeHandler(this._tokenExpiring),this._userManager.events.removeAccessTokenExpiring(this._tokenExpiring),this._isStarted=!1)}},Ri=class{constructor(e){this.refresh_token=e.refresh_token,this.id_token=e.id_token,this.session_state=e.session_state,this.scope=e.scope,this.profile=e.profile,this.data=e.state}},Pi=Object.freeze({__proto__:null,AccessTokenEvents:Fs,CheckSessionIFrame:zs,DPoPState:hi,ErrorResponse:Ks,ErrorTimeout:Ws,InMemoryWebStorage:Bs,IndexedDbDPoPStore:class{constructor(){this._dbName="oidc",this._storeName="dpop"}async set(e,t){const s=await this.createStore(this._dbName,this._storeName);await s("readwrite",(s=>(s.put(t,e),this.promisifyRequest(s.transaction))))}async get(e){const t=await this.createStore(this._dbName,this._storeName);return await t("readonly",(t=>this.promisifyRequest(t.get(e))))}async remove(e){const t=await this.get(e),s=await this.createStore(this._dbName,this._storeName);return await s("readwrite",(t=>this.promisifyRequest(t.delete(e)))),t}async getAllKeys(){const e=await this.createStore(this._dbName,this._storeName);return await e("readonly",(e=>this.promisifyRequest(e.getAllKeys())))}promisifyRequest(e){return new Promise(((t,s)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>s(e.error)}))}async createStore(e,t){const s=indexedDB.open(e);s.onupgradeneeded=()=>s.result.createObjectStore(t);const i=await this.promisifyRequest(s);return async(e,s)=>{const n=i.transaction(t,e).objectStore(t);return await s(n)}}},get Log(){return Cs},Logger:js,MetadataService:Gs,OidcClient:gi,OidcClientSettingsStore:Ys,SessionMonitor:pi,SigninResponse:oi,SigninState:ii,SignoutResponse:ci,State:si,User:_i,UserManager:class{constructor(e,t,s,i){this._logger=new js("UserManager"),this.settings=new ki(e),this._client=new gi(e),this._redirectNavigator=null!=t?t:new xi(this.settings),this._popupNavigator=null!=s?s:new Oi(this.settings),this._iframeNavigator=null!=i?i:new Ii(this.settings),this._events=new Ei(this.settings),this._silentRenewService=new Ui(this),this.settings.automaticSilentRenew&&this.startSilentRenew(),this._sessionMonitor=null,this.settings.monitorSession&&(this._sessionMonitor=new pi(this))}get events(){return this._events}get metadataService(){return this._client.metadataService}async getUser(e=!1){const t=this._logger.create("getUser"),s=await this._loadUser();return s?(t.info("user loaded"),await this._events.load(s,e),s):(t.info("user not found in storage"),null)}async removeUser(){const e=this._logger.create("removeUser");await this.storeUser(null),e.info("user removed from storage"),await this._events.unload()}async signinRedirect(e={}){var t;this._logger.create("signinRedirect");const{redirectMethod:s,...i}=e;let n;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(n=await this.generateDPoPJkt(this.settings.dpop));const r=await this._redirectNavigator.prepare({redirectMethod:s});await this._signinStart({request_type:"si:r",dpopJkt:n,...i},r)}async signinRedirectCallback(e=window.location.href){const t=this._logger.create("signinRedirectCallback"),s=await this._signinEnd(e);return s.profile&&s.profile.sub?t.info("success, signed in subject",s.profile.sub):t.info("no subject"),s}async signinResourceOwnerCredentials({username:e,password:t,skipUserInfo:s=!1}){const i=this._logger.create("signinResourceOwnerCredential"),n=await this._client.processResourceOwnerPasswordCredentials({username:e,password:t,skipUserInfo:s,extraTokenParams:this.settings.extraTokenParams});i.debug("got signin response");const r=await this._buildUser(n);return r.profile&&r.profile.sub?i.info("success, signed in subject",r.profile.sub):i.info("no subject"),r}async signinPopup(e={}){var t;const s=this._logger.create("signinPopup");let i;(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(i=await this.generateDPoPJkt(this.settings.dpop));const{popupWindowFeatures:n,popupWindowTarget:r,popupSignal:o,...a}=e,c=this.settings.popup_redirect_uri;c||s.throw(new Error("No popup_redirect_uri configured"));const d=await this._popupNavigator.prepare({popupWindowFeatures:n,popupWindowTarget:r,popupSignal:o}),l=await this._signin({request_type:"si:p",redirect_uri:c,display:"popup",dpopJkt:i,...a},d);return l&&(l.profile&&l.profile.sub?s.info("success, signed in subject",l.profile.sub):s.info("no subject")),l}async signinPopupCallback(e=window.location.href,t=!1){const s=this._logger.create("signinPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),s.info("success")}async signinSilent(e={}){var t,s;const i=this._logger.create("signinSilent"),{silentRequestTimeoutInSeconds:n,...r}=e;let o,a=await this._loadUser();if(null==a?void 0:a.refresh_token){i.debug("using refresh token");const e=new Ri(a);return await this._useRefreshToken({state:e,redirect_uri:r.redirect_uri,resource:r.resource,extraTokenParams:r.extraTokenParams,timeoutInSeconds:n})}(null==(t=this.settings.dpop)?void 0:t.bind_authorization_code)&&(o=await this.generateDPoPJkt(this.settings.dpop));const c=this.settings.silent_redirect_uri;let d;c||i.throw(new Error("No silent_redirect_uri configured")),a&&this.settings.validateSubOnSilentRenew&&(i.debug("subject prior to silent renew:",a.profile.sub),d=a.profile.sub);const l=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:n});return a=await this._signin({request_type:"si:s",redirect_uri:c,prompt:"none",id_token_hint:this.settings.includeIdTokenInSilentRenew?null==a?void 0:a.id_token:void 0,dpopJkt:o,...r},l,d),a&&((null==(s=a.profile)?void 0:s.sub)?i.info("success, signed in subject",a.profile.sub):i.info("no subject")),a}async _useRefreshToken(e){const t=await this._client.useRefreshToken({timeoutInSeconds:this.settings.silentRequestTimeoutInSeconds,...e}),s=new _i({...e.state,...t});return await this.storeUser(s),await this._events.load(s),s}async signinSilentCallback(e=window.location.href){const t=this._logger.create("signinSilentCallback");await this._iframeNavigator.callback(e),t.info("success")}async signinCallback(e=window.location.href){const{state:t}=await this._client.readSigninResponseState(e);switch(t.request_type){case"si:r":return await this.signinRedirectCallback(e);case"si:p":await this.signinPopupCallback(e);break;case"si:s":await this.signinSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async signoutCallback(e=window.location.href,t=!1){const{state:s}=await this._client.readSignoutResponseState(e);if(s)switch(s.request_type){case"so:r":return await this.signoutRedirectCallback(e);case"so:p":await this.signoutPopupCallback(e,t);break;case"so:s":await this.signoutSilentCallback(e);break;default:throw new Error("invalid response_type in state")}}async querySessionStatus(e={}){const t=this._logger.create("querySessionStatus"),{silentRequestTimeoutInSeconds:s,...i}=e,n=this.settings.silent_redirect_uri;n||t.throw(new Error("No silent_redirect_uri configured"));const r=await this._loadUser(),o=await this._iframeNavigator.prepare({silentRequestTimeoutInSeconds:s}),a=await this._signinStart({request_type:"si:s",redirect_uri:n,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,...i},o);try{const e={},s=await this._client.processSigninResponse(a.url,e);return t.debug("got signin response"),s.session_state&&s.profile.sub?(t.info("success for subject",s.profile.sub),{session_state:s.session_state,sub:s.profile.sub}):(t.info("success, user not authenticated"),null)}catch(e){if(this.settings.monitorAnonymousSession&&e instanceof Ks)switch(e.error){case"login_required":case"consent_required":case"interaction_required":case"account_selection_required":return t.info("success for anonymous user"),{session_state:e.session_state}}throw e}}async _signin(e,t,s){const i=await this._signinStart(e,t);return await this._signinEnd(i.url,s)}async _signinStart(e,t){const s=this._logger.create("_signinStart");try{const i=await this._client.createSigninRequest(e);return s.debug("got signin request"),await t.navigate({url:i.url,state:i.state.id,response_mode:i.state.response_mode,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw s.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signinEnd(e,t){const s=this._logger.create("_signinEnd"),i=await this._client.processSigninResponse(e,{});s.debug("got signin response");return await this._buildUser(i,t)}async _buildUser(e,t){const s=this._logger.create("_buildUser"),i=new _i(e);if(t){if(t!==i.profile.sub)throw s.debug("current user does not match user returned from signin. sub from signin:",i.profile.sub),new Ks({...e,error:"login_required"});s.debug("current user matches user returned from signin")}return await this.storeUser(i),s.debug("user stored"),await this._events.load(i),i}async signoutRedirect(e={}){const t=this._logger.create("signoutRedirect"),{redirectMethod:s,...i}=e,n=await this._redirectNavigator.prepare({redirectMethod:s});await this._signoutStart({request_type:"so:r",post_logout_redirect_uri:this.settings.post_logout_redirect_uri,...i},n),t.info("success")}async signoutRedirectCallback(e=window.location.href){const t=this._logger.create("signoutRedirectCallback"),s=await this._signoutEnd(e);return t.info("success"),s}async signoutPopup(e={}){const t=this._logger.create("signoutPopup"),{popupWindowFeatures:s,popupWindowTarget:i,popupSignal:n,...r}=e,o=this.settings.popup_post_logout_redirect_uri,a=await this._popupNavigator.prepare({popupWindowFeatures:s,popupWindowTarget:i,popupSignal:n});await this._signout({request_type:"so:p",post_logout_redirect_uri:o,state:null==o?void 0:{},...r},a),t.info("success")}async signoutPopupCallback(e=window.location.href,t=!1){const s=this._logger.create("signoutPopupCallback");await this._popupNavigator.callback(e,{keepOpen:t}),s.info("success")}async _signout(e,t){const s=await this._signoutStart(e,t);return await this._signoutEnd(s.url)}async _signoutStart(e={},t){var s;const i=this._logger.create("_signoutStart");try{const n=await this._loadUser();i.debug("loaded current user from storage"),this.settings.revokeTokensOnSignout&&await this._revokeInternal(n);const r=e.id_token_hint||n&&n.id_token;r&&(i.debug("setting id_token_hint in signout request"),e.id_token_hint=r),await this.removeUser(),i.debug("user removed, creating signout request");const o=await this._client.createSignoutRequest(e);return i.debug("got signout request"),await t.navigate({url:o.url,state:null==(s=o.state)?void 0:s.id,scriptOrigin:this.settings.iframeScriptOrigin})}catch(e){throw i.debug("error after preparing navigator, closing navigator window"),t.close(),e}}async _signoutEnd(e){const t=this._logger.create("_signoutEnd"),s=await this._client.processSignoutResponse(e);return t.debug("got signout response"),s}async signoutSilent(e={}){var t;const s=this._logger.create("signoutSilent"),{silentRequestTimeoutInSeconds:i,...n}=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:i});await this._signout({request_type:"so:s",post_logout_redirect_uri:o,id_token_hint:r,...n},a),s.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 s=this._logger.create("_revokeInternal");if(!e)return;const i=t.filter((t=>"string"==typeof e[t]));if(i.length){for(const t of i)await this._client.revokeToken(e[t],t),s.info(`${t} revoked successfully`),"access_token"!==t&&(e[t]=null);await this.storeUser(e),s.debug("user stored"),await this._events.load(e)}else s.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"),_i.fromStorageString(t)):(e.debug("no user storageString"),null)}async storeUser(e){const t=this._logger.create("storeUser");if(e){t.debug("storing user");const s=e.toStorageString();await this.settings.userStore.set(this._userStoreKey,s)}else this._logger.debug("removing user"),await this.settings.userStore.remove(this._userStoreKey),this.settings.dpop&&await this.settings.dpop.store.remove(this.settings.client_id)}async clearStaleState(){await this._client.clearStaleState()}async dpopProof(e,t,s,i){var n,r;const o=await(null==(r=null==(n=this.settings.dpop)?void 0:n.store)?void 0:r.get(this.settings.client_id));if(o)return await $s.generateDPoPProof({url:e,accessToken:null==t?void 0:t.access_token,httpMethod:s,keyPair:o.keys,nonce:i})}async generateDPoPJkt(e){let t=await e.store.get(this.settings.client_id);if(!t){const s=await $s.generateDPoPKeys();t=new hi(s),await e.store.set(this.settings.client_id,t)}return await $s.generateDPoPJkt(t.keys)}},UserManagerSettingsStore:ki,Version:"3.2.0",WebStorageStateStore:Zs});return xs}));
4
4
  //# sourceMappingURL=index.umd.js.map