@teamhanko/hanko-frontend-sdk
Version:
A package for simplifying UI integration with the Hanko API. It is meant for use in browsers only.
3 lines (2 loc) • 37.9 kB
JavaScript
function e(){return e=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},e.apply(null,arguments)}function t(e){return t=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},t(e)}function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,r(e,t)}function i(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(i=function(){return!!e})()}function r(e,t){return r=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},r(e,t)}function o(e){var n="function"==typeof Map?new Map:void 0;return o=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(e))return n.get(e);n.set(e,o)}function o(){return function(e,t,n){if(i())return Reflect.construct.apply(null,arguments);var o=[null];o.push.apply(o,t);var s=new(e.bind.apply(e,o));return n&&r(s,n.prototype),s}(e,arguments,t(this).constructor)}return o.prototype=Object.create(e.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),r(o,e)},o(e)}var s=/*#__PURE__*/function(){function e(){}return e.throttle=function(e,t,n){void 0===n&&(n={});var i,r,o,s=n.leading,a=void 0===s||s,c=n.trailing,u=void 0===c||c,h=0,l=function(){h=!1===a?0:Date.now(),o=null,e.apply(i,r)};return function(){var n=Date.now();h||!1!==a||(h=n);var s=t-(n-h);i=this,r=[].slice.call(arguments),s<=0||s>t?(o&&(window.clearTimeout(o),o=null),h=n,e.apply(i,r)):o||!1===u||(o=window.setTimeout(l,s))}},e}(),a="hanko-session-created",c="hanko-session-expired",u="hanko-user-logged-out",h="hanko-user-deleted",l="hanko-after-state-change",d="hanko-before-state-change",f=/*#__PURE__*/function(e){function t(t,n){return e.call(this,t,{detail:n})||this}return n(t,e),t}(/*#__PURE__*/o(CustomEvent)),v=/*#__PURE__*/function(){function e(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=s.throttle}var t=e.prototype;return t.wrapCallback=function(e,t){var n=function(t){e(t.detail)};return t?this._throttle(n,this.throttleLimit,{leading:!0,trailing:!1}):n},t.addEventListenerWithType=function(e){var t=this,n=e.type,i=e.once,r=void 0!==i&&i,o=e.throttle,s=this.wrapCallback(e.callback,void 0!==o&&o);return this._addEventListener(n,s,{once:r}),function(){return t._removeEventListener(n,s)}},e.mapAddEventListenerParams=function(e,t,n){return{type:e,callback:t.callback,once:t.once,throttle:n}},t.addEventListener=function(t,n,i){return this.addEventListenerWithType(e.mapAddEventListenerParams(t,n,i))},t.onSessionCreated=function(e,t){return this.addEventListener(a,{callback:e,once:t},!0)},t.onSessionExpired=function(e,t){return this.addEventListener(c,{callback:e,once:t},!0)},t.onUserLoggedOut=function(e,t){return this.addEventListener(u,{callback:e,once:t})},t.onUserDeleted=function(e,t){return this.addEventListener(h,{callback:e,once:t})},t.onAfterStateChange=function(e,t){return this.addEventListener(l,{callback:e,once:t},!1)},t.onBeforeStateChange=function(e,t){return this.addEventListener(d,{callback:e,once:t},!1)},e}(),p=/*#__PURE__*/function(){function e(){this._dispatchEvent=document.dispatchEvent.bind(document)}var t=e.prototype;return t.dispatch=function(e,t){this._dispatchEvent(new f(e,t))},t.dispatchSessionCreatedEvent=function(e){this.dispatch(a,e)},t.dispatchSessionExpiredEvent=function(){this.dispatch(c,null)},t.dispatchUserLoggedOutEvent=function(){this.dispatch(u,null)},t.dispatchUserDeletedEvent=function(){this.dispatch(h,null)},t.dispatchAfterStateChangeEvent=function(e){this.dispatch(l,e)},t.dispatchBeforeStateChangeEvent=function(e){this.dispatch(d,e)},e}(),m=/*#__PURE__*/function(e){function t(n,i,r){var o;return(o=e.call(this,n)||this).code=void 0,o.cause=void 0,o.code=i,o.cause=r,Object.setPrototypeOf(o,t.prototype),o}return n(t,e),t}(/*#__PURE__*/o(Error)),y=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Technical error","somethingWentWrong",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),g=/*#__PURE__*/function(e){function t(n,i){var r;return r=e.call(this,"Conflict error","conflict",i)||this,Object.setPrototypeOf(r,t.prototype),r}return n(t,e),t}(m),S=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Request timed out error","requestTimeout",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),w=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Request cancelled error","requestCancelled",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),k=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Invalid password error","invalidPassword",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),b=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Invalid Passcode error","invalidPasscode",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),C=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Invalid WebAuthn credential error","invalidWebauthnCredential",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),P=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Passcode expired error","passcodeExpired",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),E=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Maximum number of Passcode attempts reached error","passcodeAttemptsReached",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),_=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Not found error","notFound",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),x=/*#__PURE__*/function(e){function t(n,i){var r;return(r=e.call(this,"Too many requests error","tooManyRequests",i)||this).retryAfter=void 0,r.retryAfter=n,Object.setPrototypeOf(r,t.prototype),r}return n(t,e),t}(m),A=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Unauthorized error","unauthorized",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),O=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Forbidden error","forbidden",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),j=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"User verification error","userVerification",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),I=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),L=/*#__PURE__*/function(e){function t(n){var i;return i=e.call(this,"The email address already exists","emailAddressAlreadyExistsError",n)||this,Object.setPrototypeOf(i,t.prototype),i}return n(t,e),t}(m),T=/*#__PURE__*/function(e){function t(n,i){var r;return r=e.call(this,"An error occurred during third party sign up/sign in",n,i)||this,Object.setPrototypeOf(r,t.prototype),r}return n(t,e),t}(m);function N(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)"__proto__"!==i&&(e[i]=n[i])}return e}var D=function e(t,n){function i(e,i,r){if("undefined"!=typeof document){"number"==typeof(r=N({},n,r)).expires&&(r.expires=new Date(Date.now()+864e5*r.expires)),r.expires&&(r.expires=r.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var s in r)r[s]&&(o+="; "+s,!0!==r[s]&&(o+="="+r[s].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+o}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var n=document.cookie?document.cookie.split("; "):[],i={},r=0;r<n.length;r++){var o=n[r].split("="),s=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(a in i||(i[a]=t.read(s,a)),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",N({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,N({},this.attributes,t))},withConverter:function(t){return e(N({},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:"/"}),R=/*#__PURE__*/function(){function t(e){var t,n;this.authCookieName=void 0,this.authCookieDomain=void 0,this.authCookieSameSite=void 0,this.authCookieName=null!=(t=e.cookieName)?t:"hanko",this.authCookieDomain=e.cookieDomain,this.authCookieSameSite=null!=(n=e.cookieSameSite)?n:"lax"}var n=t.prototype;return n.getAuthCookie=function(){return D.get(this.authCookieName)},n.setAuthCookie=function(t,n){var i={secure:!0,sameSite:this.authCookieSameSite};void 0!==this.authCookieDomain&&(i.domain=this.authCookieDomain);var r=e({},i,n);if(("none"===r.sameSite||"None"===r.sameSite)&&!1===r.secure)throw new y(new Error("Secure attribute must be set when SameSite=None"));D.set(this.authCookieName,t,r)},n.removeAuthCookie=function(){D.remove(this.authCookieName)},t}(),K=/*#__PURE__*/function(){function e(e){this.keyName=void 0,this.keyName=e.keyName}var t=e.prototype;return t.getSessionToken=function(){return sessionStorage.getItem(this.keyName)},t.setSessionToken=function(e){sessionStorage.setItem(this.keyName,e)},t.removeSessionToken=function(){sessionStorage.removeItem(this.keyName)},e}(),U=/*#__PURE__*/function(){function e(e){this._xhr=void 0,this._xhr=e}return e.prototype.getResponseHeader=function(e){return this._xhr.getResponseHeader(e)},e}(),q=/*#__PURE__*/function(){function e(e){this.headers=void 0,this.ok=void 0,this.status=void 0,this.statusText=void 0,this.url=void 0,this._decodedJSON=void 0,this.xhr=void 0,this.headers=new U(e),this.ok=e.status>=200&&e.status<=299,this.status=e.status,this.statusText=e.statusText,this.url=e.responseURL,this.xhr=e}var t=e.prototype;return t.json=function(){return this._decodedJSON||(this._decodedJSON=JSON.parse(this.xhr.response)),this._decodedJSON},t.parseNumericHeader=function(e){var t=parseInt(this.headers.getResponseHeader(e),10);return isNaN(t)?0:t},e}(),F=/*#__PURE__*/function(){function t(t,n){var i;this.timeout=void 0,this.api=void 0,this.dispatcher=void 0,this.cookie=void 0,this.sessionTokenStorage=void 0,this.lang=void 0,this.sessionTokenLocation=void 0,this.api=t,this.timeout=null!=(i=n.timeout)?i:13e3,this.dispatcher=new p,this.cookie=new R(e({},n)),this.sessionTokenStorage=new K({keyName:n.cookieName}),this.lang=n.lang,this.sessionTokenLocation=n.sessionTokenLocation}var n=t.prototype;return n._fetch=function(e,t,n){void 0===n&&(n=new XMLHttpRequest);var i=this,r=this.api+e,o=this.timeout,s=this.getAuthToken(),a=this.lang;return new Promise(function(e,c){n.open(t.method,r,!0),n.setRequestHeader("Accept","application/json"),n.setRequestHeader("Content-Type","application/json"),n.setRequestHeader("X-Language",a),s&&n.setRequestHeader("Authorization","Bearer "+s),n.timeout=o,n.withCredentials=!0,n.onload=function(){i.processHeaders(n),e(new q(n))},n.onerror=function(){c(new y)},n.ontimeout=function(){c(new S)},n.send(t.body?t.body.toString():null)})},n.processHeaders=function(e){var t="",n=0,i="";if(e.getAllResponseHeaders().split("\r\n").forEach(function(r){var o=r.toLowerCase();o.startsWith("x-auth-token")?t=e.getResponseHeader("X-Auth-Token"):o.startsWith("x-session-lifetime")?n=parseInt(e.getResponseHeader("X-Session-Lifetime"),10):o.startsWith("x-session-retention")&&(i=e.getResponseHeader("X-Session-Retention"))}),t){var r=new RegExp("^https://"),o=!!this.api.match(r)&&!!window.location.href.match(r),s="session"===i?void 0:new Date((new Date).getTime()+1e3*n);this.setAuthToken(t,{secure:o,expires:s})}},n.get=function(e){return this._fetch(e,{method:"GET"})},n.post=function(e,t){return this._fetch(e,{method:"POST",body:JSON.stringify(t)})},n.put=function(e,t){return this._fetch(e,{method:"PUT",body:JSON.stringify(t)})},n.patch=function(e,t){return this._fetch(e,{method:"PATCH",body:JSON.stringify(t)})},n.delete=function(e){return this._fetch(e,{method:"DELETE"})},n.getAuthToken=function(){var e="";switch(this.sessionTokenLocation){case"cookie":default:e=this.cookie.getAuthCookie();break;case"sessionStorage":e=this.sessionTokenStorage.getSessionToken()}return e},n.setAuthToken=function(e,t){switch(this.sessionTokenLocation){case"cookie":default:return this.cookie.setAuthCookie(e,t);case"sessionStorage":return this.sessionTokenStorage.setSessionToken(e)}},t}(),M=function(e,t){this.client=void 0,this.client=new F(e,t)},H=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}return n(t,e),t.prototype.validate=function(){try{return Promise.resolve(this.client.get("/sessions/validate")).then(function(e){if(!e.ok)throw new y;return Promise.resolve(e.json())})}catch(e){return Promise.reject(e)}},t}(M),W=/*#__PURE__*/function(){function e(e){this.storageKey=void 0,this.defaultState={expiration:0,lastCheck:0},this.storageKey=e}var t=e.prototype;return t.load=function(){var e=window.localStorage.getItem(this.storageKey);return null==e?this.defaultState:JSON.parse(e)},t.save=function(e){window.localStorage.setItem(this.storageKey,JSON.stringify(e||this.defaultState))},e}(),z=function(e,t){var n=this;this.onActivityCallback=void 0,this.onInactivityCallback=void 0,this.handleFocus=function(){n.onActivityCallback()},this.handleBlur=function(){n.onInactivityCallback()},this.handleVisibilityChange=function(){"visible"===document.visibilityState?n.onActivityCallback():n.onInactivityCallback()},this.hasFocus=function(){return document.hasFocus()},this.onActivityCallback=e,this.onInactivityCallback=t,window.addEventListener("focus",this.handleFocus),window.addEventListener("blur",this.handleBlur),document.addEventListener("visibilitychange",this.handleVisibilityChange)},B=/*#__PURE__*/function(){function e(e,t,n){this.intervalID=null,this.timeoutID=null,this.checkInterval=void 0,this.checkSession=void 0,this.onSessionExpired=void 0,this.checkInterval=e,this.checkSession=t,this.onSessionExpired=n}var t=e.prototype;return t.scheduleSessionExpiry=function(e){var t=this;this.stop(),this.timeoutID=setTimeout(function(){try{return t.stop(),t.onSessionExpired(),Promise.resolve()}catch(e){return Promise.reject(e)}},e)},t.start=function(e,t){var n=this;void 0===e&&(e=0),void 0===t&&(t=0);var i=this.calcTimeToNextCheck(e);this.sessionExpiresSoon(t)?this.scheduleSessionExpiry(i):this.timeoutID=setTimeout(function(){try{return Promise.resolve(function(e,t){try{var i=Promise.resolve(n.checkSession()).then(function(e){if(e.is_valid){if(n.sessionExpiresSoon(e.expiration))return void n.scheduleSessionExpiry(e.expiration-Date.now());n.intervalID=setInterval(function(){try{return Promise.resolve(n.checkSession()).then(function(t){(e=t).is_valid?n.sessionExpiresSoon(e.expiration)&&n.scheduleSessionExpiry(e.expiration-Date.now()):n.stop()})}catch(e){return Promise.reject(e)}},n.checkInterval)}else n.stop()})}catch(e){return t(e)}return i&&i.then?i.then(void 0,t):i}(0,function(e){console.log(e)}))}catch(e){return Promise.reject(e)}},i)},t.stop=function(){this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null),this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)},t.isRunning=function(){return null!==this.timeoutID||null!==this.intervalID},t.sessionExpiresSoon=function(e){return e>0&&e-Date.now()<=this.checkInterval},t.calcTimeToNextCheck=function(e){var t=Date.now()-e;return this.checkInterval>=t?this.checkInterval-t%this.checkInterval:0},e}(),J=/*#__PURE__*/function(){function e(e,t,n,i){var r=this;void 0===e&&(e="hanko_session"),this.channel=void 0,this.onSessionExpired=void 0,this.onSessionCreated=void 0,this.onLeadershipRequested=void 0,this.handleMessage=function(e){var t=e.data;switch(t.action){case"sessionExpired":r.onSessionExpired(t);break;case"sessionCreated":r.onSessionCreated(t);break;case"requestLeadership":r.onLeadershipRequested(t)}},this.onSessionExpired=t,this.onSessionCreated=n,this.onLeadershipRequested=i,this.channel=new BroadcastChannel(e),this.channel.onmessage=this.handleMessage}return e.prototype.post=function(e){this.channel.postMessage(e)},e}(),V=/*#__PURE__*/function(e){function t(t,n){var i;(i=e.call(this)||this).listener=new v,i.checkInterval=3e4,i.client=void 0,i.sessionState=void 0,i.windowActivityManager=void 0,i.scheduler=void 0,i.sessionChannel=void 0,i.isLoggedIn=void 0,i.client=new H(t,n),n.sessionCheckInterval&&(i.checkInterval=n.sessionCheckInterval<3e3?3e3:n.sessionCheckInterval),i.sessionState=new W(n.cookieName+"_session_state"),i.sessionChannel=new J(i.getSessionCheckChannelName(n.sessionTokenLocation,n.sessionCheckChannelName),function(){return i.onChannelSessionExpired()},function(e){return i.onChannelSessionCreated(e)},function(){return i.onChannelLeadershipRequested()}),i.scheduler=new B(i.checkInterval,function(){return i.checkSession()},function(){return i.onSessionExpired()}),i.windowActivityManager=new z(function(){return i.startSessionCheck()},function(){return i.scheduler.stop()});var r=Date.now(),o=i.sessionState.load();return i.isLoggedIn=r<o.expiration,i.initializeEventListeners(),i.startSessionCheck(),i}n(t,e);var i=t.prototype;return i.initializeEventListeners=function(){var e=this;this.listener.onSessionCreated(function(t){var n=t.claims,i=Date.parse(n.expiration),r=Date.now();e.isLoggedIn=!0,e.sessionState.save({expiration:i,lastCheck:r}),e.sessionChannel.post({action:"sessionCreated",claims:n}),e.startSessionCheck()}),this.listener.onUserLoggedOut(function(){e.isLoggedIn=!1,e.sessionChannel.post({action:"sessionExpired"}),e.sessionState.save(null),e.scheduler.stop()}),window.addEventListener("beforeunload",function(){return e.scheduler.stop()})},i.startSessionCheck=function(){if(this.windowActivityManager.hasFocus()&&(this.sessionChannel.post({action:"requestLeadership"}),!this.scheduler.isRunning())){var e=this.sessionState.load();this.isLoggedIn&&this.scheduler.start(e.lastCheck,e.expiration)}},i.checkSession=function(){try{var e=this,t=Date.now();return Promise.resolve(e.client.validate()).then(function(n){var i=n.is_valid,r=n.claims,o=n.expiration_time,s=o?Date.parse(o):0;return!i&&e.isLoggedIn&&e.dispatchSessionExpiredEvent(),i?(e.isLoggedIn=!0,e.sessionState.save({lastCheck:t,expiration:s})):(e.isLoggedIn=!1,e.sessionState.save(null),e.sessionChannel.post({action:"sessionExpired"})),{is_valid:i,claims:r,expiration:s}})}catch(e){return Promise.reject(e)}},i.onSessionExpired=function(){this.isLoggedIn&&(this.isLoggedIn=!1,this.sessionState.save(null),this.sessionChannel.post({action:"sessionExpired"}),this.dispatchSessionExpiredEvent())},i.onChannelSessionExpired=function(){this.isLoggedIn&&(this.isLoggedIn=!1,this.dispatchSessionExpiredEvent())},i.onChannelSessionCreated=function(e){var t=e.claims,n=Date.now(),i=Date.parse(t.expiration)-n;this.isLoggedIn=!0,this.dispatchSessionCreatedEvent({claims:t,expirationSeconds:i})},i.onChannelLeadershipRequested=function(){this.windowActivityManager.hasFocus()||this.scheduler.stop()},i.getSessionCheckChannelName=function(e,t){if("sessionStorage"!==e)return t;var n=sessionStorage.getItem("sessionCheckChannelName");return null!=n&&""!==n||(n=t+"-"+(Math.floor(100*Math.random())+1),sessionStorage.setItem("sessionCheckChannelName",n)),n},t}(p),X=/*#__PURE__*/function(){function e(){}return e.supported=function(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)},e.isPlatformAuthenticatorAvailable=function(){try{return this.supported()&&window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable?Promise.resolve(window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()):Promise.resolve(!1)}catch(e){return Promise.reject(e)}},e.isSecurityKeySupported=function(){try{return void 0!==window.PublicKeyCredential&&window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?Promise.resolve(window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported()):Promise.resolve(this.supported())}catch(e){return Promise.reject(e)}},e.isConditionalMediationAvailable=function(){try{return window.PublicKeyCredential&&window.PublicKeyCredential.isConditionalMediationAvailable?Promise.resolve(window.PublicKeyCredential.isConditionalMediationAvailable()):Promise.resolve(!1)}catch(e){return Promise.reject(e)}},e}();function G(e){const t="==".slice(0,(4-e.length%4)%4),n=e.replace(/-/g,"+").replace(/_/g,"/")+t,i=atob(n),r=new ArrayBuffer(i.length),o=new Uint8Array(r);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return r}function Q(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var Y="copy",Z="convert";function $(e,t,n){if(t===Y)return n;if(t===Z)return e(n);if(t instanceof Array)return n.map(n=>$(e,t[0],n));if(t instanceof Object){const i={};for(const[r,o]of Object.entries(t)){if(o.derive){const e=o.derive(n);void 0!==e&&(n[r]=e)}if(r in n)i[r]=null!=n[r]?$(e,o.schema,n[r]):null;else if(o.required)throw new Error(`Missing key: ${r}`)}return i}}function ee(e,t){return{required:!0,schema:e,derive:t}}function te(e){return{required:!0,schema:e}}function ne(e){return{required:!1,schema:e}}var ie={type:te(Y),id:te(Z),transports:ne(Y)},re={appid:ne(Y),appidExclude:ne(Y),credProps:ne(Y)},oe={appid:ne(Y),appidExclude:ne(Y),credProps:ne(Y)},se={publicKey:te({rp:te(Y),user:te({id:te(Z),name:te(Y),displayName:te(Y)}),challenge:te(Z),pubKeyCredParams:te(Y),timeout:ne(Y),excludeCredentials:ne([ie]),authenticatorSelection:ne(Y),attestation:ne(Y),extensions:ne(re)}),signal:ne(Y)},ae={type:te(Y),id:te(Y),rawId:te(Z),authenticatorAttachment:ne(Y),response:te({clientDataJSON:te(Z),attestationObject:te(Z),transports:ee(Y,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:ee(oe,e=>e.getClientExtensionResults())},ce={mediation:ne(Y),publicKey:te({challenge:te(Z),timeout:ne(Y),rpId:ne(Y),allowCredentials:ne([ie]),userVerification:ne(Y),extensions:ne(re)}),signal:ne(Y)},ue={type:te(Y),id:te(Y),rawId:te(Z),authenticatorAttachment:ne(Y),response:te({clientDataJSON:te(Z),authenticatorData:te(Z),signature:te(Z),userHandle:te(Z)}),clientExtensionResults:ee(oe,e=>e.getClientExtensionResults())};async function he(e){const t=await navigator.credentials.get(function(e){return $(G,ce,e)}(e));return function(e){return $(Q,ue,e)}(t)}var le=/*#__PURE__*/function(){function t(){this.abortController=new AbortController}t.getInstance=function(){return t.instance||(t.instance=new t),t.instance};var n=t.prototype;return n.createAbortSignal=function(){return this.abortController.abort(),this.abortController=new AbortController,this.abortController.signal},n.getWebauthnCredential=function(t){try{return Promise.resolve(he(e({},t,{signal:this.createAbortSignal()})))}catch(e){return Promise.reject(e)}},n.getConditionalWebauthnCredential=function(e){try{return Promise.resolve(he({publicKey:e,mediation:"conditional",signal:this.createAbortSignal()}))}catch(e){return Promise.reject(e)}},n.createWebauthnCredential=function(t){try{return Promise.resolve(async function(e){return t=await navigator.credentials.create(function(e){return $(G,se,e)}(e)),$(Q,ae,t);var t}(e({},t,{signal:this.createAbortSignal()})))}catch(e){return Promise.reject(e)}},t}();le.instance=null;var de="hanko_pkce_code_verifier",fe=function(){for(var e="",t=new Uint8Array(1);e.length<64;){window.crypto.getRandomValues(t);var n=t[0];n<198&&(e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~".charAt(n%66))}return e},ve=function(e){"undefined"!=typeof window&&window.sessionStorage&&window.sessionStorage.setItem(de,e)},pe=function(){return"undefined"!=typeof window&&window.sessionStorage?window.sessionStorage.getItem(de):null},me=function(){"undefined"!=typeof window&&window.sessionStorage&&window.sessionStorage.removeItem(de)};function ye(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var ge=function(e,t,n,i,r){void 0===i&&(i="webauthn_credential_already_exists"),void 0===r&&(r="Webauthn credential already exists");try{return Promise.resolve(ye(function(){return Promise.resolve(t.createWebauthnCredential(n)).then(function(t){return Promise.resolve(e.actions.webauthn_verify_attestation_response.run({public_key:t}))})},function(){return Promise.resolve(e.actions.back.run()).then(function(e){return e.error={code:i,message:r},e})}))}catch(e){return Promise.reject(e)}},Se={preflight:function(e){try{var t=e.actions.register_client_capabilities,n=t.run,i=X.supported();return Promise.resolve(X.isConditionalMediationAvailable()).then(function(e){return Promise.resolve(X.isPlatformAuthenticatorAvailable()).then(function(r){return Promise.resolve(n.call(t,{webauthn_available:i,webauthn_conditional_mediation_available:e,webauthn_platform_authenticator_available:r}))})})}catch(e){return Promise.reject(e)}},login_passkey:function(e){try{var t=le.getInstance();return Promise.resolve(ye(function(){return Promise.resolve(t.getWebauthnCredential(e.payload.request_options)).then(function(t){return Promise.resolve(e.actions.webauthn_verify_assertion_response.run({assertion_response:t}))})},function(){return Promise.resolve(e.actions.back.run()).then(function(t){return e.error&&(t.error=e.error),t})}))}catch(e){return Promise.reject(e)}},onboarding_verify_passkey_attestation:function(e){try{var t=le.getInstance();return Promise.resolve(ge(e,t,e.payload.creation_options))}catch(e){return Promise.reject(e)}},webauthn_credential_verification:function(e){try{var t=le.getInstance();return Promise.resolve(ge(e,t,e.payload.creation_options))}catch(e){return Promise.reject(e)}},thirdparty:function(e){try{var t,n=function(n){var r;if(t)return n;function a(t){var n;if(r)return t;var i=function(){if(e.isCached)return Promise.resolve(e.actions.back.run()).then(function(e){return n=1,e});e.saveToLocalStorage(),window.location.assign(e.payload.redirect_url)}();return i&&i.then?i.then(function(t){return n?t:e}):n?i:e}var c=function(){if((null==o?void 0:o.length)>0){var t="access_denied"===o?"third_party_access_denied":"technical_error",n=i.get("error_description");return s(["error","error_description"]),Promise.resolve(e.actions.back.run(null,{dispatchAfterStateChangeEvent:!1})).then(function(e){return e.error={code:t,message:n},e.dispatchAfterStateChangeEvent(),r=1,e})}}();return c&&c.then?c.then(a):a(c)},i=new URLSearchParams(window.location.search),r=i.get("hanko_token"),o=i.get("error"),s=function(e){e.forEach(function(e){return i.delete(e)});var t=i.toString()?"?"+i.toString():"";history.replaceState(null,null,""+window.location.pathname+t)},a=function(){if((null==r?void 0:r.length)>0){s(["hanko_token"]);var n=pe();return function(i,o){try{var s=Promise.resolve(e.actions.exchange_token.run({token:r,code_verifier:n||void 0})).then(function(e){return t=1,e})}catch(e){return o(!0,e)}return s&&s.then?s.then(o.bind(null,!1),o.bind(null,!0)):o(!1,s)}(0,function(e,t){if(me(),e)throw t;return t})}}();return Promise.resolve(a&&a.then?a.then(n):n(a))}catch(e){return Promise.reject(e)}},success:function(e){try{var t=e.payload.claims,n=Date.parse(t.expiration)-Date.now();return e.removeFromLocalStorage(),e.hanko.relay.dispatchSessionCreatedEvent({claims:t,expirationSeconds:n}),Promise.resolve(e)}catch(e){return Promise.reject(e)}},account_deleted:function(e){try{return e.removeFromLocalStorage(),e.hanko.relay.dispatchUserDeletedEvent(),Promise.resolve(e)}catch(e){return Promise.reject(e)}}},we={login_init:function(e){try{return Promise.resolve(void function(){try{var t=le.getInstance();return Promise.resolve(function(){if(e.payload.request_options)return function(){try{var n=Promise.resolve(t.getConditionalWebauthnCredential(e.payload.request_options.publicKey)).then(function(t){return Promise.resolve(e.actions.webauthn_verify_assertion_response.run({assertion_response:t}))})}catch(e){return}return n&&n.then?n.then(void 0,function(){}):n}()}())}catch(e){return Promise.reject(e)}}())}catch(e){return Promise.reject(e)}}};function ke(e,t,n){if(!e.s){if(n instanceof be){if(!n.s)return void(n.o=ke.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(ke.bind(null,e,t),ke.bind(null,e,2));e.s=t,e.v=n;const i=e.o;i&&i(e)}}var be=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){var i=new e,r=this.s;if(r){var o=1&r?t:n;if(o){try{ke(i,1,o(this.v))}catch(e){ke(i,2,e)}return i}return this}return this.o=function(e){try{var r=e.v;1&e.s?ke(i,1,t?t(r):r):n?ke(i,1,n(r)):ke(i,2,r)}catch(e){ke(i,2,e)}},i},e}();function Ce(e){return e instanceof be&&1&e.s}var Pe=/*#__PURE__*/function(){function t(e,t,n,i){var r=this;if(void 0===i&&(i={}),this.name=void 0,this.flowName=void 0,this.error=void 0,this.payload=void 0,this.actions=void 0,this.csrfToken=void 0,this.status=void 0,this.previousAction=void 0,this.isCached=void 0,this.cacheKey=void 0,this.hanko=void 0,this.invokedAction=void 0,this.excludeAutoSteps=void 0,this.autoStep=void 0,this.passkeyAutofillActivation=void 0,this.flowName=t,this.name=n.name,this.error=n.error,this.payload=n.payload,this.csrfToken=n.csrf_token,this.status=n.status,this.hanko=e,this.actions=this.buildActionMap(n.actions),this.name in Se){var o=Se[this.name];this.autoStep=function(){return o(r)}}if(this.name in we){var s=we[this.name];this.passkeyAutofillActivation=function(){return s(r)}}var a=i.dispatchAfterStateChangeEvent,c=void 0===a||a,u=i.excludeAutoSteps,h=i.previousAction,l=void 0===h?null:h,d=i.isCached,f=void 0!==d&&d,v=i.cacheKey,p=void 0===v?"hanko-flow-state":v;this.excludeAutoSteps=void 0===u?null:u,this.previousAction=l,this.isCached=f,this.cacheKey=p,c&&this.dispatchAfterStateChangeEvent()}var n=t.prototype;return n.buildActionMap=function(e){var t=this,n={};return Object.keys(e).forEach(function(i){n[i]=new Ee(e[i],t)}),new Proxy(n,{get:function(e,n){if(n in e)return e[n];var i="string"==typeof n?n:n.toString();return Ee.createDisabled(i,t)}})},n.dispatchAfterStateChangeEvent=function(){this.hanko.relay.dispatchAfterStateChangeEvent({state:this})},n.serialize=function(){return{flow_name:this.flowName,name:this.name,error:this.error,payload:this.payload,csrf_token:this.csrfToken,status:this.status,previous_action:this.previousAction,actions:Object.fromEntries(Object.entries(this.actions).map(function(e){var t=e[1];return[e[0],{action:t.name,href:t.href,inputs:t.inputs,description:null}]}))}},n.saveToLocalStorage=function(){localStorage.setItem(this.cacheKey,JSON.stringify(e({},this.serialize(),{is_cached:!0})))},n.removeFromLocalStorage=function(){localStorage.removeItem(this.cacheKey)},t.initializeFlowState=function(e,n,i,r){void 0===r&&(r={});try{var o,s=new t(e,n,i,r),a=function(){if("all"!=s.excludeAutoSteps)return function(e,t,n){for(var i;;){var r=e();if(Ce(r)&&(r=r.v),!r)return o;if(r.then){i=0;break}var o=n();if(o&&o.then){if(!Ce(o)){i=1;break}o=o.s}}var s=new be,a=ke.bind(null,s,2);return(0===i?r.then(u):1===i?o.then(c):(void 0).then(function(){(r=e())?r.then?r.then(u).then(void 0,a):u(r):ke(s,1,o)})).then(void 0,a),s;function c(t){o=t;do{if(!(r=e())||Ce(r)&&!r.v)return void ke(s,1,o);if(r.then)return void r.then(u).then(void 0,a);Ce(o=n())&&(o=o.v)}while(!o||!o.then);o.then(c).then(void 0,a)}function u(e){e?(o=n())&&o.then?o.then(c).then(void 0,a):c(o):ke(s,1,o)}}(function(){var e;return!(o||!s||!s.autoStep||null!=(e=s.excludeAutoSteps)&&e.includes(s.name))},0,function(){return Promise.resolve(s.autoStep()).then(function(e){if(e.name==s.name)return o=1,e;s=e})})}();return Promise.resolve(a&&a.then?a.then(function(e){return o?e:s}):o?a:s)}catch(e){return Promise.reject(e)}},t.readFromLocalStorage=function(e){var t=localStorage.getItem(e);if(t)try{return JSON.parse(t)}catch(e){return}},t.create=function(n,i,r){void 0===r&&(r={});try{var o=r.cacheKey,s=void 0===o?"hanko-flow-state":o,a=r.loadFromCache;if(void 0===a||a){var c=t.readFromLocalStorage(s);if(c)return Promise.resolve(t.deserialize(n,c,e({},r,{cacheKey:s})))}return Promise.resolve(t.fetchState(n,"/"+i)).then(function(o){return t.initializeFlowState(n,i,o,e({},r,{cacheKey:s}))})}catch(e){return Promise.reject(e)}},t.deserialize=function(n,i,r){void 0===r&&(r={});try{return Promise.resolve(t.initializeFlowState(n,i.flow_name,i,e({},r,{previousAction:i.previous_action,isCached:i.is_cached})))}catch(e){return Promise.reject(e)}},t.fetchState=function(e,n,i){try{return Promise.resolve(function(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}(function(){return Promise.resolve(e.client.post(n,i)).then(function(e){return e.json()})},function(e){return t.createErrorResponse(e)}))}catch(e){return Promise.reject(e)}},t.createErrorResponse=function(e){return{actions:null,csrf_token:"",name:"error",payload:null,status:0,error:e}},t}(),Ee=/*#__PURE__*/function(){function t(e,t,n){void 0===n&&(n=!0),this.enabled=void 0,this.href=void 0,this.name=void 0,this.inputs=void 0,this.parentState=void 0,this.enabled=n,this.href=e.href,this.name=e.action,this.inputs=e.inputs,this.parentState=t}return t.createDisabled=function(e,n){return new t({action:e,href:"",inputs:{},description:"Disabled action"},n,!1)},t.prototype.run=function(t,n){void 0===t&&(t=null),void 0===n&&(n={});try{var i=this,r=i.parentState,o=r.name,s=r.hanko,a=r.flowName,c=r.csrfToken,u=r.invokedAction,h=r.excludeAutoSteps,l=r.cacheKey,d=n.dispatchAfterStateChangeEvent,f=void 0===d||d;if(!i.enabled)throw new Error("Action '"+i.name+"' is not enabled in state '"+o+"'");if(u)throw new Error("An action '"+u.name+"' has already been invoked on state '"+u.relatedStateName+"'. No further actions can be run.");i.parentState.invokedAction={name:i.name,relatedStateName:o},s.relay.dispatchBeforeStateChangeEvent({state:i.parentState});var v=e({},Object.keys(i.inputs).reduce(function(e,t){var n=i.inputs[t];return void 0!==n.value&&(e[t]=n.value),e},{}),t);return Promise.resolve(Pe.fetchState(s,i.href,{input_data:v,csrf_token:c})).then(function(e){return i.parentState.removeFromLocalStorage(),Pe.initializeFlowState(s,a,e,{dispatchAfterStateChangeEvent:f,excludeAutoSteps:h,previousAction:u,cacheKey:l})})}catch(e){return Promise.reject(e)}},t}(),_e=/*#__PURE__*/function(e){function t(){return e.apply(this,arguments)||this}n(t,e);var i=t.prototype;return i.getCurrent=function(){try{var e=this;return Promise.resolve(e.client.get("/me")).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new A;if(!t.ok)throw new y;var n=t.json();return Promise.resolve(e.client.get("/users/"+n.id)).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new A;if(!t.ok)throw new y;return t.json()})})}catch(e){return Promise.reject(e)}},i.getCurrentUser=function(){try{var e=this;return Promise.resolve(e.client.get("/me")).then(function(t){if(401===t.status)throw e.client.dispatcher.dispatchSessionExpiredEvent(),new A;if(!t.ok)throw new y;return t.json()})}catch(e){return Promise.reject(e)}},i.logout=function(){try{var e=this;return Promise.resolve(e.client.post("/logout")).then(function(t){if(e.client.sessionTokenStorage.removeSessionToken(),e.client.cookie.removeAuthCookie(),e.client.dispatcher.dispatchUserLoggedOutEvent(),401===t.status);else if(!t.ok)throw new y})}catch(e){return Promise.reject(e)}},t}(M),xe=/*#__PURE__*/function(t){function i(n,i){var r;(r=t.call(this)||this).session=void 0,r.user=void 0,r.cookie=void 0,r.client=void 0,r.relay=void 0;var o=e({timeout:13e3,cookieName:"hanko",localStorageKey:"hanko",sessionCheckInterval:3e4,sessionCheckChannelName:"hanko-session-check"},i);return r.client=new F(n,o),r.session=new H(n,o),r.user=new _e(n,o),r.relay=new V(n,o),r.cookie=new R(o),r}n(i,t);var r=i.prototype;return r.setLang=function(e){this.client.lang=e},r.createState=function(e,t){return void 0===t&&(t={}),Pe.create(this,e,t)},r.getUser=function(){try{return Promise.resolve(this.user.getCurrent())}catch(e){return Promise.reject(e)}},r.getCurrentUser=function(){try{return Promise.resolve(this.user.getCurrentUser())}catch(e){return Promise.reject(e)}},r.validateSession=function(){try{return Promise.resolve(this.session.validate())}catch(e){return Promise.reject(e)}},r.getSessionToken=function(){return this.cookie.getAuthCookie()},r.logout=function(){try{return Promise.resolve(this.user.logout())}catch(e){return Promise.reject(e)}},i}(v);export{Ee as Action,M as Client,g as ConflictError,f as CustomEventWithDetail,L as EmailAddressAlreadyExistsError,O as ForbiddenError,xe as Hanko,m as HankoError,F as HttpClient,b as InvalidPasscodeError,k as InvalidPasswordError,C as InvalidWebauthnCredentialError,I as MaxNumOfEmailAddressesReachedError,E as MaxNumOfPasscodeAttemptsReachedError,_ as NotFoundError,P as PasscodeExpiredError,V as Relay,S as RequestTimeoutError,H as SessionClient,Pe as State,y as TechnicalError,T as ThirdPartyError,x as TooManyRequestsError,A as UnauthorizedError,_e as UserClient,j as UserVerificationError,w as WebauthnRequestCancelledError,X as WebauthnSupport,me as clearStoredCodeVerifier,fe as generateCodeVerifier,pe as getStoredCodeVerifier,a as sessionCreatedType,c as sessionExpiredType,ve as setStoredCodeVerifier,h as userDeletedType,u as userLoggedOutType};
//# sourceMappingURL=sdk.module.js.map