@descope/react-sdk 2.0.0-alpha.0 → 2.0.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/cjs/index.cjs.js +1 -1
- package/dist/cjs/index.cjs.js.map +1 -1
- package/dist/index.d.ts +112 -60
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +2 -2
- package/dist/index.umd.js.map +1 -1
- package/package.json +11 -11
package/dist/index.umd.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Descope={},e.React)}(this,(function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(t);const i=o.default.createContext(void 0),r=e=>(...t)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...t)},s=e=>(...t)=>{let n;try{n=e(...t)}catch(e){console.error(e)}return n},a={"x-descope-sdk-name":"react","x-descope-sdk-version":"2.0.0-alpha.0"},l="undefined"!=typeof window;var c=function(){return c=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},c.apply(this,arguments)};function d(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 i=0;for(o=Object.getOwnPropertySymbols(e);i<o.length;i++)t.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(e,o[i])&&(n[o[i]]=e[o[i]])}return n}function u(e,t,n,o){return new(n||(n=Promise))((function(i,r){function s(e){try{l(o.next(e))}catch(e){r(e)}}function a(e){try{l(o.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}l((o=o.apply(e,t||[])).next())}))}function h(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function p(e,t,n,o,i){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?i.call(e,n):i?i.value=n:t.set(e,n),n}function g(e){this.message=e}"function"==typeof SuppressedError&&SuppressedError,g.prototype=new Error,g.prototype.name="InvalidCharacterError";var f="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new g("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,i=0,r=0,s="";o=t.charAt(r++);~o&&(n=i%4?64*n+o:o,i++%4)?s+=String.fromCharCode(255&n>>(-2*i&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return s};function v(e){this.message=e}function m(e,t){if("string"!=typeof e)throw new v("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(function(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(f(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return f(t)}}(e.split(".")[n]))}catch(e){throw new v("Invalid token specified: "+e.message)}}v.prototype=new Error,v.prototype.name="InvalidTokenError";var b="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function w(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var y="__lodash_hash_undefined__",I="[object Function]",k="[object GeneratorFunction]",j=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,O=/^\w*$/,S=/^\./,x=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,C=/\\(\\)?/g,U=/^\[object .+?Constructor\]$/,A="object"==typeof b&&b&&b.Object===Object&&b,E="object"==typeof self&&self&&self.Object===Object&&self,R=A||E||Function("return this")();var P,T=Array.prototype,_=Function.prototype,$=Object.prototype,L=R["__core-js_shared__"],M=(P=/[^.]+$/.exec(L&&L.keys&&L.keys.IE_PROTO||""))?"Symbol(src)_1."+P:"",q=_.toString,D=$.hasOwnProperty,W=$.toString,N=RegExp("^"+q.call(D).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),J=R.Symbol,K=T.splice,F=te(R,"Map"),H=te(Object,"create"),z=J?J.prototype:void 0,V=z?z.toString:void 0;function B(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var o=e[t];this.set(o[0],o[1])}}function G(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var o=e[t];this.set(o[0],o[1])}}function Z(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var o=e[t];this.set(o[0],o[1])}}function Y(e,t){for(var n,o,i=e.length;i--;)if((n=e[i][0])===(o=t)||n!=n&&o!=o)return i;return-1}function X(e,t){var n;t=function(e,t){if(re(e))return!1;var n=typeof e;if("number"==n||"symbol"==n||"boolean"==n||null==e||ae(e))return!0;return O.test(e)||!j.test(e)||null!=t&&e in Object(t)}(t,e)?[t]:re(n=t)?n:ne(n);for(var o=0,i=t.length;null!=e&&o<i;)e=e[oe(t[o++])];return o&&o==i?e:void 0}function Q(e){if(!se(e)||(t=e,M&&M in t))return!1;var t,n=function(e){var t=se(e)?W.call(e):"";return t==I||t==k}(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e)?N:U;return n.test(function(e){if(null!=e){try{return q.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function ee(e,t){var n,o,i=e.__data__;return("string"==(o=typeof(n=t))||"number"==o||"symbol"==o||"boolean"==o?"__proto__"!==n:null===n)?i["string"==typeof t?"string":"hash"]:i.map}function te(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Q(n)?n:void 0}B.prototype.clear=function(){this.__data__=H?H(null):{}},B.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},B.prototype.get=function(e){var t=this.__data__;if(H){var n=t[e];return n===y?void 0:n}return D.call(t,e)?t[e]:void 0},B.prototype.has=function(e){var t=this.__data__;return H?void 0!==t[e]:D.call(t,e)},B.prototype.set=function(e,t){return this.__data__[e]=H&&void 0===t?y:t,this},G.prototype.clear=function(){this.__data__=[]},G.prototype.delete=function(e){var t=this.__data__,n=Y(t,e);return!(n<0)&&(n==t.length-1?t.pop():K.call(t,n,1),!0)},G.prototype.get=function(e){var t=this.__data__,n=Y(t,e);return n<0?void 0:t[n][1]},G.prototype.has=function(e){return Y(this.__data__,e)>-1},G.prototype.set=function(e,t){var n=this.__data__,o=Y(n,e);return o<0?n.push([e,t]):n[o][1]=t,this},Z.prototype.clear=function(){this.__data__={hash:new B,map:new(F||G),string:new B}},Z.prototype.delete=function(e){return ee(this,e).delete(e)},Z.prototype.get=function(e){return ee(this,e).get(e)},Z.prototype.has=function(e){return ee(this,e).has(e)},Z.prototype.set=function(e,t){return ee(this,e).set(e,t),this};var ne=ie((function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(ae(e))return V?V.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(t);var n=[];return S.test(e)&&n.push(""),e.replace(x,(function(e,t,o,i){n.push(o?i.replace(C,"$1"):t||e)})),n}));function oe(e){if("string"==typeof e||ae(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function ie(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var o=arguments,i=t?t.apply(this,o):o[0],r=n.cache;if(r.has(i))return r.get(i);var s=e.apply(this,o);return n.cache=r.set(i,s),s};return n.cache=new(ie.Cache||Z),n}ie.Cache=Z;var re=Array.isArray;function se(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function ae(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==W.call(e)}var le=w((function(e,t,n){var o=null==e?void 0:X(e,t);return void 0===o?n:o})),ce="/v1/auth/accesskey/exchange",de="/v1/auth/otp/verify",ue="/v1/auth/otp/signin",he="/v1/auth/otp/signup",pe={email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},ge="/v1/auth/otp/signup-in",fe="/v1/auth/magiclink/verify",ve="/v1/auth/magiclink/signin",me="/v1/auth/magiclink/signup",be={email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},we="/v1/auth/magiclink/signup-in",ye="/v1/auth/enchantedlink/verify",Ie="/v1/auth/enchantedlink/signin",ke="/v1/auth/enchantedlink/signup",je="/v1/auth/enchantedlink/pending-session",Oe={email:"/v1/auth/enchantedlink/update/email"},Se="/v1/auth/enchantedlink/signup-in",xe="/v1/auth/oauth/authorize",Ce="/v1/auth/oauth/exchange",Ue="/v1/auth/saml/authorize",Ae="/v1/auth/saml/exchange",Ee="/v1/auth/totp/verify",Re="/v1/auth/totp/signup",Pe="/v1/auth/totp/update",Te={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},_e={start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},$e={start:"/v1/auth/webauthn/signup-in/start"},Le={start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"},Me="/v1/auth/password/signup",qe="/v1/auth/password/signin",De="/v1/auth/password/reset",We="/v1/auth/password/update",Ne="/v1/auth/password/replace",Je="/v1/auth/password/policy",Ke="/v1/auth/refresh",Fe="/v1/auth/logout",He="/v1/auth/logoutall",ze="/v1/auth/me",Ve="/v1/flow/start",Be="/v1/flow/next";const Ge=6e5,Ze=()=>{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")}};var Ye;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(Ye||(Ye={}));const Xe=(...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}),{})),Qe=e=>void 0===e?void 0:JSON.stringify(e),et=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},tt=({baseUrl:e,projectId:t,baseConfig:n,logger:o,hooks:i,cookiePolicy:r,fetch:s})=>{const a=((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=>Ze().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 Ze().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(o)),o}:n})(o,s),l=async o=>{const s=(null==i?void 0:i.beforeRequest)?i.beforeRequest(o):o,{path:l,body:c,headers:d,queryParams:u,method:h,token:p}=s,g=await a((({path:e,baseUrl:t,queryParams:n})=>{const o=new URL(e,t);return n&&(o.search=new URLSearchParams(n).toString()),o})({path:l,baseUrl:e,queryParams:u}),{headers:Xe(et(t,p),{"x-descope-sdk-name":"core-js","x-descope-sdk-version":"1.9.2"},(null==n?void 0:n.baseHeaders)||{},d),method:h,body:Qe(c),credentials:r||"include"});return(null==i?void 0:i.afterRequest)&&await i.afterRequest(o,null==g?void 0:g.clone()),g};return{get:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:Ye.get,token:o}),post:(e,t,{headers:n,queryParams:o,token:i}={})=>l({path:e,headers:n,queryParams:o,body:t,method:Ye.post,token:i}),put:(e,t,{headers:n,queryParams:o,token:i}={})=>l({path:e,headers:n,queryParams:o,body:t,method:Ye.put,token:i}),delete:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:Ye.delete,token:o}),hooks:i}};var nt=429;function ot(e,t,n){var o;let i=it(e);t&&(i=null===(o=null==i?void 0:i.tenants)||void 0===o?void 0:o[t]);const r=null==i?void 0:i[n];return Array.isArray(r)?r:[]}function it(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return m(e)}function rt(e){const{exp:t}=it(e);return(new Date).getTime()/1e3>t}function st(e){let t=it(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function at(e,t){return ot(e,t,"permissions")}function lt(e,t){return ot(e,t,"roles")}const ct=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function dt(e,t){var n;const o=await e,i={code:o.status,ok:o.ok,response:o},r=await o.clone().json();return o.ok?i.data=t?t(r):r:(i.error=r,o.status===nt&&Object.assign(i.error,{retryAfter:Number.parseInt(null===(n=o.headers)||void 0===n?void 0:n.get("retry-after"))||0})),i}const ut=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),ht=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),pt=e=>t=>e.test(t),gt=pt(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),ft=pt(/^\+[1-9]{1}[0-9]{3,14}$/),vt=ut(gt,'"{val}" is not a valid email'),mt=ut(ft,'"{val}" is not a valid phone number'),bt=ut((1,e=>e.length>=1),"Minimum length is 1");const wt=ut((e=>"string"==typeof e),"Input is not a string"),yt=ut((e=>void 0===e),"Input is defined"),It=(kt=[wt(),yt()],"Input is not a string or undefined",(e="Input is not a string or undefined")=>t=>{const n=kt.filter((e=>e(t)));return!(n.length<kt.length)&&(e?e.replace("{val}",t):n.join(" OR "))});var kt;const jt=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>ht(...e).validate(n[t]))),t(...n)),Ot=e=>[wt(`"${e}" must be a string`),bt(`"${e}" must not be empty`)],St=e=>[wt(`"${e}" must be a string`),vt()],xt=e=>[wt(`"${e}" must be a string`),mt()],Ct=jt(Ot("accessKey")),Ut=e=>({exchange:Ct((t=>dt(e.post(ce,{},{token:t}))))});var At,Et;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(At||(At={})),function(e){e.email="email"}(Et||(Et={}));const Rt=Object.assign(Object.assign({},At),Et);var Pt;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(Pt||(Pt={}));const Tt=Ot("loginId"),_t=jt(Ot("token")),$t=jt(Tt),Lt=jt(Ot("pendingRef")),Mt=jt(Tt,St("email")),qt=e=>({verify:_t((t=>dt(e.post(ye,{token:t})))),signIn:$t(((t,n,o,i)=>dt(e.post(ct(Ie,Rt.email),{loginId:t,URI:n,loginOptions:o},{token:i})))),signUpOrIn:$t(((t,n)=>dt(e.post(ct(Se,Rt.email),{loginId:t,URI:n})))),signUp:$t(((t,n,o)=>dt(e.post(ct(ke,Rt.email),{loginId:t,URI:n,user:o})))),waitForSession:Lt(((t,n)=>new Promise((o=>{const{pollingIntervalMs:i,timeoutMs:r}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||Ge,Ge)}))(n);let s;const a=setInterval((async()=>{const n=await e.post(je,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),o(dt(Promise.resolve(n))))}),i);s=setTimeout((()=>{o({error:{errorDescription:`Session polling timeout exceeded: ${r}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),r)})))),update:{email:Mt(((t,n,o,i,r)=>dt(e.post(Oe.email,Object.assign({loginId:t,email:n,URI:o},r),{token:i}))))}}),Dt=jt(Ot("flowId")),Wt=jt(Ot("executionId"),Ot("stepId"),Ot("interactionId")),Nt=e=>({start:Dt(((t,n,o,i,r,s)=>dt(e.post(Ve,{flowId:t,options:n,conditionInteractionId:o,interactionId:i,input:r,version:s})))),next:Wt(((t,n,o,i,r)=>dt(e.post(Be,{executionId:t,stepId:n,interactionId:o,input:i,version:r}))))}),Jt=Ot("loginId"),Kt=jt(Ot("token")),Ft=jt(Jt),Ht=jt(Jt,xt("phone")),zt=jt(Jt,St("email")),Vt=e=>({verify:Kt((t=>dt(e.post(fe,{token:t})))),signIn:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ft(((t,o,i,r)=>dt(e.post(ct(ve,n),{loginId:t,URI:o,loginOptions:i},{token:r}))))})),{}),signUp:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ft(((t,o,i)=>dt(e.post(ct(me,n),{loginId:t,URI:o,user:i}))))})),{}),signUpOrIn:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ft(((t,o)=>dt(e.post(ct(we,n),{loginId:t,URI:o}))))})),{}),update:{email:zt(((t,n,o,i,r)=>dt(e.post(be.email,Object.assign({loginId:t,email:n,URI:o},r),{token:i})))),phone:Object.keys(At).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ht(((t,o,i,r,s)=>dt(e.post(ct(be.phone,n),Object.assign({loginId:t,phone:o,URI:i},s),{token:r}))))})),{})}});var Bt;!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"}(Bt||(Bt={}));const Gt=jt(Ot("code")),Zt=e=>({start:Object.keys(Bt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,o,i)=>dt(e.post(xe,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:i}))})),{}),exchange:Gt((t=>dt(e.post(Ce,{code:t}))))}),Yt=Ot("loginId"),Xt=jt(Yt,Ot("code")),Qt=jt(Yt),en=jt(Yt,xt("phone")),tn=jt(Yt,St("email")),nn=e=>({verify:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Xt(((t,o)=>dt(e.post(ct(de,n),{code:o,loginId:t}))))})),{}),signIn:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Qt(((t,o,i)=>dt(e.post(ct(ue,n),{loginId:t,loginOptions:o},{token:i}))))})),{}),signUp:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Qt(((t,o)=>dt(e.post(ct(he,n),{loginId:t,user:o}))))})),{}),signUpOrIn:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Qt((t=>dt(e.post(ct(ge,n),{loginId:t}))))})),{}),update:{email:tn(((t,n,o,i)=>dt(e.post(pe.email,Object.assign({loginId:t,email:n},i),{token:o})))),phone:Object.keys(At).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:en(((t,o,i,r)=>dt(e.post(ct(pe.phone,n),Object.assign({loginId:t,phone:o},r),{token:i}))))})),{})}}),on=jt(Ot("tenant")),rn=jt(Ot("code")),sn=e=>({start:on(((t,n,o,i)=>dt(e.post(Ue,o||{},{queryParams:{tenant:t,redirectURL:n},token:i})))),exchange:rn((t=>dt(e.post(Ae,{code:t}))))}),an=Ot("loginId"),ln=jt(an,Ot("code")),cn=jt(an),dn=jt(an),un=e=>({signUp:cn(((t,n)=>dt(e.post(Re,{loginId:t,user:n})))),verify:ln(((t,n,o,i)=>dt(e.post(Ee,{loginId:t,code:n,loginOptions:o},{token:i})))),update:dn(((t,n)=>dt(e.post(Pe,{loginId:t},{token:n}))))}),hn=Ot("loginId"),pn=Ot("newPassword"),gn=jt(hn,Ot("password")),fn=jt(hn),vn=jt(hn,pn),mn=jt(hn,Ot("oldPassword"),pn),bn=e=>({signUp:gn(((t,n,o)=>dt(e.post(Me,{loginId:t,password:n,user:o})))),signIn:gn(((t,n)=>dt(e.post(qe,{loginId:t,password:n})))),sendReset:fn(((t,n)=>dt(e.post(De,{loginId:t,redirectUrl:n})))),update:vn(((t,n,o)=>dt(e.post(We,{loginId:t,newPassword:n},{token:o})))),replace:mn(((t,n,o)=>dt(e.post(Ne,{loginId:t,oldPassword:n,newPassword:o})))),policy:()=>dt(e.get(Je))}),wn=[wt('"loginId" must be a string')],yn=Ot("loginId"),In=Ot("origin"),kn=jt(yn,In,Ot("name")),jn=jt(yn,In),On=jt(wn,In),Sn=jt(yn,In,Ot("token")),xn=jt(Ot("transactionId"),Ot("response")),Cn=e=>({signUp:{start:kn(((t,n,o)=>dt(e.post(Te.start,{user:{loginId:t,name:o},origin:n})))),finish:xn(((t,n)=>dt(e.post(Te.finish,{transactionId:t,response:n}))))},signIn:{start:On(((t,n,o,i)=>dt(e.post(_e.start,{loginId:t,origin:n,loginOptions:o},{token:i})))),finish:xn(((t,n)=>dt(e.post(_e.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:jn(((t,n)=>dt(e.post($e.start,{loginId:t,origin:n}))))},update:{start:Sn(((t,n,o)=>dt(e.post(Le.start,{loginId:t,origin:n},{token:o})))),finish:xn(((t,n)=>dt(e.post(Le.finish,{transactionId:t,response:n}))))}}),Un=jt(Ot("token")),An=jt([It('"token" must be string or undefined')]);var En,Rn=jt([("projectId",En=Ot("projectId"),ut(((e,t)=>n=>ht(...t).validate(le(n,e)))("projectId",En))())])((e=>{var t,n;const o=[].concat((null===(t=e.hooks)||void 0===t?void 0:t.beforeRequest)||[]),i=[].concat((null===(n=e.hooks)||void 0===n?void 0:n.afterRequest)||[]);return(({projectId:e,logger:t,baseUrl:n,hooks:o,cookiePolicy:i,baseHeaders:r={},fetch:s})=>{return a=tt({baseUrl:n||"https://api.descope.com",projectId:e,logger:t,hooks:o,cookiePolicy:i,baseConfig:{baseHeaders:r},fetch:s}),{accessKey:Ut(a),otp:nn(a),magicLink:Vt(a),enchantedLink:qt(a),oauth:Zt(a),saml:sn(a),totp:un(a),webauthn:Cn(a),password:bn(a),flow:Nt(a),refresh:An((e=>dt(a.post(Ke,{},{token:e})))),logout:An((e=>dt(a.post(Fe,{},{token:e})))),logoutAll:An((e=>dt(a.post(He,{},{token:e})))),me:An((e=>dt(a.get(ze,{token:e})))),isJwtExpired:Un(rt),getTenants:Un(st),getJwtPermissions:Un(at),getJwtRoles:Un(lt),httpClient:a};var a})(Object.assign(Object.assign({},e),{hooks:{beforeRequest:e=>null==o?void 0:o.reduce(((e,t)=>t(e)),e),afterRequest:async(t,n)=>{(await Promise.allSettled(null==i?void 0:i.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))}))}}}))}));const Pn=(e,t,n)=>(t.forEach((t=>{const o=t.split(".");let i=o.shift(),r=e;for(;o.length>0;){if(r=r[i],!i||!r)throw Error(`Invalid path "${t}", "${i}" is missing or has no value`);i=o.shift()}if("function"!=typeof r[i])throw Error(`"${t}" is not a function`);const s=r[i];r[i]=n(s)})),e);var Tn=Object.assign(Rn,{DeliveryMethods:Rt});var _n="Blocked by CSP",$n="9319";function Ln(e,t){var n=[];return function(e,t){var n,o,i=(o=function(e,t,n){if(n||2===arguments.length)for(var o,i=0,r=t.length;i<r;i++)!o&&i in t||(o||(o=Array.prototype.slice.call(t,0,i)),o[i]=t[i]);return e.concat(o||Array.prototype.slice.call(t))}([],e,!0),{current:function(){return o[0]},postpone:function(){var e=o.shift();void 0!==e&&o.push(e)},exclude:function(){o.shift()}}),r=(100,3e3,n=0,function(){return Math.random()*Math.min(3e3,100*Math.pow(2,n++))}),s=i.current();if(void 0===s)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var a=function(e,n){return t(e).catch((function(e){if(n+1>=5)throw e;!function(e){if(!(e instanceof Error))return!1;var t=e.message;return t===_n||t===$n}(e)?i.postpone():i.exclude();var t,o=i.current();if(void 0===o)throw e;return(t=r(),new Promise((function(e){return setTimeout(e,t)}))).then((function(){return a(o,n+1)}))}))};return a(s,0)}(e,(function(e){var o=new Date,i=function(t){return n.push({url:e,startedAt:o,finishedAt:new Date,error:t})},r=t(e);return r.then((function(){return i()}),i),r})).then((function(e){return[e,{attempts:n}]}))}var Mn="Failed to load the JS script of the agent";function qn(e){var t;e.scriptUrlPattern;var n=e.token,o=e.apiKey,i=void 0===o?n:o,r=d(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:"https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js";return Promise.resolve().then((function(){if(!i||"string"!=typeof i)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.8.5"):e}))}(String(e),t)}))}(s,i);return Ln(e,Dn).catch(Nn)})).then((function(e){var t=e[0],n=e[1];return t.load(c(c({},r),{ldi:n}))}))}function Dn(e){return function(e,t,n,o){var i,r=document,s="securitypolicyviolation",a=function(t){var n=new URL(e,location.href),o=t.blockedURI;o!==n.href&&o!==n.protocol.slice(0,-1)&&o!==n.origin||(i=t,l())};r.addEventListener(s,a);var l=function(){return r.removeEventListener(s,a)};return Promise.resolve().then(t).then((function(e){return l(),e}),(function(e){return new Promise((function(e){return setTimeout(e)})).then((function(){if(l(),i)return function(){throw new Error(_n)}();throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,n){var o=document.createElement("script"),i=function(){var e;return null===(e=o.parentNode)||void 0===e?void 0:e.removeChild(o)},r=document.head||document.getElementsByTagName("head")[0];o.onload=function(){i(),t()},o.onerror=function(){i(),n(new Error(Mn))},o.async=!0,o.src=e,r.appendChild(o)}))}(e)})).then(Wn)}function Wn(){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($n);return n}function Nn(e){throw e instanceof Error&&e.message===$n?new Error(Mn):e}var Jn={exports:{}};
|
|
2
|
-
/*! js-cookie v3.0.5 | MIT */!function(e,t){e.exports=function(){function e(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)e[o]=n[o]}return e}function t(n,o){function i(t,i,r){if("undefined"!=typeof document){"number"==typeof(r=e({},o,r)).expires&&(r.expires=new Date(Date.now()+864e5*r.expires)),r.expires&&(r.expires=r.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var s="";for(var a in r)r[a]&&(s+="; "+a,!0!==r[a]&&(s+="="+r[a].split(";")[0]));return document.cookie=t+"="+n.write(i,t)+s}}function r(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],o={},i=0;i<t.length;i++){var r=t[i].split("="),s=r.slice(1).join("=");try{var a=decodeURIComponent(r[0]);if(o[a]=n.read(s,a),e===a)break}catch(e){}}return e?o[e]:o}}return Object.create({set:i,get:r,remove:function(t,n){i(t,"",e({},n,{expires:-1}))},withAttributes:function(n){return t(this.converter,e({},this.attributes,n))},withConverter:function(n){return t(e({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(o)},converter:{value:Object.freeze(n)}})}return 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:"/"})}()}(Jn);var Kn=w(Jn.exports);const Fn=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,o)=>{var i;return n[o]=[].concat((null===(i=e.hooks)||void 0===i?void 0:i[o])||[]).concat((null==t?void 0:t[o])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},Hn=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||{}},zn=async e=>{const t=await Hn(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)},Vn="undefined"!=typeof localStorage,Bn=(e,t)=>Vn&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),Gn=e=>Vn&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),Zn=e=>Vn&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e)),Yn=(...e)=>{console.debug(...e)},Xn="undefined"!=typeof window,Qn=Math.pow(2,31)-1,eo=Xn&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",to=(e="",t="")=>({vsid:e,vrid:t}),no=(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},oo=e=>(e.body&&(e.body.fpData=no(!0)||to()),e),io="dls_last_user_login_id",ro="dls_last_user_display_name",so=()=>Gn(io),ao=()=>Gn(ro),lo=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,i=so(),r=ao();return i&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=i,o.lastAuth.name=r),await e(...t)},co=e=>async(...t)=>{const n=await e(...t);return Zn(io),Zn(ro),n};function uo(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const ho="DS",po="DSR";function go(e=""){return Gn(`${e}${po}`)||""}function fo(e=""){Zn(`${e}${po}`),Zn(`${e}${ho}`),Kn.remove(ho)}async function vo(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=ko(n.publicKey.challenge),n.publicKey.user.id=ko(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=ko(e.id)})),n}(e);return n=await navigator.credentials.create(t),JSON.stringify({id:n.id,rawId:jo(n.rawId),type:n.type,response:{attestationObject:jo(n.response.attestationObject),clientDataJSON:jo(n.response.clientDataJSON)}});var n}async function mo(e){const t=yo(e);return Io(await navigator.credentials.get(t))}async function bo(e,t){const n=yo(e);return n.signal=t.signal,n.mediation="conditional",Io(await navigator.credentials.get(n))}async function wo(e=!1){if(!Xn)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 yo(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=ko(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=ko(e.id)})),n}function Io(e){return JSON.stringify({id:e.id,rawId:jo(e.rawId),type:e.type,response:{authenticatorData:jo(e.response.authenticatorData),clientDataJSON:jo(e.response.clientDataJSON),signature:jo(e.response.signature),userHandle:e.response.userHandle?jo(e.response.userHandle):void 0}})}function ko(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function jo(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var Oo,So=(Oo=e=>({async signUp(t,n){const o=await e.webauthn.signUp.start(t,window.location.origin,n);if(!o.ok)return o;const i=await vo(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,i)},async signIn(t){const n=await e.webauthn.signIn.start(t,window.location.origin);if(!n.ok)return n;const o=await mo(n.data.options);return await e.webauthn.signIn.finish(n.data.transactionId,o)},async signUpOrIn(t){var n;const o=await e.webauthn.signUpOrIn.start(t,window.location.origin);if(!o.ok)return o;if(null===(n=o.data)||void 0===n?void 0:n.create){const t=await vo(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,t)}{const t=await mo(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,t)}},async update(t,n){const o=await e.webauthn.update.start(t,window.location.origin,n);if(!o.ok)return o;const i=await vo(o.data.options);return await e.webauthn.update.finish(o.data.transactionId,i)},helpers:{create:vo,get:mo,isSupported:wo,conditional:bo}}),(...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}),xo=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await wo(),o=Object.assign(Object.assign({redirectUrl:window.location.href,location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n}});return t[1]=o,e.flow.start(...t)}});const Co=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>t=>{var{fpKey:n,fpLoad:o}=t,i=d(t,["fpKey","fpLoad"]);return n?(Xn?o&&(async e=>{try{if(no())return;const t=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),n=qn({apiKey:e,endpoint:eo}),o=await n,{requestId:i}=await o.get({linkedId:t});(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem("fp",JSON.stringify(t))})(to(t,i))}catch(e){global.FB_DEBUG&&console.error(e)}})(n).catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server"),e(Fn(i,{beforeRequest:oo}))):e(Object.assign({},i))}),(e=>t=>{var{autoRefresh:n}=t,o=d(t,["autoRefresh"]);if(!n)return e(o);const{clearAllTimers:i,setTimer:r}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let s,a;document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&new Date>s&&(Yn("Expiration time passed, refreshing session"),l.refresh(a))}));const l=e(Fn(o,{afterRequest:async(e,t)=>{const{refreshJwt:n,sessionJwt:o}=await Hn(t);if(401===(null==t?void 0:t.status))Yn("Received 401, canceling all timers"),i();else if(o){s=(e=>{const t=e.split(".");try{if(3===t.length){const e=JSON.parse(window.atob(t[1]));if(e.exp)return new Date(1e3*e.exp)}}catch(e){}return null})(o),a=n;let e=((c=s)?c.getTime()-(new Date).getTime():0)-2e4;e>Qn&&(Yn(`Timeout is too large (${e}ms), setting it to ${Qn}ms`),e=Qn),i();const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});Yn(`Setting refresh timer for ${t}. (${e}ms)`),r((()=>{Yn("Refreshing session due to timer"),l.refresh(n)}),e)}var c}}));return Pn(l,["logout","logoutAll"],(e=>async(...t)=>{const n=await e(...t);return Yn("Clearing all timers"),i(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.6.3"},t.baseHeaders)}))),(e=>t=>{const n=uo(),o=uo(),i=e(Fn(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))n.pub(null),o.pub(null);else{const e=await zn(t);e&&o.pub(e);const{sessionJwt:i}=await Hn(t);i&&n.pub(i)}}})),r=Pn(i,["logout","logoutAll"],(e=>async(...t)=>{const i=await e(...t);return n.pub(null),o.pub(null),i}));return Object.assign(r,{onSessionTokenChange:n.sub,onUserChange:o.sub})}),(e=>t=>{const n=e(Fn(t,{afterRequest:async(e,t)=>{var n;const o=await zn(t),i=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],r=null==o?void 0:o.name;i&&((e=>{Bn(io,e)})(i),(e=>{Bn(ro,e)})(r))}}));let o=Pn(n,["flow.start"],lo);return o=Pn(o,["logout","logoutAll"],co),Object.assign(o,{getLastUserLoginId:so,getLastUserDisplayName:ao})}),(e=>t=>{var{persistTokens:n,sessionTokenViaCookie:o,storagePrefix:i}=t,r=d(t,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!n||!Xn)return n&&console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),e(r);const s=e(Fn(r,{beforeRequest:(a=i,e=>Object.assign(e,{token:e.token||go(a)})),afterRequest:async(e,t)=>{401===(null==t?void 0:t.status)?fo(i):((e={},t,n)=>{var{refreshJwt:o,sessionJwt:i}=e,r=d(e,["refreshJwt","sessionJwt"]);void 0===t&&(t=!1),void 0===n&&(n=""),o&&Bn(`${n}${po}`,o),i&&(t?function(e,t,{cookiePath:n,cookieDomain:o,cookieExpiration:i}){if(t){const r=new Date(1e3*i);Kn.set(e,t,{path:n,domain:o,expires:r,sameSite:"Strict",secure:!0})}}(ho,i,r):Bn(`${n}${ho}`,i))})(await Hn(t),o,i)}}));var a;const l=Pn(s,["logout","logoutAll"],(e=>t=>async(...n)=>{const o=await t(...n);return fo(e),o})(i));return Object.assign(l,{getRefreshToken:()=>go(i),getSessionToken:()=>function(e=""){return Kn.get(ho)||Gn(`${e}${ho}`)||""}(i)})}))(((...e)=>{const t=Tn(...e);return Object.assign(Object.assign({},t),{flow:xo(t),webauthn:So(t)})}));let Uo;const Ao=e=>{const t=Co({...e,persistTokens:l,autoRefresh:l});return Uo=t,t};Uo=Ao({projectId:"temp pid"});const Eo=()=>l?Uo?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),Ro=()=>l?Uo?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),Po=s(((e=Eo(),t)=>Uo?.getJwtPermissions(e,t))),To=s(((e=Eo(),t)=>Uo?.getJwtRoles(e,t)));const _o=t.lazy((async()=>((await Promise.resolve().then((function(){return Ul}))).default.sdkConfigOverrides={baseHeaders:a},{default:({projectId:e,flowId:t,baseUrl:n,innerRef:i,tenant:r,theme:s,locale:a,debug:l,telemetryKey:c,redirectUrl:d,autoFocus:u})=>o.default.createElement("descope-wc",{"project-id":e,"flow-id":t,"base-url":n,ref:i,tenant:r,theme:s,locale:a,debug:l,telemetryKey:c,"redirect-url":d,"auto-focus":u})}))),$o=o.default.forwardRef((({flowId:e,onSuccess:n,onError:r,logger:s,tenant:a,theme:l,locale:c,debug:d,telemetryKey:u,redirectUrl:h,autoFocus:p,errorTransformer:g},f)=>{const[v,m]=t.useState(null);t.useImperativeHandle(f,(()=>v));const{projectId:b,baseUrl:w,sdk:y}=o.default.useContext(i),I=t.useCallback((async e=>{await y.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),n&&n(e)}),[n]);return t.useEffect((()=>{const e=v;return e?.addEventListener("success",I),r&&e?.addEventListener("error",r),()=>{r&&e?.removeEventListener("error",r),e?.removeEventListener("success",I)}}),[v,r,I]),t.useEffect((()=>{v&&(v.errorTransformer=g)}),[v,g]),t.useEffect((()=>{v&&s&&(v.logger=s)}),[v,s]),o.default.createElement("form",null,o.default.createElement(t.Suspense,{fallback:null},o.default.createElement(_o,{projectId:b,flowId:e,baseUrl:w,innerRef:m,tenant:a,theme:l,locale:c,debug:d,telemetryKey:u,redirectUrl:h,autoFocus:p})))}));var Lo=()=>{const e=t.useContext(i);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const Mo=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,qo={get(e,t){if("object"==typeof e[t]&&null!==e[t])return new Proxy(e[t],qo);if("function"==typeof e[t])return()=>{throw Error(Mo("function"))};throw Error(Mo("attribute"))}};var Do="/v1/auth/accesskey/exchange",Wo="/v1/auth/otp/verify",No="/v1/auth/otp/signin",Jo="/v1/auth/otp/signup",Ko={email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},Fo="/v1/auth/otp/signup-in",Ho="/v1/auth/magiclink/verify",zo="/v1/auth/magiclink/signin",Vo="/v1/auth/magiclink/signup",Bo={email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},Go="/v1/auth/magiclink/signup-in",Zo="/v1/auth/enchantedlink/verify",Yo="/v1/auth/enchantedlink/signin",Xo="/v1/auth/enchantedlink/signup",Qo="/v1/auth/enchantedlink/pending-session",ei={email:"/v1/auth/enchantedlink/update/email"},ti="/v1/auth/enchantedlink/signup-in",ni="/v1/auth/oauth/authorize",oi="/v1/auth/oauth/exchange",ii="/v1/auth/saml/authorize",ri="/v1/auth/saml/exchange",si="/v1/auth/totp/verify",ai="/v1/auth/totp/signup",li="/v1/auth/totp/update",ci={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},di={start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},ui={start:"/v1/auth/webauthn/signup-in/start"},hi={start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"},pi="/v1/auth/password/signup",gi="/v1/auth/password/signin",fi="/v1/auth/password/reset",vi="/v1/auth/password/update",mi="/v1/auth/password/replace",bi="/v1/auth/password/policy",wi="/v1/auth/refresh",yi="/v1/auth/logout",Ii="/v1/auth/logoutall",ki="/v1/auth/me",ji="/v1/flow/start",Oi="/v1/flow/next";const Si=6e5,xi=()=>{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")}};var Ci;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(Ci||(Ci={}));const Ui=(...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}),{})),Ai=e=>void 0===e?void 0:JSON.stringify(e),Ei=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},Ri=({baseUrl:e,projectId:t,baseConfig:n,logger:o,hooks:i,cookiePolicy:r,fetch:s})=>{const a=((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=>xi().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 xi().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(o)),o}:n})(o,s),l=async o=>{const s=(null==i?void 0:i.beforeRequest)?i.beforeRequest(o):o,{path:l,body:c,headers:d,queryParams:u,method:h,token:p}=s,g=await a((({path:e,baseUrl:t,queryParams:n})=>{const o=new URL(e,t);return n&&(o.search=new URLSearchParams(n).toString()),o})({path:l,baseUrl:e,queryParams:u}),{headers:Ui(Ei(t,p),{"x-descope-sdk-name":"core-js","x-descope-sdk-version":"1.9.2-alpha.0"},(null==n?void 0:n.baseHeaders)||{},d),method:h,body:Ai(c),credentials:r||"include"});return(null==i?void 0:i.afterRequest)&&await i.afterRequest(o,null==g?void 0:g.clone()),g};return{get:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:Ci.get,token:o}),post:(e,t,{headers:n,queryParams:o,token:i}={})=>l({path:e,headers:n,queryParams:o,body:t,method:Ci.post,token:i}),put:(e,t,{headers:n,queryParams:o,token:i}={})=>l({path:e,headers:n,queryParams:o,body:t,method:Ci.put,token:i}),delete:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:Ci.delete,token:o}),hooks:i}};var Pi=429;function Ti(e,t,n){var o;let i=_i(e);t&&(i=null===(o=null==i?void 0:i.tenants)||void 0===o?void 0:o[t]);const r=null==i?void 0:i[n];return Array.isArray(r)?r:[]}function _i(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return m(e)}function $i(e){const{exp:t}=_i(e);return(new Date).getTime()/1e3>t}function Li(e){let t=_i(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function Mi(e,t){return Ti(e,t,"permissions")}function qi(e,t){return Ti(e,t,"roles")}const Di=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function Wi(e,t){var n;const o=await e,i={code:o.status,ok:o.ok,response:o},r=await o.clone().json();return o.ok?i.data=t?t(r):r:(i.error=r,o.status===Pi&&Object.assign(i.error,{retryAfter:Number.parseInt(null===(n=o.headers)||void 0===n?void 0:n.get("retry-after"))||0})),i}const Ni=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),Ji=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),Ki=e=>t=>e.test(t),Fi=Ki(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),Hi=Ki(/^\+[1-9]{1}[0-9]{3,14}$/),zi=Ni(Fi,'"{val}" is not a valid email'),Vi=Ni(Hi,'"{val}" is not a valid phone number'),Bi=Ni((1,e=>e.length>=1),"Minimum length is 1");const Gi=Ni((e=>"string"==typeof e),"Input is not a string"),Zi=Ni((e=>void 0===e),"Input is defined"),Yi=(Xi=[Gi(),Zi()],"Input is not a string or undefined",(e="Input is not a string or undefined")=>t=>{const n=Xi.filter((e=>e(t)));return!(n.length<Xi.length)&&(e?e.replace("{val}",t):n.join(" OR "))});var Xi;const Qi=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>Ji(...e).validate(n[t]))),t(...n)),er=e=>[Gi(`"${e}" must be a string`),Bi(`"${e}" must not be empty`)],tr=e=>[Gi(`"${e}" must be a string`),zi()],nr=e=>[Gi(`"${e}" must be a string`),Vi()],or=Qi(er("accessKey")),ir=e=>({exchange:or((t=>Wi(e.post(Do,{},{token:t}))))});var rr,sr;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(rr||(rr={})),function(e){e.email="email"}(sr||(sr={}));const ar=Object.assign(Object.assign({},rr),sr);var lr;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(lr||(lr={}));const cr=er("loginId"),dr=Qi(er("token")),ur=Qi(cr),hr=Qi(er("pendingRef")),pr=Qi(cr,tr("email")),gr=e=>({verify:dr((t=>Wi(e.post(Zo,{token:t})))),signIn:ur(((t,n,o,i)=>Wi(e.post(Di(Yo,ar.email),{loginId:t,URI:n,loginOptions:o},{token:i})))),signUpOrIn:ur(((t,n)=>Wi(e.post(Di(ti,ar.email),{loginId:t,URI:n})))),signUp:ur(((t,n,o)=>Wi(e.post(Di(Xo,ar.email),{loginId:t,URI:n,user:o})))),waitForSession:hr(((t,n)=>new Promise((o=>{const{pollingIntervalMs:i,timeoutMs:r}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||Si,Si)}))(n);let s;const a=setInterval((async()=>{const n=await e.post(Qo,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),o(Wi(Promise.resolve(n))))}),i);s=setTimeout((()=>{o({error:{errorDescription:`Session polling timeout exceeded: ${r}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),r)})))),update:{email:pr(((t,n,o,i,r)=>Wi(e.post(ei.email,Object.assign({loginId:t,email:n,URI:o},r),{token:i}))))}}),fr=Qi(er("flowId")),vr=Qi(er("executionId"),er("stepId"),er("interactionId")),mr=e=>({start:fr(((t,n,o,i,r,s,a)=>Wi(e.post(ji,{flowId:t,options:n,conditionInteractionId:o,interactionId:i,version:r,componentsVersion:s,input:a})))),next:vr(((t,n,o,i,r,s)=>Wi(e.post(Oi,{executionId:t,stepId:n,interactionId:o,version:i,componentsVersion:r,input:s}))))}),br=er("loginId"),wr=Qi(er("token")),yr=Qi(br),Ir=Qi(br,nr("phone")),kr=Qi(br,tr("email")),jr=e=>({verify:wr((t=>Wi(e.post(Ho,{token:t})))),signIn:Object.keys(ar).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:yr(((t,o,i,r)=>Wi(e.post(Di(zo,n),{loginId:t,URI:o,loginOptions:i},{token:r}))))})),{}),signUp:Object.keys(ar).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:yr(((t,o,i)=>Wi(e.post(Di(Vo,n),{loginId:t,URI:o,user:i}))))})),{}),signUpOrIn:Object.keys(ar).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:yr(((t,o)=>Wi(e.post(Di(Go,n),{loginId:t,URI:o}))))})),{}),update:{email:kr(((t,n,o,i,r)=>Wi(e.post(Bo.email,Object.assign({loginId:t,email:n,URI:o},r),{token:i})))),phone:Object.keys(rr).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ir(((t,o,i,r,s)=>Wi(e.post(Di(Bo.phone,n),Object.assign({loginId:t,phone:o,URI:i},s),{token:r}))))})),{})}});var Or;!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"}(Or||(Or={}));const Sr=Qi(er("code")),xr=e=>({start:Object.keys(Or).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,o,i)=>Wi(e.post(ni,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:i}))})),{}),exchange:Sr((t=>Wi(e.post(oi,{code:t}))))}),Cr=er("loginId"),Ur=Qi(Cr,er("code")),Ar=Qi(Cr),Er=Qi(Cr,nr("phone")),Rr=Qi(Cr,tr("email")),Pr=e=>({verify:Object.keys(ar).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ur(((t,o)=>Wi(e.post(Di(Wo,n),{code:o,loginId:t}))))})),{}),signIn:Object.keys(ar).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ar(((t,o,i)=>Wi(e.post(Di(No,n),{loginId:t,loginOptions:o},{token:i}))))})),{}),signUp:Object.keys(ar).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ar(((t,o)=>Wi(e.post(Di(Jo,n),{loginId:t,user:o}))))})),{}),signUpOrIn:Object.keys(ar).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ar((t=>Wi(e.post(Di(Fo,n),{loginId:t}))))})),{}),update:{email:Rr(((t,n,o,i)=>Wi(e.post(Ko.email,Object.assign({loginId:t,email:n},i),{token:o})))),phone:Object.keys(rr).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Er(((t,o,i,r)=>Wi(e.post(Di(Ko.phone,n),Object.assign({loginId:t,phone:o},r),{token:i}))))})),{})}}),Tr=Qi(er("tenant")),_r=Qi(er("code")),$r=e=>({start:Tr(((t,n,o,i)=>Wi(e.post(ii,o||{},{queryParams:{tenant:t,redirectURL:n},token:i})))),exchange:_r((t=>Wi(e.post(ri,{code:t}))))}),Lr=er("loginId"),Mr=Qi(Lr,er("code")),qr=Qi(Lr),Dr=Qi(Lr),Wr=e=>({signUp:qr(((t,n)=>Wi(e.post(ai,{loginId:t,user:n})))),verify:Mr(((t,n,o,i)=>Wi(e.post(si,{loginId:t,code:n,loginOptions:o},{token:i})))),update:Dr(((t,n)=>Wi(e.post(li,{loginId:t},{token:n}))))}),Nr=er("loginId"),Jr=er("newPassword"),Kr=Qi(Nr,er("password")),Fr=Qi(Nr),Hr=Qi(Nr,Jr),zr=Qi(Nr,er("oldPassword"),Jr),Vr=e=>({signUp:Kr(((t,n,o)=>Wi(e.post(pi,{loginId:t,password:n,user:o})))),signIn:Kr(((t,n)=>Wi(e.post(gi,{loginId:t,password:n})))),sendReset:Fr(((t,n)=>Wi(e.post(fi,{loginId:t,redirectUrl:n})))),update:Hr(((t,n,o)=>Wi(e.post(vi,{loginId:t,newPassword:n},{token:o})))),replace:zr(((t,n,o)=>Wi(e.post(mi,{loginId:t,oldPassword:n,newPassword:o})))),policy:()=>Wi(e.get(bi))}),Br=[Gi('"loginId" must be a string')],Gr=er("loginId"),Zr=er("origin"),Yr=Qi(Gr,Zr,er("name")),Xr=Qi(Gr,Zr),Qr=Qi(Br,Zr),es=Qi(Gr,Zr,er("token")),ts=Qi(er("transactionId"),er("response")),ns=e=>({signUp:{start:Yr(((t,n,o)=>Wi(e.post(ci.start,{user:{loginId:t,name:o},origin:n})))),finish:ts(((t,n)=>Wi(e.post(ci.finish,{transactionId:t,response:n}))))},signIn:{start:Qr(((t,n,o,i)=>Wi(e.post(di.start,{loginId:t,origin:n,loginOptions:o},{token:i})))),finish:ts(((t,n)=>Wi(e.post(di.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:Xr(((t,n)=>Wi(e.post(ui.start,{loginId:t,origin:n}))))},update:{start:es(((t,n,o)=>Wi(e.post(hi.start,{loginId:t,origin:n},{token:o})))),finish:ts(((t,n)=>Wi(e.post(hi.finish,{transactionId:t,response:n}))))}}),os=Qi(er("token")),is=Qi([Yi('"token" must be string or undefined')]);var rs,ss=Qi([("projectId",rs=er("projectId"),Ni(((e,t)=>n=>Ji(...t).validate(le(n,e)))("projectId",rs))())])((e=>{var t,n;const o=[].concat((null===(t=e.hooks)||void 0===t?void 0:t.beforeRequest)||[]),i=[].concat((null===(n=e.hooks)||void 0===n?void 0:n.afterRequest)||[]);return(({projectId:e,logger:t,baseUrl:n,hooks:o,cookiePolicy:i,baseHeaders:r={},fetch:s})=>{return a=Ri({baseUrl:n||"https://api.descope.com",projectId:e,logger:t,hooks:o,cookiePolicy:i,baseConfig:{baseHeaders:r},fetch:s}),{accessKey:ir(a),otp:Pr(a),magicLink:jr(a),enchantedLink:gr(a),oauth:xr(a),saml:$r(a),totp:Wr(a),webauthn:ns(a),password:Vr(a),flow:mr(a),refresh:is((e=>Wi(a.post(wi,{},{token:e})))),logout:is((e=>Wi(a.post(yi,{},{token:e})))),logoutAll:is((e=>Wi(a.post(Ii,{},{token:e})))),me:is((e=>Wi(a.get(ki,{token:e})))),isJwtExpired:os($i),getTenants:os(Li),getJwtPermissions:os(Mi),getJwtRoles:os(qi),httpClient:a};var a})(Object.assign(Object.assign({},e),{hooks:{beforeRequest:e=>null==o?void 0:o.reduce(((e,t)=>t(e)),e),afterRequest:async(t,n)=>{(await Promise.allSettled(null==i?void 0:i.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))}))}}}))}));const as=(e,t,n)=>(t.forEach((t=>{const o=t.split(".");let i=o.shift(),r=e;for(;o.length>0;){if(r=r[i],!i||!r)throw Error(`Invalid path "${t}", "${i}" is missing or has no value`);i=o.shift()}if("function"!=typeof r[i])throw Error(`"${t}" is not a function`);const s=r[i];r[i]=n(s)})),e);var ls=Object.assign(ss,{DeliveryMethods:ar});const cs=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,o)=>{var i;return n[o]=[].concat((null===(i=e.hooks)||void 0===i?void 0:i[o])||[]).concat((null==t?void 0:t[o])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e},ds=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||{}},us=async e=>{const t=await ds(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)},hs="undefined"!=typeof localStorage,ps=(e,t)=>hs&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),gs=e=>hs&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),fs=e=>hs&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e)),vs=(...e)=>{console.debug(...e)},ms="undefined"!=typeof window,bs=Math.pow(2,31)-1,ws=ms&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",ys=(e="",t="")=>({vsid:e,vrid:t}),Is=(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},ks=e=>(e.body&&(e.body.fpData=Is(!0)||ys()),e),js="dls_last_user_login_id",Os="dls_last_user_display_name",Ss=()=>gs(js),xs=()=>gs(Os),Cs=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,i=Ss(),r=xs();return i&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=i,o.lastAuth.name=r),await e(...t)},Us=e=>async(...t)=>{const n=await e(...t);return fs(js),fs(Os),n};function As(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const Es="DS",Rs="DSR";function Ps(e=""){return gs(`${e}${Rs}`)||""}function Ts(e=""){fs(`${e}${Rs}`),fs(`${e}${Es}`),Kn.remove(Es)}async function _s(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=Ws(n.publicKey.challenge),n.publicKey.user.id=Ws(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=Ws(e.id)})),n}(e);return n=await navigator.credentials.create(t),JSON.stringify({id:n.id,rawId:Ns(n.rawId),type:n.type,response:{attestationObject:Ns(n.response.attestationObject),clientDataJSON:Ns(n.response.clientDataJSON)}});var n}async function $s(e){const t=qs(e);return Ds(await navigator.credentials.get(t))}async function Ls(e,t){const n=qs(e);return n.signal=t.signal,n.mediation="conditional",Ds(await navigator.credentials.get(n))}async function Ms(e=!1){if(!ms)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 qs(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=Ws(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=Ws(e.id)})),n}function Ds(e){return JSON.stringify({id:e.id,rawId:Ns(e.rawId),type:e.type,response:{authenticatorData:Ns(e.response.authenticatorData),clientDataJSON:Ns(e.response.clientDataJSON),signature:Ns(e.response.signature),userHandle:e.response.userHandle?Ns(e.response.userHandle):void 0}})}function Ws(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function Ns(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var Js,Ks=(Js=e=>({async signUp(t,n){const o=await e.webauthn.signUp.start(t,window.location.origin,n);if(!o.ok)return o;const i=await _s(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,i)},async signIn(t){const n=await e.webauthn.signIn.start(t,window.location.origin);if(!n.ok)return n;const o=await $s(n.data.options);return await e.webauthn.signIn.finish(n.data.transactionId,o)},async signUpOrIn(t){var n;const o=await e.webauthn.signUpOrIn.start(t,window.location.origin);if(!o.ok)return o;if(null===(n=o.data)||void 0===n?void 0:n.create){const t=await _s(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,t)}{const t=await $s(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,t)}},async update(t,n){const o=await e.webauthn.update.start(t,window.location.origin,n);if(!o.ok)return o;const i=await _s(o.data.options);return await e.webauthn.update.finish(o.data.transactionId,i)},helpers:{create:_s,get:$s,isSupported:Ms,conditional:Ls}}),(...e)=>{const t=Js(...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}),Fs=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await Ms(),o=Object.assign(Object.assign({redirectUrl:window.location.href,location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n}});return t[1]=o,e.flow.start(...t)}});const Hs=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>t=>{var{fpKey:n,fpLoad:o}=t,i=d(t,["fpKey","fpLoad"]);return n?(ms?o&&(async e=>{try{if(Is())return;const t=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),n=qn({apiKey:e,endpoint:ws}),o=await n,{requestId:i}=await o.get({linkedId:t});(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem("fp",JSON.stringify(t))})(ys(t,i))}catch(e){global.FB_DEBUG&&console.error(e)}})(n).catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server"),e(cs(i,{beforeRequest:ks}))):e(Object.assign({},i))}),(e=>t=>{var{autoRefresh:n}=t,o=d(t,["autoRefresh"]);if(!n)return e(o);const{clearAllTimers:i,setTimer:r}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let s,a;document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&new Date>s&&(vs("Expiration time passed, refreshing session"),l.refresh(a))}));const l=e(cs(o,{afterRequest:async(e,t)=>{const{refreshJwt:n,sessionJwt:o}=await ds(t);if(401===(null==t?void 0:t.status))vs("Received 401, canceling all timers"),i();else if(o){s=(e=>{const t=e.split(".");try{if(3===t.length){const e=JSON.parse(window.atob(t[1]));if(e.exp)return new Date(1e3*e.exp)}}catch(e){}return null})(o),a=n;let e=((c=s)?c.getTime()-(new Date).getTime():0)-2e4;e>bs&&(vs(`Timeout is too large (${e}ms), setting it to ${bs}ms`),e=bs),i();const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});vs(`Setting refresh timer for ${t}. (${e}ms)`),r((()=>{vs("Refreshing session due to timer"),l.refresh(n)}),e)}var c}}));return as(l,["logout","logoutAll"],(e=>async(...t)=>{const n=await e(...t);return vs("Clearing all timers"),i(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.6.3-alpha.0"},t.baseHeaders)}))),(e=>t=>{const n=As(),o=As(),i=e(cs(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))n.pub(null),o.pub(null);else{const e=await us(t);e&&o.pub(e);const{sessionJwt:i}=await ds(t);i&&n.pub(i)}}})),r=as(i,["logout","logoutAll"],(e=>async(...t)=>{const i=await e(...t);return n.pub(null),o.pub(null),i}));return Object.assign(r,{onSessionTokenChange:n.sub,onUserChange:o.sub})}),(e=>t=>{const n=e(cs(t,{afterRequest:async(e,t)=>{var n;const o=await us(t),i=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],r=null==o?void 0:o.name;i&&((e=>{ps(js,e)})(i),(e=>{ps(Os,e)})(r))}}));let o=as(n,["flow.start"],Cs);return o=as(o,["logout","logoutAll"],Us),Object.assign(o,{getLastUserLoginId:Ss,getLastUserDisplayName:xs})}),(e=>t=>{var{persistTokens:n,sessionTokenViaCookie:o,storagePrefix:i}=t,r=d(t,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!n||!ms)return n&&console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),e(r);const s=e(cs(r,{beforeRequest:(a=i,e=>Object.assign(e,{token:e.token||Ps(a)})),afterRequest:async(e,t)=>{401===(null==t?void 0:t.status)?Ts(i):((e={},t,n)=>{var{refreshJwt:o,sessionJwt:i}=e,r=d(e,["refreshJwt","sessionJwt"]);void 0===t&&(t=!1),void 0===n&&(n=""),o&&ps(`${n}${Rs}`,o),i&&(t?function(e,t,{cookiePath:n,cookieDomain:o,cookieExpiration:i}){if(t){const r=new Date(1e3*i);Kn.set(e,t,{path:n,domain:o,expires:r,sameSite:"Strict",secure:!0})}}(Es,i,r):ps(`${n}${Es}`,i))})(await ds(t),o,i)}}));var a;const l=as(s,["logout","logoutAll"],(e=>t=>async(...n)=>{const o=await t(...n);return Ts(e),o})(i));return Object.assign(l,{getRefreshToken:()=>Ps(i),getSessionToken:()=>function(e=""){return Kn.get(Es)||gs(`${e}${Es}`)||""}(i)})}))(((...e)=>{const t=ls(...e);return Object.assign(Object.assign({},t),{flow:Fs(t),webauthn:Ks(t)})})),zs="undefined"!=typeof localStorage,Vs=zs&&localStorage.getItem("base.content.url")||"https://static.descope.com/pages",Bs=zs&&localStorage.getItem("base.ui.components.url")||"https://cdn.jsdelivr.net/npm/@descope/web-components-ui@<version>/dist/umd/index.js",Gs="descope-login-flow",Zs="code",Ys="ra-challenge",Xs="ra-callback",Qs="ra-initiator",ea="data-exclude-field",ta="dls_last_auth",na="state_id",oa="saml_idp_state_id",ia="saml_idp_username",ra="sso_app_id",sa="data-type",aa="poll",la="webauthnCreate",ca="config.json",da="submit",ua="polling";var ha;function pa(e){return new URLSearchParams(window.location.search).get(e)}function ga(e){if(window.history.replaceState&&pa(e)){const t=new URL(window.location.href),n=new URLSearchParams(t.search);n.delete(e),t.search=n.toString(),window.history.replaceState({},"",t.toString())}}function fa(e,t){return u(this,void 0,void 0,(function*(){const n=yield fetch(e,{cache:"default"});if(!n.ok)throw Error(`Error fetching URL ${e} [${n.status}]`);return{body:yield n[t||"text"](),headers:Object.fromEntries(n.headers.entries())}}))}function va(e,t,n="v2-beta"){const o=new URL(Vs);return o.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(o.pathname,e,n,t),o.toString()}function ma(e,t){if(!Number.isNaN(e)&&!Number.isNaN(t))return e>t?ha.forward:e<t?ha.backward:void 0}!function(e){e.backward="backward",e.forward="forward"}(ha||(ha={}));const ba=()=>{const[e="",t=""]=(pa(Gs)||"").split("_");return{executionId:e,stepId:t}};function wa(){ga(Gs)}const ya=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),Ia=()=>{const{executionId:e,stepId:t}=ba();(e||t)&&wa();const n=pa("t")||void 0;n&&ga("t");const o=pa(Zs)||void 0;o&&ga(Zs);const i=pa("err")||void 0;i&&ga("err");const{redirectAuthCodeChallenge:r,redirectAuthCallbackUrl:s,redirectAuthInitiator:a}={redirectAuthCodeChallenge:pa(Ys),redirectAuthCallbackUrl:pa(Xs),redirectAuthInitiator:pa(Qs)};(r||s||a)&&(ga(Ys),ga(Xs),ga(Qs));const l=pa(na);l&&ga(na);const c=pa(oa);c&&ga(oa);const d=pa(ia);c&&ga(ia);const u=pa(ra);return u&&ga(ra),{executionId:e,stepId:t,token:n,code:o,exchangeError:i,redirectAuthCodeChallenge:r,redirectAuthCallbackUrl:s,redirectAuthInitiator:a,oidcIdpStateId:l,samlIdpStateId:c,samlIdpUsername:d,ssoAppId:u}},ka=e=>{let t,n;return(...o)=>{return t&&(r=o,(i=t).length===r.length&&i.every(((e,t)=>e===r[t])))||(t=o,n=e(...o)),n;var i,r}},ja=(e,t,n,o,i)=>e&&!t&&e&&!n&&!o&&e&&!i,Oa=e=>null==e?void 0:e.submit();var Sa,xa,Ca,Ua;function Aa(e,t){const n=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(n.length!==o.length)return!1;for(let o=0;o<n.length;o+=1){const i=n[o],r=e[i],s=t[i];if(null===r||null===s){if(r!==s)return!1}else if("object"==typeof r&&"object"==typeof s){if(!Aa(r,s))return!1}else if(r!==s)return!1}return!0}class Ea{constructor(e={},{updateOnlyOnChange:t=!0}={}){Sa.set(this,void 0),xa.set(this,{}),Ca.set(this,0),Ua.set(this,!1),this.update=e=>{const t="function"==typeof e?e(h(this,Sa,"f")):e,n=Object.assign(Object.assign({},h(this,Sa,"f")),t);if(!h(this,Ua,"f")||!Aa(h(this,Sa,"f"),n)){const e=h(this,Sa,"f");p(this,Sa,n,"f"),Object.freeze(h(this,Sa,"f")),setTimeout((()=>{Object.values(h(this,xa,"f")).forEach((t=>t(n,e,((e,t)=>n=>e[n]!==t[n])(n,e))))}),0)}},p(this,Sa,e,"f"),p(this,Ua,t,"f")}get current(){return Object.assign({},h(this,Sa,"f"))}subscribe(e){return p(this,Ca,h(this,Ca,"f")+1,"f"),h(this,xa,"f")[h(this,Ca,"f")]=e,h(this,Ca,"f").toString()}unsubscribe(e){const t=!!h(this,xa,"f")[e];return t&&delete h(this,xa,"f")[e],t}unsubscribeAll(){return p(this,xa,{},"f"),!0}}Sa=new WeakMap,xa=new WeakMap,Ca=new WeakMap,Ua=new WeakMap;const Ra=(e,t)=>{Object.entries(t||{}).forEach((([t,n])=>{Array.from(e.querySelectorAll(`*[name="${t}"]:not([${ea}])`)).forEach((e=>{e.setAttribute("value",n)}))}))},Pa=ka((()=>u(void 0,void 0,void 0,(function*(){var e,t,n,o;if(!window.PublicKeyCredential||!PublicKeyCredential.isConditionalMediationAvailable||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)return!1;try{const i=Promise.all([null===(e=window.PublicKeyCredential)||void 0===e?void 0:e.isConditionalMediationAvailable(),null===(t=window.PublicKeyCredential)||void 0===t?void 0:t.isUserVerifyingPlatformAuthenticatorAvailable()]).then((e=>e.every((e=>!!e)))),r=(()=>{var e;const t=null===(e=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===e?void 0:e.brands,n=null==t?void 0:t.find((({brand:e,version:t})=>"Chromium"===e&&parseFloat(t)));return n?n.version:0})()>=108;return yield(100,n=i,o=r,new Promise(((e,t)=>{let i=!1;const r=setTimeout((()=>{i=!0,void 0!==o?e(o):t(new Error("Promise timed out after 100 ms"))}),100);n.then((t=>{i||(clearTimeout(r),e(t))})).catch((e=>{i||(clearTimeout(r),t(e))}))})))}catch(e){return console.error("Conditional login check failed",e),!1}})))),Ta={"lastAuth.loginId":{"not-empty":e=>!!e.loginId,empty:e=>!e.loginId},idpInitiated:{"is-true":e=>!!e.code,"is-false":e=>!e.code},externalToken:{"is-true":e=>!!e.token,"is-false":e=>!e.token}};function _a(e){const t={};if(e)try{Object.assign(t,JSON.parse(localStorage.getItem(ta)))}catch(e){}return t}const $a=document.createElement("template");var La,Ma,qa,Da,Wa,Na,Ja,Ka,Fa,Ha,za,Va,Ba,Ga,Za,Ya,Xa,Qa,el,tl,nl,ol,il,rl,sl,al,ll,cl,dl,ul,hl,pl,gl,fl,vl,ml,bl,wl,yl,Il,kl,jl,Ol,Sl;$a.innerHTML='\n\t<style>\n\t\t:host {\n\t\t\twidth: 100%;\n\t\t\theight: 100%;\n\t\t}\n\t\t\n\t\t#wc-root {\n\t\t\theight: 100%;\n\t\t\ttransition: opacity 300ms ease-in-out;\n\t\t}\n\n\t\t#wc-root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1;\n\t\t}\n\n\t</style>\n\t<div id="wc-root"></div>\n\t';class xl extends HTMLElement{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","theme","locale","debug","storage-prefix","preview","telemetryKey","redirect-url","auto-focus"]}constructor(e){super(),La.add(this),this.logger=console,Ma.set(this,!1),this.loggerWrapper={error:(e,t="")=>{this.logger.error(e,t,new Error),h(this,La,"m",ll).call(this,e,t)},warn:(e,t="")=>{this.logger.warn(e,t)},info:(e,t="",n={})=>{this.logger.info(e,t,n)}},qa.set(this,new Ea({deferredRedirect:!1})),Da.set(this,new Ea),Wa.set(this,{}),this.getComponentsContext=()=>h(this,Wa,"f"),this.nextRequestStatus=new Ea({isLoading:!1}),Na.set(this,void 0),Ja.set(this,{popstate:h(this,La,"m",Ba).bind(this),visibilitychange:h(this,La,"m",Ga).bind(this),componentsContext:h(this,La,"m",il).bind(this)}),Ka.set(this,void 0),el.set(this,ka((()=>u(this,void 0,void 0,(function*(){const e=va(this.projectId,ca);try{const{body:t,headers:n}=yield fa(e,"json");return{projectConfig:t,executionContext:{geo:n["x-geo"]}}}catch(e){return{isMissingConfig:!0}}}))))),p(this,Ka,e,"f"),h(this,La,"m",Fa).call(this)}get projectId(){return this.getAttribute("project-id")}get flowId(){return this.getAttribute("flow-id")}get baseUrl(){return this.getAttribute("base-url")||void 0}get tenant(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get theme(){var e,t;const n=this.getAttribute("theme");return"os"===n?window.matchMedia&&(null===(t=null===(e=window.matchMedia)||void 0===e?void 0:e.call(window,"(prefers-color-scheme: dark)"))||void 0===t?void 0:t.matches)?"dark":"light":n||"light"}get telemetryKey(){return this.getAttribute("telemetryKey")||void 0}get autoFocus(){var e;const t=null!==(e=this.getAttribute("auto-focus"))&&void 0!==e?e:"true";return"skipFirstScreen"===t?t:"true"===t}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}getExecutionContext(){return u(this,void 0,void 0,(function*(){const{executionContext:e}=yield h(this,el,"f").call(this);return e}))}getProjectConfig(){return u(this,void 0,void 0,(function*(){const{projectConfig:e}=yield h(this,el,"f").call(this);return e}))}getFlowConfig(){var e,t;return u(this,void 0,void 0,(function*(){const n=yield this.getProjectConfig(),o=(null===(e=null==n?void 0:n.flows)||void 0===e?void 0:e[this.flowId])||{};return null!==(t=o.version)&&void 0!==t||(o.version=0),o}))}getTargetLocales(){return u(this,void 0,void 0,(function*(){const e=yield this.getFlowConfig();return((null==e?void 0:e.targetLocales)||[]).map((e=>e.toLowerCase()))}))}connectedCallback(){return u(this,void 0,void 0,(function*(){if(this.shadowRoot.isConnected){if(h(this,Da,"f").subscribe(h(this,La,"m",al).bind(this)),h(this,Da,"f").update({isDebug:this.debug}),h(this,La,"m",Ha).call(this))return void h(this,La,"m",za).call(this);if(h(this,La,"m",Va).call(this),yield h(this,La,"m",Xa).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");if((yield h(this,el,"f").call(this)).isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");yield h(this,La,"m",dl).call(this),yield h(this,La,"m",nl).call(this),h(this,La,"m",tl).call(this),h(this,La,"m",cl).call(this);const{executionId:e,stepId:t,token:n,code:o,exchangeError:i,redirectAuthCallbackUrl:r,redirectAuthCodeChallenge:s,redirectAuthInitiator:a,oidcIdpStateId:l,samlIdpStateId:c,samlIdpUsername:d,ssoAppId:u}=Ia();window.addEventListener("popstate",h(this,Ja,"f").popstate),window.addEventListener("components-context",h(this,Ja,"f").componentsContext),window.addEventListener("visibilitychange",h(this,Ja,"f").visibilitychange),h(this,qa,"f").subscribe(h(this,La,"m",Ya).bind(this)),h(this,qa,"f").update({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenant,redirectUrl:this.redirectUrl,locale:this.locale,stepId:t,executionId:e,token:n,code:o,exchangeError:i,telemetryKey:this.telemetryKey,redirectAuthCallbackUrl:r,redirectAuthCodeChallenge:s,redirectAuthInitiator:a,oidcIdpStateId:l,samlIdpStateId:c,samlIdpUsername:d,ssoAppId:u}),p(this,Ma,!0,"f")}}))}disconnectedCallback(){h(this,qa,"f").unsubscribeAll(),h(this,Da,"f").unsubscribeAll(),h(this,La,"m",sl).call(this),window.removeEventListener("popstate",h(this,Ja,"f").popstate),window.removeEventListener("visibilitychange",h(this,Ja,"f").visibilitychange),window.removeEventListener("components-context",h(this,Ja,"f").componentsContext)}attributeChangedCallback(e,t,n){if(this.shadowRoot.isConnected&&h(this,Ma,"f")&&t!==n&&xl.observedAttributes.includes(e)){h(this,La,"m",Va).call(this);const o=null===t;h(this,qa,"f").update((({stepId:t,executionId:i})=>{let r=t,s=i;return o||(s=null,r=null,wa()),{[ya(e)]:n,stepId:r,executionId:s}})),h(this,Da,"f").update({isDebug:this.debug})}}}Ma=new WeakMap,qa=new WeakMap,Da=new WeakMap,Wa=new WeakMap,Na=new WeakMap,Ja=new WeakMap,Ka=new WeakMap,el=new WeakMap,La=new WeakSet,Fa=function(){this.attachShadow({mode:"open"}),this.shadowRoot.appendChild($a.content.cloneNode(!0)),this.rootElement=this.shadowRoot.querySelector("#wc-root")},Ha=function(){return!this.shadowRoot.host.closest("form")&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)},za=function(){const e=this.shadowRoot.host,t=document.createElement("form");e.parentElement.appendChild(t),t.appendChild(e)},Va=function(){const e=["base-url","tenant","theme","locale","debug","telemetryKey","redirect-url","auto-focus","preview","storage-prefix"];if(xl.observedAttributes.forEach((t=>{if(!e.includes(t)&&!this[ya(t)])throw Error(`${t} cannot be empty`)})),this.theme&&"light"!==this.theme&&"dark"!==this.theme)throw Error('Supported theme values are "light", "dark", or leave empty for using the OS theme')},Ba=function(){const{stepId:e,executionId:t}=ba();h(this,qa,"f").update({stepId:e,executionId:t})},Ga=function(){document.hidden||setTimeout((()=>{h(this,qa,"f").update({deferredRedirect:!1})}),300)},Za=function(e,t,n){const o=n||void 0,i=!!o;this.sdk=Hs(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix},xl.sdkConfigOverrides),{projectId:e,baseUrl:t,fpKey:o,fpLoad:i})),["start","next"].forEach((e=>{const t=this.sdk.flow[e];this.sdk.flow[e]=(...e)=>u(this,void 0,void 0,(function*(){this.nextRequestStatus.update({isLoading:!0});try{return yield t(...e)}finally{this.nextRequestStatus.update({isLoading:!1})}}))}))},Ya=function(e,t,n){return u(this,void 0,void 0,(function*(){const{projectId:t,baseUrl:o,telemetryKey:i}=e;if(n("projectId")||n("baseUrl")||n("telemetryKey")){if(!t)return;h(this,La,"m",Za).call(this,t,o,i)}h(this,Ka,"f").call(this,e)}))},Xa=function(){return u(this,void 0,void 0,(function*(){return(yield h(this,el,"f").call(this)).isMissingConfig&&(yield h(this,La,"m",Qa).call(this))}))},Qa=function(){return u(this,void 0,void 0,(function*(){const e=va(this.projectId,ca,"v2-alpha");try{return yield fa(e,"json"),!0}catch(e){return!1}}))},tl=function(){var e,t;return u(this,void 0,void 0,(function*(){const{projectConfig:n}=yield h(this,el,"f").call(this),o=null===(t=null===(e=null==n?void 0:n.cssTemplate)||void 0===e?void 0:e[this.theme])||void 0===t?void 0:t.fonts;o&&Object.values(o).forEach((e=>(e=>{if(!e)return;const t=document.createElement("link");t.href=e,t.rel="stylesheet",document.head.appendChild(t)})(e.url)))}))},nl=function(){return u(this,void 0,void 0,(function*(){yield h(this,La,"m",ol).call(this),yield h(this,La,"m",rl).call(this)}))},ol=function(){var e,t,n,o;return u(this,void 0,void 0,(function*(){const i=document.createElement("style"),r=va(this.projectId,"theme.json");try{const{body:s}=yield fa(r,"json");i.innerText=((null===(e=null==s?void 0:s.light)||void 0===e?void 0:e.globals)||"")+((null===(t=null==s?void 0:s.dark)||void 0===t?void 0:t.globals)||"");const a=yield this.descopeUI;(null==a?void 0:a.componentsThemeManager)&&(a.componentsThemeManager.themes={light:null===(n=null==s?void 0:s.light)||void 0===n?void 0:n.components,dark:null===(o=null==s?void 0:s.dark)||void 0===o?void 0:o.components})}catch(i){this.loggerWrapper.error("Cannot fetch theme file","make sure that your projectId & flowId are correct")}this.shadowRoot.appendChild(i)}))},il=function(e){p(this,Wa,Object.assign(Object.assign({},e.detail),h(this,Wa,"f")),"f")},rl=function(){return u(this,void 0,void 0,(function*(){this.rootElement.setAttribute("data-theme",this.theme);const e=yield this.descopeUI;(null==e?void 0:e.componentsThemeManager)&&(e.componentsThemeManager.currentThemeName=this.theme)}))},sl=function(){var e;null===(e=h(this,Na,"f"))||void 0===e||e.remove(),p(this,Na,null,"f")},al=function({isDebug:e}){return u(this,void 0,void 0,(function*(){e?(p(this,Na,document.createElement("descope-debugger"),"f"),Object.assign(h(this,Na,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return Jl})),document.body.appendChild(h(this,Na,"f"))):h(this,La,"m",sl).call(this)}))},ll=function(e,t){var n;e&&this.debug&&(null===(n=h(this,Na,"f"))||void 0===n||n.updateData({title:e,description:t}))},cl=function(){this.rootElement.onkeydown=e=>{if("Enter"!==e.key)return;e.preventDefault();const t=this.rootElement.querySelectorAll("descope-button");if(1===t.length)return void t[0].click();const n=Array.from(t).filter((e=>"button"===e.getAttribute("data-type")));1===n.length&&n[0].click()}},dl=function(){var e,t;return u(this,void 0,void 0,(function*(){let n=null===(t=null===(e=yield h(this,el,"f").call(this))||void 0===e?void 0:e.projectConfig)||void 0===t?void 0:t.componentsVersion;n||(this.logger.error("Did not get components version, using latest version"),n="latest");const o=Bs.replace("<version>",n),i=document.createElement("script");this.descopeUI=new Promise((e=>{const t=()=>{this.loggerWrapper.error("Cannot load DescopeUI",`Make sure this URL is valid and return the correct script: "${o}"`),e({})};i.onload=()=>{globalThis.DescopeUI||t(),e(globalThis.DescopeUI)},i.onerror=t,i.src=o})),document.body.append(i)}))},xl.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.0.0-alpha.4"}};class Cl extends xl{static set sdkConfigOverrides(e){xl.sdkConfigOverrides=e}constructor(){const e=new Ea;super(e.update.bind(e)),ul.add(this),this.stepState=new Ea({},{updateOnlyOnChange:!1}),hl.set(this,void 0),pl.set(this,null),gl.set(this,(()=>{clearInterval(h(this,hl,"f")),p(this,hl,null,"f")})),fl.set(this,(e=>{var t,n,o,i,r,s,a,l,c;if(!(null==e?void 0:e.ok)){h(this,gl,"f").call(this),h(this,ul,"m",Sl).call(this,"error",null==e?void 0:e.error);const s=null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.url,a=`${null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status} - ${null===(o=null==e?void 0:e.response)||void 0===o?void 0:o.statusText}`;return void this.loggerWrapper.error((null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.errorDescription)||s,(null===(r=null==e?void 0:e.error)||void 0===r?void 0:r.errorMessage)||a)}const d=null===(l=null===(a=null===(s=e.data)||void 0===s?void 0:s.screen)||void 0===a?void 0:a.state)||void 0===l?void 0:l.errorText;(null===(c=e.data)||void 0===c?void 0:c.error)?this.loggerWrapper.error(`[${e.data.error.code}]: ${e.data.error.description}`,`${d?`${d} - `:""}${e.data.error.message}`):d&&this.loggerWrapper.error(d);const{status:u,authInfo:p,lastAuth:g}=e.data;if("completed"===u)return function(e){(null==e?void 0:e.authMethod)&&zs&&localStorage.setItem(ta,JSON.stringify(e))}(g),h(this,gl,"f").call(this),void h(this,ul,"m",Sl).call(this,"success",p);const{executionId:f,stepId:v,stepName:m,action:b,screen:w,redirect:y,webauthn:I,error:k,samlIdpResponse:j}=e.data;b!==aa?(this.loggerWrapper.info(`Step "${m||`#${v}`}" is ${u}`,"",{screen:w,status:u,stepId:v,stepName:m,action:b,error:k}),this.flowState.update({stepId:v,executionId:f,action:b,redirectTo:null==y?void 0:y.url,screenId:null==w?void 0:w.id,screenState:null==w?void 0:w.state,webauthnTransactionId:null==I?void 0:I.transactionId,webauthnOptions:null==I?void 0:I.options,samlIdpResponseUrl:null==j?void 0:j.url,samlIdpResponseSamlResponse:null==j?void 0:j.samlResponse,samlIdpResponseRelayState:null==j?void 0:j.relayState})):this.flowState.update({action:b})})),vl.set(this,ka((()=>u(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.error("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.error("Webauthn start failed",e.message)}}))))),this.flowState=e}connectedCallback(){const e=Object.create(null,{connectedCallback:{get:()=>super.connectedCallback}});var t,n;return u(this,void 0,void 0,(function*(){this.shadowRoot.isConnected&&(null===(t=this.flowState)||void 0===t||t.subscribe(this.onFlowChange.bind(this)),null===(n=this.stepState)||void 0===n||n.subscribe(this.onStepChange.bind(this))),yield e.connectedCallback.call(this)}))}disconnectedCallback(){var e;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),null===(e=h(this,pl,"f"))||void 0===e||e.abort(),p(this,pl,null,"f")}getHtmlFilenameWithLocale(e,t){return u(this,void 0,void 0,(function*(){let n,o=navigator.language;o&&"zh-TW"!==o&&(o=o.split("-")[0]);const i=(e||o||"").toLowerCase();return(yield this.getTargetLocales()).includes(i)&&(n=`${t}-${i}.html`),n}))}getPageContent(e,t){return u(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield fa(t,"text");return e}catch(n){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,n)}try{const{body:t}=yield fa(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(e,t,n){var o,i;return u(this,void 0,void 0,(function*(){const{projectId:r,flowId:s,tenant:a,stepId:l,executionId:c,action:d,screenId:g,screenState:f,redirectTo:v,redirectUrl:m,token:b,code:w,exchangeError:y,webauthnTransactionId:I,webauthnOptions:k,redirectAuthCodeChallenge:j,redirectAuthCallbackUrl:O,redirectAuthInitiator:S,oidcIdpStateId:x,locale:C,samlIdpStateId:U,samlIdpUsername:A,samlIdpResponseUrl:E,samlIdpResponseSamlResponse:R,samlIdpResponseRelayState:P,ssoAppId:T}=e;let _,$;h(this,hl,"f")&&h(this,gl,"f").call(this);const L=this.sdk.getLastUserLoginId(),M=yield this.getFlowConfig(),q=yield this.getProjectConfig(),D=O&&j?{callbackUrl:O,codeChallenge:j}:void 0;if(!c&&(M.conditions?({startScreenId:_,conditionInteractionId:$}=((e,t)=>{const n=null==t?void 0:t.find((({key:t,operator:n})=>{var o;if("ELSE"===t)return!0;const i=null===(o=Ta[t])||void 0===o?void 0:o[n];return!!(null==i?void 0:i(e))}));return n?{startScreenId:n.met.screenId,conditionInteractionId:n.met.interactionId}:{}})({loginId:L,code:w,token:b},M.conditions)):M.condition?({startScreenId:_,conditionInteractionId:$}=((e,t)=>{var n;const o=null===(n=Ta[null==e?void 0:e.key])||void 0===n?void 0:n[e.operator];if(!o)return{};const i=o(t)?e.met:e.unmet;return{startScreenId:null==i?void 0:i.screenId,conditionInteractionId:null==i?void 0:i.interactionId}})(M.condition,{loginId:L,code:w,token:b})):_=M.startScreenId,!ja(_,x,U,A,T))){const e={};let t=!1;w&&(t=!0,e.exchangeCode=w,e.idpInitiated=!0),b&&(t=!0,e.token=b);const n=yield this.sdk.flow.start(s,Object.assign(Object.assign({tenant:a,redirectAuth:D,oidcIdpStateId:x,samlIdpStateId:U,samlIdpUsername:A,ssoAppId:T},m&&{redirectUrl:m}),{lastAuth:_a(L)}),$,"",M.version,q.componentsVersion,t?e:void 0);return h(this,fl,"f").call(this,n),void("completed"!==(null===(o=null==n?void 0:n.data)||void 0===o?void 0:o.status)&&this.flowState.update({code:void 0,token:void 0}))}if(c&&(n("token")&&b||n("code")&&w||n("exchangeError")&&y)){const e=yield this.sdk.flow.next(c,l,da,M.version,q.componentsVersion,{token:b,exchangeCode:w,exchangeError:y});return h(this,fl,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if("loadForm"===d&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>n(e)))){if(!E||!R)return void this.loggerWrapper.error("Did not get saml idp params data to load");((e,t,n,o)=>{const i=document.createElement("form");i.method="POST",i.action=e,i.innerHTML=`\n <input type="hidden" role="saml-response" name="SAMLResponse" value="${t}" />\n <input type="hidden" role="saml-relay-state" name="RelayState" value="${n}" />\n <input style="display: none;" id="SAMLSubmitButton" type="submit" value="Continue" />\n `,document.body.appendChild(i),o(i)})(E,R,P||"",Oa)}if("redirect"===d&&(n("redirectTo")||n("deferredRedirect")))return v?"android"===S&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(v):void this.loggerWrapper.error("Did not get redirect url");if(d===la||"webauthnGet"===d){if(!I||!k)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t;null===(i=h(this,pl,"f"))||void 0===i||i.abort(),p(this,pl,null,"f");try{e=d===la?yield this.sdk.webauthn.helpers.create(k):yield this.sdk.webauthn.helpers.get(k)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),t=e.name}const n=yield this.sdk.flow.next(c,l,da,M.version,q.componentsVersion,{transactionId:I,response:e,failure:t});h(this,fl,"f").call(this,n)}if(d===aa&&p(this,hl,setInterval((()=>u(this,void 0,void 0,(function*(){const e=yield this.sdk.flow.next(c,l,ua,M.version,q.componentsVersion,{});h(this,fl,"f").call(this,e)}))),2e3),"f"),!g&&!_)return void this.loggerWrapper.warn("No screen was found to show");const W=_||g,N=yield this.getHtmlFilenameWithLocale(C,W),J={direction:ma(+l,+t.stepId),screenState:Object.assign(Object.assign({},f),{lastAuth:{loginId:L,name:this.sdk.getLastUserDisplayName()||L}}),htmlUrl:va(r,`${W}.html`),htmlLocaleUrl:N&&va(r,N),samlIdpUsername:A},K=_a(L);ja(_,x,U,A,T)?J.next=(e,t,n,o)=>this.sdk.flow.start(s,Object.assign({tenant:a,redirectAuth:D,oidcIdpStateId:x,samlIdpStateId:U,samlIdpUsername:A,ssoAppId:T,lastAuth:K,preview:this.preview},m&&{redirectUrl:m}),$,e,t,n,Object.assign(Object.assign(Object.assign({},o),w&&{exchangeCode:w,idpInitiated:!0}),b&&{token:b})):(n("projectId")||n("baseUrl")||n("executionId")||n("stepId"))&&(J.next=(...e)=>this.sdk.flow.next(c,l,...e)),this.stepState.update(J)}))}loadDescopeUiComponents(e){return u(this,void 0,void 0,(function*(){const t=(e=>[...Array.from(e.querySelectorAll("*")).reduce(((e,t)=>t.tagName.startsWith("DESCOPE-")?e.add(t.tagName.toLocaleLowerCase()):e),new Set)])(e);yield Promise.all(t.map((e=>u(this,void 0,void 0,(function*(){if(customElements.get(e))return;let t;try{t=yield this.descopeUI}catch(t){return}if(t[e])return t[e]();this.loggerWrapper.error(`Cannot load UI component "${e}"`,`Descope UI does not have a component named "${e}", available components are: "${Object.keys(t).join(", ")}"`)})))))}))}onStepChange(e,t){var n,o;return u(this,void 0,void 0,(function*(){const{htmlUrl:i,htmlLocaleUrl:r,direction:s,next:a,screenState:l}=e,c=document.createElement("template");c.innerHTML=yield this.getPageContent(i,r);const d=c.content.cloneNode(!0),p=this.loadDescopeUiComponents(c.content);this.sdk.webauthn.helpers.isSupported()?yield h(this,ul,"m",bl).call(this,d,a):d.querySelectorAll(`descope-button[${sa}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true"))),!e.samlIdpUsername||(null===(n=l.form)||void 0===n?void 0:n.loginId)||(null===(o=l.form)||void 0===o?void 0:o.email)||(l.form||(l.form={}),l.form.loginId=e.samlIdpUsername,l.form.email=e.samlIdpUsername),((e,t,n,o)=>{var i;let r=null==t?void 0:t.errorText;try{r=(null==n?void 0:n({text:null==t?void 0:t.errorText,type:null==t?void 0:t.errorType}))||(null==t?void 0:t.errorText)}catch(e){o.error("Error transforming error message",e.message)}((e,t,n="")=>{e.querySelectorAll(`[${sa}="${t}"]`).forEach((e=>{e.textContent=n,e.classList[n?"remove":"add"]("hide")}))})(e,"error-message",r),Ra(e,null==t?void 0:t.inputs),Ra(e,null==t?void 0:t.form),((e,t)=>{e.querySelectorAll(`[${sa}="totp-link"]`).forEach((e=>{e.setAttribute("href",t)}))})(e,null===(i=null==t?void 0:t.totp)||void 0===i?void 0:i.provisionUrl),((e,t)=>{e.querySelectorAll("descope-text,descope-link").forEach((e=>{e.textContent=((e,t)=>e.replace(/{{(.+?)}}/g,((e,n)=>{return o=t,n.split(".").reduce(((e,t)=>(null==e?void 0:e[t])||""),o);var o})))(e.textContent,t)}))})(e,t)})(d,l,this.errorTransformer,this.loggerWrapper);const{geo:g}=yield this.getExecutionContext();((e,t)=>{Array.from(e.querySelectorAll('descope-phone-field[default-code="autoDetect"]')).forEach((e=>{e.setAttribute("default-code",t)}))})(d,g);const f=()=>u(this,void 0,void 0,(function*(){var e;yield p,((e,t)=>{var n,o;const i=null===(n=customElements.get("descope-totp-image"))||void 0===n?void 0:n.cssVarList.url;t&&i&&(null===(o=null==e?void 0:e.style)||void 0===o||o.setProperty(i,`url(data:image/jpg;base64,${t})`))})(this.shadowRoot.querySelector("div"),null===(e=null==l?void 0:l.totp)||void 0===e?void 0:e.image),this.rootElement.replaceChildren(d);const n=!t.htmlUrl;if(((e,t,n)=>{if(!0===t||"skipFirstScreen"===t&&!n){const t=e.querySelector("*[name]");setTimeout((()=>{null==t||t.focus()}))}})(this.rootElement,this.autoFocus,n),h(this,ul,"m",jl).call(this,a),h(this,ul,"m",Sl).call(this,"page-updated",{}),this.rootElement.querySelector(`[${sa}="polling"]`)){const e=yield this.getFlowConfig(),t=yield this.getProjectConfig(),n=yield a(ua,e.version,t.componentsVersion,{});h(this,fl,"f").call(this,n)}}));s?h(this,ul,"m",Ol).call(this,f,s):f()}))}}hl=new WeakMap,pl=new WeakMap,gl=new WeakMap,fl=new WeakMap,vl=new WeakMap,ul=new WeakSet,ml=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const n=`user-${t}`;e.setAttribute("name",n),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:n)}))}},bl=function(e,t){var n;return u(this,void 0,void 0,(function*(){null===(n=h(this,pl,"f"))||void 0===n||n.abort();const o=e.querySelector('*[autocomplete="webauthn"]');if(o&&(yield Pa())){const{options:e,transactionId:n}=(yield h(this,vl,"f").call(this))||{};if(e&&n){h(this,ul,"m",ml).call(this,o),p(this,pl,new AbortController,"f");const i=yield this.getFlowConfig(),r=yield this.getProjectConfig();this.sdk.webauthn.helpers.conditional(e,h(this,pl,"f")).then((e=>u(this,void 0,void 0,(function*(){const s=yield t(o.id,i.version,r.componentsVersion,{transactionId:n,response:e});h(this,fl,"f").call(this,s)})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)}))}}}))},wl=function(){return Array.from(this.shadowRoot.querySelectorAll("*[name]")).every((e=>{var t,n;return null===(t=e.reportValidity)||void 0===t||t.call(e),null===(n=e.checkValidity)||void 0===n?void 0:n.call(e)}))},yl=function(){return u(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${ea}])`));return(yield Promise.all(e.map((e=>u(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},Il=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:n})=>{n?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},kl=function(e,t){return u(this,void 0,void 0,(function*(){if("true"===e.getAttribute("formnovalidate")||h(this,ul,"m",wl).call(this)){const o=null==e?void 0:e.getAttribute("id");h(this,ul,"m",Il).call(this,e);const i=yield h(this,ul,"m",yl).call(this),r=(n=e,Array.from((null==n?void 0:n.attributes)||[]).reduce(((e,t)=>{var n;const o=null===(n=new RegExp("^data-descope-(\\S+)$").exec(t.name))||void 0===n?void 0:n[1];return o?Object.assign(e,{[o]:t.value}):e}),{})),s=this.getComponentsContext(),a=Object.assign(Object.assign(Object.assign(Object.assign({},s),r),i),{origin:window.location.origin}),l=yield this.getFlowConfig(),c=yield this.getProjectConfig(),d=yield t(o,l.version,c.componentsVersion,a);h(this,fl,"f").call(this,d)}var n}))},jl=function(e){this.rootElement.querySelectorAll("descope-button:not([data-exclude-next])").forEach((t=>{t.onclick=()=>{h(this,ul,"m",kl).call(this,t,e)}}))},Ol=function(e,t){this.rootElement.addEventListener("transitionend",(()=>{this.rootElement.classList.remove("fade-out"),e()}),{once:!0});const n=t===ha.forward?"slide-forward":"slide-backward";Array.from(this.rootElement.getElementsByClassName("input-container")).forEach(((e,t)=>{e.style["transition-delay"]=40*t+"ms",e.classList.add(n)})),this.rootElement.classList.add("fade-out")},Sl=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},customElements.define("descope-wc",Cl);var Ul=Object.freeze({__proto__:null,default:Cl});const Al=(e,t,n,o={})=>{var i,r,s,a;return[Math.min(Math.max(t,("all"===o.left?e.offsetWidth:null!==(i=o.left)&&void 0!==i?i:0)-e.offsetWidth),window.innerWidth-("all"===o.right?e.offsetWidth:null!==(r=o.right)&&void 0!==r?r:0)),Math.min(Math.max(n,("all"===o.top?e.offsetHeight:null!==(s=o.top)&&void 0!==s?s:0)-e.offsetHeight),window.innerHeight-("all"===o.bottom?e.offsetHeight:null!==(a=o.bottom)&&void 0!==a?a:0))]};var El,Rl,Pl,Tl,_l,$l,Ll,Ml,ql,Dl;const Wl=document.createElement("template");Wl.innerHTML=`\n<style>\n .debugger {\n width: 300px;\n height: 200px;\n background-color: #FAFAFA;\n position: fixed;\n font-family: "Helvetica Neue", sans-serif;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 10px;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid lightgrey;\n pointer-events: initial;\n display: flex;\n flex-direction: column;\n min-width: 200px;\n max-width: 600px;\n max-height: calc(100% - 64px);\n min-height: 200px;\n resize: both;\n }\n\n .header {\n padding: 8px 16px;\n display: flex;\n align-items: center;\n background-color: #EEEEEE;\n cursor: move;\n border-bottom: 1px solid #e0e0e0;\n }\n\n .content {\n font-size: 14px;\n flex-grow: 1;\n overflow: auto;\n }\n\n .msg {\n border-bottom: 1px solid lightgrey;\n padding: 8px 16px;\n display: flex;\n gap: 5px;\n background-color: #FAFAFA;\n }\n\n .msg.collapsible {\n cursor: pointer;\n }\n\n .empty-state {\n padding: 8px 16px;\n background-color: #FAFAFA;\n }\n\n\n .msg.collapsible:not(.collapsed) {\n background-color: #F5F5F5;\n }\n\n .msg_title {\n padding-bottom: 5px;\n display: flex;\n gap: 8px;\n font-weight: 500;\n }\n\n .msg svg {\n padding: 1px;\n flex-shrink: 0;\n margin-top: -2px;\n }\n\n .msg_content {\n overflow: hidden;\n flex-grow: 1;\n margin-right:5px;\n }\n\n .msg_desc {\n color: #646464;\n cursor: initial;\n word-wrap: break-word;\n }\n\n .msg.collapsed .msg_desc {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .msg.collapsible.collapsed .chevron {\n transform: rotate(-45deg) translateX(-2px);\n }\n\n .msg.collapsible .chevron {\n content: "";\n width:6px;\n height:6px;\n border-bottom: 2px solid grey;\n border-right: 2px solid grey;\n transform: rotate(45deg) translateX(-1px);\n margin: 5px;\n flex-shrink:0;\n }\n</style>\n\n<div style="top:32px; left:${window.innerWidth-300-32}px;" class="debugger">\n <div class="header">\n <span>Debugger messages</span>\n </div>\n <div class="content">\n <div class="empty-state">\n No errors detected 👀\n </div>\n </div>\n</div>\n`;class Nl extends HTMLElement{constructor(){super(),El.add(this),Rl.set(this,new Ea({messages:[]})),Pl.set(this,void 0),Tl.set(this,void 0),_l.set(this,void 0),$l.set(this,{resize:h(this,El,"m",Dl).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Wl.content.cloneNode(!0)),p(this,Pl,this.shadowRoot.querySelector(".debugger"),"f"),p(this,Tl,h(this,Pl,"f").querySelector(".content"),"f"),p(this,_l,h(this,Pl,"f").querySelector(".header"),"f")}updateData(e){h(this,Rl,"f").update((t=>({messages:t.messages.concat(e)})))}connectedCallback(){var e;((e,t,n)=>{let o=0,i=0,r=0,s=0;function a(t){t.preventDefault(),o=r-t.clientX,i=s-t.clientY,r=t.clientX,s=t.clientY;const[a,l]=Al(e,e.offsetLeft-o,e.offsetTop-i,n);e.style.top=`${l}px`,e.style.left=`${a}px`}function l(){document.onmouseup=null,document.onmousemove=null}function c(e){e.preventDefault(),r=e.clientX,s=e.clientY,document.onmouseup=l,document.onmousemove=a}t?t.onmousedown=c:e.onmousedown=c})(h(this,Pl,"f"),h(this,_l,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",h(this,$l,"f").resize),(e=h(this,Pl,"f")).onmousemove=t=>{(t.target.w&&t.target.w!==t.target.offsetWidth||t.target.h&&t.target.h!==t.target.offsetHeight)&&e.onresize(t),t.target.w=t.target.offsetWidth,t.target.h=t.target.offsetHeight},h(this,Pl,"f").onresize=h(this,El,"m",ql).bind(this),h(this,Rl,"f").subscribe(h(this,El,"m",Ll).bind(this))}disconnectedCallback(){h(this,Rl,"f").unsubscribeAll(),window.removeEventListener("resize",h(this,$l,"f").resize)}}Rl=new WeakMap,Pl=new WeakMap,Tl=new WeakMap,_l=new WeakMap,$l=new WeakMap,El=new WeakSet,Ll=function(e){h(this,El,"m",Ml).call(this,e),h(this,El,"m",ql).call(this)},Ml=function(e){h(this,Tl,"f").innerHTML=e.messages.map((e=>`\n <div class="msg">\n <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M5.99984 13.167L8.99984 10.167L11.9998 13.167L13.1665 12.0003L10.1665 9.00033L13.1665 6.00033L11.9998 4.83366L8.99984 7.83366L5.99984 4.83366L4.83317 6.00033L7.83317 9.00033L4.83317 12.0003L5.99984 13.167ZM8.99984 17.3337C7.84706 17.3337 6.76373 17.1148 5.74984 16.677C4.73595 16.2398 3.854 15.6462 3.104 14.8962C2.354 14.1462 1.76039 13.2642 1.32317 12.2503C0.885393 11.2364 0.666504 10.1531 0.666504 9.00033C0.666504 7.84755 0.885393 6.76421 1.32317 5.75033C1.76039 4.73644 2.354 3.85449 3.104 3.10449C3.854 2.35449 4.73595 1.7606 5.74984 1.32283C6.76373 0.885603 7.84706 0.666992 8.99984 0.666992C10.1526 0.666992 11.2359 0.885603 12.2498 1.32283C13.2637 1.7606 14.1457 2.35449 14.8957 3.10449C15.6457 3.85449 16.2393 4.73644 16.6765 5.75033C17.1143 6.76421 17.3332 7.84755 17.3332 9.00033C17.3332 10.1531 17.1143 11.2364 16.6765 12.2503C16.2393 13.2642 15.6457 14.1462 14.8957 14.8962C14.1457 15.6462 13.2637 16.2398 12.2498 16.677C11.2359 17.1148 10.1526 17.3337 8.99984 17.3337ZM8.99984 15.667C10.8609 15.667 12.4373 15.0212 13.729 13.7295C15.0207 12.4378 15.6665 10.8614 15.6665 9.00033C15.6665 7.13921 15.0207 5.56283 13.729 4.27116C12.4373 2.97949 10.8609 2.33366 8.99984 2.33366C7.13873 2.33366 5.56234 2.97949 4.27067 4.27116C2.979 5.56283 2.33317 7.13921 2.33317 9.00033C2.33317 10.8614 2.979 12.4378 4.27067 13.7295C5.56234 15.0212 7.13873 15.667 8.99984 15.667Z" fill="#ED404A"/>\n</svg>\n\n <div class="msg_content">\n <div class="msg_title">\n ${e.title}\n </div>\n <div class="msg_desc">\n ${e.description}\n </div>\n </div>\n <div class="chevron"></div>\n </div>\n `)).join("")},ql=function(){h(this,Tl,"f").querySelectorAll(".msg").forEach((e=>{const t=e.querySelector(".msg_desc"),n=t.scrollWidth>t.clientWidth,o=t.clientHeight>20;n||o?(e.classList.add("collapsible"),e.onclick=t=>{t.target.classList.contains("msg_desc")||e.classList.toggle("collapsed")}):(e.classList.remove("collapsible"),e.onclick=null)}))},Dl=function(){const[e,t]=Al(h(this,Pl,"f"),Number.parseInt(h(this,Pl,"f").style.left,10),Number.parseInt(h(this,Pl,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});h(this,Pl,"f").style.top=`${t}px`,h(this,Pl,"f").style.left=`${e}px`},customElements.define("descope-debugger",Nl);var Jl=Object.freeze({__proto__:null,default:Nl});e.AuthProvider=({projectId:e,baseUrl:n="",sessionTokenViaCookie:s=!1,children:l})=>{const[c,d]=t.useState(),[u,h]=t.useState(),[p,g]=t.useState(!1),[f,v]=t.useState(!1),m=(({projectId:e,baseUrl:n,sessionTokenViaCookie:o})=>t.useMemo((()=>{if(e)return Ao({projectId:e,baseUrl:n,sessionTokenViaCookie:o,baseHeaders:a,persistToken:!0,autoRefresh:!0})}),[e,n,o]))({projectId:e,baseUrl:n,sessionTokenViaCookie:s});t.useEffect((()=>{if(m){const e=m.onSessionTokenChange(h),t=m.onUserChange(d);return()=>{e(),t()}}}),[m]);const b=t.useRef(!1),w=t.useCallback((()=>{b.current||(b.current=!0,v(!0),r(m?.refresh)().then((()=>{v(!1)})))}),[m]),y=t.useCallback((()=>{g(!0),r(m.me)().then((()=>{g(!1)}))}),[m]),I=t.useMemo((()=>({fetchUser:y,user:c,isUserLoading:p,fetchSession:w,session:u,isSessionLoading:f,isSessionFetched:b.current,projectId:e,baseUrl:n,setUser:d,setSession:h,sdk:m})),[y,c,p,w,u,f,b.current,e,n,d,h,m]);return o.default.createElement(i.Provider,{value:I},l)},e.Descope=$o,e.SignInFlow=e=>o.default.createElement($o,{...e,flowId:"sign-in"}),e.SignUpFlow=e=>o.default.createElement($o,{...e,flowId:"sign-up"}),e.SignUpOrInFlow=e=>o.default.createElement($o,{...e,flowId:"sign-up-or-in"}),e.getJwtPermissions=Po,e.getJwtRoles=To,e.getRefreshToken=Ro,e.getSessionToken=Eo,e.refresh=(e=Ro())=>Uo?.refresh(e),e.useDescope=()=>{const{sdk:e}=Lo();return t.useMemo((()=>e||new Proxy(Ao({projectId:"dummy"}),qo)),[e])},e.useSession=()=>{const{session:e,isSessionLoading:n,fetchSession:o,isSessionFetched:i}=Lo(),r=t.useRef(n);return t.useMemo((()=>{r.current=n}),[n]),t.useMemo((()=>{i||(r.current=!0)}),[i]),t.useEffect((()=>{e||n||o()}),[o]),{isSessionLoading:r.current,sessionToken:e,isAuthenticated:!!e}},e.useUser=()=>{const{user:e,fetchUser:n,isUserLoading:o,session:i}=Lo(),[r,s]=t.useState(!1),a=t.useRef(o),l=t.useMemo((()=>!e&&!o&&i&&!r),[n,i,r]);return t.useMemo((()=>{a.current=o}),[o]),t.useMemo((()=>{l&&(a.current=!0)}),[l]),t.useEffect((()=>{l&&(s(!0),n())}),[l]),{isUserLoading:a.current,user:e}},Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Descope={},e.React)}(this,(function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=n(t);const r=o.default.createContext(void 0),i=e=>(...t)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...t)},s=e=>(...t)=>{let n;try{n=e(...t)}catch(e){console.error(e)}return n},a={"x-descope-sdk-name":"react","x-descope-sdk-version":"2.0.0"},l="undefined"!=typeof window;var c=function(){return c=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},c.apply(this,arguments)};function d(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 u(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{l(o.next(e))}catch(e){i(e)}}function a(e){try{l(o.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}l((o=o.apply(e,t||[])).next())}))}function h(e,t,n,o){if("a"===n&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?o:"a"===n?o.call(e):o?o.value:t.get(e)}function p(e,t,n,o,r){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?r.call(e,n):r?r.value=n:t.set(e,n),n}function f(e){this.message=e}"function"==typeof SuppressedError&&SuppressedError,f.prototype=new Error,f.prototype.name="InvalidCharacterError";var g="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new f("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,r=0,i=0,s="";o=t.charAt(i++);~o&&(n=r%4?64*n+o:o,r++%4)?s+=String.fromCharCode(255&n>>(-2*r&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return s};function v(e){this.message=e}function m(e,t){if("string"!=typeof e)throw new v("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(function(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(g(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return g(t)}}(e.split(".")[n]))}catch(e){throw new v("Invalid token specified: "+e.message)}}v.prototype=new Error,v.prototype.name="InvalidTokenError";var b="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function w(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var y="__lodash_hash_undefined__",I="[object Function]",k="[object GeneratorFunction]",S=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,j=/^\w*$/,x=/^\./,C=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,O=/\\(\\)?/g,E=/^\[object .+?Constructor\]$/,A="object"==typeof b&&b&&b.Object===Object&&b,U="object"==typeof self&&self&&self.Object===Object&&self,R=A||U||Function("return this")();var _,T=Array.prototype,P=Function.prototype,L=Object.prototype,M=R["__core-js_shared__"],$=(_=/[^.]+$/.exec(M&&M.keys&&M.keys.IE_PROTO||""))?"Symbol(src)_1."+_:"",q=P.toString,W=L.hasOwnProperty,D=L.toString,F=RegExp("^"+q.call(W).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),K=R.Symbol,N=T.splice,J=te(R,"Map"),H=te(Object,"create"),z=K?K.prototype:void 0,V=z?z.toString:void 0;function B(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var o=e[t];this.set(o[0],o[1])}}function G(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var o=e[t];this.set(o[0],o[1])}}function Y(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var o=e[t];this.set(o[0],o[1])}}function Z(e,t){for(var n,o,r=e.length;r--;)if((n=e[r][0])===(o=t)||n!=n&&o!=o)return r;return-1}function X(e,t){var n;t=function(e,t){if(ie(e))return!1;var n=typeof e;if("number"==n||"symbol"==n||"boolean"==n||null==e||ae(e))return!0;return j.test(e)||!S.test(e)||null!=t&&e in Object(t)}(t,e)?[t]:ie(n=t)?n:ne(n);for(var o=0,r=t.length;null!=e&&o<r;)e=e[oe(t[o++])];return o&&o==r?e:void 0}function Q(e){if(!se(e)||(t=e,$&&$ in t))return!1;var t,n=function(e){var t=se(e)?D.call(e):"";return t==I||t==k}(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e)?F:E;return n.test(function(e){if(null!=e){try{return q.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function ee(e,t){var n,o,r=e.__data__;return("string"==(o=typeof(n=t))||"number"==o||"symbol"==o||"boolean"==o?"__proto__"!==n:null===n)?r["string"==typeof t?"string":"hash"]:r.map}function te(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Q(n)?n:void 0}B.prototype.clear=function(){this.__data__=H?H(null):{}},B.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},B.prototype.get=function(e){var t=this.__data__;if(H){var n=t[e];return n===y?void 0:n}return W.call(t,e)?t[e]:void 0},B.prototype.has=function(e){var t=this.__data__;return H?void 0!==t[e]:W.call(t,e)},B.prototype.set=function(e,t){return this.__data__[e]=H&&void 0===t?y:t,this},G.prototype.clear=function(){this.__data__=[]},G.prototype.delete=function(e){var t=this.__data__,n=Z(t,e);return!(n<0)&&(n==t.length-1?t.pop():N.call(t,n,1),!0)},G.prototype.get=function(e){var t=this.__data__,n=Z(t,e);return n<0?void 0:t[n][1]},G.prototype.has=function(e){return Z(this.__data__,e)>-1},G.prototype.set=function(e,t){var n=this.__data__,o=Z(n,e);return o<0?n.push([e,t]):n[o][1]=t,this},Y.prototype.clear=function(){this.__data__={hash:new B,map:new(J||G),string:new B}},Y.prototype.delete=function(e){return ee(this,e).delete(e)},Y.prototype.get=function(e){return ee(this,e).get(e)},Y.prototype.has=function(e){return ee(this,e).has(e)},Y.prototype.set=function(e,t){return ee(this,e).set(e,t),this};var ne=re((function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(ae(e))return V?V.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(t);var n=[];return x.test(e)&&n.push(""),e.replace(C,(function(e,t,o,r){n.push(o?r.replace(O,"$1"):t||e)})),n}));function oe(e){if("string"==typeof e||ae(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function re(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var o=arguments,r=t?t.apply(this,o):o[0],i=n.cache;if(i.has(r))return i.get(r);var s=e.apply(this,o);return n.cache=i.set(r,s),s};return n.cache=new(re.Cache||Y),n}re.Cache=Y;var ie=Array.isArray;function se(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function ae(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==D.call(e)}var le=w((function(e,t,n){var o=null==e?void 0:X(e,t);return void 0===o?n:o})),ce="/v1/auth/accesskey/exchange",de="/v1/auth/otp/verify",ue="/v1/auth/otp/signin",he="/v1/auth/otp/signup",pe={email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},fe="/v1/auth/otp/signup-in",ge="/v1/auth/magiclink/verify",ve="/v1/auth/magiclink/signin",me="/v1/auth/magiclink/signup",be={email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},we="/v1/auth/magiclink/signup-in",ye="/v1/auth/enchantedlink/verify",Ie="/v1/auth/enchantedlink/signin",ke="/v1/auth/enchantedlink/signup",Se="/v1/auth/enchantedlink/pending-session",je={email:"/v1/auth/enchantedlink/update/email"},xe="/v1/auth/enchantedlink/signup-in",Ce="/v1/auth/oauth/authorize",Oe="/v1/auth/oauth/exchange",Ee="/v1/auth/saml/authorize",Ae="/v1/auth/saml/exchange",Ue="/v1/auth/totp/verify",Re="/v1/auth/totp/signup",_e="/v1/auth/totp/update",Te={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},Pe={start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},Le={start:"/v1/auth/webauthn/signup-in/start"},Me={start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"},$e="/v1/auth/password/signup",qe="/v1/auth/password/signin",We="/v1/auth/password/reset",De="/v1/auth/password/update",Fe="/v1/auth/password/replace",Ke="/v1/auth/password/policy",Ne="/v1/auth/refresh",Je="/v1/auth/logout",He="/v1/auth/logoutall",ze="/v1/auth/me",Ve="/v1/flow/start",Be="/v1/flow/next";const Ge=6e5,Ye=()=>{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")}};var Ze;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(Ze||(Ze={}));const Xe=(...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}),{})),Qe=e=>void 0===e?void 0:JSON.stringify(e),et=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},tt=({baseUrl:e,projectId:t,baseConfig:n,logger:o,hooks:r,cookiePolicy:i,fetch:s})=>{const a=((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=>Ye().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 Ye().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(o)),o}:n})(o,s),l=async o=>{const s=(null==r?void 0:r.beforeRequest)?r.beforeRequest(o):o,{path:l,body:c,headers:d,queryParams:u,method:h,token:p}=s,f=await a((({path:e,baseUrl:t,queryParams:n})=>{const o=new URL(e,t);return n&&(o.search=new URLSearchParams(n).toString()),o})({path:l,baseUrl:e,queryParams:u}),{headers:Xe(et(t,p),{"x-descope-sdk-name":"core-js","x-descope-sdk-version":"2.0.0"},(null==n?void 0:n.baseHeaders)||{},d),method:h,body:Qe(c),credentials:i||"include"});return(null==r?void 0:r.afterRequest)&&await r.afterRequest(o,null==f?void 0:f.clone()),f};return{get:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:Ze.get,token:o}),post:(e,t,{headers:n,queryParams:o,token:r}={})=>l({path:e,headers:n,queryParams:o,body:t,method:Ze.post,token:r}),put:(e,t,{headers:n,queryParams:o,token:r}={})=>l({path:e,headers:n,queryParams:o,body:t,method:Ze.put,token:r}),delete:(e,{headers:t,queryParams:n,token:o}={})=>l({path:e,headers:t,queryParams:n,body:void 0,method:Ze.delete,token:o}),hooks:r}};var nt=429;function ot(e,t,n){var o;let r=rt(e);t&&(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 rt(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return m(e)}function it(e){const{exp:t}=rt(e);return(new Date).getTime()/1e3>t}function st(e){let t=rt(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function at(e,t){return ot(e,t,"permissions")}function lt(e,t){return ot(e,t,"roles")}const ct=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function dt(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=t?t(i):i:(r.error=i,o.status===nt&&Object.assign(r.error,{retryAfter:Number.parseInt(null===(n=o.headers)||void 0===n?void 0:n.get("retry-after"))||0})),r}const ut=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),ht=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),pt=e=>t=>e.test(t),ft=pt(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),gt=pt(/^\+[1-9]{1}[0-9]{3,14}$/),vt=ut(ft,'"{val}" is not a valid email'),mt=ut(gt,'"{val}" is not a valid phone number'),bt=ut((1,e=>e.length>=1),"Minimum length is 1");const wt=ut((e=>"string"==typeof e),"Input is not a string"),yt=ut((e=>void 0===e),"Input is defined"),It=(kt=[wt(),yt()],"Input is not a string or undefined",(e="Input is not a string or undefined")=>t=>{const n=kt.filter((e=>e(t)));return!(n.length<kt.length)&&(e?e.replace("{val}",t):n.join(" OR "))});var kt;const St=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>ht(...e).validate(n[t]))),t(...n)),jt=e=>[wt(`"${e}" must be a string`),bt(`"${e}" must not be empty`)],xt=e=>[wt(`"${e}" must be a string`),vt()],Ct=e=>[wt(`"${e}" must be a string`),mt()],Ot=St(jt("accessKey")),Et=e=>({exchange:Ot((t=>dt(e.post(ce,{},{token:t}))))});var At,Ut;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(At||(At={})),function(e){e.email="email"}(Ut||(Ut={}));const Rt=Object.assign(Object.assign({},At),Ut);var _t;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(_t||(_t={}));const Tt=jt("loginId"),Pt=St(jt("token")),Lt=St(Tt),Mt=St(jt("pendingRef")),$t=St(Tt,xt("email")),qt=e=>({verify:Pt((t=>dt(e.post(ye,{token:t})))),signIn:Lt(((t,n,o,r)=>dt(e.post(ct(Ie,Rt.email),{loginId:t,URI:n,loginOptions:o},{token:r})))),signUpOrIn:Lt(((t,n)=>dt(e.post(ct(xe,Rt.email),{loginId:t,URI:n})))),signUp:Lt(((t,n,o)=>dt(e.post(ct(ke,Rt.email),{loginId:t,URI:n,user:o})))),waitForSession:Mt(((t,n)=>new Promise((o=>{const{pollingIntervalMs:r,timeoutMs:i}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||Ge,Ge)}))(n);let s;const a=setInterval((async()=>{const n=await e.post(Se,{pendingRef:t});n.ok&&(clearInterval(a),s&&clearTimeout(s),o(dt(Promise.resolve(n))))}),r);s=setTimeout((()=>{o({error:{errorDescription:`Session polling timeout exceeded: ${i}ms`,errorCode:"0"},ok:!1}),clearInterval(a)}),i)})))),update:{email:$t(((t,n,o,r,i)=>dt(e.post(je.email,Object.assign({loginId:t,email:n,URI:o},i),{token:r}))))}}),Wt=St(jt("flowId")),Dt=St(jt("executionId"),jt("stepId"),jt("interactionId")),Ft=e=>({start:Wt(((t,n,o,r,i,s,a)=>dt(e.post(Ve,{flowId:t,options:n,conditionInteractionId:o,interactionId:r,version:i,componentsVersion:s,input:a})))),next:Dt(((t,n,o,r,i,s)=>dt(e.post(Be,{executionId:t,stepId:n,interactionId:o,version:r,componentsVersion:i,input:s}))))}),Kt=jt("loginId"),Nt=St(jt("token")),Jt=St(Kt),Ht=St(Kt,Ct("phone")),zt=St(Kt,xt("email")),Vt=e=>({verify:Nt((t=>dt(e.post(ge,{token:t})))),signIn:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Jt(((t,o,r,i)=>dt(e.post(ct(ve,n),{loginId:t,URI:o,loginOptions:r},{token:i}))))})),{}),signUp:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Jt(((t,o,r)=>dt(e.post(ct(me,n),{loginId:t,URI:o,user:r}))))})),{}),signUpOrIn:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Jt(((t,o)=>dt(e.post(ct(we,n),{loginId:t,URI:o}))))})),{}),update:{email:zt(((t,n,o,r,i)=>dt(e.post(be.email,Object.assign({loginId:t,email:n,URI:o},i),{token:r})))),phone:Object.keys(At).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ht(((t,o,r,i,s)=>dt(e.post(ct(be.phone,n),Object.assign({loginId:t,phone:o,URI:r},s),{token:i}))))})),{})}});var Bt;!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"}(Bt||(Bt={}));const Gt=St(jt("code")),Yt=e=>({start:Object.assign(((t,n,o,r)=>dt(e.post(Ce,o||{},{queryParams:Object.assign({provider:t},n&&{redirectURL:n}),token:r}))),Object.keys(Bt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,o,r)=>dt(e.post(Ce,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:r}))})),{})),exchange:Gt((t=>dt(e.post(Oe,{code:t}))))}),Zt=jt("loginId"),Xt=St(Zt,jt("code")),Qt=St(Zt),en=St(Zt,Ct("phone")),tn=St(Zt,xt("email")),nn=e=>({verify:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Xt(((t,o)=>dt(e.post(ct(de,n),{code:o,loginId:t}))))})),{}),signIn:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Qt(((t,o,r)=>dt(e.post(ct(ue,n),{loginId:t,loginOptions:o},{token:r}))))})),{}),signUp:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Qt(((t,o)=>dt(e.post(ct(he,n),{loginId:t,user:o}))))})),{}),signUpOrIn:Object.keys(Rt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Qt((t=>dt(e.post(ct(fe,n),{loginId:t}))))})),{}),update:{email:tn(((t,n,o,r)=>dt(e.post(pe.email,Object.assign({loginId:t,email:n},r),{token:o})))),phone:Object.keys(At).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:en(((t,o,r,i)=>dt(e.post(ct(pe.phone,n),Object.assign({loginId:t,phone:o},i),{token:r}))))})),{})}}),on=St(jt("tenant")),rn=St(jt("code")),sn=e=>({start:on(((t,n,o,r)=>dt(e.post(Ee,o||{},{queryParams:{tenant:t,redirectURL:n},token:r})))),exchange:rn((t=>dt(e.post(Ae,{code:t}))))}),an=jt("loginId"),ln=St(an,jt("code")),cn=St(an),dn=St(an),un=e=>({signUp:cn(((t,n)=>dt(e.post(Re,{loginId:t,user:n})))),verify:ln(((t,n,o,r)=>dt(e.post(Ue,{loginId:t,code:n,loginOptions:o},{token:r})))),update:dn(((t,n)=>dt(e.post(_e,{loginId:t},{token:n}))))}),hn=jt("loginId"),pn=jt("newPassword"),fn=St(hn,jt("password")),gn=St(hn),vn=St(hn,pn),mn=St(hn,jt("oldPassword"),pn),bn=e=>({signUp:fn(((t,n,o)=>dt(e.post($e,{loginId:t,password:n,user:o})))),signIn:fn(((t,n)=>dt(e.post(qe,{loginId:t,password:n})))),sendReset:gn(((t,n)=>dt(e.post(We,{loginId:t,redirectUrl:n})))),update:vn(((t,n,o)=>dt(e.post(De,{loginId:t,newPassword:n},{token:o})))),replace:mn(((t,n,o)=>dt(e.post(Fe,{loginId:t,oldPassword:n,newPassword:o})))),policy:()=>dt(e.get(Ke))}),wn=[wt('"loginId" must be a string')],yn=jt("loginId"),In=jt("origin"),kn=St(yn,In,jt("name")),Sn=St(yn,In),jn=St(wn,In),xn=St(yn,In,jt("token")),Cn=St(jt("transactionId"),jt("response")),On=e=>({signUp:{start:kn(((t,n,o)=>dt(e.post(Te.start,{user:{loginId:t,name:o},origin:n})))),finish:Cn(((t,n)=>dt(e.post(Te.finish,{transactionId:t,response:n}))))},signIn:{start:jn(((t,n,o,r)=>dt(e.post(Pe.start,{loginId:t,origin:n,loginOptions:o},{token:r})))),finish:Cn(((t,n)=>dt(e.post(Pe.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:Sn(((t,n)=>dt(e.post(Le.start,{loginId:t,origin:n}))))},update:{start:xn(((t,n,o)=>dt(e.post(Me.start,{loginId:t,origin:n},{token:o})))),finish:Cn(((t,n)=>dt(e.post(Me.finish,{transactionId:t,response:n}))))}}),En=St(jt("token")),An=St([It('"token" must be string or undefined')]);var Un,Rn=St([("projectId",Un=jt("projectId"),ut(((e,t)=>n=>ht(...t).validate(le(n,e)))("projectId",Un))())])((e=>{var t,n;const o=[].concat((null===(t=e.hooks)||void 0===t?void 0:t.beforeRequest)||[]),r=[].concat((null===(n=e.hooks)||void 0===n?void 0:n.afterRequest)||[]);return(({projectId:e,logger:t,baseUrl:n,hooks:o,cookiePolicy:r,baseHeaders:i={},fetch:s})=>{return a=tt({baseUrl:n||"https://api.descope.com",projectId:e,logger:t,hooks:o,cookiePolicy:r,baseConfig:{baseHeaders:i},fetch:s}),{accessKey:Et(a),otp:nn(a),magicLink:Vt(a),enchantedLink:qt(a),oauth:Yt(a),saml:sn(a),totp:un(a),webauthn:On(a),password:bn(a),flow:Ft(a),refresh:An((e=>dt(a.post(Ne,{},{token:e})))),logout:An((e=>dt(a.post(Je,{},{token:e})))),logoutAll:An((e=>dt(a.post(He,{},{token:e})))),me:An((e=>dt(a.get(ze,{token:e})))),isJwtExpired:En(it),getTenants:En(st),getJwtPermissions:En(at),getJwtRoles:En(lt),httpClient:a};var a})(Object.assign(Object.assign({},e),{hooks:{beforeRequest:e=>null==o?void 0:o.reduce(((e,t)=>t(e)),e),afterRequest:async(t,n)=>{(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))}))}}}))}));const _n=(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);var Tn=Object.assign(Rn,{DeliveryMethods:Rt});var Pn="Blocked by CSP",Ln="9319";function Mn(e,t){var n=[];return function(e,t){var n,o,r=(o=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),{current:function(){return o[0]},postpone:function(){var e=o.shift();void 0!==e&&o.push(e)},exclude:function(){o.shift()}}),i=(100,3e3,n=0,function(){return Math.random()*Math.min(3e3,100*Math.pow(2,n++))}),s=r.current();if(void 0===s)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var a=function(e,n){return t(e).catch((function(e){if(n+1>=5)throw e;!function(e){if(!(e instanceof Error))return!1;var t=e.message;return t===Pn||t===Ln}(e)?r.postpone():r.exclude();var t,o=r.current();if(void 0===o)throw e;return(t=i(),new Promise((function(e){return setTimeout(e,t)}))).then((function(){return a(o,n+1)}))}))};return a(s,0)}(e,(function(e){var o=new Date,r=function(t){return n.push({url:e,startedAt:o,finishedAt:new Date,error:t})},i=t(e);return i.then((function(){return r()}),r),i})).then((function(e){return[e,{attempts:n}]}))}var $n="Failed to load the JS script of the agent";function qn(e){var t;e.scriptUrlPattern;var n=e.token,o=e.apiKey,r=void 0===o?n:o,i=d(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:"https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js";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.8.5"):e}))}(String(e),t)}))}(s,r);return Mn(e,Wn).catch(Fn)})).then((function(e){var t=e[0],n=e[1];return t.load(c(c({},i),{ldi:n}))}))}function Wn(e){return function(e,t,n,o){var r,i=document,s="securitypolicyviolation",a=function(t){var n=new URL(e,location.href),o=t.blockedURI;o!==n.href&&o!==n.protocol.slice(0,-1)&&o!==n.origin||(r=t,l())};i.addEventListener(s,a);var l=function(){return i.removeEventListener(s,a)};return Promise.resolve().then(t).then((function(e){return l(),e}),(function(e){return new Promise((function(e){return setTimeout(e)})).then((function(){if(l(),r)return function(){throw new Error(Pn)}();throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,n){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($n))},o.async=!0,o.src=e,i.appendChild(o)}))}(e)})).then(Dn)}function Dn(){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(Ln);return n}function Fn(e){throw e instanceof Error&&e.message===Ln?new Error($n):e}var Kn={exports:{}};
|
|
2
|
+
/*! js-cookie v3.0.5 | MIT */!function(e,t){e.exports=function(){function e(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)e[o]=n[o]}return e}function t(n,o){function r(t,r,i){if("undefined"!=typeof document){"number"==typeof(i=e({},o,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var s="";for(var a in i)i[a]&&(s+="; "+a,!0!==i[a]&&(s+="="+i[a].split(";")[0]));return document.cookie=t+"="+n.write(r,t)+s}}function i(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],o={},r=0;r<t.length;r++){var i=t[r].split("="),s=i.slice(1).join("=");try{var a=decodeURIComponent(i[0]);if(o[a]=n.read(s,a),e===a)break}catch(e){}}return e?o[e]:o}}return Object.create({set:r,get:i,remove:function(t,n){r(t,"",e({},n,{expires:-1}))},withAttributes:function(n){return t(this.converter,e({},this.attributes,n))},withConverter:function(n){return t(e({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(o)},converter:{value:Object.freeze(n)}})}return 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:"/"})}()}(Kn);var Nn=w(Kn.exports);const Jn=(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},Hn=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||{}},zn=async e=>{const t=await Hn(e);return(null==t?void 0:t.user)||((null==t?void 0:t.hasOwnProperty("userId"))?t:void 0)},Vn="undefined"!=typeof localStorage,Bn=(e,t)=>Vn&&(null===localStorage||void 0===localStorage?void 0:localStorage.setItem(e,t)),Gn=e=>Vn&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem(e)),Yn=e=>Vn&&(null===localStorage||void 0===localStorage?void 0:localStorage.removeItem(e)),Zn=(...e)=>{console.debug(...e)},Xn="undefined"!=typeof window,Qn=Math.pow(2,31)-1,eo=Xn&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",to=(e="",t="")=>({vsid:e,vrid:t}),no=(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},oo=e=>(e.body&&(e.body.fpData=no(!0)||to()),e),ro="dls_last_user_login_id",io="dls_last_user_display_name",so=()=>Gn(ro),ao=()=>Gn(io),lo=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,r=so(),i=ao();return r&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=r,o.lastAuth.name=i),await e(...t)},co=e=>async(...t)=>{const n=await e(...t);return Yn(ro),Yn(io),n};function uo(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const ho="DS",po="DSR";function fo(e=""){return Gn(`${e}${po}`)||""}function go(e=""){Yn(`${e}${po}`),Yn(`${e}${ho}`),Nn.remove(ho)}async function vo(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=ko(n.publicKey.challenge),n.publicKey.user.id=ko(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=ko(e.id)})),n}(e);return n=await navigator.credentials.create(t),JSON.stringify({id:n.id,rawId:So(n.rawId),type:n.type,response:{attestationObject:So(n.response.attestationObject),clientDataJSON:So(n.response.clientDataJSON)}});var n}async function mo(e){const t=yo(e);return Io(await navigator.credentials.get(t))}async function bo(e,t){const n=yo(e);return n.signal=t.signal,n.mediation="conditional",Io(await navigator.credentials.get(n))}async function wo(e=!1){if(!Xn)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 yo(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=ko(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=ko(e.id)})),n}function Io(e){return JSON.stringify({id:e.id,rawId:So(e.rawId),type:e.type,response:{authenticatorData:So(e.response.authenticatorData),clientDataJSON:So(e.response.clientDataJSON),signature:So(e.response.signature),userHandle:e.response.userHandle?So(e.response.userHandle):void 0}})}function ko(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function So(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}var jo,xo=(jo=e=>({async signUp(t,n){const o=await e.webauthn.signUp.start(t,window.location.origin,n);if(!o.ok)return o;const r=await vo(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,r)},async signIn(t){const n=await e.webauthn.signIn.start(t,window.location.origin);if(!n.ok)return n;const o=await mo(n.data.options);return await e.webauthn.signIn.finish(n.data.transactionId,o)},async signUpOrIn(t){var n;const o=await e.webauthn.signUpOrIn.start(t,window.location.origin);if(!o.ok)return o;if(null===(n=o.data)||void 0===n?void 0:n.create){const t=await vo(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,t)}{const t=await mo(o.data.options);return await e.webauthn.signIn.finish(o.data.transactionId,t)}},async update(t,n){const o=await e.webauthn.update.start(t,window.location.origin,n);if(!o.ok)return o;const r=await vo(o.data.options);return await e.webauthn.update.finish(o.data.transactionId,r)},helpers:{create:vo,get:mo,isSupported:wo,conditional:bo}}),(...e)=>{const t=jo(...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}),Co=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await wo(),o=Object.assign(Object.assign({redirectUrl:window.location.href,location:window.location.href},t[1]),{deviceInfo:{webAuthnSupport:n}});return t[1]=o,e.flow.start(...t)}});const Oo=function(...e){return t=>e.reduce(((e,t)=>t(e)),t)}((e=>t=>{var{fpKey:n,fpLoad:o}=t,r=d(t,["fpKey","fpLoad"]);return n?(Xn?o&&(async e=>{try{if(no())return;const t=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27),n=qn({apiKey:e,endpoint:eo}),o=await n,{requestId:r}=await o.get({linkedId:t});(e=>{const t={value:e,expiry:(new Date).getTime()+864e5};localStorage.setItem("fp",JSON.stringify(t))})(to(t,r))}catch(e){global.FB_DEBUG&&console.error(e)}})(n).catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server"),e(Jn(r,{beforeRequest:oo}))):e(Object.assign({},r))}),(e=>t=>{var{autoRefresh:n}=t,o=d(t,["autoRefresh"]);if(!n)return e(o);const{clearAllTimers:r,setTimer:i}=(()=>{const e=[];return{clearAllTimers:()=>{for(;e.length;)clearTimeout(e.pop())},setTimer:(t,n)=>{e.push(setTimeout(t,n))}}})();let s,a;document.addEventListener("visibilitychange",(()=>{"visible"===document.visibilityState&&new Date>s&&(Zn("Expiration time passed, refreshing session"),l.refresh(a))}));const l=e(Jn(o,{afterRequest:async(e,t)=>{const{refreshJwt:n,sessionJwt:o}=await Hn(t);if(401===(null==t?void 0:t.status))Zn("Received 401, canceling all timers"),r();else if(o){s=(e=>{const t=e.split(".");try{if(3===t.length){const e=JSON.parse(window.atob(t[1]));if(e.exp)return new Date(1e3*e.exp)}}catch(e){}return null})(o),a=n;let e=((c=s)?c.getTime()-(new Date).getTime():0)-2e4;e>Qn&&(Zn(`Timeout is too large (${e}ms), setting it to ${Qn}ms`),e=Qn),r();const t=new Date(Date.now()+e).toLocaleTimeString("en-US",{hour12:!1});Zn(`Setting refresh timer for ${t}. (${e}ms)`),i((()=>{Zn("Refreshing session due to timer"),l.refresh(n)}),e)}var c}}));return _n(l,["logout","logoutAll"],(e=>async(...t)=>{const n=await e(...t);return Zn("Clearing all timers"),r(),n}))}),(e=>t=>e(Object.assign(Object.assign({},t),{baseHeaders:Object.assign({"x-descope-sdk-name":"web-js","x-descope-sdk-version":"1.6.7"},t.baseHeaders)}))),(e=>t=>{const n=uo(),o=uo(),r=e(Jn(t,{afterRequest:async(e,t)=>{if(401===(null==t?void 0:t.status))n.pub(null),o.pub(null);else{const e=await zn(t);e&&o.pub(e);const{sessionJwt:r}=await Hn(t);r&&n.pub(r)}}})),i=_n(r,["logout","logoutAll"],(e=>async(...t)=>{const r=await e(...t);return n.pub(null),o.pub(null),r}));return Object.assign(i,{onSessionTokenChange:n.sub,onUserChange:o.sub})}),(e=>t=>{const n=e(Jn(t,{afterRequest:async(e,t)=>{var n;const o=await zn(t),r=null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0],i=null==o?void 0:o.name;r&&((e=>{Bn(ro,e)})(r),(e=>{Bn(io,e)})(i))}}));let o=_n(n,["flow.start"],lo);return o=_n(o,["logout","logoutAll"],co),Object.assign(o,{getLastUserLoginId:so,getLastUserDisplayName:ao})}),(e=>t=>{var{persistTokens:n,sessionTokenViaCookie:o,storagePrefix:r}=t,i=d(t,["persistTokens","sessionTokenViaCookie","storagePrefix"]);if(!n||!Xn)return n&&console.warn("Storing auth tokens in local storage and cookies are a client side only capabilities and will not be done when running in the server"),e(i);const s=e(Jn(i,{beforeRequest:(a=r,e=>Object.assign(e,{token:e.token||fo(a)})),afterRequest:async(e,t)=>{401===(null==t?void 0:t.status)?go(r):((e={},t,n)=>{var{refreshJwt:o,sessionJwt:r}=e,i=d(e,["refreshJwt","sessionJwt"]);void 0===t&&(t=!1),void 0===n&&(n=""),o&&Bn(`${n}${po}`,o),r&&(t?function(e,t,{cookiePath:n,cookieDomain:o,cookieExpiration:r}){if(t){const i=new Date(1e3*r);Nn.set(e,t,{path:n,domain:o,expires:i,sameSite:"Strict",secure:!0})}}(ho,r,i):Bn(`${n}${ho}`,r))})(await Hn(t),o,r)}}));var a;const l=_n(s,["logout","logoutAll"],(e=>t=>async(...n)=>{const o=await t(...n);return go(e),o})(r));return Object.assign(l,{getRefreshToken:()=>fo(r),getSessionToken:()=>function(e=""){return Nn.get(ho)||Gn(`${e}${ho}`)||""}(r)})}))(((...e)=>{const t=Tn(...e);return Object.assign(Object.assign({},t),{flow:Co(t),webauthn:xo(t)})}));let Eo;const Ao=e=>{const t=Oo({...e,persistTokens:l,autoRefresh:l});return Eo=t,t};Eo=Ao({projectId:"temp pid"});const Uo=()=>l?Eo?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),Ro=()=>l?Eo?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),_o=s(((e=Uo(),t)=>Eo?.getJwtPermissions(e,t))),To=s(((e=Uo(),t)=>Eo?.getJwtRoles(e,t)));const Po=t.lazy((async()=>((await Promise.resolve().then((function(){return ki}))).default.sdkConfigOverrides={baseHeaders:a},{default:({projectId:e,flowId:t,baseUrl:n,innerRef:r,tenant:i,theme:s,locale:a,debug:l,telemetryKey:c,redirectUrl:d,autoFocus:u})=>o.default.createElement("descope-wc",{"project-id":e,"flow-id":t,"base-url":n,ref:r,tenant:i,theme:s,locale:a,debug:l,telemetryKey:c,"redirect-url":d,"auto-focus":u})}))),Lo=o.default.forwardRef((({flowId:e,onSuccess:n,onError:i,logger:s,tenant:a,theme:l,locale:c,debug:d,telemetryKey:u,redirectUrl:h,autoFocus:p,errorTransformer:f},g)=>{const[v,m]=t.useState(null);t.useImperativeHandle(g,(()=>v));const{projectId:b,baseUrl:w,sdk:y}=o.default.useContext(r),I=t.useCallback((async e=>{await y.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),n&&n(e)}),[n]);return t.useEffect((()=>{const e=v;return e?.addEventListener("success",I),i&&e?.addEventListener("error",i),()=>{i&&e?.removeEventListener("error",i),e?.removeEventListener("success",I)}}),[v,i,I]),t.useEffect((()=>{v&&(v.errorTransformer=f)}),[v,f]),t.useEffect((()=>{v&&s&&(v.logger=s)}),[v,s]),o.default.createElement("form",null,o.default.createElement(t.Suspense,{fallback:null},o.default.createElement(Po,{projectId:b,flowId:e,baseUrl:w,innerRef:m,tenant:a,theme:l,locale:c,debug:d,telemetryKey:u,redirectUrl:h,autoFocus:p})))}));var Mo=()=>{const e=t.useContext(r);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const $o=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,qo={get(e,t){if("object"==typeof e[t]&&null!==e[t])return new Proxy(e[t],qo);if("function"==typeof e[t])return()=>{throw Error($o("function"))};throw Error($o("attribute"))}},Wo="undefined"!=typeof localStorage,Do=Wo&&localStorage.getItem("base.content.url")||"https://static.descope.com/pages",Fo=Wo&&localStorage.getItem("base.ui.components.url")||"https://cdn.jsdelivr.net/npm/@descope/web-components-ui@<version>/dist/umd/index.js",Ko="descope-login-flow",No="code",Jo="ra-challenge",Ho="ra-callback",zo="ra-initiator",Vo="data-exclude-field",Bo="dls_last_auth",Go="state_id",Yo="saml_idp_state_id",Zo="saml_idp_username",Xo="sso_app_id",Qo="data-type",er="poll",tr="webauthnCreate",nr="config.json",or="submit",rr="polling";var ir;function sr(e){return new URLSearchParams(window.location.search).get(e)}function ar(e){if(window.history.replaceState&&sr(e)){const t=new URL(window.location.href),n=new URLSearchParams(t.search);n.delete(e),t.search=n.toString(),window.history.replaceState({},"",t.toString())}}function lr(e,t){return u(this,void 0,void 0,(function*(){const n=yield fetch(e,{cache:"default"});if(!n.ok)throw Error(`Error fetching URL ${e} [${n.status}]`);return{body:yield n[t||"text"](),headers:Object.fromEntries(n.headers.entries())}}))}function cr(e,t,n="v2-beta"){const o=new URL(Do);return o.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(o.pathname,e,n,t),o.toString()}function dr(e,t){if(!Number.isNaN(e)&&!Number.isNaN(t))return e>t?ir.forward:e<t?ir.backward:void 0}!function(e){e.backward="backward",e.forward="forward"}(ir||(ir={}));const ur=()=>{const[e="",t=""]=(sr(Ko)||"").split("_");return{executionId:e,stepId:t}};function hr(){ar(Ko)}const pr=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),fr=()=>{const{executionId:e,stepId:t}=ur();(e||t)&&hr();const n=sr("t")||void 0;n&&ar("t");const o=sr(No)||void 0;o&&ar(No);const r=sr("err")||void 0;r&&ar("err");const{redirectAuthCodeChallenge:i,redirectAuthCallbackUrl:s,redirectAuthInitiator:a}={redirectAuthCodeChallenge:sr(Jo),redirectAuthCallbackUrl:sr(Ho),redirectAuthInitiator:sr(zo)};(i||s||a)&&(ar(Jo),ar(Ho),ar(zo));const l=sr(Go);l&&ar(Go);const c=sr(Yo);c&&ar(Yo);const d=sr(Zo);c&&ar(Zo);const u=sr(Xo);return u&&ar(Xo),{executionId:e,stepId:t,token:n,code:o,exchangeError:r,redirectAuthCodeChallenge:i,redirectAuthCallbackUrl:s,redirectAuthInitiator:a,oidcIdpStateId:l,samlIdpStateId:c,samlIdpUsername:d,ssoAppId:u}},gr=e=>{let t,n;return(...o)=>{return t&&(i=o,(r=t).length===i.length&&r.every(((e,t)=>e===i[t])))||(t=o,n=e(...o)),n;var r,i}},vr=(e,t,n,o,r)=>e&&!t&&e&&!n&&!o&&e&&!r,mr=e=>null==e?void 0:e.submit();var br,wr,yr,Ir;function kr(e,t){const n=Object.getOwnPropertyNames(e),o=Object.getOwnPropertyNames(t);if(n.length!==o.length)return!1;for(let o=0;o<n.length;o+=1){const r=n[o],i=e[r],s=t[r];if(null===i||null===s){if(i!==s)return!1}else if("object"==typeof i&&"object"==typeof s){if(!kr(i,s))return!1}else if(i!==s)return!1}return!0}class Sr{constructor(e={},{updateOnlyOnChange:t=!0}={}){br.set(this,void 0),wr.set(this,{}),yr.set(this,0),Ir.set(this,!1),this.update=e=>{const t="function"==typeof e?e(h(this,br,"f")):e,n=Object.assign(Object.assign({},h(this,br,"f")),t);if(!h(this,Ir,"f")||!kr(h(this,br,"f"),n)){const e=h(this,br,"f");p(this,br,n,"f"),Object.freeze(h(this,br,"f")),setTimeout((()=>{Object.values(h(this,wr,"f")).forEach((t=>t(n,e,((e,t)=>n=>e[n]!==t[n])(n,e))))}),0)}},p(this,br,e,"f"),p(this,Ir,t,"f")}get current(){return Object.assign({},h(this,br,"f"))}subscribe(e){return p(this,yr,h(this,yr,"f")+1,"f"),h(this,wr,"f")[h(this,yr,"f")]=e,h(this,yr,"f").toString()}unsubscribe(e){const t=!!h(this,wr,"f")[e];return t&&delete h(this,wr,"f")[e],t}unsubscribeAll(){return p(this,wr,{},"f"),!0}}br=new WeakMap,wr=new WeakMap,yr=new WeakMap,Ir=new WeakMap;const jr=(e,t)=>{Object.entries(t||{}).forEach((([t,n])=>{Array.from(e.querySelectorAll(`*[name="${t}"]:not([${Vo}])`)).forEach((e=>{e.setAttribute("value",n)}))}))},xr=gr((()=>u(void 0,void 0,void 0,(function*(){var e,t,n,o;if(!window.PublicKeyCredential||!PublicKeyCredential.isConditionalMediationAvailable||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)return!1;try{const r=Promise.all([null===(e=window.PublicKeyCredential)||void 0===e?void 0:e.isConditionalMediationAvailable(),null===(t=window.PublicKeyCredential)||void 0===t?void 0:t.isUserVerifyingPlatformAuthenticatorAvailable()]).then((e=>e.every((e=>!!e)))),i=(()=>{var e;const t=null===(e=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===e?void 0:e.brands,n=null==t?void 0:t.find((({brand:e,version:t})=>"Chromium"===e&&parseFloat(t)));return n?n.version:0})()>=108;return yield(100,n=r,o=i,new Promise(((e,t)=>{let r=!1;const i=setTimeout((()=>{r=!0,void 0!==o?e(o):t(new Error("Promise timed out after 100 ms"))}),100);n.then((t=>{r||(clearTimeout(i),e(t))})).catch((e=>{r||(clearTimeout(i),t(e))}))})))}catch(e){return console.error("Conditional login check failed",e),!1}})))),Cr={"lastAuth.loginId":{"not-empty":e=>!!e.loginId,empty:e=>!e.loginId},idpInitiated:{"is-true":e=>!!e.code,"is-false":e=>!e.code},externalToken:{"is-true":e=>!!e.token,"is-false":e=>!e.token},abTestingKey:{"greater-than":(e,t)=>(e.abTestingKey||0)>t,"less-than":(e,t)=>(e.abTestingKey||0)<t}};function Or(e){const t={};if(e)try{Object.assign(t,JSON.parse(localStorage.getItem(Bo)))}catch(e){}return t}const Er="dls_ab_testing_id",Ar=document.createElement("template");var Ur,Rr,_r,Tr,Pr,Lr,Mr,$r,qr,Wr,Dr,Fr,Kr,Nr,Jr,Hr,zr,Vr,Br,Gr,Yr,Zr,Xr,Qr,ei,ti,ni,oi,ri,ii,si,ai,li,ci,di,ui,hi,pi,fi,gi,vi,mi,bi,wi;Ar.innerHTML='\n\t<style>\n\t\t:host {\n all: initial;\n\t\t\twidth: 100%;\n\t\t\theight: 100%;\n\t\t}\n\n\t\t#wc-root {\n\t\t\theight: 100%;\n\t\t\ttransition: opacity 300ms ease-in-out;\n\t\t}\n\n\t\t#wc-root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1;\n\t\t}\n\n\t</style>\n\t<div id="wc-root"></div>\n\t';class yi extends HTMLElement{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","theme","locale","debug","storage-prefix","preview","telemetryKey","redirect-url","auto-focus"]}constructor(e){super(),Ur.add(this),this.logger=console,Rr.set(this,!1),this.loggerWrapper={error:(e,t="")=>{this.logger.error(e,t,new Error),h(this,Ur,"m",ni).call(this,e,t)},warn:(e,t="")=>{this.logger.warn(e,t)},info:(e,t="",n={})=>{this.logger.info(e,t,n)}},_r.set(this,new Sr({deferredRedirect:!1})),Tr.set(this,new Sr),Pr.set(this,{}),this.getComponentsContext=()=>h(this,Pr,"f"),this.nextRequestStatus=new Sr({isLoading:!1}),Lr.set(this,void 0),Mr.set(this,{popstate:h(this,Ur,"m",Kr).bind(this),visibilitychange:h(this,Ur,"m",Nr).bind(this),componentsContext:h(this,Ur,"m",Xr).bind(this)}),$r.set(this,void 0),Br.set(this,gr((()=>u(this,void 0,void 0,(function*(){const e=cr(this.projectId,nr);try{const{body:t,headers:n}=yield lr(e,"json");return{projectConfig:t,executionContext:{geo:n["x-geo"]}}}catch(e){return{isMissingConfig:!0}}}))))),p(this,$r,e,"f"),h(this,Ur,"m",qr).call(this)}get projectId(){return this.getAttribute("project-id")}get flowId(){return this.getAttribute("flow-id")}get baseUrl(){return this.getAttribute("base-url")||void 0}get tenant(){return this.getAttribute("tenant")||void 0}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get theme(){var e,t;const n=this.getAttribute("theme");return"os"===n?window.matchMedia&&(null===(t=null===(e=window.matchMedia)||void 0===e?void 0:e.call(window,"(prefers-color-scheme: dark)"))||void 0===t?void 0:t.matches)?"dark":"light":n||"light"}get telemetryKey(){return this.getAttribute("telemetryKey")||void 0}get autoFocus(){var e;const t=null!==(e=this.getAttribute("auto-focus"))&&void 0!==e?e:"true";return"skipFirstScreen"===t?t:"true"===t}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}getExecutionContext(){return u(this,void 0,void 0,(function*(){const{executionContext:e}=yield h(this,Br,"f").call(this);return e}))}getProjectConfig(){return u(this,void 0,void 0,(function*(){const{projectConfig:e}=yield h(this,Br,"f").call(this);return e}))}getFlowConfig(){var e,t;return u(this,void 0,void 0,(function*(){const n=yield this.getProjectConfig(),o=(null===(e=null==n?void 0:n.flows)||void 0===e?void 0:e[this.flowId])||{};return null!==(t=o.version)&&void 0!==t||(o.version=0),o}))}getTargetLocales(){return u(this,void 0,void 0,(function*(){const e=yield this.getFlowConfig();return((null==e?void 0:e.targetLocales)||[]).map((e=>e.toLowerCase()))}))}connectedCallback(){return u(this,void 0,void 0,(function*(){if(this.shadowRoot.isConnected){if(h(this,Tr,"f").subscribe(h(this,Ur,"m",ti).bind(this)),h(this,Tr,"f").update({isDebug:this.debug}),h(this,Ur,"m",Wr).call(this))return void h(this,Ur,"m",Dr).call(this);if(h(this,Ur,"m",Fr).call(this),yield h(this,Ur,"m",zr).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");if((yield h(this,Br,"f").call(this)).isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");yield h(this,Ur,"m",ri).call(this),yield h(this,Ur,"m",Yr).call(this),h(this,Ur,"m",Gr).call(this),h(this,Ur,"m",oi).call(this);const{executionId:e,stepId:t,token:n,code:o,exchangeError:r,redirectAuthCallbackUrl:i,redirectAuthCodeChallenge:s,redirectAuthInitiator:a,oidcIdpStateId:l,samlIdpStateId:c,samlIdpUsername:d,ssoAppId:u}=fr();window.addEventListener("popstate",h(this,Mr,"f").popstate),window.addEventListener("components-context",h(this,Mr,"f").componentsContext),window.addEventListener("visibilitychange",h(this,Mr,"f").visibilitychange),h(this,_r,"f").subscribe(h(this,Ur,"m",Hr).bind(this)),h(this,_r,"f").update({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenant,redirectUrl:this.redirectUrl,locale:this.locale,stepId:t,executionId:e,token:n,code:o,exchangeError:r,telemetryKey:this.telemetryKey,redirectAuthCallbackUrl:i,redirectAuthCodeChallenge:s,redirectAuthInitiator:a,oidcIdpStateId:l,samlIdpStateId:c,samlIdpUsername:d,ssoAppId:u}),p(this,Rr,!0,"f")}}))}disconnectedCallback(){h(this,_r,"f").unsubscribeAll(),h(this,Tr,"f").unsubscribeAll(),h(this,Ur,"m",ei).call(this),window.removeEventListener("popstate",h(this,Mr,"f").popstate),window.removeEventListener("visibilitychange",h(this,Mr,"f").visibilitychange),window.removeEventListener("components-context",h(this,Mr,"f").componentsContext)}attributeChangedCallback(e,t,n){if(this.shadowRoot.isConnected&&h(this,Rr,"f")&&t!==n&&yi.observedAttributes.includes(e)){h(this,Ur,"m",Fr).call(this);const o=null===t;h(this,_r,"f").update((({stepId:t,executionId:r})=>{let i=t,s=r;return o||(s=null,i=null,hr()),{[pr(e)]:n,stepId:i,executionId:s}})),h(this,Tr,"f").update({isDebug:this.debug})}}}Rr=new WeakMap,_r=new WeakMap,Tr=new WeakMap,Pr=new WeakMap,Lr=new WeakMap,Mr=new WeakMap,$r=new WeakMap,Br=new WeakMap,Ur=new WeakSet,qr=function(){this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Ar.content.cloneNode(!0)),this.rootElement=this.shadowRoot.querySelector("#wc-root")},Wr=function(){return!this.shadowRoot.host.closest("form")&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)},Dr=function(){const e=this.shadowRoot.host,t=document.createElement("form");e.parentElement.appendChild(t),t.appendChild(e)},Fr=function(){const e=["base-url","tenant","theme","locale","debug","telemetryKey","redirect-url","auto-focus","preview","storage-prefix"];if(yi.observedAttributes.forEach((t=>{if(!e.includes(t)&&!this[pr(t)])throw Error(`${t} cannot be empty`)})),this.theme&&"light"!==this.theme&&"dark"!==this.theme)throw Error('Supported theme values are "light", "dark", or leave empty for using the OS theme')},Kr=function(){const{stepId:e,executionId:t}=ur();h(this,_r,"f").update({stepId:e,executionId:t})},Nr=function(){document.hidden||setTimeout((()=>{h(this,_r,"f").update({deferredRedirect:!1})}),300)},Jr=function(e,t,n){const o=n||void 0,r=!!o;this.sdk=Oo(Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix},yi.sdkConfigOverrides),{projectId:e,baseUrl:t,fpKey:o,fpLoad:r})),["start","next"].forEach((e=>{const t=this.sdk.flow[e];this.sdk.flow[e]=(...e)=>u(this,void 0,void 0,(function*(){this.nextRequestStatus.update({isLoading:!0});try{return yield t(...e)}finally{this.nextRequestStatus.update({isLoading:!1})}}))}))},Hr=function(e,t,n){return u(this,void 0,void 0,(function*(){const{projectId:t,baseUrl:o,telemetryKey:r}=e;if(n("projectId")||n("baseUrl")||n("telemetryKey")){if(!t)return;h(this,Ur,"m",Jr).call(this,t,o,r)}h(this,$r,"f").call(this,e)}))},zr=function(){return u(this,void 0,void 0,(function*(){return(yield h(this,Br,"f").call(this)).isMissingConfig&&(yield h(this,Ur,"m",Vr).call(this))}))},Vr=function(){return u(this,void 0,void 0,(function*(){const e=cr(this.projectId,nr,"v2-alpha");try{return yield lr(e,"json"),!0}catch(e){return!1}}))},Gr=function(){var e,t;return u(this,void 0,void 0,(function*(){const{projectConfig:n}=yield h(this,Br,"f").call(this),o=null===(t=null===(e=null==n?void 0:n.cssTemplate)||void 0===e?void 0:e[this.theme])||void 0===t?void 0:t.fonts;o&&Object.values(o).forEach((e=>(e=>{if(!e)return;const t=document.createElement("link");t.href=e,t.rel="stylesheet",document.head.appendChild(t)})(e.url)))}))},Yr=function(){return u(this,void 0,void 0,(function*(){yield h(this,Ur,"m",Zr).call(this),yield h(this,Ur,"m",Qr).call(this)}))},Zr=function(){var e,t,n,o;return u(this,void 0,void 0,(function*(){const r=document.createElement("style"),i=cr(this.projectId,"theme.json");try{const{body:s}=yield lr(i,"json");r.innerText=((null===(e=null==s?void 0:s.light)||void 0===e?void 0:e.globals)||"")+((null===(t=null==s?void 0:s.dark)||void 0===t?void 0:t.globals)||"");const a=yield this.descopeUI;(null==a?void 0:a.componentsThemeManager)&&(a.componentsThemeManager.themes={light:null===(n=null==s?void 0:s.light)||void 0===n?void 0:n.components,dark:null===(o=null==s?void 0:s.dark)||void 0===o?void 0:o.components})}catch(r){this.loggerWrapper.error("Cannot fetch theme file","make sure that your projectId & flowId are correct")}this.shadowRoot.appendChild(r)}))},Xr=function(e){p(this,Pr,Object.assign(Object.assign({},e.detail),h(this,Pr,"f")),"f")},Qr=function(){return u(this,void 0,void 0,(function*(){this.rootElement.setAttribute("data-theme",this.theme);const e=yield this.descopeUI;(null==e?void 0:e.componentsThemeManager)&&(e.componentsThemeManager.currentThemeName=this.theme)}))},ei=function(){var e;null===(e=h(this,Lr,"f"))||void 0===e||e.remove(),p(this,Lr,null,"f")},ti=function({isDebug:e}){return u(this,void 0,void 0,(function*(){e?(p(this,Lr,document.createElement("descope-debugger"),"f"),Object.assign(h(this,Lr,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return Mi})),document.body.appendChild(h(this,Lr,"f"))):h(this,Ur,"m",ei).call(this)}))},ni=function(e,t){var n;e&&this.debug&&(null===(n=h(this,Lr,"f"))||void 0===n||n.updateData({title:e,description:t}))},oi=function(){this.rootElement.onkeydown=e=>{if("Enter"!==e.key)return;e.preventDefault();const t=this.rootElement.querySelectorAll("descope-button");if(1===t.length)return void t[0].click();const n=Array.from(t).filter((e=>"button"===e.getAttribute("data-type")));1===n.length&&n[0].click()}},ri=function(){var e,t;return u(this,void 0,void 0,(function*(){let n=null===(t=null===(e=yield h(this,Br,"f").call(this))||void 0===e?void 0:e.projectConfig)||void 0===t?void 0:t.componentsVersion;n||(this.logger.error("Did not get components version, using latest version"),n="latest");const o=Fo.replace("<version>",n),r=document.createElement("script");this.descopeUI=new Promise((e=>{const t=()=>{this.loggerWrapper.error("Cannot load DescopeUI",`Make sure this URL is valid and return the correct script: "${o}"`),e({})};r.onload=()=>{globalThis.DescopeUI||t(),e(globalThis.DescopeUI)},r.onerror=t,r.src=o})),document.body.append(r)}))},yi.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"3.0.0"}};class Ii extends yi{static set sdkConfigOverrides(e){yi.sdkConfigOverrides=e}constructor(){const e=new Sr;super(e.update.bind(e)),ii.add(this),this.stepState=new Sr({},{updateOnlyOnChange:!1}),si.set(this,void 0),ai.set(this,null),li.set(this,(()=>{clearInterval(h(this,si,"f")),p(this,si,null,"f")})),ci.set(this,(e=>{var t,n,o,r,i,s,a,l,c;if(!(null==e?void 0:e.ok)){h(this,li,"f").call(this),h(this,ii,"m",wi).call(this,"error",null==e?void 0:e.error);const s=null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.url,a=`${null===(n=null==e?void 0:e.response)||void 0===n?void 0:n.status} - ${null===(o=null==e?void 0:e.response)||void 0===o?void 0:o.statusText}`;return void this.loggerWrapper.error((null===(r=null==e?void 0:e.error)||void 0===r?void 0:r.errorDescription)||s,(null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.errorMessage)||a)}const d=null===(l=null===(a=null===(s=e.data)||void 0===s?void 0:s.screen)||void 0===a?void 0:a.state)||void 0===l?void 0:l.errorText;(null===(c=e.data)||void 0===c?void 0:c.error)?this.loggerWrapper.error(`[${e.data.error.code}]: ${e.data.error.description}`,`${d?`${d} - `:""}${e.data.error.message}`):d&&this.loggerWrapper.error(d);const{status:u,authInfo:p,lastAuth:f}=e.data;if("completed"===u)return function(e){(null==e?void 0:e.authMethod)&&Wo&&localStorage.setItem(Bo,JSON.stringify(e))}(f),h(this,li,"f").call(this),void h(this,ii,"m",wi).call(this,"success",p);const{executionId:g,stepId:v,stepName:m,action:b,screen:w,redirect:y,webauthn:I,error:k,samlIdpResponse:S}=e.data;b!==er?(this.loggerWrapper.info(`Step "${m||`#${v}`}" is ${u}`,"",{screen:w,status:u,stepId:v,stepName:m,action:b,error:k}),this.flowState.update({stepId:v,executionId:g,action:b,redirectTo:null==y?void 0:y.url,screenId:null==w?void 0:w.id,screenState:null==w?void 0:w.state,webauthnTransactionId:null==I?void 0:I.transactionId,webauthnOptions:null==I?void 0:I.options,samlIdpResponseUrl:null==S?void 0:S.url,samlIdpResponseSamlResponse:null==S?void 0:S.samlResponse,samlIdpResponseRelayState:null==S?void 0:S.relayState})):this.flowState.update({action:b})})),di.set(this,gr((()=>u(this,void 0,void 0,(function*(){var e;try{const t=yield this.sdk.webauthn.signIn.start("",window.location.origin);return t.ok||this.loggerWrapper.error("Webauthn start failed",null===(e=null==t?void 0:t.error)||void 0===e?void 0:e.errorMessage),t.data}catch(e){this.loggerWrapper.error("Webauthn start failed",e.message)}}))))),this.flowState=e}connectedCallback(){const e=Object.create(null,{connectedCallback:{get:()=>super.connectedCallback}});var t,n;return u(this,void 0,void 0,(function*(){this.shadowRoot.isConnected&&(null===(t=this.flowState)||void 0===t||t.subscribe(this.onFlowChange.bind(this)),null===(n=this.stepState)||void 0===n||n.subscribe(this.onStepChange.bind(this))),yield e.connectedCallback.call(this)}))}disconnectedCallback(){var e;super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll(),null===(e=h(this,ai,"f"))||void 0===e||e.abort(),p(this,ai,null,"f")}getHtmlFilenameWithLocale(e,t){return u(this,void 0,void 0,(function*(){let n,o=navigator.language;o&&"zh-TW"!==o&&(o=o.split("-")[0]);const r=(e||o||"").toLowerCase();return(yield this.getTargetLocales()).includes(r)&&(n=`${t}-${r}.html`),n}))}getPageContent(e,t){return u(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield lr(t,"text");return e}catch(n){this.loggerWrapper.error(`Failed to fetch flow page from ${t}. Fallback to url ${e}`,n)}try{const{body:t}=yield lr(e,"text");return t}catch(e){this.loggerWrapper.error("Failed to fetch flow page",e.message)}return null}))}onFlowChange(e,t,n){var o,r;return u(this,void 0,void 0,(function*(){const{projectId:i,flowId:s,tenant:a,stepId:l,executionId:c,action:d,screenId:f,screenState:g,redirectTo:v,redirectUrl:m,token:b,code:w,exchangeError:y,webauthnTransactionId:I,webauthnOptions:k,redirectAuthCodeChallenge:S,redirectAuthCallbackUrl:j,redirectAuthInitiator:x,oidcIdpStateId:C,locale:O,samlIdpStateId:E,samlIdpUsername:A,samlIdpResponseUrl:U,samlIdpResponseSamlResponse:R,samlIdpResponseRelayState:_,ssoAppId:T}=e;let P,L;h(this,si,"f")&&h(this,li,"f").call(this);const M=(()=>{const e=localStorage.getItem(Er);if(!e){const e=Math.floor(100*Math.random()+1);return localStorage.setItem(Er,e.toString()),e}return Number(e)})(),$=this.sdk.getLastUserLoginId(),q=yield this.getFlowConfig(),W=yield this.getProjectConfig(),D=j&&S?{callbackUrl:j,codeChallenge:S}:void 0;if(!c&&(q.conditions?({startScreenId:P,conditionInteractionId:L}=((e,t)=>{const n=null==t?void 0:t.find((({key:t,operator:n,predicate:o})=>{var r;if("ELSE"===t)return!0;const i=null===(r=Cr[t])||void 0===r?void 0:r[n];return!!(null==i?void 0:i(e,o))}));return n?{startScreenId:n.met.screenId,conditionInteractionId:n.met.interactionId}:{}})({loginId:$,code:w,token:b,abTestingKey:M},q.conditions)):q.condition?({startScreenId:P,conditionInteractionId:L}=((e,t)=>{var n;const o=null===(n=Cr[null==e?void 0:e.key])||void 0===n?void 0:n[e.operator];if(!o)return{};const r=o(t,e.predicate)?e.met:e.unmet;return{startScreenId:null==r?void 0:r.screenId,conditionInteractionId:null==r?void 0:r.interactionId}})(q.condition,{loginId:$,code:w,token:b,abTestingKey:M})):P=q.startScreenId,!vr(P,C,E,A,T))){const e={};let t=!1;w&&(t=!0,e.exchangeCode=w,e.idpInitiated=!0),b&&(t=!0,e.token=b);const n=yield this.sdk.flow.start(s,Object.assign(Object.assign({tenant:a,redirectAuth:D,oidcIdpStateId:C,samlIdpStateId:E,samlIdpUsername:A,ssoAppId:T},m&&{redirectUrl:m}),{lastAuth:Or($),abTestingKey:M}),L,"",q.version,W.componentsVersion,t?e:void 0);return h(this,ci,"f").call(this,n),void("completed"!==(null===(o=null==n?void 0:n.data)||void 0===o?void 0:o.status)&&this.flowState.update({code:void 0,token:void 0}))}if(c&&(n("token")&&b||n("code")&&w||n("exchangeError")&&y)){const e=yield this.sdk.flow.next(c,l,or,q.version,W.componentsVersion,{token:b,exchangeCode:w,exchangeError:y});return h(this,ci,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if("loadForm"===d&&["samlIdpResponseUrl","samlIdpResponseSamlResponse","samlIdpResponseRelayState"].some((e=>n(e)))){if(!U||!R)return void this.loggerWrapper.error("Did not get saml idp params data to load");((e,t,n,o)=>{const r=document.createElement("form");r.method="POST",r.action=e,r.innerHTML=`\n <input type="hidden" role="saml-response" name="SAMLResponse" value="${t}" />\n <input type="hidden" role="saml-relay-state" name="RelayState" value="${n}" />\n <input style="display: none;" id="SAMLSubmitButton" type="submit" value="Continue" />\n `,document.body.appendChild(r),o(r)})(U,R,_||"",mr)}if("redirect"===d&&(n("redirectTo")||n("deferredRedirect")))return v?"android"===x&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(v):void this.loggerWrapper.error("Did not get redirect url");if(d===tr||"webauthnGet"===d){if(!I||!k)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t;null===(r=h(this,ai,"f"))||void 0===r||r.abort(),p(this,ai,null,"f");try{e=d===tr?yield this.sdk.webauthn.helpers.create(k):yield this.sdk.webauthn.helpers.get(k)}catch(e){"InvalidStateError"===e.name?this.loggerWrapper.warn("WebAuthn operation failed",e.message):"NotAllowedError"!==e.name&&this.loggerWrapper.error(e.message),t=e.name}const n=yield this.sdk.flow.next(c,l,or,q.version,W.componentsVersion,{transactionId:I,response:e,failure:t});h(this,ci,"f").call(this,n)}if(d===er&&p(this,si,setInterval((()=>u(this,void 0,void 0,(function*(){const e=yield this.sdk.flow.next(c,l,rr,q.version,W.componentsVersion,{});h(this,ci,"f").call(this,e)}))),2e3),"f"),!f&&!P)return void this.loggerWrapper.warn("No screen was found to show");const F=P||f,K=yield this.getHtmlFilenameWithLocale(O,F),N={direction:dr(+l,+t.stepId),screenState:Object.assign(Object.assign({},g),{lastAuth:{loginId:$,name:this.sdk.getLastUserDisplayName()||$}}),htmlUrl:cr(i,`${F}.html`),htmlLocaleUrl:K&&cr(i,K),samlIdpUsername:A},J=Or($);vr(P,C,E,A,T)?N.next=(e,t,n,o)=>this.sdk.flow.start(s,Object.assign({tenant:a,redirectAuth:D,oidcIdpStateId:C,samlIdpStateId:E,samlIdpUsername:A,ssoAppId:T,lastAuth:J,preview:this.preview,abTestingKey:M},m&&{redirectUrl:m}),L,e,t,n,Object.assign(Object.assign(Object.assign({},o),w&&{exchangeCode:w,idpInitiated:!0}),b&&{token:b})):(n("projectId")||n("baseUrl")||n("executionId")||n("stepId"))&&(N.next=(...e)=>this.sdk.flow.next(c,l,...e)),this.stepState.update(N)}))}loadDescopeUiComponents(e){return u(this,void 0,void 0,(function*(){const t=(e=>[...Array.from(e.querySelectorAll("*")).reduce(((e,t)=>t.tagName.startsWith("DESCOPE-")?e.add(t.tagName.toLocaleLowerCase()):e),new Set)])(e);yield Promise.all(t.map((e=>u(this,void 0,void 0,(function*(){if(customElements.get(e))return;let t;try{t=yield this.descopeUI}catch(t){return}if(t[e])return t[e]();this.loggerWrapper.error(`Cannot load UI component "${e}"`,`Descope UI does not have a component named "${e}", available components are: "${Object.keys(t).join(", ")}"`)})))))}))}onStepChange(e,t){var n,o;return u(this,void 0,void 0,(function*(){const{htmlUrl:r,htmlLocaleUrl:i,direction:s,next:a,screenState:l}=e,c=document.createElement("template");c.innerHTML=yield this.getPageContent(r,i);const d=c.content.cloneNode(!0),p=this.loadDescopeUiComponents(c.content);this.sdk.webauthn.helpers.isSupported()?yield h(this,ii,"m",hi).call(this,d,a):d.querySelectorAll(`descope-button[${Qo}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true"))),!e.samlIdpUsername||(null===(n=l.form)||void 0===n?void 0:n.loginId)||(null===(o=l.form)||void 0===o?void 0:o.email)||(l.form||(l.form={}),l.form.loginId=e.samlIdpUsername,l.form.email=e.samlIdpUsername),((e,t,n,o)=>{var r;let i=null==t?void 0:t.errorText;try{i=(null==n?void 0:n({text:null==t?void 0:t.errorText,type:null==t?void 0:t.errorType}))||(null==t?void 0:t.errorText)}catch(e){o.error("Error transforming error message",e.message)}((e,t,n="")=>{e.querySelectorAll(`[${Qo}="${t}"]`).forEach((e=>{e.textContent=n,e.classList[n?"remove":"add"]("hide")}))})(e,"error-message",i),jr(e,null==t?void 0:t.inputs),jr(e,null==t?void 0:t.form),((e,t)=>{e.querySelectorAll(`[${Qo}="totp-link"]`).forEach((e=>{e.setAttribute("href",t)}))})(e,null===(r=null==t?void 0:t.totp)||void 0===r?void 0:r.provisionUrl),((e,t)=>{e.querySelectorAll("descope-text,descope-link").forEach((e=>{e.textContent=((e,t)=>e.replace(/{{(.+?)}}/g,((e,n)=>{return o=t,n.split(".").reduce(((e,t)=>(null==e?void 0:e[t])||""),o);var o})))(e.textContent,t)}))})(e,t)})(d,l,this.errorTransformer,this.loggerWrapper);const{geo:f}=yield this.getExecutionContext();((e,t)=>{Array.from(e.querySelectorAll('descope-phone-field[default-code="autoDetect"]')).forEach((e=>{e.setAttribute("default-code",t)}))})(d,f);const g=()=>u(this,void 0,void 0,(function*(){var e;yield p,((e,t)=>{var n,o;const r=null===(n=customElements.get("descope-totp-image"))||void 0===n?void 0:n.cssVarList.url;t&&r&&(null===(o=null==e?void 0:e.style)||void 0===o||o.setProperty(r,`url(data:image/jpg;base64,${t})`))})(this.shadowRoot.querySelector("div"),null===(e=null==l?void 0:l.totp)||void 0===e?void 0:e.image),this.rootElement.replaceChildren(d);const n=!t.htmlUrl;if(((e,t,n)=>{if(!0===t||"skipFirstScreen"===t&&!n){const t=e.querySelector("*[name]");setTimeout((()=>{null==t||t.focus()}))}})(this.rootElement,this.autoFocus,n),h(this,ii,"m",mi).call(this,a),h(this,ii,"m",wi).call(this,"page-updated",{}),this.rootElement.querySelector(`[${Qo}="polling"]`)){const e=yield this.getFlowConfig(),t=yield this.getProjectConfig(),n=yield a(rr,e.version,t.componentsVersion,{});h(this,ci,"f").call(this,n)}}));s?h(this,ii,"m",bi).call(this,g,s):g()}))}}si=new WeakMap,ai=new WeakMap,li=new WeakMap,ci=new WeakMap,di=new WeakMap,ii=new WeakSet,ui=function(e){const t=e.getAttribute("name");if(!["email"].includes(t)){const n=`user-${t}`;e.setAttribute("name",n),e.addEventListener("input",(()=>{e.setAttribute("name",e.value?t:n)}))}},hi=function(e,t){var n;return u(this,void 0,void 0,(function*(){null===(n=h(this,ai,"f"))||void 0===n||n.abort();const o=e.querySelector('*[autocomplete="webauthn"]');if(o&&(yield xr())){const{options:e,transactionId:n}=(yield h(this,di,"f").call(this))||{};if(e&&n){h(this,ii,"m",ui).call(this,o),p(this,ai,new AbortController,"f");const r=yield this.getFlowConfig(),i=yield this.getProjectConfig();this.sdk.webauthn.helpers.conditional(e,h(this,ai,"f")).then((e=>u(this,void 0,void 0,(function*(){const s=yield t(o.id,r.version,i.componentsVersion,{transactionId:n,response:e});h(this,ci,"f").call(this,s)})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)}))}}}))},pi=function(){return Array.from(this.shadowRoot.querySelectorAll("*[name]")).every((e=>{var t,n;return null===(t=e.reportValidity)||void 0===t||t.call(e),null===(n=e.checkValidity)||void 0===n?void 0:n.call(e)}))},fi=function(){return u(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`*[name]:not([${Vo}])`));return(yield Promise.all(e.map((e=>u(this,void 0,void 0,(function*(){return{name:e.getAttribute("name"),value:e.value}})))))).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},gi=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:n})=>{n?e.setAttribute("loading","true"):(this.nextRequestStatus.unsubscribe(t),e.removeAttribute("loading"))}))},vi=function(e,t){return u(this,void 0,void 0,(function*(){if("true"===e.getAttribute("formnovalidate")||h(this,ii,"m",pi).call(this)){const o=null==e?void 0:e.getAttribute("id");h(this,ii,"m",gi).call(this,e);const r=yield h(this,ii,"m",fi).call(this),i=(n=e,Array.from((null==n?void 0:n.attributes)||[]).reduce(((e,t)=>{var n;const o=null===(n=new RegExp("^data-descope-(\\S+)$").exec(t.name))||void 0===n?void 0:n[1];return o?Object.assign(e,{[o]:t.value}):e}),{})),s=this.getComponentsContext(),a=Object.assign(Object.assign(Object.assign(Object.assign({},s),i),r),{origin:window.location.origin}),l=yield this.getFlowConfig(),c=yield this.getProjectConfig(),d=yield t(o,l.version,c.componentsVersion,a);h(this,ci,"f").call(this,d)}var n}))},mi=function(e){this.rootElement.querySelectorAll("descope-button:not([data-exclude-next])").forEach((t=>{t.onclick=()=>{h(this,ii,"m",vi).call(this,t,e)}}))},bi=function(e,t){this.rootElement.addEventListener("transitionend",(()=>{this.rootElement.classList.remove("fade-out"),e()}),{once:!0});const n=t===ir.forward?"slide-forward":"slide-backward";Array.from(this.rootElement.getElementsByClassName("input-container")).forEach(((e,t)=>{e.style["transition-delay"]=40*t+"ms",e.classList.add(n)})),this.rootElement.classList.add("fade-out")},wi=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},customElements.define("descope-wc",Ii);var ki=Object.freeze({__proto__:null,default:Ii});const Si=(e,t,n,o={})=>{var r,i,s,a;return[Math.min(Math.max(t,("all"===o.left?e.offsetWidth:null!==(r=o.left)&&void 0!==r?r:0)-e.offsetWidth),window.innerWidth-("all"===o.right?e.offsetWidth:null!==(i=o.right)&&void 0!==i?i:0)),Math.min(Math.max(n,("all"===o.top?e.offsetHeight:null!==(s=o.top)&&void 0!==s?s:0)-e.offsetHeight),window.innerHeight-("all"===o.bottom?e.offsetHeight:null!==(a=o.bottom)&&void 0!==a?a:0))]};var ji,xi,Ci,Oi,Ei,Ai,Ui,Ri,_i,Ti;const Pi=document.createElement("template");Pi.innerHTML=`\n<style>\n .debugger {\n width: 300px;\n height: 200px;\n background-color: #FAFAFA;\n position: fixed;\n font-family: "Helvetica Neue", sans-serif;\n box-shadow: rgba(0, 0, 0, 0.1) 0px 5px 10px;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid lightgrey;\n pointer-events: initial;\n display: flex;\n flex-direction: column;\n min-width: 200px;\n max-width: 600px;\n max-height: calc(100% - 64px);\n min-height: 200px;\n resize: both;\n }\n\n .header {\n padding: 8px 16px;\n display: flex;\n align-items: center;\n background-color: #EEEEEE;\n cursor: move;\n border-bottom: 1px solid #e0e0e0;\n }\n\n .content {\n font-size: 14px;\n flex-grow: 1;\n overflow: auto;\n }\n\n .msg {\n border-bottom: 1px solid lightgrey;\n padding: 8px 16px;\n display: flex;\n gap: 5px;\n background-color: #FAFAFA;\n }\n\n .msg.collapsible {\n cursor: pointer;\n }\n\n .empty-state {\n padding: 8px 16px;\n background-color: #FAFAFA;\n }\n\n\n .msg.collapsible:not(.collapsed) {\n background-color: #F5F5F5;\n }\n\n .msg_title {\n padding-bottom: 5px;\n display: flex;\n gap: 8px;\n font-weight: 500;\n }\n\n .msg svg {\n padding: 1px;\n flex-shrink: 0;\n margin-top: -2px;\n }\n\n .msg_content {\n overflow: hidden;\n flex-grow: 1;\n margin-right:5px;\n }\n\n .msg_desc {\n color: #646464;\n cursor: initial;\n word-wrap: break-word;\n }\n\n .msg.collapsed .msg_desc {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .msg.collapsible.collapsed .chevron {\n transform: rotate(-45deg) translateX(-2px);\n }\n\n .msg.collapsible .chevron {\n content: "";\n width:6px;\n height:6px;\n border-bottom: 2px solid grey;\n border-right: 2px solid grey;\n transform: rotate(45deg) translateX(-1px);\n margin: 5px;\n flex-shrink:0;\n }\n</style>\n\n<div style="top:32px; left:${window.innerWidth-300-32}px;" class="debugger">\n <div class="header">\n <span>Debugger messages</span>\n </div>\n <div class="content">\n <div class="empty-state">\n No errors detected 👀\n </div>\n </div>\n</div>\n`;class Li extends HTMLElement{constructor(){super(),ji.add(this),xi.set(this,new Sr({messages:[]})),Ci.set(this,void 0),Oi.set(this,void 0),Ei.set(this,void 0),Ai.set(this,{resize:h(this,ji,"m",Ti).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Pi.content.cloneNode(!0)),p(this,Ci,this.shadowRoot.querySelector(".debugger"),"f"),p(this,Oi,h(this,Ci,"f").querySelector(".content"),"f"),p(this,Ei,h(this,Ci,"f").querySelector(".header"),"f")}updateData(e){h(this,xi,"f").update((t=>({messages:t.messages.concat(e)})))}connectedCallback(){var e;((e,t,n)=>{let o=0,r=0,i=0,s=0;function a(t){t.preventDefault(),o=i-t.clientX,r=s-t.clientY,i=t.clientX,s=t.clientY;const[a,l]=Si(e,e.offsetLeft-o,e.offsetTop-r,n);e.style.top=`${l}px`,e.style.left=`${a}px`}function l(){document.onmouseup=null,document.onmousemove=null}function c(e){e.preventDefault(),i=e.clientX,s=e.clientY,document.onmouseup=l,document.onmousemove=a}t?t.onmousedown=c:e.onmousedown=c})(h(this,Ci,"f"),h(this,Ei,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",h(this,Ai,"f").resize),(e=h(this,Ci,"f")).onmousemove=t=>{(t.target.w&&t.target.w!==t.target.offsetWidth||t.target.h&&t.target.h!==t.target.offsetHeight)&&e.onresize(t),t.target.w=t.target.offsetWidth,t.target.h=t.target.offsetHeight},h(this,Ci,"f").onresize=h(this,ji,"m",_i).bind(this),h(this,xi,"f").subscribe(h(this,ji,"m",Ui).bind(this))}disconnectedCallback(){h(this,xi,"f").unsubscribeAll(),window.removeEventListener("resize",h(this,Ai,"f").resize)}}xi=new WeakMap,Ci=new WeakMap,Oi=new WeakMap,Ei=new WeakMap,Ai=new WeakMap,ji=new WeakSet,Ui=function(e){h(this,ji,"m",Ri).call(this,e),h(this,ji,"m",_i).call(this)},Ri=function(e){h(this,Oi,"f").innerHTML=e.messages.map((e=>`\n <div class="msg">\n <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path d="M5.99984 13.167L8.99984 10.167L11.9998 13.167L13.1665 12.0003L10.1665 9.00033L13.1665 6.00033L11.9998 4.83366L8.99984 7.83366L5.99984 4.83366L4.83317 6.00033L7.83317 9.00033L4.83317 12.0003L5.99984 13.167ZM8.99984 17.3337C7.84706 17.3337 6.76373 17.1148 5.74984 16.677C4.73595 16.2398 3.854 15.6462 3.104 14.8962C2.354 14.1462 1.76039 13.2642 1.32317 12.2503C0.885393 11.2364 0.666504 10.1531 0.666504 9.00033C0.666504 7.84755 0.885393 6.76421 1.32317 5.75033C1.76039 4.73644 2.354 3.85449 3.104 3.10449C3.854 2.35449 4.73595 1.7606 5.74984 1.32283C6.76373 0.885603 7.84706 0.666992 8.99984 0.666992C10.1526 0.666992 11.2359 0.885603 12.2498 1.32283C13.2637 1.7606 14.1457 2.35449 14.8957 3.10449C15.6457 3.85449 16.2393 4.73644 16.6765 5.75033C17.1143 6.76421 17.3332 7.84755 17.3332 9.00033C17.3332 10.1531 17.1143 11.2364 16.6765 12.2503C16.2393 13.2642 15.6457 14.1462 14.8957 14.8962C14.1457 15.6462 13.2637 16.2398 12.2498 16.677C11.2359 17.1148 10.1526 17.3337 8.99984 17.3337ZM8.99984 15.667C10.8609 15.667 12.4373 15.0212 13.729 13.7295C15.0207 12.4378 15.6665 10.8614 15.6665 9.00033C15.6665 7.13921 15.0207 5.56283 13.729 4.27116C12.4373 2.97949 10.8609 2.33366 8.99984 2.33366C7.13873 2.33366 5.56234 2.97949 4.27067 4.27116C2.979 5.56283 2.33317 7.13921 2.33317 9.00033C2.33317 10.8614 2.979 12.4378 4.27067 13.7295C5.56234 15.0212 7.13873 15.667 8.99984 15.667Z" fill="#ED404A"/>\n</svg>\n\n <div class="msg_content">\n <div class="msg_title">\n ${e.title}\n </div>\n <div class="msg_desc">\n ${e.description}\n </div>\n </div>\n <div class="chevron"></div>\n </div>\n `)).join("")},_i=function(){h(this,Oi,"f").querySelectorAll(".msg").forEach((e=>{const t=e.querySelector(".msg_desc"),n=t.scrollWidth>t.clientWidth,o=t.clientHeight>20;n||o?(e.classList.add("collapsible"),e.onclick=t=>{t.target.classList.contains("msg_desc")||e.classList.toggle("collapsed")}):(e.classList.remove("collapsible"),e.onclick=null)}))},Ti=function(){const[e,t]=Si(h(this,Ci,"f"),Number.parseInt(h(this,Ci,"f").style.left,10),Number.parseInt(h(this,Ci,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});h(this,Ci,"f").style.top=`${t}px`,h(this,Ci,"f").style.left=`${e}px`},customElements.define("descope-debugger",Li);var Mi=Object.freeze({__proto__:null,default:Li});e.AuthProvider=({projectId:e,baseUrl:n="",sessionTokenViaCookie:s=!1,children:l})=>{const[c,d]=t.useState(),[u,h]=t.useState(),[p,f]=t.useState(!1),[g,v]=t.useState(!1),m=(({projectId:e,baseUrl:n,sessionTokenViaCookie:o})=>t.useMemo((()=>{if(e)return Ao({projectId:e,baseUrl:n,sessionTokenViaCookie:o,baseHeaders:a,persistToken:!0,autoRefresh:!0})}),[e,n,o]))({projectId:e,baseUrl:n,sessionTokenViaCookie:s});t.useEffect((()=>{if(m){const e=m.onSessionTokenChange(h),t=m.onUserChange(d);return()=>{e(),t()}}}),[m]);const b=t.useRef(!1),w=t.useCallback((()=>{b.current||(b.current=!0,v(!0),i(m?.refresh)().then((()=>{v(!1)})))}),[m]),y=t.useCallback((()=>{f(!0),i(m.me)().then((()=>{f(!1)}))}),[m]),I=t.useMemo((()=>({fetchUser:y,user:c,isUserLoading:p,fetchSession:w,session:u,isSessionLoading:g,isSessionFetched:b.current,projectId:e,baseUrl:n,setUser:d,setSession:h,sdk:m})),[y,c,p,w,u,g,b.current,e,n,d,h,m]);return o.default.createElement(r.Provider,{value:I},l)},e.Descope=Lo,e.SignInFlow=e=>o.default.createElement(Lo,{...e,flowId:"sign-in"}),e.SignUpFlow=e=>o.default.createElement(Lo,{...e,flowId:"sign-up"}),e.SignUpOrInFlow=e=>o.default.createElement(Lo,{...e,flowId:"sign-up-or-in"}),e.getJwtPermissions=_o,e.getJwtRoles=To,e.getRefreshToken=Ro,e.getSessionToken=Uo,e.refresh=(e=Ro())=>Eo?.refresh(e),e.useDescope=()=>{const{sdk:e}=Mo();return t.useMemo((()=>e||new Proxy(Ao({projectId:"dummy"}),qo)),[e])},e.useSession=()=>{const{session:e,isSessionLoading:n,fetchSession:o,isSessionFetched:r}=Mo(),i=t.useRef(n);return t.useMemo((()=>{i.current=n}),[n]),t.useMemo((()=>{r||(i.current=!0)}),[r]),t.useEffect((()=>{e||n||o()}),[o]),{isSessionLoading:i.current,sessionToken:e,isAuthenticated:!!e}},e.useUser=()=>{const{user:e,fetchUser:n,isUserLoading:o,session:r}=Mo(),[i,s]=t.useState(!1),a=t.useRef(o),l=t.useMemo((()=>!e&&!o&&r&&!i),[n,r,i]);return t.useMemo((()=>{a.current=o}),[o]),t.useMemo((()=>{l&&(a.current=!0)}),[l]),t.useEffect((()=>{l&&(s(!0),n())}),[l]),{isUserLoading:a.current,user:e}},Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
3
3
|
//# sourceMappingURL=index.umd.js.map
|