@teamhanko/hanko-frontend-sdk 1.4.0 → 1.5.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.
- package/README.md +8 -11
- package/dist/Hanko.d.ts +8 -3
- package/dist/lib/Dto.d.ts +38 -0
- package/dist/lib/client/HttpClient.d.ts +1 -2
- package/dist/lib/client/SessionClient.d.ts +12 -1
- package/dist/lib/events/CustomEvents.d.ts +4 -3
- package/dist/lib/events/Dispatcher.d.ts +0 -15
- package/dist/lib/events/Relay.d.ts +44 -39
- package/dist/lib/events/Scheduler.d.ts +51 -24
- package/dist/lib/events/SessionChannel.d.ts +61 -0
- package/dist/lib/events/SessionState.d.ts +38 -0
- package/dist/lib/events/WindowActivityManager.d.ts +36 -0
- package/dist/lib/flow-api/types/payload.d.ts +2 -0
- package/dist/lib/state/State.d.ts +0 -3
- package/dist/sdk.cjs +1 -1
- package/dist/sdk.cjs.map +1 -1
- package/dist/sdk.modern.js +1 -1
- package/dist/sdk.modern.js.map +1 -1
- package/dist/sdk.module.js +1 -1
- package/dist/sdk.module.js.map +1 -1
- package/dist/sdk.umd.js +1 -1
- package/dist/sdk.umd.js.map +1 -1
- package/package.json +1 -1
- package/dist/lib/Session.d.ts +0 -61
- package/dist/lib/state/session/SessionState.d.ts +0 -76
package/dist/sdk.modern.js
CHANGED
|
@@ -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)}var t=0;function s(e){return"__private_"+t+++"_"+e}function i(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}class n extends Error{constructor(e,t,s){super(e),this.code=void 0,this.cause=void 0,this.code=t,this.cause=s,Object.setPrototypeOf(this,n.prototype)}}class o extends n{constructor(e){super("Technical error","somethingWentWrong",e),Object.setPrototypeOf(this,o.prototype)}}class r extends n{constructor(e,t){super("Conflict error","conflict",t),Object.setPrototypeOf(this,r.prototype)}}class a extends n{constructor(e){super("Request timed out error","requestTimeout",e),Object.setPrototypeOf(this,a.prototype)}}class c extends n{constructor(e){super("Request cancelled error","requestCancelled",e),Object.setPrototypeOf(this,c.prototype)}}class h extends n{constructor(e){super("Invalid password error","invalidPassword",e),Object.setPrototypeOf(this,h.prototype)}}class d extends n{constructor(e){super("Invalid Passcode error","invalidPasscode",e),Object.setPrototypeOf(this,d.prototype)}}class l extends n{constructor(e){super("Invalid WebAuthn credential error","invalidWebauthnCredential",e),Object.setPrototypeOf(this,l.prototype)}}class u extends n{constructor(e){super("Passcode expired error","passcodeExpired",e),Object.setPrototypeOf(this,u.prototype)}}class p extends n{constructor(e){super("Maximum number of Passcode attempts reached error","passcodeAttemptsReached",e),Object.setPrototypeOf(this,p.prototype)}}class m extends n{constructor(e){super("Not found error","notFound",e),Object.setPrototypeOf(this,m.prototype)}}class w extends n{constructor(e,t){super("Too many requests error","tooManyRequests",t),this.retryAfter=void 0,this.retryAfter=e,Object.setPrototypeOf(this,w.prototype)}}class f extends n{constructor(e){super("Unauthorized error","unauthorized",e),Object.setPrototypeOf(this,f.prototype)}}class v extends n{constructor(e){super("Forbidden error","forbidden",e),Object.setPrototypeOf(this,v.prototype)}}class g extends n{constructor(e){super("User verification error","userVerification",e),Object.setPrototypeOf(this,g.prototype)}}class y extends n{constructor(e){super("Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",e),Object.setPrototypeOf(this,y.prototype)}}class k extends n{constructor(e){super("The email address already exists","emailAddressAlreadyExistsError",e),Object.setPrototypeOf(this,k.prototype)}}class E extends n{constructor(e,t){super("An error occurred during third party sign up/sign in",e,t),Object.setPrototypeOf(this,E.prototype)}}class S{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 x extends S{constructor(e){super(`${e.localStorageKey}_session`)}read(){return super.read(),this}getState(){var e;return(e=this.ls).session||(e.session={expiry:0,authFlowCompleted:!1}),this.ls.session}getExpirationSeconds(){return S.timeToRemainingSeconds(this.getState().expiry)}setExpirationSeconds(e){return this.getState().expiry=S.remainingSecondsToTime(e),this}getAuthFlowCompleted(){return this.getState().authFlowCompleted}setAuthFlowCompleted(e){return this.getState().authFlowCompleted=e,this}reset(){return delete this.getState().expiry,this}}const b="hanko-session-created",_="hanko-session-expired",C="hanko-user-logged-out",O="hanko-user-deleted";class P extends CustomEvent{constructor(e,t){super(e,{detail:t})}}class A{constructor(t){this._dispatchEvent=document.dispatchEvent.bind(document),this._sessionState=void 0,this._sessionState=new x(e({},t))}dispatch(e,t){this._dispatchEvent(new P(e,t))}dispatchSessionCreatedEvent(e){this.dispatch(b,e)}dispatchSessionExpiredEvent(){this.dispatch(_,null)}dispatchUserLoggedOutEvent(){this.dispatch(C,null)}dispatchUserDeletedEvent(){this.dispatch(O,null)}}function j(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 T=function e(t,s){function i(e,i,n){if("undefined"!=typeof document){"number"==typeof(n=j({},s,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var r in n)n[r]&&(o+="; "+r,!0!==n[r]&&(o+="="+n[r].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+o}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var s=document.cookie?document.cookie.split("; "):[],i={},n=0;n<s.length;n++){var o=s[n].split("="),r=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(i[a]=t.read(r,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",j({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,j({},this.attributes,t))},withConverter:function(t){return e(j({},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 N{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 T.get(this.authCookieName)}setAuthCookie(t,s){const i={secure:!0,sameSite:this.authCookieSameSite};void 0!==this.authCookieDomain&&(i.domain=this.authCookieDomain);const n=e({},i,s);if(("none"===n.sameSite||"None"===n.sameSite)&&!1===n.secure)throw new o(new Error("Secure attribute must be set when SameSite=None"));T.set(this.authCookieName,t,n)}removeAuthCookie(){T.remove(this.authCookieName)}}class R{constructor(e){this._xhr=void 0,this._xhr=e}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}class L{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 R(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 D{constructor(t,s){this.timeout=void 0,this.api=void 0,this.sessionState=void 0,this.dispatcher=void 0,this.cookie=void 0,this.lang=void 0,this.api=t,this.timeout=s.timeout,this.sessionState=new x(e({},s)),this.dispatcher=new A(e({},s)),this.cookie=new N(e({},s)),this.lang=s.lang}_fetch(e,t,s=new XMLHttpRequest){const i=this,n=this.api+e,r=this.timeout,c=this.cookie.getAuthCookie(),h=this.lang;return new Promise(function(e,d){s.open(t.method,n,!0),s.setRequestHeader("Accept","application/json"),s.setRequestHeader("Content-Type","application/json"),s.setRequestHeader("X-Language",h),c&&s.setRequestHeader("Authorization",`Bearer ${c}`),s.timeout=r,s.withCredentials=!0,s.onload=()=>{i.processHeaders(s),e(new L(s))},s.onerror=()=>{d(new o)},s.ontimeout=()=>{d(new a)},s.send(t.body?t.body.toString():null)})}processHeaders(e){let t="",s=0,i="";if(e.getAllResponseHeaders().split("\r\n").forEach(n=>{const o=n.toLowerCase();o.startsWith("x-auth-token")?t=e.getResponseHeader("X-Auth-Token"):o.startsWith("x-session-lifetime")?s=parseInt(e.getResponseHeader("X-Session-Lifetime"),10):o.startsWith("x-session-retention")&&(i=e.getResponseHeader("X-Session-Retention"))}),t){const e=new RegExp("^https://"),n=!!this.api.match(e)&&!!window.location.href.match(e),o="session"===i?void 0:new Date((new Date).getTime()+1e3*s);this.cookie.setAuthCookie(t,{secure:n,expires:o})}s>0&&(this.sessionState.read(),this.sessionState.setExpirationSeconds(s),this.sessionState.setAuthFlowCompleted(!1),this.sessionState.write())}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 D(e,t)}}class W extends U{getDomain(e){if(!e)throw new E("somethingWentWrong",new Error("email missing from request"));const t=e.split("@");if(2!==t.length)throw new E("somethingWentWrong",new Error("email is not in a valid email format."));const s=t[1].trim();if(""===s)throw new E("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 m(new Error("provider not found"));if(!e.ok)throw new o(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 E("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 E(e,new Error(s))}}}class I extends U{async getInfo(e){const t=await this.client.post("/user",{email:e});if(404===t.status)throw new m;if(!t.ok)throw new o;return t.json()}async create(e){const t=await this.client.post("/users",{email:e});if(409===t.status)throw new r;if(403===t.status)throw new v;if(!t.ok)throw new o;return t.json()}async getCurrent(){const e=await this.client.get("/me");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new f;if(!e.ok)throw new o;const t=e.json(),s=await this.client.get(`/users/${t.id}`);if(401===s.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new f;if(!s.ok)throw new o;return s.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 f;throw new o}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 o}}class q extends U{async list(){const e=await this.client.get("/emails");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new f;if(!e.ok)throw new o;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 k;if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new f;if(409===t.status)throw new y;throw new o}async setPrimaryEmail(e){const t=await this.client.post(`/emails/${e}/set_primary`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new f;if(!t.ok)throw new o}async delete(e){const t=await this.client.delete(`/emails/${e}`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new f;if(!t.ok)throw new o}}class K extends U{async auth(e,t){const s=new URL("/thirdparty/auth",this.client.api);if(!e)throw new E("somethingWentWrong",new Error("provider missing from request"));if(!t)throw new E("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 E(e,new Error(s))}}}class M 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 o;return t.json()}}class H{static throttle(e,t,s={}){const{leading:i=!0,trailing:n=!0}=s;let o,r,a,c=0;const h=()=>{c=!1===i?0:Date.now(),a=null,e.apply(o,r)};return function(...s){const d=Date.now();c||!1!==i||(c=d);const l=t-(d-c);o=this,r=s,l<=0||l>t?(a&&(window.clearTimeout(a),a=null),c=d,e.apply(o,r)):a||!1===n||(a=window.setTimeout(h,l))}}}class F{constructor(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=H.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 n=this.wrapCallback(t,i);return this._addEventListener(e,n,{once:s}),()=>this._removeEventListener(e,n)}static mapAddEventListenerParams(e,{once:t,callback:s},i){return{type:e,callback:s,once:t,throttle:i}}addEventListener(e,t,s){return this.addEventListenerWithType(F.mapAddEventListenerParams(e,t,s))}onSessionCreated(e,t){return this.addEventListener(b,{callback:e,once:t},!0)}onSessionExpired(e,t){return this.addEventListener(_,{callback:e,once:t},!0)}onUserLoggedOut(e,t){return this.addEventListener(C,{callback:e,once:t})}onUserDeleted(e,t){return this.addEventListener(O,{callback:e,once:t})}}class J{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 ${constructor(t){this._sessionState=void 0,this._cookie=void 0,this._sessionState=new x(e({},t)),this._cookie=new N(e({},t))}get(){const e=this._get();return $.validate(e)?e:null}isValid(){const e=this._get();return $.validate(e)}_get(){return this._sessionState.read(),{expirationSeconds:this._sessionState.getExpirationSeconds(),jwt:this._cookie.getAuthCookie()}}isAuthFlowCompleted(){return this._sessionState.read(),this._sessionState.getAuthFlowCompleted()}static validate(e){return e.expirationSeconds>0}}class B extends A{constructor(t){super(e({},t)),this._listener=new F,this._scheduler=new J,this._session=void 0,this.scheduleSessionExpiredEvent=e=>{this._scheduler.removeTasksWithType(_),this._scheduler.scheduleTask(_,()=>this.dispatchSessionExpiredEvent(),e.expirationSeconds)},this.cancelSessionExpiredEvent=()=>{this._scheduler.removeTasksWithType(_)},this.handleStorageEvent=e=>{if("hanko_session"!==e.key)return;const t=this._session.get();t?this.dispatchSessionCreatedEvent(t):this.dispatchSessionExpiredEvent()},this._session=new $(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)}}var V,z=/*#__PURE__*/s("actionDefinitions"),X=/*#__PURE__*/s("createActionsProxy");class G{toJSON(){return{name:this.name,payload:this.payload,error:this.error,status:this.status,csrf_token:this.csrf_token,actions:i(this,z)[z]}}constructor({name:e,payload:t,error:s,status:n,actions:o,csrf_token:r},a){Object.defineProperty(this,X,{value:Q}),this.name=void 0,this.payload=void 0,this.error=void 0,this.status=void 0,this.csrf_token=void 0,Object.defineProperty(this,z,{writable:!0,value:void 0}),this.actions=void 0,this.fetchNextState=void 0,this.name=e,this.payload=t,this.error=s,this.status=n,this.csrf_token=r,i(this,z)[z]=o,this.actions=i(this,X)[X](o,r),this.fetchNextState=a}runAction(e,t){const s={};if("inputs"in e&&"object"==typeof e.inputs&&null!==e.inputs){const t=e.inputs;for(const i in e.inputs){const e=t[i];e&&"value"in e&&(s[i]=e.value)}}return this.fetchNextState(e.href,{input_data:s,csrf_token:t})}validateAction(e){if("inputs"in e)for(const t in e.inputs){const s=e.inputs[t];function i(e,s,i,n){throw new Y({reason:e,inputName:t,wanted:i,actual:n,message:s})}const n=s.value;s.required&&!n&&i(V.Required,"is required"),(null!=s.min_length||null!=s.max_length)&&("length"in n||i(V.InvalidInputDefinition,'has min/max length requirement, but is missing "length" property',"string",typeof n),null!=s.min_length&&n<s.min_length&&i(V.MinLength,`too short (min ${s.min_length})`,s.min_length,n.length),null!=s.max_length&&n>s.max_length&&i(V.MaxLength,`too long (max ${s.max_length})`,s.max_length,n.length))}}}function Q(e,t){const s=e=>this.runAction(e,t),i=e=>this.validateAction(e);return new Proxy(e,{get(e,t){if("symbol"==typeof t)return e[t];const n=e[t];return null==n?null:e=>{const t=Object.assign(JSON.parse(JSON.stringify(n)),{validate:()=>(i(t),t),tryValidate(){try{i(t)}catch(e){if(e instanceof Y)return e;throw e}},run:()=>s(t)});if(null!==t&&"object"==typeof t&&"inputs"in t)for(const s in e){const i=t.inputs;i[s]||(i[s]={name:s,type:""}),i[s].value=e[s]}return t}}})}!function(e){e[e.InvalidInputDefinition=0]="InvalidInputDefinition",e[e.MinLength=1]="MinLength",e[e.MaxLength=2]="MaxLength",e[e.Required=3]="Required"}(V||(V={}));class Y extends Error{constructor(e){super(`"${e.inputName}" ${e.message}`),this.reason=void 0,this.inputName=void 0,this.wanted=void 0,this.actual=void 0,this.name="ValidationError",this.reason=e.reason,this.inputName=e.inputName,this.wanted=e.wanted,this.actual=e.actual}}function Z(e){return"object"==typeof e&&null!==e&&"status"in e&&"error"in e&&"name"in e&&Boolean(e.name)&&Boolean(e.status)}class ee extends U{constructor(...e){var t;super(...e),t=this,this.run=async function(e,s){try{if(!Z(e))throw new se(e);const n=s[e.name];if(!n)throw new te(e);let o=await n(e);if("object"==typeof(i=o)&&null!==i&&"href"in i&&"inputs"in i&&(o=await o.run()),Z(o))return t.run(o,s)}catch(e){if("function"==typeof s.onError)return s.onError(e)}var i}}async init(e,t){var s=this;const i=await async function e(i,n){try{const t=await s.client.post(i,n);return new G(t.json(),e)}catch(e){null==t.onError||t.onError(e)}}(e);await this.run(i,t)}async fromString(e,t){var s=this;const i=new G(JSON.parse(e),async function e(i,n){try{const t=await s.client.post(i,n);return new G(t.json(),e)}catch(e){null==t.onError||t.onError(e)}});await this.run(i,t)}}class te extends n{constructor(e){super("No handler found for state: "+("string"==typeof e.name?`"${e.name}"`:`(${typeof e.name})`),"handlerNotFoundError"),this.state=void 0,this.state=e,Object.setPrototypeOf(this,te.prototype)}}class se extends Error{constructor(e){super("Invalid state: "+("string"==typeof e.name?`"${e.name}"`:`(${typeof e.name})`)),this.state=void 0,this.state=e}}class ie extends U{async isValid(){const e=await this.client.get("/sessions/validate");if(!e.ok)throw new o;return e.json()}}class ne extends F{constructor(t,s){super(),this.api=void 0,this.user=void 0,this.email=void 0,this.thirdParty=void 0,this.enterprise=void 0,this.token=void 0,this.sessionClient=void 0,this.relay=void 0,this.session=void 0,this.flow=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),void 0!==(null==s?void 0:s.lang)&&(i.lang=s.lang),this.api=t,this.user=new I(t,i),this.email=new q(t,i),this.thirdParty=new K(t,i),this.enterprise=new W(t,i),this.token=new M(t,i),this.sessionClient=new ie(t,i),this.relay=new B(e({},i)),this.session=new $(e({},i)),this.flow=new ee(t,i)}setLang(e){this.flow.client.lang=e}}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()}}export{r as ConflictError,P as CustomEventWithDetail,k as EmailAddressAlreadyExistsError,q as EmailClient,W as EnterpriseClient,v as ForbiddenError,ne as Hanko,n as HankoError,d as InvalidPasscodeError,h as InvalidPasswordError,l as InvalidWebauthnCredentialError,y as MaxNumOfEmailAddressesReachedError,p as MaxNumOfPasscodeAttemptsReachedError,m as NotFoundError,u as PasscodeExpiredError,a as RequestTimeoutError,ie as SessionClient,o as TechnicalError,K as ThirdPartyClient,E as ThirdPartyError,M as TokenClient,w as TooManyRequestsError,f as UnauthorizedError,I as UserClient,g as UserVerificationError,c as WebauthnRequestCancelledError,oe as WebauthnSupport,b as sessionCreatedType,_ as sessionExpiredType,O 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)}var t=0;function s(e){return"__private_"+t+++"_"+e}function i(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}class n extends Error{constructor(e,t,s){super(e),this.code=void 0,this.cause=void 0,this.code=t,this.cause=s,Object.setPrototypeOf(this,n.prototype)}}class o extends n{constructor(e){super("Technical error","somethingWentWrong",e),Object.setPrototypeOf(this,o.prototype)}}class r extends n{constructor(e,t){super("Conflict error","conflict",t),Object.setPrototypeOf(this,r.prototype)}}class a extends n{constructor(e){super("Request timed out error","requestTimeout",e),Object.setPrototypeOf(this,a.prototype)}}class c extends n{constructor(e){super("Request cancelled error","requestCancelled",e),Object.setPrototypeOf(this,c.prototype)}}class h extends n{constructor(e){super("Invalid password error","invalidPassword",e),Object.setPrototypeOf(this,h.prototype)}}class d extends n{constructor(e){super("Invalid Passcode error","invalidPasscode",e),Object.setPrototypeOf(this,d.prototype)}}class l extends n{constructor(e){super("Invalid WebAuthn credential error","invalidWebauthnCredential",e),Object.setPrototypeOf(this,l.prototype)}}class u extends n{constructor(e){super("Passcode expired error","passcodeExpired",e),Object.setPrototypeOf(this,u.prototype)}}class p extends n{constructor(e){super("Maximum number of Passcode attempts reached error","passcodeAttemptsReached",e),Object.setPrototypeOf(this,p.prototype)}}class v extends n{constructor(e){super("Not found error","notFound",e),Object.setPrototypeOf(this,v.prototype)}}class m extends n{constructor(e,t){super("Too many requests error","tooManyRequests",t),this.retryAfter=void 0,this.retryAfter=e,Object.setPrototypeOf(this,m.prototype)}}class w extends n{constructor(e){super("Unauthorized error","unauthorized",e),Object.setPrototypeOf(this,w.prototype)}}class f extends n{constructor(e){super("Forbidden error","forbidden",e),Object.setPrototypeOf(this,f.prototype)}}class g extends n{constructor(e){super("User verification error","userVerification",e),Object.setPrototypeOf(this,g.prototype)}}class y extends n{constructor(e){super("Maximum number of email addresses reached error","maxNumOfEmailAddressesReached",e),Object.setPrototypeOf(this,y.prototype)}}class k extends n{constructor(e){super("The email address already exists","emailAddressAlreadyExistsError",e),Object.setPrototypeOf(this,k.prototype)}}class x extends n{constructor(e,t){super("An error occurred during third party sign up/sign in",e,t),Object.setPrototypeOf(this,x.prototype)}}const E="hanko-session-created",S="hanko-session-expired",C="hanko-user-logged-out",b="hanko-user-deleted";class O extends CustomEvent{constructor(e,t){super(e,{detail:t})}}class _{constructor(){this._dispatchEvent=document.dispatchEvent.bind(document)}dispatch(e,t){this._dispatchEvent(new O(e,t))}dispatchSessionCreatedEvent(e){this.dispatch(E,e)}dispatchSessionExpiredEvent(){this.dispatch(S,null)}dispatchUserLoggedOutEvent(){this.dispatch(C,null)}dispatchUserDeletedEvent(){this.dispatch(b,null)}}function I(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 L=function e(t,s){function i(e,i,n){if("undefined"!=typeof document){"number"==typeof(n=I({},s,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var o="";for(var r in n)n[r]&&(o+="; "+r,!0!==n[r]&&(o+="="+n[r].split(";")[0]));return document.cookie=e+"="+t.write(i,e)+o}}return Object.create({set:i,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var s=document.cookie?document.cookie.split("; "):[],i={},n=0;n<s.length;n++){var o=s[n].split("="),r=o.slice(1).join("=");try{var a=decodeURIComponent(o[0]);if(i[a]=t.read(r,a),e===a)break}catch(e){}}return e?i[e]:i}},remove:function(e,t){i(e,"",I({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,I({},this.attributes,t))},withConverter:function(t){return e(I({},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 P{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 L.get(this.authCookieName)}setAuthCookie(t,s){const i={secure:!0,sameSite:this.authCookieSameSite};void 0!==this.authCookieDomain&&(i.domain=this.authCookieDomain);const n=e({},i,s);if(("none"===n.sameSite||"None"===n.sameSite)&&!1===n.secure)throw new o(new Error("Secure attribute must be set when SameSite=None"));L.set(this.authCookieName,t,n)}removeAuthCookie(){L.remove(this.authCookieName)}}class A{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 A(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 N{constructor(t,s){this.timeout=void 0,this.api=void 0,this.dispatcher=void 0,this.cookie=void 0,this.lang=void 0,this.api=t,this.timeout=s.timeout,this.dispatcher=new _,this.cookie=new P(e({},s)),this.lang=s.lang}_fetch(e,t,s=new XMLHttpRequest){const i=this,n=this.api+e,r=this.timeout,c=this.cookie.getAuthCookie(),h=this.lang;return new Promise(function(e,d){s.open(t.method,n,!0),s.setRequestHeader("Accept","application/json"),s.setRequestHeader("Content-Type","application/json"),s.setRequestHeader("X-Language",h),c&&s.setRequestHeader("Authorization",`Bearer ${c}`),s.timeout=r,s.withCredentials=!0,s.onload=()=>{i.processHeaders(s),e(new D(s))},s.onerror=()=>{d(new o)},s.ontimeout=()=>{d(new a)},s.send(t.body?t.body.toString():null)})}_fetch_blocking(e,t,s=new XMLHttpRequest){const i=this.api+e,n=this.cookie.getAuthCookie();return s.open(t.method,i,!1),s.setRequestHeader("Accept","application/json"),s.setRequestHeader("Content-Type","application/json"),n&&s.setRequestHeader("Authorization",`Bearer ${n}`),s.withCredentials=!0,s.send(t.body?t.body.toString():null),s.responseText}processHeaders(e){let t="",s=0,i="";if(e.getAllResponseHeaders().split("\r\n").forEach(n=>{const o=n.toLowerCase();o.startsWith("x-auth-token")?t=e.getResponseHeader("X-Auth-Token"):o.startsWith("x-session-lifetime")?s=parseInt(e.getResponseHeader("X-Session-Lifetime"),10):o.startsWith("x-session-retention")&&(i=e.getResponseHeader("X-Session-Retention"))}),t){const e=new RegExp("^https://"),n=!!this.api.match(e)&&!!window.location.href.match(e),o="session"===i?void 0:new Date((new Date).getTime()+1e3*s);this.cookie.setAuthCookie(t,{secure:n,expires:o})}}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 j{constructor(e,t){this.client=void 0,this.client=new N(e,t)}}class R extends j{getDomain(e){if(!e)throw new x("somethingWentWrong",new Error("email missing from request"));const t=e.split("@");if(2!==t.length)throw new x("somethingWentWrong",new Error("email is not in a valid email format."));const s=t[1].trim();if(""===s)throw new x("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 v(new Error("provider not found"));if(!e.ok)throw new o(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 x("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 x(e,new Error(s))}}}class T extends j{async getInfo(e){const t=await this.client.post("/user",{email:e});if(404===t.status)throw new v;if(!t.ok)throw new o;return t.json()}async create(e){const t=await this.client.post("/users",{email:e});if(409===t.status)throw new r;if(403===t.status)throw new f;if(!t.ok)throw new o;return t.json()}async getCurrent(){const e=await this.client.get("/me");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!e.ok)throw new o;const t=e.json(),s=await this.client.get(`/users/${t.id}`);if(401===s.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!s.ok)throw new o;return s.json()}async delete(){const e=await this.client.delete("/user");if(e.ok)return this.client.cookie.removeAuthCookie(),void this.client.dispatcher.dispatchUserDeletedEvent();if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;throw new o}async logout(){const e=await this.client.post("/logout");if(this.client.cookie.removeAuthCookie(),this.client.dispatcher.dispatchUserLoggedOutEvent(),401!==e.status&&!e.ok)throw new o}}class q extends j{async list(){const e=await this.client.get("/emails");if(401===e.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!e.ok)throw new o;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 k;if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(409===t.status)throw new y;throw new o}async setPrimaryEmail(e){const t=await this.client.post(`/emails/${e}/set_primary`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!t.ok)throw new o}async delete(e){const t=await this.client.delete(`/emails/${e}`);if(401===t.status)throw this.client.dispatcher.dispatchSessionExpiredEvent(),new w;if(!t.ok)throw new o}}class U extends j{async auth(e,t){const s=new URL("/thirdparty/auth",this.client.api);if(!e)throw new x("somethingWentWrong",new Error("provider missing from request"));if(!t)throw new x("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 x(e,new Error(s))}}}class W extends j{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 o;return t.json()}}class M{static throttle(e,t,s={}){const{leading:i=!0,trailing:n=!0}=s;let o,r,a,c=0;const h=()=>{c=!1===i?0:Date.now(),a=null,e.apply(o,r)};return function(...s){const d=Date.now();c||!1!==i||(c=d);const l=t-(d-c);o=this,r=s,l<=0||l>t?(a&&(window.clearTimeout(a),a=null),c=d,e.apply(o,r)):a||!1===n||(a=window.setTimeout(h,l))}}}class H{constructor(){this.throttleLimit=1e3,this._addEventListener=document.addEventListener.bind(document),this._removeEventListener=document.removeEventListener.bind(document),this._throttle=M.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 n=this.wrapCallback(t,i);return this._addEventListener(e,n,{once:s}),()=>this._removeEventListener(e,n)}static mapAddEventListenerParams(e,{once:t,callback:s},i){return{type:e,callback:s,once:t,throttle:i}}addEventListener(e,t,s){return this.addEventListenerWithType(H.mapAddEventListenerParams(e,t,s))}onSessionCreated(e,t){return this.addEventListener(E,{callback:e,once:t},!0)}onSessionExpired(e,t){return this.addEventListener(S,{callback:e,once:t},!0)}onUserLoggedOut(e,t){return this.addEventListener(C,{callback:e,once:t})}onUserDeleted(e,t){return this.addEventListener(b,{callback:e,once:t})}}class K extends j{async validate(){const e=await this.client.get("/sessions/validate");if(!e.ok)throw new o;return await e.json()}}class J extends j{isValid(){let e;try{const t=this.client._fetch_blocking("/sessions/validate",{method:"GET"});e=JSON.parse(t)}catch(e){throw new o(e)}return!!e&&e.is_valid}}class ${constructor(e){this.storageKey=void 0,this.defaultState={expiration:0,lastCheck:0},this.storageKey=e}load(){const e=window.localStorage.getItem(this.storageKey);return null==e?this.defaultState:JSON.parse(e)}save(e){window.localStorage.setItem(this.storageKey,JSON.stringify(e||this.defaultState))}}class F{constructor(e,t){this.onActivityCallback=void 0,this.onInactivityCallback=void 0,this.handleFocus=()=>{this.onActivityCallback()},this.handleBlur=()=>{this.onInactivityCallback()},this.handleVisibilityChange=()=>{"visible"===document.visibilityState?this.onActivityCallback():this.onInactivityCallback()},this.hasFocus=()=>document.hasFocus(),this.onActivityCallback=e,this.onInactivityCallback=t,window.addEventListener("focus",this.handleFocus),window.addEventListener("blur",this.handleBlur),document.addEventListener("visibilitychange",this.handleVisibilityChange)}}class B{constructor(e,t,s){this.intervalID=null,this.timeoutID=null,this.checkInterval=void 0,this.checkSession=void 0,this.onSessionExpired=void 0,this.checkInterval=e,this.checkSession=t,this.onSessionExpired=s}scheduleSessionExpiry(e){var t=this;this.stop(),this.timeoutID=setTimeout(async function(){t.stop(),t.onSessionExpired()},e)}start(e=0,t=0){var s=this;const i=this.calcTimeToNextCheck(e);this.sessionExpiresSoon(t)?this.scheduleSessionExpiry(i):this.timeoutID=setTimeout(async function(){let e=await s.checkSession();if(e.is_valid){if(s.sessionExpiresSoon(e.expiration))return void s.scheduleSessionExpiry(e.expiration-Date.now());s.intervalID=setInterval(async function(){e=await s.checkSession(),e.is_valid?s.sessionExpiresSoon(e.expiration)&&s.scheduleSessionExpiry(e.expiration-Date.now()):s.stop()},s.checkInterval)}else s.stop()},i)}stop(){this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null),this.intervalID&&(clearInterval(this.intervalID),this.intervalID=null)}isRunning(){return null!==this.timeoutID||null!==this.intervalID}sessionExpiresSoon(e){return e>0&&e-Date.now()<=this.checkInterval}calcTimeToNextCheck(e){const t=Date.now()-e;return this.checkInterval>=t?this.checkInterval-t%this.checkInterval:0}}class z{constructor(e="hanko_session",t,s,i){this.channel=void 0,this.onSessionExpired=void 0,this.onSessionCreated=void 0,this.onLeadershipRequested=void 0,this.handleMessage=e=>{const t=e.data;switch(t.action){case"sessionExpired":this.onSessionExpired(t);break;case"sessionCreated":this.onSessionCreated(t);break;case"requestLeadership":this.onLeadershipRequested(t)}},this.onSessionExpired=t,this.onSessionCreated=s,this.onLeadershipRequested=i,this.channel=new BroadcastChannel(e),this.channel.onmessage=this.handleMessage}post(e){this.channel.postMessage(e)}}class V extends _{constructor(e,t){super(),this.listener=new H,this.checkInterval=3e4,this.client=void 0,this.sessionState=void 0,this.windowActivityManager=void 0,this.scheduler=void 0,this.sessionChannel=void 0,this.isLoggedIn=void 0,this.client=new K(e,t),this.checkInterval=t.sessionCheckInterval,this.sessionState=new $(`${t.cookieName}_session_state`),this.sessionChannel=new z(t.sessionCheckChannelName,()=>this.onChannelSessionExpired(),e=>this.onChannelSessionCreated(e),()=>this.onChannelLeadershipRequested()),this.scheduler=new B(this.checkInterval,()=>this.checkSession(),()=>this.onSessionExpired()),this.windowActivityManager=new F(()=>this.startSessionCheck(),()=>this.scheduler.stop());const s=Date.now(),{expiration:i}=this.sessionState.load();this.isLoggedIn=s<i,this.initializeEventListeners(),this.startSessionCheck()}initializeEventListeners(){this.listener.onSessionCreated(e=>{const{claims:t}=e,s=Date.parse(t.expiration),i=Date.now();this.isLoggedIn=!0,this.sessionState.save({expiration:s,lastCheck:i}),this.sessionChannel.post({action:"sessionCreated",claims:t}),this.startSessionCheck()}),this.listener.onUserLoggedOut(()=>{this.isLoggedIn=!1,this.sessionChannel.post({action:"sessionExpired"}),this.sessionState.save(null),this.scheduler.stop()}),window.addEventListener("beforeunload",()=>this.scheduler.stop())}startSessionCheck(){if(!this.windowActivityManager.hasFocus())return;if(this.sessionChannel.post({action:"requestLeadership"}),this.scheduler.isRunning())return;const{lastCheck:e,expiration:t}=this.sessionState.load();this.isLoggedIn&&this.scheduler.start(e,t)}async checkSession(){const e=Date.now(),{is_valid:t,claims:s,expiration_time:i}=await this.client.validate(),n=i?Date.parse(i):0;return!t&&this.isLoggedIn&&this.dispatchSessionExpiredEvent(),t?(this.isLoggedIn=!0,this.sessionState.save({lastCheck:e,expiration:n})):(this.isLoggedIn=!1,this.sessionState.save(null),this.sessionChannel.post({action:"sessionExpired"})),{is_valid:t,claims:s,expiration:n}}onSessionExpired(){this.isLoggedIn&&(this.isLoggedIn=!1,this.sessionState.save(null),this.sessionChannel.post({action:"sessionExpired"}),this.dispatchSessionExpiredEvent())}onChannelSessionExpired(){this.isLoggedIn&&(this.isLoggedIn=!1,this.dispatchSessionExpiredEvent())}onChannelSessionCreated(e){const{claims:t}=e,s=Date.now(),i=Date.parse(t.expiration)-s;this.isLoggedIn=!0,this.dispatchSessionCreatedEvent({claims:t,expirationSeconds:i})}onChannelLeadershipRequested(){this.windowActivityManager.hasFocus()||this.scheduler.stop()}}var X,G=/*#__PURE__*/s("actionDefinitions"),Q=/*#__PURE__*/s("createActionsProxy");class Y{toJSON(){return{name:this.name,payload:this.payload,error:this.error,status:this.status,csrf_token:this.csrf_token,actions:i(this,G)[G]}}constructor({name:e,payload:t,error:s,status:n,actions:o,csrf_token:r},a){Object.defineProperty(this,Q,{value:Z}),this.name=void 0,this.payload=void 0,this.error=void 0,this.status=void 0,this.csrf_token=void 0,Object.defineProperty(this,G,{writable:!0,value:void 0}),this.actions=void 0,this.fetchNextState=void 0,this.name=e,this.payload=t,this.error=s,this.status=n,this.csrf_token=r,i(this,G)[G]=o,this.actions=i(this,Q)[Q](o,r),this.fetchNextState=a}runAction(e,t){const s={};if("inputs"in e&&"object"==typeof e.inputs&&null!==e.inputs){const t=e.inputs;for(const i in e.inputs){const e=t[i];e&&"value"in e&&(s[i]=e.value)}}return this.fetchNextState(e.href,{input_data:s,csrf_token:t})}validateAction(e){if("inputs"in e)for(const t in e.inputs){const s=e.inputs[t];function i(e,s,i,n){throw new ee({reason:e,inputName:t,wanted:i,actual:n,message:s})}const n=s.value;s.required&&!n&&i(X.Required,"is required"),(null!=s.min_length||null!=s.max_length)&&("length"in n||i(X.InvalidInputDefinition,'has min/max length requirement, but is missing "length" property',"string",typeof n),null!=s.min_length&&n<s.min_length&&i(X.MinLength,`too short (min ${s.min_length})`,s.min_length,n.length),null!=s.max_length&&n>s.max_length&&i(X.MaxLength,`too long (max ${s.max_length})`,s.max_length,n.length))}}}function Z(e,t){const s=e=>this.runAction(e,t),i=e=>this.validateAction(e);return new Proxy(e,{get(e,t){if("symbol"==typeof t)return e[t];const n=e[t];return null==n?null:e=>{const t=Object.assign(JSON.parse(JSON.stringify(n)),{validate:()=>(i(t),t),tryValidate(){try{i(t)}catch(e){if(e instanceof ee)return e;throw e}},run:()=>s(t)});if(null!==t&&"object"==typeof t&&"inputs"in t)for(const s in e){const i=t.inputs;i[s]||(i[s]={name:s,type:""}),i[s].value=e[s]}return t}}})}!function(e){e[e.InvalidInputDefinition=0]="InvalidInputDefinition",e[e.MinLength=1]="MinLength",e[e.MaxLength=2]="MaxLength",e[e.Required=3]="Required"}(X||(X={}));class ee extends Error{constructor(e){super(`"${e.inputName}" ${e.message}`),this.reason=void 0,this.inputName=void 0,this.wanted=void 0,this.actual=void 0,this.name="ValidationError",this.reason=e.reason,this.inputName=e.inputName,this.wanted=e.wanted,this.actual=e.actual}}function te(e){return"object"==typeof e&&null!==e&&"status"in e&&"error"in e&&"name"in e&&Boolean(e.name)&&Boolean(e.status)}class se extends j{constructor(...e){var t;super(...e),t=this,this.run=async function(e,s){try{if(!te(e))throw new ne(e);const n=s[e.name];if(!n)throw new ie(e);let o=await n(e);if("object"==typeof(i=o)&&null!==i&&"href"in i&&"inputs"in i&&(o=await o.run()),te(o))return t.run(o,s)}catch(e){if("function"==typeof s.onError)return s.onError(e)}var i}}async init(e,t){var s=this;const i=await async function e(i,n){try{const t=await s.client.post(i,n);return new Y(t.json(),e)}catch(e){null==t.onError||t.onError(e)}}(e);await this.run(i,t)}async fromString(e,t){var s=this;const i=new Y(JSON.parse(e),async function e(i,n){try{const t=await s.client.post(i,n);return new Y(t.json(),e)}catch(e){null==t.onError||t.onError(e)}});await this.run(i,t)}}class ie extends n{constructor(e){super("No handler found for state: "+("string"==typeof e.name?`"${e.name}"`:`(${typeof e.name})`),"handlerNotFoundError"),this.state=void 0,this.state=e,Object.setPrototypeOf(this,ie.prototype)}}class ne extends Error{constructor(e){super("Invalid state: "+("string"==typeof e.name?`"${e.name}"`:`(${typeof e.name})`)),this.state=void 0,this.state=e}}class oe extends H{constructor(e,t){super(),this.api=void 0,this.user=void 0,this.email=void 0,this.thirdParty=void 0,this.enterprise=void 0,this.token=void 0,this.sessionClient=void 0,this.session=void 0,this.relay=void 0,this.flow=void 0;const s={timeout:13e3,cookieName:"hanko",localStorageKey:"hanko",sessionCheckInterval:3e4,sessionCheckChannelName:"hanko-session-check"};void 0!==(null==t?void 0:t.cookieName)&&(s.cookieName=t.cookieName),void 0!==(null==t?void 0:t.timeout)&&(s.timeout=t.timeout),void 0!==(null==t?void 0:t.localStorageKey)&&(s.localStorageKey=t.localStorageKey),void 0!==(null==t?void 0:t.cookieDomain)&&(s.cookieDomain=t.cookieDomain),void 0!==(null==t?void 0:t.cookieSameSite)&&(s.cookieSameSite=t.cookieSameSite),void 0!==(null==t?void 0:t.lang)&&(s.lang=t.lang),void 0!==(null==t?void 0:t.sessionCheckInterval)&&(s.sessionCheckInterval=t.sessionCheckInterval<3e3?3e3:t.sessionCheckInterval),void 0!==(null==t?void 0:t.sessionCheckChannelName)&&(s.sessionCheckChannelName=t.sessionCheckChannelName),this.api=e,this.user=new T(e,s),this.email=new q(e,s),this.thirdParty=new U(e,s),this.enterprise=new R(e,s),this.token=new W(e,s),this.sessionClient=new K(e,s),this.session=new J(e,s),this.relay=new V(e,s),this.flow=new se(e,s)}setLang(e){this.flow.client.lang=e}}class re{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()}}export{r as ConflictError,O as CustomEventWithDetail,k as EmailAddressAlreadyExistsError,q as EmailClient,R as EnterpriseClient,f as ForbiddenError,oe as Hanko,n as HankoError,d as InvalidPasscodeError,h as InvalidPasswordError,l as InvalidWebauthnCredentialError,y as MaxNumOfEmailAddressesReachedError,p as MaxNumOfPasscodeAttemptsReachedError,v as NotFoundError,u as PasscodeExpiredError,a as RequestTimeoutError,K as SessionClient,o as TechnicalError,U as ThirdPartyClient,x as ThirdPartyError,W as TokenClient,m as TooManyRequestsError,w as UnauthorizedError,T as UserClient,g as UserVerificationError,c as WebauthnRequestCancelledError,re as WebauthnSupport,E as sessionCreatedType,S as sessionExpiredType,b as userDeletedType,C as userLoggedOutType};
|
|
2
2
|
//# sourceMappingURL=sdk.modern.js.map
|