@descope/web-js-sdk 0.1.0-alpha.6 → 0.1.0-alpha.8

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";var e=require("tslib"),t=require("@descope/core-js-sdk"),s=require("@fingerprintjs/fingerprintjs-pro"),n=require("js-cookie");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=a(t),r=a(n);const o=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],c=e=>{const t=s.load({apiKey:e||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=o("vsid")),e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem("vsid",e);const s=await t,n=await s.get({linkedId:e});sessionStorage.setItem("vrid",n.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var l,u,d,g,h;const p=e=>Object.assign({},e);class f{constructor(t){l.add(this),u.set(this,void 0),d.set(this,{}),g.set(this,0),e.__classPrivateFieldSet(this,u,t,"f")}get current(){return p(e.__classPrivateFieldGet(this,u,"f"))}update(t){const s=t;if(!((e,t)=>{const s=e&&Object.getOwnPropertyNames(e)||[],n=t&&Object.getOwnPropertyNames(t)||[];if(s.length!==n.length)return!1;for(let n=0;n<s.length;n+=1){const a=s[n];if(e[a]!==t[a])return!1}return!0})(e.__classPrivateFieldGet(this,u,"f"),s)){const t=e.__classPrivateFieldGet(this,u,"f");e.__classPrivateFieldSet(this,u,s,"f"),Object.freeze(e.__classPrivateFieldGet(this,u,"f")),setTimeout((()=>{Object.values(e.__classPrivateFieldGet(this,d,"f")).forEach((e=>e(p(s),t)))}),0)}}subscribe(t){e.__classPrivateFieldSet(this,g,e.__classPrivateFieldGet(this,g,"f")+1,"f"),e.__classPrivateFieldGet(this,d,"f")[e.__classPrivateFieldGet(this,g,"f")]=t;const s=e.__classPrivateFieldGet(this,g,"f");return()=>e.__classPrivateFieldGet(this,l,"m",h).call(this,s.toString())}unsubscribeAll(){e.__classPrivateFieldSet(this,d,{},"f")}}u=new WeakMap,d=new WeakMap,g=new WeakMap,l=new WeakSet,h=function(t){!!e.__classPrivateFieldGet(this,d,"f")[t]&&delete e.__classPrivateFieldGet(this,d,"f")[t]};let w=[];function b(e,t,s){const n=function(e){const t=e.split(".");try{if(3===t.length){const t=JSON.parse(window.atob(e.split(".")[1]));if(t.exp)return new Date(1e3*t.exp)}}catch(e){}return null}(t);if(n){let t;for(;t=w.pop();)clearTimeout(t);const a=n.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(s)}),a);w.push(i)}}function v(e,t,s){!function(e,{cookiePath:t,cookieDomain:s,cookieExpiration:n}){e&&r.default.set("DS",e,{path:t,domain:s,expires:n,sameSite:"None",secure:!0})}(e,s),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function S(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function _(e){const t=function(e){var t;const s=JSON.parse(e);return s.publicKey.challenge=O(s.publicKey.challenge),s.publicKey.user.id=O(s.publicKey.user.id),null===(t=s.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=O(e.id)})),s}(e),s=await navigator.credentials.create(t);return n=s,JSON.stringify(Object.assign(Object.assign({},n),{rawId:m(n.rawId),response:Object.assign(Object.assign({},n.response),{attestationObject:m(n.response.attestationObject),clientDataJSON:m(n.response.clientDataJSON)})}));var n}async function y(e){const t=function(e){var t;const s=JSON.parse(e);return s.publicKey.challenge=O(s.publicKey.challenge),null===(t=s.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=O(e.id)})),s}(e),s=await navigator.credentials.get(t);return n=s,JSON.stringify(Object.assign(Object.assign({},n),{rawId:m(n.rawId),response:Object.assign(Object.assign({},n.response),{authenticatorData:m(n.response.authenticatorData),clientDataJSON:m(n.response.clientDataJSON),signature:m(n.response.signature),userHandle:n.response.userHandle?m(n.response.userHandle):void 0})}));var n}function O(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function m(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}const k="undefined"!=typeof window;module.exports=t=>{var{autoRefresh:s=!0,persistTokens:n=!0}=t,a=e.__rest(t,["autoRefresh","persistTokens"]);k?c(a.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const o=a;let l,u;const d=new f({sessionToken:""}),g=new f({});o.hooks={beforeRequest:e=>null==l?void 0:l(e),afterRequest:(e,t)=>null==u?void 0:u(e,t)};const h=i.default(o),p=Object.assign(Object.assign({},h),{webauthn:(w=h,{async signUp(e,t){const s=await w.webauthn.signUp.start(e,window.location.origin,t),n=await _(s.data.options);return await w.webauthn.signUp.finish(s.data.transactionId,n)},async signIn(e){const t=await w.webauthn.signIn.start(e,window.location.origin),s=await y(t.data.options);return await w.webauthn.signIn.finish(t.data.transactionId,s)},async signUpOrIn(e){var t;const s=await w.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=s.data)||void 0===t?void 0:t.create){const e=await _(s.data.options);return await w.webauthn.signUp.finish(s.data.transactionId,e)}{const e=await y(s.data.options);return await w.webauthn.signIn.finish(s.data.transactionId,e)}},async update(e,t){const s=await w.webauthn.update.start(e,window.location.origin,t),n=await _(s.data.options);return await w.webauthn.update.finish(s.data.transactionId,n)},helpers:{create:_,get:y}}),onSessionTokenChange:e=>{var t;const s=null===(t=d.current)||void 0===t?void 0:t.sessionToken;return s&&e(s),d.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=g.current;return t&&Object.entries(t).length>0&&e(t),g.subscribe((t=>{e(t)}))}});var w;return s&&(p.logout=(...e)=>{const t=S(),s=[(null==e?void 0:e.shift())||t,...e],n=h.logout(...s);return localStorage&&localStorage.removeItem("DSR"),r.default.remove("DS"),n}),l=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""})),!e.token&&n&&(e.token=S()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.6"}),e},(s||n)&&(u=(t,a)=>{!async function(t,s,n,a){try{if(401===s.status)return n.sessionToken.update({sessionToken:""}),void n.user.update({});const i=await(null==s?void 0:s.json());if(i){const s=function(e){return(null==e?void 0:e.authInfo)||e||{}}(i),{sessionJwt:r,refreshJwt:o,user:c}=s,l=e.__rest(s,["sessionJwt","refreshJwt","user"]);a.persistTokens&&v(r,o,l),r&&n.sessionToken.update({sessionToken:r}),c&&n.user.update(c),r&&o&&a.autoRefresh&&b(t,r,o)}}catch(e){console.error("Could not set tokens from body",e)}}(p.refresh,a,{sessionToken:d,user:g},{autoRefresh:s,persistTokens:n})}),s&&p.refresh(),p};
1
+ "use strict";var e=require("tslib"),t=require("@descope/core-js-sdk"),s=require("@fingerprintjs/fingerprintjs-pro"),n=require("js-cookie");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=a(t),r=a(n);const o=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],c=e=>{const t=s.load({apiKey:e||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=o("vsid")),e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem("vsid",e);const s=await t,n=await s.get({linkedId:e});sessionStorage.setItem("vrid",n.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var l,u,d,g,p;const f=e=>Object.assign({},e);class h{constructor(t){l.add(this),u.set(this,void 0),d.set(this,{}),g.set(this,0),e.__classPrivateFieldSet(this,u,t,"f")}get current(){return f(e.__classPrivateFieldGet(this,u,"f"))}update(t){const s=t;if(!((e,t)=>{const s=e&&Object.getOwnPropertyNames(e)||[],n=t&&Object.getOwnPropertyNames(t)||[];if(s.length!==n.length)return!1;for(let n=0;n<s.length;n+=1){const a=s[n];if(e[a]!==t[a])return!1}return!0})(e.__classPrivateFieldGet(this,u,"f"),s)){const t=e.__classPrivateFieldGet(this,u,"f");e.__classPrivateFieldSet(this,u,s,"f"),Object.freeze(e.__classPrivateFieldGet(this,u,"f")),setTimeout((()=>{Object.values(e.__classPrivateFieldGet(this,d,"f")).forEach((e=>e(f(s),t)))}),0)}}subscribe(t){e.__classPrivateFieldSet(this,g,e.__classPrivateFieldGet(this,g,"f")+1,"f"),e.__classPrivateFieldGet(this,d,"f")[e.__classPrivateFieldGet(this,g,"f")]=t;const s=e.__classPrivateFieldGet(this,g,"f");return()=>e.__classPrivateFieldGet(this,l,"m",p).call(this,s.toString())}unsubscribeAll(){e.__classPrivateFieldSet(this,d,{},"f")}}u=new WeakMap,d=new WeakMap,g=new WeakMap,l=new WeakSet,p=function(t){!!e.__classPrivateFieldGet(this,d,"f")[t]&&delete e.__classPrivateFieldGet(this,d,"f")[t]};let w=[];function v(e,t,s){const n=function(e){const t=e.split(".");try{if(3===t.length){const t=JSON.parse(window.atob(e.split(".")[1]));if(t.exp)return new Date(1e3*t.exp)}}catch(e){}return null}(t);if(n){let t;for(;t=w.pop();)clearTimeout(t);const a=n.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(s)}),a);w.push(i)}}function b(e,t,s){!function(e,{cookiePath:t,cookieDomain:s,cookieExpiration:n}){e&&r.default.set("DS",e,{path:t,domain:s,expires:n,sameSite:"None",secure:!0})}(e,s),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function S(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function _(e){const t=function(e){var t;const s=JSON.parse(e);return s.publicKey.challenge=O(s.publicKey.challenge),s.publicKey.user.id=O(s.publicKey.user.id),null===(t=s.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=O(e.id)})),s}(e),s=await navigator.credentials.create(t);return n=s,JSON.stringify(Object.assign(Object.assign({},n),{rawId:m(n.rawId),response:Object.assign(Object.assign({},n.response),{attestationObject:m(n.response.attestationObject),clientDataJSON:m(n.response.clientDataJSON)})}));var n}async function y(e){const t=function(e){var t;const s=JSON.parse(e);return s.publicKey.challenge=O(s.publicKey.challenge),null===(t=s.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=O(e.id)})),s}(e),s=await navigator.credentials.get(t);return n=s,JSON.stringify(Object.assign(Object.assign({},n),{rawId:m(n.rawId),response:Object.assign(Object.assign({},n.response),{authenticatorData:m(n.response.authenticatorData),clientDataJSON:m(n.response.clientDataJSON),signature:m(n.response.signature),userHandle:n.response.userHandle?m(n.response.userHandle):void 0})}));var n}function O(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function m(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}const k="undefined"!=typeof window;module.exports=t=>{var{autoRefresh:s=!0,persistTokens:n=!0}=t,a=e.__rest(t,["autoRefresh","persistTokens"]);k?c(a.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const o=a;let l,u;const d=new h({sessionToken:""}),g=new h({});o.hooks={beforeRequest:e=>null==l?void 0:l(e),afterRequest:(e,t)=>null==u?void 0:u(e,t)};const p=i.default(o),f=Object.assign(Object.assign({},p),{webauthn:(w=p,{async signUp(e,t){const s=await w.webauthn.signUp.start(e,window.location.origin,t),n=await _(s.data.options);return await w.webauthn.signUp.finish(s.data.transactionId,n)},async signIn(e){const t=await w.webauthn.signIn.start(e,window.location.origin),s=await y(t.data.options);return await w.webauthn.signIn.finish(t.data.transactionId,s)},async signUpOrIn(e){var t;const s=await w.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=s.data)||void 0===t?void 0:t.create){const e=await _(s.data.options);return await w.webauthn.signUp.finish(s.data.transactionId,e)}{const e=await y(s.data.options);return await w.webauthn.signIn.finish(s.data.transactionId,e)}},async update(e,t){const s=await w.webauthn.update.start(e,window.location.origin,t),n=await _(s.data.options);return await w.webauthn.update.finish(s.data.transactionId,n)},helpers:{create:_,get:y}}),onSessionTokenChange:e=>{var t;const s=null===(t=d.current)||void 0===t?void 0:t.sessionToken;return s&&e(s),d.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=g.current;return t&&Object.entries(t).length>0&&e(t),g.subscribe((t=>{e(t)}))}});var w;return s&&["logout","logoutAll"].forEach((e=>{const t=p[e];f[e]=(...e)=>{const s=S(),n=[(null==e?void 0:e.shift())||s,...e],a=t(...n);return localStorage&&localStorage.removeItem("DSR"),r.default.remove("DS"),d.update({sessionToken:""}),a}})),l=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""})),!e.token&&n&&(e.token=S()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.8"}),e},f.me=async(...e)=>{var t;const s=await p.me(...e);if(s.ok){const e=await(null===(t=s.response)||void 0===t?void 0:t.clone().json());g.update(e)}return s},(s||n)&&(u=(t,a)=>{!async function(t,s,n,a){try{if(401===s.status)return n.sessionToken.update({sessionToken:""}),void n.user.update({});const i=await(null==s?void 0:s.json());if(i){const s=function(e){return(null==e?void 0:e.authInfo)||e||{}}(i),{sessionJwt:r,refreshJwt:o,user:c}=s,l=e.__rest(s,["sessionJwt","refreshJwt","user"]);a.persistTokens&&b(r,o,l),r&&n.sessionToken.update({sessionToken:r}),c&&n.user.update(c),r&&o&&a.autoRefresh&&v(t,r,o)}}catch(e){console.error("Could not set tokens from body",e)}}(f.refresh,a,{sessionToken:d,user:g},{autoRefresh:s,persistTokens:n})}),s&&S()&&f.refresh(),f};
2
2
  //# sourceMappingURL=index.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../../src/constants.ts","../../src/helpers.ts","../../src/fp.ts","../../src/state.ts","../../src/tokens.ts","../../src/webauthn.ts","../../src/index.ts"],"sourcesContent":["/** Fingerprint.js identity key */\nexport const FP_KEY = 'A9aCLRHzKCv3uL69oqDr';\n/** Session ID for visitor */\nexport const VISITOR_SESSION_ID_PARAM = 'vsid';\n/** Request ID for visitor */\nexport const VISITOR_REQUEST_ID_PARAM = 'vrid';\n","/** Wrapper around URLSearchParams that receives prop name as string */\nexport const getQueryParams = () => {\n\tconst params = new Proxy(new URLSearchParams(window.location.search), {\n\t\tget: (searchParams, prop) => searchParams.get(prop.toString())\n\t});\n\n\treturn params;\n};\n\n/** Returns specific URL query param */\nexport const getQueryParam = (param: string) => {\n\tconst params = getQueryParams();\n\n\treturn params[param];\n};\n\n/** Generate UUID based on current time and some randomness */\nexport const generateUUID = () => {\n\t// return alphanumeric, sortable uuid of 27 characters\n\treturn (\n\t\tDate.now().toString(36) +\n\t\tMath.random().toString(36).substring(2) + // removing '0.' prefix\n\t\tMath.random().toString(36).substring(2)\n\t).substring(0, 27);\n};\n","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { getQueryParam, generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = getQueryParam(VISITOR_SESSION_ID_PARAM);\n\t\t\t\t}\n\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = generateUUID();\n\t\t\t\t}\n\n\t\t\t\tsessionStorage.setItem(VISITOR_SESSION_ID_PARAM, sessionId);\n\n\t\t\t\tconst agent = await agentP;\n\t\t\t\tconst res = await agent.get({ linkedId: sessionId });\n\t\t\t\tsessionStorage.setItem(VISITOR_REQUEST_ID_PARAM, res.requestId);\n\t\t\t} catch (ex) {\n\t\t\t\t// istanbul ignore next\n\t\t\t\tif (global.FB_DEBUG) {\n\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\tconsole.error(ex);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n};\n\nexport default fp;\n","// supported state types are string and object\ntype StateObject = Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tconst aProperties = (a && Object.getOwnPropertyNames(a)) || [];\n\tconst bProperties = (b && Object.getOwnPropertyNames(b)) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\nconst clone = (state: StateObject): StateObject => {\n\treturn { ...state };\n};\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n\t\treturn clone(this.#state) as T;\n\t}\n\n\tupdate(newState: T) {\n\t\tconst nextState: T = newState;\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) => cb(clone(nextState) as T, prevState));\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\n\t\t// return unsubscribe function\n\t\tconst currentToken = this.#token;\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (state: T, prevState?: T) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(\n\tsessionJwt: string,\n\trefreshJwt: string,\n\tcookieParams: Partial<JWTResponse>\n) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || ({} as JWTResponse);\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token\n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(\n\trefreshFn: RefreshFn,\n\tres: Response,\n\tstate: SdkState,\n\toptions: TokensOptions\n) {\n\ttry {\n\t\tif (res.status === 401) {\n\t\t\t// reset state if got unauthorized status code\n\t\t\tstate.sessionToken.update({ sessionToken: '' });\n\t\t\tstate.user.update({});\n\t\t\treturn;\n\t\t}\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tif (sessionJwt) {\n\t\t\t\tstate.sessionToken.update({ sessionToken: sessionJwt });\n\t\t\t}\n\t\t\tif (user) {\n\t\t\t\tstate.user.update(user);\n\t\t\t}\n\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { CoreSdk } from './types';\n\n/** Constructs a higher level WebAuthn API that wraps the functions from code-js-sdk */\nconst createWebAuthn = (sdk: CoreSdk) => ({\n\tasync signUp(identifier: string, name: string) {\n\t\tconst startResponse = await sdk.webauthn.signUp.start(identifier, window.location.origin, name);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signIn.start(identifier, window.location.origin);\n\t\tconst getResponse = await get(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tgetResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signUpOrIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signUpOrIn.start(identifier, window.location.origin);\n\t\tif (startResponse.data?.create) {\n\t\t\tconst createResponse = await create(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tcreateResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t} else {\n\t\t\tconst getResponse = await get(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tgetResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t}\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(\n\t\t\tidentifier,\n\t\t\twindow.location.origin,\n\t\t\ttoken\n\t\t);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\t/** Helper functions for working with WebAuthn browser APIs using JSON data */\n\thelpers: {\n\t\t/** Wraps the navigation.credentials.create call to translate JSON inputs and outputs */\n\t\tcreate,\n\t\t/** Wraps the navigation.credentials.get call to translate JSON inputs and outputs */\n\t\tget\n\t}\n});\n\n// Helpers functions\n\nasync function create(options: string): Promise<string> {\n\tconst createOptions = decodeCreateOptions(options);\n\tconst createResponse = (await navigator.credentials.create(\n\t\tcreateOptions\n\t)) as AttestationPublicKeyCredential;\n\treturn encodeCreateResponse(createResponse);\n}\n\nasync function get(options: string): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAttestationResponse;\n};\n\nfunction decodeCreateOptions(value: string): CredentialCreationOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.user.id = decodeBase64Url(options.publicKey.user.id);\n\toptions.publicKey.excludeCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeCreateResponse(credential: AttestationPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tattestationObject: encodeBase64Url(credential.response.attestationObject),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON)\n\t\t}\n\t});\n}\n\n// Conversion of data structures for Get/Assertion/Login ceremony\n\ntype AssertionPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAssertionResponse;\n};\n\nfunction decodeGetOptions(value: string): CredentialRequestOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.allowCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeGetResponse(credential: AssertionPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tauthenticatorData: encodeBase64Url(credential.response.authenticatorData),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t\tsignature: encodeBase64Url(credential.response.signature),\n\t\t\tuserHandle: credential.response.userHandle\n\t\t\t\t? encodeBase64Url(credential.response.userHandle)\n\t\t\t\t: undefined\n\t\t}\n\t});\n}\n\n// Conversion between ArrayBuffers and Base64Url strings\n\nfunction decodeBase64Url(value: string): ArrayBufferLike {\n\tconst base64 = value.replace(/_/g, '/').replace(/-/g, '+');\n\treturn Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;\n}\n\nfunction encodeBase64Url(value: ArrayBufferLike): string {\n\tconst base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(value)));\n\treturn base64.replace(/\\//g, '_').replace(/\\+/g, '-').replace(/=/g, '');\n}\n\n// Exports\n\nexport default createWebAuthn;\n","import createSdk, { UserResponse } from '@descope/core-js-sdk';\nimport { VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport fp from './fp';\nimport State from './state';\nimport { clearTokens, getRefreshToken, handleDescopeTokens } from './tokens';\nimport { CoreSdk, TokensOptions } from './types';\nimport createWebAuthn from './webauthn';\n\ndeclare const BUILD_VERSION: string;\n\n// this sdk can be used in SSR apps\nconst isBrowser = typeof window !== 'undefined';\n\nconst prepareQueryParams = (\n\tqueryParams\n): {\n\t[key: string]: string;\n} => ({\n\t...queryParams,\n\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n});\n\n/** Configuration arguments which include the Descope core SDK args and fingerprint configuration.\n * Also specifies token options - if we should persist tokens from responses automatically and auto-refresh.\n */\nexport type WebJSSDKArgs = Parameters<typeof createSdk>[0] &\n\tTokensOptions & {\n\t\t// FingerprintJS API key\n\t\tfpKey?: string;\n\t};\n\n/**\n * Wrapper around DescopeSDK to handle fingerprint.js and storage of JWT tokens in cookies and localStorage,\n * It also sets a timer to refresh session JWT automatically.\n */\nexport default ({ autoRefresh = true, persistTokens = true, ...args }: WebJSSDKArgs) => {\n\t// istanbul ignore next\n\tif (!isBrowser) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Fingerprint is a client side only capability and will not work when running in the server'\n\t\t);\n\t} else {\n\t\tfp(args.fpKey)\n\t\t\t.get()\n\t\t\t.catch(() => null);\n\t}\n\n\tconst sdkConfig = args;\n\n\t// we defer defining the hook implementations themselves until the webSdk is created later, so that the hooks\n\t// call the actual webSdk functions rather than those from coreSdk, and so that the sdk functions used by\n\t// the hooks can be mocked\n\tlet beforeRequestHook: typeof sdkConfig.hooks.beforeRequest;\n\tlet afterRequestHook: typeof sdkConfig.hooks.afterRequest;\n\n\tconst sessionToken = new State<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: (cb: (sessionToken: string) => void) => {\n\t\t\t// wrapper callback converts from the state object to sessionToken string\n\t\t\tconst bcWrapper = ({ sessionToken }) => {\n\t\t\t\tcb(sessionToken);\n\t\t\t};\n\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tconst currentSessionToken = sessionToken.current?.sessionToken;\n\t\t\tif (currentSessionToken) {\n\t\t\t\tcb(currentSessionToken);\n\t\t\t}\n\t\t\treturn sessionToken.subscribe(bcWrapper);\n\t\t},\n\t\tonUserChange: (cb: (user: UserResponse) => void) => {\n\t\t\tconst bcWrapper = (user: UserResponse) => {\n\t\t\t\tcb(user);\n\t\t\t};\n\t\t\tconst currUser = user.current;\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tif (currUser && Object.entries(currUser).length > 0) {\n\t\t\t\tcb(currUser);\n\t\t\t}\n\n\t\t\treturn user.subscribe(bcWrapper);\n\t\t}\n\t};\n\n\tif (autoRefresh) {\n\t\twebSdk.logout = (...args: Parameters<CoreSdk['logout']>) => {\n\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t// Make it easier for Descoper to just call logout without parameters if this is dev env and refresh is stored in localStorage\n\t\t\tconst token = args?.shift();\n\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\tconst res = coreSdk.logout(...logoutArgs);\n\t\t\tclearTokens();\n\t\t\treturn res;\n\t\t};\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tconfig.queryParams = prepareQueryParams(config.queryParams);\n\t\tif (!config.token && persistTokens) {\n\t\t\tconfig.token = getRefreshToken();\n\t\t}\n\t\tconfig.headers = {\n\t\t\t...config.headers,\n\t\t\t'x-descope-sdk-name': 'web-js',\n\t\t\t'x-descope-sdk-version': BUILD_VERSION\n\t\t};\n\t\treturn config;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (req, res) => {\n\t\t\thandleDescopeTokens(\n\t\t\t\twebSdk.refresh,\n\t\t\t\tres,\n\t\t\t\t{ sessionToken, user },\n\t\t\t\t{ autoRefresh, persistTokens }\n\t\t\t);\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\t// refresh on init is done after afterRequestHook is configured\n\t\twebSdk.refresh();\n\t}\n\n\treturn webSdk;\n};\n"],"names":["getQueryParam","param","Proxy","URLSearchParams","window","location","search","get","searchParams","prop","toString","fp","fpKey","agentP","load","apiKey","async","sessionId","sessionStorage","getItem","Date","now","Math","random","substring","setItem","agent","res","linkedId","requestId","ex","global","FB_DEBUG","console","error","clone","state","Object","assign","State","constructor","init","_State_state","set","this","_State_subscribers","_State_token","__classPrivateFieldSet","current","__classPrivateFieldGet","update","newState","nextState","a","b","aProperties","getOwnPropertyNames","bProperties","length","i","propName","compare","prevState","freeze","setTimeout","values","forEach","cb","subscribe","currentToken","_State_instances","_State_unsubscribe","call","unsubscribeAll","token","refreshTimeoutIds","setRefreshSessionTimeout","refreshFn","sessionJwt","refreshJWT","sessionExpiration","parts","split","claims","JSON","parse","atob","exp","getSessionExpiration","previousTimeout","pop","clearTimeout","refreshTimeout","getTime","timeoutId","push","setDescopeTokens","refreshJwt","cookieParams","cookiePath","cookieDomain","cookieExpiration","Cookies","path","domain","expires","sameSite","secure","setSessionToken","localStorage","setRefreshToken","getRefreshToken","create","options","createOptions","value","publicKey","challenge","decodeBase64Url","user","id","_a","excludeCredentials","item","decodeCreateOptions","createResponse","navigator","credentials","credential","stringify","rawId","encodeBase64Url","response","attestationObject","clientDataJSON","getOptions","allowCredentials","decodeGetOptions","getResponse","authenticatorData","signature","userHandle","undefined","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","isBrowser","autoRefresh","persistTokens","args","__rest","catch","warn","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webSdk","webauthn","sdk","identifier","name","startResponse","signUp","start","origin","data","finish","transactionId","signIn","signUpOrIn","helpers","onSessionTokenChange","currentSessionToken","onUserChange","currUser","entries","logout","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","headers","status","body","json","authInfo","extractJWTResponse","handleDescopeTokens","refresh"],"mappings":"qOACO,MCS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F,MAAQqC,KAEhBwD,EAAOkC,QACHpK,OAAAC,OAAAD,OAAAC,OAAA,CAAA,EAAAiI,EAAOkC,SAAO,CACjB,qBAAsB,SACtB,wBAAyB,kBAEnBlC,CAAM,GAGVZ,GAAeC,KAClBO,EAAmB,CAACM,EAAK9I,MFPpBX,eACN6D,EACAlD,EACAS,EACA6E,GAEA,IACC,GAAmB,MAAftF,EAAI+K,OAIP,OAFAtK,EAAMgI,aAAalH,OAAO,CAAEkH,aAAc,UAC1ChI,EAAMmF,KAAKrE,OAAO,CAAA,GAGnB,MAAMyJ,QAAahL,aAAG,EAAHA,EAAKiL,QACxB,GAAID,EAAM,CACT,MAAMlF,EA3BT,SAA4BkF,GAE3B,OAAOA,aAAA,EAAAA,EAAME,WAAYF,GAAS,CAAA,CACnC,CAwB6DG,CAAmBH,IAAvE7H,WAAEA,EAAUmB,WAAEA,EAAUsB,KAAEA,GAAkDE,EAAzCvB,EAAnC4D,EAAAA,OAAArC,EAAA,CAAA,aAAA,aAAA,SAEFR,EAAQ2C,eACX5D,EAAiBlB,EAAYmB,EAAYC,GAItCpB,GACH1C,EAAMgI,aAAalH,OAAO,CAAEkH,aAActF,IAEvCyC,GACHnF,EAAMmF,KAAKrE,OAAOqE,GAIfzC,GAAcmB,GAAcgB,EAAQ0C,aACvC/E,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOnE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CE/BGiL,CACCnC,EAAOoC,QACPrL,EACA,CAAEyI,eAAc7C,QAChB,CAAEoC,cAAaC,iBACf,GAICD,GAEHiB,EAAOoC,UAGDpC,CAAM"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../../src/constants.ts","../../src/helpers.ts","../../src/fp.ts","../../src/state.ts","../../src/tokens.ts","../../src/webauthn.ts","../../src/index.ts"],"sourcesContent":["/** Fingerprint.js identity key */\nexport const FP_KEY = 'A9aCLRHzKCv3uL69oqDr';\n/** Session ID for visitor */\nexport const VISITOR_SESSION_ID_PARAM = 'vsid';\n/** Request ID for visitor */\nexport const VISITOR_REQUEST_ID_PARAM = 'vrid';\n","/** Wrapper around URLSearchParams that receives prop name as string */\nexport const getQueryParams = () => {\n\tconst params = new Proxy(new URLSearchParams(window.location.search), {\n\t\tget: (searchParams, prop) => searchParams.get(prop.toString())\n\t});\n\n\treturn params;\n};\n\n/** Returns specific URL query param */\nexport const getQueryParam = (param: string) => {\n\tconst params = getQueryParams();\n\n\treturn params[param];\n};\n\n/** Generate UUID based on current time and some randomness */\nexport const generateUUID = () => {\n\t// return alphanumeric, sortable uuid of 27 characters\n\treturn (\n\t\tDate.now().toString(36) +\n\t\tMath.random().toString(36).substring(2) + // removing '0.' prefix\n\t\tMath.random().toString(36).substring(2)\n\t).substring(0, 27);\n};\n","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { getQueryParam, generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = getQueryParam(VISITOR_SESSION_ID_PARAM);\n\t\t\t\t}\n\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = generateUUID();\n\t\t\t\t}\n\n\t\t\t\tsessionStorage.setItem(VISITOR_SESSION_ID_PARAM, sessionId);\n\n\t\t\t\tconst agent = await agentP;\n\t\t\t\tconst res = await agent.get({ linkedId: sessionId });\n\t\t\t\tsessionStorage.setItem(VISITOR_REQUEST_ID_PARAM, res.requestId);\n\t\t\t} catch (ex) {\n\t\t\t\t// istanbul ignore next\n\t\t\t\tif (global.FB_DEBUG) {\n\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\tconsole.error(ex);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n};\n\nexport default fp;\n","// supported state types are string and object\ntype StateObject = Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tconst aProperties = (a && Object.getOwnPropertyNames(a)) || [];\n\tconst bProperties = (b && Object.getOwnPropertyNames(b)) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\nconst clone = (state: StateObject): StateObject => {\n\treturn { ...state };\n};\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n\t\treturn clone(this.#state) as T;\n\t}\n\n\tupdate(newState: T) {\n\t\tconst nextState: T = newState;\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) => cb(clone(nextState) as T, prevState));\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\n\t\t// return unsubscribe function\n\t\tconst currentToken = this.#token;\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (state: T, prevState?: T) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(\n\tsessionJwt: string,\n\trefreshJwt: string,\n\tcookieParams: Partial<JWTResponse>\n) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || ({} as JWTResponse);\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token\n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(\n\trefreshFn: RefreshFn,\n\tres: Response,\n\tstate: SdkState,\n\toptions: TokensOptions\n) {\n\ttry {\n\t\tif (res.status === 401) {\n\t\t\t// reset state if got unauthorized status code\n\t\t\tstate.sessionToken.update({ sessionToken: '' });\n\t\t\tstate.user.update({});\n\t\t\treturn;\n\t\t}\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tif (sessionJwt) {\n\t\t\t\tstate.sessionToken.update({ sessionToken: sessionJwt });\n\t\t\t}\n\t\t\tif (user) {\n\t\t\t\tstate.user.update(user);\n\t\t\t}\n\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { CoreSdk } from './types';\n\n/** Constructs a higher level WebAuthn API that wraps the functions from code-js-sdk */\nconst createWebAuthn = (sdk: CoreSdk) => ({\n\tasync signUp(identifier: string, name: string) {\n\t\tconst startResponse = await sdk.webauthn.signUp.start(identifier, window.location.origin, name);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signIn.start(identifier, window.location.origin);\n\t\tconst getResponse = await get(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tgetResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signUpOrIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signUpOrIn.start(identifier, window.location.origin);\n\t\tif (startResponse.data?.create) {\n\t\t\tconst createResponse = await create(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tcreateResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t} else {\n\t\t\tconst getResponse = await get(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tgetResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t}\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(\n\t\t\tidentifier,\n\t\t\twindow.location.origin,\n\t\t\ttoken\n\t\t);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\t/** Helper functions for working with WebAuthn browser APIs using JSON data */\n\thelpers: {\n\t\t/** Wraps the navigation.credentials.create call to translate JSON inputs and outputs */\n\t\tcreate,\n\t\t/** Wraps the navigation.credentials.get call to translate JSON inputs and outputs */\n\t\tget\n\t}\n});\n\n// Helpers functions\n\nasync function create(options: string): Promise<string> {\n\tconst createOptions = decodeCreateOptions(options);\n\tconst createResponse = (await navigator.credentials.create(\n\t\tcreateOptions\n\t)) as AttestationPublicKeyCredential;\n\treturn encodeCreateResponse(createResponse);\n}\n\nasync function get(options: string): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAttestationResponse;\n};\n\nfunction decodeCreateOptions(value: string): CredentialCreationOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.user.id = decodeBase64Url(options.publicKey.user.id);\n\toptions.publicKey.excludeCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeCreateResponse(credential: AttestationPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tattestationObject: encodeBase64Url(credential.response.attestationObject),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON)\n\t\t}\n\t});\n}\n\n// Conversion of data structures for Get/Assertion/Login ceremony\n\ntype AssertionPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAssertionResponse;\n};\n\nfunction decodeGetOptions(value: string): CredentialRequestOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.allowCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeGetResponse(credential: AssertionPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tauthenticatorData: encodeBase64Url(credential.response.authenticatorData),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t\tsignature: encodeBase64Url(credential.response.signature),\n\t\t\tuserHandle: credential.response.userHandle\n\t\t\t\t? encodeBase64Url(credential.response.userHandle)\n\t\t\t\t: undefined\n\t\t}\n\t});\n}\n\n// Conversion between ArrayBuffers and Base64Url strings\n\nfunction decodeBase64Url(value: string): ArrayBufferLike {\n\tconst base64 = value.replace(/_/g, '/').replace(/-/g, '+');\n\treturn Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;\n}\n\nfunction encodeBase64Url(value: ArrayBufferLike): string {\n\tconst base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(value)));\n\treturn base64.replace(/\\//g, '_').replace(/\\+/g, '-').replace(/=/g, '');\n}\n\n// Exports\n\nexport default createWebAuthn;\n","import createSdk, { UserResponse } from '@descope/core-js-sdk';\nimport { VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport fp from './fp';\nimport State from './state';\nimport { clearTokens, getRefreshToken, handleDescopeTokens } from './tokens';\nimport { CoreSdk, TokensOptions } from './types';\nimport createWebAuthn from './webauthn';\n\ndeclare const BUILD_VERSION: string;\n\n// this sdk can be used in SSR apps\nconst isBrowser = typeof window !== 'undefined';\n\nconst prepareQueryParams = (\n\tqueryParams\n): {\n\t[key: string]: string;\n} => ({\n\t...queryParams,\n\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n});\n\n/** Configuration arguments which include the Descope core SDK args and fingerprint configuration.\n * Also specifies token options - if we should persist tokens from responses automatically and auto-refresh.\n */\nexport type WebJSSDKArgs = Parameters<typeof createSdk>[0] &\n\tTokensOptions & {\n\t\t// FingerprintJS API key\n\t\tfpKey?: string;\n\t};\n\n/**\n * Wrapper around DescopeSDK to handle fingerprint.js and storage of JWT tokens in cookies and localStorage,\n * It also sets a timer to refresh session JWT automatically.\n */\nexport default ({ autoRefresh = true, persistTokens = true, ...args }: WebJSSDKArgs) => {\n\t// istanbul ignore next\n\tif (!isBrowser) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Fingerprint is a client side only capability and will not work when running in the server'\n\t\t);\n\t} else {\n\t\tfp(args.fpKey)\n\t\t\t.get()\n\t\t\t.catch(() => null);\n\t}\n\n\tconst sdkConfig = args;\n\n\t// we defer defining the hook implementations themselves until the webSdk is created later, so that the hooks\n\t// call the actual webSdk functions rather than those from coreSdk, and so that the sdk functions used by\n\t// the hooks can be mocked\n\tlet beforeRequestHook: typeof sdkConfig.hooks.beforeRequest;\n\tlet afterRequestHook: typeof sdkConfig.hooks.afterRequest;\n\n\tconst sessionToken = new State<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: (cb: (sessionToken: string) => void) => {\n\t\t\t// wrapper callback converts from the state object to sessionToken string\n\t\t\tconst bcWrapper = ({ sessionToken }) => {\n\t\t\t\tcb(sessionToken);\n\t\t\t};\n\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tconst currentSessionToken = sessionToken.current?.sessionToken;\n\t\t\tif (currentSessionToken) {\n\t\t\t\tcb(currentSessionToken);\n\t\t\t}\n\t\t\treturn sessionToken.subscribe(bcWrapper);\n\t\t},\n\t\tonUserChange: (cb: (user: UserResponse) => void) => {\n\t\t\tconst bcWrapper = (user: UserResponse) => {\n\t\t\t\tcb(user);\n\t\t\t};\n\t\t\tconst currUser = user.current;\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tif (currUser && Object.entries(currUser).length > 0) {\n\t\t\t\tcb(currUser);\n\t\t\t}\n\n\t\t\treturn user.subscribe(bcWrapper);\n\t\t}\n\t};\n\n\tif (autoRefresh) {\n\t\t// Make it easier for Descoper to just call logout/logoutAll without parameters,\n\t\t// In case this is a dev env and refresh is stored in localStorage\n\t\t['logout', 'logoutAll'].forEach((fnName) => {\n\t\t\tconst originFn = coreSdk[fnName] as Function;\n\t\t\twebSdk[fnName] = (...args: any) => {\n\t\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t\tconst token = args?.shift();\n\t\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\t\tconst res = originFn(...logoutArgs);\n\t\t\t\tclearTokens();\n\t\t\t\tsessionToken.update({ sessionToken: '' });\n\t\t\t\treturn res;\n\t\t\t};\n\t\t});\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tconfig.queryParams = prepareQueryParams(config.queryParams);\n\t\tif (!config.token && persistTokens) {\n\t\t\tconfig.token = getRefreshToken();\n\t\t}\n\t\tconfig.headers = {\n\t\t\t...config.headers,\n\t\t\t'x-descope-sdk-name': 'web-js',\n\t\t\t'x-descope-sdk-version': BUILD_VERSION\n\t\t};\n\t\treturn config;\n\t};\n\n\twebSdk.me = async (...args: Parameters<CoreSdk['me']>) => {\n\t\tconst res = await coreSdk.me(...args);\n\t\tif (res.ok) {\n\t\t\tconst body = await res.response?.clone().json();\n\t\t\tuser.update(body);\n\t\t}\n\t\treturn res;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (_, res) => {\n\t\t\thandleDescopeTokens(\n\t\t\t\twebSdk.refresh,\n\t\t\t\tres,\n\t\t\t\t{ sessionToken, user },\n\t\t\t\t{ autoRefresh, persistTokens }\n\t\t\t);\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\tif (getRefreshToken()) {\n\t\t\t// refresh on init is done after afterRequestHook is configured\n\t\t\twebSdk.refresh();\n\t\t}\n\t}\n\n\treturn webSdk;\n};\n"],"names":["getQueryParam","param","Proxy","URLSearchParams","window","location","search","get","searchParams","prop","toString","fp","fpKey","agentP","load","apiKey","async","sessionId","sessionStorage","getItem","Date","now","Math","random","substring","setItem","agent","res","linkedId","requestId","ex","global","FB_DEBUG","console","error","clone","state","Object","assign","State","constructor","init","_State_state","set","this","_State_subscribers","_State_token","__classPrivateFieldSet","current","__classPrivateFieldGet","update","newState","nextState","a","b","aProperties","getOwnPropertyNames","bProperties","length","i","propName","compare","prevState","freeze","setTimeout","values","forEach","cb","subscribe","currentToken","_State_instances","_State_unsubscribe","call","unsubscribeAll","token","refreshTimeoutIds","setRefreshSessionTimeout","refreshFn","sessionJwt","refreshJWT","sessionExpiration","parts","split","claims","JSON","parse","atob","exp","getSessionExpiration","previousTimeout","pop","clearTimeout","refreshTimeout","getTime","timeoutId","push","setDescopeTokens","refreshJwt","cookieParams","cookiePath","cookieDomain","cookieExpiration","Cookies","path","domain","expires","sameSite","secure","setSessionToken","localStorage","setRefreshToken","getRefreshToken","create","options","createOptions","value","publicKey","challenge","decodeBase64Url","user","id","_a","excludeCredentials","item","decodeCreateOptions","createResponse","navigator","credentials","credential","stringify","rawId","encodeBase64Url","response","attestationObject","clientDataJSON","getOptions","allowCredentials","decodeGetOptions","getResponse","authenticatorData","signature","userHandle","undefined","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","isBrowser","autoRefresh","persistTokens","args","__rest","catch","warn","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webSdk","webauthn","sdk","identifier","name","startResponse","signUp","start","origin","data","finish","transactionId","signIn","signUpOrIn","helpers","onSessionTokenChange","currentSessionToken","onUserChange","currUser","entries","fnName","originFn","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","headers","me","ok","body","json","_","status","authInfo","extractJW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AJC,MAAOnE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CEjBGqL,CACCvC,EAAOwC,QACPzL,EACA,CAAEyI,eAAc7C,QAChB,CAAEoC,cAAaC,iBACf,GAICD,GACC5C,KAEH6D,EAAOwC,UAIFxC,CAAM"}
package/dist/index.d.ts CHANGED
@@ -219,7 +219,7 @@ declare const _default: ({ autoRefresh, persistTokens, ...args }: WebJSSDKArgs)
219
219
  };
220
220
  refresh: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
221
221
  logout: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
222
- deleteCookies: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
222
+ logoutAll: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
223
223
  me: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<UserResponse>>;
224
224
  isJwtExpired: (token: string) => boolean;
225
225
  getJwtPermissions: (token: string, tenant?: string) => string[];
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import{__classPrivateFieldSet as e,__classPrivateFieldGet as t,__rest as n}from"tslib";import s from"@descope/core-js-sdk";import{load as a}from"@fingerprintjs/fingerprintjs-pro";import i from"js-cookie";const o=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],r=e=>{const t=a({apiKey:e||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=o("vsid")),e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem("vsid",e);const n=await t,s=await n.get({linkedId:e});sessionStorage.setItem("vrid",s.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var c,u,l,d,g;const p=e=>Object.assign({},e);class h{constructor(t){c.add(this),u.set(this,void 0),l.set(this,{}),d.set(this,0),e(this,u,t,"f")}get current(){return p(t(this,u,"f"))}update(n){const s=n;if(!((e,t)=>{const n=e&&Object.getOwnPropertyNames(e)||[],s=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==s.length)return!1;for(let s=0;s<n.length;s+=1){const a=n[s];if(e[a]!==t[a])return!1}return!0})(t(this,u,"f"),s)){const n=t(this,u,"f");e(this,u,s,"f"),Object.freeze(t(this,u,"f")),setTimeout((()=>{Object.values(t(this,l,"f")).forEach((e=>e(p(s),n)))}),0)}}subscribe(n){e(this,d,t(this,d,"f")+1,"f"),t(this,l,"f")[t(this,d,"f")]=n;const s=t(this,d,"f");return()=>t(this,c,"m",g).call(this,s.toString())}unsubscribeAll(){e(this,l,{},"f")}}u=new WeakMap,l=new WeakMap,d=new WeakMap,c=new WeakSet,g=function(e){!!t(this,l,"f")[e]&&delete t(this,l,"f")[e]};let f=[];function w(e,t,n){const s=function(e){const t=e.split(".");try{if(3===t.length){const t=JSON.parse(window.atob(e.split(".")[1]));if(t.exp)return new Date(1e3*t.exp)}}catch(e){}return null}(t);if(s){let t;for(;t=f.pop();)clearTimeout(t);const a=s.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(n)}),a);f.push(i)}}function b(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:s}){e&&i.set("DS",e,{path:t,domain:n,expires:s,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function v(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function m(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=y(n.publicKey.challenge),n.publicKey.user.id=y(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=y(e.id)})),n}(e),n=await navigator.credentials.create(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:O(s.rawId),response:Object.assign(Object.assign({},s.response),{attestationObject:O(s.response.attestationObject),clientDataJSON:O(s.response.clientDataJSON)})}));var s}async function S(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=y(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=y(e.id)})),n}(e),n=await navigator.credentials.get(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:O(s.rawId),response:Object.assign(Object.assign({},s.response),{authenticatorData:O(s.response.authenticatorData),clientDataJSON:O(s.response.clientDataJSON),signature:O(s.response.signature),userHandle:s.response.userHandle?O(s.response.userHandle):void 0})}));var s}function y(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function O(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}const k="undefined"!=typeof window;var j=e=>{var{autoRefresh:t=!0,persistTokens:a=!0}=e,o=n(e,["autoRefresh","persistTokens"]);k?r(o.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const c=o;let u,l;const d=new h({sessionToken:""}),g=new h({});c.hooks={beforeRequest:e=>null==u?void 0:u(e),afterRequest:(e,t)=>null==l?void 0:l(e,t)};const p=s(c),f=Object.assign(Object.assign({},p),{webauthn:(y=p,{async signUp(e,t){const n=await y.webauthn.signUp.start(e,window.location.origin,t),s=await m(n.data.options);return await y.webauthn.signUp.finish(n.data.transactionId,s)},async signIn(e){const t=await y.webauthn.signIn.start(e,window.location.origin),n=await S(t.data.options);return await y.webauthn.signIn.finish(t.data.transactionId,n)},async signUpOrIn(e){var t;const n=await y.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=n.data)||void 0===t?void 0:t.create){const e=await m(n.data.options);return await y.webauthn.signUp.finish(n.data.transactionId,e)}{const e=await S(n.data.options);return await y.webauthn.signIn.finish(n.data.transactionId,e)}},async update(e,t){const n=await y.webauthn.update.start(e,window.location.origin,t),s=await m(n.data.options);return await y.webauthn.update.finish(n.data.transactionId,s)},helpers:{create:m,get:S}}),onSessionTokenChange:e=>{var t;const n=null===(t=d.current)||void 0===t?void 0:t.sessionToken;return n&&e(n),d.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=g.current;return t&&Object.entries(t).length>0&&e(t),g.subscribe((t=>{e(t)}))}});var y;return t&&(f.logout=(...e)=>{const t=v(),n=[(null==e?void 0:e.shift())||t,...e],s=p.logout(...n);return localStorage&&localStorage.removeItem("DSR"),i.remove("DS"),s}),u=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""})),!e.token&&a&&(e.token=v()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.6"}),e},(t||a)&&(l=(e,s)=>{!async function(e,t,s,a){try{if(401===t.status)return s.sessionToken.update({sessionToken:""}),void s.user.update({});const i=await(null==t?void 0:t.json());if(i){const t=function(e){return(null==e?void 0:e.authInfo)||e||{}}(i),{sessionJwt:o,refreshJwt:r,user:c}=t,u=n(t,["sessionJwt","refreshJwt","user"]);a.persistTokens&&b(o,r,u),o&&s.sessionToken.update({sessionToken:o}),c&&s.user.update(c),o&&r&&a.autoRefresh&&w(e,o,r)}}catch(e){console.error("Could not set tokens from body",e)}}(f.refresh,s,{sessionToken:d,user:g},{autoRefresh:t,persistTokens:a})}),t&&f.refresh(),f};export{j as default};
1
+ import{__classPrivateFieldSet as e,__classPrivateFieldGet as t,__rest as n}from"tslib";import s from"@descope/core-js-sdk";import{load as a}from"@fingerprintjs/fingerprintjs-pro";import o from"js-cookie";const i=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],r=e=>{const t=a({apiKey:e||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let e=sessionStorage.getItem("vsid");e||(e=i("vsid")),e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem("vsid",e);const n=await t,s=await n.get({linkedId:e});sessionStorage.setItem("vrid",s.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var c,u,l,d,g;const p=e=>Object.assign({},e);class h{constructor(t){c.add(this),u.set(this,void 0),l.set(this,{}),d.set(this,0),e(this,u,t,"f")}get current(){return p(t(this,u,"f"))}update(n){const s=n;if(!((e,t)=>{const n=e&&Object.getOwnPropertyNames(e)||[],s=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==s.length)return!1;for(let s=0;s<n.length;s+=1){const a=n[s];if(e[a]!==t[a])return!1}return!0})(t(this,u,"f"),s)){const n=t(this,u,"f");e(this,u,s,"f"),Object.freeze(t(this,u,"f")),setTimeout((()=>{Object.values(t(this,l,"f")).forEach((e=>e(p(s),n)))}),0)}}subscribe(n){e(this,d,t(this,d,"f")+1,"f"),t(this,l,"f")[t(this,d,"f")]=n;const s=t(this,d,"f");return()=>t(this,c,"m",g).call(this,s.toString())}unsubscribeAll(){e(this,l,{},"f")}}u=new WeakMap,l=new WeakMap,d=new WeakMap,c=new WeakSet,g=function(e){!!t(this,l,"f")[e]&&delete t(this,l,"f")[e]};let f=[];function w(e,t,n){const s=function(e){const t=e.split(".");try{if(3===t.length){const t=JSON.parse(window.atob(e.split(".")[1]));if(t.exp)return new Date(1e3*t.exp)}}catch(e){}return null}(t);if(s){let t;for(;t=f.pop();)clearTimeout(t);const a=s.getTime()-2e4-(new Date).getTime(),o=setTimeout((()=>{e(n)}),a);f.push(o)}}function b(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:s}){e&&o.set("DS",e,{path:t,domain:n,expires:s,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem("DSR",e)}(t)}function v(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem("DSR"):""}async function m(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=y(n.publicKey.challenge),n.publicKey.user.id=y(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=y(e.id)})),n}(e),n=await navigator.credentials.create(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:O(s.rawId),response:Object.assign(Object.assign({},s.response),{attestationObject:O(s.response.attestationObject),clientDataJSON:O(s.response.clientDataJSON)})}));var s}async function S(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=y(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=y(e.id)})),n}(e),n=await navigator.credentials.get(t);return s=n,JSON.stringify(Object.assign(Object.assign({},s),{rawId:O(s.rawId),response:Object.assign(Object.assign({},s.response),{authenticatorData:O(s.response.authenticatorData),clientDataJSON:O(s.response.clientDataJSON),signature:O(s.response.signature),userHandle:s.response.userHandle?O(s.response.userHandle):void 0})}));var s}function y(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function O(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}const k="undefined"!=typeof window;var j=e=>{var{autoRefresh:t=!0,persistTokens:a=!0}=e,i=n(e,["autoRefresh","persistTokens"]);k?r(i.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const c=i;let u,l;const d=new h({sessionToken:""}),g=new h({});c.hooks={beforeRequest:e=>null==u?void 0:u(e),afterRequest:(e,t)=>null==l?void 0:l(e,t)};const p=s(c),f=Object.assign(Object.assign({},p),{webauthn:(y=p,{async signUp(e,t){const n=await y.webauthn.signUp.start(e,window.location.origin,t),s=await m(n.data.options);return await y.webauthn.signUp.finish(n.data.transactionId,s)},async signIn(e){const t=await y.webauthn.signIn.start(e,window.location.origin),n=await S(t.data.options);return await y.webauthn.signIn.finish(t.data.transactionId,n)},async signUpOrIn(e){var t;const n=await y.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=n.data)||void 0===t?void 0:t.create){const e=await m(n.data.options);return await y.webauthn.signUp.finish(n.data.transactionId,e)}{const e=await S(n.data.options);return await y.webauthn.signIn.finish(n.data.transactionId,e)}},async update(e,t){const n=await y.webauthn.update.start(e,window.location.origin,t),s=await m(n.data.options);return await y.webauthn.update.finish(n.data.transactionId,s)},helpers:{create:m,get:S}}),onSessionTokenChange:e=>{var t;const n=null===(t=d.current)||void 0===t?void 0:t.sessionToken;return n&&e(n),d.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=g.current;return t&&Object.entries(t).length>0&&e(t),g.subscribe((t=>{e(t)}))}});var y;return t&&["logout","logoutAll"].forEach((e=>{const t=p[e];f[e]=(...e)=>{const n=v(),s=[(null==e?void 0:e.shift())||n,...e],a=t(...s);return localStorage&&localStorage.removeItem("DSR"),o.remove("DS"),d.update({sessionToken:""}),a}})),u=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{vsid:sessionStorage.getItem("vsid")||"",vrid:sessionStorage.getItem("vrid")||""})),!e.token&&a&&(e.token=v()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.8"}),e},f.me=async(...e)=>{var t;const n=await p.me(...e);if(n.ok){const e=await(null===(t=n.response)||void 0===t?void 0:t.clone().json());g.update(e)}return n},(t||a)&&(l=(e,s)=>{!async function(e,t,s,a){try{if(401===t.status)return s.sessionToken.update({sessionToken:""}),void s.user.update({});const o=await(null==t?void 0:t.json());if(o){const t=function(e){return(null==e?void 0:e.authInfo)||e||{}}(o),{sessionJwt:i,refreshJwt:r,user:c}=t,u=n(t,["sessionJwt","refreshJwt","user"]);a.persistTokens&&b(i,r,u),i&&s.sessionToken.update({sessionToken:i}),c&&s.user.update(c),i&&r&&a.autoRefresh&&w(e,i,r)}}catch(e){console.error("Could not set tokens from body",e)}}(f.refresh,s,{sessionToken:d,user:g},{autoRefresh:t,persistTokens:a})}),t&&v()&&f.refresh(),f};export{j as default};
2
2
  //# sourceMappingURL=index.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../src/constants.ts","../src/helpers.ts","../src/fp.ts","../src/state.ts","../src/tokens.ts","../src/webauthn.ts","../src/index.ts"],"sourcesContent":["/** Fingerprint.js identity key */\nexport const FP_KEY = 'A9aCLRHzKCv3uL69oqDr';\n/** Session ID for visitor */\nexport const VISITOR_SESSION_ID_PARAM = 'vsid';\n/** Request ID for visitor */\nexport const VISITOR_REQUEST_ID_PARAM = 'vrid';\n","/** Wrapper around URLSearchParams that receives prop name as string */\nexport const getQueryParams = () => {\n\tconst params = new Proxy(new URLSearchParams(window.location.search), {\n\t\tget: (searchParams, prop) => searchParams.get(prop.toString())\n\t});\n\n\treturn params;\n};\n\n/** Returns specific URL query param */\nexport const getQueryParam = (param: string) => {\n\tconst params = getQueryParams();\n\n\treturn params[param];\n};\n\n/** Generate UUID based on current time and some randomness */\nexport const generateUUID = () => {\n\t// return alphanumeric, sortable uuid of 27 characters\n\treturn (\n\t\tDate.now().toString(36) +\n\t\tMath.random().toString(36).substring(2) + // removing '0.' prefix\n\t\tMath.random().toString(36).substring(2)\n\t).substring(0, 27);\n};\n","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { getQueryParam, generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = getQueryParam(VISITOR_SESSION_ID_PARAM);\n\t\t\t\t}\n\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = generateUUID();\n\t\t\t\t}\n\n\t\t\t\tsessionStorage.setItem(VISITOR_SESSION_ID_PARAM, sessionId);\n\n\t\t\t\tconst agent = await agentP;\n\t\t\t\tconst res = await agent.get({ linkedId: sessionId });\n\t\t\t\tsessionStorage.setItem(VISITOR_REQUEST_ID_PARAM, res.requestId);\n\t\t\t} catch (ex) {\n\t\t\t\t// istanbul ignore next\n\t\t\t\tif (global.FB_DEBUG) {\n\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\tconsole.error(ex);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n};\n\nexport default fp;\n","// supported state types are string and object\ntype StateObject = Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tconst aProperties = (a && Object.getOwnPropertyNames(a)) || [];\n\tconst bProperties = (b && Object.getOwnPropertyNames(b)) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\nconst clone = (state: StateObject): StateObject => {\n\treturn { ...state };\n};\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n\t\treturn clone(this.#state) as T;\n\t}\n\n\tupdate(newState: T) {\n\t\tconst nextState: T = newState;\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) => cb(clone(nextState) as T, prevState));\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\n\t\t// return unsubscribe function\n\t\tconst currentToken = this.#token;\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (state: T, prevState?: T) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(\n\tsessionJwt: string,\n\trefreshJwt: string,\n\tcookieParams: Partial<JWTResponse>\n) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || ({} as JWTResponse);\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token\n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(\n\trefreshFn: RefreshFn,\n\tres: Response,\n\tstate: SdkState,\n\toptions: TokensOptions\n) {\n\ttry {\n\t\tif (res.status === 401) {\n\t\t\t// reset state if got unauthorized status code\n\t\t\tstate.sessionToken.update({ sessionToken: '' });\n\t\t\tstate.user.update({});\n\t\t\treturn;\n\t\t}\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tif (sessionJwt) {\n\t\t\t\tstate.sessionToken.update({ sessionToken: sessionJwt });\n\t\t\t}\n\t\t\tif (user) {\n\t\t\t\tstate.user.update(user);\n\t\t\t}\n\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { CoreSdk } from './types';\n\n/** Constructs a higher level WebAuthn API that wraps the functions from code-js-sdk */\nconst createWebAuthn = (sdk: CoreSdk) => ({\n\tasync signUp(identifier: string, name: string) {\n\t\tconst startResponse = await sdk.webauthn.signUp.start(identifier, window.location.origin, name);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signIn.start(identifier, window.location.origin);\n\t\tconst getResponse = await get(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tgetResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signUpOrIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signUpOrIn.start(identifier, window.location.origin);\n\t\tif (startResponse.data?.create) {\n\t\t\tconst createResponse = await create(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tcreateResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t} else {\n\t\t\tconst getResponse = await get(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tgetResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t}\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(\n\t\t\tidentifier,\n\t\t\twindow.location.origin,\n\t\t\ttoken\n\t\t);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\t/** Helper functions for working with WebAuthn browser APIs using JSON data */\n\thelpers: {\n\t\t/** Wraps the navigation.credentials.create call to translate JSON inputs and outputs */\n\t\tcreate,\n\t\t/** Wraps the navigation.credentials.get call to translate JSON inputs and outputs */\n\t\tget\n\t}\n});\n\n// Helpers functions\n\nasync function create(options: string): Promise<string> {\n\tconst createOptions = decodeCreateOptions(options);\n\tconst createResponse = (await navigator.credentials.create(\n\t\tcreateOptions\n\t)) as AttestationPublicKeyCredential;\n\treturn encodeCreateResponse(createResponse);\n}\n\nasync function get(options: string): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAttestationResponse;\n};\n\nfunction decodeCreateOptions(value: string): CredentialCreationOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.user.id = decodeBase64Url(options.publicKey.user.id);\n\toptions.publicKey.excludeCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeCreateResponse(credential: AttestationPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tattestationObject: encodeBase64Url(credential.response.attestationObject),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON)\n\t\t}\n\t});\n}\n\n// Conversion of data structures for Get/Assertion/Login ceremony\n\ntype AssertionPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAssertionResponse;\n};\n\nfunction decodeGetOptions(value: string): CredentialRequestOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.allowCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeGetResponse(credential: AssertionPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tauthenticatorData: encodeBase64Url(credential.response.authenticatorData),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t\tsignature: encodeBase64Url(credential.response.signature),\n\t\t\tuserHandle: credential.response.userHandle\n\t\t\t\t? encodeBase64Url(credential.response.userHandle)\n\t\t\t\t: undefined\n\t\t}\n\t});\n}\n\n// Conversion between ArrayBuffers and Base64Url strings\n\nfunction decodeBase64Url(value: string): ArrayBufferLike {\n\tconst base64 = value.replace(/_/g, '/').replace(/-/g, '+');\n\treturn Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;\n}\n\nfunction encodeBase64Url(value: ArrayBufferLike): string {\n\tconst base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(value)));\n\treturn base64.replace(/\\//g, '_').replace(/\\+/g, '-').replace(/=/g, '');\n}\n\n// Exports\n\nexport default createWebAuthn;\n","import createSdk, { UserResponse } from '@descope/core-js-sdk';\nimport { VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport fp from './fp';\nimport State from './state';\nimport { clearTokens, getRefreshToken, handleDescopeTokens } from './tokens';\nimport { CoreSdk, TokensOptions } from './types';\nimport createWebAuthn from './webauthn';\n\ndeclare const BUILD_VERSION: string;\n\n// this sdk can be used in SSR apps\nconst isBrowser = typeof window !== 'undefined';\n\nconst prepareQueryParams = (\n\tqueryParams\n): {\n\t[key: string]: string;\n} => ({\n\t...queryParams,\n\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n});\n\n/** Configuration arguments which include the Descope core SDK args and fingerprint configuration.\n * Also specifies token options - if we should persist tokens from responses automatically and auto-refresh.\n */\nexport type WebJSSDKArgs = Parameters<typeof createSdk>[0] &\n\tTokensOptions & {\n\t\t// FingerprintJS API key\n\t\tfpKey?: string;\n\t};\n\n/**\n * Wrapper around DescopeSDK to handle fingerprint.js and storage of JWT tokens in cookies and localStorage,\n * It also sets a timer to refresh session JWT automatically.\n */\nexport default ({ autoRefresh = true, persistTokens = true, ...args }: WebJSSDKArgs) => {\n\t// istanbul ignore next\n\tif (!isBrowser) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Fingerprint is a client side only capability and will not work when running in the server'\n\t\t);\n\t} else {\n\t\tfp(args.fpKey)\n\t\t\t.get()\n\t\t\t.catch(() => null);\n\t}\n\n\tconst sdkConfig = args;\n\n\t// we defer defining the hook implementations themselves until the webSdk is created later, so that the hooks\n\t// call the actual webSdk functions rather than those from coreSdk, and so that the sdk functions used by\n\t// the hooks can be mocked\n\tlet beforeRequestHook: typeof sdkConfig.hooks.beforeRequest;\n\tlet afterRequestHook: typeof sdkConfig.hooks.afterRequest;\n\n\tconst sessionToken = new State<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: (cb: (sessionToken: string) => void) => {\n\t\t\t// wrapper callback converts from the state object to sessionToken string\n\t\t\tconst bcWrapper = ({ sessionToken }) => {\n\t\t\t\tcb(sessionToken);\n\t\t\t};\n\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tconst currentSessionToken = sessionToken.current?.sessionToken;\n\t\t\tif (currentSessionToken) {\n\t\t\t\tcb(currentSessionToken);\n\t\t\t}\n\t\t\treturn sessionToken.subscribe(bcWrapper);\n\t\t},\n\t\tonUserChange: (cb: (user: UserResponse) => void) => {\n\t\t\tconst bcWrapper = (user: UserResponse) => {\n\t\t\t\tcb(user);\n\t\t\t};\n\t\t\tconst currUser = user.current;\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tif (currUser && Object.entries(currUser).length > 0) {\n\t\t\t\tcb(currUser);\n\t\t\t}\n\n\t\t\treturn user.subscribe(bcWrapper);\n\t\t}\n\t};\n\n\tif (autoRefresh) {\n\t\twebSdk.logout = (...args: Parameters<CoreSdk['logout']>) => {\n\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t// Make it easier for Descoper to just call logout without parameters if this is dev env and refresh is stored in localStorage\n\t\t\tconst token = args?.shift();\n\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\tconst res = coreSdk.logout(...logoutArgs);\n\t\t\tclearTokens();\n\t\t\treturn res;\n\t\t};\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tconfig.queryParams = prepareQueryParams(config.queryParams);\n\t\tif (!config.token && persistTokens) {\n\t\t\tconfig.token = getRefreshToken();\n\t\t}\n\t\tconfig.headers = {\n\t\t\t...config.headers,\n\t\t\t'x-descope-sdk-name': 'web-js',\n\t\t\t'x-descope-sdk-version': BUILD_VERSION\n\t\t};\n\t\treturn config;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (req, res) => {\n\t\t\thandleDescopeTokens(\n\t\t\t\twebSdk.refresh,\n\t\t\t\tres,\n\t\t\t\t{ sessionToken, user },\n\t\t\t\t{ autoRefresh, persistTokens }\n\t\t\t);\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\t// refresh on init is done after afterRequestHook is configured\n\t\twebSdk.refresh();\n\t}\n\n\treturn webSdk;\n};\n"],"names":["getQueryParam","param","Proxy","URLSearchParams","window","location","search","get","searchParams","prop","toString","fp","fpKey","agentP","load","apiKey","async","sessionId","sessionStorage","getItem","Date","now","Math","random","substring","setItem","agent","res","linkedId","requestId","ex","global","FB_DEBUG","console","error","clone","state","Object","assign","State","constructor","init","_State_state","set","this","_State_subscribers","_State_token","__classPrivateFieldSet","current","__classPrivateFieldGet","update","newState","nextState","a","b","aProperties","getOwnPropertyNames","bProperties","length","i","propName","compare","prevState","freeze","setTimeout","values","forEach","cb","subscribe","currentToken","_State_instances","_State_unsubscribe","call","unsubscribeAll","token","refreshTimeoutIds","setRefreshSessionTimeout","refreshFn","sessionJwt","refreshJWT","sessionExpiration","parts","split","claims","JSON","parse","atob","exp","getSessionExpiration","previousTimeout","pop","clearTimeout","refreshTimeout","getTime","timeoutId","push","setDescopeTokens","refreshJwt","cookieParams","cookiePath","cookieDomain","cookieExpiration","Cookies","path","domain","expires","sameSite","secure","setSessionToken","localStorage","setRefreshToken","getRefreshToken","create","options","createOptions","value","publicKey","challenge","decodeBase64Url","user","id","_a","excludeCredentials","item","decodeCreateOptions","createResponse","navigator","credentials","credential","stringify","rawId","encodeBase64Url","response","attestationObject","clientDataJSON","getOptions","allowCredentials","decodeGetOptions","getResponse","authenticatorData","signature","userHandle","undefined","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","isBrowser","index","autoRefresh","persistTokens","args","__rest","catch","warn","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webSdk","webauthn","sdk","identifier","name","startResponse","signUp","start","origin","data","finish","transactionId","signIn","signUpOrIn","helpers","onSessionTokenChange","currentSessionToken","onUserChange","currUser","entries","logout","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","headers","status","body","json","authInfo","extractJWTResponse","handleDescopeTokens","refresh"],"mappings":"4MACO,MCSMA,EAAiBC,GAR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B,kBAEnBlC,CAAM,GAGVZ,GAAeC,KAClBO,EAAmB,CAACM,EAAK/I,MFPpBX,eACN6D,EACAlD,EACAS,EACA6E,GAEA,IACC,GAAmB,MAAftF,EAAIgL,OAIP,OAFAvK,EAAMiI,aAAanH,OAAO,CAAEmH,aAAc,UAC1CjI,EAAMmF,KAAKrE,OAAO,CAAA,GAGnB,MAAM0J,QAAajL,aAAG,EAAHA,EAAKkL,QACxB,GAAID,EAAM,CACT,MAAMnF,EA3BT,SAA4BmF,GAE3B,OAAOA,aAAA,EAAAA,EAAME,WAAYF,GAAS,CAAA,CACnC,CAwB6DG,CAAmBH,IAAvE9H,WAAEA,EAAUmB,WAAEA,EAAUsB,KAAEA,GAAkDE,EAAzCvB,EAAnC6D,EAAAtC,EAAA,CAAA,aAAA,aAAA,SAEFR,EAAQ4C,eACX7D,EAAiBlB,EAAYmB,EAAYC,GAItCpB,GACH1C,EAAMiI,aAAanH,OAAO,CAAEmH,aAAcvF,IAEvCyC,GACHnF,EAAMmF,KAAKrE,OAAOqE,GAIfzC,GAAcmB,GAAcgB,EAAQ2C,aACvChF,EAAyBC,EAAWC,EAAYmB,EAEjD,CAKD,CAJC,MAAOnE,GAGRG,QAAQC,MAAM,iCAAkCJ,EAChD,CACF,CE/BGkL,CACCnC,EAAOoC,QACPtL,EACA,CAAE0I,eAAc9C,QAChB,CAAEqC,cAAaC,iBACf,GAICD,GAEHiB,EAAOoC,UAGDpC,CAAM"}
1
+ {"version":3,"file":"index.esm.js","sources":["../src/constants.ts","../src/helpers.ts","../src/fp.ts","../src/state.ts","../src/tokens.ts","../src/webauthn.ts","../src/index.ts"],"sourcesContent":["/** Fingerprint.js identity key */\nexport const FP_KEY = 'A9aCLRHzKCv3uL69oqDr';\n/** Session ID for visitor */\nexport const VISITOR_SESSION_ID_PARAM = 'vsid';\n/** Request ID for visitor */\nexport const VISITOR_REQUEST_ID_PARAM = 'vrid';\n","/** Wrapper around URLSearchParams that receives prop name as string */\nexport const getQueryParams = () => {\n\tconst params = new Proxy(new URLSearchParams(window.location.search), {\n\t\tget: (searchParams, prop) => searchParams.get(prop.toString())\n\t});\n\n\treturn params;\n};\n\n/** Returns specific URL query param */\nexport const getQueryParam = (param: string) => {\n\tconst params = getQueryParams();\n\n\treturn params[param];\n};\n\n/** Generate UUID based on current time and some randomness */\nexport const generateUUID = () => {\n\t// return alphanumeric, sortable uuid of 27 characters\n\treturn (\n\t\tDate.now().toString(36) +\n\t\tMath.random().toString(36).substring(2) + // removing '0.' prefix\n\t\tMath.random().toString(36).substring(2)\n\t).substring(0, 27);\n};\n","import { load } from '@fingerprintjs/fingerprintjs-pro';\nimport { FP_KEY, VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport { getQueryParam, generateUUID } from './helpers';\n\n/** Fingerprint.js API wrapper */\nconst fp = (fpKey?: string) => {\n\tconst agentP = load({ apiKey: fpKey || FP_KEY });\n\n\treturn {\n\t\tget: async () => {\n\t\t\ttry {\n\t\t\t\tlet sessionId = sessionStorage.getItem(VISITOR_SESSION_ID_PARAM);\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = getQueryParam(VISITOR_SESSION_ID_PARAM);\n\t\t\t\t}\n\n\t\t\t\tif (!sessionId) {\n\t\t\t\t\tsessionId = generateUUID();\n\t\t\t\t}\n\n\t\t\t\tsessionStorage.setItem(VISITOR_SESSION_ID_PARAM, sessionId);\n\n\t\t\t\tconst agent = await agentP;\n\t\t\t\tconst res = await agent.get({ linkedId: sessionId });\n\t\t\t\tsessionStorage.setItem(VISITOR_REQUEST_ID_PARAM, res.requestId);\n\t\t\t} catch (ex) {\n\t\t\t\t// istanbul ignore next\n\t\t\t\tif (global.FB_DEBUG) {\n\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\tconsole.error(ex);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n};\n\nexport default fp;\n","// supported state types are string and object\ntype StateObject = Record<string, any>;\n\ntype Subscribers<T> = Record<string, SubscribeCb<T>>;\n\nconst compare = <T extends StateObject>(a: T, b: T) => {\n\tconst aProperties = (a && Object.getOwnPropertyNames(a)) || [];\n\tconst bProperties = (b && Object.getOwnPropertyNames(b)) || [];\n\n\tif (aProperties.length !== bProperties.length) {\n\t\treturn false;\n\t}\n\n\tfor (let i = 0; i < aProperties.length; i += 1) {\n\t\tconst propName = aProperties[i];\n\n\t\tif (a[propName] !== b[propName]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n};\n\nconst clone = (state: StateObject): StateObject => {\n\treturn { ...state };\n};\n\nclass State<T extends StateObject> {\n\t#state: T;\n\n\t#subscribers: Subscribers<T> = {};\n\n\t#token = 0;\n\n\tconstructor(init: T) {\n\t\tthis.#state = init;\n\t}\n\n\tget current() {\n\t\treturn clone(this.#state) as T;\n\t}\n\n\tupdate(newState: T) {\n\t\tconst nextState: T = newState;\n\t\tif (!compare(this.#state, nextState)) {\n\t\t\tconst prevState = this.#state;\n\t\t\tthis.#state = nextState as T;\n\t\t\tObject.freeze(this.#state);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tObject.values(this.#subscribers).forEach((cb) => cb(clone(nextState) as T, prevState));\n\t\t\t}, 0);\n\t\t}\n\t}\n\n\tsubscribe(cb: SubscribeCb<T>) {\n\t\tthis.#token += 1;\n\t\tthis.#subscribers[this.#token] = cb;\n\n\t\t// return unsubscribe function\n\t\tconst currentToken = this.#token;\n\t\treturn () => this.#unsubscribe(currentToken.toString());\n\t}\n\n\t#unsubscribe(token: string) {\n\t\tconst isFound = !!this.#subscribers[token];\n\n\t\tif (isFound) {\n\t\t\tdelete this.#subscribers[token];\n\t\t}\n\t}\n\n\tunsubscribeAll() {\n\t\tthis.#subscribers = {};\n\t}\n}\nexport type SubscribeCb<T> = (state: T, prevState?: T) => void;\nexport default State;\n","import { JWTResponse } from '@descope/core-js-sdk';\nimport Cookies from 'js-cookie';\nimport { RefreshFn, SdkState, TokensOptions } from './types';\n\n/** Default name for the session cookie */\nconst sessionCookieName = 'DS';\n/** Default name for the refresh cookie */\nconst refreshStorageKey = 'DSR';\n/** Holds the list of timer IDs for auto-refresh of the session token timers so we can clean them later */\nlet refreshTimeoutIds: NodeJS.Timeout[] = [];\n\n/**\n * Store refresh token in localStorage.\n * This is only relevant for development where the refresh token is returned in the response body.\n * For production, it is recommended to configure Descope project to return refresh token as httpOnly cookie as it is more secure this way.\n * @param refreshJwt The refresh JWT to store\n */\nfunction setRefreshToken(refreshJwt: string) {\n\tif (localStorage && refreshJwt) {\n\t\tlocalStorage.setItem(refreshStorageKey, refreshJwt);\n\t}\n}\n\n/**\n * Store the session JWT as a cookie on the given domain and path with the given expiration.\n * This is useful so that the application backend will automatically get the cookie for the session\n * @param sessionJwt The session JWT to store as a cookie\n * @param cookieParams configuration that is usually returned from the JWT\n */\nfunction setSessionToken(\n\tsessionJwt: string,\n\t{ cookiePath, cookieDomain, cookieExpiration }: Partial<JWTResponse>\n) {\n\tif (sessionJwt) {\n\t\tCookies.set(sessionCookieName, sessionJwt, {\n\t\t\tpath: cookiePath,\n\t\t\tdomain: cookieDomain,\n\t\t\texpires: cookieExpiration,\n\t\t\tsameSite: 'None',\n\t\t\tsecure: true\n\t\t});\n\t}\n}\n\n/**\n * Get the JWT expiration WITHOUT VALIDATING the JWT\n * @param token The JWT to extract expiration from\n * @returns The Date for when the JWT expires or null if there is an issue\n */\nfunction getSessionExpiration(token: string) {\n\tconst parts = token.split('.');\n\ttry {\n\t\tif (parts.length === 3) {\n\t\t\tconst claims = JSON.parse(window.atob(token.split('.')[1]));\n\t\t\tif (claims.exp) {\n\t\t\t\treturn new Date(claims.exp * 1000);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// fallback to null\n\t}\n\t// istanbul ignore next\n\treturn null;\n}\n\n/**\n * Start a timer to auto-refresh the session JWT based on the expiry of the session\n * @param refreshFn The function to actually perform the refresh\n * @param sessionJwt The current session JWT to extract timeout from\n * @param refreshJWT The current refresh JWT to be used for refresh function\n */\nfunction setRefreshSessionTimeout(refreshFn: RefreshFn, sessionJwt: string, refreshJWT: string) {\n\tconst sessionExpiration = getSessionExpiration(sessionJwt);\n\tif (sessionExpiration) {\n\t\tlet previousTimeout: NodeJS.Timeout;\n\t\twhile ((previousTimeout = refreshTimeoutIds.pop())) {\n\t\t\tclearTimeout(previousTimeout);\n\t\t}\n\t\t// set refresh to happen 20 (magic number) seconds before session token is expired\n\t\tconst refreshTimeout = sessionExpiration.getTime() - 20 * 1000 - new Date().getTime();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\t// token can also be empty if the refresh JWT is returned as httpOnly cookie\n\t\t\trefreshFn(refreshJWT);\n\t\t}, refreshTimeout);\n\t\trefreshTimeoutIds.push(timeoutId);\n\t}\n}\n\n/**\n * Store the Descope session cookie and the refresh localStorage.\n * For production if configured correctly (returning refresh JWT as httpOnly cookie), it will not store the refresh JWT\n * @param sessionJwt The session JWT to store\n * @param refreshJwt The refresh JWT to store\n * @param cookieParams cookie configuration for setting session JWT cookie\n */\nfunction setDescopeTokens(\n\tsessionJwt: string,\n\trefreshJwt: string,\n\tcookieParams: Partial<JWTResponse>\n) {\n\tsetSessionToken(sessionJwt, cookieParams);\n\tsetRefreshToken(refreshJwt);\n}\n\n/**\n * Extracts JWT response from request body.\n * @param body The response body\n */\nfunction extractJWTResponse(body: any): JWTResponse {\n\t// auth info can be in body authInfo attribute, or the body itself, depending on the core-sdk function\n\treturn body?.authInfo || body || ({} as JWTResponse);\n}\n\n/**\n * Hook function to wrap around Descope SDK and handle tokens\n * @param refreshFn The function to use for refreshing token\n * @param res The raw HTTP response\n * @param state The callbacks that are used to update session token\n * @param options token options that are used for tokens management purposes\n */\nexport async function handleDescopeTokens(\n\trefreshFn: RefreshFn,\n\tres: Response,\n\tstate: SdkState,\n\toptions: TokensOptions\n) {\n\ttry {\n\t\tif (res.status === 401) {\n\t\t\t// reset state if got unauthorized status code\n\t\t\tstate.sessionToken.update({ sessionToken: '' });\n\t\t\tstate.user.update({});\n\t\t\treturn;\n\t\t}\n\t\tconst body = await res?.json();\n\t\tif (body) {\n\t\t\tconst { sessionJwt, refreshJwt, user, ...cookieParams } = extractJWTResponse(body);\n\t\t\t// Persist token\n\t\t\tif (options.persistTokens) {\n\t\t\t\tsetDescopeTokens(sessionJwt, refreshJwt, cookieParams);\n\t\t\t}\n\n\t\t\t// Update state\n\t\t\tif (sessionJwt) {\n\t\t\t\tstate.sessionToken.update({ sessionToken: sessionJwt });\n\t\t\t}\n\t\t\tif (user) {\n\t\t\t\tstate.user.update(user);\n\t\t\t}\n\n\t\t\t// Auto refresh\n\t\t\tif (sessionJwt && refreshJwt && options.autoRefresh) {\n\t\t\t\tsetRefreshSessionTimeout(refreshFn, sessionJwt, refreshJwt);\n\t\t\t}\n\t\t}\n\t} catch (ex) {\n\t\t// istanbul ignore next\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error('Could not set tokens from body', ex);\n\t}\n}\n\n/** Return the refresh token from the localStorage. Not for production usage because refresh token will not be saved in localStorage. */\nexport function getRefreshToken() {\n\treturn localStorage ? localStorage?.getItem(refreshStorageKey) : '';\n}\n\n/** Remove both the localStorage refresh JWT and the session cookie */\nexport function clearTokens() {\n\tif (localStorage) {\n\t\tlocalStorage.removeItem(refreshStorageKey);\n\t}\n\tCookies.remove(sessionCookieName);\n}\n","import { CoreSdk } from './types';\n\n/** Constructs a higher level WebAuthn API that wraps the functions from code-js-sdk */\nconst createWebAuthn = (sdk: CoreSdk) => ({\n\tasync signUp(identifier: string, name: string) {\n\t\tconst startResponse = await sdk.webauthn.signUp.start(identifier, window.location.origin, name);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signIn.start(identifier, window.location.origin);\n\t\tconst getResponse = await get(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tgetResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\tasync signUpOrIn(identifier: string) {\n\t\tconst startResponse = await sdk.webauthn.signUpOrIn.start(identifier, window.location.origin);\n\t\tif (startResponse.data?.create) {\n\t\t\tconst createResponse = await create(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signUp.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tcreateResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t} else {\n\t\t\tconst getResponse = await get(startResponse.data.options);\n\t\t\tconst finishResponse = await sdk.webauthn.signIn.finish(\n\t\t\t\tstartResponse.data.transactionId,\n\t\t\t\tgetResponse\n\t\t\t);\n\t\t\treturn finishResponse;\n\t\t}\n\t},\n\n\tasync update(identifier: string, token: string) {\n\t\tconst startResponse = await sdk.webauthn.update.start(\n\t\t\tidentifier,\n\t\t\twindow.location.origin,\n\t\t\ttoken\n\t\t);\n\t\tconst createResponse = await create(startResponse.data.options);\n\t\tconst finishResponse = await sdk.webauthn.update.finish(\n\t\t\tstartResponse.data.transactionId,\n\t\t\tcreateResponse\n\t\t);\n\t\treturn finishResponse;\n\t},\n\n\t/** Helper functions for working with WebAuthn browser APIs using JSON data */\n\thelpers: {\n\t\t/** Wraps the navigation.credentials.create call to translate JSON inputs and outputs */\n\t\tcreate,\n\t\t/** Wraps the navigation.credentials.get call to translate JSON inputs and outputs */\n\t\tget\n\t}\n});\n\n// Helpers functions\n\nasync function create(options: string): Promise<string> {\n\tconst createOptions = decodeCreateOptions(options);\n\tconst createResponse = (await navigator.credentials.create(\n\t\tcreateOptions\n\t)) as AttestationPublicKeyCredential;\n\treturn encodeCreateResponse(createResponse);\n}\n\nasync function get(options: string): Promise<string> {\n\tconst getOptions = decodeGetOptions(options);\n\tconst getResponse = (await navigator.credentials.get(getOptions)) as AssertionPublicKeyCredential;\n\treturn encodeGetResponse(getResponse);\n}\n\n// Conversion of data structures for Create/Attestation/Register ceremony\n\ntype AttestationPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAttestationResponse;\n};\n\nfunction decodeCreateOptions(value: string): CredentialCreationOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.user.id = decodeBase64Url(options.publicKey.user.id);\n\toptions.publicKey.excludeCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeCreateResponse(credential: AttestationPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tattestationObject: encodeBase64Url(credential.response.attestationObject),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON)\n\t\t}\n\t});\n}\n\n// Conversion of data structures for Get/Assertion/Login ceremony\n\ntype AssertionPublicKeyCredential = PublicKeyCredential & {\n\tresponse: AuthenticatorAssertionResponse;\n};\n\nfunction decodeGetOptions(value: string): CredentialRequestOptions {\n\tconst options = JSON.parse(value);\n\toptions.publicKey.challenge = decodeBase64Url(options.publicKey.challenge);\n\toptions.publicKey.allowCredentials?.forEach((item: any) => {\n\t\titem.id = decodeBase64Url(item.id);\n\t});\n\treturn options;\n}\n\nfunction encodeGetResponse(credential: AssertionPublicKeyCredential): string {\n\treturn JSON.stringify({\n\t\t...credential,\n\t\trawId: encodeBase64Url(credential.rawId),\n\t\tresponse: {\n\t\t\t...credential.response,\n\t\t\tauthenticatorData: encodeBase64Url(credential.response.authenticatorData),\n\t\t\tclientDataJSON: encodeBase64Url(credential.response.clientDataJSON),\n\t\t\tsignature: encodeBase64Url(credential.response.signature),\n\t\t\tuserHandle: credential.response.userHandle\n\t\t\t\t? encodeBase64Url(credential.response.userHandle)\n\t\t\t\t: undefined\n\t\t}\n\t});\n}\n\n// Conversion between ArrayBuffers and Base64Url strings\n\nfunction decodeBase64Url(value: string): ArrayBufferLike {\n\tconst base64 = value.replace(/_/g, '/').replace(/-/g, '+');\n\treturn Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)).buffer;\n}\n\nfunction encodeBase64Url(value: ArrayBufferLike): string {\n\tconst base64 = btoa(String.fromCharCode.apply(null, new Uint8Array(value)));\n\treturn base64.replace(/\\//g, '_').replace(/\\+/g, '-').replace(/=/g, '');\n}\n\n// Exports\n\nexport default createWebAuthn;\n","import createSdk, { UserResponse } from '@descope/core-js-sdk';\nimport { VISITOR_REQUEST_ID_PARAM, VISITOR_SESSION_ID_PARAM } from './constants';\nimport fp from './fp';\nimport State from './state';\nimport { clearTokens, getRefreshToken, handleDescopeTokens } from './tokens';\nimport { CoreSdk, TokensOptions } from './types';\nimport createWebAuthn from './webauthn';\n\ndeclare const BUILD_VERSION: string;\n\n// this sdk can be used in SSR apps\nconst isBrowser = typeof window !== 'undefined';\n\nconst prepareQueryParams = (\n\tqueryParams\n): {\n\t[key: string]: string;\n} => ({\n\t...queryParams,\n\t[VISITOR_SESSION_ID_PARAM]: sessionStorage.getItem(VISITOR_SESSION_ID_PARAM) || '',\n\t[VISITOR_REQUEST_ID_PARAM]: sessionStorage.getItem(VISITOR_REQUEST_ID_PARAM) || ''\n});\n\n/** Configuration arguments which include the Descope core SDK args and fingerprint configuration.\n * Also specifies token options - if we should persist tokens from responses automatically and auto-refresh.\n */\nexport type WebJSSDKArgs = Parameters<typeof createSdk>[0] &\n\tTokensOptions & {\n\t\t// FingerprintJS API key\n\t\tfpKey?: string;\n\t};\n\n/**\n * Wrapper around DescopeSDK to handle fingerprint.js and storage of JWT tokens in cookies and localStorage,\n * It also sets a timer to refresh session JWT automatically.\n */\nexport default ({ autoRefresh = true, persistTokens = true, ...args }: WebJSSDKArgs) => {\n\t// istanbul ignore next\n\tif (!isBrowser) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t'Fingerprint is a client side only capability and will not work when running in the server'\n\t\t);\n\t} else {\n\t\tfp(args.fpKey)\n\t\t\t.get()\n\t\t\t.catch(() => null);\n\t}\n\n\tconst sdkConfig = args;\n\n\t// we defer defining the hook implementations themselves until the webSdk is created later, so that the hooks\n\t// call the actual webSdk functions rather than those from coreSdk, and so that the sdk functions used by\n\t// the hooks can be mocked\n\tlet beforeRequestHook: typeof sdkConfig.hooks.beforeRequest;\n\tlet afterRequestHook: typeof sdkConfig.hooks.afterRequest;\n\n\tconst sessionToken = new State<{ sessionToken: string }>({ sessionToken: '' });\n\tconst user = new State<UserResponse>({} as UserResponse);\n\n\tsdkConfig.hooks = {\n\t\tbeforeRequest: (config) => {\n\t\t\treturn beforeRequestHook?.(config);\n\t\t},\n\t\tafterRequest: (req, res) => {\n\t\t\treturn afterRequestHook?.(req, res);\n\t\t}\n\t};\n\n\tconst coreSdk = createSdk(sdkConfig);\n\n\tconst webSdk = {\n\t\t...coreSdk,\n\t\twebauthn: createWebAuthn(coreSdk),\n\t\tonSessionTokenChange: (cb: (sessionToken: string) => void) => {\n\t\t\t// wrapper callback converts from the state object to sessionToken string\n\t\t\tconst bcWrapper = ({ sessionToken }) => {\n\t\t\t\tcb(sessionToken);\n\t\t\t};\n\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tconst currentSessionToken = sessionToken.current?.sessionToken;\n\t\t\tif (currentSessionToken) {\n\t\t\t\tcb(currentSessionToken);\n\t\t\t}\n\t\t\treturn sessionToken.subscribe(bcWrapper);\n\t\t},\n\t\tonUserChange: (cb: (user: UserResponse) => void) => {\n\t\t\tconst bcWrapper = (user: UserResponse) => {\n\t\t\t\tcb(user);\n\t\t\t};\n\t\t\tconst currUser = user.current;\n\t\t\t// run callback with current state for a case that the state's consumer calls 'subscribe' after state was already updated\n\t\t\tif (currUser && Object.entries(currUser).length > 0) {\n\t\t\t\tcb(currUser);\n\t\t\t}\n\n\t\t\treturn user.subscribe(bcWrapper);\n\t\t}\n\t};\n\n\tif (autoRefresh) {\n\t\t// Make it easier for Descoper to just call logout/logoutAll without parameters,\n\t\t// In case this is a dev env and refresh is stored in localStorage\n\t\t['logout', 'logoutAll'].forEach((fnName) => {\n\t\t\tconst originFn = coreSdk[fnName] as Function;\n\t\t\twebSdk[fnName] = (...args: any) => {\n\t\t\t\tconst refreshToken = getRefreshToken();\n\t\t\t\tconst token = args?.shift();\n\t\t\t\tconst logoutArgs = [token || refreshToken, ...args];\n\t\t\t\tconst res = originFn(...logoutArgs);\n\t\t\t\tclearTokens();\n\t\t\t\tsessionToken.update({ sessionToken: '' });\n\t\t\t\treturn res;\n\t\t\t};\n\t\t});\n\t}\n\n\tbeforeRequestHook = (config) => {\n\t\tconfig.queryParams = prepareQueryParams(config.queryParams);\n\t\tif (!config.token && persistTokens) {\n\t\t\tconfig.token = getRefreshToken();\n\t\t}\n\t\tconfig.headers = {\n\t\t\t...config.headers,\n\t\t\t'x-descope-sdk-name': 'web-js',\n\t\t\t'x-descope-sdk-version': BUILD_VERSION\n\t\t};\n\t\treturn config;\n\t};\n\n\twebSdk.me = async (...args: Parameters<CoreSdk['me']>) => {\n\t\tconst res = await coreSdk.me(...args);\n\t\tif (res.ok) {\n\t\t\tconst body = await res.response?.clone().json();\n\t\t\tuser.update(body);\n\t\t}\n\t\treturn res;\n\t};\n\n\tif (autoRefresh || persistTokens) {\n\t\tafterRequestHook = (_, res) => {\n\t\t\thandleDescopeTokens(\n\t\t\t\twebSdk.refresh,\n\t\t\t\tres,\n\t\t\t\t{ sessionToken, user },\n\t\t\t\t{ autoRefresh, persistTokens }\n\t\t\t);\n\t\t};\n\t}\n\n\tif (autoRefresh) {\n\t\tif (getRefreshToken()) {\n\t\t\t// refresh on init is done after afterRequestHook is configured\n\t\t\twebSdk.refresh();\n\t\t}\n\t}\n\n\treturn webSdk;\n};\n"],"names":["getQueryParam","param","Proxy","URLSearchParams","window","location","search","get","searchParams","prop","toString","fp","fpKey","agentP","load","apiKey","async","sessionId","sessionStorage","getItem","Date","now","Math","random","substring","setItem","agent","res","linkedId","requestId","ex","global","FB_DEBUG","console","error","clone","state","Object","assign","State","constructor","init","_State_state","set","this","_State_subscribers","_State_token","__classPrivateFieldSet","current","__classPrivateFieldGet","update","newState","nextState","a","b","aProperties","getOwnPropertyNames","bProperties","length","i","propName","compare","prevState","freeze","setTimeout","values","forEach","cb","subscribe","currentToken","_State_instances","_State_unsubscribe","call","unsubscribeAll","token","refreshTimeoutIds","setRefreshSessionTimeout","refreshFn","sessionJwt","refreshJWT","sessionExpiration","parts","split","claims","JSON","parse","atob","exp","getSessionExpiration","previousTimeout","pop","clearTimeout","refreshTimeout","getTime","timeoutId","push","setDescopeTokens","refreshJwt","cookieParams","cookiePath","cookieDomain","cookieExpiration","Cookies","path","domain","expires","sameSite","secure","setSessionToken","localStorage","setRefreshToken","getRefreshToken","create","options","createOptions","value","publicKey","challenge","decodeBase64Url","user","id","_a","excludeCredentials","item","decodeCreateOptions","createResponse","navigator","credentials","credential","stringify","rawId","encodeBase64Url","response","attestationObject","clientDataJSON","getOptions","allowCredentials","decodeGetOptions","getResponse","authenticatorData","signature","userHandle","undefined","base64","replace","Uint8Array","from","c","charCodeAt","buffer","btoa","String","fromCharCode","apply","isBrowser","index","autoRefresh","persistTokens","args","__rest","catch","warn","sdkConfig","beforeRequestHook","afterRequestHook","sessionToken","hooks","beforeRequest","config","afterRequest","req","coreSdk","createSdk","webSdk","webauthn","sdk","identifier","name","startResponse","signUp","start","origin","data","finish","transactionId","signIn","signUpOrIn","helpers","onSessionTokenChange","currentSessionToken","onUserChange","currUser","entries","fnName","originFn","refreshToken","logoutArgs","shift","removeItem","remove","queryParams","vsid","vrid","headers","me","ok","body","json","_","status","authInfo","extractJWTResponse","handleDescopeTokens","refresh"],"mappings":"4MACO,MCSMA,EAAiBC,GARd,IAAIC,MAAM,IAAIC,gBAAgBC,OAAOC,SAASC,QAAS,CACrEC,IAAK,CAACC,EAAcC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eof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).descopeSdk=t()}(this,(function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},e.apply(this,arguments)};function t(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}function n(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}function r(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n}function o(e){this.message=e}o.prototype=new Error,o.prototype.name="InvalidCharacterError";var i="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new o("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,r,i=0,a=0,s="";r=t.charAt(a++);~r&&(n=i%4?64*n+r:r,i++%4)?s+=String.fromCharCode(255&n>>(-2*i&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return s};function a(e){this.message=e}function s(e,t){if("string"!=typeof e)throw new a("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(i(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))}(t)}catch(e){return i(t)}}(e.split(".")[n]))}catch(e){throw new a("Invalid token specified: "+e.message)}}a.prototype=new Error,a.prototype.name="InvalidTokenError";var c="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},u="__lodash_hash_undefined__",l="[object Function]",p="[object GeneratorFunction]",d=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,h=/^\w*$/,f=/^\./,g=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,v=/\\(\\)?/g,y=/^\[object .+?Constructor\]$/,b="object"==typeof c&&c&&c.Object===Object&&c,w="object"==typeof self&&self&&self.Object===Object&&self,m=b||w||Function("return this")();var O,k=Array.prototype,j=Function.prototype,I=Object.prototype,_=m["__core-js_shared__"],x=(O=/[^.]+$/.exec(_&&_.keys&&_.keys.IE_PROTO||""))?"Symbol(src)_1."+O:"",S=j.toString,P=I.hasOwnProperty,U=I.toString,R=RegExp("^"+S.call(P).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),T=m.Symbol,E=k.splice,C=F(m,"Map"),D=F(Object,"create"),q=T?T.prototype:void 0,A=q?q.toString:void 0;function $(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function J(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function M(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function N(e,t){for(var n,r,o=e.length;o--;)if((n=e[o][0])===(r=t)||n!=n&&r!=r)return o;return-1}function K(e,t){var n;t=function(e,t){if(G(e))return!1;var n=typeof e;if("number"==n||"symbol"==n||"boolean"==n||null==e||V(e))return!0;return h.test(e)||!d.test(e)||null!=t&&e in Object(t)}(t,e)?[t]:G(n=t)?n:z(n);for(var r=0,o=t.length;null!=e&&r<o;)e=e[H(t[r++])];return r&&r==o?e:void 0}function L(e){if(!Z(e)||(t=e,x&&x in t))return!1;var t,n=function(e){var t=Z(e)?U.call(e):"";return t==l||t==p}(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e)?R:y;return n.test(function(e){if(null!=e){try{return S.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function B(e,t){var n,r,o=e.__data__;return("string"==(r=typeof(n=t))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==n:null===n)?o["string"==typeof t?"string":"hash"]:o.map}function F(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return L(n)?n:void 0}$.prototype.clear=function(){this.__data__=D?D(null):{}},$.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},$.prototype.get=function(e){var t=this.__data__;if(D){var n=t[e];return n===u?void 0:n}return P.call(t,e)?t[e]:void 0},$.prototype.has=function(e){var t=this.__data__;return D?void 0!==t[e]:P.call(t,e)},$.prototype.set=function(e,t){return this.__data__[e]=D&&void 0===t?u:t,this},J.prototype.clear=function(){this.__data__=[]},J.prototype.delete=function(e){var t=this.__data__,n=N(t,e);return!(n<0)&&(n==t.length-1?t.pop():E.call(t,n,1),!0)},J.prototype.get=function(e){var t=this.__data__,n=N(t,e);return n<0?void 0:t[n][1]},J.prototype.has=function(e){return N(this.__data__,e)>-1},J.prototype.set=function(e,t){var n=this.__data__,r=N(n,e);return r<0?n.push([e,t]):n[r][1]=t,this},M.prototype.clear=function(){this.__data__={hash:new $,map:new(C||J),string:new $}},M.prototype.delete=function(e){return B(this,e).delete(e)},M.prototype.get=function(e){return B(this,e).get(e)},M.prototype.has=function(e){return B(this,e).has(e)},M.prototype.set=function(e,t){return B(this,e).set(e,t),this};var z=W((function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(V(e))return A?A.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(t);var n=[];return f.test(e)&&n.push(""),e.replace(g,(function(e,t,r,o){n.push(r?o.replace(v,"$1"):t||e)})),n}));function H(e){if("string"==typeof e||V(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function W(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var a=e.apply(this,r);return n.cache=i.set(o,a),a};return n.cache=new(W.Cache||M),n}W.Cache=M;var G=Array.isArray;function Z(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function V(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==U.call(e)}var Q,X=function(e,t,n){var r=null==e?void 0:K(e,t);return void 0===r?n:r},Y="/v1/auth/accesskey/exchange",ee="/v1/auth/otp/verify",te="/v1/auth/otp/signin",ne="/v1/auth/otp/signup",re={email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},oe="/v1/auth/otp/signup-in",ie="/v1/auth/magiclink/verify",ae="/v1/auth/magiclink/signin",se="/v1/auth/magiclink/signup",ce="/v1/auth/magiclink/pending-session",ue={email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},le="/v1/auth/magiclink/signup-in",pe="/v1/auth/oauth/authorize",de="/v1/auth/oauth/exchange",he="/v1/auth/saml/authorize",fe="/v1/auth/saml/exchange",ge="/v1/auth/totp/verify",ve="/v1/auth/totp/signup",ye="/v1/user/totp/update",be={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},we={start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},me={start:"/v1/auth/webauthn/signup-in/start"},Oe={start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"},ke="/v1/flow/start",je="/v1/flow/next";!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(Q||(Q={}));const Ie=()=>{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")}},_e=(...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,r])=>(e[n]=r,e)),e),e}),{})),xe=e=>void 0===e?void 0:JSON.stringify(e),Se=(e,t="")=>{let n=e;return""!==t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},Pe=({baseUrl:e,projectId:t,baseConfig:n,logger:r,hooks:o,cookiePolicy:i})=>{const a=((e,t)=>{const n=t||fetch;if(!n)throw new Error("fetch is not defined");return e?async(...t)=>{e.log((e=>Ie().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const r=await n(...t);return e[r.ok?"log":"error"](await(async e=>{const t=await e.text();return e.text=()=>Promise.resolve(t),e.json=()=>Promise.resolve(JSON.parse(t)),Ie().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(r)),r}:n})(r),s=async r=>{const s=(null==o?void 0:o.beforeRequest)?o.beforeRequest(r):r,{path:c,body:u,headers:l,queryParams:p,method:d,token:h}=s,f=await a((({path:e,baseUrl:t,queryParams:n})=>{const r=new URL(e,t);return n&&(r.search=new URLSearchParams(n).toString()),r})({path:c,baseUrl:e,queryParams:p}),{headers:_e(Se(t,h),{"x-descope-sdk-name":"core-js","x-descope-sdk-version":"0.0.41-alpha.26"},(null==n?void 0:n.baseHeaders)||{},l),method:d,body:xe(u),credentials:i||"include"});return(null==o?void 0:o.afterRequest)&&o.afterRequest(r,null==f?void 0:f.clone()),f};return{get:(e,{headers:t,queryParams:n,token:r}={})=>s({path:e,headers:t,queryParams:n,body:void 0,method:Q.get,token:r}),post:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.post,token:o}),put:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.put,token:o}),delete:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.delete,token:o})}};function Ue(e,t,n){var r;let o=Re(e);t&&(o=null===(r=o.tenants)||void 0===r?void 0:r[t]);const i=o[n];return Array.isArray(i)?i:[]}function Re(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return s(e)}function Te(e){const{exp:t}=Re(e);return(new Date).getTime()/1e3>t}function Ee(e,t){return Ue(e,t,"permissions")}function Ce(e,t){return Ue(e,t,"roles")}const De=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function qe(e){const t=await e,n={code:t.status,ok:t.ok,response:t},r=await t.clone().json();return t.ok?n.data=r:n.error=r,n}const Ae=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),$e=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),Je=e=>t=>e.test(t),Me=Je(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),Ne=Je(/^\+[1-9]{1}[0-9]{3,14}$/),Ke=Ae(Me,'"{val}" is not a valid email'),Le=Ae(Ne,'"{val}" is not a valid phone number'),Be=Ae((1,e=>e.length>=1),"Minimum length is 1");const Fe=Ae((e=>"string"==typeof e),"Input is not a string"),ze=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>$e(...e).validate(n[t]))),t(...n)),He=e=>[Fe(`"${e}" must be a string`),Be(`"${e}" must not be empty`)],We=e=>[Fe(`"${e}" must be a string`),Ke()],Ge=e=>[Fe(`"${e}" must be a string`),Le()],Ze=ze(He("accessKey")),Ve=e=>({exchange:Ze((t=>qe(e.post(Y,{},{token:t}))))});var Qe,Xe,Ye,et,tt;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(Qe||(Qe={})),function(e){e.email="email",e.sms="sms",e.whatsapp="whatsapp"}(Xe||(Xe={})),function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(Ye||(Ye={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify"}(et||(et={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify",e.updatePhone="updatePhone"}(tt||(tt={}));const nt=He("identifier"),rt=ze(nt,He("code")),ot=ze(nt),it=ze(nt,Ge("phone")),at=ze(nt,We("email")),st=e=>({verify:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:rt(((t,r)=>qe(e.post(De(ee,n),{code:r,externalId:t}))))})),{}),signIn:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ot(((t,r,o)=>qe(e.post(De(te,n),{externalId:t,loginOptions:r},{token:o}))))})),{}),signUp:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ot(((t,r)=>qe(e.post(De(ne,n),{externalId:t,user:r}))))})),{}),signUpOrIn:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ot((t=>qe(e.post(De(oe,n),{externalId:t}))))})),{}),update:{email:at(((t,n,r)=>qe(e.post(re.email,{externalId:t,email:n},{token:r})))),phone:Object.keys(Qe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:it(((t,r,o)=>qe(e.post(De(re.phone,n),{externalId:t,phone:r},{token:o}))))})),{})}}),ct=He("identifier"),ut=He("uri"),lt=ze(He("token")),pt=ze(ct,ut),dt=ze(He("pendingRef")),ht=ze(ct,Ge("phone"),ut),ft=ze(ct,We("email"),ut),gt=e=>({verify:lt((t=>qe(e.post(ie,{token:t})))),signIn:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:pt(((t,r,o,i)=>qe(e.post(De(ae,n),{externalId:t,URI:r,crossDevice:!0,loginOptions:o},{token:i}))))})),{}),signUpOrIn:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:pt(((t,r)=>qe(e.post(De(le,n),{externalId:t,URI:r,crossDevice:!0}))))})),{}),signUp:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:pt(((t,r,o)=>qe(e.post(De(se,n),{externalId:t,URI:r,user:o,crossDevice:!0}))))})),{}),waitForSession:dt(((t,n)=>new Promise((r=>{const{pollingIntervalMs:o,timeoutMs:i}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||6e5,6e5)}))(n);let a;const s=setInterval((async()=>{const n=await e.post(ce,{pendingRef:t});n.ok&&(clearInterval(s),a&&clearTimeout(a),r(qe(Promise.resolve(n))))}),o);a=setTimeout((()=>{r({error:{message:`Session polling timeout exceeded: ${i}ms`,code:"0"},ok:!1}),clearInterval(s)}),i)})))),update:{email:ft(((t,n,r,o)=>qe(e.post(ue.email,{externalId:t,email:n,URI:r,crossDevice:!0},{token:o})))),phone:Object.keys(Qe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ht(((t,r,o,i)=>qe(e.post(De(ue.phone,n),{externalId:t,phone:r,URI:o,crossDevice:!0},{token:i}))))})),{})}}),vt=e=>({verify:lt((t=>qe(e.post(ie,{token:t})))),signIn:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:pt(((t,r,o,i)=>qe(e.post(De(ae,n),{externalId:t,URI:r,loginOptions:o},{token:i}))))})),{}),signUp:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:pt(((t,r,o)=>qe(e.post(De(se,n),{externalId:t,URI:r,user:o}))))})),{}),signUpOrIn:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:pt(((t,r)=>qe(e.post(De(le,n),{externalId:t,URI:r}))))})),{}),update:{email:ft(((t,n,r,o)=>qe(e.post(ue.email,{externalId:t,email:n,URI:r},{token:o})))),phone:Object.keys(Qe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ht(((t,r,o,i)=>qe(e.post(De(ue.phone,n),{externalId:t,phone:r,URI:o},{token:i}))))})),{})},crossDevice:gt(e)});var yt;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple"}(yt||(yt={}));const bt=ze(He("code")),wt=e=>({start:Object.keys(yt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:async(t,{redirect:r=!1}={},o,i)=>{const a=await e.post(pe,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:i});if(!r||!a.ok)return qe(Promise.resolve(a));const{url:s}=await a.json();window.location.href=s}})),{}),exchange:bt((t=>qe(e.post(de,{code:t}))))}),mt=ze(He("flowId")),Ot=ze(He("executionId"),He("stepId"),He("interactionId")),kt=e=>({start:mt(((t,n)=>qe(e.post(ke,{flowId:t,options:n})))),next:Ot(((t,n,r,o)=>qe(e.post(je,{executionId:t,stepId:n,interactionId:r,input:o}))))}),jt=ze(He("tenant")),It=ze(He("code")),_t=e=>({start:jt((async(t,n,{redirect:r=!1}={},o,i)=>{const a=await e.post(he,o||{},{queryParams:{tenant:t,redirectURL:n},token:i});if(!r||!a.ok)return qe(Promise.resolve(a));const{url:s}=await a.json();window.location.href=s})),exchange:It((t=>qe(e.post(fe,{code:t}))))}),xt=He("identifier"),St=ze(xt,He("code")),Pt=ze(xt),Ut=ze(xt),Rt=e=>({signUp:Pt(((t,n)=>qe(e.post(ve,{externalId:t,user:n})))),verify:St(((t,n,r,o)=>qe(e.post(ge,{externalId:t,code:n,loginOptions:r},{token:o})))),update:Ut(((t,n)=>qe(e.post(ye,{externalId:t},{token:n}))))}),Tt=He("identifier"),Et=He("origin"),Ct=ze(Tt,Et,He("name")),Dt=ze(Tt,Et),qt=ze(Tt,Et,He("token")),At=ze(He("transactionId"),He("response")),$t=e=>({signUp:{start:Ct(((t,n,r)=>qe(e.post(be.start,{user:{externalId:t,name:r},origin:n})))),finish:At(((t,n)=>qe(e.post(be.finish,{transactionId:t,response:n}))))},signIn:{start:Dt(((t,n,r,o)=>qe(e.post(we.start,{externalId:t,origin:n,loginOptions:r},{token:o})))),finish:At(((t,n)=>qe(e.post(we.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:Dt(((t,n)=>qe(e.post(me.start,{externalId:t,origin:n}))))},update:{start:qt(((t,n,r)=>qe(e.post(Oe.start,{externalId:t,origin:n},{token:r})))),finish:At(((t,n)=>qe(e.post(Oe.finish,{transactionId:t,response:n}))))}}),Jt=ze(He("token"));var Mt;const Nt=ze([("projectId",Mt=He("projectId"),Ae(((e,t)=>e=>$e(...t).validate(X(e,"projectId")))(0,Mt))())])((({projectId:e,logger:t,baseUrl:n,hooks:r,cookiePolicy:o})=>{return i=Pe({baseUrl:n||"https://api.descope.com",projectId:e,logger:t,hooks:r,cookiePolicy:o}),{accessKey:Ve(i),otp:st(i),magicLink:vt(i),oauth:wt(i),saml:_t(i),totp:Rt(i),webauthn:$t(i),flow:kt(i),refresh:e=>qe(i.post("/v1/auth/refresh",{},{token:e})),logout:e=>qe(i.post("/v1/auth/logoutall",{},{token:e})),deleteCookies:e=>qe(i.post("/v1/auth/deletecookies",{},{token:e})),me:e=>qe(i.get("/v1/auth/me",{token:e})),isJwtExpired:Jt(Te),getJwtPermissions:Jt(Ee),getJwtRoles:Jt(Ce),httpClient:i};var i}));Nt.DeliveryMethods=Xe;const Kt="vsid",Lt="vrid";function Bt(e,t,n){return void 0===n&&(n=0),t(n).catch((function(r){if(n>=e.maxRetries||!e.shouldRetry(r))throw r;var o,i,a,s,c=(o=e.baseDelay,i=e.maxDelay,a=e.baseDelay*Math.pow(2,n),Math.max(o,Math.min(i,a)));return(s=c,new Promise((function(e){return setTimeout(e,s)}))).then((function(){return Bt(e,t,n+1)}))}))}var Ft="Failed to load the JS script of the agent";function zt(n){var r,o=n.scriptUrlPattern,i=n.token,a=n.apiKey,s=void 0===a?i:a,c=t(n,["scriptUrlPattern","token","apiKey"]),u=(r=n,"scriptUrlPattern",Object.prototype.hasOwnProperty.call(r,"scriptUrlPattern")?o:void 0),l=[];return Promise.resolve().then((function(){if(!s||"string"!=typeof s)throw new Error("API key required");return Bt({maxRetries:5,baseDelay:100,maxDelay:3e3,shouldRetry:function(e){return!(e instanceof Error&&"Blocked by CSP"===e.message)}},(function(){var e,t=new Date,n=function(){return l.push({startedAt:t,finishedAt:new Date})},r=function(e,t,n,r){var o,i=document,a="securitypolicyviolation",s=function(t){var n=new URL(e,location.href),r=t.blockedURI;r!==n.href&&r!==n.protocol.slice(0,-1)&&r!==n.origin||(o=t,c())};i.addEventListener(a,s);var c=function(){return i.removeEventListener(a,s)};return Promise.resolve().then(t).then((function(e){return c(),e}),(function(e){return new Promise((function(e){return setTimeout(e)})).then((function(){if(c(),o)return function(){throw new Error("Blocked by CSP")}();throw e}))}))}(e=function(e,t){void 0===t&&(t="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js");var n=encodeURIComponent;return t.replace(/<[^<>]+>/g,(function(t){return"<version>"===t?"3":"<apiKey>"===t?n(e):"<loaderVersion>"===t?n("3.7.1"):t}))}(s,u),(function(){return function(e){return new Promise((function(t,n){var r=document.createElement("script"),o=function(){var e;return null===(e=r.parentNode)||void 0===e?void 0:e.removeChild(r)},i=document.head||document.getElementsByTagName("head")[0];r.onload=function(){o(),t()},r.onerror=function(){o(),n(new Error(Ft))},r.async=!0,r.src=e,i.appendChild(r)}))}(e)}));return r.then(n,n),r}))})).then((function(){var t=window,n="__fpjs_p_l_b",r=t[n];if(function(e,t){var n,r=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==r?void 0:r.configurable)?delete e[t]:r&&!r.writable||(e[t]=void 0)}(t,n),"function"!=typeof(null==r?void 0:r.load))throw new Error(Ft);return r.load(e(e({},c),{ldi:{attempts:l}}))}))}const Ht=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],Wt=e=>{const t=zt({apiKey:e||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let e=sessionStorage.getItem(Kt);e||(e=Ht(Kt)),e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem(Kt,e);const n=await t,r=await n.get({linkedId:e});sessionStorage.setItem(Lt,r.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var Gt,Zt,Vt,Qt,Xt;const Yt=e=>Object.assign({},e);class en{constructor(e){Gt.add(this),Zt.set(this,void 0),Vt.set(this,{}),Qt.set(this,0),r(this,Zt,e,"f")}get current(){return Yt(n(this,Zt,"f"))}update(e){const t=e;if(!((e,t)=>{const n=e&&Object.getOwnPropertyNames(e)||[],r=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==r.length)return!1;for(let r=0;r<n.length;r+=1){const o=n[r];if(e[o]!==t[o])return!1}return!0})(n(this,Zt,"f"),t)){const e=n(this,Zt,"f");r(this,Zt,t,"f"),Object.freeze(n(this,Zt,"f")),setTimeout((()=>{Object.values(n(this,Vt,"f")).forEach((n=>n(Yt(t),e)))}),0)}}subscribe(e){r(this,Qt,n(this,Qt,"f")+1,"f"),n(this,Vt,"f")[n(this,Qt,"f")]=e;const t=n(this,Qt,"f");return()=>n(this,Gt,"m",Xt).call(this,t.toString())}unsubscribeAll(){r(this,Vt,{},"f")}}
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).descopeSdk=t()}(this,(function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},e.apply(this,arguments)};function t(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}function n(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}function r(e,t,n,r,o){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!o)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?o.call(e,n):o?o.value=n:t.set(e,n),n}function o(e){this.message=e}o.prototype=new Error,o.prototype.name="InvalidCharacterError";var a="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new o("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,r,a=0,i=0,s="";r=t.charAt(i++);~r&&(n=a%4?64*n+r:r,a++%4)?s+=String.fromCharCode(255&n>>(-2*a&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return s};function i(e){this.message=e}function s(e,t){if("string"!=typeof e)throw new i("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(a(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 a(t)}}(e.split(".")[n]))}catch(e){throw new i("Invalid token specified: "+e.message)}}i.prototype=new Error,i.prototype.name="InvalidTokenError";var c="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},u="__lodash_hash_undefined__",l="[object Function]",p="[object GeneratorFunction]",d=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,h=/^\w*$/,f=/^\./,g=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,v=/\\(\\)?/g,y=/^\[object .+?Constructor\]$/,b="object"==typeof c&&c&&c.Object===Object&&c,w="object"==typeof self&&self&&self.Object===Object&&self,m=b||w||Function("return this")();var O,k=Array.prototype,j=Function.prototype,I=Object.prototype,_=m["__core-js_shared__"],x=(O=/[^.]+$/.exec(_&&_.keys&&_.keys.IE_PROTO||""))?"Symbol(src)_1."+O:"",S=j.toString,P=I.hasOwnProperty,U=I.toString,R=RegExp("^"+S.call(P).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),T=m.Symbol,E=k.splice,C=F(m,"Map"),D=F(Object,"create"),A=T?T.prototype:void 0,q=A?A.toString:void 0;function $(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function J(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function M(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function N(e,t){for(var n,r,o=e.length;o--;)if((n=e[o][0])===(r=t)||n!=n&&r!=r)return o;return-1}function K(e,t){var n;t=function(e,t){if(G(e))return!1;var n=typeof e;if("number"==n||"symbol"==n||"boolean"==n||null==e||V(e))return!0;return h.test(e)||!d.test(e)||null!=t&&e in Object(t)}(t,e)?[t]:G(n=t)?n:z(n);for(var r=0,o=t.length;null!=e&&r<o;)e=e[H(t[r++])];return r&&r==o?e:void 0}function L(e){if(!Z(e)||(t=e,x&&x in t))return!1;var t,n=function(e){var t=Z(e)?U.call(e):"";return t==l||t==p}(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e)?R:y;return n.test(function(e){if(null!=e){try{return S.call(e)}catch(e){}try{return e+""}catch(e){}}return""}(e))}function B(e,t){var n,r,o=e.__data__;return("string"==(r=typeof(n=t))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==n:null===n)?o["string"==typeof t?"string":"hash"]:o.map}function F(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return L(n)?n:void 0}$.prototype.clear=function(){this.__data__=D?D(null):{}},$.prototype.delete=function(e){return this.has(e)&&delete this.__data__[e]},$.prototype.get=function(e){var t=this.__data__;if(D){var n=t[e];return n===u?void 0:n}return P.call(t,e)?t[e]:void 0},$.prototype.has=function(e){var t=this.__data__;return D?void 0!==t[e]:P.call(t,e)},$.prototype.set=function(e,t){return this.__data__[e]=D&&void 0===t?u:t,this},J.prototype.clear=function(){this.__data__=[]},J.prototype.delete=function(e){var t=this.__data__,n=N(t,e);return!(n<0)&&(n==t.length-1?t.pop():E.call(t,n,1),!0)},J.prototype.get=function(e){var t=this.__data__,n=N(t,e);return n<0?void 0:t[n][1]},J.prototype.has=function(e){return N(this.__data__,e)>-1},J.prototype.set=function(e,t){var n=this.__data__,r=N(n,e);return r<0?n.push([e,t]):n[r][1]=t,this},M.prototype.clear=function(){this.__data__={hash:new $,map:new(C||J),string:new $}},M.prototype.delete=function(e){return B(this,e).delete(e)},M.prototype.get=function(e){return B(this,e).get(e)},M.prototype.has=function(e){return B(this,e).has(e)},M.prototype.set=function(e,t){return B(this,e).set(e,t),this};var z=W((function(e){var t;e=null==(t=e)?"":function(e){if("string"==typeof e)return e;if(V(e))return q?q.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}(t);var n=[];return f.test(e)&&n.push(""),e.replace(g,(function(e,t,r,o){n.push(r?o.replace(v,"$1"):t||e)})),n}));function H(e){if("string"==typeof e||V(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function W(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],a=n.cache;if(a.has(o))return a.get(o);var i=e.apply(this,r);return n.cache=a.set(o,i),i};return n.cache=new(W.Cache||M),n}W.Cache=M;var G=Array.isArray;function Z(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function V(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==U.call(e)}var Q,X=function(e,t,n){var r=null==e?void 0:K(e,t);return void 0===r?n:r},Y="/v1/auth/accesskey/exchange",ee="/v1/auth/otp/verify",te="/v1/auth/otp/signin",ne="/v1/auth/otp/signup",re={email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},oe="/v1/auth/otp/signup-in",ae="/v1/auth/magiclink/verify",ie="/v1/auth/magiclink/signin",se="/v1/auth/magiclink/signup",ce="/v1/auth/magiclink/pending-session",ue={email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},le="/v1/auth/magiclink/signup-in",pe="/v1/auth/oauth/authorize",de="/v1/auth/oauth/exchange",he="/v1/auth/saml/authorize",fe="/v1/auth/saml/exchange",ge="/v1/auth/totp/verify",ve="/v1/auth/totp/signup",ye="/v1/user/totp/update",be={start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},we={start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},me={start:"/v1/auth/webauthn/signup-in/start"},Oe={start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"},ke="/v1/flow/start",je="/v1/flow/next";!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(Q||(Q={}));const Ie=()=>{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")}},_e=(...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,r])=>(e[n]=r,e)),e),e}),{})),xe=e=>void 0===e?void 0:JSON.stringify(e),Se=(e,t="")=>{let n=e;return""!==t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},Pe=({baseUrl:e,projectId:t,baseConfig:n,logger:r,hooks:o,cookiePolicy:a})=>{const i=((e,t)=>{const n=t||fetch;if(!n)throw new Error("fetch is not defined");return e?async(...t)=>{e.log((e=>Ie().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const r=await n(...t);return e[r.ok?"log":"error"](await(async e=>{const t=await e.text();return e.text=()=>Promise.resolve(t),e.json=()=>Promise.resolve(JSON.parse(t)),Ie().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(r)),r}:n})(r),s=async r=>{const s=(null==o?void 0:o.beforeRequest)?o.beforeRequest(r):r,{path:c,body:u,headers:l,queryParams:p,method:d,token:h}=s,f=await i((({path:e,baseUrl:t,queryParams:n})=>{const r=new URL(e,t);return n&&(r.search=new URLSearchParams(n).toString()),r})({path:c,baseUrl:e,queryParams:p}),{headers:_e(Se(t,h),{"x-descope-sdk-name":"core-js","x-descope-sdk-version":"0.0.41-alpha.27"},(null==n?void 0:n.baseHeaders)||{},l),method:d,body:xe(u),credentials:a||"include"});return(null==o?void 0:o.afterRequest)&&o.afterRequest(r,null==f?void 0:f.clone()),f};return{get:(e,{headers:t,queryParams:n,token:r}={})=>s({path:e,headers:t,queryParams:n,body:void 0,method:Q.get,token:r}),post:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.post,token:o}),put:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.put,token:o}),delete:(e,t,{headers:n,queryParams:r,token:o}={})=>s({path:e,headers:n,queryParams:r,body:t,method:Q.delete,token:o})}};function Ue(e,t,n){var r;let o=Re(e);t&&(o=null===(r=o.tenants)||void 0===r?void 0:r[t]);const a=o[n];return Array.isArray(a)?a:[]}function Re(e){if("string"!=typeof e||!e)throw new Error("Invalid token provided");return s(e)}function Te(e){const{exp:t}=Re(e);return(new Date).getTime()/1e3>t}function Ee(e,t){return Ue(e,t,"permissions")}function Ce(e,t){return Ue(e,t,"roles")}const De=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function Ae(e){const t=await e,n={code:t.status,ok:t.ok,response:t},r=await t.clone().json();return t.ok?n.data=r:n.error=r,n}const qe=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),$e=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),Je=e=>t=>e.test(t),Me=Je(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),Ne=Je(/^\+[1-9]{1}[0-9]{3,14}$/),Ke=qe(Me,'"{val}" is not a valid email'),Le=qe(Ne,'"{val}" is not a valid phone number'),Be=qe((1,e=>e.length>=1),"Minimum length is 1");const Fe=qe((e=>"string"==typeof e),"Input is not a string"),ze=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>$e(...e).validate(n[t]))),t(...n)),He=e=>[Fe(`"${e}" must be a string`),Be(`"${e}" must not be empty`)],We=e=>[Fe(`"${e}" must be a string`),Ke()],Ge=e=>[Fe(`"${e}" must be a string`),Le()],Ze=ze(He("accessKey")),Ve=e=>({exchange:Ze((t=>Ae(e.post(Y,{},{token:t}))))});var Qe,Xe,Ye,et,tt;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(Qe||(Qe={})),function(e){e.email="email",e.sms="sms",e.whatsapp="whatsapp"}(Xe||(Xe={})),function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(Ye||(Ye={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify"}(et||(et={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify",e.updatePhone="updatePhone"}(tt||(tt={}));const nt=He("identifier"),rt=ze(nt,He("code")),ot=ze(nt),at=ze(nt,Ge("phone")),it=ze(nt,We("email")),st=e=>({verify:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:rt(((t,r)=>Ae(e.post(De(ee,n),{code:r,externalId:t}))))})),{}),signIn:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ot(((t,r,o)=>Ae(e.post(De(te,n),{externalId:t,loginOptions:r},{token:o}))))})),{}),signUp:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ot(((t,r)=>Ae(e.post(De(ne,n),{externalId:t,user:r}))))})),{}),signUpOrIn:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ot((t=>Ae(e.post(De(oe,n),{externalId:t}))))})),{}),update:{email:it(((t,n,r)=>Ae(e.post(re.email,{externalId:t,email:n},{token:r})))),phone:Object.keys(Qe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:at(((t,r,o)=>Ae(e.post(De(re.phone,n),{externalId:t,phone:r},{token:o}))))})),{})}}),ct=He("identifier"),ut=He("uri"),lt=ze(He("token")),pt=ze(ct,ut),dt=ze(He("pendingRef")),ht=ze(ct,Ge("phone"),ut),ft=ze(ct,We("email"),ut),gt=e=>({verify:lt((t=>Ae(e.post(ae,{token:t})))),signIn:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:pt(((t,r,o,a)=>Ae(e.post(De(ie,n),{externalId:t,URI:r,crossDevice:!0,loginOptions:o},{token:a}))))})),{}),signUpOrIn:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:pt(((t,r)=>Ae(e.post(De(le,n),{externalId:t,URI:r,crossDevice:!0}))))})),{}),signUp:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:pt(((t,r,o)=>Ae(e.post(De(se,n),{externalId:t,URI:r,user:o,crossDevice:!0}))))})),{}),waitForSession:dt(((t,n)=>new Promise((r=>{const{pollingIntervalMs:o,timeoutMs:a}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||6e5,6e5)}))(n);let i;const s=setInterval((async()=>{const n=await e.post(ce,{pendingRef:t});n.ok&&(clearInterval(s),i&&clearTimeout(i),r(Ae(Promise.resolve(n))))}),o);i=setTimeout((()=>{r({error:{message:`Session polling timeout exceeded: ${a}ms`,code:"0"},ok:!1}),clearInterval(s)}),a)})))),update:{email:ft(((t,n,r,o)=>Ae(e.post(ue.email,{externalId:t,email:n,URI:r,crossDevice:!0},{token:o})))),phone:Object.keys(Qe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ht(((t,r,o,a)=>Ae(e.post(De(ue.phone,n),{externalId:t,phone:r,URI:o,crossDevice:!0},{token:a}))))})),{})}}),vt=e=>({verify:lt((t=>Ae(e.post(ae,{token:t})))),signIn:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:pt(((t,r,o,a)=>Ae(e.post(De(ie,n),{externalId:t,URI:r,loginOptions:o},{token:a}))))})),{}),signUp:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:pt(((t,r,o)=>Ae(e.post(De(se,n),{externalId:t,URI:r,user:o}))))})),{}),signUpOrIn:Object.keys(Xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:pt(((t,r)=>Ae(e.post(De(le,n),{externalId:t,URI:r}))))})),{}),update:{email:ft(((t,n,r,o)=>Ae(e.post(ue.email,{externalId:t,email:n,URI:r},{token:o})))),phone:Object.keys(Qe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ht(((t,r,o,a)=>Ae(e.post(De(ue.phone,n),{externalId:t,phone:r,URI:o},{token:a}))))})),{})},crossDevice:gt(e)});var yt;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple"}(yt||(yt={}));const bt=ze(He("code")),wt=e=>({start:Object.keys(yt).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:async(t,{redirect:r=!1}={},o,a)=>{const i=await e.post(pe,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:a});if(!r||!i.ok)return Ae(Promise.resolve(i));const{url:s}=await i.json();window.location.href=s}})),{}),exchange:bt((t=>Ae(e.post(de,{code:t}))))}),mt=ze(He("flowId")),Ot=ze(He("executionId"),He("stepId"),He("interactionId")),kt=e=>({start:mt(((t,n)=>Ae(e.post(ke,{flowId:t,options:n})))),next:Ot(((t,n,r,o)=>Ae(e.post(je,{executionId:t,stepId:n,interactionId:r,input:o}))))}),jt=ze(He("tenant")),It=ze(He("code")),_t=e=>({start:jt((async(t,n,{redirect:r=!1}={},o,a)=>{const i=await e.post(he,o||{},{queryParams:{tenant:t,redirectURL:n},token:a});if(!r||!i.ok)return Ae(Promise.resolve(i));const{url:s}=await i.json();window.location.href=s})),exchange:It((t=>Ae(e.post(fe,{code:t}))))}),xt=He("identifier"),St=ze(xt,He("code")),Pt=ze(xt),Ut=ze(xt),Rt=e=>({signUp:Pt(((t,n)=>Ae(e.post(ve,{externalId:t,user:n})))),verify:St(((t,n,r,o)=>Ae(e.post(ge,{externalId:t,code:n,loginOptions:r},{token:o})))),update:Ut(((t,n)=>Ae(e.post(ye,{externalId:t},{token:n}))))}),Tt=He("identifier"),Et=He("origin"),Ct=ze(Tt,Et,He("name")),Dt=ze(Tt,Et),At=ze(Tt,Et,He("token")),qt=ze(He("transactionId"),He("response")),$t=e=>({signUp:{start:Ct(((t,n,r)=>Ae(e.post(be.start,{user:{externalId:t,name:r},origin:n})))),finish:qt(((t,n)=>Ae(e.post(be.finish,{transactionId:t,response:n}))))},signIn:{start:Dt(((t,n,r,o)=>Ae(e.post(we.start,{externalId:t,origin:n,loginOptions:r},{token:o})))),finish:qt(((t,n)=>Ae(e.post(we.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:Dt(((t,n)=>Ae(e.post(me.start,{externalId:t,origin:n}))))},update:{start:At(((t,n,r)=>Ae(e.post(Oe.start,{externalId:t,origin:n},{token:r})))),finish:qt(((t,n)=>Ae(e.post(Oe.finish,{transactionId:t,response:n}))))}}),Jt=ze(He("token"));var Mt;const Nt=ze([("projectId",Mt=He("projectId"),qe(((e,t)=>e=>$e(...t).validate(X(e,"projectId")))(0,Mt))())])((({projectId:e,logger:t,baseUrl:n,hooks:r,cookiePolicy:o})=>{return a=Pe({baseUrl:n||"https://api.descope.com",projectId:e,logger:t,hooks:r,cookiePolicy:o}),{accessKey:Ve(a),otp:st(a),magicLink:vt(a),oauth:wt(a),saml:_t(a),totp:Rt(a),webauthn:$t(a),flow:kt(a),refresh:e=>Ae(a.post("/v1/auth/refresh",{},{token:e})),logout:e=>Ae(a.post("/v1/auth/logout",{},{token:e})),logoutAll:e=>Ae(a.post("/v1/auth/logoutall",{},{token:e})),me:e=>Ae(a.get("/v1/auth/me",{token:e})),isJwtExpired:Jt(Te),getJwtPermissions:Jt(Ee),getJwtRoles:Jt(Ce),httpClient:a};var a}));Nt.DeliveryMethods=Xe;const Kt="vsid",Lt="vrid";function Bt(e,t,n){return void 0===n&&(n=0),t(n).catch((function(r){if(n>=e.maxRetries||!e.shouldRetry(r))throw r;var o,a,i,s,c=(o=e.baseDelay,a=e.maxDelay,i=e.baseDelay*Math.pow(2,n),Math.max(o,Math.min(a,i)));return(s=c,new Promise((function(e){return setTimeout(e,s)}))).then((function(){return Bt(e,t,n+1)}))}))}var Ft="Failed to load the JS script of the agent";function zt(n){var r,o=n.scriptUrlPattern,a=n.token,i=n.apiKey,s=void 0===i?a:i,c=t(n,["scriptUrlPattern","token","apiKey"]),u=(r=n,"scriptUrlPattern",Object.prototype.hasOwnProperty.call(r,"scriptUrlPattern")?o:void 0),l=[];return Promise.resolve().then((function(){if(!s||"string"!=typeof s)throw new Error("API key required");return Bt({maxRetries:5,baseDelay:100,maxDelay:3e3,shouldRetry:function(e){return!(e instanceof Error&&"Blocked by CSP"===e.message)}},(function(){var e,t=new Date,n=function(){return l.push({startedAt:t,finishedAt:new Date})},r=function(e,t,n,r){var o,a=document,i="securitypolicyviolation",s=function(t){var n=new URL(e,location.href),r=t.blockedURI;r!==n.href&&r!==n.protocol.slice(0,-1)&&r!==n.origin||(o=t,c())};a.addEventListener(i,s);var c=function(){return a.removeEventListener(i,s)};return Promise.resolve().then(t).then((function(e){return c(),e}),(function(e){return new Promise((function(e){return setTimeout(e)})).then((function(){if(c(),o)return function(){throw new Error("Blocked by CSP")}();throw e}))}))}(e=function(e,t){void 0===t&&(t="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js");var n=encodeURIComponent;return t.replace(/<[^<>]+>/g,(function(t){return"<version>"===t?"3":"<apiKey>"===t?n(e):"<loaderVersion>"===t?n("3.7.1"):t}))}(s,u),(function(){return function(e){return new Promise((function(t,n){var r=document.createElement("script"),o=function(){var e;return null===(e=r.parentNode)||void 0===e?void 0:e.removeChild(r)},a=document.head||document.getElementsByTagName("head")[0];r.onload=function(){o(),t()},r.onerror=function(){o(),n(new Error(Ft))},r.async=!0,r.src=e,a.appendChild(r)}))}(e)}));return r.then(n,n),r}))})).then((function(){var t=window,n="__fpjs_p_l_b",r=t[n];if(function(e,t){var n,r=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==r?void 0:r.configurable)?delete e[t]:r&&!r.writable||(e[t]=void 0)}(t,n),"function"!=typeof(null==r?void 0:r.load))throw new Error(Ft);return r.load(e(e({},c),{ldi:{attempts:l}}))}))}const Ht=e=>new Proxy(new URLSearchParams(window.location.search),{get:(e,t)=>e.get(t.toString())})[e],Wt=e=>{const t=zt({apiKey:e||"A9aCLRHzKCv3uL69oqDr"});return{get:async()=>{try{let e=sessionStorage.getItem(Kt);e||(e=Ht(Kt)),e||(e=(Date.now().toString(36)+Math.random().toString(36).substring(2)+Math.random().toString(36).substring(2)).substring(0,27)),sessionStorage.setItem(Kt,e);const n=await t,r=await n.get({linkedId:e});sessionStorage.setItem(Lt,r.requestId)}catch(e){global.FB_DEBUG&&console.error(e)}}}};var Gt,Zt,Vt,Qt,Xt;const Yt=e=>Object.assign({},e);class en{constructor(e){Gt.add(this),Zt.set(this,void 0),Vt.set(this,{}),Qt.set(this,0),r(this,Zt,e,"f")}get current(){return Yt(n(this,Zt,"f"))}update(e){const t=e;if(!((e,t)=>{const n=e&&Object.getOwnPropertyNames(e)||[],r=t&&Object.getOwnPropertyNames(t)||[];if(n.length!==r.length)return!1;for(let r=0;r<n.length;r+=1){const o=n[r];if(e[o]!==t[o])return!1}return!0})(n(this,Zt,"f"),t)){const e=n(this,Zt,"f");r(this,Zt,t,"f"),Object.freeze(n(this,Zt,"f")),setTimeout((()=>{Object.values(n(this,Vt,"f")).forEach((n=>n(Yt(t),e)))}),0)}}subscribe(e){r(this,Qt,n(this,Qt,"f")+1,"f"),n(this,Vt,"f")[n(this,Qt,"f")]=e;const t=n(this,Qt,"f");return()=>n(this,Gt,"m",Xt).call(this,t.toString())}unsubscribeAll(){r(this,Vt,{},"f")}}
2
2
  /*! js-cookie v3.0.1 | MIT */
3
- function tn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)e[r]=n[r]}return e}Zt=new WeakMap,Vt=new WeakMap,Qt=new WeakMap,Gt=new WeakSet,Xt=function(e){!!n(this,Vt,"f")[e]&&delete n(this,Vt,"f")[e]};var nn=function e(t,n){function r(e,r,o){if("undefined"!=typeof document){"number"==typeof(o=tn({},n,o)).expires&&(o.expires=new Date(Date.now()+864e5*o.expires)),o.expires&&(o.expires=o.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var a in o)o[a]&&(i+="; "+a,!0!==o[a]&&(i+="="+o[a].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+i}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},o=0;o<n.length;o++){var i=n[o].split("="),a=i.slice(1).join("=");try{var s=decodeURIComponent(i[0]);if(r[s]=t.read(a,s),e===s)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",tn({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,tn({},this.attributes,t))},withConverter:function(t){return e(tn({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const rn="DSR";let on=[];function an(e,t,n){const r=function(e){const t=e.split(".");try{if(3===t.length){const t=JSON.parse(window.atob(e.split(".")[1]));if(t.exp)return new Date(1e3*t.exp)}}catch(e){}return null}(t);if(r){let t;for(;t=on.pop();)clearTimeout(t);const o=r.getTime()-2e4-(new Date).getTime(),i=setTimeout((()=>{e(n)}),o);on.push(i)}}function sn(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:r}){e&&nn.set("DS",e,{path:t,domain:n,expires:r,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem(rn,e)}(t)}function cn(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem(rn):""}async function un(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=pn(n.publicKey.challenge),n.publicKey.user.id=pn(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=pn(e.id)})),n}(e),n=await navigator.credentials.create(t);return r=n,JSON.stringify(Object.assign(Object.assign({},r),{rawId:dn(r.rawId),response:Object.assign(Object.assign({},r.response),{attestationObject:dn(r.response.attestationObject),clientDataJSON:dn(r.response.clientDataJSON)})}));var r}async function ln(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=pn(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=pn(e.id)})),n}(e),n=await navigator.credentials.get(t);return r=n,JSON.stringify(Object.assign(Object.assign({},r),{rawId:dn(r.rawId),response:Object.assign(Object.assign({},r.response),{authenticatorData:dn(r.response.authenticatorData),clientDataJSON:dn(r.response.clientDataJSON),signature:dn(r.response.signature),userHandle:r.response.userHandle?dn(r.response.userHandle):void 0})}));var r}function pn(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function dn(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}const hn="undefined"!=typeof window;return e=>{var{autoRefresh:n=!0,persistTokens:r=!0}=e,o=t(e,["autoRefresh","persistTokens"]);hn?Wt(o.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const i=o;let a,s;const c=new en({sessionToken:""}),u=new en({});i.hooks={beforeRequest:e=>null==a?void 0:a(e),afterRequest:(e,t)=>null==s?void 0:s(e,t)};const l=Nt(i),p=Object.assign(Object.assign({},l),{webauthn:(d=l,{async signUp(e,t){const n=await d.webauthn.signUp.start(e,window.location.origin,t),r=await un(n.data.options);return await d.webauthn.signUp.finish(n.data.transactionId,r)},async signIn(e){const t=await d.webauthn.signIn.start(e,window.location.origin),n=await ln(t.data.options);return await d.webauthn.signIn.finish(t.data.transactionId,n)},async signUpOrIn(e){var t;const n=await d.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=n.data)||void 0===t?void 0:t.create){const e=await un(n.data.options);return await d.webauthn.signUp.finish(n.data.transactionId,e)}{const e=await ln(n.data.options);return await d.webauthn.signIn.finish(n.data.transactionId,e)}},async update(e,t){const n=await d.webauthn.update.start(e,window.location.origin,t),r=await un(n.data.options);return await d.webauthn.update.finish(n.data.transactionId,r)},helpers:{create:un,get:ln}}),onSessionTokenChange:e=>{var t;const n=null===(t=c.current)||void 0===t?void 0:t.sessionToken;return n&&e(n),c.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=u.current;return t&&Object.entries(t).length>0&&e(t),u.subscribe((t=>{e(t)}))}});var d;return n&&(p.logout=(...e)=>{const t=cn(),n=[(null==e?void 0:e.shift())||t,...e],r=l.logout(...n);return localStorage&&localStorage.removeItem(rn),nn.remove("DS"),r}),a=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{[Kt]:sessionStorage.getItem(Kt)||"",[Lt]:sessionStorage.getItem(Lt)||""})),!e.token&&r&&(e.token=cn()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.6"}),e},(n||r)&&(s=(e,o)=>{!async function(e,n,r,o){try{if(401===n.status)return r.sessionToken.update({sessionToken:""}),void r.user.update({});const i=await(null==n?void 0:n.json());if(i){const n=function(e){return(null==e?void 0:e.authInfo)||e||{}}(i),{sessionJwt:a,refreshJwt:s,user:c}=n,u=t(n,["sessionJwt","refreshJwt","user"]);o.persistTokens&&sn(a,s,u),a&&r.sessionToken.update({sessionToken:a}),c&&r.user.update(c),a&&s&&o.autoRefresh&&an(e,a,s)}}catch(e){console.error("Could not set tokens from body",e)}}(p.refresh,o,{sessionToken:c,user:u},{autoRefresh:n,persistTokens:r})}),n&&p.refresh(),p}}));
3
+ function tn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)e[r]=n[r]}return e}Zt=new WeakMap,Vt=new WeakMap,Qt=new WeakMap,Gt=new WeakSet,Xt=function(e){!!n(this,Vt,"f")[e]&&delete n(this,Vt,"f")[e]};var nn=function e(t,n){function r(e,r,o){if("undefined"!=typeof document){"number"==typeof(o=tn({},n,o)).expires&&(o.expires=new Date(Date.now()+864e5*o.expires)),o.expires&&(o.expires=o.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var i in o)o[i]&&(a+="; "+i,!0!==o[i]&&(a+="="+o[i].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+a}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],r={},o=0;o<n.length;o++){var a=n[o].split("="),i=a.slice(1).join("=");try{var s=decodeURIComponent(a[0]);if(r[s]=t.read(i,s),e===s)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",tn({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,tn({},this.attributes,t))},withConverter:function(t){return e(tn({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(n)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const rn="DSR";let on=[];function an(e,t,n){const r=function(e){const t=e.split(".");try{if(3===t.length){const t=JSON.parse(window.atob(e.split(".")[1]));if(t.exp)return new Date(1e3*t.exp)}}catch(e){}return null}(t);if(r){let t;for(;t=on.pop();)clearTimeout(t);const o=r.getTime()-2e4-(new Date).getTime(),a=setTimeout((()=>{e(n)}),o);on.push(a)}}function sn(e,t,n){!function(e,{cookiePath:t,cookieDomain:n,cookieExpiration:r}){e&&nn.set("DS",e,{path:t,domain:n,expires:r,sameSite:"None",secure:!0})}(e,n),function(e){localStorage&&e&&localStorage.setItem(rn,e)}(t)}function cn(){return localStorage?null===localStorage||void 0===localStorage?void 0:localStorage.getItem(rn):""}async function un(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=pn(n.publicKey.challenge),n.publicKey.user.id=pn(n.publicKey.user.id),null===(t=n.publicKey.excludeCredentials)||void 0===t||t.forEach((e=>{e.id=pn(e.id)})),n}(e),n=await navigator.credentials.create(t);return r=n,JSON.stringify(Object.assign(Object.assign({},r),{rawId:dn(r.rawId),response:Object.assign(Object.assign({},r.response),{attestationObject:dn(r.response.attestationObject),clientDataJSON:dn(r.response.clientDataJSON)})}));var r}async function ln(e){const t=function(e){var t;const n=JSON.parse(e);return n.publicKey.challenge=pn(n.publicKey.challenge),null===(t=n.publicKey.allowCredentials)||void 0===t||t.forEach((e=>{e.id=pn(e.id)})),n}(e),n=await navigator.credentials.get(t);return r=n,JSON.stringify(Object.assign(Object.assign({},r),{rawId:dn(r.rawId),response:Object.assign(Object.assign({},r.response),{authenticatorData:dn(r.response.authenticatorData),clientDataJSON:dn(r.response.clientDataJSON),signature:dn(r.response.signature),userHandle:r.response.userHandle?dn(r.response.userHandle):void 0})}));var r}function pn(e){const t=e.replace(/_/g,"/").replace(/-/g,"+");return Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer}function dn(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}const hn="undefined"!=typeof window;return e=>{var{autoRefresh:n=!0,persistTokens:r=!0}=e,o=t(e,["autoRefresh","persistTokens"]);hn?Wt(o.fpKey).get().catch((()=>null)):console.warn("Fingerprint is a client side only capability and will not work when running in the server");const a=o;let i,s;const c=new en({sessionToken:""}),u=new en({});a.hooks={beforeRequest:e=>null==i?void 0:i(e),afterRequest:(e,t)=>null==s?void 0:s(e,t)};const l=Nt(a),p=Object.assign(Object.assign({},l),{webauthn:(d=l,{async signUp(e,t){const n=await d.webauthn.signUp.start(e,window.location.origin,t),r=await un(n.data.options);return await d.webauthn.signUp.finish(n.data.transactionId,r)},async signIn(e){const t=await d.webauthn.signIn.start(e,window.location.origin),n=await ln(t.data.options);return await d.webauthn.signIn.finish(t.data.transactionId,n)},async signUpOrIn(e){var t;const n=await d.webauthn.signUpOrIn.start(e,window.location.origin);if(null===(t=n.data)||void 0===t?void 0:t.create){const e=await un(n.data.options);return await d.webauthn.signUp.finish(n.data.transactionId,e)}{const e=await ln(n.data.options);return await d.webauthn.signIn.finish(n.data.transactionId,e)}},async update(e,t){const n=await d.webauthn.update.start(e,window.location.origin,t),r=await un(n.data.options);return await d.webauthn.update.finish(n.data.transactionId,r)},helpers:{create:un,get:ln}}),onSessionTokenChange:e=>{var t;const n=null===(t=c.current)||void 0===t?void 0:t.sessionToken;return n&&e(n),c.subscribe((({sessionToken:t})=>{e(t)}))},onUserChange:e=>{const t=u.current;return t&&Object.entries(t).length>0&&e(t),u.subscribe((t=>{e(t)}))}});var d;return n&&["logout","logoutAll"].forEach((e=>{const t=l[e];p[e]=(...e)=>{const n=cn(),r=[(null==e?void 0:e.shift())||n,...e],o=t(...r);return localStorage&&localStorage.removeItem(rn),nn.remove("DS"),c.update({sessionToken:""}),o}})),i=e=>{var t;return e.queryParams=(t=e.queryParams,Object.assign(Object.assign({},t),{[Kt]:sessionStorage.getItem(Kt)||"",[Lt]:sessionStorage.getItem(Lt)||""})),!e.token&&r&&(e.token=cn()),e.headers=Object.assign(Object.assign({},e.headers),{"x-descope-sdk-name":"web-js","x-descope-sdk-version":"0.1.0-alpha.8"}),e},p.me=async(...e)=>{var t;const n=await l.me(...e);if(n.ok){const e=await(null===(t=n.response)||void 0===t?void 0:t.clone().json());u.update(e)}return n},(n||r)&&(s=(e,o)=>{!async function(e,n,r,o){try{if(401===n.status)return r.sessionToken.update({sessionToken:""}),void r.user.update({});const a=await(null==n?void 0:n.json());if(a){const n=function(e){return(null==e?void 0:e.authInfo)||e||{}}(a),{sessionJwt:i,refreshJwt:s,user:c}=n,u=t(n,["sessionJwt","refreshJwt","user"]);o.persistTokens&&sn(i,s,u),i&&r.sessionToken.update({sessionToken:i}),c&&r.user.update(c),i&&s&&o.autoRefresh&&an(e,i,s)}}catch(e){console.error("Could not set tokens from body",e)}}(p.refresh,o,{sessionToken:c,user:u},{autoRefresh:n,persistTokens:r})}),n&&cn()&&p.refresh(),p}}));
4
4
  //# sourceMappingURL=index.umd.js.map