@teamhanko/hanko-frontend-sdk 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 m extends t{constructor(e){super("User verification error","userVerification",e),Object.setPrototypeOf(this,m.prototype)}}class g extends t{constructor(e){super("Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",e),Object.setPrototypeOf(this,g.prototype)}}class f extends t{constructor(e){super("The email address already exists","emailAddressAlreadyExistsError",e),Object.setPrototypeOf(this,f.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 k 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 x="hanko-session-created",b="hanko-session-expired",_="hanko-user-logged-out",C="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(x,e)}dispatchSessionExpiredEvent(){this.dispatch(b,null)}dispatchUserLoggedOutEvent(){this.dispatch(_,null)}dispatchUserDeletedEvent(){this.dispatch(C,null)}dispatchAuthFlowCompletedEvent(e){this._sessionState.read().setAuthFlowCompleted(!0).write(),this.dispatch(A,e)}}function P(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 R=function e(t,s){function i(e,i,r){if("undefined"!=typeof document){"number"==typeof(r=P({},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,"",P({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,P({},this.attributes,t))},withConverter:function(t){return e(P({},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 D{constructor(e){this.authCookieName=void 0,this.authCookieName=e.cookieName}getAuthCookie(){return R.get(this.authCookieName)}setAuthCookie(e,t={secure:!0}){R.set(this.authCookieName,e,t)}removeAuthCookie(){R.remove(this.authCookieName)}}class j{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 j(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 k(s.cookieName),this.dispatcher=new T(e({},s)),this.cookie=new D(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 W extends U{getDomain(e){if(!e)throw new v("somethingWentWrong",new Error("email missing from request"));const t=e.split("@");if(2!==t.length)throw new v("somethingWentWrong",new Error("email is not in a valid email format."));const s=t[1].trim();if(""===s)throw new v("somethingWentWrong",new Error("email is not in a valid email format."));return s}async hasProvider(e){const t=this.getDomain(e);return this.client.get(`/saml/provider?domain=${t}`).then(e=>{if(404==e.status)throw new l(new Error("provider not found"));if(!e.ok)throw new s(new Error("unable to fetch provider"));return e.ok})}auth(e,t){const s=new URL("/saml/auth",this.client.api),i=this.getDomain(e);if(!t)throw new v("somethingWentWrong",new Error("redirectTo missing from request"));s.searchParams.append("domain",i),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="enterpriseAccessDenied";break;case"user_conflict":e="emailAddressAlreadyExistsError";break;case"multiple_accounts":e="enterpriseMultipleAccounts";break;case"unverified_email":e="enterpriseUnverifiedEmail";break;case"email_maxnum":e="maxNumOfEmailAddressesReached";break;default:e="somethingWentWrong"}return new v(e,new Error(s))}}}class H extends U{constructor(e,t){super(e,t),this.state=void 0,this.state=new k(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 q 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 k(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 F 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 z(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 J(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 M="copy",$="convert";function B(e,t,s){if(t===M)return s;if(t===$)return e(s);if(t instanceof Array)return s.map(s=>B(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]?B(e,n.schema,s[r]):null;else if(n.required)throw new Error(`Missing key: ${r}`)}return i}}function V(e,t){return{required:!0,schema:e,derive:t}}function X(e){return{required:!0,schema:e}}function G(e){return{required:!1,schema:e}}var Q={type:X(M),id:X($),transports:G(M)},Y={appid:G(M),appidExclude:G(M),credProps:G(M)},Z={appid:G(M),appidExclude:G(M),credProps:G(M)},ee={publicKey:X({rp:X(M),user:X({id:X($),name:X(M),displayName:X(M)}),challenge:X($),pubKeyCredParams:X(M),timeout:G(M),excludeCredentials:G([Q]),authenticatorSelection:G(M),attestation:G(M),extensions:G(Y)}),signal:G(M)},te={type:X(M),id:X(M),rawId:X($),authenticatorAttachment:G(M),response:X({clientDataJSON:X($),attestationObject:X($),transports:V(M,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:V(Z,e=>e.getClientExtensionResults())},se={mediation:G(M),publicKey:X({challenge:X($),timeout:G(M),rpId:G(M),allowCredentials:G([Q]),userVerification:G(M),extensions:G(Y)}),signal:G(M)},ie={type:X(M),id:X(M),rawId:X($),authenticatorAttachment:G(M),response:X({clientDataJSON:X($),authenticatorData:X($),signature:X($),userHandle:X($)}),clientExtensionResults:V(Z,e=>e.getClientExtensionResults())};async function re(e){const t=await navigator.credentials.create(function(e){return B(z,ee,e)}(e));return function(e){return B(J,te,e)}(t)}async function ne(e){const t=await navigator.credentials.get(function(e){return B(z,se,e)}(e));return function(e){return B(J,ie,e)}(t)}class oe{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 ae 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 ce extends U{constructor(e,t){super(e,t),this.webauthnState=void 0,this.passcodeState=void 0,this.controller=void 0,this._getCredential=ne,this._createCredential=re,this.webauthnState=new ae(t.cookieName),this.passcodeState=new k(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 m;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=oe.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 de 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 f;if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(409===t.status)throw new g;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 he 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 le 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 ue{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 pe{constructor(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=ue.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(pe.mapAddEventListenerParams(e,t,s))}onSessionCreated(e,t){return this.addEventListener(x,{callback:e,once:t},!0)}onSessionExpired(e,t){return this.addEventListener(b,{callback:e,once:t},!0)}onUserLoggedOut(e,t){return this.addEventListener(_,{callback:e,once:t})}onUserDeleted(e,t){return this.addEventListener(C,{callback:e,once:t})}onAuthFlowCompleted(e,t){return this.addEventListener(A,{callback:e,once:t})}}class we{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 me{constructor(t){this._sessionState=void 0,this._cookie=void 0,this._sessionState=new S(e({},t)),this._cookie=new D(e({},t))}get(){const e=this._get();return me.validate(e)?e:null}isValid(){const e=this._get();return me.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 pe,this._scheduler=new we,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 me(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 pe{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.enterprise=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 F(t,i),this.webauthn=new ce(t,i),this.password=new q(t,i),this.passcode=new H(t,i),this.email=new de(t,i),this.thirdParty=new he(t,i),this.enterprise=new W(t,i),this.token=new le(t,i),this.relay=new ge(e({},i)),this.session=new me(e({},i))}}export{N as ConfigClient,i as ConflictError,O as CustomEventWithDetail,f as EmailAddressAlreadyExistsError,de as EmailClient,W as EnterpriseClient,w as ForbiddenError,fe as Hanko,t as HankoError,a as InvalidPasscodeError,o as InvalidPasswordError,c as InvalidWebauthnCredentialError,g as MaxNumOfEmailAddressesReachedError,h as MaxNumOfPasscodeAttemptsReachedError,l as NotFoundError,H as PasscodeClient,d as PasscodeExpiredError,q as PasswordClient,r as RequestTimeoutError,s as TechnicalError,he as ThirdPartyClient,v as ThirdPartyError,le as TokenClient,u as TooManyRequestsError,p as UnauthorizedError,F as UserClient,m as UserVerificationError,ce as WebauthnClient,n as WebauthnRequestCancelledError,oe as WebauthnSupport,A as authFlowCompletedType,x as sessionCreatedType,b as sessionExpiredType,C as userDeletedType,_ 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 m extends t{constructor(e){super("User verification error","userVerification",e),Object.setPrototypeOf(this,m.prototype)}}class g extends t{constructor(e){super("Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",e),Object.setPrototypeOf(this,g.prototype)}}class f extends t{constructor(e){super("The email address already exists","emailAddressAlreadyExistsError",e),Object.setPrototypeOf(this,f.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 k 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 E extends k{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 b="hanko-session-created",x="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(b,e)}dispatchSessionExpiredEvent(){this.dispatch(x,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 D{constructor(e){var t;this.authCookieName=void 0,this.authCookieDomain=void 0,this.authCookieSameSite=void 0,this.authCookieName=e.cookieName,this.authCookieDomain=e.cookieDomain,this.authCookieSameSite=null!=(t=e.cookieSameSite)?t:"lax"}getAuthCookie(){return P.get(this.authCookieName)}setAuthCookie(t,i){const r={secure:!0,sameSite:this.authCookieSameSite};void 0!==this.authCookieDomain&&(r.domain=this.authCookieDomain);const n=e({},r,i);if(("none"===n.sameSite||"None"===n.sameSite)&&!1===n.secure)throw new s(new Error("Secure attribute must be set when SameSite=None"));P.set(this.authCookieName,t,n)}removeAuthCookie(){P.remove(this.authCookieName)}}class j{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 j(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 E(s.cookieName),this.dispatcher=new T(e({},s)),this.cookie=new D(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=new RegExp("^https://"),t=!!this.api.match(e)&&!!window.location.href.match(e),r=new Date((new Date).getTime()+1e3*i);this.cookie.setAuthCookie(s,{secure:t,expires:r})}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 W extends U{getDomain(e){if(!e)throw new v("somethingWentWrong",new Error("email missing from request"));const t=e.split("@");if(2!==t.length)throw new v("somethingWentWrong",new Error("email is not in a valid email format."));const s=t[1].trim();if(""===s)throw new v("somethingWentWrong",new Error("email is not in a valid email format."));return s}async hasProvider(e){const t=this.getDomain(e);return this.client.get(`/saml/provider?domain=${t}`).then(e=>{if(404==e.status)throw new l(new Error("provider not found"));if(!e.ok)throw new s(new Error("unable to fetch provider"));return e.ok})}auth(e,t){const s=new URL("/saml/auth",this.client.api),i=this.getDomain(e);if(!t)throw new v("somethingWentWrong",new Error("redirectTo missing from request"));s.searchParams.append("domain",i),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="enterpriseAccessDenied";break;case"user_conflict":e="emailAddressAlreadyExistsError";break;case"multiple_accounts":e="enterpriseMultipleAccounts";break;case"unverified_email":e="enterpriseUnverifiedEmail";break;case"email_maxnum":e="maxNumOfEmailAddressesReached";break;default:e="somethingWentWrong"}return new v(e,new Error(s))}}}class H extends U{constructor(e,t){super(e,t),this.state=void 0,this.state=new E(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 k{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 q 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 E(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 F 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 z(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 J(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 M="copy",$="convert";function B(e,t,s){if(t===M)return s;if(t===$)return e(s);if(t instanceof Array)return s.map(s=>B(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]?B(e,n.schema,s[r]):null;else if(n.required)throw new Error(`Missing key: ${r}`)}return i}}function V(e,t){return{required:!0,schema:e,derive:t}}function X(e){return{required:!0,schema:e}}function G(e){return{required:!1,schema:e}}var Q={type:X(M),id:X($),transports:G(M)},Y={appid:G(M),appidExclude:G(M),credProps:G(M)},Z={appid:G(M),appidExclude:G(M),credProps:G(M)},ee={publicKey:X({rp:X(M),user:X({id:X($),name:X(M),displayName:X(M)}),challenge:X($),pubKeyCredParams:X(M),timeout:G(M),excludeCredentials:G([Q]),authenticatorSelection:G(M),attestation:G(M),extensions:G(Y)}),signal:G(M)},te={type:X(M),id:X(M),rawId:X($),authenticatorAttachment:G(M),response:X({clientDataJSON:X($),attestationObject:X($),transports:V(M,e=>{var t;return(null==(t=e.getTransports)?void 0:t.call(e))||[]})}),clientExtensionResults:V(Z,e=>e.getClientExtensionResults())},se={mediation:G(M),publicKey:X({challenge:X($),timeout:G(M),rpId:G(M),allowCredentials:G([Q]),userVerification:G(M),extensions:G(Y)}),signal:G(M)},ie={type:X(M),id:X(M),rawId:X($),authenticatorAttachment:G(M),response:X({clientDataJSON:X($),authenticatorData:X($),signature:X($),userHandle:X($)}),clientExtensionResults:V(Z,e=>e.getClientExtensionResults())};async function re(e){const t=await navigator.credentials.create(function(e){return B(z,ee,e)}(e));return function(e){return B(J,te,e)}(t)}async function ne(e){const t=await navigator.credentials.get(function(e){return B(z,se,e)}(e));return function(e){return B(J,ie,e)}(t)}class oe{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 ae extends k{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 ce extends U{constructor(e,t){super(e,t),this.webauthnState=void 0,this.passcodeState=void 0,this.controller=void 0,this._getCredential=ne,this._createCredential=re,this.webauthnState=new ae(t.cookieName),this.passcodeState=new E(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 m;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=oe.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 de 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 f;if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new p;if(409===t.status)throw new g;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 he 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;case"signup_disabled":e="signupDisabled";break;default:e="somethingWentWrong"}return new v(e,new Error(s))}}}class le 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 ue{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 pe{constructor(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=ue.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(pe.mapAddEventListenerParams(e,t,s))}onSessionCreated(e,t){return this.addEventListener(b,{callback:e,once:t},!0)}onSessionExpired(e,t){return this.addEventListener(x,{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 we{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 me{constructor(t){this._sessionState=void 0,this._cookie=void 0,this._sessionState=new S(e({},t)),this._cookie=new D(e({},t))}get(){const e=this._get();return me.validate(e)?e:null}isValid(){const e=this._get();return me.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 pe,this._scheduler=new we,this._session=void 0,this.scheduleSessionExpiredEvent=e=>{this._scheduler.removeTasksWithType(x),this._scheduler.scheduleTask(x,()=>this.dispatchSessionExpiredEvent(),e.expirationSeconds)},this.cancelSessionExpiredEvent=()=>{this._scheduler.removeTasksWithType(x)},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 me(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 pe{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.enterprise=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),void 0!==(null==s?void 0:s.cookieDomain)&&(i.cookieDomain=s.cookieDomain),void 0!==(null==s?void 0:s.cookieSameSite)&&(i.cookieSameSite=s.cookieSameSite),this.api=t,this.config=new N(t,i),this.user=new F(t,i),this.webauthn=new ce(t,i),this.password=new q(t,i),this.passcode=new H(t,i),this.email=new de(t,i),this.thirdParty=new he(t,i),this.enterprise=new W(t,i),this.token=new le(t,i),this.relay=new ge(e({},i)),this.session=new me(e({},i))}}export{N as ConfigClient,i as ConflictError,O as CustomEventWithDetail,f as EmailAddressAlreadyExistsError,de as EmailClient,W as EnterpriseClient,w as ForbiddenError,fe as Hanko,t as HankoError,a as InvalidPasscodeError,o as InvalidPasswordError,c as InvalidWebauthnCredentialError,g as MaxNumOfEmailAddressesReachedError,h as MaxNumOfPasscodeAttemptsReachedError,l as NotFoundError,H as PasscodeClient,d as PasscodeExpiredError,q as PasswordClient,r as RequestTimeoutError,s as TechnicalError,he as ThirdPartyClient,v as ThirdPartyError,le as TokenClient,u as TooManyRequestsError,p as UnauthorizedError,F as UserClient,m as UserVerificationError,ce as WebauthnClient,n as WebauthnRequestCancelledError,oe as WebauthnSupport,A as authFlowCompletedType,b as sessionCreatedType,x as sessionExpiredType,_ as userDeletedType,C as userLoggedOutType};
2
2
  //# sourceMappingURL=sdk.modern.js.map