@teamhanko/hanko-frontend-sdk 0.8.3 → 0.8.4

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
- function e(){return e=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},e.apply(this,arguments)}class t extends Error{constructor(e,s,i){super(e),this.code=void 0,this.cause=void 0,this.code=s,this.cause=i,Object.setPrototypeOf(this,t.prototype)}}class s extends t{constructor(e){super("Technical error","somethingWentWrong",e),Object.setPrototypeOf(this,s.prototype)}}class i extends t{constructor(e,t){super("Conflict error","conflict",t),Object.setPrototypeOf(this,i.prototype)}}class r extends t{constructor(e){super("Request timed out error","requestTimeout",e),Object.setPrototypeOf(this,r.prototype)}}class n extends t{constructor(e){super("Request cancelled error","requestCancelled",e),Object.setPrototypeOf(this,n.prototype)}}class o extends t{constructor(e){super("Invalid password error","invalidPassword",e),Object.setPrototypeOf(this,o.prototype)}}class a extends t{constructor(e){super("Invalid Passcode error","invalidPasscode",e),Object.setPrototypeOf(this,a.prototype)}}class c extends t{constructor(e){super("Invalid WebAuthn credential error","invalidWebauthnCredential",e),Object.setPrototypeOf(this,c.prototype)}}class d extends t{constructor(e){super("Passcode expired error","passcodeExpired",e),Object.setPrototypeOf(this,d.prototype)}}class h extends t{constructor(e){super("Maximum number of Passcode attempts reached error","passcodeAttemptsReached",e),Object.setPrototypeOf(this,h.prototype)}}class l extends t{constructor(e){super("Not found error","notFound",e),Object.setPrototypeOf(this,l.prototype)}}class u extends t{constructor(e,t){super("Too many requests error","tooManyRequests",t),this.retryAfter=void 0,this.retryAfter=e,Object.setPrototypeOf(this,u.prototype)}}class p extends t{constructor(e){super("Unauthorized error","unauthorized",e),Object.setPrototypeOf(this,p.prototype)}}class w extends t{constructor(e){super("Forbidden error","forbidden",e),Object.setPrototypeOf(this,w.prototype)}}class g extends t{constructor(e){super("User verification error","userVerification",e),Object.setPrototypeOf(this,g.prototype)}}class f extends t{constructor(e){super("Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",e),Object.setPrototypeOf(this,f.prototype)}}class m extends t{constructor(e){super("The email address already exists","emailAddressAlreadyExistsError",e),Object.setPrototypeOf(this,m.prototype)}}class v extends t{constructor(e,t){super("An error occurred during third party sign up/sign in",e,t),Object.setPrototypeOf(this,v.prototype)}}class y{constructor(e){this.key=void 0,this.ls=void 0,this.key=e,this.ls={}}read(){let e;try{const t=localStorage.getItem(this.key),s=decodeURIComponent(decodeURI(window.atob(t)));e=JSON.parse(s)}catch(e){return this.ls={},this}return this.ls=e,this}write(){const e=JSON.stringify(this.ls),t=window.btoa(encodeURI(encodeURIComponent(e)));return localStorage.setItem(this.key,t),this}static timeToRemainingSeconds(e=0){return e-Math.floor(Date.now()/1e3)}static remainingSecondsToTime(e=0){return Math.floor(Date.now()/1e3)+e}}class S extends y{constructor(e){super(`${e.localStorageKey}_session`)}read(){return super.read(),this}getState(){var e;return(e=this.ls).session||(e.session={expiry:0,userID:"",authFlowCompleted:!1}),this.ls.session}getExpirationSeconds(){return y.timeToRemainingSeconds(this.getState().expiry)}setExpirationSeconds(e){return this.getState().expiry=y.remainingSecondsToTime(e),this}getUserID(){return this.getState().userID}setUserID(e){return this.getState().userID=e,this}getAuthFlowCompleted(){return this.getState().authFlowCompleted}setAuthFlowCompleted(e){return this.getState().authFlowCompleted=e,this}reset(){const e=this.getState();return delete e.expiry,delete e.userID,this}}class E extends y{getUserState(e){var t;return(t=this.ls).users||(t.users={}),Object.prototype.hasOwnProperty.call(this.ls.users,e)||(this.ls.users[e]={}),this.ls.users[e]}}class x extends E{getState(e){var t;return(t=super.getUserState(e)).passcode||(t.passcode={})}read(){return super.read(),this}getActiveID(e){return this.getState(e).id}setActiveID(e,t){return this.getState(e).id=t,this}getEmailID(e){return this.getState(e).emailID}setEmailID(e,t){return this.getState(e).emailID=t,this}reset(e){const t=this.getState(e);return delete t.id,delete t.ttl,delete t.resendAfter,delete t.emailID,this}getTTL(e){return y.timeToRemainingSeconds(this.getState(e).ttl)}setTTL(e,t){return this.getState(e).ttl=y.remainingSecondsToTime(t),this}getResendAfter(e){return y.timeToRemainingSeconds(this.getState(e).resendAfter)}setResendAfter(e,t){return this.getState(e).resendAfter=y.remainingSecondsToTime(t),this}}const k="hanko-session-created",b="hanko-session-expired",C="hanko-user-logged-out",_="hanko-user-deleted",A="hanko-auth-flow-completed";class O extends CustomEvent{constructor(e,t){super(e,{detail:t})}}class T{constructor(t){this._dispatchEvent=document.dispatchEvent.bind(document),this._sessionState=void 0,this._sessionState=new S(e({},t))}dispatch(e,t){this._dispatchEvent(new O(e,t))}dispatchSessionCreatedEvent(e){this.dispatch(k,e)}dispatchSessionExpiredEvent(){this.dispatch(b,null)}dispatchUserLoggedOutEvent(){this.dispatch(C,null)}dispatchUserDeletedEvent(){this.dispatch(_,null)}dispatchAuthFlowCompletedEvent(e){this._sessionState.read().setAuthFlowCompleted(!0).write(),this.dispatch(A,e)}}function R(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)e[i]=s[i]}return e}var P=function e(t,s){function i(e,i,r){if("undefined"!=typeof document){"number"==typeof(r=R({},s,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 n="";for(var o in r)r[o]&&(n+="; "+o,!0!==r[o]&&(n+="="+r[o].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+n}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var s=document.cookie?document.cookie.split("; "):[],i={},r=0;r<s.length;r++){var n=s[r].split("="),o=n.slice(1).join("=");try{var a=decodeURIComponent(n[0]);if(i[a]=t.read(o,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",R({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,R({},this.attributes,t))},withConverter:function(t){return e(R({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(s)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});class j{constructor(e){this.authCookieName=void 0,this.authCookieName=e.cookieName}getAuthCookie(){return P.get(this.authCookieName)}setAuthCookie(e,t=!0){P.set(this.authCookieName,e,{secure:t})}removeAuthCookie(){P.remove(this.authCookieName)}}class I{constructor(e){this._xhr=void 0,this._xhr=e}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}class D{constructor(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 I(e),this.ok=e.status>=200&&e.status<=299,this.status=e.status,this.statusText=e.statusText,this.url=e.responseURL,this.xhr=e}json(){return this._decodedJSON||(this._decodedJSON=JSON.parse(this.xhr.response)),this._decodedJSON}parseNumericHeader(e){const t=parseInt(this.headers.getResponseHeader(e),10);return isNaN(t)?0:t}}class L{constructor(t,s){this.timeout=void 0,this.api=void 0,this.sessionState=void 0,this.passcodeState=void 0,this.dispatcher=void 0,this.cookie=void 0,this.api=t,this.timeout=s.timeout,this.sessionState=new S(e({},s)),this.passcodeState=new x(s.cookieName),this.dispatcher=new T(e({},s)),this.cookie=new j(e({},s))}_fetch(e,t,i=new XMLHttpRequest){const n=this.api+e,o=this.timeout,a=this.cookie.getAuthCookie();return new Promise(function(e,c){i.open(t.method,n,!0),i.setRequestHeader("Accept","application/json"),i.setRequestHeader("Content-Type","application/json"),a&&i.setRequestHeader("Authorization",`Bearer ${a}`),i.timeout=o,i.withCredentials=!0,i.onload=()=>{const t=new D(i);e(t)},i.onerror=()=>{c(new s)},i.ontimeout=()=>{c(new r)},i.send(t.body?t.body.toString():null)})}processResponseHeadersOnLogin(e,t){let s="",i=0;if(t.xhr.getAllResponseHeaders().split("\r\n").forEach(e=>{const r=e.toLowerCase();r.startsWith("x-auth-token")?s=t.headers.getResponseHeader("X-Auth-Token"):r.startsWith("x-session-lifetime")&&(i=parseInt(t.headers.getResponseHeader("X-Session-Lifetime"),10))}),s){const e=!!this.api.match("^https://");this.cookie.setAuthCookie(s,e)}this.passcodeState.read().reset(e).write(),i>0&&(this.sessionState.read(),this.sessionState.setExpirationSeconds(i),this.sessionState.setUserID(e),this.sessionState.setAuthFlowCompleted(!1),this.sessionState.write(),this.dispatcher.dispatchSessionCreatedEvent({jwt:s,userID:e,expirationSeconds:i}))}get(e){return this._fetch(e,{method:"GET"})}post(e,t){return this._fetch(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this._fetch(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this._fetch(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this._fetch(e,{method:"DELETE"})}}class U{constructor(e,t){this.client=void 0,this.client=new L(e,t)}}class N extends U{async get(){const e=await this.client.get("/.well-known/config");if(!e.ok)throw new s;return e.json()}}class H extends U{constructor(e,t){super(e,t),this.state=void 0,this.state=new x(t.cookieName)}async initialize(e,t,i){this.state.read();const r=this.state.getTTL(e),n=this.state.getActiveID(e),o=this.state.getEmailID(e);let a=this.state.getResendAfter(e);if(a>0)throw new u(a);if(!i&&r>0&&t===o)return{id:n,ttl:r};const c={user_id:e};t&&(c.email_id=t);const d=await this.client.post("/passcode/login/initialize",c);if(429===d.status)throw a=d.parseNumericHeader("Retry-After"),this.state.setResendAfter(e,a).write(),new u(a);if(!d.ok)throw new s;const h=d.json();return this.state.setActiveID(e,h.id).setTTL(e,h.ttl),t&&this.state.setEmailID(e,t),this.state.write(),h}async finalize(e,t){const i=this.state.read().getActiveID(e);if(this.state.getTTL(e)<=0)throw new d;const r=await this.client.post("/passcode/login/finalize",{id:i,code:t});if(401===r.status)throw new a;if(410===r.status)throw this.state.reset(e).write(),new h;if(!r.ok)throw new s;this.client.processResponseHeadersOnLogin(e,r)}getTTL(e){return this.state.read().getTTL(e)}getResendAfter(e){return this.state.read().getResendAfter(e)}}class K extends E{getState(e){var t;return(t=super.getUserState(e)).password||(t.password={})}read(){return super.read(),this}getRetryAfter(e){return y.timeToRemainingSeconds(this.getState(e).retryAfter)}setRetryAfter(e,t){return this.getState(e).retryAfter=y.remainingSecondsToTime(t),this}}class F extends U{constructor(e,t){super(e,t),this.passwordState=void 0,this.passcodeState=void 0,this.passwordState=new K(t.cookieName),this.passcodeState=new x(t.cookieName)}async login(e,t){const i=await this.client.post("/password/login",{user_id:e,password:t});if(401===i.status)throw new o;if(429===i.status){const t=i.parseNumericHeader("Retry-After");throw this.passwordState.read().setRetryAfter(e,t).write(),new u(t)}if(!i.ok)throw new s;this.client.processResponseHeadersOnLogin(e,i)}async update(e,t){const i=await this.client.put("/password",{user_id:e,password:t});if(401===i.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!i.ok)throw new s}getRetryAfter(e){return this.passwordState.read().getRetryAfter(e)}}class W extends U{async getInfo(e){const t=await this.client.post("/user",{email:e});if(404===t.status)throw new l;if(!t.ok)throw new s;return t.json()}async create(e){const t=await this.client.post("/users",{email:e});if(409===t.status)throw new i;if(403===t.status)throw new w;if(!t.ok)throw new s;const r=t.json();return r&&r.user_id&&this.client.processResponseHeadersOnLogin(r.user_id,t),r}async getCurrent(){const e=await this.client.get("/me");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!e.ok)throw new s;const t=e.json(),i=await this.client.get(`/users/${t.id}`);if(401===i.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!i.ok)throw new s;return i.json()}async delete(){const e=await this.client.delete("/user");if(e.ok)return this.client.cookie.removeAuthCookie(),this.client.sessionState.reset().write(),void this.client.dispatcher.dispatchUserDeletedEvent();if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;throw new s}async logout(){const e=await this.client.post("/logout");if(this.client.cookie.removeAuthCookie(),this.client.sessionState.reset().write(),this.client.dispatcher.dispatchUserLoggedOutEvent(),401!==e.status&&!e.ok)throw new s}}function q(e){const t="==".slice(0,(4-e.length%4)%4),s=e.replace(/-/g,"+").replace(/_/g,"/")+t,i=atob(s),r=new ArrayBuffer(i.length),n=new Uint8Array(r);for(let e=0;e<i.length;e++)n[e]=i.charCodeAt(e);return r}function z(e){const t=new Uint8Array(e);let s="";for(const e of t)s+=String.fromCharCode(e);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var J="copy",M="convert";function $(e,t,s){if(t===J)return s;if(t===M)return e(s);if(t instanceof Array)return s.map(s=>$(e,t[0],s));if(t instanceof Object){const i={};for(const[r,n]of Object.entries(t)){if(n.derive){const e=n.derive(s);void 0!==e&&(s[r]=e)}if(r in s)i[r]=null!=s[r]?$(e,n.schema,s[r]):null;else if(n.required)throw new Error(`Missing key: ${r}`)}return i}}function B(e,t){return{required:!0,schema:e,derive:t}}function V(e){return{required:!0,schema:e}}function X(e){return{required:!1,schema:e}}var G={type:V(J),id:V(M),transports:X(J)},Q={appid:X(J),appidExclude:X(J),credProps:X(J)},Y={appid:X(J),appidExclude:X(J),credProps:X(J)},Z={publicKey:V({rp:V(J),user:V({id:V(M),name:V(J),displayName:V(J)}),challenge:V(M),pubKeyCredParams:V(J),timeout:X(J),excludeCredentials:X([G]),authenticatorSelection:X(J),attestation:X(J),extensions:X(Q)}),signal:X(J)},ee={type:V(J),id:V(J),rawId:V(M),authenticatorAttachment:X(J),response:V({clientDataJSON:V(M),attestationObject:V(M),transports:B(J,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:B(Y,e=>e.getClientExtensionResults())},te={mediation:X(J),publicKey:V({challenge:V(M),timeout:X(J),rpId:X(J),allowCredentials:X([G]),userVerification:X(J),extensions:X(Q)}),signal:X(J)},se={type:V(J),id:V(J),rawId:V(M),authenticatorAttachment:X(J),response:V({clientDataJSON:V(M),authenticatorData:V(M),signature:V(M),userHandle:V(M)}),clientExtensionResults:B(Y,e=>e.getClientExtensionResults())};async function ie(e){const t=await navigator.credentials.create(function(e){return $(q,Z,e)}(e));return function(e){return $(z,ee,e)}(t)}async function re(e){const t=await navigator.credentials.get(function(e){return $(q,te,e)}(e));return function(e){return $(z,se,e)}(t)}class ne{static supported(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)}static async isPlatformAuthenticatorAvailable(){return!(!this.supported()||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)&&window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}static async isSecurityKeySupported(){return void 0!==window.PublicKeyCredential&&window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported():this.supported()}static async isConditionalMediationAvailable(){return!(!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable)&&window.PublicKeyCredential.isConditionalMediationAvailable()}}class oe extends E{getState(e){var t;return(t=super.getUserState(e)).webauthn||(t.webauthn={})}read(){return super.read(),this}getCredentials(e){var t;return(t=this.getState(e)).credentials||(t.credentials=[])}addCredential(e,t){return this.getCredentials(e).push(t),this}matchCredentials(e,t){return this.getCredentials(e).filter(e=>t.find(t=>t.id===e)).map(e=>({id:e}))}}class ae extends U{constructor(e,t){super(e,t),this.webauthnState=void 0,this.passcodeState=void 0,this.controller=void 0,this._getCredential=re,this._createCredential=ie,this.webauthnState=new oe(t.cookieName),this.passcodeState=new x(t.cookieName)}async login(e,t){const i=await this.client.post("/webauthn/login/initialize",{user_id:e});if(!i.ok)throw new s;const r=i.json();let o;r.signal=this._createAbortSignal(),t&&(r.mediation="conditional");try{o=await this._getCredential(r)}catch(e){throw new n(e)}const a=await this.client.post("/webauthn/login/finalize",o);if(400===a.status||401===a.status)throw new c;if(!a.ok)throw new s;const d=a.json();return this.webauthnState.read().addCredential(d.user_id,d.credential_id).write(),this.client.processResponseHeadersOnLogin(d.user_id,a),d}async register(){const e=await this.client.post("/webauthn/registration/initialize");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!e.ok)throw new s;const t=e.json();let i;t.signal=this._createAbortSignal();try{i=await this._createCredential(t)}catch(e){throw new n(e)}i.transports=i.response.transports;const r=await this.client.post("/webauthn/registration/finalize",i);if(401===r.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(422===r.status)throw new g;if(!r.ok)throw new s;const o=r.json();this.webauthnState.read().addCredential(o.user_id,o.credential_id).write()}async listCredentials(){const e=await this.client.get("/webauthn/credentials");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!e.ok)throw new s;return e.json()}async updateCredential(e,t){const i=await this.client.patch(`/webauthn/credentials/${e}`,{name:t});if(401===i.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!i.ok)throw new s}async deleteCredential(e){const t=await this.client.delete(`/webauthn/credentials/${e}`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!t.ok)throw new s}async shouldRegister(e){const t=ne.supported();if(!e.webauthn_credentials||!e.webauthn_credentials.length)return t;const s=this.webauthnState.read().matchCredentials(e.id,e.webauthn_credentials);return t&&!s.length}_createAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}}class ce extends U{async list(){const e=await this.client.get("/emails");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!e.ok)throw new s;return e.json()}async create(e){const t=await this.client.post("/emails",{address:e});if(t.ok)return t.json();if(400===t.status)throw new m;if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(409===t.status)throw new f;throw new s}async setPrimaryEmail(e){const t=await this.client.post(`/emails/${e}/set_primary`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!t.ok)throw new s}async delete(e){const t=await this.client.delete(`/emails/${e}`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!t.ok)throw new s}}class de extends U{async auth(e,t){const s=new URL("/thirdparty/auth",this.client.api);if(!e)throw new v("somethingWentWrong",new Error("provider missing from request"));if(!t)throw new v("somethingWentWrong",new Error("redirectTo missing from request"));s.searchParams.append("provider",e),s.searchParams.append("redirect_to",t),window.location.assign(s.href)}getError(){const e=new URLSearchParams(window.location.search),t=e.get("error"),s=e.get("error_description");if(t){let e="";switch(t){case"access_denied":e="thirdPartyAccessDenied";break;case"user_conflict":e="emailAddressAlreadyExistsError";break;case"multiple_accounts":e="thirdPartyMultipleAccounts";break;case"unverified_email":e="thirdPartyUnverifiedEmail";break;case"email_maxnum":e="maxNumOfEmailAddressesReached";break;default:e="somethingWentWrong"}return new v(e,new Error(s))}}}class he extends U{async validate(){const e=new URLSearchParams(window.location.search).get("hanko_token");if(!e)return;window.history.replaceState(null,null,window.location.pathname);const t=await this.client.post("/token",{value:e});if(!t.ok)throw new s;const i=t.json();this.client.processResponseHeadersOnLogin(i.user_id,t)}}class le{static throttle(e,t,s={}){const{leading:i=!0,trailing:r=!0}=s;let n,o,a,c=0;const d=()=>{c=!1===i?0:Date.now(),a=null,e.apply(n,o)};return function(...s){const h=Date.now();c||!1!==i||(c=h);const l=t-(h-c);n=this,o=s,l<=0||l>t?(a&&(window.clearTimeout(a),a=null),c=h,e.apply(n,o)):a||!1===r||(a=window.setTimeout(d,l))}}}class ue{constructor(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=le.throttle}wrapCallback(e,t){const s=t=>{e(t.detail)};return t?this._throttle(s,this.throttleLimit,{leading:!0,trailing:!1}):s}addEventListenerWithType({type:e,callback:t,once:s=!1,throttle:i=!1}){const r=this.wrapCallback(t,i);return this._addEventListener(e,r,{once:s}),()=>this._removeEventListener(e,r)}static mapAddEventListenerParams(e,{once:t,callback:s},i){return{type:e,callback:s,once:t,throttle:i}}addEventListener(e,t,s){return this.addEventListenerWithType(ue.mapAddEventListenerParams(e,t,s))}onSessionCreated(e,t){return this.addEventListener(k,{callback:e,once:t},!0)}onSessionExpired(e,t){return this.addEventListener(b,{callback:e,once:t},!0)}onUserLoggedOut(e,t){return this.addEventListener(C,{callback:e,once:t})}onUserDeleted(e,t){return this.addEventListener(_,{callback:e,once:t})}onAuthFlowCompleted(e,t){return this.addEventListener(A,{callback:e,once:t})}}class pe{constructor(){this._tasks=[]}removeTask(e){window.clearTimeout(e.timeoutID),this._tasks=this._tasks.filter(t=>t!==e)}removeTasksWithType(e){this._tasks.filter(t=>t.type===e).forEach(e=>this.removeTask(e))}scheduleTask(e,t,s){const i={timeoutID:window.setTimeout(()=>{t(),this.removeTask(i)},1e3*s),type:e,func:t};this._tasks.push(i)}}class we{constructor(t){this._sessionState=void 0,this._cookie=void 0,this._sessionState=new S(e({},t)),this._cookie=new j(e({},t))}get(){const e=this._get();return we.validate(e)?e:null}isValid(){const e=this._get();return we.validate(e)}_get(){return this._sessionState.read(),{userID:this._sessionState.getUserID(),expirationSeconds:this._sessionState.getExpirationSeconds(),jwt:this._cookie.getAuthCookie()}}isAuthFlowCompleted(){return this._sessionState.read(),this._sessionState.getAuthFlowCompleted()}static validate(e){var t;return!!(e.expirationSeconds>0&&null!=(t=e.userID)&&t.length)}}class ge extends T{constructor(t){super(e({},t)),this._listener=new ue,this._scheduler=new pe,this._session=void 0,this.scheduleSessionExpiredEvent=e=>{this._scheduler.removeTasksWithType(b),this._scheduler.scheduleTask(b,()=>this.dispatchSessionExpiredEvent(),e.expirationSeconds)},this.cancelSessionExpiredEvent=()=>{this._scheduler.removeTasksWithType(b)},this.handleStorageEvent=e=>{if("hanko_session"!==e.key)return;const t=this._session.get();t?this._session.isAuthFlowCompleted()?this.dispatchAuthFlowCompletedEvent({userID:t.userID}):this.dispatchSessionCreatedEvent(t):this.dispatchSessionExpiredEvent()},this._session=new we(e({},t)),this.listenEventDependencies()}listenEventDependencies(){this._listener.onSessionCreated(this.scheduleSessionExpiredEvent),this._listener.onSessionExpired(this.cancelSessionExpiredEvent),this._listener.onUserDeleted(this.cancelSessionExpiredEvent),this._listener.onUserLoggedOut(this.cancelSessionExpiredEvent),window.addEventListener("storage",this.handleStorageEvent);const e=this._session.get();e&&this.scheduleSessionExpiredEvent(e)}}class fe extends ue{constructor(t,s){super(),this.api=void 0,this.config=void 0,this.user=void 0,this.webauthn=void 0,this.password=void 0,this.passcode=void 0,this.email=void 0,this.thirdParty=void 0,this.token=void 0,this.relay=void 0,this.session=void 0;const i={timeout:13e3,cookieName:"hanko",localStorageKey:"hanko"};void 0!==(null==s?void 0:s.cookieName)&&(i.cookieName=s.cookieName),void 0!==(null==s?void 0:s.timeout)&&(i.timeout=s.timeout),void 0!==(null==s?void 0:s.localStorageKey)&&(i.localStorageKey=s.localStorageKey),this.api=t,this.config=new N(t,i),this.user=new W(t,i),this.webauthn=new ae(t,i),this.password=new F(t,i),this.passcode=new H(t,i),this.email=new ce(t,i),this.thirdParty=new de(t,i),this.token=new he(t,i),this.relay=new ge(e({},i)),this.session=new we(e({},i))}}export{N as ConfigClient,i as ConflictError,O as CustomEventWithDetail,m as EmailAddressAlreadyExistsError,ce as EmailClient,w as ForbiddenError,fe as Hanko,t as HankoError,a as InvalidPasscodeError,o as InvalidPasswordError,c as InvalidWebauthnCredentialError,f as MaxNumOfEmailAddressesReachedError,h as MaxNumOfPasscodeAttemptsReachedError,l as NotFoundError,H as PasscodeClient,d as PasscodeExpiredError,F as PasswordClient,r as RequestTimeoutError,s as TechnicalError,de as ThirdPartyClient,v as ThirdPartyError,he as TokenClient,u as TooManyRequestsError,p as UnauthorizedError,W as UserClient,g as UserVerificationError,ae as WebauthnClient,n as WebauthnRequestCancelledError,ne as WebauthnSupport,A as authFlowCompletedType,k as sessionCreatedType,b as sessionExpiredType,_ as userDeletedType,C as userLoggedOutType};
1
+ function e(){return e=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},e.apply(this,arguments)}class t extends Error{constructor(e,s,i){super(e),this.code=void 0,this.cause=void 0,this.code=s,this.cause=i,Object.setPrototypeOf(this,t.prototype)}}class s extends t{constructor(e){super("Technical error","somethingWentWrong",e),Object.setPrototypeOf(this,s.prototype)}}class i extends t{constructor(e,t){super("Conflict error","conflict",t),Object.setPrototypeOf(this,i.prototype)}}class r extends t{constructor(e){super("Request timed out error","requestTimeout",e),Object.setPrototypeOf(this,r.prototype)}}class n extends t{constructor(e){super("Request cancelled error","requestCancelled",e),Object.setPrototypeOf(this,n.prototype)}}class o extends t{constructor(e){super("Invalid password error","invalidPassword",e),Object.setPrototypeOf(this,o.prototype)}}class a extends t{constructor(e){super("Invalid Passcode error","invalidPasscode",e),Object.setPrototypeOf(this,a.prototype)}}class c extends t{constructor(e){super("Invalid WebAuthn credential error","invalidWebauthnCredential",e),Object.setPrototypeOf(this,c.prototype)}}class d extends t{constructor(e){super("Passcode expired error","passcodeExpired",e),Object.setPrototypeOf(this,d.prototype)}}class h extends t{constructor(e){super("Maximum number of Passcode attempts reached error","passcodeAttemptsReached",e),Object.setPrototypeOf(this,h.prototype)}}class l extends t{constructor(e){super("Not found error","notFound",e),Object.setPrototypeOf(this,l.prototype)}}class u extends t{constructor(e,t){super("Too many requests error","tooManyRequests",t),this.retryAfter=void 0,this.retryAfter=e,Object.setPrototypeOf(this,u.prototype)}}class p extends t{constructor(e){super("Unauthorized error","unauthorized",e),Object.setPrototypeOf(this,p.prototype)}}class w extends t{constructor(e){super("Forbidden error","forbidden",e),Object.setPrototypeOf(this,w.prototype)}}class g extends t{constructor(e){super("User verification error","userVerification",e),Object.setPrototypeOf(this,g.prototype)}}class f extends t{constructor(e){super("Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",e),Object.setPrototypeOf(this,f.prototype)}}class m extends t{constructor(e){super("The email address already exists","emailAddressAlreadyExistsError",e),Object.setPrototypeOf(this,m.prototype)}}class v extends t{constructor(e,t){super("An error occurred during third party sign up/sign in",e,t),Object.setPrototypeOf(this,v.prototype)}}class y{constructor(e){this.key=void 0,this.ls=void 0,this.key=e,this.ls={}}read(){let e;try{const t=localStorage.getItem(this.key),s=decodeURIComponent(decodeURI(window.atob(t)));e=JSON.parse(s)}catch(e){return this.ls={},this}return this.ls=e,this}write(){const e=JSON.stringify(this.ls),t=window.btoa(encodeURI(encodeURIComponent(e)));return localStorage.setItem(this.key,t),this}static timeToRemainingSeconds(e=0){return e-Math.floor(Date.now()/1e3)}static remainingSecondsToTime(e=0){return Math.floor(Date.now()/1e3)+e}}class S extends y{constructor(e){super(`${e.localStorageKey}_session`)}read(){return super.read(),this}getState(){var e;return(e=this.ls).session||(e.session={expiry:0,userID:"",authFlowCompleted:!1}),this.ls.session}getExpirationSeconds(){return y.timeToRemainingSeconds(this.getState().expiry)}setExpirationSeconds(e){return this.getState().expiry=y.remainingSecondsToTime(e),this}getUserID(){return this.getState().userID}setUserID(e){return this.getState().userID=e,this}getAuthFlowCompleted(){return this.getState().authFlowCompleted}setAuthFlowCompleted(e){return this.getState().authFlowCompleted=e,this}reset(){const e=this.getState();return delete e.expiry,delete e.userID,this}}class E extends y{getUserState(e){var t;return(t=this.ls).users||(t.users={}),Object.prototype.hasOwnProperty.call(this.ls.users,e)||(this.ls.users[e]={}),this.ls.users[e]}}class x extends E{getState(e){var t;return(t=super.getUserState(e)).passcode||(t.passcode={})}read(){return super.read(),this}getActiveID(e){return this.getState(e).id}setActiveID(e,t){return this.getState(e).id=t,this}getEmailID(e){return this.getState(e).emailID}setEmailID(e,t){return this.getState(e).emailID=t,this}reset(e){const t=this.getState(e);return delete t.id,delete t.ttl,delete t.resendAfter,delete t.emailID,this}getTTL(e){return y.timeToRemainingSeconds(this.getState(e).ttl)}setTTL(e,t){return this.getState(e).ttl=y.remainingSecondsToTime(t),this}getResendAfter(e){return y.timeToRemainingSeconds(this.getState(e).resendAfter)}setResendAfter(e,t){return this.getState(e).resendAfter=y.remainingSecondsToTime(t),this}}const k="hanko-session-created",b="hanko-session-expired",C="hanko-user-logged-out",_="hanko-user-deleted",A="hanko-auth-flow-completed";class O extends CustomEvent{constructor(e,t){super(e,{detail:t})}}class T{constructor(t){this._dispatchEvent=document.dispatchEvent.bind(document),this._sessionState=void 0,this._sessionState=new S(e({},t))}dispatch(e,t){this._dispatchEvent(new O(e,t))}dispatchSessionCreatedEvent(e){this.dispatch(k,e)}dispatchSessionExpiredEvent(){this.dispatch(b,null)}dispatchUserLoggedOutEvent(){this.dispatch(C,null)}dispatchUserDeletedEvent(){this.dispatch(_,null)}dispatchAuthFlowCompletedEvent(e){this._sessionState.read().setAuthFlowCompleted(!0).write(),this.dispatch(A,e)}}function R(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)e[i]=s[i]}return e}var P=function e(t,s){function i(e,i,r){if("undefined"!=typeof document){"number"==typeof(r=R({},s,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 n="";for(var o in r)r[o]&&(n+="; "+o,!0!==r[o]&&(n+="="+r[o].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+n}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var s=document.cookie?document.cookie.split("; "):[],i={},r=0;r<s.length;r++){var n=s[r].split("="),o=n.slice(1).join("=");try{var a=decodeURIComponent(n[0]);if(i[a]=t.read(o,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",R({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,R({},this.attributes,t))},withConverter:function(t){return e(R({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(s)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});class j{constructor(e){this.authCookieName=void 0,this.authCookieName=e.cookieName}getAuthCookie(){return P.get(this.authCookieName)}setAuthCookie(e,t={secure:!0}){P.set(this.authCookieName,e,t)}removeAuthCookie(){P.remove(this.authCookieName)}}class D{constructor(e){this._xhr=void 0,this._xhr=e}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}class I{constructor(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 D(e),this.ok=e.status>=200&&e.status<=299,this.status=e.status,this.statusText=e.statusText,this.url=e.responseURL,this.xhr=e}json(){return this._decodedJSON||(this._decodedJSON=JSON.parse(this.xhr.response)),this._decodedJSON}parseNumericHeader(e){const t=parseInt(this.headers.getResponseHeader(e),10);return isNaN(t)?0:t}}class L{constructor(t,s){this.timeout=void 0,this.api=void 0,this.sessionState=void 0,this.passcodeState=void 0,this.dispatcher=void 0,this.cookie=void 0,this.api=t,this.timeout=s.timeout,this.sessionState=new S(e({},s)),this.passcodeState=new x(s.cookieName),this.dispatcher=new T(e({},s)),this.cookie=new j(e({},s))}_fetch(e,t,i=new XMLHttpRequest){const n=this.api+e,o=this.timeout,a=this.cookie.getAuthCookie();return new Promise(function(e,c){i.open(t.method,n,!0),i.setRequestHeader("Accept","application/json"),i.setRequestHeader("Content-Type","application/json"),a&&i.setRequestHeader("Authorization",`Bearer ${a}`),i.timeout=o,i.withCredentials=!0,i.onload=()=>{const t=new I(i);e(t)},i.onerror=()=>{c(new s)},i.ontimeout=()=>{c(new r)},i.send(t.body?t.body.toString():null)})}processResponseHeadersOnLogin(e,t){let s="",i=0;if(t.xhr.getAllResponseHeaders().split("\r\n").forEach(e=>{const r=e.toLowerCase();r.startsWith("x-auth-token")?s=t.headers.getResponseHeader("X-Auth-Token"):r.startsWith("x-session-lifetime")&&(i=parseInt(t.headers.getResponseHeader("X-Session-Lifetime"),10))}),s){const e=!!this.api.match("^https://"),t=new Date((new Date).getTime()+1e3*i);this.cookie.setAuthCookie(s,{secure:e,expires:t})}this.passcodeState.read().reset(e).write(),i>0&&(this.sessionState.read(),this.sessionState.setExpirationSeconds(i),this.sessionState.setUserID(e),this.sessionState.setAuthFlowCompleted(!1),this.sessionState.write(),this.dispatcher.dispatchSessionCreatedEvent({jwt:s,userID:e,expirationSeconds:i}))}get(e){return this._fetch(e,{method:"GET"})}post(e,t){return this._fetch(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this._fetch(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this._fetch(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this._fetch(e,{method:"DELETE"})}}class U{constructor(e,t){this.client=void 0,this.client=new L(e,t)}}class N extends U{async get(){const e=await this.client.get("/.well-known/config");if(!e.ok)throw new s;return e.json()}}class H extends U{constructor(e,t){super(e,t),this.state=void 0,this.state=new x(t.cookieName)}async initialize(e,t,i){this.state.read();const r=this.state.getTTL(e),n=this.state.getActiveID(e),o=this.state.getEmailID(e);let a=this.state.getResendAfter(e);if(a>0)throw new u(a);if(!i&&r>0&&t===o)return{id:n,ttl:r};const c={user_id:e};t&&(c.email_id=t);const d=await this.client.post("/passcode/login/initialize",c);if(429===d.status)throw a=d.parseNumericHeader("Retry-After"),this.state.setResendAfter(e,a).write(),new u(a);if(!d.ok)throw new s;const h=d.json();return this.state.setActiveID(e,h.id).setTTL(e,h.ttl),t&&this.state.setEmailID(e,t),this.state.write(),h}async finalize(e,t){const i=this.state.read().getActiveID(e);if(this.state.getTTL(e)<=0)throw new d;const r=await this.client.post("/passcode/login/finalize",{id:i,code:t});if(401===r.status)throw new a;if(410===r.status)throw this.state.reset(e).write(),new h;if(!r.ok)throw new s;this.client.processResponseHeadersOnLogin(e,r)}getTTL(e){return this.state.read().getTTL(e)}getResendAfter(e){return this.state.read().getResendAfter(e)}}class K extends E{getState(e){var t;return(t=super.getUserState(e)).password||(t.password={})}read(){return super.read(),this}getRetryAfter(e){return y.timeToRemainingSeconds(this.getState(e).retryAfter)}setRetryAfter(e,t){return this.getState(e).retryAfter=y.remainingSecondsToTime(t),this}}class F extends U{constructor(e,t){super(e,t),this.passwordState=void 0,this.passcodeState=void 0,this.passwordState=new K(t.cookieName),this.passcodeState=new x(t.cookieName)}async login(e,t){const i=await this.client.post("/password/login",{user_id:e,password:t});if(401===i.status)throw new o;if(429===i.status){const t=i.parseNumericHeader("Retry-After");throw this.passwordState.read().setRetryAfter(e,t).write(),new u(t)}if(!i.ok)throw new s;this.client.processResponseHeadersOnLogin(e,i)}async update(e,t){const i=await this.client.put("/password",{user_id:e,password:t});if(401===i.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!i.ok)throw new s}getRetryAfter(e){return this.passwordState.read().getRetryAfter(e)}}class W extends U{async getInfo(e){const t=await this.client.post("/user",{email:e});if(404===t.status)throw new l;if(!t.ok)throw new s;return t.json()}async create(e){const t=await this.client.post("/users",{email:e});if(409===t.status)throw new i;if(403===t.status)throw new w;if(!t.ok)throw new s;const r=t.json();return r&&r.user_id&&this.client.processResponseHeadersOnLogin(r.user_id,t),r}async getCurrent(){const e=await this.client.get("/me");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!e.ok)throw new s;const t=e.json(),i=await this.client.get(`/users/${t.id}`);if(401===i.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!i.ok)throw new s;return i.json()}async delete(){const e=await this.client.delete("/user");if(e.ok)return this.client.cookie.removeAuthCookie(),this.client.sessionState.reset().write(),void this.client.dispatcher.dispatchUserDeletedEvent();if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;throw new s}async logout(){const e=await this.client.post("/logout");if(this.client.cookie.removeAuthCookie(),this.client.sessionState.reset().write(),this.client.dispatcher.dispatchUserLoggedOutEvent(),401!==e.status&&!e.ok)throw new s}}function q(e){const t="==".slice(0,(4-e.length%4)%4),s=e.replace(/-/g,"+").replace(/_/g,"/")+t,i=atob(s),r=new ArrayBuffer(i.length),n=new Uint8Array(r);for(let e=0;e<i.length;e++)n[e]=i.charCodeAt(e);return r}function z(e){const t=new Uint8Array(e);let s="";for(const e of t)s+=String.fromCharCode(e);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var J="copy",M="convert";function $(e,t,s){if(t===J)return s;if(t===M)return e(s);if(t instanceof Array)return s.map(s=>$(e,t[0],s));if(t instanceof Object){const i={};for(const[r,n]of Object.entries(t)){if(n.derive){const e=n.derive(s);void 0!==e&&(s[r]=e)}if(r in s)i[r]=null!=s[r]?$(e,n.schema,s[r]):null;else if(n.required)throw new Error(`Missing key: ${r}`)}return i}}function B(e,t){return{required:!0,schema:e,derive:t}}function V(e){return{required:!0,schema:e}}function X(e){return{required:!1,schema:e}}var G={type:V(J),id:V(M),transports:X(J)},Q={appid:X(J),appidExclude:X(J),credProps:X(J)},Y={appid:X(J),appidExclude:X(J),credProps:X(J)},Z={publicKey:V({rp:V(J),user:V({id:V(M),name:V(J),displayName:V(J)}),challenge:V(M),pubKeyCredParams:V(J),timeout:X(J),excludeCredentials:X([G]),authenticatorSelection:X(J),attestation:X(J),extensions:X(Q)}),signal:X(J)},ee={type:V(J),id:V(J),rawId:V(M),authenticatorAttachment:X(J),response:V({clientDataJSON:V(M),attestationObject:V(M),transports:B(J,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:B(Y,e=>e.getClientExtensionResults())},te={mediation:X(J),publicKey:V({challenge:V(M),timeout:X(J),rpId:X(J),allowCredentials:X([G]),userVerification:X(J),extensions:X(Q)}),signal:X(J)},se={type:V(J),id:V(J),rawId:V(M),authenticatorAttachment:X(J),response:V({clientDataJSON:V(M),authenticatorData:V(M),signature:V(M),userHandle:V(M)}),clientExtensionResults:B(Y,e=>e.getClientExtensionResults())};async function ie(e){const t=await navigator.credentials.create(function(e){return $(q,Z,e)}(e));return function(e){return $(z,ee,e)}(t)}async function re(e){const t=await navigator.credentials.get(function(e){return $(q,te,e)}(e));return function(e){return $(z,se,e)}(t)}class ne{static supported(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get&&window.PublicKeyCredential)}static async isPlatformAuthenticatorAvailable(){return!(!this.supported()||!window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable)&&window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}static async isSecurityKeySupported(){return void 0!==window.PublicKeyCredential&&window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported?window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported():this.supported()}static async isConditionalMediationAvailable(){return!(!window.PublicKeyCredential||!window.PublicKeyCredential.isConditionalMediationAvailable)&&window.PublicKeyCredential.isConditionalMediationAvailable()}}class oe extends E{getState(e){var t;return(t=super.getUserState(e)).webauthn||(t.webauthn={})}read(){return super.read(),this}getCredentials(e){var t;return(t=this.getState(e)).credentials||(t.credentials=[])}addCredential(e,t){return this.getCredentials(e).push(t),this}matchCredentials(e,t){return this.getCredentials(e).filter(e=>t.find(t=>t.id===e)).map(e=>({id:e}))}}class ae extends U{constructor(e,t){super(e,t),this.webauthnState=void 0,this.passcodeState=void 0,this.controller=void 0,this._getCredential=re,this._createCredential=ie,this.webauthnState=new oe(t.cookieName),this.passcodeState=new x(t.cookieName)}async login(e,t){const i=await this.client.post("/webauthn/login/initialize",{user_id:e});if(!i.ok)throw new s;const r=i.json();let o;r.signal=this._createAbortSignal(),t&&(r.mediation="conditional");try{o=await this._getCredential(r)}catch(e){throw new n(e)}const a=await this.client.post("/webauthn/login/finalize",o);if(400===a.status||401===a.status)throw new c;if(!a.ok)throw new s;const d=a.json();return this.webauthnState.read().addCredential(d.user_id,d.credential_id).write(),this.client.processResponseHeadersOnLogin(d.user_id,a),d}async register(){const e=await this.client.post("/webauthn/registration/initialize");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!e.ok)throw new s;const t=e.json();let i;t.signal=this._createAbortSignal();try{i=await this._createCredential(t)}catch(e){throw new n(e)}i.transports=i.response.transports;const r=await this.client.post("/webauthn/registration/finalize",i);if(401===r.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(422===r.status)throw new g;if(!r.ok)throw new s;const o=r.json();this.webauthnState.read().addCredential(o.user_id,o.credential_id).write()}async listCredentials(){const e=await this.client.get("/webauthn/credentials");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!e.ok)throw new s;return e.json()}async updateCredential(e,t){const i=await this.client.patch(`/webauthn/credentials/${e}`,{name:t});if(401===i.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!i.ok)throw new s}async deleteCredential(e){const t=await this.client.delete(`/webauthn/credentials/${e}`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!t.ok)throw new s}async shouldRegister(e){const t=ne.supported();if(!e.webauthn_credentials||!e.webauthn_credentials.length)return t;const s=this.webauthnState.read().matchCredentials(e.id,e.webauthn_credentials);return t&&!s.length}_createAbortSignal(){return this.controller&&this.controller.abort(),this.controller=new AbortController,this.controller.signal}}class ce extends U{async list(){const e=await this.client.get("/emails");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!e.ok)throw new s;return e.json()}async create(e){const t=await this.client.post("/emails",{address:e});if(t.ok)return t.json();if(400===t.status)throw new m;if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(409===t.status)throw new f;throw new s}async setPrimaryEmail(e){const t=await this.client.post(`/emails/${e}/set_primary`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!t.ok)throw new s}async delete(e){const t=await this.client.delete(`/emails/${e}`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(!t.ok)throw new s}}class de extends U{async auth(e,t){const s=new URL("/thirdparty/auth",this.client.api);if(!e)throw new v("somethingWentWrong",new Error("provider missing from request"));if(!t)throw new v("somethingWentWrong",new Error("redirectTo missing from request"));s.searchParams.append("provider",e),s.searchParams.append("redirect_to",t),window.location.assign(s.href)}getError(){const e=new URLSearchParams(window.location.search),t=e.get("error"),s=e.get("error_description");if(t){let e="";switch(t){case"access_denied":e="thirdPartyAccessDenied";break;case"user_conflict":e="emailAddressAlreadyExistsError";break;case"multiple_accounts":e="thirdPartyMultipleAccounts";break;case"unverified_email":e="thirdPartyUnverifiedEmail";break;case"email_maxnum":e="maxNumOfEmailAddressesReached";break;default:e="somethingWentWrong"}return new v(e,new Error(s))}}}class he extends U{async validate(){const e=new URLSearchParams(window.location.search).get("hanko_token");if(!e)return;window.history.replaceState(null,null,window.location.pathname);const t=await this.client.post("/token",{value:e});if(!t.ok)throw new s;const i=t.json();this.client.processResponseHeadersOnLogin(i.user_id,t)}}class le{static throttle(e,t,s={}){const{leading:i=!0,trailing:r=!0}=s;let n,o,a,c=0;const d=()=>{c=!1===i?0:Date.now(),a=null,e.apply(n,o)};return function(...s){const h=Date.now();c||!1!==i||(c=h);const l=t-(h-c);n=this,o=s,l<=0||l>t?(a&&(window.clearTimeout(a),a=null),c=h,e.apply(n,o)):a||!1===r||(a=window.setTimeout(d,l))}}}class ue{constructor(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=le.throttle}wrapCallback(e,t){const s=t=>{e(t.detail)};return t?this._throttle(s,this.throttleLimit,{leading:!0,trailing:!1}):s}addEventListenerWithType({type:e,callback:t,once:s=!1,throttle:i=!1}){const r=this.wrapCallback(t,i);return this._addEventListener(e,r,{once:s}),()=>this._removeEventListener(e,r)}static mapAddEventListenerParams(e,{once:t,callback:s},i){return{type:e,callback:s,once:t,throttle:i}}addEventListener(e,t,s){return this.addEventListenerWithType(ue.mapAddEventListenerParams(e,t,s))}onSessionCreated(e,t){return this.addEventListener(k,{callback:e,once:t},!0)}onSessionExpired(e,t){return this.addEventListener(b,{callback:e,once:t},!0)}onUserLoggedOut(e,t){return this.addEventListener(C,{callback:e,once:t})}onUserDeleted(e,t){return this.addEventListener(_,{callback:e,once:t})}onAuthFlowCompleted(e,t){return this.addEventListener(A,{callback:e,once:t})}}class pe{constructor(){this._tasks=[]}removeTask(e){window.clearTimeout(e.timeoutID),this._tasks=this._tasks.filter(t=>t!==e)}removeTasksWithType(e){this._tasks.filter(t=>t.type===e).forEach(e=>this.removeTask(e))}scheduleTask(e,t,s){const i={timeoutID:window.setTimeout(()=>{t(),this.removeTask(i)},1e3*s),type:e,func:t};this._tasks.push(i)}}class we{constructor(t){this._sessionState=void 0,this._cookie=void 0,this._sessionState=new S(e({},t)),this._cookie=new j(e({},t))}get(){const e=this._get();return we.validate(e)?e:null}isValid(){const e=this._get();return we.validate(e)}_get(){return this._sessionState.read(),{userID:this._sessionState.getUserID(),expirationSeconds:this._sessionState.getExpirationSeconds(),jwt:this._cookie.getAuthCookie()}}isAuthFlowCompleted(){return this._sessionState.read(),this._sessionState.getAuthFlowCompleted()}static validate(e){var t;return!!(e.expirationSeconds>0&&null!=(t=e.userID)&&t.length)}}class ge extends T{constructor(t){super(e({},t)),this._listener=new ue,this._scheduler=new pe,this._session=void 0,this.scheduleSessionExpiredEvent=e=>{this._scheduler.removeTasksWithType(b),this._scheduler.scheduleTask(b,()=>this.dispatchSessionExpiredEvent(),e.expirationSeconds)},this.cancelSessionExpiredEvent=()=>{this._scheduler.removeTasksWithType(b)},this.handleStorageEvent=e=>{if("hanko_session"!==e.key)return;const t=this._session.get();t?this._session.isAuthFlowCompleted()?this.dispatchAuthFlowCompletedEvent({userID:t.userID}):this.dispatchSessionCreatedEvent(t):this.dispatchSessionExpiredEvent()},this._session=new we(e({},t)),this.listenEventDependencies()}listenEventDependencies(){this._listener.onSessionCreated(this.scheduleSessionExpiredEvent),this._listener.onSessionExpired(this.cancelSessionExpiredEvent),this._listener.onUserDeleted(this.cancelSessionExpiredEvent),this._listener.onUserLoggedOut(this.cancelSessionExpiredEvent),window.addEventListener("storage",this.handleStorageEvent);const e=this._session.get();e&&this.scheduleSessionExpiredEvent(e)}}class fe extends ue{constructor(t,s){super(),this.api=void 0,this.config=void 0,this.user=void 0,this.webauthn=void 0,this.password=void 0,this.passcode=void 0,this.email=void 0,this.thirdParty=void 0,this.token=void 0,this.relay=void 0,this.session=void 0;const i={timeout:13e3,cookieName:"hanko",localStorageKey:"hanko"};void 0!==(null==s?void 0:s.cookieName)&&(i.cookieName=s.cookieName),void 0!==(null==s?void 0:s.timeout)&&(i.timeout=s.timeout),void 0!==(null==s?void 0:s.localStorageKey)&&(i.localStorageKey=s.localStorageKey),this.api=t,this.config=new N(t,i),this.user=new W(t,i),this.webauthn=new ae(t,i),this.password=new F(t,i),this.passcode=new H(t,i),this.email=new ce(t,i),this.thirdParty=new de(t,i),this.token=new he(t,i),this.relay=new ge(e({},i)),this.session=new we(e({},i))}}export{N as ConfigClient,i as ConflictError,O as CustomEventWithDetail,m as EmailAddressAlreadyExistsError,ce as EmailClient,w as ForbiddenError,fe as Hanko,t as HankoError,a as InvalidPasscodeError,o as InvalidPasswordError,c as InvalidWebauthnCredentialError,f as MaxNumOfEmailAddressesReachedError,h as MaxNumOfPasscodeAttemptsReachedError,l as NotFoundError,H as PasscodeClient,d as PasscodeExpiredError,F as PasswordClient,r as RequestTimeoutError,s as TechnicalError,de as ThirdPartyClient,v as ThirdPartyError,he as TokenClient,u as TooManyRequestsError,p as UnauthorizedError,W as UserClient,g as UserVerificationError,ae as WebauthnClient,n as WebauthnRequestCancelledError,ne as WebauthnSupport,A as authFlowCompletedType,k as sessionCreatedType,b as sessionExpiredType,_ as userDeletedType,C as userLoggedOutType};
2
2
  //# sourceMappingURL=sdk.modern.js.map