@descope/react-sdk 1.0.11 → 1.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@descope/web-js-sdk");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var o=r(e),n=r(t);const u=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)},c=e=>(...t)=>{let r;try{r=e(...t)}catch(e){console.error(e)}return r},a={"x-descope-sdk-name":"react","x-descope-sdk-version":"1.0.11"},l="undefined"!=typeof window;let d;const f=e=>{const t=n.default({...e,persistTokens:l,autoRefresh:l});return d=t,t};d=f({projectId:"temp pid"});const p=()=>l?d?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),h=()=>l?d?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),m=c(((e=p(),t)=>d?.getJwtPermissions(e,t))),g=c(((e=p(),t)=>d?.getJwtRoles(e,t)));const k=e.lazy((async()=>((await Promise.resolve().then((function(){return s(require("@descope/web-component"))}))).default.sdkConfigOverrides={baseHeaders:a},{default:({projectId:e,flowId:t,baseUrl:r,innerRef:s,tenant:n,theme:u,locale:i,debug:c,telemetryKey:a,redirectUrl:l,autoFocus:d})=>o.default.createElement("descope-wc",{"project-id":e,"flow-id":t,"base-url":r,ref:s,tenant:n,theme:u,locale:i,debug:c,telemetryKey:a,"redirect-url":l,"auto-focus":d})}))),w=o.default.forwardRef((({flowId:t,onSuccess:r,onError:s,logger:n,tenant:i,theme:c,locale:a,debug:l,telemetryKey:d,redirectUrl:f,autoFocus:p,errorTransformer:h},m)=>{const[g,w]=e.useState(null);e.useImperativeHandle(m,(()=>g));const{projectId:b,baseUrl:y,sdk:S}=o.default.useContext(u),E=e.useCallback((async e=>{await S.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),r&&r(e)}),[r]);return e.useEffect((()=>{const e=g;return e?.addEventListener("success",E),s&&e?.addEventListener("error",s),()=>{s&&e?.removeEventListener("error",s),e?.removeEventListener("success",E)}}),[g,s,E]),e.useEffect((()=>{g&&(g.errorTransformer=h)}),[g,h]),e.useEffect((()=>{g&&n&&(g.logger=n)}),[g,n]),o.default.createElement("form",null,o.default.createElement(e.Suspense,{fallback:null},o.default.createElement(k,{projectId:b,flowId:t,baseUrl:y,innerRef:w,tenant:i,theme:c,locale:a,debug:l,telemetryKey:d,redirectUrl:f,autoFocus:p})))}));var b=()=>{const t=e.useContext(u);if(!t)throw Error("You can only use this hook in the context of <AuthProvider />");return t};const y=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,S={get(e,t){if("object"==typeof e[t]&&null!==e[t])return new Proxy(e[t],S);if("function"==typeof e[t])return()=>{throw Error(y("function"))};throw Error(y("attribute"))}};exports.AuthProvider=({projectId:t,baseUrl:r="",sessionTokenViaCookie:s=!1,children:n})=>{const[c,l]=e.useState(),[d,p]=e.useState(),[h,m]=e.useState(!1),[g,k]=e.useState(!1),w=(({projectId:t,baseUrl:r,sessionTokenViaCookie:s})=>e.useMemo((()=>{if(t)return f({projectId:t,baseUrl:r,sessionTokenViaCookie:s,baseHeaders:a,persistToken:!0,autoRefresh:!0})}),[t,r,s]))({projectId:t,baseUrl:r,sessionTokenViaCookie:s});e.useEffect((()=>{if(w){const e=w.onSessionTokenChange(p),t=w.onUserChange(l);return()=>{e(),t()}}}),[w]);const b=e.useRef(!1),y=e.useCallback((()=>{b.current||(b.current=!0,k(!0),i(w?.refresh)().then((()=>{k(!1)})))}),[w]),S=e.useCallback((()=>{m(!0),i(w.me)().then((()=>{m(!1)}))}),[w]),E=e.useMemo((()=>({fetchUser:S,user:c,isUserLoading:h,fetchSession:y,session:d,isSessionLoading:g,isSessionFetched:b.current,projectId:t,baseUrl:r,setUser:l,setSession:p,sdk:w})),[S,c,h,y,d,g,b.current,t,r,l,p,w]);return o.default.createElement(u.Provider,{value:E},n)},exports.Descope=w,exports.SignInFlow=e=>o.default.createElement(w,{...e,flowId:"sign-in"}),exports.SignUpFlow=e=>o.default.createElement(w,{...e,flowId:"sign-up"}),exports.SignUpOrInFlow=e=>o.default.createElement(w,{...e,flowId:"sign-up-or-in"}),exports.getJwtPermissions=m,exports.getJwtRoles=g,exports.getRefreshToken=h,exports.getSessionToken=p,exports.refresh=(e=h())=>d?.refresh(e),exports.useDescope=()=>{const{sdk:t}=b();return e.useMemo((()=>t||new Proxy(f({projectId:"dummy"}),S)),[t])},exports.useSession=()=>{const{session:t,isSessionLoading:r,fetchSession:s,isSessionFetched:o}=b(),n=e.useRef(r);return e.useMemo((()=>{n.current=r}),[r]),e.useMemo((()=>{o||(n.current=!0)}),[o]),e.useEffect((()=>{t||r||s()}),[s]),{isSessionLoading:n.current,sessionToken:t,isAuthenticated:!!t}},exports.useUser=()=>{const{user:t,fetchUser:r,isUserLoading:s,session:o}=b(),[n,u]=e.useState(!1),i=e.useRef(s),c=e.useMemo((()=>!t&&!s&&o&&!n),[r,o,n]);return e.useMemo((()=>{i.current=s}),[s]),e.useMemo((()=>{c&&(i.current=!0)}),[c]),e.useEffect((()=>{c&&(u(!0),r())}),[c]),{isUserLoading:i.current,user:t}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@descope/web-js-sdk");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var o=r(e),n=r(t);const u=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)},c=e=>(...t)=>{let r;try{r=e(...t)}catch(e){console.error(e)}return r},a={"x-descope-sdk-name":"react","x-descope-sdk-version":"1.0.12"},l="undefined"!=typeof window;let d;const f=e=>{const t=n.default({...e,persistTokens:l,autoRefresh:l});return d=t,t};d=f({projectId:"temp pid"});const p=()=>l?d?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),h=()=>l?d?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),m=c(((e=p(),t)=>d?.getJwtPermissions(e,t))),g=c(((e=p(),t)=>d?.getJwtRoles(e,t)));const k=e.lazy((async()=>((await Promise.resolve().then((function(){return s(require("@descope/web-component"))}))).default.sdkConfigOverrides={baseHeaders:a},{default:({projectId:e,flowId:t,baseUrl:r,innerRef:s,tenant:n,theme:u,locale:i,debug:c,telemetryKey:a,redirectUrl:l,autoFocus:d})=>o.default.createElement("descope-wc",{"project-id":e,"flow-id":t,"base-url":r,ref:s,tenant:n,theme:u,locale:i,debug:c,telemetryKey:a,"redirect-url":l,"auto-focus":d})}))),w=o.default.forwardRef((({flowId:t,onSuccess:r,onError:s,logger:n,tenant:i,theme:c,locale:a,debug:l,telemetryKey:d,redirectUrl:f,autoFocus:p,errorTransformer:h},m)=>{const[g,w]=e.useState(null);e.useImperativeHandle(m,(()=>g));const{projectId:b,baseUrl:y,sdk:S}=o.default.useContext(u),E=e.useCallback((async e=>{await S.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),r&&r(e)}),[r]);return e.useEffect((()=>{const e=g;return e?.addEventListener("success",E),s&&e?.addEventListener("error",s),()=>{s&&e?.removeEventListener("error",s),e?.removeEventListener("success",E)}}),[g,s,E]),e.useEffect((()=>{g&&(g.errorTransformer=h)}),[g,h]),e.useEffect((()=>{g&&n&&(g.logger=n)}),[g,n]),o.default.createElement("form",null,o.default.createElement(e.Suspense,{fallback:null},o.default.createElement(k,{projectId:b,flowId:t,baseUrl:y,innerRef:w,tenant:i,theme:c,locale:a,debug:l,telemetryKey:d,redirectUrl:f,autoFocus:p})))}));var b=()=>{const t=e.useContext(u);if(!t)throw Error("You can only use this hook in the context of <AuthProvider />");return t};const y=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,S={get(e,t){if("object"==typeof e[t]&&null!==e[t])return new Proxy(e[t],S);if("function"==typeof e[t])return()=>{throw Error(y("function"))};throw Error(y("attribute"))}};exports.AuthProvider=({projectId:t,baseUrl:r="",sessionTokenViaCookie:s=!1,children:n})=>{const[c,l]=e.useState(),[d,p]=e.useState(),[h,m]=e.useState(!1),[g,k]=e.useState(!1),w=(({projectId:t,baseUrl:r,sessionTokenViaCookie:s})=>e.useMemo((()=>{if(t)return f({projectId:t,baseUrl:r,sessionTokenViaCookie:s,baseHeaders:a,persistToken:!0,autoRefresh:!0})}),[t,r,s]))({projectId:t,baseUrl:r,sessionTokenViaCookie:s});e.useEffect((()=>{if(w){const e=w.onSessionTokenChange(p),t=w.onUserChange(l);return()=>{e(),t()}}}),[w]);const b=e.useRef(!1),y=e.useCallback((()=>{b.current||(b.current=!0,k(!0),i(w?.refresh)().then((()=>{k(!1)})))}),[w]),S=e.useCallback((()=>{m(!0),i(w.me)().then((()=>{m(!1)}))}),[w]),E=e.useMemo((()=>({fetchUser:S,user:c,isUserLoading:h,fetchSession:y,session:d,isSessionLoading:g,isSessionFetched:b.current,projectId:t,baseUrl:r,setUser:l,setSession:p,sdk:w})),[S,c,h,y,d,g,b.current,t,r,l,p,w]);return o.default.createElement(u.Provider,{value:E},n)},exports.Descope=w,exports.SignInFlow=e=>o.default.createElement(w,{...e,flowId:"sign-in"}),exports.SignUpFlow=e=>o.default.createElement(w,{...e,flowId:"sign-up"}),exports.SignUpOrInFlow=e=>o.default.createElement(w,{...e,flowId:"sign-up-or-in"}),exports.getJwtPermissions=m,exports.getJwtRoles=g,exports.getRefreshToken=h,exports.getSessionToken=p,exports.refresh=(e=h())=>d?.refresh(e),exports.useDescope=()=>{const{sdk:t}=b();return e.useMemo((()=>t||new Proxy(f({projectId:"dummy"}),S)),[t])},exports.useSession=()=>{const{session:t,isSessionLoading:r,fetchSession:s,isSessionFetched:o}=b(),n=e.useRef(r);return e.useMemo((()=>{n.current=r}),[r]),e.useMemo((()=>{o||(n.current=!0)}),[o]),e.useEffect((()=>{t||r||s()}),[s]),{isSessionLoading:n.current,sessionToken:t,isAuthenticated:!!t}},exports.useUser=()=>{const{user:t,fetchUser:r,isUserLoading:s,session:o}=b(),[n,u]=e.useState(!1),i=e.useRef(s),c=e.useMemo((()=>!t&&!s&&o&&!n),[r,o,n]);return e.useMemo((()=>{i.current=s}),[s]),e.useMemo((()=>{c&&(i.current=!0)}),[c]),e.useEffect((()=>{c&&(u(!0),r())}),[c]),{isUserLoading:i.current,user:t}};
2
2
  //# sourceMappingURL=index.cjs.js.map
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import e,{useMemo as r,useState as t,useEffect as o,useRef as n,useCallback as s,lazy as i,useImperativeHandle as c,Suspense as a,useContext as u}from"react";import d from"@descope/web-js-sdk";const l=e.createContext(void 0),f=e=>(...r)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...r)},p=e=>(...r)=>{let t;try{t=e(...r)}catch(e){console.error(e)}return t},h={"x-descope-sdk-name":"react","x-descope-sdk-version":"1.0.11"},m="undefined"!=typeof window;let k;const g=e=>{const r=d({...e,persistTokens:m,autoRefresh:m});return k=r,r};k=g({projectId:"temp pid"});const w=()=>m?k?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),y=()=>m?k?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),b=p(((e=w(),r)=>k?.getJwtPermissions(e,r))),I=p(((e=w(),r)=>k?.getJwtRoles(e,r))),U=(e=y())=>k?.refresh(e);const E=({projectId:i,baseUrl:c="",sessionTokenViaCookie:a=!1,children:u})=>{const[d,p]=t(),[m,k]=t(),[w,y]=t(!1),[b,I]=t(!1),U=(({projectId:e,baseUrl:t,sessionTokenViaCookie:o})=>r((()=>{if(e)return g({projectId:e,baseUrl:t,sessionTokenViaCookie:o,baseHeaders:h,persistToken:!0,autoRefresh:!0})}),[e,t,o]))({projectId:i,baseUrl:c,sessionTokenViaCookie:a});o((()=>{if(U){const e=U.onSessionTokenChange(k),r=U.onUserChange(p);return()=>{e(),r()}}}),[U]);const E=n(!1),S=s((()=>{E.current||(E.current=!0,I(!0),f(U?.refresh)().then((()=>{I(!1)})))}),[U]),j=s((()=>{y(!0),f(U.me)().then((()=>{y(!1)}))}),[U]),v=r((()=>({fetchUser:j,user:d,isUserLoading:w,fetchSession:S,session:m,isSessionLoading:b,isSessionFetched:E.current,projectId:i,baseUrl:c,setUser:p,setSession:k,sdk:U})),[j,d,w,S,m,b,E.current,i,c,p,k,U]);return e.createElement(l.Provider,{value:v},u)},S=i((async()=>((await import("@descope/web-component")).default.sdkConfigOverrides={baseHeaders:h},{default:({projectId:r,flowId:t,baseUrl:o,innerRef:n,tenant:s,theme:i,locale:c,debug:a,telemetryKey:u,redirectUrl:d,autoFocus:l})=>e.createElement("descope-wc",{"project-id":r,"flow-id":t,"base-url":o,ref:n,tenant:s,theme:i,locale:c,debug:a,telemetryKey:u,"redirect-url":d,"auto-focus":l})}))),j=e.forwardRef((({flowId:r,onSuccess:n,onError:i,logger:u,tenant:d,theme:f,locale:p,debug:h,telemetryKey:m,redirectUrl:k,autoFocus:g,errorTransformer:w},y)=>{const[b,I]=t(null);c(y,(()=>b));const{projectId:U,baseUrl:E,sdk:j}=e.useContext(l),v=s((async e=>{await j.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),n&&n(e)}),[n]);return o((()=>{const e=b;return e?.addEventListener("success",v),i&&e?.addEventListener("error",i),()=>{i&&e?.removeEventListener("error",i),e?.removeEventListener("success",v)}}),[b,i,v]),o((()=>{b&&(b.errorTransformer=w)}),[b,w]),o((()=>{b&&u&&(b.logger=u)}),[b,u]),e.createElement("form",null,e.createElement(a,{fallback:null},e.createElement(S,{projectId:U,flowId:r,baseUrl:E,innerRef:I,tenant:d,theme:f,locale:p,debug:h,telemetryKey:m,redirectUrl:k,autoFocus:g})))})),v=r=>e.createElement(j,{...r,flowId:"sign-in"}),T=r=>e.createElement(j,{...r,flowId:"sign-up"}),C=r=>e.createElement(j,{...r,flowId:"sign-up-or-in"});var R=()=>{const e=u(l);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const L=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,x={get(e,r){if("object"==typeof e[r]&&null!==e[r])return new Proxy(e[r],x);if("function"==typeof e[r])return()=>{throw Error(L("function"))};throw Error(L("attribute"))}},P=()=>{const{sdk:e}=R();return r((()=>e||new Proxy(g({projectId:"dummy"}),x)),[e])},F=()=>{const{session:e,isSessionLoading:t,fetchSession:s,isSessionFetched:i}=R(),c=n(t);return r((()=>{c.current=t}),[t]),r((()=>{i||(c.current=!0)}),[i]),o((()=>{e||t||s()}),[s]),{isSessionLoading:c.current,sessionToken:e,isAuthenticated:!!e}},A=()=>{const{user:e,fetchUser:s,isUserLoading:i,session:c}=R(),[a,u]=t(!1),d=n(i),l=r((()=>!e&&!i&&c&&!a),[s,c,a]);return r((()=>{d.current=i}),[i]),r((()=>{l&&(d.current=!0)}),[l]),o((()=>{l&&(u(!0),s())}),[l]),{isUserLoading:d.current,user:e}};export{E as AuthProvider,j as Descope,v as SignInFlow,T as SignUpFlow,C as SignUpOrInFlow,b as getJwtPermissions,I as getJwtRoles,y as getRefreshToken,w as getSessionToken,U as refresh,P as useDescope,F as useSession,A as useUser};
1
+ import e,{useMemo as r,useState as t,useEffect as o,useRef as n,useCallback as s,lazy as i,useImperativeHandle as c,Suspense as a,useContext as u}from"react";import d from"@descope/web-js-sdk";const l=e.createContext(void 0),f=e=>(...r)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...r)},p=e=>(...r)=>{let t;try{t=e(...r)}catch(e){console.error(e)}return t},h={"x-descope-sdk-name":"react","x-descope-sdk-version":"1.0.12"},m="undefined"!=typeof window;let k;const g=e=>{const r=d({...e,persistTokens:m,autoRefresh:m});return k=r,r};k=g({projectId:"temp pid"});const w=()=>m?k?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),y=()=>m?k?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),b=p(((e=w(),r)=>k?.getJwtPermissions(e,r))),I=p(((e=w(),r)=>k?.getJwtRoles(e,r))),U=(e=y())=>k?.refresh(e);const E=({projectId:i,baseUrl:c="",sessionTokenViaCookie:a=!1,children:u})=>{const[d,p]=t(),[m,k]=t(),[w,y]=t(!1),[b,I]=t(!1),U=(({projectId:e,baseUrl:t,sessionTokenViaCookie:o})=>r((()=>{if(e)return g({projectId:e,baseUrl:t,sessionTokenViaCookie:o,baseHeaders:h,persistToken:!0,autoRefresh:!0})}),[e,t,o]))({projectId:i,baseUrl:c,sessionTokenViaCookie:a});o((()=>{if(U){const e=U.onSessionTokenChange(k),r=U.onUserChange(p);return()=>{e(),r()}}}),[U]);const E=n(!1),S=s((()=>{E.current||(E.current=!0,I(!0),f(U?.refresh)().then((()=>{I(!1)})))}),[U]),j=s((()=>{y(!0),f(U.me)().then((()=>{y(!1)}))}),[U]),v=r((()=>({fetchUser:j,user:d,isUserLoading:w,fetchSession:S,session:m,isSessionLoading:b,isSessionFetched:E.current,projectId:i,baseUrl:c,setUser:p,setSession:k,sdk:U})),[j,d,w,S,m,b,E.current,i,c,p,k,U]);return e.createElement(l.Provider,{value:v},u)},S=i((async()=>((await import("@descope/web-component")).default.sdkConfigOverrides={baseHeaders:h},{default:({projectId:r,flowId:t,baseUrl:o,innerRef:n,tenant:s,theme:i,locale:c,debug:a,telemetryKey:u,redirectUrl:d,autoFocus:l})=>e.createElement("descope-wc",{"project-id":r,"flow-id":t,"base-url":o,ref:n,tenant:s,theme:i,locale:c,debug:a,telemetryKey:u,"redirect-url":d,"auto-focus":l})}))),j=e.forwardRef((({flowId:r,onSuccess:n,onError:i,logger:u,tenant:d,theme:f,locale:p,debug:h,telemetryKey:m,redirectUrl:k,autoFocus:g,errorTransformer:w},y)=>{const[b,I]=t(null);c(y,(()=>b));const{projectId:U,baseUrl:E,sdk:j}=e.useContext(l),v=s((async e=>{await j.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),n&&n(e)}),[n]);return o((()=>{const e=b;return e?.addEventListener("success",v),i&&e?.addEventListener("error",i),()=>{i&&e?.removeEventListener("error",i),e?.removeEventListener("success",v)}}),[b,i,v]),o((()=>{b&&(b.errorTransformer=w)}),[b,w]),o((()=>{b&&u&&(b.logger=u)}),[b,u]),e.createElement("form",null,e.createElement(a,{fallback:null},e.createElement(S,{projectId:U,flowId:r,baseUrl:E,innerRef:I,tenant:d,theme:f,locale:p,debug:h,telemetryKey:m,redirectUrl:k,autoFocus:g})))})),v=r=>e.createElement(j,{...r,flowId:"sign-in"}),T=r=>e.createElement(j,{...r,flowId:"sign-up"}),C=r=>e.createElement(j,{...r,flowId:"sign-up-or-in"});var R=()=>{const e=u(l);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const L=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,x={get(e,r){if("object"==typeof e[r]&&null!==e[r])return new Proxy(e[r],x);if("function"==typeof e[r])return()=>{throw Error(L("function"))};throw Error(L("attribute"))}},P=()=>{const{sdk:e}=R();return r((()=>e||new Proxy(g({projectId:"dummy"}),x)),[e])},F=()=>{const{session:e,isSessionLoading:t,fetchSession:s,isSessionFetched:i}=R(),c=n(t);return r((()=>{c.current=t}),[t]),r((()=>{i||(c.current=!0)}),[i]),o((()=>{e||t||s()}),[s]),{isSessionLoading:c.current,sessionToken:e,isAuthenticated:!!e}},A=()=>{const{user:e,fetchUser:s,isUserLoading:i,session:c}=R(),[a,u]=t(!1),d=n(i),l=r((()=>!e&&!i&&c&&!a),[s,c,a]);return r((()=>{d.current=i}),[i]),r((()=>{l&&(d.current=!0)}),[l]),o((()=>{l&&(u(!0),s())}),[l]),{isUserLoading:d.current,user:e}};export{E as AuthProvider,j as Descope,v as SignInFlow,T as SignUpFlow,C as SignUpOrInFlow,b as getJwtPermissions,I as getJwtRoles,y as getRefreshToken,w as getSessionToken,U as refresh,P as useDescope,F as useSession,A as useUser};
2
2
  //# sourceMappingURL=index.esm.js.map
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 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":"1.0.11"},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__",k="[object Function]",I="[object GeneratorFunction]",x=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,S=/^\w*$/,j=/^\./,O=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,C=/\\(\\)?/g,E=/^\[object .+?Constructor\]$/,A="object"==typeof b&&b&&b.Object===Object&&b,U="object"==typeof self&&self&&self.Object===Object&&self,_=A||U||Function("return this")();var R,P=Array.prototype,T=Function.prototype,L=Object.prototype,M=_["__core-js_shared__"],$=(R=/[^.]+$/.exec(M&&M.keys&&M.keys.IE_PROTO||""))?"Symbol(src)_1."+R:"",q=T.toString,W=L.hasOwnProperty,D=L.toString,F=RegExp("^"+q.call(W).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),N=_.Symbol,K=P.splice,J=te(_,"Map"),H=te(Object,"create"),z=N?N.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 S.test(e)||!x.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==k||t==I}(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():K.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 j.test(e)&&n.push(""),e.replace(O,(function(e,t,o,r){n.push(o?r.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 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",ke="/v1/auth/enchantedlink/signin",Ie="/v1/auth/enchantedlink/signup",xe="/v1/auth/enchantedlink/pending-session",Se={email:"/v1/auth/enchantedlink/update/email"},je="/v1/auth/enchantedlink/signup-in",Oe="/v1/auth/oauth/authorize",Ce="/v1/auth/oauth/exchange",Ee="/v1/auth/saml/authorize",Ae="/v1/auth/saml/exchange",Ue="/v1/auth/totp/verify",_e="/v1/auth/totp/signup",Re="/v1/auth/totp/update",Pe={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},Te={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",Ne="/v1/auth/password/policy",Ke="/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":"1.7.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"),kt=(It=[wt(),yt()],"Input is not a string or undefined",(e="Input is not a string or undefined")=>t=>{const n=It.filter((e=>e(t)));return!(n.length<It.length)&&(e?e.replace("{val}",t):n.join(" OR "))});var It;const xt=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>ht(...e).validate(n[t]))),t(...n)),St=e=>[wt(`"${e}" must be a string`),bt(`"${e}" must not be empty`)],jt=e=>[wt(`"${e}" must be a string`),vt()],Ot=e=>[wt(`"${e}" must be a string`),mt()],Ct=xt(St("accessKey")),Et=e=>({exchange:Ct((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 _t=Object.assign(Object.assign({},At),Ut);var Rt;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(Rt||(Rt={}));const Pt=St("loginId"),Tt=xt(St("token")),Lt=xt(Pt),Mt=xt(St("pendingRef")),$t=xt(Pt,jt("email")),qt=e=>({verify:Tt((t=>dt(e.post(ye,{token:t})))),signIn:Lt(((t,n,o,r)=>dt(e.post(ct(ke,_t.email),{loginId:t,URI:n,loginOptions:o},{token:r})))),signUpOrIn:Lt(((t,n)=>dt(e.post(ct(je,_t.email),{loginId:t,URI:n})))),signUp:Lt(((t,n,o)=>dt(e.post(ct(Ie,_t.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(xe,{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(Se.email,Object.assign({loginId:t,email:n,URI:o},i),{token:r}))))}}),Wt=xt(St("flowId")),Dt=xt(St("executionId"),St("stepId"),St("interactionId")),Ft=e=>({start:Wt(((t,n,o,r,i,s)=>dt(e.post(Ve,{flowId:t,options:n,conditionInteractionId:o,interactionId:r,input:i,version:s})))),next:Dt(((t,n,o,r,i)=>dt(e.post(Be,{executionId:t,stepId:n,interactionId:o,input:r,version:i}))))}),Nt=St("loginId"),Kt=xt(St("token")),Jt=xt(Nt),Ht=xt(Nt,Ot("phone")),zt=xt(Nt,jt("email")),Vt=e=>({verify:Kt((t=>dt(e.post(ge,{token:t})))),signIn:Object.keys(_t).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(_t).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(_t).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"}(Bt||(Bt={}));const Gt=xt(St("code")),Yt=e=>({start:Object.keys(Bt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,o,r)=>dt(e.post(Oe,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:r}))})),{}),exchange:Gt((t=>dt(e.post(Ce,{code:t}))))}),Zt=St("loginId"),Xt=xt(Zt,St("code")),Qt=xt(Zt),en=xt(Zt,Ot("phone")),tn=xt(Zt,jt("email")),nn=e=>({verify:Object.keys(_t).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(_t).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(_t).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(_t).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=xt(St("tenant")),rn=xt(St("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=St("loginId"),ln=xt(an,St("code")),cn=xt(an),dn=xt(an),un=e=>({signUp:cn(((t,n)=>dt(e.post(_e,{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(Re,{loginId:t},{token:n}))))}),hn=St("loginId"),pn=St("newPassword"),fn=xt(hn,St("password")),gn=xt(hn),vn=xt(hn,pn),mn=xt(hn,St("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(Ne))}),wn=[wt('"loginId" must be a string')],yn=St("loginId"),kn=St("origin"),In=xt(yn,kn,St("name")),xn=xt(yn,kn),Sn=xt(wn,kn),jn=xt(yn,kn,St("token")),On=xt(St("transactionId"),St("response")),Cn=e=>({signUp:{start:In(((t,n,o)=>dt(e.post(Pe.start,{user:{loginId:t,name:o},origin:n})))),finish:On(((t,n)=>dt(e.post(Pe.finish,{transactionId:t,response:n}))))},signIn:{start:Sn(((t,n,o,r)=>dt(e.post(Te.start,{loginId:t,origin:n,loginOptions:o},{token:r})))),finish:On(((t,n)=>dt(e.post(Te.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:xn(((t,n)=>dt(e.post(Le.start,{loginId:t,origin:n}))))},update:{start:jn(((t,n,o)=>dt(e.post(Me.start,{loginId:t,origin:n},{token:o})))),finish:On(((t,n)=>dt(e.post(Me.finish,{transactionId:t,response:n}))))}}),En=xt(St("token")),An=xt([kt('"token" must be string or undefined')]);var Un,_n=xt([("projectId",Un=St("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:Cn(a),password:bn(a),flow:Ft(a),refresh:An((e=>dt(a.post(Ke,{},{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 Rn=(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 Pn=Object.assign(_n,{DeliveryMethods:_t});var Tn="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===Tn||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(Tn)}();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 Nn={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:"/"})}()}(Nn);var Kn=w(Nn.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=Xn&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",eo=(e="",t="")=>({vsid:e,vrid:t}),to=(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},no=e=>(e.body&&(e.body.fpData=to(!0)||eo()),e),oo="dls_last_user_login_id",ro="dls_last_user_display_name",io=()=>Gn(oo),so=()=>Gn(ro),ao=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,r=io(),i=so();return r&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=r,o.lastAuth.name=i),await e(...t)},lo=e=>async(...t)=>{const n=await e(...t);return Yn(oo),Yn(ro),n};function co(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const uo="DS",ho="DSR";function po(){return Gn(ho)||""}function fo(){return Kn.get(uo)||Gn(uo)||""}function go(){Yn(ho),Yn(uo),Kn.remove(uo)}const vo=e=>Object.assign(e,{token:e.token||po()}),mo=e=>async(...t)=>{const n=await e(...t);return go(),n};async function bo(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=So(n.publicKey.challenge),n.publicKey.user.id=So(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=So(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 wo(e){const t=Io(e);return xo(await navigator.credentials.get(t))}async function yo(e,t){const n=Io(e);return n.signal=t.signal,n.mediation="conditional",xo(await navigator.credentials.get(n))}async function ko(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 Io(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=So(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=So(e.id)})),n}function xo(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 So(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,Co=(Oo=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 bo(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 wo(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 bo(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,t)}{const t=await wo(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 bo(o.data.options);return await e.webauthn.update.finish(o.data.transactionId,r)},helpers:{create:bo,get:wo,isSupported:ko,conditional:yo}}),(...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}),Eo=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await ko(),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 Ao=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(to())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:Qn}),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))})(eo(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:no}))):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;const e=((c=s)?c.getTime()-(new Date).getTime():0)-2e4;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 Rn(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.4.0"},t.baseHeaders)}))),(e=>t=>{const n=co(),o=co(),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=Rn(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(oo,e)})(r),(e=>{Bn(ro,e)})(i))}}));let o=Rn(n,["flow.start"],ao);return o=Rn(o,["logout","logoutAll"],lo),Object.assign(o,{getLastUserLoginId:io,getLastUserDisplayName:so})}),(e=>t=>{var{persistTokens:n,sessionTokenViaCookie:o}=t,r=d(t,["persistTokens","sessionTokenViaCookie"]);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 i=e(Jn(r,{beforeRequest:vo,afterRequest:async(e,t)=>{401===(null==t?void 0:t.status)?go():((e={},t)=>{var{refreshJwt:n,sessionJwt:o}=e,r=d(e,["refreshJwt","sessionJwt"]);void 0===t&&(t=!1),n&&Bn(ho,n),o&&(t?function(e,t,{cookiePath:n,cookieDomain:o,cookieExpiration:r}){if(t){const i=new Date(1e3*r);Kn.set(e,t,{path:n,domain:o,expires:i,sameSite:"Strict",secure:!0})}}(uo,o,r):Bn(uo,o))})(await Hn(t),o)}})),s=Rn(i,["logout","logoutAll"],mo);return Object.assign(s,{getRefreshToken:po,getSessionToken:fo})}))(((...e)=>{const t=Pn(...e);return Object.assign(Object.assign({},t),{flow:Eo(t),webauthn:Co(t)})}));let Uo;const _o=e=>{const t=Ao({...e,persistTokens:l,autoRefresh:l});return Uo=t,t};Uo=_o({projectId:"temp pid"});const Ro=()=>l?Uo?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),Po=()=>l?Uo?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),To=s(((e=Ro(),t)=>Uo?.getJwtPermissions(e,t))),Lo=s(((e=Ro(),t)=>Uo?.getJwtRoles(e,t)));const Mo=t.lazy((async()=>((await Promise.resolve().then((function(){return gi}))).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})}))),$o=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),k=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",k),i&&e?.addEventListener("error",i),()=>{i&&e?.removeEventListener("error",i),e?.removeEventListener("success",k)}}),[v,i,k]),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(Mo,{projectId:b,flowId:e,baseUrl:w,innerRef:m,tenant:a,theme:l,locale:c,debug:d,telemetryKey:u,redirectUrl:h,autoFocus:p})))}));var qo=()=>{const e=t.useContext(r);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const Wo=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,Do={get(e,t){if("object"==typeof e[t]&&null!==e[t])return new Proxy(e[t],Do);if("function"==typeof e[t])return()=>{throw Error(Wo("function"))};throw Error(Wo("attribute"))}},Fo="undefined"!=typeof localStorage,No=Fo&&localStorage.getItem("base.content.url")||"https://static.descope.com/pages",Ko="descope-login-flow",Jo="code",Ho="ra-challenge",zo="ra-callback",Vo="ra-initiator",Bo="data-exclude-field",Go="dls_last_auth",Yo="state_id",Zo="data-type",Xo="poll",Qo="webauthnCreate",er="submit",tr="polling";var nr,or,rr;function ir(e){return new URLSearchParams(window.location.search).get(e)}function sr(e){if(window.history.replaceState&&ir(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 ar(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 lr(e,t){const n=new URL(No);return n.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(n.pathname,e,"v2-alpha",t),n.toString()}function cr(e,t){if(!Number.isNaN(e)&&!Number.isNaN(t))return e>t?nr.forward:e<t?nr.backward:void 0}!function(e){e.backward="backward",e.forward="forward"}(nr||(nr={}));const dr=()=>{const[e="",t=""]=(ir(Ko)||"").split("_");return{executionId:e,stepId:t}};function ur(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}function hr(){sr(Ko)}const pr=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),fr=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}},gr=null===(rr=null===(or=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===or?void 0:or.brands)||void 0===rr?void 0:rr.find((({brand:e,version:t})=>"Chromium"===e&&parseFloat(t))),vr=(e,t)=>e&&!t;var mr,br,wr,yr;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 Ir{constructor(e={},{updateOnlyOnChange:t=!0}={}){mr.set(this,void 0),br.set(this,{}),wr.set(this,0),yr.set(this,!1),this.update=e=>{const t="function"==typeof e?e(h(this,mr,"f")):e,n=Object.assign(Object.assign({},h(this,mr,"f")),t);if(!h(this,yr,"f")||!kr(h(this,mr,"f"),n)){const e=h(this,mr,"f");p(this,mr,n,"f"),Object.freeze(h(this,mr,"f")),setTimeout((()=>{Object.values(h(this,br,"f")).forEach((t=>t(n,e,((e,t)=>n=>e[n]!==t[n])(n,e))))}),0)}},p(this,mr,e,"f"),p(this,yr,t,"f")}get current(){return Object.assign({},h(this,mr,"f"))}subscribe(e){return p(this,wr,h(this,wr,"f")+1,"f"),h(this,br,"f")[h(this,wr,"f")]=e,h(this,wr,"f").toString()}unsubscribe(e){const t=!!h(this,br,"f")[e];return t&&delete h(this,br,"f")[e],t}unsubscribeAll(){return p(this,br,{},"f"),!0}}mr=new WeakMap,br=new WeakMap,wr=new WeakMap,yr=new WeakMap;const xr=(e,t)=>{Object.entries(t||{}).forEach((([t,n])=>{Array.from(e.querySelectorAll(`.descope-input[name="${t}"]:not([${Bo}])`)).forEach((e=>{e.value=n}))}))},Sr=fr((()=>u(void 0,void 0,void 0,(function*(){var e,t;if(!window.PublicKeyCredential||!PublicKeyCredential.isConditionalMediationAvailable||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)return console.warn("webauthn","Conditional UI is not supported"),!1;try{const n=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)))),o=108;return yield Promise.race([n,(100,new Promise(((e,t)=>{setTimeout((()=>{t(new Error("Promise timed out after 100 ms"))}),100)}))).catch((()=>gr()>=o))])}catch(e){return console.warn("webauthn","Conditional login check failed",e),!1}})))),jr={"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 Or(e){const t={};if(e)try{Object.assign(t,JSON.parse(localStorage.getItem(Go)))}catch(e){}return t}const Cr=document.createElement("template");var Er,Ar,Ur,_r,Rr,Pr,Tr,Lr,Mr,$r,qr,Wr,Dr,Fr,Nr,Kr,Jr,Hr,zr,Vr,Br,Gr,Yr,Zr,Xr,Qr,ei,ti,ni,oi,ri,ii,si,ai,li,ci,di,ui,hi;Cr.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 pi extends HTMLElement{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","theme","locale","debug","telemetryKey","redirect-url","auto-focus","prefer-biometrics"]}constructor(e){super(),Er.add(this),this.logger=console,Ar.set(this,!1),this.loggerWrapper={error:(e,t="")=>{this.logger.error(e,t,new Error),h(this,Er,"m",Yr).call(this,e,t)},warn:(e,t="")=>{this.logger.warn(e,t)},info:(e,t="",n={})=>{this.logger.info(e,t,n)}},Ur.set(this,new Ir({deferredRedirect:!1})),_r.set(this,new Ir),this.nextRequestStatus=new Ir({isLoading:!1}),Rr.set(this,void 0),Pr.set(this,{popstate:h(this,Er,"m",Wr).bind(this),visibilitychange:h(this,Er,"m",Dr).bind(this)}),Tr.set(this,void 0),Kr.set(this,fr((()=>u(this,void 0,void 0,(function*(){const e=lr(this.projectId,"config.json");try{const{body:t,headers:n}=yield ar(e,"json");return{projectConfig:t,executionContext:{geo:n["x-geo"]}}}catch(e){this.loggerWrapper.error("Cannot get config file","make sure that your projectId & flowId are correct")}return{}}))))),p(this,Tr,e,"f"),h(this,Er,"m",Lr).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 preferBiometrics(){var e;return"true"===(null!==(e=this.getAttribute("prefer-biometrics"))&&void 0!==e?e:"true")}getExecutionContext(){return u(this,void 0,void 0,(function*(){const{executionContext:e}=yield h(this,Kr,"f").call(this);return e}))}getFlowConfig(){var e,t;return u(this,void 0,void 0,(function*(){const{projectConfig:n}=yield h(this,Kr,"f").call(this),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,Er,"m",Mr).call(this))return void h(this,Er,"m",$r).call(this);h(this,Er,"m",qr).call(this),h(this,Er,"m",Hr).call(this),h(this,Er,"m",Jr).call(this),h(this,Er,"m",Zr).call(this);const{executionId:e,stepId:t,token:n,code:o,exchangeError:r,redirectAuthCallbackUrl:i,redirectAuthCodeChallenge:s,redirectAuthInitiator:a,oidcIdpStateId:l}=(()=>{const{executionId:e,stepId:t}=dr();(e||t)&&hr();const n=ir("t")||void 0;n&&sr("t");const o=ir(Jo)||void 0;o&&sr(Jo);const r=ir("err")||void 0;r&&sr("err");const{redirectAuthCodeChallenge:i,redirectAuthCallbackUrl:s,redirectAuthInitiator:a}={redirectAuthCodeChallenge:ir(Ho),redirectAuthCallbackUrl:ir(zo),redirectAuthInitiator:ir(Vo)};(i||s||a)&&(sr(Ho),sr(zo),sr(Vo));const l=ir(Yo);return l&&sr(Yo),{executionId:e,stepId:t,token:n,code:o,exchangeError:r,redirectAuthCodeChallenge:i,redirectAuthCallbackUrl:s,redirectAuthInitiator:a,oidcIdpStateId:l}})();window.addEventListener("popstate",h(this,Pr,"f").popstate),window.addEventListener("visibilitychange",h(this,Pr,"f").visibilitychange),h(this,Ur,"f").subscribe(h(this,Er,"m",Nr).bind(this)),h(this,_r,"f").subscribe(h(this,Er,"m",Gr).bind(this)),h(this,Ur,"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}),h(this,_r,"f").update({isDebug:this.debug}),p(this,Ar,!0,"f")}}))}disconnectedCallback(){h(this,Ur,"f").unsubscribeAll(),h(this,_r,"f").unsubscribeAll(),h(this,Er,"m",Br).call(this),window.removeEventListener("popstate",h(this,Pr,"f").popstate)}attributeChangedCallback(e,t,n){if(this.shadowRoot.isConnected&&h(this,Ar,"f")&&t!==n&&pi.observedAttributes.includes(e)){h(this,Er,"m",qr).call(this);const o=null===t;h(this,Ur,"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,_r,"f").update({isDebug:this.debug})}}}Ar=new WeakMap,Ur=new WeakMap,_r=new WeakMap,Rr=new WeakMap,Pr=new WeakMap,Tr=new WeakMap,Kr=new WeakMap,Er=new WeakSet,Lr=function(){this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Cr.content.cloneNode(!0)),this.rootElement=this.shadowRoot.querySelector("#wc-root")},Mr=function(){return!this.shadowRoot.host.closest("form")&&ur()},$r=function(){const e=this.shadowRoot.host,t=document.createElement("form");e.parentElement.appendChild(t),t.appendChild(e)},qr=function(){const e=["base-url","tenant","theme","locale","debug","telemetryKey","redirect-url","auto-focus","prefer-biometrics"];if(pi.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')},Wr=function(){const{stepId:e,executionId:t}=dr();h(this,Ur,"f").update({stepId:e,executionId:t})},Dr=function(){document.hidden||setTimeout((()=>{h(this,Ur,"f").update({deferredRedirect:!1})}),300)},Fr=function(e,t,n){const o=n||void 0,r=!!o;this.sdk=Ao(Object.assign(Object.assign({persistTokens:!0},pi.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})}}))}))},Nr=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,Er,"m",Fr).call(this,t,o,r)}h(this,Tr,"f").call(this,e)}))},Jr=function(){var e,t,n,o;return u(this,void 0,void 0,(function*(){const{projectConfig:r}=yield h(this,Kr,"f").call(this);null===(o=null===(n=null===(t=null===(e=null==r?void 0:r.cssTemplate)||void 0===e?void 0:e[this.theme])||void 0===t?void 0:t.typography)||void 0===n?void 0:n.fontFamilies)||void 0===o||o.forEach((e=>(e=>{if(!e)return;const t=document.createElement("link");t.href=e,t.rel="stylesheet",document.head.appendChild(t)})(e.url)))}))},Hr=function(){h(this,Er,"m",zr).call(this),h(this,Er,"m",Vr).call(this)},zr=function(){return u(this,void 0,void 0,(function*(){const e=document.createElement("style"),t=lr(this.projectId,"theme.css");try{const{body:n}=yield ar(t,"text");e.innerText=n}catch(e){this.loggerWrapper.error("Cannot fetch theme file","make sure that your projectId & flowId are correct")}this.shadowRoot.appendChild(e)}))},Vr=function(){this.rootElement.setAttribute("data-theme",this.theme)},Br=function(){var e;null===(e=h(this,Rr,"f"))||void 0===e||e.remove(),p(this,Rr,null,"f")},Gr=function({isDebug:e}){return u(this,void 0,void 0,(function*(){e?(yield Promise.resolve().then((function(){return Ai})),p(this,Rr,document.createElement("descope-debugger"),"f"),Object.assign(h(this,Rr,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),document.body.appendChild(h(this,Rr,"f"))):h(this,Er,"m",Br).call(this)}))},Yr=function(e,t){var n;e&&this.debug&&(null===(n=h(this,Rr,"f"))||void 0===n||n.updateData({title:e,description:t}))},Zr=function(){this.rootElement.onkeydown=e=>{if("Enter"!==e.key)return;e.preventDefault();const t=this.rootElement.querySelectorAll("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()}},pi.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"2.8.9"}};class fi extends pi{static set sdkConfigOverrides(e){pi.sdkConfigOverrides=e}constructor(){const e=new Ir;super(e.update.bind(e)),Xr.add(this),this.stepState=new Ir({},{updateOnlyOnChange:!1}),Qr.set(this,void 0),ei.set(this,null),ti.set(this,(()=>{clearInterval(h(this,Qr,"f")),p(this,Qr,null,"f")})),ni.set(this,(e=>{var t,n,o,r,i,s,a,l,c;if(!(null==e?void 0:e.ok)){h(this,ti,"f").call(this),h(this,Xr,"m",hi).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)&&Fo&&localStorage.setItem(Go,JSON.stringify(e))}(f),h(this,ti,"f").call(this),void h(this,Xr,"m",hi).call(this,"success",p);const{executionId:g,stepId:v,stepName:m,action:b,screen:w,redirect:y,webauthn:k,error:I}=e.data;b!==Xo?(this.loggerWrapper.info(`Step "${m||`#${v}`}" is ${u}`,"",{screen:w,status:u,stepId:v,stepName:m,action:b,error:I}),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==k?void 0:k.transactionId,webauthnOptions:null==k?void 0:k.options})):this.flowState.update({action:b})})),oi.set(this,fr((()=>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(){super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll()}getHtmlFilenameWithLocale(e,t){return u(this,void 0,void 0,(function*(){let n;const o=(e||navigator.language||"").toLowerCase();return(yield this.getTargetLocales()).includes(o)&&(n=`${t}-${o}.html`),n}))}getPageContent(e,t){return u(this,void 0,void 0,(function*(){if(t)try{const{body:e}=yield ar(t,"text");return e}catch(n){this.loggerWrapper.error(`Failed to fetch html page from ${t}. Fallback to url ${e}`,n)}try{const{body:t}=yield ar(e,"text");return t}catch(t){this.loggerWrapper.error(`Failed to fetch html page from ${e}`,t)}return null}))}onFlowChange(e,t,n){var o,r,i,s,a,l;return u(this,void 0,void 0,(function*(){const{projectId:c,flowId:d,tenant:f,stepId:g,executionId:v,action:m,screenId:b,screenState:w,redirectTo:y,redirectUrl:k,token:I,code:x,exchangeError:S,webauthnTransactionId:j,webauthnOptions:O,redirectAuthCodeChallenge:C,redirectAuthCallbackUrl:E,redirectAuthInitiator:A,oidcIdpStateId:U,locale:_}=e;let R,P;h(this,Qr,"f")&&h(this,ti,"f").call(this);const T=this.sdk.getLastUserLoginId(),L=yield this.getFlowConfig(),M=E&&C?{callbackUrl:E,codeChallenge:C}:void 0;if(!v&&(L.conditions?({startScreenId:R,conditionInteractionId:P}=((e,t)=>{const n=null==t?void 0:t.find((({key:t,operator:n})=>{var o;if("ELSE"===t)return!0;const r=null===(o=jr[t])||void 0===o?void 0:o[n];return!!(null==r?void 0:r(e))}));return n?{startScreenId:n.met.screenId,conditionInteractionId:n.met.interactionId}:{}})({loginId:T,code:x,token:I},L.conditions)):L.condition?({startScreenId:R,conditionInteractionId:P}=((e,t)=>{var n;const o=null===(n=jr[null==e?void 0:e.key])||void 0===n?void 0:n[e.operator];if(!o)return{};const r=o(t)?e.met:e.unmet;return{startScreenId:null==r?void 0:r.screenId,conditionInteractionId:null==r?void 0:r.interactionId}})(L.condition,{loginId:T,code:x,token:I})):R=L.startScreenId,!vr(R,U))){const e={};let t=!1;x&&(t=!0,e.exchangeCode=x,e.idpInitiated=!0),I&&(t=!0,e.token=I);const n=yield this.sdk.flow.start(d,Object.assign(Object.assign({tenant:f,redirectAuth:M,oidcIdpStateId:U},k&&{redirectUrl:k}),{lastAuth:Or(T)}),P,"",t?e:void 0,L.version);return h(this,ni,"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(v&&(n("token")&&I||n("code")&&x||n("exchangeError")&&S)){const e=yield this.sdk.flow.next(v,g,er,{token:I,exchangeCode:x,exchangeError:S},L.version);return h(this,ni,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if("redirect"===m&&(n("redirectTo")||n("deferredRedirect")))return y?"android"===A&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(y):void this.loggerWrapper.error("Did not get redirect url");if(m===Qo||"webauthnGet"===m){if(!j||!O)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t,n=O;if(this.preferBiometrics&&m===Qo&&ur()&&(yield null===(i=null===(r=window.PublicKeyCredential)||void 0===r?void 0:r.isUserVerifyingPlatformAuthenticatorAvailable)||void 0===i?void 0:i.call(r)))try{const e=JSON.parse(n);e.publicKey&&((a=e.publicKey).authenticatorSelection||(a.authenticatorSelection={}),(l=e.publicKey.authenticatorSelection).authenticatorAttachment||(l.authenticatorAttachment="platform"),n=JSON.stringify(e))}catch(e){this.loggerWrapper.info("Failed to modify webauthn create options")}null===(s=h(this,ei,"f"))||void 0===s||s.abort(),p(this,ei,null,"f");try{e=m===Qo?yield this.sdk.webauthn.helpers.create(n):yield this.sdk.webauthn.helpers.get(n)}catch(e){if("NotAllowedError"!==e.name)return void this.loggerWrapper.error(e.message);t=!0}const o=yield this.sdk.flow.next(v,g,er,{transactionId:j,response:e,cancelWebauthn:t},L.version);h(this,ni,"f").call(this,o)}if(m===Xo&&p(this,Qr,setInterval((()=>u(this,void 0,void 0,(function*(){const e=yield this.sdk.flow.next(v,g,tr,{},L.version);h(this,ni,"f").call(this,e)}))),2e3),"f"),!b&&!R)return void this.loggerWrapper.warn("No screen was found to show");const $=R||b,q=yield this.getHtmlFilenameWithLocale(_,$),W={direction:cr(+g,+t.stepId),screenState:Object.assign(Object.assign({},w),{lastAuth:{loginId:T,name:this.sdk.getLastUserDisplayName()||T}}),htmlUrl:lr(c,`${$}.html`),htmlLocaleUrl:q&&lr(c,q)},D=Or(T);vr(R,U)?W.next=(e,t)=>this.sdk.flow.start(d,Object.assign({tenant:f,redirectAuth:M,oidcIdpStateId:U,lastAuth:D},k&&{redirectUrl:k}),P,e,Object.assign(Object.assign(Object.assign({},t),x&&{exchangeCode:x,idpInitiated:!0}),I&&{token:I}),L.version):(n("projectId")||n("baseUrl")||n("executionId")||n("stepId"))&&(W.next=(...e)=>this.sdk.flow.next(v,g,...e)),this.stepState.update(W)}))}onStepChange(e,t){var n;return u(this,void 0,void 0,(function*(){const{htmlUrl:o,htmlLocaleUrl:r,direction:i,next:s,screenState:a}=e,l=document.createElement("template");l.innerHTML=yield this.getPageContent(o,r);const c=l.content.cloneNode(!0),d=((e,t)=>{var n;const o=Array.from(e.querySelectorAll("script[data-id]")).map((n=>{var o;const r=n.getAttribute("data-id"),i=null===(o=e.getElementById(r))||void 0===o?void 0:o.innerHTML,s=Function(i).bind(n.previousSibling,t);return n.remove(),s}));return null===(n=e.querySelector("scripts"))||void 0===n||n.remove(),o})(c,yield this.getExecutionContext());this.sdk.webauthn.helpers.isSupported()?yield h(this,Xr,"m",ii).call(this,c,s):c.querySelectorAll(`button[${Zo}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true"))),((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(`[${Zo}="${t}"]`).forEach((e=>{e.textContent=n,e.classList[n?"remove":"add"]("hide")}))})(e,"error-message",i),xr(e,null==t?void 0:t.inputs),xr(e,null==t?void 0:t.form),((e,t)=>{e.querySelectorAll(`[${Zo}="totp-link"]`).forEach((e=>{e.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)})(c,a,this.errorTransformer,this.loggerWrapper),((e,t)=>{var n;t&&(null===(n=null==e?void 0:e.style)||void 0===n||n.setProperty("--totp-image",`url(data:image/jpg;base64,${t})`))})(c.querySelector("div"),null===(n=null==a?void 0:a.totp)||void 0===n?void 0:n.image);const p=()=>u(this,void 0,void 0,(function*(){try{d.forEach((e=>{e()}))}catch(e){this.loggerWrapper.error(e.message)}this.rootElement.replaceChildren(c);const e=!t.htmlUrl;if(((e,t,n)=>{if(!0===t||"skipFirstScreen"===t&&!n){const t=e.querySelector('input:not([aria-hidden="true"])');null==t||t.focus()}})(this.rootElement,this.autoFocus,e),h(this,Xr,"m",di).call(this,s),h(this,Xr,"m",hi).call(this,"page-updated",{}),this.rootElement.querySelector(`[${Zo}="polling"]`)){const e=yield s(tr,{});h(this,ni,"f").call(this,e)}}));i?h(this,Xr,"m",ui).call(this,p,i):p()}))}}Qr=new WeakMap,ei=new WeakMap,ti=new WeakMap,ni=new WeakMap,oi=new WeakMap,Xr=new WeakSet,ri=function(e){const t=e.name;if(!["email"].includes(t)){const n=`user-${t}`;e.name=n,e.addEventListener("input",(()=>{e.name=e.value?t:n}))}},ii=function(e,t){var n;return u(this,void 0,void 0,(function*(){null===(n=h(this,ei,"f"))||void 0===n||n.abort();const o=e.querySelector('input[autocomplete="webauthn"]');if(o&&(yield Sr())){const{options:e,transactionId:n}=(yield h(this,oi,"f").call(this))||{};e&&n&&(h(this,Xr,"m",ri).call(this,o),p(this,ei,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(e,h(this,ei,"f")).then((e=>u(this,void 0,void 0,(function*(){const r=yield t(o.id,{transactionId:n,response:e});h(this,ni,"f").call(this,r)})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},si=function(){return Array.from(this.shadowRoot.querySelectorAll(".descope-input")).every((e=>(e.reportValidity(),e.checkValidity())))},ai=function(){return u(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`.descope-input[name]:not([${Bo}])`)),t=yield Promise.all(e.map((e=>u(this,void 0,void 0,(function*(){const t=yield(e=>new Promise((t=>{var n;switch(e.type){case"checkbox":t(e.checked);break;case"file":{const o=new FileReader;(null===(n=e.files)||void 0===n?void 0:n.length)?(o.onload=e=>{const n=e.target.result;t(n)},o.readAsDataURL(e.files[0])):t(null);break}default:t(e.value)}})))(e);return{name:e.name,value:t}})))));return t.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},li=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:n})=>{var o,r;n?null===(o=null==e?void 0:e.classList)||void 0===o||o.add("loading"):(this.nextRequestStatus.unsubscribe(t),null===(r=null==e?void 0:e.classList)||void 0===r||r.remove("loading"))}))},ci=function(e,t){return u(this,void 0,void 0,(function*(){if(e.formNoValidate||h(this,Xr,"m",si).call(this)){const o=null==e?void 0:e.getAttribute("id");h(this,Xr,"m",li).call(this,e);const r=yield h(this,Xr,"m",ai).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=Object.assign(Object.assign(Object.assign({},i),r),{origin:window.location.origin}),a=yield t(o,s);h(this,ni,"f").call(this,a)}var n}))},di=function(e){this.rootElement.querySelectorAll("button:not([data-exclude-next])").forEach((t=>{t.onclick=()=>{h(this,Xr,"m",ci).call(this,t,e)}}))},ui=function(e,t){this.rootElement.addEventListener("transitionend",(()=>{this.rootElement.classList.remove("fade-out"),e()}),{once:!0});const n=t===nr.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")},hi=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},customElements.define("descope-wc",fi);var gi=Object.freeze({__proto__:null,default:fi});const vi=(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 mi,bi,wi,yi,ki,Ii,xi,Si,ji,Oi;const Ci=document.createElement("template");Ci.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 } \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 Ei extends HTMLElement{constructor(){super(),mi.add(this),bi.set(this,new Ir({messages:[]})),wi.set(this,void 0),yi.set(this,void 0),ki.set(this,void 0),Ii.set(this,{resize:h(this,mi,"m",Oi).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Ci.content.cloneNode(!0)),p(this,wi,this.shadowRoot.querySelector(".debugger"),"f"),p(this,yi,h(this,wi,"f").querySelector(".content"),"f"),p(this,ki,h(this,wi,"f").querySelector(".header"),"f")}updateData(e){h(this,bi,"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]=vi(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,wi,"f"),h(this,ki,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",h(this,Ii,"f").resize),(e=h(this,wi,"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,wi,"f").onresize=h(this,mi,"m",ji).bind(this),h(this,bi,"f").subscribe(h(this,mi,"m",xi).bind(this))}disconnectedCallback(){h(this,bi,"f").unsubscribeAll(),window.removeEventListener("resize",h(this,Ii,"f").resize)}}bi=new WeakMap,wi=new WeakMap,yi=new WeakMap,ki=new WeakMap,Ii=new WeakMap,mi=new WeakSet,xi=function(e){h(this,mi,"m",Si).call(this,e),h(this,mi,"m",ji).call(this)},Si=function(e){h(this,yi,"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("")},ji=function(){h(this,yi,"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)}))},Oi=function(){const[e,t]=vi(h(this,wi,"f"),Number.parseInt(h(this,wi,"f").style.left,10),Number.parseInt(h(this,wi,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});h(this,wi,"f").style.top=`${t}px`,h(this,wi,"f").style.left=`${e}px`},customElements.define("descope-debugger",Ei);var Ai=Object.freeze({__proto__:null,default:Ei});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 _o({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]),k=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:k},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=To,e.getJwtRoles=Lo,e.getRefreshToken=Po,e.getSessionToken=Ro,e.refresh=(e=Po())=>Uo?.refresh(e),e.useDescope=()=>{const{sdk:e}=qo();return t.useMemo((()=>e||new Proxy(_o({projectId:"dummy"}),Do)),[e])},e.useSession=()=>{const{session:e,isSessionLoading:n,fetchSession:o,isSessionFetched:r}=qo(),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}=qo(),[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})}));
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":"1.0.12"},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__",k="[object Function]",I="[object GeneratorFunction]",x=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,S=/^\w*$/,j=/^\./,O=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,C=/\\(\\)?/g,E=/^\[object .+?Constructor\]$/,A="object"==typeof b&&b&&b.Object===Object&&b,U="object"==typeof self&&self&&self.Object===Object&&self,_=A||U||Function("return this")();var R,P=Array.prototype,T=Function.prototype,L=Object.prototype,M=_["__core-js_shared__"],$=(R=/[^.]+$/.exec(M&&M.keys&&M.keys.IE_PROTO||""))?"Symbol(src)_1."+R:"",q=T.toString,W=L.hasOwnProperty,D=L.toString,F=RegExp("^"+q.call(W).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),N=_.Symbol,K=P.splice,J=te(_,"Map"),H=te(Object,"create"),z=N?N.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 S.test(e)||!x.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==k||t==I}(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():K.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 j.test(e)&&n.push(""),e.replace(O,(function(e,t,o,r){n.push(o?r.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 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",ke="/v1/auth/enchantedlink/signin",Ie="/v1/auth/enchantedlink/signup",xe="/v1/auth/enchantedlink/pending-session",Se={email:"/v1/auth/enchantedlink/update/email"},je="/v1/auth/enchantedlink/signup-in",Oe="/v1/auth/oauth/authorize",Ce="/v1/auth/oauth/exchange",Ee="/v1/auth/saml/authorize",Ae="/v1/auth/saml/exchange",Ue="/v1/auth/totp/verify",_e="/v1/auth/totp/signup",Re="/v1/auth/totp/update",Pe={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},Te={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",Ne="/v1/auth/password/policy",Ke="/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":"1.7.3"},(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"),kt=(It=[wt(),yt()],"Input is not a string or undefined",(e="Input is not a string or undefined")=>t=>{const n=It.filter((e=>e(t)));return!(n.length<It.length)&&(e?e.replace("{val}",t):n.join(" OR "))});var It;const xt=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>ht(...e).validate(n[t]))),t(...n)),St=e=>[wt(`"${e}" must be a string`),bt(`"${e}" must not be empty`)],jt=e=>[wt(`"${e}" must be a string`),vt()],Ot=e=>[wt(`"${e}" must be a string`),mt()],Ct=xt(St("accessKey")),Et=e=>({exchange:Ct((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 _t=Object.assign(Object.assign({},At),Ut);var Rt;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(Rt||(Rt={}));const Pt=St("loginId"),Tt=xt(St("token")),Lt=xt(Pt),Mt=xt(St("pendingRef")),$t=xt(Pt,jt("email")),qt=e=>({verify:Tt((t=>dt(e.post(ye,{token:t})))),signIn:Lt(((t,n,o,r)=>dt(e.post(ct(ke,_t.email),{loginId:t,URI:n,loginOptions:o},{token:r})))),signUpOrIn:Lt(((t,n)=>dt(e.post(ct(je,_t.email),{loginId:t,URI:n})))),signUp:Lt(((t,n,o)=>dt(e.post(ct(Ie,_t.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(xe,{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(Se.email,Object.assign({loginId:t,email:n,URI:o},i),{token:r}))))}}),Wt=xt(St("flowId")),Dt=xt(St("executionId"),St("stepId"),St("interactionId")),Ft=e=>({start:Wt(((t,n,o,r,i,s)=>dt(e.post(Ve,{flowId:t,options:n,conditionInteractionId:o,interactionId:r,input:i,version:s})))),next:Dt(((t,n,o,r,i)=>dt(e.post(Be,{executionId:t,stepId:n,interactionId:o,input:r,version:i}))))}),Nt=St("loginId"),Kt=xt(St("token")),Jt=xt(Nt),Ht=xt(Nt,Ot("phone")),zt=xt(Nt,jt("email")),Vt=e=>({verify:Kt((t=>dt(e.post(ge,{token:t})))),signIn:Object.keys(_t).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(_t).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(_t).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"}(Bt||(Bt={}));const Gt=xt(St("code")),Yt=e=>({start:Object.keys(Bt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,o,r)=>dt(e.post(Oe,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:r}))})),{}),exchange:Gt((t=>dt(e.post(Ce,{code:t}))))}),Zt=St("loginId"),Xt=xt(Zt,St("code")),Qt=xt(Zt),en=xt(Zt,Ot("phone")),tn=xt(Zt,jt("email")),nn=e=>({verify:Object.keys(_t).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(_t).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(_t).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(_t).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=xt(St("tenant")),rn=xt(St("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=St("loginId"),ln=xt(an,St("code")),cn=xt(an),dn=xt(an),un=e=>({signUp:cn(((t,n)=>dt(e.post(_e,{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(Re,{loginId:t},{token:n}))))}),hn=St("loginId"),pn=St("newPassword"),fn=xt(hn,St("password")),gn=xt(hn),vn=xt(hn,pn),mn=xt(hn,St("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(Ne))}),wn=[wt('"loginId" must be a string')],yn=St("loginId"),kn=St("origin"),In=xt(yn,kn,St("name")),xn=xt(yn,kn),Sn=xt(wn,kn),jn=xt(yn,kn,St("token")),On=xt(St("transactionId"),St("response")),Cn=e=>({signUp:{start:In(((t,n,o)=>dt(e.post(Pe.start,{user:{loginId:t,name:o},origin:n})))),finish:On(((t,n)=>dt(e.post(Pe.finish,{transactionId:t,response:n}))))},signIn:{start:Sn(((t,n,o,r)=>dt(e.post(Te.start,{loginId:t,origin:n,loginOptions:o},{token:r})))),finish:On(((t,n)=>dt(e.post(Te.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:xn(((t,n)=>dt(e.post(Le.start,{loginId:t,origin:n}))))},update:{start:jn(((t,n,o)=>dt(e.post(Me.start,{loginId:t,origin:n},{token:o})))),finish:On(((t,n)=>dt(e.post(Me.finish,{transactionId:t,response:n}))))}}),En=xt(St("token")),An=xt([kt('"token" must be string or undefined')]);var Un,_n=xt([("projectId",Un=St("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:Cn(a),password:bn(a),flow:Ft(a),refresh:An((e=>dt(a.post(Ke,{},{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 Rn=(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 Pn=Object.assign(_n,{DeliveryMethods:_t});var Tn="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===Tn||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(Tn)}();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 Nn={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:"/"})}()}(Nn);var Kn=w(Nn.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=Xn&&(null===localStorage||void 0===localStorage?void 0:localStorage.getItem("fingerprint.endpoint.url"))||"https://fp.descope.com",eo=(e="",t="")=>({vsid:e,vrid:t}),to=(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},no=e=>(e.body&&(e.body.fpData=to(!0)||eo()),e),oo="dls_last_user_login_id",ro="dls_last_user_display_name",io=()=>Gn(oo),so=()=>Gn(ro),ao=e=>async(...t)=>{var n;t[1]=t[1]||{};const[,o={}]=t,r=io(),i=so();return r&&(null!==(n=o.lastAuth)&&void 0!==n||(o.lastAuth={}),o.lastAuth.loginId=r,o.lastAuth.name=i),await e(...t)},lo=e=>async(...t)=>{const n=await e(...t);return Yn(oo),Yn(ro),n};function co(){const e=[];return{pub:t=>{e.forEach((e=>e(t)))},sub:t=>{const n=e.push(t)-1;return()=>e.splice(n,1)}}}const uo="DS",ho="DSR";function po(){return Gn(ho)||""}function fo(){return Kn.get(uo)||Gn(uo)||""}function go(){Yn(ho),Yn(uo),Kn.remove(uo)}const vo=e=>Object.assign(e,{token:e.token||po()}),mo=e=>async(...t)=>{const n=await e(...t);return go(),n};async function bo(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=So(n.publicKey.challenge),n.publicKey.user.id=So(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=So(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 wo(e){const t=Io(e);return xo(await navigator.credentials.get(t))}async function yo(e,t){const n=Io(e);return n.signal=t.signal,n.mediation="conditional",xo(await navigator.credentials.get(n))}async function ko(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 Io(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=So(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=So(e.id)})),n}function xo(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 So(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,Co=(Oo=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 bo(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 wo(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 bo(o.data.options);return await e.webauthn.signUp.finish(o.data.transactionId,t)}{const t=await wo(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 bo(o.data.options);return await e.webauthn.update.finish(o.data.transactionId,r)},helpers:{create:bo,get:wo,isSupported:ko,conditional:yo}}),(...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}),Eo=e=>Object.assign(Object.assign({},e.flow),{start:async(...t)=>{const n=await ko(),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 Ao=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(to())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:Qn}),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))})(eo(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:no}))):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;const e=((c=s)?c.getTime()-(new Date).getTime():0)-2e4;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 Rn(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.4.3"},t.baseHeaders)}))),(e=>t=>{const n=co(),o=co(),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=Rn(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(oo,e)})(r),(e=>{Bn(ro,e)})(i))}}));let o=Rn(n,["flow.start"],ao);return o=Rn(o,["logout","logoutAll"],lo),Object.assign(o,{getLastUserLoginId:io,getLastUserDisplayName:so})}),(e=>t=>{var{persistTokens:n,sessionTokenViaCookie:o}=t,r=d(t,["persistTokens","sessionTokenViaCookie"]);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 i=e(Jn(r,{beforeRequest:vo,afterRequest:async(e,t)=>{401===(null==t?void 0:t.status)?go():((e={},t)=>{var{refreshJwt:n,sessionJwt:o}=e,r=d(e,["refreshJwt","sessionJwt"]);void 0===t&&(t=!1),n&&Bn(ho,n),o&&(t?function(e,t,{cookiePath:n,cookieDomain:o,cookieExpiration:r}){if(t){const i=new Date(1e3*r);Kn.set(e,t,{path:n,domain:o,expires:i,sameSite:"Strict",secure:!0})}}(uo,o,r):Bn(uo,o))})(await Hn(t),o)}})),s=Rn(i,["logout","logoutAll"],mo);return Object.assign(s,{getRefreshToken:po,getSessionToken:fo})}))(((...e)=>{const t=Pn(...e);return Object.assign(Object.assign({},t),{flow:Eo(t),webauthn:Co(t)})}));let Uo;const _o=e=>{const t=Ao({...e,persistTokens:l,autoRefresh:l});return Uo=t,t};Uo=_o({projectId:"temp pid"});const Ro=()=>l?Uo?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),Po=()=>l?Uo?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),To=s(((e=Ro(),t)=>Uo?.getJwtPermissions(e,t))),Lo=s(((e=Ro(),t)=>Uo?.getJwtRoles(e,t)));const Mo=t.lazy((async()=>((await Promise.resolve().then((function(){return gi}))).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})}))),$o=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),k=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",k),i&&e?.addEventListener("error",i),()=>{i&&e?.removeEventListener("error",i),e?.removeEventListener("success",k)}}),[v,i,k]),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(Mo,{projectId:b,flowId:e,baseUrl:w,innerRef:m,tenant:a,theme:l,locale:c,debug:d,telemetryKey:u,redirectUrl:h,autoFocus:p})))}));var qo=()=>{const e=t.useContext(r);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const Wo=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,Do={get(e,t){if("object"==typeof e[t]&&null!==e[t])return new Proxy(e[t],Do);if("function"==typeof e[t])return()=>{throw Error(Wo("function"))};throw Error(Wo("attribute"))}},Fo="undefined"!=typeof localStorage,No=Fo&&localStorage.getItem("base.content.url")||"https://static.descope.com/pages",Ko="descope-login-flow",Jo="code",Ho="ra-challenge",zo="ra-callback",Vo="ra-initiator",Bo="data-exclude-field",Go="dls_last_auth",Yo="state_id",Zo="data-type",Xo="poll",Qo="webauthnCreate",er="submit",tr="polling";var nr,or,rr;function ir(e){return new URLSearchParams(window.location.search).get(e)}function sr(e){if(window.history.replaceState&&ir(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 ar(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 lr(e,t){const n=new URL(No);return n.pathname=((...e)=>e.join("/").replace(/\/+/g,"/"))(n.pathname,e,"v2-alpha",t),n.toString()}function cr(e,t){if(!Number.isNaN(e)&&!Number.isNaN(t))return e>t?nr.forward:e<t?nr.backward:void 0}!function(e){e.backward="backward",e.forward="forward"}(nr||(nr={}));const dr=()=>{const[e="",t=""]=(ir(Ko)||"").split("_");return{executionId:e,stepId:t}};function ur(){return/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}function hr(){sr(Ko)}const pr=e=>e.replace(/-./g,(e=>e[1].toUpperCase())),fr=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}},gr=null===(rr=null===(or=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===or?void 0:or.brands)||void 0===rr?void 0:rr.find((({brand:e,version:t})=>"Chromium"===e&&parseFloat(t))),vr=(e,t)=>e&&!t;var mr,br,wr,yr;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 Ir{constructor(e={},{updateOnlyOnChange:t=!0}={}){mr.set(this,void 0),br.set(this,{}),wr.set(this,0),yr.set(this,!1),this.update=e=>{const t="function"==typeof e?e(h(this,mr,"f")):e,n=Object.assign(Object.assign({},h(this,mr,"f")),t);if(!h(this,yr,"f")||!kr(h(this,mr,"f"),n)){const e=h(this,mr,"f");p(this,mr,n,"f"),Object.freeze(h(this,mr,"f")),setTimeout((()=>{Object.values(h(this,br,"f")).forEach((t=>t(n,e,((e,t)=>n=>e[n]!==t[n])(n,e))))}),0)}},p(this,mr,e,"f"),p(this,yr,t,"f")}get current(){return Object.assign({},h(this,mr,"f"))}subscribe(e){return p(this,wr,h(this,wr,"f")+1,"f"),h(this,br,"f")[h(this,wr,"f")]=e,h(this,wr,"f").toString()}unsubscribe(e){const t=!!h(this,br,"f")[e];return t&&delete h(this,br,"f")[e],t}unsubscribeAll(){return p(this,br,{},"f"),!0}}mr=new WeakMap,br=new WeakMap,wr=new WeakMap,yr=new WeakMap;const xr=(e,t)=>{Object.entries(t||{}).forEach((([t,n])=>{Array.from(e.querySelectorAll(`.descope-input[name="${t}"]:not([${Bo}])`)).forEach((e=>{e.value=n}))}))},Sr=fr((()=>u(void 0,void 0,void 0,(function*(){var e,t;if(!window.PublicKeyCredential||!PublicKeyCredential.isConditionalMediationAvailable||!PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)return console.warn("webauthn","Conditional UI is not supported"),!1;try{const n=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)))),o=108;return yield Promise.race([n,(100,new Promise(((e,t)=>{setTimeout((()=>{t(new Error("Promise timed out after 100 ms"))}),100)}))).catch((()=>gr()>=o))])}catch(e){return console.warn("webauthn","Conditional login check failed",e),!1}})))),jr={"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 Or(e){const t={};if(e)try{Object.assign(t,JSON.parse(localStorage.getItem(Go)))}catch(e){}return t}const Cr=document.createElement("template");var Er,Ar,Ur,_r,Rr,Pr,Tr,Lr,Mr,$r,qr,Wr,Dr,Fr,Nr,Kr,Jr,Hr,zr,Vr,Br,Gr,Yr,Zr,Xr,Qr,ei,ti,ni,oi,ri,ii,si,ai,li,ci,di,ui,hi;Cr.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 pi extends HTMLElement{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","theme","locale","debug","telemetryKey","redirect-url","auto-focus","prefer-biometrics"]}constructor(e){super(),Er.add(this),this.logger=console,Ar.set(this,!1),this.loggerWrapper={error:(e,t="")=>{this.logger.error(e,t,new Error),h(this,Er,"m",Yr).call(this,e,t)},warn:(e,t="")=>{this.logger.warn(e,t)},info:(e,t="",n={})=>{this.logger.info(e,t,n)}},Ur.set(this,new Ir({deferredRedirect:!1})),_r.set(this,new Ir),this.nextRequestStatus=new Ir({isLoading:!1}),Rr.set(this,void 0),Pr.set(this,{popstate:h(this,Er,"m",Wr).bind(this),visibilitychange:h(this,Er,"m",Dr).bind(this)}),Tr.set(this,void 0),Kr.set(this,fr((()=>u(this,void 0,void 0,(function*(){const e=lr(this.projectId,"config.json");try{const{body:t,headers:n}=yield ar(e,"json");return{projectConfig:t,executionContext:{geo:n["x-geo"]}}}catch(e){this.loggerWrapper.error("Cannot get config file","make sure that your projectId & flowId are correct")}return{}}))))),p(this,Tr,e,"f"),h(this,Er,"m",Lr).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 preferBiometrics(){var e;return"true"===(null!==(e=this.getAttribute("prefer-biometrics"))&&void 0!==e?e:"true")}getExecutionContext(){return u(this,void 0,void 0,(function*(){const{executionContext:e}=yield h(this,Kr,"f").call(this);return e}))}getFlowConfig(){var e,t;return u(this,void 0,void 0,(function*(){const{projectConfig:n}=yield h(this,Kr,"f").call(this),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,Er,"m",Mr).call(this))return void h(this,Er,"m",$r).call(this);h(this,Er,"m",qr).call(this),h(this,Er,"m",Hr).call(this),h(this,Er,"m",Jr).call(this),h(this,Er,"m",Zr).call(this);const{executionId:e,stepId:t,token:n,code:o,exchangeError:r,redirectAuthCallbackUrl:i,redirectAuthCodeChallenge:s,redirectAuthInitiator:a,oidcIdpStateId:l}=(()=>{const{executionId:e,stepId:t}=dr();(e||t)&&hr();const n=ir("t")||void 0;n&&sr("t");const o=ir(Jo)||void 0;o&&sr(Jo);const r=ir("err")||void 0;r&&sr("err");const{redirectAuthCodeChallenge:i,redirectAuthCallbackUrl:s,redirectAuthInitiator:a}={redirectAuthCodeChallenge:ir(Ho),redirectAuthCallbackUrl:ir(zo),redirectAuthInitiator:ir(Vo)};(i||s||a)&&(sr(Ho),sr(zo),sr(Vo));const l=ir(Yo);return l&&sr(Yo),{executionId:e,stepId:t,token:n,code:o,exchangeError:r,redirectAuthCodeChallenge:i,redirectAuthCallbackUrl:s,redirectAuthInitiator:a,oidcIdpStateId:l}})();window.addEventListener("popstate",h(this,Pr,"f").popstate),window.addEventListener("visibilitychange",h(this,Pr,"f").visibilitychange),h(this,Ur,"f").subscribe(h(this,Er,"m",Nr).bind(this)),h(this,_r,"f").subscribe(h(this,Er,"m",Gr).bind(this)),h(this,Ur,"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}),h(this,_r,"f").update({isDebug:this.debug}),p(this,Ar,!0,"f")}}))}disconnectedCallback(){h(this,Ur,"f").unsubscribeAll(),h(this,_r,"f").unsubscribeAll(),h(this,Er,"m",Br).call(this),window.removeEventListener("popstate",h(this,Pr,"f").popstate)}attributeChangedCallback(e,t,n){if(this.shadowRoot.isConnected&&h(this,Ar,"f")&&t!==n&&pi.observedAttributes.includes(e)){h(this,Er,"m",qr).call(this);const o=null===t;h(this,Ur,"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,_r,"f").update({isDebug:this.debug})}}}Ar=new WeakMap,Ur=new WeakMap,_r=new WeakMap,Rr=new WeakMap,Pr=new WeakMap,Tr=new WeakMap,Kr=new WeakMap,Er=new WeakSet,Lr=function(){this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Cr.content.cloneNode(!0)),this.rootElement=this.shadowRoot.querySelector("#wc-root")},Mr=function(){return!this.shadowRoot.host.closest("form")&&ur()},$r=function(){const e=this.shadowRoot.host,t=document.createElement("form");e.parentElement.appendChild(t),t.appendChild(e)},qr=function(){const e=["base-url","tenant","theme","locale","debug","telemetryKey","redirect-url","auto-focus","prefer-biometrics"];if(pi.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')},Wr=function(){const{stepId:e,executionId:t}=dr();h(this,Ur,"f").update({stepId:e,executionId:t})},Dr=function(){document.hidden||setTimeout((()=>{h(this,Ur,"f").update({deferredRedirect:!1})}),300)},Fr=function(e,t,n){const o=n||void 0,r=!!o;this.sdk=Ao(Object.assign(Object.assign({persistTokens:!0},pi.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})}}))}))},Nr=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,Er,"m",Fr).call(this,t,o,r)}h(this,Tr,"f").call(this,e)}))},Jr=function(){var e,t,n,o;return u(this,void 0,void 0,(function*(){const{projectConfig:r}=yield h(this,Kr,"f").call(this);null===(o=null===(n=null===(t=null===(e=null==r?void 0:r.cssTemplate)||void 0===e?void 0:e[this.theme])||void 0===t?void 0:t.typography)||void 0===n?void 0:n.fontFamilies)||void 0===o||o.forEach((e=>(e=>{if(!e)return;const t=document.createElement("link");t.href=e,t.rel="stylesheet",document.head.appendChild(t)})(e.url)))}))},Hr=function(){h(this,Er,"m",zr).call(this),h(this,Er,"m",Vr).call(this)},zr=function(){return u(this,void 0,void 0,(function*(){const e=document.createElement("style"),t=lr(this.projectId,"theme.css");try{const{body:n}=yield ar(t,"text");e.innerText=n}catch(e){this.loggerWrapper.error("Cannot fetch theme file","make sure that your projectId & flowId are correct")}this.shadowRoot.appendChild(e)}))},Vr=function(){this.rootElement.setAttribute("data-theme",this.theme)},Br=function(){var e;null===(e=h(this,Rr,"f"))||void 0===e||e.remove(),p(this,Rr,null,"f")},Gr=function({isDebug:e}){return u(this,void 0,void 0,(function*(){e?(yield Promise.resolve().then((function(){return Ai})),p(this,Rr,document.createElement("descope-debugger"),"f"),Object.assign(h(this,Rr,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),document.body.appendChild(h(this,Rr,"f"))):h(this,Er,"m",Br).call(this)}))},Yr=function(e,t){var n;e&&this.debug&&(null===(n=h(this,Rr,"f"))||void 0===n||n.updateData({title:e,description:t}))},Zr=function(){this.rootElement.onkeydown=e=>{if("Enter"!==e.key)return;e.preventDefault();const t=this.rootElement.querySelectorAll("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()}},pi.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"2.9.0"}};class fi extends pi{static set sdkConfigOverrides(e){pi.sdkConfigOverrides=e}constructor(){const e=new Ir;super(e.update.bind(e)),Xr.add(this),this.stepState=new Ir({},{updateOnlyOnChange:!1}),Qr.set(this,void 0),ei.set(this,null),ti.set(this,(()=>{clearInterval(h(this,Qr,"f")),p(this,Qr,null,"f")})),ni.set(this,(e=>{var t,n,o,r,i,s,a,l,c;if(!(null==e?void 0:e.ok)){h(this,ti,"f").call(this),h(this,Xr,"m",hi).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)&&Fo&&localStorage.setItem(Go,JSON.stringify(e))}(f),h(this,ti,"f").call(this),void h(this,Xr,"m",hi).call(this,"success",p);const{executionId:g,stepId:v,stepName:m,action:b,screen:w,redirect:y,webauthn:k,error:I}=e.data;b!==Xo?(this.loggerWrapper.info(`Step "${m||`#${v}`}" is ${u}`,"",{screen:w,status:u,stepId:v,stepName:m,action:b,error:I}),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==k?void 0:k.transactionId,webauthnOptions:null==k?void 0:k.options})):this.flowState.update({action:b})})),oi.set(this,fr((()=>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(){super.disconnectedCallback(),this.flowState.unsubscribeAll(),this.stepState.unsubscribeAll()}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 ar(t,"text");return e}catch(n){this.loggerWrapper.error(`Failed to fetch html page from ${t}. Fallback to url ${e}`,n)}try{const{body:t}=yield ar(e,"text");return t}catch(t){this.loggerWrapper.error(`Failed to fetch html page from ${e}`,t)}return null}))}onFlowChange(e,t,n){var o,r,i,s,a,l;return u(this,void 0,void 0,(function*(){const{projectId:c,flowId:d,tenant:f,stepId:g,executionId:v,action:m,screenId:b,screenState:w,redirectTo:y,redirectUrl:k,token:I,code:x,exchangeError:S,webauthnTransactionId:j,webauthnOptions:O,redirectAuthCodeChallenge:C,redirectAuthCallbackUrl:E,redirectAuthInitiator:A,oidcIdpStateId:U,locale:_}=e;let R,P;h(this,Qr,"f")&&h(this,ti,"f").call(this);const T=this.sdk.getLastUserLoginId(),L=yield this.getFlowConfig(),M=E&&C?{callbackUrl:E,codeChallenge:C}:void 0;if(!v&&(L.conditions?({startScreenId:R,conditionInteractionId:P}=((e,t)=>{const n=null==t?void 0:t.find((({key:t,operator:n})=>{var o;if("ELSE"===t)return!0;const r=null===(o=jr[t])||void 0===o?void 0:o[n];return!!(null==r?void 0:r(e))}));return n?{startScreenId:n.met.screenId,conditionInteractionId:n.met.interactionId}:{}})({loginId:T,code:x,token:I},L.conditions)):L.condition?({startScreenId:R,conditionInteractionId:P}=((e,t)=>{var n;const o=null===(n=jr[null==e?void 0:e.key])||void 0===n?void 0:n[e.operator];if(!o)return{};const r=o(t)?e.met:e.unmet;return{startScreenId:null==r?void 0:r.screenId,conditionInteractionId:null==r?void 0:r.interactionId}})(L.condition,{loginId:T,code:x,token:I})):R=L.startScreenId,!vr(R,U))){const e={};let t=!1;x&&(t=!0,e.exchangeCode=x,e.idpInitiated=!0),I&&(t=!0,e.token=I);const n=yield this.sdk.flow.start(d,Object.assign(Object.assign({tenant:f,redirectAuth:M,oidcIdpStateId:U},k&&{redirectUrl:k}),{lastAuth:Or(T)}),P,"",t?e:void 0,L.version);return h(this,ni,"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(v&&(n("token")&&I||n("code")&&x||n("exchangeError")&&S)){const e=yield this.sdk.flow.next(v,g,er,{token:I,exchangeCode:x,exchangeError:S},L.version);return h(this,ni,"f").call(this,e),void this.flowState.update({token:void 0,code:void 0,exchangeError:void 0})}if("redirect"===m&&(n("redirectTo")||n("deferredRedirect")))return y?"android"===A&&document.hidden?void this.flowState.update({deferredRedirect:!0}):void window.location.assign(y):void this.loggerWrapper.error("Did not get redirect url");if(m===Qo||"webauthnGet"===m){if(!j||!O)return void this.loggerWrapper.error("Did not get webauthn transaction id or options");let e,t,n=O;if(this.preferBiometrics&&m===Qo&&ur()&&(yield null===(i=null===(r=window.PublicKeyCredential)||void 0===r?void 0:r.isUserVerifyingPlatformAuthenticatorAvailable)||void 0===i?void 0:i.call(r)))try{const e=JSON.parse(n);e.publicKey&&((a=e.publicKey).authenticatorSelection||(a.authenticatorSelection={}),(l=e.publicKey.authenticatorSelection).authenticatorAttachment||(l.authenticatorAttachment="platform"),n=JSON.stringify(e))}catch(e){this.loggerWrapper.info("Failed to modify webauthn create options")}null===(s=h(this,ei,"f"))||void 0===s||s.abort(),p(this,ei,null,"f");try{e=m===Qo?yield this.sdk.webauthn.helpers.create(n):yield this.sdk.webauthn.helpers.get(n)}catch(e){if("NotAllowedError"!==e.name)return void this.loggerWrapper.error(e.message);t=!0}const o=yield this.sdk.flow.next(v,g,er,{transactionId:j,response:e,cancelWebauthn:t},L.version);h(this,ni,"f").call(this,o)}if(m===Xo&&p(this,Qr,setInterval((()=>u(this,void 0,void 0,(function*(){const e=yield this.sdk.flow.next(v,g,tr,{},L.version);h(this,ni,"f").call(this,e)}))),2e3),"f"),!b&&!R)return void this.loggerWrapper.warn("No screen was found to show");const $=R||b,q=yield this.getHtmlFilenameWithLocale(_,$),W={direction:cr(+g,+t.stepId),screenState:Object.assign(Object.assign({},w),{lastAuth:{loginId:T,name:this.sdk.getLastUserDisplayName()||T}}),htmlUrl:lr(c,`${$}.html`),htmlLocaleUrl:q&&lr(c,q)},D=Or(T);vr(R,U)?W.next=(e,t)=>this.sdk.flow.start(d,Object.assign({tenant:f,redirectAuth:M,oidcIdpStateId:U,lastAuth:D},k&&{redirectUrl:k}),P,e,Object.assign(Object.assign(Object.assign({},t),x&&{exchangeCode:x,idpInitiated:!0}),I&&{token:I}),L.version):(n("projectId")||n("baseUrl")||n("executionId")||n("stepId"))&&(W.next=(...e)=>this.sdk.flow.next(v,g,...e)),this.stepState.update(W)}))}onStepChange(e,t){var n;return u(this,void 0,void 0,(function*(){const{htmlUrl:o,htmlLocaleUrl:r,direction:i,next:s,screenState:a}=e,l=document.createElement("template");l.innerHTML=yield this.getPageContent(o,r);const c=l.content.cloneNode(!0),d=((e,t)=>{var n;const o=Array.from(e.querySelectorAll("script[data-id]")).map((n=>{var o;const r=n.getAttribute("data-id"),i=null===(o=e.getElementById(r))||void 0===o?void 0:o.innerHTML,s=Function(i).bind(n.previousSibling,t);return n.remove(),s}));return null===(n=e.querySelector("scripts"))||void 0===n||n.remove(),o})(c,yield this.getExecutionContext());this.sdk.webauthn.helpers.isSupported()?yield h(this,Xr,"m",ii).call(this,c,s):c.querySelectorAll(`button[${Zo}="biometrics"]`).forEach((e=>e.setAttribute("disabled","true"))),((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(`[${Zo}="${t}"]`).forEach((e=>{e.textContent=n,e.classList[n?"remove":"add"]("hide")}))})(e,"error-message",i),xr(e,null==t?void 0:t.inputs),xr(e,null==t?void 0:t.form),((e,t)=>{e.querySelectorAll(`[${Zo}="totp-link"]`).forEach((e=>{e.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)})(c,a,this.errorTransformer,this.loggerWrapper),((e,t)=>{var n;t&&(null===(n=null==e?void 0:e.style)||void 0===n||n.setProperty("--totp-image",`url(data:image/jpg;base64,${t})`))})(c.querySelector("div"),null===(n=null==a?void 0:a.totp)||void 0===n?void 0:n.image);const p=()=>u(this,void 0,void 0,(function*(){try{d.forEach((e=>{e()}))}catch(e){this.loggerWrapper.error(e.message)}this.rootElement.replaceChildren(c);const e=!t.htmlUrl;if(((e,t,n)=>{if(!0===t||"skipFirstScreen"===t&&!n){const t=e.querySelector('input:not([aria-hidden="true"])');null==t||t.focus()}})(this.rootElement,this.autoFocus,e),h(this,Xr,"m",di).call(this,s),h(this,Xr,"m",hi).call(this,"page-updated",{}),this.rootElement.querySelector(`[${Zo}="polling"]`)){const e=yield s(tr,{});h(this,ni,"f").call(this,e)}}));i?h(this,Xr,"m",ui).call(this,p,i):p()}))}}Qr=new WeakMap,ei=new WeakMap,ti=new WeakMap,ni=new WeakMap,oi=new WeakMap,Xr=new WeakSet,ri=function(e){const t=e.name;if(!["email"].includes(t)){const n=`user-${t}`;e.name=n,e.addEventListener("input",(()=>{e.name=e.value?t:n}))}},ii=function(e,t){var n;return u(this,void 0,void 0,(function*(){null===(n=h(this,ei,"f"))||void 0===n||n.abort();const o=e.querySelector('input[autocomplete="webauthn"]');if(o&&(yield Sr())){const{options:e,transactionId:n}=(yield h(this,oi,"f").call(this))||{};e&&n&&(h(this,Xr,"m",ri).call(this,o),p(this,ei,new AbortController,"f"),this.sdk.webauthn.helpers.conditional(e,h(this,ei,"f")).then((e=>u(this,void 0,void 0,(function*(){const r=yield t(o.id,{transactionId:n,response:e});h(this,ni,"f").call(this,r)})))).catch((e=>{"AbortError"!==e.name&&this.loggerWrapper.error("Conditional login failed",e.message)})))}}))},si=function(){return Array.from(this.shadowRoot.querySelectorAll(".descope-input")).every((e=>(e.reportValidity(),e.checkValidity())))},ai=function(){return u(this,void 0,void 0,(function*(){const e=Array.from(this.shadowRoot.querySelectorAll(`.descope-input[name]:not([${Bo}])`)),t=yield Promise.all(e.map((e=>u(this,void 0,void 0,(function*(){const t=yield(e=>new Promise((t=>{var n;switch(e.type){case"checkbox":t(e.checked);break;case"file":{const o=new FileReader;(null===(n=e.files)||void 0===n?void 0:n.length)?(o.onload=e=>{const n=e.target.result;t(n)},o.readAsDataURL(e.files[0])):t(null);break}default:t(e.value)}})))(e);return{name:e.name,value:t}})))));return t.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.name]:t.value})),{})}))},li=function(e){const t=this.nextRequestStatus.subscribe((({isLoading:n})=>{var o,r;n?null===(o=null==e?void 0:e.classList)||void 0===o||o.add("loading"):(this.nextRequestStatus.unsubscribe(t),null===(r=null==e?void 0:e.classList)||void 0===r||r.remove("loading"))}))},ci=function(e,t){return u(this,void 0,void 0,(function*(){if(e.formNoValidate||h(this,Xr,"m",si).call(this)){const o=null==e?void 0:e.getAttribute("id");h(this,Xr,"m",li).call(this,e);const r=yield h(this,Xr,"m",ai).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=Object.assign(Object.assign(Object.assign({},i),r),{origin:window.location.origin}),a=yield t(o,s);h(this,ni,"f").call(this,a)}var n}))},di=function(e){this.rootElement.querySelectorAll("button:not([data-exclude-next])").forEach((t=>{t.onclick=()=>{h(this,Xr,"m",ci).call(this,t,e)}}))},ui=function(e,t){this.rootElement.addEventListener("transitionend",(()=>{this.rootElement.classList.remove("fade-out"),e()}),{once:!0});const n=t===nr.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")},hi=function(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t}))},customElements.define("descope-wc",fi);var gi=Object.freeze({__proto__:null,default:fi});const vi=(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 mi,bi,wi,yi,ki,Ii,xi,Si,ji,Oi;const Ci=document.createElement("template");Ci.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 } \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 Ei extends HTMLElement{constructor(){super(),mi.add(this),bi.set(this,new Ir({messages:[]})),wi.set(this,void 0),yi.set(this,void 0),ki.set(this,void 0),Ii.set(this,{resize:h(this,mi,"m",Oi).bind(this)}),this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Ci.content.cloneNode(!0)),p(this,wi,this.shadowRoot.querySelector(".debugger"),"f"),p(this,yi,h(this,wi,"f").querySelector(".content"),"f"),p(this,ki,h(this,wi,"f").querySelector(".header"),"f")}updateData(e){h(this,bi,"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]=vi(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,wi,"f"),h(this,ki,"f"),{top:"all",bottom:100,left:100,right:100}),window.addEventListener("resize",h(this,Ii,"f").resize),(e=h(this,wi,"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,wi,"f").onresize=h(this,mi,"m",ji).bind(this),h(this,bi,"f").subscribe(h(this,mi,"m",xi).bind(this))}disconnectedCallback(){h(this,bi,"f").unsubscribeAll(),window.removeEventListener("resize",h(this,Ii,"f").resize)}}bi=new WeakMap,wi=new WeakMap,yi=new WeakMap,ki=new WeakMap,Ii=new WeakMap,mi=new WeakSet,xi=function(e){h(this,mi,"m",Si).call(this,e),h(this,mi,"m",ji).call(this)},Si=function(e){h(this,yi,"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("")},ji=function(){h(this,yi,"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)}))},Oi=function(){const[e,t]=vi(h(this,wi,"f"),Number.parseInt(h(this,wi,"f").style.left,10),Number.parseInt(h(this,wi,"f").style.top,10),{top:"all",bottom:100,left:100,right:100});h(this,wi,"f").style.top=`${t}px`,h(this,wi,"f").style.left=`${e}px`},customElements.define("descope-debugger",Ei);var Ai=Object.freeze({__proto__:null,default:Ei});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 _o({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]),k=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:k},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=To,e.getJwtRoles=Lo,e.getRefreshToken=Po,e.getSessionToken=Ro,e.refresh=(e=Po())=>Uo?.refresh(e),e.useDescope=()=>{const{sdk:e}=qo();return t.useMemo((()=>e||new Proxy(_o({projectId:"dummy"}),Do)),[e])},e.useSession=()=>{const{session:e,isSessionLoading:n,fetchSession:o,isSessionFetched:r}=qo(),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}=qo(),[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