@teamhanko/hanko-frontend-sdk 2.0.0 → 2.1.1
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 +2 -2
- package/dist/lib/flow-api/types/action.d.ts +2 -1
- package/dist/lib/flow-api/types/input.d.ts +3 -0
- package/dist/lib/flow-api/types/payload.d.ts +5 -0
- 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/sdk.module.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.module.js","sources":["../src/lib/Throttle.ts","../src/lib/events/CustomEvents.ts","../src/lib/events/Listener.ts","../src/lib/events/Dispatcher.ts","../src/lib/Errors.ts","../../node_modules/js-cookie/dist/js.cookie.mjs","../src/lib/Cookie.ts","../src/lib/SessionStorage.ts","../src/lib/client/HttpClient.ts","../src/lib/client/Client.ts","../src/lib/client/SessionClient.ts","../src/lib/events/SessionState.ts","../src/lib/events/WindowActivityManager.ts","../src/lib/events/Scheduler.ts","../src/lib/events/SessionChannel.ts","../src/lib/events/Relay.ts","../src/lib/WebauthnSupport.ts","../../node_modules/@github/webauthn-json/dist/esm/webauthn-json.js","../src/lib/flow-api/WebauthnManager.ts","../src/lib/flow-api/auto-steps.ts","../src/lib/flow-api/passkey-autofill-activation.ts","../src/lib/flow-api/State.ts","../src/lib/client/UserClient.ts","../src/Hanko.ts"],"sourcesContent":["/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {boolean=} leading - Whether to allow the function to be called on the leading edge of the wait timeout.\n * @property {boolean=} trailing - Whether to allow the function to be called on the trailing edge of the wait timeout.\n */\ninterface ThrottleOptions {\n leading?: boolean;\n trailing?: boolean;\n}\n\n// eslint-disable-next-line no-unused-vars\ntype ThrottledFunction<T extends (...args: any[]) => any> = (\n // eslint-disable-next-line no-unused-vars\n ...args: Parameters<T>\n) => void;\n\n/**\n * Provides throttle functionality.\n *\n * @hideconstructor\n * @category SDK\n * @subcategory Internal\n */\nexport class Throttle {\n /**\n * Throttles a function, ensuring that it can only be called once per `wait` milliseconds.\n *\n * @static\n * @param {function} func - The function to throttle.\n * @param {number} wait - The number of milliseconds to wait between function invocations.\n * @param {ThrottleOptions} options - Optional configuration for the throttle.\n * @returns {function} A throttled version of the original function.\n */\n // eslint-disable-next-line no-unused-vars,require-jsdoc\n static throttle<T extends (...args: any[]) => any>(\n func: T,\n wait: number,\n options: ThrottleOptions = {},\n ): ThrottledFunction<T> {\n const { leading = true, trailing = true } = options;\n let context: any;\n let args: any;\n let timeoutID: number;\n let previous = 0;\n\n // This function is used to invoke the original function.\n const executeThrottledFunction = () => {\n // If 'leading' is false and this is not the first invocation of the throttled function, set 'previous' to 0 to\n // ensure that the function is not called immediately.\n previous = leading === false ? 0 : Date.now();\n timeoutID = null;\n // Invoke the original function.\n func.apply(context, args);\n };\n\n // This is the throttled function that will be returned.\n const throttled = function (...funcArgs: Parameters<T>) {\n const now = Date.now();\n\n // If this is the first time the throttled function is being called, and 'leading' is false,\n // set 'previous' to the current time to ensure that the function is not called immediately.\n if (!previous && leading === false) previous = now;\n\n // The remaining wait time.\n const remaining = wait - (now - previous);\n\n // Save the context and arguments of the function call.\n // eslint-disable-next-line no-invalid-this\n context = this;\n args = funcArgs;\n\n // Check whether it's time to call the function immediately based on the leading and trailing options. If leading\n // is enabled and there was no previous invocation, or if trailing is enabled and the wait time has already passed,\n // the function will be invoked immediately.\n if (remaining <= 0 || remaining > wait) {\n // If there is a pending timeout, clear it.\n if (timeoutID) {\n window.clearTimeout(timeoutID);\n timeoutID = null;\n }\n\n // Invoke the original function and update the previous timestamp.\n previous = now;\n func.apply(context, args);\n } else if (!timeoutID && trailing !== false) {\n // If there is no pending timeout and trailing is allowed, start a new timeout.\n timeoutID = window.setTimeout(executeThrottledFunction, remaining);\n }\n };\n\n return throttled;\n }\n}\n","import { Claims } from \"../Dto\";\nimport { AnyState } from \"../flow-api/types/flow\";\n\n/**\n * The type of the `hanko-session-created` event.\n * @typedef {string} sessionCreatedType\n * @memberOf Listener\n */\nexport const sessionCreatedType: \"hanko-session-created\" =\n \"hanko-session-created\";\n\n/**\n * The type of the `hanko-session-expired` event.\n * @typedef {string} sessionExpiredType\n * @memberOf Listener\n */\nexport const sessionExpiredType: \"hanko-session-expired\" =\n \"hanko-session-expired\";\n\n/**\n * The type of the `hanko-user-logged-out` event.\n * @typedef {string} userLoggedOutType\n * @memberOf Listener\n */\nexport const userLoggedOutType: \"hanko-user-logged-out\" =\n \"hanko-user-logged-out\";\n\n/**\n * The type of the `hanko-user-deleted` event.\n * @typedef {string} userDeletedType\n * @memberOf Listener\n */\nexport const userDeletedType: \"hanko-user-deleted\" = \"hanko-user-deleted\";\n\n/**\n * The type of the `hanko-user-logged-in` event.\n * @typedef {string} userLoggedInType\n * @memberOf Listener\n */\nexport const userLoggedInType: \"hanko-user-logged-in\" = \"hanko-user-logged-in\";\n\n/**\n * The type of the `hanko-user-created` event.\n * @typedef {string} userCreatedType\n * @memberOf Listener\n */\nexport const userCreatedType: \"hanko-user-created\" = \"hanko-user-created\";\n\n/**\n * The type of the `hanko-after-state-change` event.\n * @typedef {string} flowAfterStateChangeType\n * @memberOf Listener\n */\nexport const flowAfterStateChangeType: \"hanko-after-state-change\" =\n \"hanko-after-state-change\";\n\n/**\n * The type of the `hanko-before-state-change` event.\n * @typedef {string} flowBeforeStateChangeType\n * @memberOf Listener\n */\nexport const flowBeforeStateChangeType: \"hanko-before-state-change\" =\n \"hanko-before-state-change\";\n\n/**\n * The type of the `hanko-flow-error` event.\n * @typedef {string} flowErrorType\n * @memberOf Listener\n */\nexport const flowErrorType: \"hanko-flow-error\" = \"hanko-flow-error\";\n\n/**\n * The data passed in the `hanko-session-created` or `hanko-session-resumed` event.\n *\n * @interface\n * @category SDK\n * @subcategory Events\n * @property {number} expirationSeconds - This property is deprecated. The number of seconds until the JWT expires.\n * @property {Claims} claims - The JSON web token associated with the session. Only present when the Hanko-API allows the JWT to be accessible client-side.\n */\nexport interface SessionDetail {\n claims: Claims;\n expirationSeconds: number; // deprecated\n}\n\nexport interface FlowErrorDetail {\n error: Error;\n}\n\nexport interface FlowDetail {\n state: AnyState;\n}\n\n/**\n * A custom event that includes a detail object.\n *\n * @category SDK\n * @subcategory Events\n * @extends CustomEvent\n * @ignore\n * @param {string} type - The type of the event.\n * @param {T} detail - The detail object to include in the event.\n */\nexport class CustomEventWithDetail<T> extends CustomEvent<T> {\n // eslint-disable-next-line require-jsdoc\n constructor(type: string, detail: T) {\n super(type, { detail });\n }\n}\n","import { Throttle } from \"../Throttle\";\nimport {\n CustomEventWithDetail,\n SessionDetail,\n FlowDetail,\n sessionCreatedType,\n sessionExpiredType,\n userDeletedType,\n userLoggedOutType,\n flowAfterStateChangeType,\n flowBeforeStateChangeType,\n flowErrorType,\n FlowErrorDetail,\n} from \"./CustomEvents\";\n\n/**\n * A callback function to be executed when an event is triggered.\n *\n * @alias CallbackFunc\n * @typedef {function} CallbackFunc\n * @memberOf Listener\n */\n// eslint-disable-next-line no-unused-vars\ntype CallbackFunc<T> = (detail: T) => any;\n\n/**\n * A wrapped callback function that will execute the original callback.\n *\n * @ignore\n * @param {T} event - The event object passed in the event.\n */\n// eslint-disable-next-line no-unused-vars\ntype WrappedCallback<T> = (event: CustomEventWithDetail<T>) => void;\n\n/**\n * A function returned when adding an event listener. The function can be called to remove the corresponding event\n * listener.\n *\n * @alias CleanupFunc\n * @typedef {function} CleanupFunc\n * @memberOf Listener\n */\ntype CleanupFunc = () => void;\n\n/**\n * @interface\n * @ignore\n * @property {Function} callback - The function to be executed.\n * @property {boolean=} once - Whether the event listener should be removed after being called once.\n */\ninterface EventListenerParams<T> {\n callback: CallbackFunc<T>;\n once?: boolean;\n}\n\n/**\n * @interface\n * @ignore\n * @extends {EventListenerParams<T>}\n * @property {string} type - The type of the event.\n * @property {boolean=} throttle - Whether the event listener should be throttled.\n */\ninterface EventListenerWithTypeParams<T> extends EventListenerParams<T> {\n type: string;\n throttle?: boolean;\n}\n\n/**\n * A class to bind event listener for custom events.\n *\n * @category SDK\n * @subcategory Events\n */\nexport class Listener {\n public throttleLimit = 1000;\n _addEventListener = document.addEventListener.bind(document);\n _removeEventListener = document.removeEventListener.bind(document);\n _throttle = Throttle.throttle;\n\n /**\n * Wraps the given callback.\n *\n * @param callback\n * @param throttle\n * @private\n * @return {WrappedCallback}\n */\n private wrapCallback<T>(\n callback: CallbackFunc<T>,\n throttle: boolean,\n ): WrappedCallback<T> {\n // The function that will be called when the event is triggered.\n const wrappedCallback = (event: CustomEventWithDetail<T>) => {\n callback(event.detail);\n };\n\n // Throttle the listener if multiple SDK instances could trigger the same event at the same time,\n // but the callback function should only be executed once.\n if (throttle) {\n return this._throttle(wrappedCallback, this.throttleLimit, {\n leading: true,\n trailing: false,\n });\n }\n\n return wrappedCallback;\n }\n\n /**\n * Adds an event listener with the specified type, callback function, and options.\n *\n * @private\n * @param {EventListenerWithTypeParams<T>} params - The parameters for the event listener.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n private addEventListenerWithType<T>({\n type,\n callback,\n once = false,\n throttle = false,\n }: EventListenerWithTypeParams<T>): CleanupFunc {\n const wrappedCallback = this.wrapCallback(callback, throttle);\n this._addEventListener(type, wrappedCallback, { once });\n return () => this._removeEventListener(type, wrappedCallback);\n }\n\n /**\n * Maps the parameters for an event listener to the `EventListenerWithTypeParams` interface.\n *\n * @static\n * @private\n * @param {string} type - The type of the event.\n * @param {EventListenerParams<T>} params - The parameters for the event listener.\n * @param {boolean} [throttle=false] - Whether the event listener should be throttled.\n * @returns {EventListenerWithTypeParams<T>}\n **/\n private static mapAddEventListenerParams<T>(\n type: string,\n { once, callback }: EventListenerParams<T>,\n throttle?: boolean,\n ): EventListenerWithTypeParams<T> {\n return {\n type,\n callback,\n once,\n throttle,\n };\n }\n\n /**\n * Adds an event listener with the specified type, callback function, and options.\n *\n * @private\n * @param {string} type - The type of the event.\n * @param {EventListenerParams<T>} params - The parameters for the event listener.\n * @param {boolean=} throttle - Whether the event listener should be throttled.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n private addEventListener<T>(\n type: string,\n params: EventListenerParams<T>,\n throttle?: boolean,\n ) {\n return this.addEventListenerWithType(\n Listener.mapAddEventListenerParams(type, params, throttle),\n );\n }\n\n /**\n * Adds an event listener for \"hanko-session-created\" events. Will be triggered across all browser windows, when the user\n * logs in, or when the page has been loaded or refreshed and there is a valid session.\n *\n * @param {CallbackFunc<SessionDetail>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onSessionCreated(\n callback: CallbackFunc<SessionDetail>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(sessionCreatedType, { callback, once }, true);\n }\n\n /**\n * Adds an event listener for \"hanko-session-expired\" events. The event will be triggered across all browser windows\n * as soon as the current JWT expires or the user logs out. It also triggers, when the user deletes the account in\n * another window.\n *\n * @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onSessionExpired(\n callback: CallbackFunc<null>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(sessionExpiredType, { callback, once }, true);\n }\n\n /**\n * Adds an event listener for hanko-user-deleted events. The event triggers, when the user has deleted the account in\n * the browser window where the deletion happened.\n *\n * @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onUserLoggedOut(\n callback: CallbackFunc<null>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(userLoggedOutType, { callback, once });\n }\n\n /**\n * Adds an event listener for hanko-user-deleted events. The event triggers, when the user has deleted the account.\n *\n * @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onUserDeleted(\n callback: CallbackFunc<null>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(userDeletedType, { callback, once });\n }\n\n public onAfterStateChange(\n callback: CallbackFunc<FlowDetail>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(\n flowAfterStateChangeType,\n { callback, once },\n false,\n );\n }\n\n public onBeforeStateChange(\n callback: CallbackFunc<FlowDetail>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(\n flowBeforeStateChangeType,\n { callback, once },\n false,\n );\n }\n}\n","import {\n SessionDetail,\n CustomEventWithDetail,\n sessionCreatedType,\n sessionExpiredType,\n userDeletedType,\n userLoggedOutType,\n flowAfterStateChangeType,\n FlowDetail,\n flowBeforeStateChangeType,\n} from \"./CustomEvents\";\n\n/**\n * A class that dispatches custom events.\n *\n * @category SDK\n * @subcategory Internal\n */\nexport class Dispatcher {\n _dispatchEvent = document.dispatchEvent.bind(document);\n\n /**\n * Dispatches a custom event.\n *\n * @param {string} type\n * @param {T} detail\n * @private\n */\n private dispatch<T>(type: string, detail: T) {\n this._dispatchEvent(new CustomEventWithDetail(type, detail));\n }\n\n /**\n * Dispatches a \"hanko-session-created\" event to the document with the specified detail.\n *\n * @param {SessionDetail} detail - The event detail.\n */\n public dispatchSessionCreatedEvent(detail: SessionDetail) {\n this.dispatch(sessionCreatedType, detail);\n }\n\n /**\n * Dispatches a \"hanko-session-expired\" event to the document.\n */\n public dispatchSessionExpiredEvent() {\n this.dispatch(sessionExpiredType, null);\n }\n\n /**\n * Dispatches a \"hanko-user-logged-out\" event to the document.\n */\n public dispatchUserLoggedOutEvent() {\n this.dispatch(userLoggedOutType, null);\n }\n\n /**\n * Dispatches a \"hanko-user-deleted\" event to the document.\n */\n public dispatchUserDeletedEvent() {\n this.dispatch(userDeletedType, null);\n }\n\n /**\n * Dispatches a \"hanko-after-state-change\" event to the document.\n */\n public dispatchAfterStateChangeEvent(detail: FlowDetail) {\n this.dispatch(flowAfterStateChangeType, detail);\n }\n\n /**\n * Dispatches a \"hanko-before-state-change\" event to the document.\n */\n public dispatchBeforeStateChangeEvent(detail: FlowDetail) {\n this.dispatch(flowBeforeStateChangeType, detail);\n }\n}\n","/**\n * Every error thrown in the SDK is an instance of 'HankoError'. The value of the 'code' property is eligible to\n * translate the error into an error message.\n *\n * @extends {Error}\n * @category SDK\n * @subcategory Errors\n * @param code {string} - An error code that refers to the error instance.\n * @param cause {Error=} - The original error\n */\nabstract class HankoError extends Error {\n code: string;\n cause?: Error;\n\n // eslint-disable-next-line require-jsdoc\n protected constructor(message: string, code: string, cause?: Error) {\n super(message);\n /**\n * @public\n * @type {string}\n */\n this.code = code;\n /**\n * @public\n * @type {Error=}\n */\n this.cause = cause;\n Object.setPrototypeOf(this, HankoError.prototype);\n }\n}\n\n/**\n * Every error that doesn't need to be handled in a special way is a 'TechnicalError'. Whenever you catch one, there is\n * usually nothing you can do but present an error to the user, e.g. \"Something went wrong\".\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass TechnicalError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Technical error\", \"somethingWentWrong\", cause);\n Object.setPrototypeOf(this, TechnicalError.prototype);\n }\n}\n\n/**\n * Attempting to create a resource that already exists results in a 'ConflictError'.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ConflictError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(userID?: string, cause?: Error) {\n super(\"Conflict error\", \"conflict\", cause);\n Object.setPrototypeOf(this, ConflictError.prototype);\n }\n}\n\n/**\n * A 'RequestTimeoutError' occurs when the specified timeout has been reached.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass RequestTimeoutError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Request timed out error\", \"requestTimeout\", cause);\n Object.setPrototypeOf(this, RequestTimeoutError.prototype);\n }\n}\n\n/**\n * A 'WebauthnRequestCancelledError' occurs during WebAuthn authentication or registration, when the WebAuthn API throws\n * an error. In most cases, this happens when the user cancels the browser's WebAuthn dialog.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass WebauthnRequestCancelledError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Request cancelled error\", \"requestCancelled\", cause);\n Object.setPrototypeOf(this, WebauthnRequestCancelledError.prototype);\n }\n}\n\n/**\n * An 'InvalidPasswordError' occurs when invalid credentials are provided when logging in with a password.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidPasswordError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Invalid password error\", \"invalidPassword\", cause);\n Object.setPrototypeOf(this, InvalidPasswordError.prototype);\n }\n}\n\n/**\n * An 'InvalidPasswordError' occurs when an incorrect code is entered when logging in with a passcode.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidPasscodeError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Invalid Passcode error\", \"invalidPasscode\", cause);\n Object.setPrototypeOf(this, InvalidPasscodeError.prototype);\n }\n}\n\n/**\n * An 'InvalidWebauthnCredentialError' occurs if invalid credentials were used when logging in with WebAuthn.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidWebauthnCredentialError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Invalid WebAuthn credential error\",\n \"invalidWebauthnCredential\",\n cause,\n );\n Object.setPrototypeOf(this, InvalidWebauthnCredentialError.prototype);\n }\n}\n\n/**\n * A 'PasscodeExpiredError' occurs when the passcode has expired.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass PasscodeExpiredError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Passcode expired error\", \"passcodeExpired\", cause);\n Object.setPrototypeOf(this, PasscodeExpiredError.prototype);\n }\n}\n\n/**\n * A 'MaxNumOfPasscodeAttemptsReachedError' occurs when an incorrect passcode is provided too many times.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass MaxNumOfPasscodeAttemptsReachedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Maximum number of Passcode attempts reached error\",\n \"passcodeAttemptsReached\",\n cause,\n );\n Object.setPrototypeOf(this, MaxNumOfPasscodeAttemptsReachedError.prototype);\n }\n}\n\n/**\n * A 'NotFoundError' occurs when the requested resource was not found.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass NotFoundError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Not found error\", \"notFound\", cause);\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n\n/**\n * A 'TooManyRequestsError' occurs due to rate limiting when too many requests are made.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass TooManyRequestsError extends HankoError {\n retryAfter?: number;\n // eslint-disable-next-line require-jsdoc\n constructor(retryAfter?: number, cause?: Error) {\n super(\"Too many requests error\", \"tooManyRequests\", cause);\n this.retryAfter = retryAfter;\n Object.setPrototypeOf(this, TooManyRequestsError.prototype);\n }\n}\n\n/**\n * An 'UnauthorizedError' occurs when the user is not authorized to access the resource.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass UnauthorizedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Unauthorized error\", \"unauthorized\", cause);\n Object.setPrototypeOf(this, UnauthorizedError.prototype);\n }\n}\n\n/**\n * A 'ForbiddenError' occurs when the user is not allowed to perform the requested action.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ForbiddenError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Forbidden error\", \"forbidden\", cause);\n Object.setPrototypeOf(this, ForbiddenError.prototype);\n }\n}\n\n/**\n * A 'UserVerificationError' occurs when the user verification requirements\n * for a WebAuthn ceremony are not met.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass UserVerificationError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"User verification error\", \"userVerification\", cause);\n Object.setPrototypeOf(this, UserVerificationError.prototype);\n }\n}\n\n/**\n * A 'MaxNumOfEmailAddressesReachedError' occurs when the user tries to add a new email address while the maximum number\n * of email addresses (see backend configuration) equals the number of email addresses already registered.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass MaxNumOfEmailAddressesReachedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Maximum number of email addresses reached error\",\n \"maxNumOfEmailAddressesReached\",\n cause,\n );\n Object.setPrototypeOf(this, MaxNumOfEmailAddressesReachedError.prototype);\n }\n}\n\n/**\n * An 'EmailAddressAlreadyExistsError' occurs when the user tries to add a new email address which already exists.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass EmailAddressAlreadyExistsError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"The email address already exists\",\n \"emailAddressAlreadyExistsError\",\n cause,\n );\n Object.setPrototypeOf(this, EmailAddressAlreadyExistsError.prototype);\n }\n}\n\n/**\n * A `ThirdPartyError` may occur during a sign in/sign up with a third party\n * provider.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ThirdPartyError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(code: string, cause?: Error) {\n super(\"An error occurred during third party sign up/sign in\", code, cause);\n Object.setPrototypeOf(this, ThirdPartyError.prototype);\n }\n}\n\nexport {\n HankoError,\n TechnicalError,\n ConflictError,\n RequestTimeoutError,\n WebauthnRequestCancelledError,\n InvalidPasswordError,\n InvalidPasscodeError,\n InvalidWebauthnCredentialError,\n PasscodeExpiredError,\n MaxNumOfPasscodeAttemptsReachedError,\n NotFoundError,\n TooManyRequestsError,\n UnauthorizedError,\n ForbiddenError,\n UserVerificationError,\n MaxNumOfEmailAddressesReachedError,\n EmailAddressAlreadyExistsError,\n ThirdPartyError,\n};\n","/*! js-cookie v3.0.5 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n function set (name, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n name = encodeURIComponent(name)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n name + '=' + converter.write(value, name) + stringifiedAttributes)\n }\n\n function get (name) {\n if (typeof document === 'undefined' || (arguments.length && !name)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var found = decodeURIComponent(parts[0]);\n jar[found] = converter.read(value, found);\n\n if (name === found) {\n break\n }\n } catch (e) {}\n }\n\n return name ? jar[name] : jar\n }\n\n return Object.create(\n {\n set,\n get,\n remove: function (name, attributes) {\n set(\n name,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n/* eslint-enable no-var */\n\nexport { api as default };\n","import JSCookie, { CookieAttributes } from \"js-cookie\";\nimport { TechnicalError } from \"./Errors\";\n\n/**\n * Options for Cookie\n *\n * @category SDK\n * @subcategory Internal\n * @property {string=} cookieName - The name of the session cookie set from the SDK. Defaults to \"hanko\".\n * @property {string=} cookieDomain - The domain where the cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.\n * @property {string=} cookieSameSite -Specify whether/when cookies are sent with cross-site requests. Defaults to \"lax\".\n */\ninterface CookieOptions {\n cookieName?: string;\n cookieDomain?: string;\n cookieSameSite?: CookieSameSite;\n}\n\nexport type CookieSameSite =\n | \"strict\"\n | \"Strict\"\n | \"lax\"\n | \"Lax\"\n | \"none\"\n | \"None\";\n\n/**\n * A class to manage cookies.\n *\n * @category SDK\n * @subcategory Internal\n * @param {CookieOptions} options - The options that can be used\n */\nexport class Cookie {\n authCookieName: string;\n authCookieDomain?: string;\n authCookieSameSite: CookieSameSite;\n\n // eslint-disable-next-line require-jsdoc\n constructor(options: CookieOptions) {\n this.authCookieName = options.cookieName ?? \"hanko\";\n this.authCookieDomain = options.cookieDomain;\n this.authCookieSameSite = options.cookieSameSite ?? \"lax\";\n }\n\n /**\n * Returns the authentication token that was stored in the cookie.\n *\n * @return {string}\n */\n getAuthCookie(): string {\n return JSCookie.get(this.authCookieName);\n }\n\n /**\n * Stores the authentication token to the cookie.\n *\n * @param {string} token - The authentication token to be stored.\n * @param {CookieAttributes} options - Options for setting the auth cookie.\n */\n setAuthCookie(token: string, options?: CookieAttributes) {\n const defaults: CookieAttributes = {\n secure: true,\n sameSite: this.authCookieSameSite,\n };\n\n if (this.authCookieDomain !== undefined) {\n defaults.domain = this.authCookieDomain;\n }\n\n const o: CookieAttributes = { ...defaults, ...options };\n\n if (\n (o.sameSite === \"none\" || o.sameSite === \"None\") &&\n o.secure === false\n ) {\n throw new TechnicalError(\n new Error(\"Secure attribute must be set when SameSite=None\"),\n );\n }\n\n JSCookie.set(this.authCookieName, token, o);\n }\n\n /**\n * Removes the cookie used for authentication.\n */\n removeAuthCookie() {\n JSCookie.remove(this.authCookieName);\n }\n}\n","/**\n * Options for SessionStorage\n *\n * @category SDK\n * @subcategory Internal\n * @property {string} keyName - The name of the sessionStorage session token entry set from the SDK.\n */\ninterface SessionStorageOptions {\n keyName: string;\n}\n\n/**\n * A class to manage sessionStorage.\n *\n * @category SDK\n * @subcategory Internal\n * @param {SessionStorageOptions} options - The options that can be used.\n */\nexport class SessionStorage {\n keyName: string;\n\n // eslint-disable-next-line require-jsdoc\n constructor(options: SessionStorageOptions) {\n this.keyName = options.keyName;\n }\n\n /**\n * Return the session token that was stored in the sessionStorage.\n *\n * @return {string}\n */\n getSessionToken(): string {\n return sessionStorage.getItem(this.keyName);\n }\n\n /**\n * Stores the session token in the sessionStorage.\n *\n * @param {string} token - The session token to be stored.\n */\n setSessionToken(token: string) {\n sessionStorage.setItem(this.keyName, token);\n }\n\n /**\n * Removes the session token used for authentication.\n */\n removeSessionToken() {\n sessionStorage.removeItem(this.keyName);\n }\n}\n","import { RequestTimeoutError, TechnicalError } from \"../Errors\";\nimport { Dispatcher } from \"../events/Dispatcher\";\nimport { Cookie } from \"../Cookie\";\nimport { SessionStorage } from \"../SessionStorage\";\nimport { CookieAttributes } from \"js-cookie\";\nimport { HankoOptions } from \"../../Hanko\";\n\nexport type SessionTokenLocation = \"cookie\" | \"sessionStorage\";\n\n/**\n * This class wraps an XMLHttpRequest to maintain compatibility with the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {XMLHttpRequest} xhr - The request to be wrapped.\n * @see HttpClient\n */\nclass Headers {\n _xhr: XMLHttpRequest;\n\n // eslint-disable-next-line require-jsdoc\n constructor(xhr: XMLHttpRequest) {\n this._xhr = xhr;\n }\n\n /**\n * Returns the response header with the given name.\n *\n * @param {string} name\n * @return {string}\n */\n getResponseHeader(name: string) {\n return this._xhr.getResponseHeader(name);\n }\n}\n\n/**\n * This class wraps an XMLHttpRequest to maintain compatibility with the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {XMLHttpRequest} xhr - The request to be wrapped.\n * @see HttpClient\n */\nclass Response {\n headers: Headers;\n ok: boolean;\n status: number;\n statusText: string;\n url: string;\n _decodedJSON: any;\n xhr: XMLHttpRequest;\n\n // eslint-disable-next-line require-jsdoc\n constructor(xhr: XMLHttpRequest) {\n /**\n * @public\n * @type {Headers}\n */\n this.headers = new Headers(xhr);\n /**\n * @public\n * @type {boolean}\n */\n this.ok = xhr.status >= 200 && xhr.status <= 299;\n /**\n * @public\n * @type {number}\n */\n this.status = xhr.status;\n /**\n * @public\n * @type {string}\n */\n this.statusText = xhr.statusText;\n /**\n * @public\n * @type {string}\n */\n this.url = xhr.responseURL;\n /**\n * @private\n * @type {XMLHttpRequest}\n */\n this.xhr = xhr;\n }\n\n /**\n * Returns the JSON decoded response.\n *\n * @return {any}\n */\n json() {\n if (!this._decodedJSON) {\n this._decodedJSON = JSON.parse(this.xhr.response);\n }\n return this._decodedJSON;\n }\n\n /**\n * Returns the response header value with the given `name` as a number. When the value is not a number the return\n * value will be 0.\n *\n * @param {string} name - The name of the header field\n * @return {number}\n */\n parseNumericHeader(name: string): number {\n const result = parseInt(this.headers.getResponseHeader(name), 10);\n return isNaN(result) ? 0 : result;\n }\n}\n\n/**\n * Options for the HttpClient\n *\n * @category SDK\n * @subcategory Internal\n * @property {number=} timeout - The http request timeout in milliseconds.\n * @property {string} cookieName - The name of the session cookie set from the SDK.\n * @property {string=} cookieDomain - The domain where cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.\n * @property {string?} lang - The language used by the client(s) to convey to the Hanko API the language to use -\n * e.g. for translating outgoing emails - in a custom header (X-Language).\n */\nexport interface HttpClientOptions {\n timeout?: number;\n cookieName?: string;\n cookieDomain?: string;\n lang?: string;\n sessionTokenLocation?: SessionTokenLocation;\n}\n\n/**\n * Internally used for communication with the Hanko API. It also handles authorization tokens to enable authorized\n * requests.\n *\n * Currently, there is an issue with Safari and on iOS 15 devices where decoding a JSON response via the fetch API\n * breaks the user gesture and the user is not able to use the authenticator. Therefore, this class uses XMLHttpRequests\n * instead of the fetch API, but maintains compatibility by wrapping the XMLHttpRequests. So, if the issues are fixed,\n * we can easily return to the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {string} api - The URL of your Hanko API instance\n * @param {HttpClientOptions} options - The options the HttpClient must be provided\n */\nclass HttpClient {\n timeout: number;\n api: string;\n dispatcher: Dispatcher;\n cookie: Cookie;\n sessionTokenStorage: SessionStorage;\n lang: string;\n sessionTokenLocation: SessionTokenLocation;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options: HankoOptions) {\n this.api = api;\n this.timeout = options.timeout ?? 13000;\n this.dispatcher = new Dispatcher();\n this.cookie = new Cookie({ ...options });\n this.sessionTokenStorage = new SessionStorage({\n keyName: options.cookieName,\n });\n this.lang = options.lang;\n this.sessionTokenLocation = options.sessionTokenLocation;\n }\n\n // eslint-disable-next-line require-jsdoc\n _fetch(path: string, options: RequestInit, xhr = new XMLHttpRequest()) {\n const self = this;\n const url = this.api + path;\n const timeout = this.timeout;\n const bearerToken = this.getAuthToken();\n const lang = this.lang;\n\n return new Promise<Response>(function (resolve, reject) {\n xhr.open(options.method, url, true);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\n xhr.setRequestHeader(\"X-Language\", lang);\n\n if (bearerToken) {\n xhr.setRequestHeader(\"Authorization\", `Bearer ${bearerToken}`);\n }\n\n xhr.timeout = timeout;\n xhr.withCredentials = true;\n xhr.onload = () => {\n self.processHeaders(xhr);\n resolve(new Response(xhr));\n };\n\n xhr.onerror = () => {\n reject(new TechnicalError());\n };\n\n xhr.ontimeout = () => {\n reject(new RequestTimeoutError());\n };\n\n xhr.send(options.body ? options.body.toString() : null);\n });\n }\n\n /**\n * Processes the response headers on login and extracts the JWT and expiration time.\n *\n * @param {XMLHttpRequest} xhr - The xhr object.\n */\n processHeaders(xhr: XMLHttpRequest) {\n let jwt = \"\";\n let expirationSeconds = 0;\n let retention = \"\";\n\n xhr\n .getAllResponseHeaders()\n .split(\"\\r\\n\")\n .forEach((h) => {\n const header = h.toLowerCase();\n if (header.startsWith(\"x-auth-token\")) {\n jwt = xhr.getResponseHeader(\"X-Auth-Token\");\n } else if (header.startsWith(\"x-session-lifetime\")) {\n expirationSeconds = parseInt(\n xhr.getResponseHeader(\"X-Session-Lifetime\"),\n 10,\n );\n } else if (header.startsWith(\"x-session-retention\")) {\n retention = xhr.getResponseHeader(\"X-Session-Retention\");\n }\n });\n\n if (jwt) {\n const https = new RegExp(\"^https://\");\n const secure =\n !!this.api.match(https) && !!window.location.href.match(https);\n\n const expires =\n retention === \"session\"\n ? undefined\n : new Date(new Date().getTime() + expirationSeconds * 1000);\n\n this.setAuthToken(jwt, { secure, expires });\n }\n }\n\n /**\n * Performs a GET request.\n *\n * @param {string} path - The path to the requested resource.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n get(path: string) {\n return this._fetch(path, { method: \"GET\" });\n }\n\n /**\n * Performs a POST request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n post(path: string, body?: any) {\n return this._fetch(path, {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a PUT request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n put(path: string, body?: any) {\n return this._fetch(path, {\n method: \"PUT\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a PATCH request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n patch(path: string, body?: any) {\n return this._fetch(path, {\n method: \"PATCH\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a DELETE request.\n *\n * @param {string} path - The path to the requested resource.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n delete(path: string) {\n return this._fetch(path, {\n method: \"DELETE\",\n });\n }\n\n /**\n * Returns the session token either from the cookie or the sessionStorage.\n * @private\n * @return {string}\n */\n private getAuthToken(): string {\n let token = \"\";\n switch (this.sessionTokenLocation) {\n case \"cookie\":\n token = this.cookie.getAuthCookie();\n break;\n case \"sessionStorage\":\n token = this.sessionTokenStorage.getSessionToken();\n break;\n default:\n token = this.cookie.getAuthCookie();\n break;\n }\n return token;\n }\n\n /**\n * Stores the session token either in a cookie or in the sessionStorage depending on the configuration.\n * @param {string} token - The session token to be stored.\n * @param {CookieAttributes} options - Options for setting the auth cookie.\n * @private\n */\n private setAuthToken(token: string, options: CookieAttributes) {\n switch (this.sessionTokenLocation) {\n case \"cookie\":\n return this.cookie.setAuthCookie(token, options);\n case \"sessionStorage\":\n return this.sessionTokenStorage.setSessionToken(token);\n default:\n return this.cookie.setAuthCookie(token, options);\n }\n }\n}\n\nexport { Headers, Response, HttpClient };\n","import { HttpClient, HttpClientOptions } from \"./HttpClient\";\n\n/**\n * A class to be extended by the other client classes.\n *\n * @abstract\n * @category SDK\n * @subcategory Internal\n * @param {string} api - The URL of your Hanko API instance\n * @param {HttpClientOptions} options - The options that can be used\n */\nabstract class Client {\n client: HttpClient;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options: HttpClientOptions) {\n /**\n * @public\n * @type {HttpClient}\n */\n this.client = new HttpClient(api, options);\n }\n}\n\nexport { Client };\n","import { Client } from \"./Client\";\nimport { SessionCheckResponse } from \"../Dto\";\nimport { TechnicalError } from \"../Errors\";\n\n/**\n * A class that handles communication with the Hanko API for the purposes\n * of sessions.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nexport class SessionClient extends Client {\n /**\n * Checks if the current session is still valid.\n *\n * @return {Promise<SessionCheckResponse>}\n * @throws {TechnicalError}\n */\n async validate(): Promise<SessionCheckResponse> {\n const response = await this.client.get(\"/sessions/validate\");\n\n if (!response.ok) {\n throw new TechnicalError();\n }\n\n return await response.json();\n }\n}\n","/**\n * Represents the session state with expiration and last check timestamps.\n *\n * @category SDK\n * @subcategory Internal\n */\nexport interface State {\n expiration: number; // Timestamp (in milliseconds) when the session expires.\n lastCheck: number; // Timestamp (in milliseconds) of the last session check.\n}\n\n/**\n * Manages session state persistence using localStorage.\n *\n * @category SDK\n * @subcategory Internal\n */\nexport class SessionState {\n private readonly storageKey: string;\n private readonly defaultState: State = {\n expiration: 0,\n lastCheck: 0,\n };\n\n /**\n * Creates an instance of SessionState.\n *\n * @param {string} storageKey - The key used to store session state in localStorage.\n */\n constructor(storageKey: string) {\n this.storageKey = storageKey;\n }\n\n /**\n * Loads the current session state from localStorage.\n *\n * @returns {State} The parsed session state or a default state if not found.\n */\n load(): State {\n const item = window.localStorage.getItem(this.storageKey);\n return item == null ? this.defaultState : JSON.parse(item);\n }\n\n /**\n * Saves the session state to localStorage.\n *\n * @param {State | null} session - The session state to save. If null, the default state is used.\n */\n save(session: State | null): void {\n window.localStorage.setItem(\n this.storageKey,\n JSON.stringify(session ? session : this.defaultState),\n );\n }\n}\n","// Callback type for handling window activity changes.\ntype Callback = () => void;\n\n/**\n * Manages window focus and blur events.\n *\n * @class\n * @category SDK\n * @subcategory Internal\n * @param {Callback} onActivityCallback - Callback to invoke when the window gains focus.\n * @param {Callback} onInactivityCallback - Callback to invoke when the window loses focus.\n */\nexport class WindowActivityManager {\n private readonly onActivityCallback: Callback; // Callback for when the window or tab gains focus.\n private readonly onInactivityCallback: Callback; // Callback for when the window or tab loses focus.\n\n // eslint-disable-next-line require-jsdoc\n constructor(onActivityCallback: Callback, onInactivityCallback: Callback) {\n this.onActivityCallback = onActivityCallback;\n this.onInactivityCallback = onInactivityCallback;\n\n // Attach event listeners for focus and blur\n window.addEventListener(\"focus\", this.handleFocus);\n window.addEventListener(\"blur\", this.handleBlur);\n document.addEventListener(\"visibilitychange\", this.handleVisibilityChange);\n }\n\n /**\n * Handles the focus event and invokes the activity callback.\n * @private\n */\n private handleFocus = (): void => {\n this.onActivityCallback();\n };\n\n /**\n * Handles the blur event and invokes the inactivity callback.\n * @private\n */\n private handleBlur = (): void => {\n this.onInactivityCallback();\n };\n\n /**\n * Handles the visibility change event and invokes appropriate callbacks.\n * @private\n */\n private handleVisibilityChange = (): void => {\n if (document.visibilityState === \"visible\") {\n this.onActivityCallback();\n } else {\n this.onInactivityCallback();\n }\n };\n\n /**\n * Checks if the current window has focus.\n * @returns {boolean} True if the window has focus; otherwise, false.\n */\n hasFocus = (): boolean => {\n return document.hasFocus();\n };\n}\n","import { SessionCheckResponse } from \"../Dto\";\n\n// Type representing data returned by the session check callback.\nexport type SessionCheckResult =\n | (Omit<SessionCheckResponse, \"expiration_time\"> & {\n expiration: number;\n })\n | null;\n\n/**\n * Callback type for performing a session check.\n * @ignore\n */\ntype SessionCheckCallback = () => Promise<SessionCheckResult>;\n\n/**\n * Callback type for handling session timeout events.\n * @ignore\n */\ntype SessionExpiredCallback = () => void;\n\n/**\n * Manages scheduling for periodic and timeout-based session checks.\n *\n * @category SDK\n * @subcategory Internal\n * @param {number} checkInterval - The interval in milliseconds between periodic session checks.\n * @param {SessionCheckCallback} checkSession - The callback function to perform a session check.\n * @param {SessionExpiredCallback} onSessionExpired - The callback function to handle session timeout events.\n */\nexport class Scheduler {\n private intervalID: ReturnType<typeof setInterval> | null = null; // Identifier for the periodic check interval.\n private timeoutID: ReturnType<typeof setTimeout> | null = null; // Identifier for the session expiration timeout.\n private readonly checkInterval: number; // The interval between periodic session checks.\n private readonly checkSession: SessionCheckCallback; // The callback function to perform a session check.\n private readonly onSessionExpired: SessionExpiredCallback; // The callback function to handle session expired events.\n\n // eslint-disable-next-line require-jsdoc\n constructor(\n checkInterval: number,\n checkSession: SessionCheckCallback,\n onSessionExpired: SessionExpiredCallback,\n ) {\n this.checkInterval = checkInterval;\n this.checkSession = checkSession;\n this.onSessionExpired = onSessionExpired;\n }\n\n /**\n * Handles the session expiration when it is about to expire soon.\n * Stops any ongoing checks and schedules a timeout for the expiration.\n *\n * @param {number} timeToExpiration - The time in milliseconds until the session expires.\n */\n scheduleSessionExpiry(timeToExpiration: number): void {\n this.stop();\n this.timeoutID = setTimeout(async () => {\n this.stop();\n this.onSessionExpired();\n }, timeToExpiration);\n }\n\n /**\n * Starts the session check process.\n * Determines when the next check should run based on the last known check time and session expiration.\n * If the session is expiring soon, schedules an expiration event instead of starting periodic checks.\n *\n * @param {number} lastCheck - The timestamp (in milliseconds) of the last session check.\n * @param {number} expiration - The timestamp (in milliseconds) of when the session expires.\n */\n start(lastCheck: number = 0, expiration: number = 0): void {\n const timeToNextCheck = this.calcTimeToNextCheck(lastCheck);\n\n if (this.sessionExpiresSoon(expiration)) {\n this.scheduleSessionExpiry(timeToNextCheck);\n return;\n }\n\n // Schedule the first check after an optional delay\n this.timeoutID = setTimeout(async () => {\n let result = await this.checkSession();\n\n if (result.is_valid) {\n if (this.sessionExpiresSoon(result.expiration)) {\n this.scheduleSessionExpiry(result.expiration - Date.now());\n return;\n }\n\n // Begin periodic checks\n this.intervalID = setInterval(async () => {\n result = await this.checkSession();\n\n if (result.is_valid) {\n if (this.sessionExpiresSoon(result.expiration)) {\n this.scheduleSessionExpiry(result.expiration - Date.now());\n }\n } else {\n this.stop();\n }\n }, this.checkInterval);\n } else {\n this.stop();\n }\n }, timeToNextCheck);\n }\n\n /**\n * Stops the session check process and clears all timers.\n */\n stop(): void {\n if (this.timeoutID) {\n clearTimeout(this.timeoutID);\n this.timeoutID = null;\n }\n\n if (this.intervalID) {\n clearInterval(this.intervalID);\n this.intervalID = null;\n }\n }\n\n /**\n * Checks if the scheduler is currently running.\n * @returns {boolean} True if the scheduler is running; otherwise, false.\n */\n isRunning(): boolean {\n return this.timeoutID !== null || this.intervalID !== null;\n }\n /**\n * Checks if the session is about to expire.\n * @param {number} expiration - Timestamp when the session will expire.\n * @returns {boolean} True if the session is about to expire; otherwise, false.\n */\n sessionExpiresSoon(expiration: number): boolean {\n return expiration > 0 && expiration - Date.now() <= this.checkInterval;\n }\n\n /**\n * Calculates the time until the next session check should occur.\n *\n * @param {number} lastCheck - The timestamp (in milliseconds) of the last session check.\n * @returns {number} The time in milliseconds until the next check should be performed.\n */\n calcTimeToNextCheck(lastCheck: number): number {\n const timeSinceLastCheck = Date.now() - lastCheck;\n return this.checkInterval >= timeSinceLastCheck\n ? this.checkInterval - (timeSinceLastCheck % this.checkInterval)\n : 0;\n }\n}\n","import { Claims } from \"../Dto\";\n\n/**\n * Enum-like type defining the actions that can be broadcasted.\n *\n * @ignore\n * @category SDK\n * @subcategory Internal\n */\ntype Action = \"sessionExpired\" | \"sessionCreated\" | \"requestLeadership\";\n\n/**\n * Interface representing the data structure of a channel event.\n *\n * @interface\n * @property {Action} action - The type of action being broadcasted.\n * @property {Claims=} claims - Optional claims associated with the event.\n * @property {boolean=} is_valid - Optional indication of the session validity.\n * @category SDK\n * @subcategory Internal\n */\nexport interface BroadcastMessage {\n action: Action;\n claims?: Claims;\n is_valid?: boolean;\n}\n\n/**\n * Callback type for handling broadcast messages.\n *\n * @ignore\n */\n// eslint-disable-next-line no-unused-vars\ntype Callback = (msg: BroadcastMessage) => void;\n\n/**\n * Manages inter-tab communication using the BroadcastChannel API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {string} channelName - The name of the broadcast channel.\n * @param {Callback} onSessionExpired - Callback invoked when the session has expired.\n * @param {Callback} onSessionCreated - Callback invoked when a session is created.\n * @param {Callback} onLeadershipRequested - Callback invoked when a leadership request is received.\n */\nexport class SessionChannel {\n channel: BroadcastChannel; // The broadcast channel used for communication.\n onSessionExpired: Callback; // Callback invoked when the session has expired.\n onSessionCreated: Callback; // Callback invoked when a session is created.\n onLeadershipRequested: Callback; // Callback invoked when a leadership request is received.\n\n // eslint-disable-next-line require-jsdoc\n constructor(\n channelName: string = \"hanko_session\",\n onSessionExpired: Callback,\n onSessionCreated: Callback,\n onLeadershipRequested: Callback,\n ) {\n this.onSessionExpired = onSessionExpired;\n this.onSessionCreated = onSessionCreated;\n this.onLeadershipRequested = onLeadershipRequested;\n\n this.channel = new BroadcastChannel(channelName);\n this.channel.onmessage = this.handleMessage;\n }\n\n /**\n * Sends a message via the broadcast channel to inform other tabs of session changes.\n *\n * @param {BroadcastMessage} msg - The messsage to broadcast.\n */\n post(msg: BroadcastMessage) {\n this.channel.postMessage(msg);\n }\n\n /**\n * Handles incoming messages from the broadcast channel.\n *\n * @param {MessageEvent} event - The message event containing the broadcast data.\n * @private\n */\n private handleMessage = (event: MessageEvent) => {\n const data = event.data as BroadcastMessage;\n switch (data.action) {\n case \"sessionExpired\":\n this.onSessionExpired(data);\n break;\n case \"sessionCreated\":\n this.onSessionCreated(data);\n break;\n case \"requestLeadership\":\n this.onLeadershipRequested(data);\n break;\n }\n };\n}\n","import { Listener } from \"./Listener\";\nimport { Dispatcher } from \"./Dispatcher\";\nimport { SessionClient } from \"../client/SessionClient\";\nimport { SessionState } from \"./SessionState\";\nimport { WindowActivityManager } from \"./WindowActivityManager\";\nimport { Scheduler, SessionCheckResult } from \"./Scheduler\";\nimport { SessionTokenLocation } from \"../client/HttpClient\";\nimport { SessionChannel, BroadcastMessage } from \"./SessionChannel\";\nimport { HankoOptions } from \"../../Hanko\";\n\n/**\n * A class that manages session checks, dispatches events based on session status,\n * and uses broadcast channels for inter-tab communication.\n *\n * @category SDK\n * @subcategory Internal\n * @extends Dispatcher\n * @param {string} api - The API endpoint URL.\n * @param {HankoOptions} options - The internal configuration options of the SDK.\n */\nexport class Relay extends Dispatcher {\n listener = new Listener(); // Listener for session-related events.\n private readonly checkInterval: number = 30000; // Interval for session validity checks in milliseconds.\n private readonly client: SessionClient; // Client for session validation.\n private readonly sessionState: SessionState; // Manages session-related states.\n private readonly windowActivityManager: WindowActivityManager; // Manages window activity states.\n private readonly scheduler: Scheduler; // Schedules session validity checks.\n private readonly sessionChannel: SessionChannel; // Handles inter-tab communication via broadcast channels.\n private isLoggedIn: boolean;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options: HankoOptions) {\n super();\n this.client = new SessionClient(api, options);\n\n if (options.sessionCheckInterval) {\n this.checkInterval =\n options.sessionCheckInterval < 3000\n ? 3000\n : options.sessionCheckInterval;\n }\n\n this.sessionState = new SessionState(`${options.cookieName}_session_state`);\n this.sessionChannel = new SessionChannel(\n this.getSessionCheckChannelName(\n options.sessionTokenLocation,\n options.sessionCheckChannelName,\n ),\n () => this.onChannelSessionExpired(),\n (msg) => this.onChannelSessionCreated(msg),\n () => this.onChannelLeadershipRequested(),\n );\n this.scheduler = new Scheduler(\n this.checkInterval,\n () => this.checkSession(),\n () => this.onSessionExpired(),\n );\n this.windowActivityManager = new WindowActivityManager(\n () => this.startSessionCheck(),\n () => this.scheduler.stop(),\n );\n\n const now = Date.now();\n const { expiration } = this.sessionState.load();\n\n this.isLoggedIn = now < expiration;\n this.initializeEventListeners();\n this.startSessionCheck();\n }\n\n /**\n * Sets up all event listeners and initializes session management.\n * This method is crucial for ensuring the session is monitored across all tabs.\n * @private\n */\n private initializeEventListeners(): void {\n // Listen for session creation events\n this.listener.onSessionCreated((detail) => {\n const { claims } = detail;\n const expiration = Date.parse(claims.expiration);\n const lastCheck = Date.now();\n\n this.isLoggedIn = true;\n this.sessionState.save({ expiration, lastCheck }); // Save initial session state\n this.sessionChannel.post({ action: \"sessionCreated\", claims }); // Inform other tabs\n this.startSessionCheck(); // Begin session checks now that a user is logged in\n });\n\n // Listen for user logout events\n this.listener.onUserLoggedOut(() => {\n this.isLoggedIn = false;\n this.sessionChannel.post({ action: \"sessionExpired\" }); // Inform other tabs session ended\n this.sessionState.save(null);\n this.scheduler.stop();\n });\n\n window.addEventListener(\"beforeunload\", () => this.scheduler.stop());\n }\n\n /**\n * Initiates session checking based on the last check time.\n * This method decides when the next check should occur to balance between performance and freshness.\n * @private\n */\n private startSessionCheck(): void {\n if (this.windowActivityManager.hasFocus()) {\n this.sessionChannel.post({ action: \"requestLeadership\" }); // Inform other tabs this tab is now checking\n } else {\n return;\n }\n\n if (this.scheduler.isRunning()) {\n return;\n }\n\n const { lastCheck, expiration } = this.sessionState.load();\n\n if (this.isLoggedIn) {\n this.scheduler.start(lastCheck, expiration);\n }\n }\n\n /**\n * Validates the current session and updates session information.\n * This method checks if the session is still valid and updates local data accordingly.\n * @returns {Promise<SessionCheckResult>} - A promise that resolves with the session check result.\n * @private\n */\n private async checkSession(): Promise<SessionCheckResult> {\n const lastCheck = Date.now();\n // eslint-disable-next-line camelcase\n const { is_valid, claims, expiration_time } = await this.client.validate();\n\n // eslint-disable-next-line camelcase\n const expiration = expiration_time ? Date.parse(expiration_time) : 0;\n\n // eslint-disable-next-line camelcase\n if (!is_valid && this.isLoggedIn) {\n this.dispatchSessionExpiredEvent();\n }\n\n // eslint-disable-next-line camelcase\n if (is_valid) {\n this.isLoggedIn = true;\n this.sessionState.save({ lastCheck, expiration });\n } else {\n this.isLoggedIn = false;\n this.sessionState.save(null);\n this.sessionChannel.post({ action: \"sessionExpired\" }); // Inform other tabs\n }\n\n return {\n // eslint-disable-next-line camelcase\n is_valid,\n claims,\n expiration,\n };\n }\n\n /**\n * Resets session-related states when a session expires.\n * Ensures that authentication state is cleared and an expiration event is dispatched.\n * Assumes the user is logged out by default if the session state is unknown.\n * @private\n */\n private onSessionExpired() {\n if (this.isLoggedIn) {\n this.isLoggedIn = false;\n this.sessionState.save(null);\n this.sessionChannel.post({ action: \"sessionExpired\" }); // Inform other tabs\n this.dispatchSessionExpiredEvent();\n }\n }\n\n /**\n * Handles session expired events from broadcast messages.\n * @private\n */\n private onChannelSessionExpired() {\n if (this.isLoggedIn) {\n this.isLoggedIn = false;\n this.dispatchSessionExpiredEvent();\n }\n }\n\n /**\n * Handles session creation events from broadcast messages.\n * @param {BroadcastMessage} msg - The broadcast message containing session details.\n * @private\n */\n private onChannelSessionCreated(msg: BroadcastMessage) {\n const { claims } = msg;\n const now = Date.now();\n const expiration = Date.parse(claims.expiration);\n const expirationSeconds = expiration - now;\n\n this.isLoggedIn = true;\n this.dispatchSessionCreatedEvent({\n claims,\n expirationSeconds, // deprecated\n });\n }\n\n /**\n * Handles leadership requests from other tabs.\n * @private\n */\n private onChannelLeadershipRequested() {\n if (!this.windowActivityManager.hasFocus()) {\n this.scheduler.stop();\n }\n }\n\n /**\n * Retrieves or generates the session check channel name based on the session token storage location.\n *\n * - If the `sessionTokenLocation` is `\"cookie\"`, the provided `sessionCheckChannelName` is returned as-is.\n * - If the `sessionTokenLocation` is `\"sessionStorage\"`, the function attempts to retrieve the channel name from\n * `sessionStorage`. If none is found, a new name is generated with the value of `sessionCheckChannelName` as a prefix and a random number,\n * then stored in `sessionStorage` for future use.\n *\n * @param sessionTokenLocation - Indicates where the session token is stored, either `\"cookie\"` or `\"sessionStorage\"`.\n * @param sessionCheckChannelName - The name or prefix used for the session check channel.\n * @returns The resolved session check channel name, or `undefined` if not applicable.\n * @private\n */\n private getSessionCheckChannelName(\n sessionTokenLocation: SessionTokenLocation,\n sessionCheckChannelName?: string,\n ): string | undefined {\n if (sessionTokenLocation == \"cookie\") {\n return sessionCheckChannelName;\n }\n let channelName = sessionStorage.getItem(\"sessionCheckChannelName\");\n if (\n channelName === null ||\n channelName === undefined ||\n channelName === \"\"\n ) {\n channelName = `${sessionCheckChannelName}-${\n Math.floor(Math.random() * 100) + 1\n }`;\n sessionStorage.setItem(\"sessionCheckChannelName\", channelName);\n }\n return channelName;\n }\n}\n","/**\n * A class to check the browser's WebAuthn support.\n *\n * @hideconstructor\n * @category SDK\n * @subcategory Utilities\n */\nclass WebauthnSupport {\n /**\n * Does a simple check to test for the credential management API functions we need, and an indication of\n * public key credential authentication support.\n *\n * @see https://developers.google.com/web/updates/2018/03/webauthn-credential-management\n * @return boolean\n */\n static supported(): boolean {\n return !!(\n navigator.credentials &&\n navigator.credentials.create &&\n navigator.credentials.get &&\n window.PublicKeyCredential\n );\n }\n\n /**\n * Checks whether a user-verifying platform authenticator is available.\n *\n * @return Promise<boolean>\n */\n static async isPlatformAuthenticatorAvailable(): Promise<boolean> {\n if (\n this.supported() &&\n window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n ) {\n return window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n }\n\n return false;\n }\n\n /**\n * Checks whether external CTAP2 security keys are supported.\n *\n * @return Promise<boolean>\n */\n static async isSecurityKeySupported(): Promise<boolean> {\n if (\n window.PublicKeyCredential !== undefined &&\n // @ts-ignore\n window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported\n ) {\n // @ts-ignore\n return window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported();\n }\n\n return this.supported();\n }\n\n /**\n * Checks whether autofill assisted requests are supported.\n *\n * @return Promise<boolean>\n */\n static async isConditionalMediationAvailable(): Promise<boolean> {\n if (\n // @ts-ignore\n window.PublicKeyCredential &&\n // @ts-ignore\n window.PublicKeyCredential.isConditionalMediationAvailable\n ) {\n // @ts-ignore\n return window.PublicKeyCredential.isConditionalMediationAvailable();\n }\n\n return false;\n }\n}\n\nexport { WebauthnSupport };\n","// src/webauthn-json/base64url.ts\nfunction base64urlToBuffer(baseurl64String) {\n const padding = \"==\".slice(0, (4 - baseurl64String.length % 4) % 4);\n const base64String = baseurl64String.replace(/-/g, \"+\").replace(/_/g, \"/\") + padding;\n const str = atob(base64String);\n const buffer = new ArrayBuffer(str.length);\n const byteView = new Uint8Array(buffer);\n for (let i = 0; i < str.length; i++) {\n byteView[i] = str.charCodeAt(i);\n }\n return buffer;\n}\nfunction bufferToBase64url(buffer) {\n const byteView = new Uint8Array(buffer);\n let str = \"\";\n for (const charCode of byteView) {\n str += String.fromCharCode(charCode);\n }\n const base64String = btoa(str);\n const base64urlString = base64String.replace(/\\+/g, \"-\").replace(\n /\\//g,\n \"_\"\n ).replace(/=/g, \"\");\n return base64urlString;\n}\n\n// src/webauthn-json/convert.ts\nvar copyValue = \"copy\";\nvar convertValue = \"convert\";\nfunction convert(conversionFn, schema2, input) {\n if (schema2 === copyValue) {\n return input;\n }\n if (schema2 === convertValue) {\n return conversionFn(input);\n }\n if (schema2 instanceof Array) {\n return input.map((v) => convert(conversionFn, schema2[0], v));\n }\n if (schema2 instanceof Object) {\n const output = {};\n for (const [key, schemaField] of Object.entries(schema2)) {\n if (schemaField.derive) {\n const v = schemaField.derive(input);\n if (v !== void 0) {\n input[key] = v;\n }\n }\n if (!(key in input)) {\n if (schemaField.required) {\n throw new Error(`Missing key: ${key}`);\n }\n continue;\n }\n if (input[key] == null) {\n output[key] = null;\n continue;\n }\n output[key] = convert(\n conversionFn,\n schemaField.schema,\n input[key]\n );\n }\n return output;\n }\n}\nfunction derived(schema2, derive) {\n return {\n required: true,\n schema: schema2,\n derive\n };\n}\nfunction required(schema2) {\n return {\n required: true,\n schema: schema2\n };\n}\nfunction optional(schema2) {\n return {\n required: false,\n schema: schema2\n };\n}\n\n// src/webauthn-json/basic/schema.ts\nvar publicKeyCredentialDescriptorSchema = {\n type: required(copyValue),\n id: required(convertValue),\n transports: optional(copyValue)\n};\nvar simplifiedExtensionsSchema = {\n appid: optional(copyValue),\n appidExclude: optional(copyValue),\n credProps: optional(copyValue)\n};\nvar simplifiedClientExtensionResultsSchema = {\n appid: optional(copyValue),\n appidExclude: optional(copyValue),\n credProps: optional(copyValue)\n};\nvar credentialCreationOptions = {\n publicKey: required({\n rp: required(copyValue),\n user: required({\n id: required(convertValue),\n name: required(copyValue),\n displayName: required(copyValue)\n }),\n challenge: required(convertValue),\n pubKeyCredParams: required(copyValue),\n timeout: optional(copyValue),\n excludeCredentials: optional([publicKeyCredentialDescriptorSchema]),\n authenticatorSelection: optional(copyValue),\n attestation: optional(copyValue),\n extensions: optional(simplifiedExtensionsSchema)\n }),\n signal: optional(copyValue)\n};\nvar publicKeyCredentialWithAttestation = {\n type: required(copyValue),\n id: required(copyValue),\n rawId: required(convertValue),\n authenticatorAttachment: optional(copyValue),\n response: required({\n clientDataJSON: required(convertValue),\n attestationObject: required(convertValue),\n transports: derived(\n copyValue,\n (response) => {\n var _a;\n return ((_a = response.getTransports) == null ? void 0 : _a.call(response)) || [];\n }\n )\n }),\n clientExtensionResults: derived(\n simplifiedClientExtensionResultsSchema,\n (pkc) => pkc.getClientExtensionResults()\n )\n};\nvar credentialRequestOptions = {\n mediation: optional(copyValue),\n publicKey: required({\n challenge: required(convertValue),\n timeout: optional(copyValue),\n rpId: optional(copyValue),\n allowCredentials: optional([publicKeyCredentialDescriptorSchema]),\n userVerification: optional(copyValue),\n extensions: optional(simplifiedExtensionsSchema)\n }),\n signal: optional(copyValue)\n};\nvar publicKeyCredentialWithAssertion = {\n type: required(copyValue),\n id: required(copyValue),\n rawId: required(convertValue),\n authenticatorAttachment: optional(copyValue),\n response: required({\n clientDataJSON: required(convertValue),\n authenticatorData: required(convertValue),\n signature: required(convertValue),\n userHandle: required(convertValue)\n }),\n clientExtensionResults: derived(\n simplifiedClientExtensionResultsSchema,\n (pkc) => pkc.getClientExtensionResults()\n )\n};\nvar schema = {\n credentialCreationOptions,\n publicKeyCredentialWithAttestation,\n credentialRequestOptions,\n publicKeyCredentialWithAssertion\n};\n\n// src/webauthn-json/basic/api.ts\nfunction createRequestFromJSON(requestJSON) {\n return convert(base64urlToBuffer, credentialCreationOptions, requestJSON);\n}\nfunction createResponseToJSON(credential) {\n return convert(\n bufferToBase64url,\n publicKeyCredentialWithAttestation,\n credential\n );\n}\nasync function create(requestJSON) {\n const credential = await navigator.credentials.create(\n createRequestFromJSON(requestJSON)\n );\n return createResponseToJSON(credential);\n}\nfunction getRequestFromJSON(requestJSON) {\n return convert(base64urlToBuffer, credentialRequestOptions, requestJSON);\n}\nfunction getResponseToJSON(credential) {\n return convert(\n bufferToBase64url,\n publicKeyCredentialWithAssertion,\n credential\n );\n}\nasync function get(requestJSON) {\n const credential = await navigator.credentials.get(\n getRequestFromJSON(requestJSON)\n );\n return getResponseToJSON(credential);\n}\n\n// src/webauthn-json/basic/supported.ts\nfunction supported() {\n return !!(navigator.credentials && navigator.credentials.create && navigator.credentials.get && window.PublicKeyCredential);\n}\nexport {\n create,\n get,\n schema,\n supported\n};\n//# sourceMappingURL=webauthn-json.js.map\n","import {\n CredentialRequestOptionsJSON,\n CredentialCreationOptionsJSON,\n PublicKeyCredentialWithAssertionJSON,\n PublicKeyCredentialWithAttestationJSON,\n create,\n get,\n} from \"@github/webauthn-json\";\n\n/**\n * Manages WebAuthn credential operations as a singleton, ensuring only one active request at a time.\n * Uses an internal AbortController to cancel previous requests when a new one is initiated.\n */\nclass WebauthnManager {\n private static instance: WebauthnManager | null = null;\n private abortController = new AbortController();\n // eslint-disable-next-line no-useless-constructor,require-jsdoc\n private constructor() {}\n\n /**\n * Gets the singleton instance of WebauthnManager.\n * Creates a new instance if one doesn't exist, otherwise returns the existing one.\n * @returns {WebauthnManager} The singleton instance\n */\n public static getInstance(): WebauthnManager {\n if (!WebauthnManager.instance) {\n WebauthnManager.instance = new WebauthnManager();\n }\n return WebauthnManager.instance;\n }\n\n /**\n * Creates a new abort signal, aborting any ongoing WebAuthn request.\n * @private\n * @returns {AbortSignal} The new abort signal\n */\n private createAbortSignal(): AbortSignal {\n this.abortController.abort(); // Cancel any ongoing request\n this.abortController = new AbortController();\n return this.abortController.signal;\n }\n\n /**\n * Retrieves a WebAuthn credential using the provided options.\n * Aborts any previous request before starting a new one.\n * @param {CredentialRequestOptionsJSON} options - The options for credential retrieval\n * @returns {Promise<PublicKeyCredentialWithAssertionJSON>} A promise resolving to the retrieved credential\n * @throws {DOMException} If the WebAuthn request fails (e.g., aborted, not allowed)\n */\n public async getWebauthnCredential(\n options: CredentialRequestOptionsJSON,\n ): Promise<PublicKeyCredentialWithAssertionJSON> {\n return await get({\n ...options,\n signal: this.createAbortSignal(),\n });\n }\n\n /**\n * Retrieves a WebAuthn credential with conditional UI mediation.\n * Aborts any previous request before starting a new one.\n * @param {CredentialRequestOptionsJSON} publicKey - The public key options for conditional retrieval\n * @returns {Promise<PublicKeyCredentialWithAssertionJSON>} A promise resolving to the retrieved credential\n * @throws {DOMException} If the WebAuthn request fails (e.g., aborted, not allowed)\n */\n public async getConditionalWebauthnCredential(\n publicKey: CredentialRequestOptionsJSON[\"publicKey\"],\n ): Promise<PublicKeyCredentialWithAssertionJSON> {\n return await get({\n publicKey,\n mediation: \"conditional\" as CredentialMediationRequirement,\n signal: this.createAbortSignal(),\n });\n }\n\n /**\n * Creates a new WebAuthn credential using the provided options.\n * Aborts any previous request before starting a new one.\n * @param {CredentialCreationOptionsJSON} options - The options for credential creation\n * @returns {Promise<PublicKeyCredentialWithAttestationJSON>} A promise resolving to the created credential\n * @throws {DOMException} If the WebAuthn request fails (e.g., aborted, not allowed)\n */\n public async createWebauthnCredential(\n options: CredentialCreationOptionsJSON,\n ): Promise<PublicKeyCredentialWithAttestationJSON> {\n return await create({\n ...options,\n signal: this.createAbortSignal(),\n });\n }\n}\n\nexport default WebauthnManager;\n","import { AutoSteps } from \"./types/flow\";\nimport { WebauthnSupport } from \"../WebauthnSupport\";\nimport WebauthnManager from \"./WebauthnManager\";\nimport { CredentialCreationOptionsJSON } from \"@github/webauthn-json\";\n\n// Helper function to handle WebAuthn credential creation and error handling\n// eslint-disable-next-line require-jsdoc\nasync function handleCredentialCreation(\n state: any,\n manager: WebauthnManager,\n options: CredentialCreationOptionsJSON,\n errorCode: string = \"webauthn_credential_already_exists\",\n errorMessage: string = \"Webauthn credential already exists\",\n) {\n try {\n const attestationResponse = await manager.createWebauthnCredential(options);\n return await state.actions.webauthn_verify_attestation_response.run({\n public_key: attestationResponse,\n });\n } catch {\n const nextState = await state.actions.back.run();\n nextState.error = { code: errorCode, message: errorMessage };\n return nextState;\n }\n}\n\nexport const autoSteps: AutoSteps = {\n preflight: async (state) => {\n return await state.actions.register_client_capabilities.run({\n webauthn_available: WebauthnSupport.supported(),\n webauthn_conditional_mediation_available:\n await WebauthnSupport.isConditionalMediationAvailable(),\n webauthn_platform_authenticator_available:\n await WebauthnSupport.isPlatformAuthenticatorAvailable(),\n });\n },\n\n login_passkey: async (state) => {\n const manager = WebauthnManager.getInstance();\n try {\n const assertionResponse = await manager.getWebauthnCredential(\n state.payload.request_options,\n );\n return await state.actions.webauthn_verify_assertion_response.run({\n assertion_response: assertionResponse,\n });\n } catch {\n const nextState = await state.actions.back.run();\n if (state.error) {\n nextState.error = state.error;\n }\n return nextState;\n }\n },\n\n onboarding_verify_passkey_attestation: async (state) => {\n const manager = WebauthnManager.getInstance();\n return handleCredentialCreation(\n state,\n manager,\n state.payload.creation_options,\n );\n },\n\n webauthn_credential_verification: async (state) => {\n const manager = WebauthnManager.getInstance();\n return handleCredentialCreation(\n state,\n manager,\n state.payload.creation_options,\n );\n },\n\n async thirdparty(state) {\n const searchParams = new URLSearchParams(window.location.search);\n const token = searchParams.get(\"hanko_token\");\n const error = searchParams.get(\"error\");\n\n const updateUrl = (paramsToDelete: string[]) => {\n paramsToDelete.forEach((param) => searchParams.delete(param));\n const newSearch = searchParams.toString()\n ? `?${searchParams.toString()}`\n : \"\";\n history.replaceState(\n null,\n null,\n `${window.location.pathname}${newSearch}`,\n );\n };\n\n if (token?.length > 0) {\n updateUrl([\"hanko_token\"]);\n return await state.actions.exchange_token.run({ token });\n }\n\n if (error?.length > 0) {\n const errorCode =\n error === \"access_denied\"\n ? \"third_party_access_denied\"\n : \"technical_error\";\n const message = searchParams.get(\"error_description\");\n\n updateUrl([\"error\", \"error_description\"]);\n\n const nextState = await state.actions.back.run(null, {\n dispatchAfterStateChangeEvent: false,\n });\n\n nextState.error = { code: errorCode, message };\n nextState.dispatchAfterStateChangeEvent();\n\n return nextState;\n }\n\n if (!state.isCached) {\n state.saveToLocalStorage();\n window.location.assign(state.payload.redirect_url);\n } else {\n return await state.actions.back.run();\n }\n\n return state;\n },\n\n success: async (state) => {\n const { claims } = state.payload;\n const expirationSeconds = Date.parse(claims.expiration) - Date.now();\n state.removeFromLocalStorage();\n state.hanko.relay.dispatchSessionCreatedEvent({\n claims,\n expirationSeconds,\n });\n return state;\n },\n\n account_deleted: async (state) => {\n state.removeFromLocalStorage();\n state.hanko.relay.dispatchUserDeletedEvent();\n return state;\n },\n};\n","import { PasskeyAutofillActivationHandlers } from \"./types/flow\";\nimport WebauthnManager from \"./WebauthnManager\";\n\nexport const passkeyAutofillActivationHandlers: PasskeyAutofillActivationHandlers =\n {\n login_init: async (state) => {\n return void (async function () {\n const manager = WebauthnManager.getInstance();\n\n if (state.payload.request_options) {\n try {\n const { publicKey } = state.payload.request_options;\n\n const assertionResponse =\n await manager.getConditionalWebauthnCredential(publicKey);\n\n return await state.actions.webauthn_verify_assertion_response.run({\n assertion_response: assertionResponse,\n });\n } catch {\n // We do not need to handle the error, because this is a conditional request, which can fail silently\n return;\n }\n }\n })();\n },\n };\n","import { Hanko } from \"../../Hanko\";\nimport { Actions, Payloads, StateName } from \"./types/state\";\nimport { Input } from \"./types/input\";\nimport { FlowError } from \"./types/flowError\";\nimport { Action as ActionType } from \"./types/action\";\nimport { AnyState, FlowName, FlowResponse } from \"./types/flow\";\nimport { autoSteps } from \"./auto-steps\";\nimport { passkeyAutofillActivationHandlers } from \"./passkey-autofill-activation\";\n\nexport type AutoSteppedStates = keyof typeof autoSteps;\n\nexport type PasskeyAutofillStates =\n keyof typeof passkeyAutofillActivationHandlers;\n\nexport type AutoStepExclusion = AutoSteppedStates[] | \"all\";\n\nexport type ActionMap<TState extends StateName> = {\n [K in keyof Actions[TState]]: Action<\n Actions[TState][K] extends ActionType<infer TInputs> ? TInputs : never\n >;\n};\n\nexport type ActionInfo = {\n name: string;\n relatedStateName: StateName;\n};\n\nexport interface StateInitConfig {\n dispatchAfterStateChangeEvent?: boolean;\n excludeAutoSteps?: AutoStepExclusion;\n previousAction?: ActionInfo;\n isCached?: boolean;\n cacheKey?: string;\n}\n\nexport type StateCreateConfig = Pick<\n StateInitConfig,\n \"dispatchAfterStateChangeEvent\" | \"excludeAutoSteps\" | \"cacheKey\"\n> & {\n loadFromCache?: boolean;\n};\n\nexport type ActionRunConfig = Pick<\n StateInitConfig,\n \"dispatchAfterStateChangeEvent\"\n>;\n\ntype SerializedState = FlowResponse<any> & {\n flow_name: FlowName;\n previous_action?: ActionInfo;\n is_cached?: boolean;\n};\n\ntype ExtractInputValues<TInputs> = {\n [K in keyof TInputs]: TInputs[K] extends Input<infer TValue> ? TValue : never;\n};\n\n/**\n * Represents a state in a flow with associated actions and properties.\n * @template TState - The specific state name type.\n * @constructor\n * @param {Hanko} hanko - The Hanko instance for API interactions.\n * @param {FlowName} flowName - The name of the flow this state belongs to.\n * @param {FlowResponse<TState>} response - The flow response containing state data.\n * @param {StateInitConfig} [options={}] - Configuration options for state initialization.\n * @category SDK\n * @subcategory FlowAPI\n */\nexport class State<TState extends StateName = StateName> {\n public readonly name: TState;\n public readonly flowName: FlowName;\n public error?: FlowError;\n public readonly payload?: Payloads[TState];\n public readonly actions: ActionMap<TState>;\n public readonly csrfToken: string;\n public readonly status: number;\n public readonly previousAction?: ActionInfo;\n public readonly isCached: boolean;\n public readonly cacheKey: string;\n public readonly hanko: Hanko;\n public invokedAction?: ActionInfo;\n public readonly excludeAutoSteps: AutoStepExclusion;\n\n public readonly autoStep?: TState extends AutoSteppedStates\n ? () => Promise<AnyState>\n : never;\n public readonly passkeyAutofillActivation: TState extends PasskeyAutofillStates\n ? () => Promise<void>\n : never;\n\n /**\n * Constructs a new State instance.\n * @param {Hanko} hanko - The Hanko instance for API interactions.\n * @param {FlowName} flowName - The name of the flow this state belongs to.\n * @param {FlowResponse<TState>} response - The flow response containing state data.\n * @param {StateInitConfig} [options={}] - Configuration options for state initialization.\n */\n constructor(\n hanko: Hanko,\n flowName: FlowName,\n response: FlowResponse<TState>,\n options: StateInitConfig = {},\n ) {\n this.flowName = flowName;\n this.name = response.name;\n this.error = response.error;\n this.payload = response.payload;\n this.csrfToken = response.csrf_token;\n this.status = response.status;\n this.hanko = hanko;\n this.actions = this.buildActionMap(response.actions);\n\n if (this.name in autoSteps) {\n const handler = autoSteps[this.name as AutoSteppedStates];\n (this.autoStep as () => Promise<AnyState>) = () => handler(this as any);\n }\n\n if (this.name in passkeyAutofillActivationHandlers) {\n const handler =\n passkeyAutofillActivationHandlers[this.name as PasskeyAutofillStates];\n (this.passkeyAutofillActivation as () => Promise<void>) = () =>\n handler(this as any);\n }\n\n const {\n dispatchAfterStateChangeEvent = true,\n excludeAutoSteps = null,\n previousAction = null,\n isCached = false,\n cacheKey = \"hanko-flow-state\",\n } = options;\n\n this.excludeAutoSteps = excludeAutoSteps;\n this.previousAction = previousAction;\n this.isCached = isCached;\n this.cacheKey = cacheKey;\n\n if (dispatchAfterStateChangeEvent) {\n this.dispatchAfterStateChangeEvent();\n }\n }\n\n /**\n * Builds the action map for this state, wrapping it in a Proxy to handle undefined actions.\n * @param {Actions} actions - The actions available in this state.\n * @returns {ActionMap<TState>} The action map for the state.\n * @private\n */\n private buildActionMap(actions: Actions[TState]): ActionMap<TState> {\n const actionMap: Partial<ActionMap<TState>> = {};\n\n Object.keys(actions).forEach((actionName) => {\n const key = actionName as keyof Actions[TState];\n const action = actions[key] as ActionType<any>;\n\n actionMap[key] = new Action(action, this);\n });\n\n // Return a Proxy that handles missing keys\n return new Proxy(actionMap as ActionMap<TState>, {\n get: (target: ActionMap<TState>, prop: string | symbol): Action<any> => {\n if (prop in target) {\n return target[prop as keyof ActionMap<TState>];\n }\n\n const actionName = typeof prop === \"string\" ? prop : prop.toString();\n\n return Action.createDisabled(actionName, this);\n },\n });\n }\n\n /**\n * Dispatches an event after the state has changed.\n */\n public dispatchAfterStateChangeEvent() {\n this.hanko.relay.dispatchAfterStateChangeEvent({\n state: this as AnyState,\n });\n }\n\n /**\n * Serializes the current state into a storable format.\n * @returns {SerializedState} The serialized state object.\n */\n public serialize(): SerializedState {\n return {\n flow_name: this.flowName,\n name: this.name,\n error: this.error,\n payload: this.payload,\n csrf_token: this.csrfToken,\n status: this.status,\n previous_action: this.previousAction,\n actions: Object.fromEntries(\n (Object.entries(this.actions) as [string, Action<any>][]).map(\n ([name, action]) => [\n name,\n {\n action: action.name,\n href: action.href,\n inputs: action.inputs,\n description: null,\n },\n ],\n ),\n ),\n };\n }\n\n /**\n * Saves the current state to localStorage.\n * @returns {void}\n */\n public saveToLocalStorage(): void {\n localStorage.setItem(\n this.cacheKey,\n JSON.stringify({ ...this.serialize(), is_cached: true }),\n );\n }\n\n /**\n * Removes the current state from localStorage.\n * @returns {void}\n */\n public removeFromLocalStorage(): void {\n localStorage.removeItem(this.cacheKey);\n }\n\n /**\n * Initializes a flow state, processing auto-steps if applicable.\n * @param {Hanko} hanko - The Hanko instance for API interactions.\n * @param {FlowName} flowName - The name of the flow.\n * @param {FlowResponse<any>} response - The initial flow response.\n * @param {StateInitConfig} [options={}] - Configuration options.\n * @param {boolean} [options.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after state change.\n * @param {AutoStepExclusion} [options.excludeAutoSteps=null] - States to exclude from auto-step processing, or \"all\".\n * @param {ActionInfo} [options.previousAction=null] - Information about the previous action.\n * @param {boolean} [options.isCached=false] - Whether the state is loaded from cache.\n * @param {string} [options.cacheKey=\"hanko-flow-state\"] - Key for localStorage caching.\n * @returns {Promise<AnyState>} A promise resolving to the initialized state.\n */\n public static async initializeFlowState(\n hanko: Hanko,\n flowName: FlowName,\n response: FlowResponse<any>,\n options: StateInitConfig = {},\n ): Promise<AnyState> {\n let state = new State(hanko, flowName, response, options);\n\n if (state.excludeAutoSteps != \"all\") {\n while (\n state &&\n state.autoStep &&\n !state.excludeAutoSteps?.includes(state.name)\n ) {\n const nextState = await state.autoStep();\n if (nextState.name != state.name) {\n state = nextState;\n } else {\n return nextState;\n }\n }\n }\n\n return state;\n }\n\n /**\n * Retrieves and parses state data from localStorage.\n * @param {string} cacheKey - The key used to store the state in localStorage.\n * @returns {SerializedState | undefined} The parsed serialized state, or undefined if not found or invalid.\n */\n public static readFromLocalStorage(\n cacheKey: string,\n ): SerializedState | undefined {\n const raw = localStorage.getItem(cacheKey);\n if (raw) {\n try {\n return JSON.parse(raw) as SerializedState;\n } catch {\n return undefined;\n }\n }\n }\n\n /**\n * Creates a new state instance, using cached or fetched data.\n * @param {Hanko} hanko - The Hanko instance for API interactions.\n * @param {FlowName} flowName - The name of the flow.\n * @param {StateCreateConfig} [config={}] - Configuration options.\n * @param {boolean} [config.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after state change.\n * @param {AutoStepExclusion} [config.excludeAutoSteps=null] - States to exclude from auto-step processing, or \"all\".\n * @param {string} [config.cacheKey=\"hanko-flow-state\"] - Key for localStorage caching.\n * @param {boolean} [config.loadFromCache=true] - Whether to attempt loading from cache.\n * @returns {Promise<AnyState>} A promise resolving to the created state.\n */\n public static async create(\n hanko: Hanko,\n flowName: FlowName,\n config: StateCreateConfig = {},\n ): Promise<AnyState> {\n const { cacheKey = \"hanko-flow-state\", loadFromCache = true } = config;\n if (loadFromCache) {\n const cachedState = State.readFromLocalStorage(cacheKey);\n if (cachedState) {\n return State.deserialize(hanko, cachedState, {\n ...config,\n cacheKey,\n });\n }\n }\n\n const newState = await State.fetchState(hanko, `/${flowName}`);\n return State.initializeFlowState(hanko, flowName, newState, {\n ...config,\n cacheKey,\n });\n }\n\n /**\n * Deserializes a state from a serialized state object.\n * @param {Hanko} hanko - The Hanko instance for API interactions.\n * @param {SerializedState} serializedState - The serialized state data.\n * @param {StateCreateConfig} [config={}] - Configuration options.\n * @param {boolean} [config.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after state change.\n * @param {AutoStepExclusion} [config.excludeAutoSteps=null] - States to exclude from auto-step processing, or \"all\".\n * @param {string} [config.cacheKey=\"hanko-flow-state\"] - Key for localStorage caching.\n * @param {boolean} [config.loadFromCache=true] - Whether to attempt loading from cache.\n * @returns {Promise<AnyState>} A promise resolving to the deserialized state.\n */\n public static async deserialize(\n hanko: Hanko,\n serializedState: SerializedState,\n config: StateCreateConfig = {},\n ): Promise<AnyState> {\n return State.initializeFlowState(\n hanko,\n serializedState.flow_name,\n serializedState,\n {\n ...config,\n previousAction: serializedState.previous_action,\n isCached: serializedState.is_cached,\n },\n );\n }\n\n /**\n * Fetches state data from the server.\n * @param {Hanko} hanko - The Hanko instance for API interactions.\n * @param {string} href - The endpoint to fetch from.\n * @param {any} [body] - Optional request body.\n * @returns {Promise<FlowResponse<any>>} A promise resolving to the flow response.\n */\n static async fetchState(\n hanko: Hanko,\n href: string,\n body?: any,\n ): Promise<FlowResponse<any>> {\n try {\n const response = await hanko.client.post(href, body);\n return response.json();\n } catch (error) {\n return State.createErrorResponse(error);\n }\n }\n\n /**\n * Creates an error flow response.\n * @param {FlowError} error - The error to include in the response.\n * @returns {FlowResponse<\"error\">} A flow response with error details.\n * @private\n */\n private static createErrorResponse(error: FlowError): FlowResponse<\"error\"> {\n return {\n actions: null,\n csrf_token: \"\",\n name: \"error\",\n payload: null,\n status: 0,\n error,\n };\n }\n}\n\n/**\n * Represents an actionable operation within a state.\n * @template TInputs - The type of inputs required for the action.\n * @param {ActionType<TInputs>} action - The action type definition.\n * @param {State} parentState - The state this action belongs to.\n * @param {boolean} [enabled=true] - Whether the action is enabled.\n * @category SDK\n * @subcategory FlowAPI\n */\nexport class Action<TInputs> {\n public readonly enabled: boolean;\n public readonly href: string;\n public readonly name: string;\n public readonly inputs: TInputs;\n private readonly parentState: State;\n\n /**\n * Constructs a new Action instance.\n * @param {ActionType<TInputs>} action - The action type definition.\n * @param {State} parentState - The state this action belongs to.\n * @param {boolean} [enabled=true] - Whether the action is enabled.\n */\n constructor(\n action: ActionType<TInputs>,\n parentState: State,\n enabled: boolean = true,\n ) {\n this.enabled = enabled;\n this.href = action.href;\n this.name = action.action;\n this.inputs = action.inputs;\n this.parentState = parentState;\n }\n\n /**\n * Creates a disabled action instance.\n * @template TInputs - The type of inputs (inferred as empty).\n * @param {string} name - The name of the action.\n * @param {State} parentState - The state this action belongs to.\n * @returns {Action<TInputs>} A disabled action instance.\n */\n static createDisabled<TInputs>(\n name: string,\n parentState: State,\n ): Action<TInputs> {\n return new Action(\n {\n action: name,\n href: \"\", // No valid href since it’s disabled\n inputs: {} as TInputs,\n description: \"Disabled action\",\n },\n parentState,\n false,\n );\n }\n\n /**\n * Executes the action, transitioning to a new state.\n * @param {ExtractInputValues<TInputs>} [inputValues=null] - Values for the action's inputs.\n * @param {ActionRunConfig} [config={}] - Configuration options.\n * @param {boolean} [config.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after state change.\n * @returns {Promise<AnyState>} A promise resolving to the next state.\n * @throws {FlowError} If the action is disabled or already invoked.\n */\n async run(\n inputValues: ExtractInputValues<TInputs> = null,\n config: ActionRunConfig = {},\n ): Promise<AnyState> {\n const {\n name,\n hanko,\n flowName,\n csrfToken,\n invokedAction,\n excludeAutoSteps,\n cacheKey,\n } = this.parentState;\n const { dispatchAfterStateChangeEvent = true } = config;\n\n if (!this.enabled) {\n throw new Error(\n `Action '${this.name}' is not enabled in state '${name}'`,\n );\n }\n\n if (invokedAction) {\n throw new Error(\n `An action '${invokedAction.name}' has already been invoked on state '${invokedAction.relatedStateName}'. No further actions can be run.`,\n );\n }\n\n this.parentState.invokedAction = {\n name: this.name,\n relatedStateName: name,\n };\n\n hanko.relay.dispatchBeforeStateChangeEvent({\n state: this.parentState as AnyState,\n });\n\n // Extract default values from this.inputs\n const defaultValues = Object.keys(this.inputs).reduce(\n (acc, key) => {\n const input = (this.inputs as any)[key] as Input<any>;\n if (input.value !== undefined) {\n acc[key] = input.value;\n }\n return acc;\n },\n {} as Record<string, any>,\n );\n\n // Merge defaults with user-provided inputs\n const mergedInputData = {\n ...defaultValues,\n ...inputValues,\n };\n\n const requestBody = {\n input_data: mergedInputData,\n csrf_token: csrfToken,\n };\n\n const response = await State.fetchState(hanko, this.href, requestBody);\n\n this.parentState.removeFromLocalStorage();\n\n return State.initializeFlowState(hanko, flowName, response, {\n dispatchAfterStateChangeEvent,\n excludeAutoSteps,\n previousAction: invokedAction,\n cacheKey,\n });\n }\n}\n","import { TechnicalError, UnauthorizedError } from \"../Errors\";\nimport { Client } from \"./Client\";\nimport { User } from \"../flow-api/types/payload\";\nimport { Me } from \"../Dto\";\n\n/**\n * A class to manage user information.\n *\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass UserClient extends Client {\n /**\n * Fetches the current user.\n *\n * @return {Promise<User>}\n * @throws {UnauthorizedError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/IsUserAuthorized\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/listUser\n */\n async getCurrent(): Promise<User> {\n const meResponse = await this.client.get(\"/me\");\n\n if (meResponse.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!meResponse.ok) {\n throw new TechnicalError();\n }\n\n const me: Me = meResponse.json();\n const userResponse = await this.client.get(`/users/${me.id}`);\n\n if (userResponse.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!userResponse.ok) {\n throw new TechnicalError();\n }\n\n return userResponse.json();\n }\n\n /**\n * Logs out the current user and expires the existing session cookie. A valid session cookie is required to call the logout endpoint.\n *\n * @return {Promise<void>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n async logout(): Promise<void> {\n const logoutResponse = await this.client.post(\"/logout\");\n\n // For cross-domain operations, the frontend SDK creates the cookie by reading the \"X-Auth-Token\" header, and\n // \"Set-Cookie\" headers sent by the backend have no effect due to the browser's security policy, which means that\n // the cookie must also be removed client-side in that case.\n this.client.sessionTokenStorage.removeSessionToken();\n this.client.cookie.removeAuthCookie();\n this.client.dispatcher.dispatchUserLoggedOutEvent();\n\n if (logoutResponse.status === 401) {\n // The user is logged out already\n return;\n } else if (!logoutResponse.ok) {\n throw new TechnicalError();\n }\n }\n}\n\nexport { UserClient };\n","import { Listener } from \"./lib/events/Listener\";\nimport { Relay } from \"./lib/events/Relay\";\nimport { Cookie, CookieSameSite } from \"./lib/Cookie\";\nimport { SessionClient } from \"./lib/client/SessionClient\";\nimport { HttpClient, SessionTokenLocation } from \"./lib/client/HttpClient\";\nimport { FlowName } from \"./lib/flow-api/types/flow\";\nimport { StateCreateConfig, State } from \"./lib/flow-api/State\";\nimport { UserClient } from \"./lib/client/UserClient\";\nimport { SessionCheckResponse } from \"./lib/Dto\";\nimport { User } from \"./lib/flow-api/types/payload\";\n\n/**\n * The options for the Hanko class\n *\n * @interface\n * @property {number=} timeout - The http request timeout in milliseconds. Defaults to 13000ms\n * @property {string=} cookieName - The name of the session cookie set from the SDK. Defaults to \"hanko\"\n * @property {string=} cookieDomain - The domain where the cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.\n * @property {string=} cookieSameSite - Specify whether/when cookies are sent with cross-site requests. Defaults to \"lax\".\n * @property {string=} localStorageKey - The prefix / name of the local storage keys. Defaults to \"hanko\"\n * @property {string=} lang - Used to convey the preferred language to the API, e.g. for translating outgoing emails.\n * It is transmitted to the API in a custom header (X-Language).\n * Should match one of the supported languages (\"bn\", \"de\", \"en\", \"fr\", \"it, \"pt-BR\", \"zh\")\n * if email delivery by Hanko is enabled. If email delivery by Hanko is disabled and the\n * relying party configures a webhook for the \"email.send\" event, then the set language is\n * reflected in the payload of the token contained in the webhook request.\n * @property {number=} sessionCheckInterval - Interval for session validity checks in milliseconds. Must be greater than 3000 (3s), defaults to 3000 otherwise.\n * @property {string=} sessionCheckChannelName - The broadcast channel name for inter-tab communication.\n * @property {string=} sessionTokenLocation - The location where the session token is stored.\n */\nexport interface HankoOptions {\n timeout?: number;\n cookieName?: string;\n cookieDomain?: string;\n cookieSameSite?: CookieSameSite;\n localStorageKey?: string;\n lang?: string;\n sessionCheckInterval?: number;\n sessionCheckChannelName?: string;\n sessionTokenLocation?: SessionTokenLocation;\n}\n\n/**\n * A class that bundles all available SDK functions.\n *\n * @extends {Listener}\n * @param {string} api - The URL of your Hanko API instance\n * @param {HankoOptions=} options - The options that can be used\n */\nclass Hanko extends Listener {\n private readonly session: SessionClient;\n private readonly user: UserClient;\n private readonly cookie: Cookie;\n public readonly client: HttpClient;\n public readonly relay: Relay;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options?: HankoOptions) {\n super();\n const opts: HankoOptions = {\n timeout: 13000,\n cookieName: \"hanko\",\n localStorageKey: \"hanko\",\n sessionCheckInterval: 30000,\n sessionCheckChannelName: \"hanko-session-check\",\n ...options,\n };\n\n /**\n * @public\n * @type {Client}\n */\n this.client = new HttpClient(api, opts);\n /**\n * @public\n * @type {SessionClient}\n */\n this.session = new SessionClient(api, opts);\n /**\n * @public\n * @type {SessionClient}\n */\n this.user = new UserClient(api, opts);\n /**\n * @public\n * @type {Relay}\n */\n this.relay = new Relay(api, opts);\n /**\n * @public\n * @type {Cookie}\n */\n this.cookie = new Cookie(opts);\n }\n\n /**\n * Sets the preferred language on the underlying sub-clients. The clients'\n * base HttpClient uses this language to transmit an X-Language header to the\n * API which is then used to e.g. translate outgoing emails.\n *\n * @public\n * @param lang {string} - The preferred language to convey to the API.\n */\n setLang(lang: string) {\n this.client.lang = lang;\n }\n\n /**\n * Creates a new flow state for the specified flow.\n *\n * This method initializes a state by either loading from cache (if configured) or fetching from the server.\n * It uses the provided configuration to control caching, event dispatching, and auto-step behavior.\n *\n * @param {FlowName} flowName - The name of the flow to create a state for.\n * @param {StateCreateConfig} [config={}] - Configuration options for state creation.\n * @param {boolean} [config.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after the state changes.\n * @param {AutoStepExclusion} [config.excludeAutoSteps=null] - States to exclude from auto-step processing, or `\"all\"` to skip all auto-steps.\n * @param {string} [config.cacheKey=\"hanko-flow-state\"] - Key used for caching the state in localStorage.\n * @param {boolean} [config.loadFromCache=true] - Whether to attempt loading the state from cache.\n * @returns {Promise<AnyState>} A promise that resolves to the created flow state.\n * @category SDK\n * @subcategory FlowAPI\n */\n createState(flowName: FlowName, config: StateCreateConfig = {}) {\n return State.create(this, flowName, config);\n }\n\n /**\n * Retrieves the current user's profile information.\n *\n * @public\n * @returns {Promise<User>} A promise that resolves to the user object\n * @throws {UnauthorizedError} If the user is not authenticated\n * @throws {TechnicalError} If an unexpected error occurs\n */\n async getUser(): Promise<User> {\n return this.user.getCurrent();\n }\n\n /**\n * Validates the current session.\n *\n * @public\n * @returns {Promise<SessionCheckResponse>} A promise that resolves to the session check response\n */\n async validateSession(): Promise<SessionCheckResponse> {\n return this.session.validate();\n }\n\n /**\n * Retrieves the current session token from the authentication cookie.\n *\n * @public\n * @returns {string} The session token\n */\n getSessionToken(): string {\n return this.cookie.getAuthCookie();\n }\n\n /**\n * Logs out the current user by invalidating the session.\n *\n * @public\n * @returns {Promise<void>} A promise that resolves when the logout is complete\n */\n async logout(): Promise<void> {\n return this.user.logout();\n }\n}\n\nexport { Hanko };\n"],"names":["Throttle","throttle","func","wait","options","context","args","timeoutID","_options$leading","leading","_options$trailing","trailing","previous","Date","now","apply","remaining","this","window","clearTimeout","setTimeout","executeThrottledFunction","sessionCreatedType","sessionExpiredType","userLoggedOutType","flowAfterStateChangeType","CustomEventWithDetail","_CustomEvent","type","detail","call","_inheritsLoose","CustomEvent","Listener","throttleLimit","_addEventListener","document","addEventListener","bind","_removeEventListener","removeEventListener","_throttle","wrapCallback","callback","wrappedCallback","event","_proto","addEventListenerWithType","_ref","_ref$once","once","_ref$throttle","_this","mapAddEventListenerParams","_ref2","params","onSessionCreated","onSessionExpired","onUserLoggedOut","onUserDeleted","userDeletedType","onAfterStateChange","onBeforeStateChange","flowBeforeStateChangeType","Dispatcher","_dispatchEvent","dispatchEvent","dispatch","dispatchSessionCreatedEvent","dispatchSessionExpiredEvent","dispatchUserLoggedOutEvent","dispatchUserDeletedEvent","dispatchAfterStateChangeEvent","dispatchBeforeStateChangeEvent","HankoError","_Error","message","code","cause","Object","setPrototypeOf","prototype","Error","TechnicalError","_HankoError","_this2","_assertThisInitialized","ConflictError","_HankoError2","userID","_this3","RequestTimeoutError","_this4","_HankoError3","_HankoError4","WebauthnRequestCancelledError","_this5","InvalidPasswordError","_HankoError5","_this6","InvalidPasscodeError","_HankoError6","_this7","InvalidWebauthnCredentialError","_HankoError7","_this8","PasscodeExpiredError","_HankoError8","_this9","MaxNumOfPasscodeAttemptsReachedError","_HankoError9","_this10","NotFoundError","_this11","_HankoError10","_HankoError11","TooManyRequestsError","retryAfter","_this12","UnauthorizedError","_HankoError12","_this13","ForbiddenError","_HankoError13","_this14","UserVerificationError","_HankoError14","_this15","MaxNumOfEmailAddressesReachedError","_HankoError15","_this16","EmailAddressAlreadyExistsError","_HankoError16","_this17","ThirdPartyError","_this18","_HankoError17","assign","target","i","arguments","length","source","key","api","init","converter","defaultAttributes","set","name","value","attributes","expires","toUTCString","encodeURIComponent","replace","decodeURIComponent","escape","stringifiedAttributes","attributeName","split","cookie","write","create","get","cookies","jar","parts","slice","join","found","read","e","remove","withAttributes","withConverter","freeze","path","Cookie","_options$cookieName","_options$cookieSameSi","authCookieName","authCookieDomain","authCookieSameSite","cookieName","cookieDomain","cookieSameSite","getAuthCookie","JSCookie","setAuthCookie","token","defaults","secure","sameSite","undefined","domain","o","removeAuthCookie","SessionStorage","keyName","getSessionToken","sessionStorage","getItem","setSessionToken","setItem","removeSessionToken","removeItem","Headers","xhr","_xhr","getResponseHeader","Response","headers","ok","status","statusText","url","_decodedJSON","responseURL","_proto2","json","JSON","parse","response","parseNumericHeader","result","parseInt","isNaN","HttpClient","timeout","dispatcher","sessionTokenStorage","lang","sessionTokenLocation","_options$timeout","_proto3","_fetch","XMLHttpRequest","bearerToken","getAuthToken","Promise","resolve","reject","open","method","setRequestHeader","withCredentials","onload","self","processHeaders","onerror","ontimeout","send","body","toString","jwt","expirationSeconds","getAllResponseHeaders","forEach","h","header","toLowerCase","startsWith","retention","https","RegExp","match","location","href","getTime","setAuthToken","post","stringify","put","patch","Client","client","validate","SessionClient","SessionState","storageKey","defaultState","expiration","lastCheck","load","item","localStorage","save","session","WindowActivityManager","onActivityCallback","onInactivityCallback","handleFocus","handleBlur","handleVisibilityChange","visibilityState","hasFocus","Scheduler","checkInterval","checkSession","intervalID","scheduleSessionExpiry","timeToExpiration","stop","start","timeToNextCheck","calcTimeToNextCheck","sessionExpiresSoon","is_valid","setInterval","_this2$checkSession","clearInterval","isRunning","timeSinceLastCheck","SessionChannel","channelName","onLeadershipRequested","channel","handleMessage","data","action","BroadcastChannel","onmessage","msg","postMessage","_Dispatcher","Relay","listener","sessionState","windowActivityManager","scheduler","sessionChannel","isLoggedIn","sessionCheckInterval","getSessionCheckChannelName","sessionCheckChannelName","onChannelSessionExpired","onChannelSessionCreated","onChannelLeadershipRequested","startSessionCheck","_this$sessionState$lo","initializeEventListeners","claims","_this$sessionState$lo2","then","expiration_time","Math","floor","random","WebauthnSupport","supported","navigator","credentials","PublicKeyCredential","isPlatformAuthenticatorAvailable","isUserVerifyingPlatformAuthenticatorAvailable","isSecurityKeySupported","isExternalCTAP2SecurityKeySupported","isConditionalMediationAvailable","base64urlToBuffer","baseurl64String","padding","base64String","str","atob","buffer","ArrayBuffer","byteView","Uint8Array","charCodeAt","bufferToBase64url","charCode","String","fromCharCode","btoa","copyValue","convertValue","convert","conversionFn","schema2","input","Array","map","v","output","schemaField","entries","derive","schema","required","derived","optional","publicKeyCredentialDescriptorSchema","id","transports","simplifiedExtensionsSchema","appid","appidExclude","credProps","simplifiedClientExtensionResultsSchema","credentialCreationOptions","publicKey","rp","user","displayName","challenge","pubKeyCredParams","excludeCredentials","authenticatorSelection","attestation","extensions","signal","publicKeyCredentialWithAttestation","rawId","authenticatorAttachment","clientDataJSON","attestationObject","_a","getTransports","clientExtensionResults","pkc","getClientExtensionResults","credentialRequestOptions","mediation","rpId","allowCredentials","userVerification","publicKeyCredentialWithAssertion","authenticatorData","signature","userHandle","async","requestJSON","credential","getRequestFromJSON","getResponseToJSON","WebauthnManager","abortController","AbortController","getInstance","instance","createAbortSignal","abort","getWebauthnCredential","getConditionalWebauthnCredential","createWebauthnCredential","createRequestFromJSON","handleCredentialCreation","state","manager","errorCode","errorMessage","_catch","attestationResponse","actions","webauthn_verify_attestation_response","run","public_key","back","nextState","error","autoSteps","preflight","register_client_capabilities","_state$actions$regist2","_WebauthnSupport$isPl","_run","webauthn_available","_WebauthnSupport$supp","webauthn_conditional_mediation_available","_WebauthnSupport$isCo","webauthn_platform_authenticator_available","login_passkey","payload","request_options","assertionResponse","webauthn_verify_assertion_response","assertion_response","onboarding_verify_passkey_attestation","creation_options","webauthn_credential_verification","thirdparty","_temp5","_result","_exit2","_exit","_temp3","_result2","_exit3","_temp","isCached","saveToLocalStorage","redirect_url","_temp2","searchParams","updateUrl","search","paramsToDelete","param","newSearch","history","replaceState","pathname","_temp4","exchange_token","success","removeFromLocalStorage","hanko","relay","account_deleted","passkeyAutofillActivationHandlers","login_init","pact","s","_Pact","_settle","observer","onFulfilled","onRejected","State","flowName","csrfToken","previousAction","cacheKey","invokedAction","excludeAutoSteps","autoStep","passkeyAutofillActivation","csrf_token","buildActionMap","handler","_handler","_options$dispatchAfte","_options$previousActi","_options$isCached","_options$cacheKey","_options$excludeAutoS","actionMap","keys","actionName","Action","Proxy","prop","createDisabled","serialize","flow_name","previous_action","fromEntries","inputs","description","_extends","is_cached","initializeFlowState","test","update","stage","shouldContinue","_isSettledPact","updateValue","_resumeAfterUpdate","_resumeAfterTest","_resumeAfterBody","_for","_state$excludeAutoSte","includes","readFromLocalStorage","raw","_unused","config","_config$cacheKey","_config$loadFromCache","loadFromCache","cachedState","deserialize","fetchState","newState","serializedState","createErrorResponse","parentState","enabled","inputValues","_this3$parentState","_config2$dispatchAfte","relatedStateName","mergedInputData","defaultValues","reduce","acc","input_data","getCurrent","meResponse","me","userResponse","logout","logoutResponse","Hanko","_Listener","opts","localStorageKey","UserClient","setLang","createState","getUser","validateSession"],"mappings":"6lDAyBaA,IAAAA,wCAoEV,SAzDMC,SAAP,SACEC,EACAC,EACAC,YAAAA,IAAAA,EAA2B,CAAE,GAE7B,IACgBC,EACHC,EACQC,EAH8BC,EAAPJ,EAApCK,QAAAA,cAAcD,EAAAE,EAAsBN,EAApBO,SAAAA,cAAeD,EAI3BE,EAAG,IAGkB,WAG/BA,GAAuB,IAAZH,EAAoB,EAAII,KAAKC,MACxCP,EAAY,KAEZL,EAAKa,MAAMV,EAASC,EACtB,EAqCA,OAlCkB,WAChB,IAAMQ,EAAMD,KAAKC,MAIZF,IAAwB,IAAZH,IAAmBG,EAAWE,GAG/C,IAAeE,EAAGb,GAAQW,EAAMF,GAIhCP,EAAUY,KACVX,2BAKIU,GAAa,GAAKA,EAAY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DkBvjB,OAsDlBujB,EAAAA,QAAA,SAAQhX,GACNvN,KAAKmQ,OAAO5C,KAAOA,CACrB,EAkBAiX,EAAAA,YAAA,SAAYjF,EAAoBgD,GAC9B,YAD8BA,IAAAA,IAAAA,EAA4B,CAAE,GACrDjD,GAAMpW,OAAOlJ,KAAMuf,EAAUgD,EACtC,IAUMkC,QAAO,WAAA,IACX,OAAA1W,QAAAC,QAAOhO,KAAKkY,KAAK0L,aAClB,CAAA,MAAAja,GAAA,OAAAoE,QAAAE,OAAAtE,EAAA,CAAA,EAAA9H,EAQK6iB,gBAAe,WAAA,IACnB,OAAO3W,QAAAC,QAAAhO,KAAK+Q,QAAQX,WAStB7E,CARC,MAQDA,GAAAA,OAAAA,QAAAA,OAAAA,EAAAA,CAAAA,EAAAA,EAAAA,gBAAA,WACE,OAAOvL,KAAKgJ,OAAO0B,eACrB,EAQMsZ,EAAAA,OAAM,WAAA,IACV,OAAOjW,QAAAC,QAAAhO,KAAKkY,KAAK8L,SArHDhjB,CAsHjB,MAtHiBA,GAAAA,OAAAA,QAAAA,OAAAA,EAAAA,CAAAA,EAAAA,CAAAA,CAAR,CAAQA"}
|
|
1
|
+
{"version":3,"file":"sdk.module.js","sources":["../src/lib/Throttle.ts","../src/lib/events/CustomEvents.ts","../src/lib/events/Listener.ts","../src/lib/events/Dispatcher.ts","../src/lib/Errors.ts","../../node_modules/js-cookie/dist/js.cookie.mjs","../src/lib/Cookie.ts","../src/lib/SessionStorage.ts","../src/lib/client/HttpClient.ts","../src/lib/client/Client.ts","../src/lib/client/SessionClient.ts","../src/lib/events/SessionState.ts","../src/lib/events/WindowActivityManager.ts","../src/lib/events/Scheduler.ts","../src/lib/events/SessionChannel.ts","../src/lib/events/Relay.ts","../src/lib/WebauthnSupport.ts","../../node_modules/@github/webauthn-json/dist/esm/webauthn-json.js","../src/lib/flow-api/WebauthnManager.ts","../src/lib/flow-api/auto-steps.ts","../src/lib/flow-api/passkey-autofill-activation.ts","../src/lib/flow-api/State.ts","../src/lib/client/UserClient.ts","../src/Hanko.ts"],"sourcesContent":["/**\n * @interface\n * @category SDK\n * @subcategory Internal\n * @property {boolean=} leading - Whether to allow the function to be called on the leading edge of the wait timeout.\n * @property {boolean=} trailing - Whether to allow the function to be called on the trailing edge of the wait timeout.\n */\ninterface ThrottleOptions {\n leading?: boolean;\n trailing?: boolean;\n}\n\n// eslint-disable-next-line no-unused-vars\ntype ThrottledFunction<T extends (...args: any[]) => any> = (\n // eslint-disable-next-line no-unused-vars\n ...args: Parameters<T>\n) => void;\n\n/**\n * Provides throttle functionality.\n *\n * @hideconstructor\n * @category SDK\n * @subcategory Internal\n */\nexport class Throttle {\n /**\n * Throttles a function, ensuring that it can only be called once per `wait` milliseconds.\n *\n * @static\n * @param {function} func - The function to throttle.\n * @param {number} wait - The number of milliseconds to wait between function invocations.\n * @param {ThrottleOptions} options - Optional configuration for the throttle.\n * @returns {function} A throttled version of the original function.\n */\n // eslint-disable-next-line no-unused-vars,require-jsdoc\n static throttle<T extends (...args: any[]) => any>(\n func: T,\n wait: number,\n options: ThrottleOptions = {},\n ): ThrottledFunction<T> {\n const { leading = true, trailing = true } = options;\n let context: any;\n let args: any;\n let timeoutID: number;\n let previous = 0;\n\n // This function is used to invoke the original function.\n const executeThrottledFunction = () => {\n // If 'leading' is false and this is not the first invocation of the throttled function, set 'previous' to 0 to\n // ensure that the function is not called immediately.\n previous = leading === false ? 0 : Date.now();\n timeoutID = null;\n // Invoke the original function.\n func.apply(context, args);\n };\n\n // This is the throttled function that will be returned.\n const throttled = function (...funcArgs: Parameters<T>) {\n const now = Date.now();\n\n // If this is the first time the throttled function is being called, and 'leading' is false,\n // set 'previous' to the current time to ensure that the function is not called immediately.\n if (!previous && leading === false) previous = now;\n\n // The remaining wait time.\n const remaining = wait - (now - previous);\n\n // Save the context and arguments of the function call.\n // eslint-disable-next-line no-invalid-this\n context = this;\n args = funcArgs;\n\n // Check whether it's time to call the function immediately based on the leading and trailing options. If leading\n // is enabled and there was no previous invocation, or if trailing is enabled and the wait time has already passed,\n // the function will be invoked immediately.\n if (remaining <= 0 || remaining > wait) {\n // If there is a pending timeout, clear it.\n if (timeoutID) {\n window.clearTimeout(timeoutID);\n timeoutID = null;\n }\n\n // Invoke the original function and update the previous timestamp.\n previous = now;\n func.apply(context, args);\n } else if (!timeoutID && trailing !== false) {\n // If there is no pending timeout and trailing is allowed, start a new timeout.\n timeoutID = window.setTimeout(executeThrottledFunction, remaining);\n }\n };\n\n return throttled;\n }\n}\n","import { Claims } from \"../Dto\";\nimport { AnyState } from \"../flow-api/types/flow\";\n\n/**\n * The type of the `hanko-session-created` event.\n * @typedef {string} sessionCreatedType\n * @memberOf Listener\n */\nexport const sessionCreatedType: \"hanko-session-created\" =\n \"hanko-session-created\";\n\n/**\n * The type of the `hanko-session-expired` event.\n * @typedef {string} sessionExpiredType\n * @memberOf Listener\n */\nexport const sessionExpiredType: \"hanko-session-expired\" =\n \"hanko-session-expired\";\n\n/**\n * The type of the `hanko-user-logged-out` event.\n * @typedef {string} userLoggedOutType\n * @memberOf Listener\n */\nexport const userLoggedOutType: \"hanko-user-logged-out\" =\n \"hanko-user-logged-out\";\n\n/**\n * The type of the `hanko-user-deleted` event.\n * @typedef {string} userDeletedType\n * @memberOf Listener\n */\nexport const userDeletedType: \"hanko-user-deleted\" = \"hanko-user-deleted\";\n\n/**\n * The type of the `hanko-user-logged-in` event.\n * @typedef {string} userLoggedInType\n * @memberOf Listener\n */\nexport const userLoggedInType: \"hanko-user-logged-in\" = \"hanko-user-logged-in\";\n\n/**\n * The type of the `hanko-user-created` event.\n * @typedef {string} userCreatedType\n * @memberOf Listener\n */\nexport const userCreatedType: \"hanko-user-created\" = \"hanko-user-created\";\n\n/**\n * The type of the `hanko-after-state-change` event.\n * @typedef {string} flowAfterStateChangeType\n * @memberOf Listener\n */\nexport const flowAfterStateChangeType: \"hanko-after-state-change\" =\n \"hanko-after-state-change\";\n\n/**\n * The type of the `hanko-before-state-change` event.\n * @typedef {string} flowBeforeStateChangeType\n * @memberOf Listener\n */\nexport const flowBeforeStateChangeType: \"hanko-before-state-change\" =\n \"hanko-before-state-change\";\n\n/**\n * The type of the `hanko-flow-error` event.\n * @typedef {string} flowErrorType\n * @memberOf Listener\n */\nexport const flowErrorType: \"hanko-flow-error\" = \"hanko-flow-error\";\n\n/**\n * The data passed in the `hanko-session-created` or `hanko-session-resumed` event.\n *\n * @interface\n * @category SDK\n * @subcategory Events\n * @property {number} expirationSeconds - This property is deprecated. The number of seconds until the JWT expires.\n * @property {Claims} claims - The JSON web token associated with the session. Only present when the Hanko-API allows the JWT to be accessible client-side.\n */\nexport interface SessionDetail {\n claims: Claims;\n expirationSeconds: number; // deprecated\n}\n\nexport interface FlowErrorDetail {\n error: Error;\n}\n\nexport interface FlowDetail {\n state: AnyState;\n}\n\n/**\n * A custom event that includes a detail object.\n *\n * @category SDK\n * @subcategory Events\n * @extends CustomEvent\n * @ignore\n * @param {string} type - The type of the event.\n * @param {T} detail - The detail object to include in the event.\n */\nexport class CustomEventWithDetail<T> extends CustomEvent<T> {\n // eslint-disable-next-line require-jsdoc\n constructor(type: string, detail: T) {\n super(type, { detail });\n }\n}\n","import { Throttle } from \"../Throttle\";\nimport {\n CustomEventWithDetail,\n SessionDetail,\n FlowDetail,\n sessionCreatedType,\n sessionExpiredType,\n userDeletedType,\n userLoggedOutType,\n flowAfterStateChangeType,\n flowBeforeStateChangeType,\n flowErrorType,\n FlowErrorDetail,\n} from \"./CustomEvents\";\n\n/**\n * A callback function to be executed when an event is triggered.\n *\n * @alias CallbackFunc\n * @typedef {function} CallbackFunc\n * @memberOf Listener\n */\n// eslint-disable-next-line no-unused-vars\ntype CallbackFunc<T> = (detail: T) => any;\n\n/**\n * A wrapped callback function that will execute the original callback.\n *\n * @ignore\n * @param {T} event - The event object passed in the event.\n */\n// eslint-disable-next-line no-unused-vars\ntype WrappedCallback<T> = (event: CustomEventWithDetail<T>) => void;\n\n/**\n * A function returned when adding an event listener. The function can be called to remove the corresponding event\n * listener.\n *\n * @alias CleanupFunc\n * @typedef {function} CleanupFunc\n * @memberOf Listener\n */\ntype CleanupFunc = () => void;\n\n/**\n * @interface\n * @ignore\n * @property {Function} callback - The function to be executed.\n * @property {boolean=} once - Whether the event listener should be removed after being called once.\n */\ninterface EventListenerParams<T> {\n callback: CallbackFunc<T>;\n once?: boolean;\n}\n\n/**\n * @interface\n * @ignore\n * @extends {EventListenerParams<T>}\n * @property {string} type - The type of the event.\n * @property {boolean=} throttle - Whether the event listener should be throttled.\n */\ninterface EventListenerWithTypeParams<T> extends EventListenerParams<T> {\n type: string;\n throttle?: boolean;\n}\n\n/**\n * A class to bind event listener for custom events.\n *\n * @category SDK\n * @subcategory Events\n */\nexport class Listener {\n public throttleLimit = 1000;\n _addEventListener = document.addEventListener.bind(document);\n _removeEventListener = document.removeEventListener.bind(document);\n _throttle = Throttle.throttle;\n\n /**\n * Wraps the given callback.\n *\n * @param callback\n * @param throttle\n * @private\n * @return {WrappedCallback}\n */\n private wrapCallback<T>(\n callback: CallbackFunc<T>,\n throttle: boolean,\n ): WrappedCallback<T> {\n // The function that will be called when the event is triggered.\n const wrappedCallback = (event: CustomEventWithDetail<T>) => {\n callback(event.detail);\n };\n\n // Throttle the listener if multiple SDK instances could trigger the same event at the same time,\n // but the callback function should only be executed once.\n if (throttle) {\n return this._throttle(wrappedCallback, this.throttleLimit, {\n leading: true,\n trailing: false,\n });\n }\n\n return wrappedCallback;\n }\n\n /**\n * Adds an event listener with the specified type, callback function, and options.\n *\n * @private\n * @param {EventListenerWithTypeParams<T>} params - The parameters for the event listener.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n private addEventListenerWithType<T>({\n type,\n callback,\n once = false,\n throttle = false,\n }: EventListenerWithTypeParams<T>): CleanupFunc {\n const wrappedCallback = this.wrapCallback(callback, throttle);\n this._addEventListener(type, wrappedCallback, { once });\n return () => this._removeEventListener(type, wrappedCallback);\n }\n\n /**\n * Maps the parameters for an event listener to the `EventListenerWithTypeParams` interface.\n *\n * @static\n * @private\n * @param {string} type - The type of the event.\n * @param {EventListenerParams<T>} params - The parameters for the event listener.\n * @param {boolean} [throttle=false] - Whether the event listener should be throttled.\n * @returns {EventListenerWithTypeParams<T>}\n **/\n private static mapAddEventListenerParams<T>(\n type: string,\n { once, callback }: EventListenerParams<T>,\n throttle?: boolean,\n ): EventListenerWithTypeParams<T> {\n return {\n type,\n callback,\n once,\n throttle,\n };\n }\n\n /**\n * Adds an event listener with the specified type, callback function, and options.\n *\n * @private\n * @param {string} type - The type of the event.\n * @param {EventListenerParams<T>} params - The parameters for the event listener.\n * @param {boolean=} throttle - Whether the event listener should be throttled.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n private addEventListener<T>(\n type: string,\n params: EventListenerParams<T>,\n throttle?: boolean,\n ) {\n return this.addEventListenerWithType(\n Listener.mapAddEventListenerParams(type, params, throttle),\n );\n }\n\n /**\n * Adds an event listener for \"hanko-session-created\" events. Will be triggered across all browser windows, when the user\n * logs in, or when the page has been loaded or refreshed and there is a valid session.\n *\n * @param {CallbackFunc<SessionDetail>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onSessionCreated(\n callback: CallbackFunc<SessionDetail>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(sessionCreatedType, { callback, once }, true);\n }\n\n /**\n * Adds an event listener for \"hanko-session-expired\" events. The event will be triggered across all browser windows\n * as soon as the current JWT expires or the user logs out. It also triggers, when the user deletes the account in\n * another window.\n *\n * @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onSessionExpired(\n callback: CallbackFunc<null>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(sessionExpiredType, { callback, once }, true);\n }\n\n /**\n * Adds an event listener for hanko-user-deleted events. The event triggers, when the user has deleted the account in\n * the browser window where the deletion happened.\n *\n * @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onUserLoggedOut(\n callback: CallbackFunc<null>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(userLoggedOutType, { callback, once });\n }\n\n /**\n * Adds an event listener for hanko-user-deleted events. The event triggers, when the user has deleted the account.\n *\n * @param {CallbackFunc<null>} callback - The function to be called when the event is triggered.\n * @param {boolean=} once - Whether the event listener should be removed after being called once.\n * @returns {CleanupFunc} This function can be called to remove the event listener.\n */\n public onUserDeleted(\n callback: CallbackFunc<null>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(userDeletedType, { callback, once });\n }\n\n public onAfterStateChange(\n callback: CallbackFunc<FlowDetail>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(\n flowAfterStateChangeType,\n { callback, once },\n false,\n );\n }\n\n public onBeforeStateChange(\n callback: CallbackFunc<FlowDetail>,\n once?: boolean,\n ): CleanupFunc {\n return this.addEventListener(\n flowBeforeStateChangeType,\n { callback, once },\n false,\n );\n }\n}\n","import {\n SessionDetail,\n CustomEventWithDetail,\n sessionCreatedType,\n sessionExpiredType,\n userDeletedType,\n userLoggedOutType,\n flowAfterStateChangeType,\n FlowDetail,\n flowBeforeStateChangeType,\n} from \"./CustomEvents\";\n\n/**\n * A class that dispatches custom events.\n *\n * @category SDK\n * @subcategory Internal\n */\nexport class Dispatcher {\n _dispatchEvent = document.dispatchEvent.bind(document);\n\n /**\n * Dispatches a custom event.\n *\n * @param {string} type\n * @param {T} detail\n * @private\n */\n private dispatch<T>(type: string, detail: T) {\n this._dispatchEvent(new CustomEventWithDetail(type, detail));\n }\n\n /**\n * Dispatches a \"hanko-session-created\" event to the document with the specified detail.\n *\n * @param {SessionDetail} detail - The event detail.\n */\n public dispatchSessionCreatedEvent(detail: SessionDetail) {\n this.dispatch(sessionCreatedType, detail);\n }\n\n /**\n * Dispatches a \"hanko-session-expired\" event to the document.\n */\n public dispatchSessionExpiredEvent() {\n this.dispatch(sessionExpiredType, null);\n }\n\n /**\n * Dispatches a \"hanko-user-logged-out\" event to the document.\n */\n public dispatchUserLoggedOutEvent() {\n this.dispatch(userLoggedOutType, null);\n }\n\n /**\n * Dispatches a \"hanko-user-deleted\" event to the document.\n */\n public dispatchUserDeletedEvent() {\n this.dispatch(userDeletedType, null);\n }\n\n /**\n * Dispatches a \"hanko-after-state-change\" event to the document.\n */\n public dispatchAfterStateChangeEvent(detail: FlowDetail) {\n this.dispatch(flowAfterStateChangeType, detail);\n }\n\n /**\n * Dispatches a \"hanko-before-state-change\" event to the document.\n */\n public dispatchBeforeStateChangeEvent(detail: FlowDetail) {\n this.dispatch(flowBeforeStateChangeType, detail);\n }\n}\n","/**\n * Every error thrown in the SDK is an instance of 'HankoError'. The value of the 'code' property is eligible to\n * translate the error into an error message.\n *\n * @extends {Error}\n * @category SDK\n * @subcategory Errors\n * @param code {string} - An error code that refers to the error instance.\n * @param cause {Error=} - The original error\n */\nabstract class HankoError extends Error {\n code: string;\n cause?: Error;\n\n // eslint-disable-next-line require-jsdoc\n protected constructor(message: string, code: string, cause?: Error) {\n super(message);\n /**\n * @public\n * @type {string}\n */\n this.code = code;\n /**\n * @public\n * @type {Error=}\n */\n this.cause = cause;\n Object.setPrototypeOf(this, HankoError.prototype);\n }\n}\n\n/**\n * Every error that doesn't need to be handled in a special way is a 'TechnicalError'. Whenever you catch one, there is\n * usually nothing you can do but present an error to the user, e.g. \"Something went wrong\".\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass TechnicalError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Technical error\", \"somethingWentWrong\", cause);\n Object.setPrototypeOf(this, TechnicalError.prototype);\n }\n}\n\n/**\n * Attempting to create a resource that already exists results in a 'ConflictError'.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ConflictError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(userID?: string, cause?: Error) {\n super(\"Conflict error\", \"conflict\", cause);\n Object.setPrototypeOf(this, ConflictError.prototype);\n }\n}\n\n/**\n * A 'RequestTimeoutError' occurs when the specified timeout has been reached.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass RequestTimeoutError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Request timed out error\", \"requestTimeout\", cause);\n Object.setPrototypeOf(this, RequestTimeoutError.prototype);\n }\n}\n\n/**\n * A 'WebauthnRequestCancelledError' occurs during WebAuthn authentication or registration, when the WebAuthn API throws\n * an error. In most cases, this happens when the user cancels the browser's WebAuthn dialog.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass WebauthnRequestCancelledError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Request cancelled error\", \"requestCancelled\", cause);\n Object.setPrototypeOf(this, WebauthnRequestCancelledError.prototype);\n }\n}\n\n/**\n * An 'InvalidPasswordError' occurs when invalid credentials are provided when logging in with a password.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidPasswordError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Invalid password error\", \"invalidPassword\", cause);\n Object.setPrototypeOf(this, InvalidPasswordError.prototype);\n }\n}\n\n/**\n * An 'InvalidPasswordError' occurs when an incorrect code is entered when logging in with a passcode.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidPasscodeError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Invalid Passcode error\", \"invalidPasscode\", cause);\n Object.setPrototypeOf(this, InvalidPasscodeError.prototype);\n }\n}\n\n/**\n * An 'InvalidWebauthnCredentialError' occurs if invalid credentials were used when logging in with WebAuthn.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass InvalidWebauthnCredentialError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Invalid WebAuthn credential error\",\n \"invalidWebauthnCredential\",\n cause,\n );\n Object.setPrototypeOf(this, InvalidWebauthnCredentialError.prototype);\n }\n}\n\n/**\n * A 'PasscodeExpiredError' occurs when the passcode has expired.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass PasscodeExpiredError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Passcode expired error\", \"passcodeExpired\", cause);\n Object.setPrototypeOf(this, PasscodeExpiredError.prototype);\n }\n}\n\n/**\n * A 'MaxNumOfPasscodeAttemptsReachedError' occurs when an incorrect passcode is provided too many times.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass MaxNumOfPasscodeAttemptsReachedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Maximum number of Passcode attempts reached error\",\n \"passcodeAttemptsReached\",\n cause,\n );\n Object.setPrototypeOf(this, MaxNumOfPasscodeAttemptsReachedError.prototype);\n }\n}\n\n/**\n * A 'NotFoundError' occurs when the requested resource was not found.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass NotFoundError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Not found error\", \"notFound\", cause);\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n\n/**\n * A 'TooManyRequestsError' occurs due to rate limiting when too many requests are made.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass TooManyRequestsError extends HankoError {\n retryAfter?: number;\n // eslint-disable-next-line require-jsdoc\n constructor(retryAfter?: number, cause?: Error) {\n super(\"Too many requests error\", \"tooManyRequests\", cause);\n this.retryAfter = retryAfter;\n Object.setPrototypeOf(this, TooManyRequestsError.prototype);\n }\n}\n\n/**\n * An 'UnauthorizedError' occurs when the user is not authorized to access the resource.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass UnauthorizedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Unauthorized error\", \"unauthorized\", cause);\n Object.setPrototypeOf(this, UnauthorizedError.prototype);\n }\n}\n\n/**\n * A 'ForbiddenError' occurs when the user is not allowed to perform the requested action.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ForbiddenError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"Forbidden error\", \"forbidden\", cause);\n Object.setPrototypeOf(this, ForbiddenError.prototype);\n }\n}\n\n/**\n * A 'UserVerificationError' occurs when the user verification requirements\n * for a WebAuthn ceremony are not met.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass UserVerificationError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\"User verification error\", \"userVerification\", cause);\n Object.setPrototypeOf(this, UserVerificationError.prototype);\n }\n}\n\n/**\n * A 'MaxNumOfEmailAddressesReachedError' occurs when the user tries to add a new email address while the maximum number\n * of email addresses (see backend configuration) equals the number of email addresses already registered.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass MaxNumOfEmailAddressesReachedError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"Maximum number of email addresses reached error\",\n \"maxNumOfEmailAddressesReached\",\n cause,\n );\n Object.setPrototypeOf(this, MaxNumOfEmailAddressesReachedError.prototype);\n }\n}\n\n/**\n * An 'EmailAddressAlreadyExistsError' occurs when the user tries to add a new email address which already exists.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass EmailAddressAlreadyExistsError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(cause?: Error) {\n super(\n \"The email address already exists\",\n \"emailAddressAlreadyExistsError\",\n cause,\n );\n Object.setPrototypeOf(this, EmailAddressAlreadyExistsError.prototype);\n }\n}\n\n/**\n * A `ThirdPartyError` may occur during a sign in/sign up with a third party\n * provider.\n *\n * @category SDK\n * @subcategory Errors\n * @extends {HankoError}\n */\nclass ThirdPartyError extends HankoError {\n // eslint-disable-next-line require-jsdoc\n constructor(code: string, cause?: Error) {\n super(\"An error occurred during third party sign up/sign in\", code, cause);\n Object.setPrototypeOf(this, ThirdPartyError.prototype);\n }\n}\n\nexport {\n HankoError,\n TechnicalError,\n ConflictError,\n RequestTimeoutError,\n WebauthnRequestCancelledError,\n InvalidPasswordError,\n InvalidPasscodeError,\n InvalidWebauthnCredentialError,\n PasscodeExpiredError,\n MaxNumOfPasscodeAttemptsReachedError,\n NotFoundError,\n TooManyRequestsError,\n UnauthorizedError,\n ForbiddenError,\n UserVerificationError,\n MaxNumOfEmailAddressesReachedError,\n EmailAddressAlreadyExistsError,\n ThirdPartyError,\n};\n","/*! js-cookie v3.0.5 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n function set (name, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n name = encodeURIComponent(name)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n name + '=' + converter.write(value, name) + stringifiedAttributes)\n }\n\n function get (name) {\n if (typeof document === 'undefined' || (arguments.length && !name)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var found = decodeURIComponent(parts[0]);\n jar[found] = converter.read(value, found);\n\n if (name === found) {\n break\n }\n } catch (e) {}\n }\n\n return name ? jar[name] : jar\n }\n\n return Object.create(\n {\n set,\n get,\n remove: function (name, attributes) {\n set(\n name,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n/* eslint-enable no-var */\n\nexport { api as default };\n","import JSCookie, { CookieAttributes } from \"js-cookie\";\nimport { TechnicalError } from \"./Errors\";\n\n/**\n * Options for Cookie\n *\n * @category SDK\n * @subcategory Internal\n * @property {string=} cookieName - The name of the session cookie set from the SDK. Defaults to \"hanko\".\n * @property {string=} cookieDomain - The domain where the cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.\n * @property {string=} cookieSameSite -Specify whether/when cookies are sent with cross-site requests. Defaults to \"lax\".\n */\ninterface CookieOptions {\n cookieName?: string;\n cookieDomain?: string;\n cookieSameSite?: CookieSameSite;\n}\n\nexport type CookieSameSite =\n | \"strict\"\n | \"Strict\"\n | \"lax\"\n | \"Lax\"\n | \"none\"\n | \"None\";\n\n/**\n * A class to manage cookies.\n *\n * @category SDK\n * @subcategory Internal\n * @param {CookieOptions} options - The options that can be used\n */\nexport class Cookie {\n authCookieName: string;\n authCookieDomain?: string;\n authCookieSameSite: CookieSameSite;\n\n // eslint-disable-next-line require-jsdoc\n constructor(options: CookieOptions) {\n this.authCookieName = options.cookieName ?? \"hanko\";\n this.authCookieDomain = options.cookieDomain;\n this.authCookieSameSite = options.cookieSameSite ?? \"lax\";\n }\n\n /**\n * Returns the authentication token that was stored in the cookie.\n *\n * @return {string}\n */\n getAuthCookie(): string {\n return JSCookie.get(this.authCookieName);\n }\n\n /**\n * Stores the authentication token to the cookie.\n *\n * @param {string} token - The authentication token to be stored.\n * @param {CookieAttributes} options - Options for setting the auth cookie.\n */\n setAuthCookie(token: string, options?: CookieAttributes) {\n const defaults: CookieAttributes = {\n secure: true,\n sameSite: this.authCookieSameSite,\n };\n\n if (this.authCookieDomain !== undefined) {\n defaults.domain = this.authCookieDomain;\n }\n\n const o: CookieAttributes = { ...defaults, ...options };\n\n if (\n (o.sameSite === \"none\" || o.sameSite === \"None\") &&\n o.secure === false\n ) {\n throw new TechnicalError(\n new Error(\"Secure attribute must be set when SameSite=None\"),\n );\n }\n\n JSCookie.set(this.authCookieName, token, o);\n }\n\n /**\n * Removes the cookie used for authentication.\n */\n removeAuthCookie() {\n JSCookie.remove(this.authCookieName);\n }\n}\n","/**\n * Options for SessionStorage\n *\n * @category SDK\n * @subcategory Internal\n * @property {string} keyName - The name of the sessionStorage session token entry set from the SDK.\n */\ninterface SessionStorageOptions {\n keyName: string;\n}\n\n/**\n * A class to manage sessionStorage.\n *\n * @category SDK\n * @subcategory Internal\n * @param {SessionStorageOptions} options - The options that can be used.\n */\nexport class SessionStorage {\n keyName: string;\n\n // eslint-disable-next-line require-jsdoc\n constructor(options: SessionStorageOptions) {\n this.keyName = options.keyName;\n }\n\n /**\n * Return the session token that was stored in the sessionStorage.\n *\n * @return {string}\n */\n getSessionToken(): string {\n return sessionStorage.getItem(this.keyName);\n }\n\n /**\n * Stores the session token in the sessionStorage.\n *\n * @param {string} token - The session token to be stored.\n */\n setSessionToken(token: string) {\n sessionStorage.setItem(this.keyName, token);\n }\n\n /**\n * Removes the session token used for authentication.\n */\n removeSessionToken() {\n sessionStorage.removeItem(this.keyName);\n }\n}\n","import { RequestTimeoutError, TechnicalError } from \"../Errors\";\nimport { Dispatcher } from \"../events/Dispatcher\";\nimport { Cookie } from \"../Cookie\";\nimport { SessionStorage } from \"../SessionStorage\";\nimport { CookieAttributes } from \"js-cookie\";\nimport { HankoOptions } from \"../../Hanko\";\n\nexport type SessionTokenLocation = \"cookie\" | \"sessionStorage\";\n\n/**\n * This class wraps an XMLHttpRequest to maintain compatibility with the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {XMLHttpRequest} xhr - The request to be wrapped.\n * @see HttpClient\n */\nclass Headers {\n _xhr: XMLHttpRequest;\n\n // eslint-disable-next-line require-jsdoc\n constructor(xhr: XMLHttpRequest) {\n this._xhr = xhr;\n }\n\n /**\n * Returns the response header with the given name.\n *\n * @param {string} name\n * @return {string}\n */\n getResponseHeader(name: string) {\n return this._xhr.getResponseHeader(name);\n }\n}\n\n/**\n * This class wraps an XMLHttpRequest to maintain compatibility with the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {XMLHttpRequest} xhr - The request to be wrapped.\n * @see HttpClient\n */\nclass Response {\n headers: Headers;\n ok: boolean;\n status: number;\n statusText: string;\n url: string;\n _decodedJSON: any;\n xhr: XMLHttpRequest;\n\n // eslint-disable-next-line require-jsdoc\n constructor(xhr: XMLHttpRequest) {\n /**\n * @public\n * @type {Headers}\n */\n this.headers = new Headers(xhr);\n /**\n * @public\n * @type {boolean}\n */\n this.ok = xhr.status >= 200 && xhr.status <= 299;\n /**\n * @public\n * @type {number}\n */\n this.status = xhr.status;\n /**\n * @public\n * @type {string}\n */\n this.statusText = xhr.statusText;\n /**\n * @public\n * @type {string}\n */\n this.url = xhr.responseURL;\n /**\n * @private\n * @type {XMLHttpRequest}\n */\n this.xhr = xhr;\n }\n\n /**\n * Returns the JSON decoded response.\n *\n * @return {any}\n */\n json() {\n if (!this._decodedJSON) {\n this._decodedJSON = JSON.parse(this.xhr.response);\n }\n return this._decodedJSON;\n }\n\n /**\n * Returns the response header value with the given `name` as a number. When the value is not a number the return\n * value will be 0.\n *\n * @param {string} name - The name of the header field\n * @return {number}\n */\n parseNumericHeader(name: string): number {\n const result = parseInt(this.headers.getResponseHeader(name), 10);\n return isNaN(result) ? 0 : result;\n }\n}\n\n/**\n * Options for the HttpClient\n *\n * @category SDK\n * @subcategory Internal\n * @property {number=} timeout - The http request timeout in milliseconds.\n * @property {string} cookieName - The name of the session cookie set from the SDK.\n * @property {string=} cookieDomain - The domain where cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.\n * @property {string?} lang - The language used by the client(s) to convey to the Hanko API the language to use -\n * e.g. for translating outgoing emails - in a custom header (X-Language).\n */\nexport interface HttpClientOptions {\n timeout?: number;\n cookieName?: string;\n cookieDomain?: string;\n lang?: string;\n sessionTokenLocation?: SessionTokenLocation;\n}\n\n/**\n * Internally used for communication with the Hanko API. It also handles authorization tokens to enable authorized\n * requests.\n *\n * Currently, there is an issue with Safari and on iOS 15 devices where decoding a JSON response via the fetch API\n * breaks the user gesture and the user is not able to use the authenticator. Therefore, this class uses XMLHttpRequests\n * instead of the fetch API, but maintains compatibility by wrapping the XMLHttpRequests. So, if the issues are fixed,\n * we can easily return to the fetch API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {string} api - The URL of your Hanko API instance\n * @param {HttpClientOptions} options - The options the HttpClient must be provided\n */\nclass HttpClient {\n timeout: number;\n api: string;\n dispatcher: Dispatcher;\n cookie: Cookie;\n sessionTokenStorage: SessionStorage;\n lang: string;\n sessionTokenLocation: SessionTokenLocation;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options: HankoOptions) {\n this.api = api;\n this.timeout = options.timeout ?? 13000;\n this.dispatcher = new Dispatcher();\n this.cookie = new Cookie({ ...options });\n this.sessionTokenStorage = new SessionStorage({\n keyName: options.cookieName,\n });\n this.lang = options.lang;\n this.sessionTokenLocation = options.sessionTokenLocation;\n }\n\n // eslint-disable-next-line require-jsdoc\n _fetch(path: string, options: RequestInit, xhr = new XMLHttpRequest()) {\n const self = this;\n const url = this.api + path;\n const timeout = this.timeout;\n const bearerToken = this.getAuthToken();\n const lang = this.lang;\n\n return new Promise<Response>(function (resolve, reject) {\n xhr.open(options.method, url, true);\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n xhr.setRequestHeader(\"Content-Type\", \"application/json\");\n xhr.setRequestHeader(\"X-Language\", lang);\n\n if (bearerToken) {\n xhr.setRequestHeader(\"Authorization\", `Bearer ${bearerToken}`);\n }\n\n xhr.timeout = timeout;\n xhr.withCredentials = true;\n xhr.onload = () => {\n self.processHeaders(xhr);\n resolve(new Response(xhr));\n };\n\n xhr.onerror = () => {\n reject(new TechnicalError());\n };\n\n xhr.ontimeout = () => {\n reject(new RequestTimeoutError());\n };\n\n xhr.send(options.body ? options.body.toString() : null);\n });\n }\n\n /**\n * Processes the response headers on login and extracts the JWT and expiration time.\n *\n * @param {XMLHttpRequest} xhr - The xhr object.\n */\n processHeaders(xhr: XMLHttpRequest) {\n let jwt = \"\";\n let expirationSeconds = 0;\n let retention = \"\";\n\n xhr\n .getAllResponseHeaders()\n .split(\"\\r\\n\")\n .forEach((h) => {\n const header = h.toLowerCase();\n if (header.startsWith(\"x-auth-token\")) {\n jwt = xhr.getResponseHeader(\"X-Auth-Token\");\n } else if (header.startsWith(\"x-session-lifetime\")) {\n expirationSeconds = parseInt(\n xhr.getResponseHeader(\"X-Session-Lifetime\"),\n 10,\n );\n } else if (header.startsWith(\"x-session-retention\")) {\n retention = xhr.getResponseHeader(\"X-Session-Retention\");\n }\n });\n\n if (jwt) {\n const https = new RegExp(\"^https://\");\n const secure =\n !!this.api.match(https) && !!window.location.href.match(https);\n\n const expires =\n retention === \"session\"\n ? undefined\n : new Date(new Date().getTime() + expirationSeconds * 1000);\n\n this.setAuthToken(jwt, { secure, expires });\n }\n }\n\n /**\n * Performs a GET request.\n *\n * @param {string} path - The path to the requested resource.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n get(path: string) {\n return this._fetch(path, { method: \"GET\" });\n }\n\n /**\n * Performs a POST request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n post(path: string, body?: any) {\n return this._fetch(path, {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a PUT request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n put(path: string, body?: any) {\n return this._fetch(path, {\n method: \"PUT\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a PATCH request.\n *\n * @param {string} path - The path to the requested resource.\n * @param {any=} body - The request body.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n patch(path: string, body?: any) {\n return this._fetch(path, {\n method: \"PATCH\",\n body: JSON.stringify(body),\n });\n }\n\n /**\n * Performs a DELETE request.\n *\n * @param {string} path - The path to the requested resource.\n * @return {Promise<Response>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n delete(path: string) {\n return this._fetch(path, {\n method: \"DELETE\",\n });\n }\n\n /**\n * Returns the session token either from the cookie or the sessionStorage.\n * @private\n * @return {string}\n */\n private getAuthToken(): string {\n let token = \"\";\n switch (this.sessionTokenLocation) {\n case \"cookie\":\n token = this.cookie.getAuthCookie();\n break;\n case \"sessionStorage\":\n token = this.sessionTokenStorage.getSessionToken();\n break;\n default:\n token = this.cookie.getAuthCookie();\n break;\n }\n return token;\n }\n\n /**\n * Stores the session token either in a cookie or in the sessionStorage depending on the configuration.\n * @param {string} token - The session token to be stored.\n * @param {CookieAttributes} options - Options for setting the auth cookie.\n * @private\n */\n private setAuthToken(token: string, options: CookieAttributes) {\n switch (this.sessionTokenLocation) {\n case \"cookie\":\n return this.cookie.setAuthCookie(token, options);\n case \"sessionStorage\":\n return this.sessionTokenStorage.setSessionToken(token);\n default:\n return this.cookie.setAuthCookie(token, options);\n }\n }\n}\n\nexport { Headers, Response, HttpClient };\n","import { HttpClient, HttpClientOptions } from \"./HttpClient\";\n\n/**\n * A class to be extended by the other client classes.\n *\n * @abstract\n * @category SDK\n * @subcategory Internal\n * @param {string} api - The URL of your Hanko API instance\n * @param {HttpClientOptions} options - The options that can be used\n */\nabstract class Client {\n client: HttpClient;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options: HttpClientOptions) {\n /**\n * @public\n * @type {HttpClient}\n */\n this.client = new HttpClient(api, options);\n }\n}\n\nexport { Client };\n","import { Client } from \"./Client\";\nimport { SessionCheckResponse } from \"../Dto\";\nimport { TechnicalError } from \"../Errors\";\n\n/**\n * A class that handles communication with the Hanko API for the purposes\n * of sessions.\n *\n * @constructor\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nexport class SessionClient extends Client {\n /**\n * Checks if the current session is still valid.\n *\n * @return {Promise<SessionCheckResponse>}\n * @throws {TechnicalError}\n */\n async validate(): Promise<SessionCheckResponse> {\n const response = await this.client.get(\"/sessions/validate\");\n\n if (!response.ok) {\n throw new TechnicalError();\n }\n\n return await response.json();\n }\n}\n","/**\n * Represents the session state with expiration and last check timestamps.\n *\n * @category SDK\n * @subcategory Internal\n */\nexport interface State {\n expiration: number; // Timestamp (in milliseconds) when the session expires.\n lastCheck: number; // Timestamp (in milliseconds) of the last session check.\n}\n\n/**\n * Manages session state persistence using localStorage.\n *\n * @category SDK\n * @subcategory Internal\n */\nexport class SessionState {\n private readonly storageKey: string;\n private readonly defaultState: State = {\n expiration: 0,\n lastCheck: 0,\n };\n\n /**\n * Creates an instance of SessionState.\n *\n * @param {string} storageKey - The key used to store session state in localStorage.\n */\n constructor(storageKey: string) {\n this.storageKey = storageKey;\n }\n\n /**\n * Loads the current session state from localStorage.\n *\n * @returns {State} The parsed session state or a default state if not found.\n */\n load(): State {\n const item = window.localStorage.getItem(this.storageKey);\n return item == null ? this.defaultState : JSON.parse(item);\n }\n\n /**\n * Saves the session state to localStorage.\n *\n * @param {State | null} session - The session state to save. If null, the default state is used.\n */\n save(session: State | null): void {\n window.localStorage.setItem(\n this.storageKey,\n JSON.stringify(session ? session : this.defaultState),\n );\n }\n}\n","// Callback type for handling window activity changes.\ntype Callback = () => void;\n\n/**\n * Manages window focus and blur events.\n *\n * @class\n * @category SDK\n * @subcategory Internal\n * @param {Callback} onActivityCallback - Callback to invoke when the window gains focus.\n * @param {Callback} onInactivityCallback - Callback to invoke when the window loses focus.\n */\nexport class WindowActivityManager {\n private readonly onActivityCallback: Callback; // Callback for when the window or tab gains focus.\n private readonly onInactivityCallback: Callback; // Callback for when the window or tab loses focus.\n\n // eslint-disable-next-line require-jsdoc\n constructor(onActivityCallback: Callback, onInactivityCallback: Callback) {\n this.onActivityCallback = onActivityCallback;\n this.onInactivityCallback = onInactivityCallback;\n\n // Attach event listeners for focus and blur\n window.addEventListener(\"focus\", this.handleFocus);\n window.addEventListener(\"blur\", this.handleBlur);\n document.addEventListener(\"visibilitychange\", this.handleVisibilityChange);\n }\n\n /**\n * Handles the focus event and invokes the activity callback.\n * @private\n */\n private handleFocus = (): void => {\n this.onActivityCallback();\n };\n\n /**\n * Handles the blur event and invokes the inactivity callback.\n * @private\n */\n private handleBlur = (): void => {\n this.onInactivityCallback();\n };\n\n /**\n * Handles the visibility change event and invokes appropriate callbacks.\n * @private\n */\n private handleVisibilityChange = (): void => {\n if (document.visibilityState === \"visible\") {\n this.onActivityCallback();\n } else {\n this.onInactivityCallback();\n }\n };\n\n /**\n * Checks if the current window has focus.\n * @returns {boolean} True if the window has focus; otherwise, false.\n */\n hasFocus = (): boolean => {\n return document.hasFocus();\n };\n}\n","import { SessionCheckResponse } from \"../Dto\";\n\n// Type representing data returned by the session check callback.\nexport type SessionCheckResult =\n | (Omit<SessionCheckResponse, \"expiration_time\"> & {\n expiration: number;\n })\n | null;\n\n/**\n * Callback type for performing a session check.\n * @ignore\n */\ntype SessionCheckCallback = () => Promise<SessionCheckResult>;\n\n/**\n * Callback type for handling session timeout events.\n * @ignore\n */\ntype SessionExpiredCallback = () => void;\n\n/**\n * Manages scheduling for periodic and timeout-based session checks.\n *\n * @category SDK\n * @subcategory Internal\n * @param {number} checkInterval - The interval in milliseconds between periodic session checks.\n * @param {SessionCheckCallback} checkSession - The callback function to perform a session check.\n * @param {SessionExpiredCallback} onSessionExpired - The callback function to handle session timeout events.\n */\nexport class Scheduler {\n private intervalID: ReturnType<typeof setInterval> | null = null; // Identifier for the periodic check interval.\n private timeoutID: ReturnType<typeof setTimeout> | null = null; // Identifier for the session expiration timeout.\n private readonly checkInterval: number; // The interval between periodic session checks.\n private readonly checkSession: SessionCheckCallback; // The callback function to perform a session check.\n private readonly onSessionExpired: SessionExpiredCallback; // The callback function to handle session expired events.\n\n // eslint-disable-next-line require-jsdoc\n constructor(\n checkInterval: number,\n checkSession: SessionCheckCallback,\n onSessionExpired: SessionExpiredCallback,\n ) {\n this.checkInterval = checkInterval;\n this.checkSession = checkSession;\n this.onSessionExpired = onSessionExpired;\n }\n\n /**\n * Handles the session expiration when it is about to expire soon.\n * Stops any ongoing checks and schedules a timeout for the expiration.\n *\n * @param {number} timeToExpiration - The time in milliseconds until the session expires.\n */\n scheduleSessionExpiry(timeToExpiration: number): void {\n this.stop();\n this.timeoutID = setTimeout(async () => {\n this.stop();\n this.onSessionExpired();\n }, timeToExpiration);\n }\n\n /**\n * Starts the session check process.\n * Determines when the next check should run based on the last known check time and session expiration.\n * If the session is expiring soon, schedules an expiration event instead of starting periodic checks.\n *\n * @param {number} lastCheck - The timestamp (in milliseconds) of the last session check.\n * @param {number} expiration - The timestamp (in milliseconds) of when the session expires.\n */\n start(lastCheck: number = 0, expiration: number = 0): void {\n const timeToNextCheck = this.calcTimeToNextCheck(lastCheck);\n\n if (this.sessionExpiresSoon(expiration)) {\n this.scheduleSessionExpiry(timeToNextCheck);\n return;\n }\n\n // Schedule the first check after an optional delay\n this.timeoutID = setTimeout(async () => {\n try {\n let result = await this.checkSession();\n\n if (result.is_valid) {\n if (this.sessionExpiresSoon(result.expiration)) {\n this.scheduleSessionExpiry(result.expiration - Date.now());\n return;\n }\n\n // Begin periodic checks\n this.intervalID = setInterval(async () => {\n result = await this.checkSession();\n\n if (result.is_valid) {\n if (this.sessionExpiresSoon(result.expiration)) {\n this.scheduleSessionExpiry(result.expiration - Date.now());\n }\n } else {\n this.stop();\n }\n }, this.checkInterval);\n } else {\n this.stop();\n }\n } catch (e) {\n console.log(e);\n }\n }, timeToNextCheck);\n }\n\n /**\n * Stops the session check process and clears all timers.\n */\n stop(): void {\n if (this.timeoutID) {\n clearTimeout(this.timeoutID);\n this.timeoutID = null;\n }\n\n if (this.intervalID) {\n clearInterval(this.intervalID);\n this.intervalID = null;\n }\n }\n\n /**\n * Checks if the scheduler is currently running.\n * @returns {boolean} True if the scheduler is running; otherwise, false.\n */\n isRunning(): boolean {\n return this.timeoutID !== null || this.intervalID !== null;\n }\n\n /**\n * Checks if the session is about to expire.\n * @param {number} expiration - Timestamp when the session will expire.\n * @returns {boolean} True if the session is about to expire; otherwise, false.\n */\n sessionExpiresSoon(expiration: number): boolean {\n return expiration > 0 && expiration - Date.now() <= this.checkInterval;\n }\n\n /**\n * Calculates the time until the next session check should occur.\n *\n * @param {number} lastCheck - The timestamp (in milliseconds) of the last session check.\n * @returns {number} The time in milliseconds until the next check should be performed.\n */\n calcTimeToNextCheck(lastCheck: number): number {\n const timeSinceLastCheck = Date.now() - lastCheck;\n return this.checkInterval >= timeSinceLastCheck\n ? this.checkInterval - (timeSinceLastCheck % this.checkInterval)\n : 0;\n }\n}\n","import { Claims } from \"../Dto\";\n\n/**\n * Enum-like type defining the actions that can be broadcasted.\n *\n * @ignore\n * @category SDK\n * @subcategory Internal\n */\ntype Action = \"sessionExpired\" | \"sessionCreated\" | \"requestLeadership\";\n\n/**\n * Interface representing the data structure of a channel event.\n *\n * @interface\n * @property {Action} action - The type of action being broadcasted.\n * @property {Claims=} claims - Optional claims associated with the event.\n * @property {boolean=} is_valid - Optional indication of the session validity.\n * @category SDK\n * @subcategory Internal\n */\nexport interface BroadcastMessage {\n action: Action;\n claims?: Claims;\n is_valid?: boolean;\n}\n\n/**\n * Callback type for handling broadcast messages.\n *\n * @ignore\n */\n// eslint-disable-next-line no-unused-vars\ntype Callback = (msg: BroadcastMessage) => void;\n\n/**\n * Manages inter-tab communication using the BroadcastChannel API.\n *\n * @category SDK\n * @subcategory Internal\n * @param {string} channelName - The name of the broadcast channel.\n * @param {Callback} onSessionExpired - Callback invoked when the session has expired.\n * @param {Callback} onSessionCreated - Callback invoked when a session is created.\n * @param {Callback} onLeadershipRequested - Callback invoked when a leadership request is received.\n */\nexport class SessionChannel {\n channel: BroadcastChannel; // The broadcast channel used for communication.\n onSessionExpired: Callback; // Callback invoked when the session has expired.\n onSessionCreated: Callback; // Callback invoked when a session is created.\n onLeadershipRequested: Callback; // Callback invoked when a leadership request is received.\n\n // eslint-disable-next-line require-jsdoc\n constructor(\n channelName: string = \"hanko_session\",\n onSessionExpired: Callback,\n onSessionCreated: Callback,\n onLeadershipRequested: Callback,\n ) {\n this.onSessionExpired = onSessionExpired;\n this.onSessionCreated = onSessionCreated;\n this.onLeadershipRequested = onLeadershipRequested;\n\n this.channel = new BroadcastChannel(channelName);\n this.channel.onmessage = this.handleMessage;\n }\n\n /**\n * Sends a message via the broadcast channel to inform other tabs of session changes.\n *\n * @param {BroadcastMessage} msg - The messsage to broadcast.\n */\n post(msg: BroadcastMessage) {\n this.channel.postMessage(msg);\n }\n\n /**\n * Handles incoming messages from the broadcast channel.\n *\n * @param {MessageEvent} event - The message event containing the broadcast data.\n * @private\n */\n private handleMessage = (event: MessageEvent) => {\n const data = event.data as BroadcastMessage;\n switch (data.action) {\n case \"sessionExpired\":\n this.onSessionExpired(data);\n break;\n case \"sessionCreated\":\n this.onSessionCreated(data);\n break;\n case \"requestLeadership\":\n this.onLeadershipRequested(data);\n break;\n }\n };\n}\n","import { Listener } from \"./Listener\";\nimport { Dispatcher } from \"./Dispatcher\";\nimport { SessionClient } from \"../client/SessionClient\";\nimport { SessionState } from \"./SessionState\";\nimport { WindowActivityManager } from \"./WindowActivityManager\";\nimport { Scheduler, SessionCheckResult } from \"./Scheduler\";\nimport { SessionTokenLocation } from \"../client/HttpClient\";\nimport { SessionChannel, BroadcastMessage } from \"./SessionChannel\";\nimport { HankoOptions } from \"../../Hanko\";\n\n/**\n * A class that manages session checks, dispatches events based on session status,\n * and uses broadcast channels for inter-tab communication.\n *\n * @category SDK\n * @subcategory Internal\n * @extends Dispatcher\n * @param {string} api - The API endpoint URL.\n * @param {HankoOptions} options - The internal configuration options of the SDK.\n */\nexport class Relay extends Dispatcher {\n listener = new Listener(); // Listener for session-related events.\n private readonly checkInterval: number = 30000; // Interval for session validity checks in milliseconds.\n private readonly client: SessionClient; // Client for session validation.\n private readonly sessionState: SessionState; // Manages session-related states.\n private readonly windowActivityManager: WindowActivityManager; // Manages window activity states.\n private readonly scheduler: Scheduler; // Schedules session validity checks.\n private readonly sessionChannel: SessionChannel; // Handles inter-tab communication via broadcast channels.\n private isLoggedIn: boolean;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options: HankoOptions) {\n super();\n this.client = new SessionClient(api, options);\n\n if (options.sessionCheckInterval) {\n this.checkInterval =\n options.sessionCheckInterval < 3000\n ? 3000\n : options.sessionCheckInterval;\n }\n\n this.sessionState = new SessionState(`${options.cookieName}_session_state`);\n this.sessionChannel = new SessionChannel(\n this.getSessionCheckChannelName(\n options.sessionTokenLocation,\n options.sessionCheckChannelName,\n ),\n () => this.onChannelSessionExpired(),\n (msg) => this.onChannelSessionCreated(msg),\n () => this.onChannelLeadershipRequested(),\n );\n this.scheduler = new Scheduler(\n this.checkInterval,\n () => this.checkSession(),\n () => this.onSessionExpired(),\n );\n this.windowActivityManager = new WindowActivityManager(\n () => this.startSessionCheck(),\n () => this.scheduler.stop(),\n );\n\n const now = Date.now();\n const { expiration } = this.sessionState.load();\n\n this.isLoggedIn = now < expiration;\n this.initializeEventListeners();\n this.startSessionCheck();\n }\n\n /**\n * Sets up all event listeners and initializes session management.\n * This method is crucial for ensuring the session is monitored across all tabs.\n * @private\n */\n private initializeEventListeners(): void {\n // Listen for session creation events\n this.listener.onSessionCreated((detail) => {\n const { claims } = detail;\n const expiration = Date.parse(claims.expiration);\n const lastCheck = Date.now();\n\n this.isLoggedIn = true;\n this.sessionState.save({ expiration, lastCheck }); // Save initial session state\n this.sessionChannel.post({ action: \"sessionCreated\", claims }); // Inform other tabs\n this.startSessionCheck(); // Begin session checks now that a user is logged in\n });\n\n // Listen for user logout events\n this.listener.onUserLoggedOut(() => {\n this.isLoggedIn = false;\n this.sessionChannel.post({ action: \"sessionExpired\" }); // Inform other tabs session ended\n this.sessionState.save(null);\n this.scheduler.stop();\n });\n\n window.addEventListener(\"beforeunload\", () => this.scheduler.stop());\n }\n\n /**\n * Initiates session checking based on the last check time.\n * This method decides when the next check should occur to balance between performance and freshness.\n * @private\n */\n private startSessionCheck(): void {\n if (this.windowActivityManager.hasFocus()) {\n this.sessionChannel.post({ action: \"requestLeadership\" }); // Inform other tabs this tab is now checking\n } else {\n return;\n }\n\n if (this.scheduler.isRunning()) {\n return;\n }\n\n const { lastCheck, expiration } = this.sessionState.load();\n\n if (this.isLoggedIn) {\n this.scheduler.start(lastCheck, expiration);\n }\n }\n\n /**\n * Validates the current session and updates session information.\n * This method checks if the session is still valid and updates local data accordingly.\n * @returns {Promise<SessionCheckResult>} - A promise that resolves with the session check result.\n * @private\n */\n private async checkSession(): Promise<SessionCheckResult> {\n const lastCheck = Date.now();\n // eslint-disable-next-line camelcase\n const { is_valid, claims, expiration_time } = await this.client.validate();\n\n // eslint-disable-next-line camelcase\n const expiration = expiration_time ? Date.parse(expiration_time) : 0;\n\n // eslint-disable-next-line camelcase\n if (!is_valid && this.isLoggedIn) {\n this.dispatchSessionExpiredEvent();\n }\n\n // eslint-disable-next-line camelcase\n if (is_valid) {\n this.isLoggedIn = true;\n this.sessionState.save({ lastCheck, expiration });\n } else {\n this.isLoggedIn = false;\n this.sessionState.save(null);\n this.sessionChannel.post({ action: \"sessionExpired\" }); // Inform other tabs\n }\n\n return {\n // eslint-disable-next-line camelcase\n is_valid,\n claims,\n expiration,\n };\n }\n\n /**\n * Resets session-related states when a session expires.\n * Ensures that authentication state is cleared and an expiration event is dispatched.\n * Assumes the user is logged out by default if the session state is unknown.\n * @private\n */\n private onSessionExpired() {\n if (this.isLoggedIn) {\n this.isLoggedIn = false;\n this.sessionState.save(null);\n this.sessionChannel.post({ action: \"sessionExpired\" }); // Inform other tabs\n this.dispatchSessionExpiredEvent();\n }\n }\n\n /**\n * Handles session expired events from broadcast messages.\n * @private\n */\n private onChannelSessionExpired() {\n if (this.isLoggedIn) {\n this.isLoggedIn = false;\n this.dispatchSessionExpiredEvent();\n }\n }\n\n /**\n * Handles session creation events from broadcast messages.\n * @param {BroadcastMessage} msg - The broadcast message containing session details.\n * @private\n */\n private onChannelSessionCreated(msg: BroadcastMessage) {\n const { claims } = msg;\n const now = Date.now();\n const expiration = Date.parse(claims.expiration);\n const expirationSeconds = expiration - now;\n\n this.isLoggedIn = true;\n this.dispatchSessionCreatedEvent({\n claims,\n expirationSeconds, // deprecated\n });\n }\n\n /**\n * Handles leadership requests from other tabs.\n * @private\n */\n private onChannelLeadershipRequested() {\n if (!this.windowActivityManager.hasFocus()) {\n this.scheduler.stop();\n }\n }\n\n /**\n * Retrieves or generates the session check channel name based on the session token storage location.\n *\n * - If the `sessionTokenLocation` is `\"cookie\"`, the provided `sessionCheckChannelName` is returned as-is.\n * - If the `sessionTokenLocation` is `\"sessionStorage\"`, the function attempts to retrieve the channel name from\n * `sessionStorage`. If none is found, a new name is generated with the value of `sessionCheckChannelName` as a prefix and a random number,\n * then stored in `sessionStorage` for future use.\n *\n * @param sessionTokenLocation - Indicates where the session token is stored, either `\"cookie\"` or `\"sessionStorage\"`.\n * @param sessionCheckChannelName - The name or prefix used for the session check channel.\n * @returns The resolved session check channel name, or `undefined` if not applicable.\n * @private\n */\n private getSessionCheckChannelName(\n sessionTokenLocation: SessionTokenLocation,\n sessionCheckChannelName?: string,\n ): string | undefined {\n if (sessionTokenLocation !== \"sessionStorage\") {\n return sessionCheckChannelName;\n }\n let channelName = sessionStorage.getItem(\"sessionCheckChannelName\");\n if (\n channelName === null ||\n channelName === undefined ||\n channelName === \"\"\n ) {\n channelName = `${sessionCheckChannelName}-${\n Math.floor(Math.random() * 100) + 1\n }`;\n sessionStorage.setItem(\"sessionCheckChannelName\", channelName);\n }\n return channelName;\n }\n}\n","/**\n * A class to check the browser's WebAuthn support.\n *\n * @hideconstructor\n * @category SDK\n * @subcategory Utilities\n */\nclass WebauthnSupport {\n /**\n * Does a simple check to test for the credential management API functions we need, and an indication of\n * public key credential authentication support.\n *\n * @see https://developers.google.com/web/updates/2018/03/webauthn-credential-management\n * @return boolean\n */\n static supported(): boolean {\n return !!(\n navigator.credentials &&\n navigator.credentials.create &&\n navigator.credentials.get &&\n window.PublicKeyCredential\n );\n }\n\n /**\n * Checks whether a user-verifying platform authenticator is available.\n *\n * @return Promise<boolean>\n */\n static async isPlatformAuthenticatorAvailable(): Promise<boolean> {\n if (\n this.supported() &&\n window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable\n ) {\n return window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n }\n\n return false;\n }\n\n /**\n * Checks whether external CTAP2 security keys are supported.\n *\n * @return Promise<boolean>\n */\n static async isSecurityKeySupported(): Promise<boolean> {\n if (\n window.PublicKeyCredential !== undefined &&\n // @ts-ignore\n window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported\n ) {\n // @ts-ignore\n return window.PublicKeyCredential.isExternalCTAP2SecurityKeySupported();\n }\n\n return this.supported();\n }\n\n /**\n * Checks whether autofill assisted requests are supported.\n *\n * @return Promise<boolean>\n */\n static async isConditionalMediationAvailable(): Promise<boolean> {\n if (\n // @ts-ignore\n window.PublicKeyCredential &&\n // @ts-ignore\n window.PublicKeyCredential.isConditionalMediationAvailable\n ) {\n // @ts-ignore\n return window.PublicKeyCredential.isConditionalMediationAvailable();\n }\n\n return false;\n }\n}\n\nexport { WebauthnSupport };\n","// src/webauthn-json/base64url.ts\nfunction base64urlToBuffer(baseurl64String) {\n const padding = \"==\".slice(0, (4 - baseurl64String.length % 4) % 4);\n const base64String = baseurl64String.replace(/-/g, \"+\").replace(/_/g, \"/\") + padding;\n const str = atob(base64String);\n const buffer = new ArrayBuffer(str.length);\n const byteView = new Uint8Array(buffer);\n for (let i = 0; i < str.length; i++) {\n byteView[i] = str.charCodeAt(i);\n }\n return buffer;\n}\nfunction bufferToBase64url(buffer) {\n const byteView = new Uint8Array(buffer);\n let str = \"\";\n for (const charCode of byteView) {\n str += String.fromCharCode(charCode);\n }\n const base64String = btoa(str);\n const base64urlString = base64String.replace(/\\+/g, \"-\").replace(\n /\\//g,\n \"_\"\n ).replace(/=/g, \"\");\n return base64urlString;\n}\n\n// src/webauthn-json/convert.ts\nvar copyValue = \"copy\";\nvar convertValue = \"convert\";\nfunction convert(conversionFn, schema2, input) {\n if (schema2 === copyValue) {\n return input;\n }\n if (schema2 === convertValue) {\n return conversionFn(input);\n }\n if (schema2 instanceof Array) {\n return input.map((v) => convert(conversionFn, schema2[0], v));\n }\n if (schema2 instanceof Object) {\n const output = {};\n for (const [key, schemaField] of Object.entries(schema2)) {\n if (schemaField.derive) {\n const v = schemaField.derive(input);\n if (v !== void 0) {\n input[key] = v;\n }\n }\n if (!(key in input)) {\n if (schemaField.required) {\n throw new Error(`Missing key: ${key}`);\n }\n continue;\n }\n if (input[key] == null) {\n output[key] = null;\n continue;\n }\n output[key] = convert(\n conversionFn,\n schemaField.schema,\n input[key]\n );\n }\n return output;\n }\n}\nfunction derived(schema2, derive) {\n return {\n required: true,\n schema: schema2,\n derive\n };\n}\nfunction required(schema2) {\n return {\n required: true,\n schema: schema2\n };\n}\nfunction optional(schema2) {\n return {\n required: false,\n schema: schema2\n };\n}\n\n// src/webauthn-json/basic/schema.ts\nvar publicKeyCredentialDescriptorSchema = {\n type: required(copyValue),\n id: required(convertValue),\n transports: optional(copyValue)\n};\nvar simplifiedExtensionsSchema = {\n appid: optional(copyValue),\n appidExclude: optional(copyValue),\n credProps: optional(copyValue)\n};\nvar simplifiedClientExtensionResultsSchema = {\n appid: optional(copyValue),\n appidExclude: optional(copyValue),\n credProps: optional(copyValue)\n};\nvar credentialCreationOptions = {\n publicKey: required({\n rp: required(copyValue),\n user: required({\n id: required(convertValue),\n name: required(copyValue),\n displayName: required(copyValue)\n }),\n challenge: required(convertValue),\n pubKeyCredParams: required(copyValue),\n timeout: optional(copyValue),\n excludeCredentials: optional([publicKeyCredentialDescriptorSchema]),\n authenticatorSelection: optional(copyValue),\n attestation: optional(copyValue),\n extensions: optional(simplifiedExtensionsSchema)\n }),\n signal: optional(copyValue)\n};\nvar publicKeyCredentialWithAttestation = {\n type: required(copyValue),\n id: required(copyValue),\n rawId: required(convertValue),\n authenticatorAttachment: optional(copyValue),\n response: required({\n clientDataJSON: required(convertValue),\n attestationObject: required(convertValue),\n transports: derived(\n copyValue,\n (response) => {\n var _a;\n return ((_a = response.getTransports) == null ? void 0 : _a.call(response)) || [];\n }\n )\n }),\n clientExtensionResults: derived(\n simplifiedClientExtensionResultsSchema,\n (pkc) => pkc.getClientExtensionResults()\n )\n};\nvar credentialRequestOptions = {\n mediation: optional(copyValue),\n publicKey: required({\n challenge: required(convertValue),\n timeout: optional(copyValue),\n rpId: optional(copyValue),\n allowCredentials: optional([publicKeyCredentialDescriptorSchema]),\n userVerification: optional(copyValue),\n extensions: optional(simplifiedExtensionsSchema)\n }),\n signal: optional(copyValue)\n};\nvar publicKeyCredentialWithAssertion = {\n type: required(copyValue),\n id: required(copyValue),\n rawId: required(convertValue),\n authenticatorAttachment: optional(copyValue),\n response: required({\n clientDataJSON: required(convertValue),\n authenticatorData: required(convertValue),\n signature: required(convertValue),\n userHandle: required(convertValue)\n }),\n clientExtensionResults: derived(\n simplifiedClientExtensionResultsSchema,\n (pkc) => pkc.getClientExtensionResults()\n )\n};\nvar schema = {\n credentialCreationOptions,\n publicKeyCredentialWithAttestation,\n credentialRequestOptions,\n publicKeyCredentialWithAssertion\n};\n\n// src/webauthn-json/basic/api.ts\nfunction createRequestFromJSON(requestJSON) {\n return convert(base64urlToBuffer, credentialCreationOptions, requestJSON);\n}\nfunction createResponseToJSON(credential) {\n return convert(\n bufferToBase64url,\n publicKeyCredentialWithAttestation,\n credential\n );\n}\nasync function create(requestJSON) {\n const credential = await navigator.credentials.create(\n createRequestFromJSON(requestJSON)\n );\n return createResponseToJSON(credential);\n}\nfunction getRequestFromJSON(requestJSON) {\n return convert(base64urlToBuffer, credentialRequestOptions, requestJSON);\n}\nfunction getResponseToJSON(credential) {\n return convert(\n bufferToBase64url,\n publicKeyCredentialWithAssertion,\n credential\n );\n}\nasync function get(requestJSON) {\n const credential = await navigator.credentials.get(\n getRequestFromJSON(requestJSON)\n );\n return getResponseToJSON(credential);\n}\n\n// src/webauthn-json/basic/supported.ts\nfunction supported() {\n return !!(navigator.credentials && navigator.credentials.create && navigator.credentials.get && window.PublicKeyCredential);\n}\nexport {\n create,\n get,\n schema,\n supported\n};\n//# sourceMappingURL=webauthn-json.js.map\n","import {\n CredentialRequestOptionsJSON,\n CredentialCreationOptionsJSON,\n PublicKeyCredentialWithAssertionJSON,\n PublicKeyCredentialWithAttestationJSON,\n create,\n get,\n} from \"@github/webauthn-json\";\n\n/**\n * Manages WebAuthn credential operations as a singleton, ensuring only one active request at a time.\n * Uses an internal AbortController to cancel previous requests when a new one is initiated.\n */\nclass WebauthnManager {\n private static instance: WebauthnManager | null = null;\n private abortController = new AbortController();\n // eslint-disable-next-line no-useless-constructor,require-jsdoc\n private constructor() {}\n\n /**\n * Gets the singleton instance of WebauthnManager.\n * Creates a new instance if one doesn't exist, otherwise returns the existing one.\n * @returns {WebauthnManager} The singleton instance\n */\n public static getInstance(): WebauthnManager {\n if (!WebauthnManager.instance) {\n WebauthnManager.instance = new WebauthnManager();\n }\n return WebauthnManager.instance;\n }\n\n /**\n * Creates a new abort signal, aborting any ongoing WebAuthn request.\n * @private\n * @returns {AbortSignal} The new abort signal\n */\n private createAbortSignal(): AbortSignal {\n this.abortController.abort(); // Cancel any ongoing request\n this.abortController = new AbortController();\n return this.abortController.signal;\n }\n\n /**\n * Retrieves a WebAuthn credential using the provided options.\n * Aborts any previous request before starting a new one.\n * @param {CredentialRequestOptionsJSON} options - The options for credential retrieval\n * @returns {Promise<PublicKeyCredentialWithAssertionJSON>} A promise resolving to the retrieved credential\n * @throws {DOMException} If the WebAuthn request fails (e.g., aborted, not allowed)\n */\n public async getWebauthnCredential(\n options: CredentialRequestOptionsJSON,\n ): Promise<PublicKeyCredentialWithAssertionJSON> {\n return await get({\n ...options,\n signal: this.createAbortSignal(),\n });\n }\n\n /**\n * Retrieves a WebAuthn credential with conditional UI mediation.\n * Aborts any previous request before starting a new one.\n * @param {CredentialRequestOptionsJSON} publicKey - The public key options for conditional retrieval\n * @returns {Promise<PublicKeyCredentialWithAssertionJSON>} A promise resolving to the retrieved credential\n * @throws {DOMException} If the WebAuthn request fails (e.g., aborted, not allowed)\n */\n public async getConditionalWebauthnCredential(\n publicKey: CredentialRequestOptionsJSON[\"publicKey\"],\n ): Promise<PublicKeyCredentialWithAssertionJSON> {\n return await get({\n publicKey,\n mediation: \"conditional\" as CredentialMediationRequirement,\n signal: this.createAbortSignal(),\n });\n }\n\n /**\n * Creates a new WebAuthn credential using the provided options.\n * Aborts any previous request before starting a new one.\n * @param {CredentialCreationOptionsJSON} options - The options for credential creation\n * @returns {Promise<PublicKeyCredentialWithAttestationJSON>} A promise resolving to the created credential\n * @throws {DOMException} If the WebAuthn request fails (e.g., aborted, not allowed)\n */\n public async createWebauthnCredential(\n options: CredentialCreationOptionsJSON,\n ): Promise<PublicKeyCredentialWithAttestationJSON> {\n return await create({\n ...options,\n signal: this.createAbortSignal(),\n });\n }\n}\n\nexport default WebauthnManager;\n","import { AutoSteps } from \"./types/flow\";\nimport { WebauthnSupport } from \"../WebauthnSupport\";\nimport WebauthnManager from \"./WebauthnManager\";\nimport { CredentialCreationOptionsJSON } from \"@github/webauthn-json\";\n\n// Helper function to handle WebAuthn credential creation and error handling\n// eslint-disable-next-line require-jsdoc\nasync function handleCredentialCreation(\n state: any,\n manager: WebauthnManager,\n options: CredentialCreationOptionsJSON,\n errorCode: string = \"webauthn_credential_already_exists\",\n errorMessage: string = \"Webauthn credential already exists\",\n) {\n try {\n const attestationResponse = await manager.createWebauthnCredential(options);\n return await state.actions.webauthn_verify_attestation_response.run({\n public_key: attestationResponse,\n });\n } catch {\n const nextState = await state.actions.back.run();\n nextState.error = { code: errorCode, message: errorMessage };\n return nextState;\n }\n}\n\nexport const autoSteps: AutoSteps = {\n preflight: async (state) => {\n return await state.actions.register_client_capabilities.run({\n webauthn_available: WebauthnSupport.supported(),\n webauthn_conditional_mediation_available:\n await WebauthnSupport.isConditionalMediationAvailable(),\n webauthn_platform_authenticator_available:\n await WebauthnSupport.isPlatformAuthenticatorAvailable(),\n });\n },\n\n login_passkey: async (state) => {\n const manager = WebauthnManager.getInstance();\n try {\n const assertionResponse = await manager.getWebauthnCredential(\n state.payload.request_options,\n );\n return await state.actions.webauthn_verify_assertion_response.run({\n assertion_response: assertionResponse,\n });\n } catch {\n const nextState = await state.actions.back.run();\n if (state.error) {\n nextState.error = state.error;\n }\n return nextState;\n }\n },\n\n onboarding_verify_passkey_attestation: async (state) => {\n const manager = WebauthnManager.getInstance();\n return handleCredentialCreation(\n state,\n manager,\n state.payload.creation_options,\n );\n },\n\n webauthn_credential_verification: async (state) => {\n const manager = WebauthnManager.getInstance();\n return handleCredentialCreation(\n state,\n manager,\n state.payload.creation_options,\n );\n },\n\n async thirdparty(state) {\n const searchParams = new URLSearchParams(window.location.search);\n const token = searchParams.get(\"hanko_token\");\n const error = searchParams.get(\"error\");\n\n const updateUrl = (paramsToDelete: string[]) => {\n paramsToDelete.forEach((param) => searchParams.delete(param));\n const newSearch = searchParams.toString()\n ? `?${searchParams.toString()}`\n : \"\";\n history.replaceState(\n null,\n null,\n `${window.location.pathname}${newSearch}`,\n );\n };\n\n if (token?.length > 0) {\n updateUrl([\"hanko_token\"]);\n return await state.actions.exchange_token.run({ token });\n }\n\n if (error?.length > 0) {\n const errorCode =\n error === \"access_denied\"\n ? \"third_party_access_denied\"\n : \"technical_error\";\n const message = searchParams.get(\"error_description\");\n\n updateUrl([\"error\", \"error_description\"]);\n\n const nextState = await state.actions.back.run(null, {\n dispatchAfterStateChangeEvent: false,\n });\n\n nextState.error = { code: errorCode, message };\n nextState.dispatchAfterStateChangeEvent();\n\n return nextState;\n }\n\n if (!state.isCached) {\n state.saveToLocalStorage();\n window.location.assign(state.payload.redirect_url);\n } else {\n return await state.actions.back.run();\n }\n\n return state;\n },\n\n success: async (state) => {\n const { claims } = state.payload;\n const expirationSeconds = Date.parse(claims.expiration) - Date.now();\n state.removeFromLocalStorage();\n state.hanko.relay.dispatchSessionCreatedEvent({\n claims,\n expirationSeconds,\n });\n return state;\n },\n\n account_deleted: async (state) => {\n state.removeFromLocalStorage();\n state.hanko.relay.dispatchUserDeletedEvent();\n return state;\n },\n};\n","import { PasskeyAutofillActivationHandlers } from \"./types/flow\";\nimport WebauthnManager from \"./WebauthnManager\";\n\nexport const passkeyAutofillActivationHandlers: PasskeyAutofillActivationHandlers =\n {\n login_init: async (state) => {\n return void (async function () {\n const manager = WebauthnManager.getInstance();\n\n if (state.payload.request_options) {\n try {\n const { publicKey } = state.payload.request_options;\n\n const assertionResponse =\n await manager.getConditionalWebauthnCredential(publicKey);\n\n return await state.actions.webauthn_verify_assertion_response.run({\n assertion_response: assertionResponse,\n });\n } catch {\n // We do not need to handle the error, because this is a conditional request, which can fail silently\n return;\n }\n }\n })();\n },\n };\n","import { Hanko } from \"../../Hanko\";\nimport { Actions, Payloads, StateName } from \"./types/state\";\nimport { Input } from \"./types/input\";\nimport { FlowError } from \"./types/flowError\";\nimport { Action as ActionType } from \"./types/action\";\nimport { AnyState, FlowName, FlowResponse } from \"./types/flow\";\nimport { autoSteps } from \"./auto-steps\";\nimport { passkeyAutofillActivationHandlers } from \"./passkey-autofill-activation\";\n\nexport type AutoSteppedStates = keyof typeof autoSteps;\n\nexport type PasskeyAutofillStates =\n keyof typeof passkeyAutofillActivationHandlers;\n\nexport type AutoStepExclusion = AutoSteppedStates[] | \"all\";\n\nexport type ActionMap<TState extends StateName> = {\n [K in keyof Actions[TState]]: Action<\n Actions[TState][K] extends ActionType<infer TInputs> ? TInputs : never\n >;\n};\n\nexport type ActionInfo = {\n name: string;\n relatedStateName: StateName;\n};\n\nexport interface StateInitConfig {\n dispatchAfterStateChangeEvent?: boolean;\n excludeAutoSteps?: AutoStepExclusion;\n previousAction?: ActionInfo;\n isCached?: boolean;\n cacheKey?: string;\n}\n\nexport type StateCreateConfig = Pick<\n StateInitConfig,\n \"dispatchAfterStateChangeEvent\" | \"excludeAutoSteps\" | \"cacheKey\"\n> & {\n loadFromCache?: boolean;\n};\n\nexport type ActionRunConfig = Pick<\n StateInitConfig,\n \"dispatchAfterStateChangeEvent\"\n>;\n\ntype SerializedState = FlowResponse<any> & {\n flow_name: FlowName;\n previous_action?: ActionInfo;\n is_cached?: boolean;\n};\n\ntype ExtractInputValues<TInputs> = {\n [K in keyof TInputs]: TInputs[K] extends Input<infer TValue> ? TValue : never;\n};\n\n/**\n * Represents a state in a flow with associated actions and properties.\n * @template TState - The specific state name type.\n * @constructor\n * @param {Hanko} hanko - The Hanko instance for API interactions.\n * @param {FlowName} flowName - The name of the flow this state belongs to.\n * @param {FlowResponse<TState>} response - The flow response containing state data.\n * @param {StateInitConfig} [options={}] - Configuration options for state initialization.\n * @category SDK\n * @subcategory FlowAPI\n */\nexport class State<TState extends StateName = StateName> {\n public readonly name: TState;\n public readonly flowName: FlowName;\n public error?: FlowError;\n public readonly payload?: Payloads[TState];\n public readonly actions: ActionMap<TState>;\n public readonly csrfToken: string;\n public readonly status: number;\n public readonly previousAction?: ActionInfo;\n public readonly isCached: boolean;\n public readonly cacheKey: string;\n public readonly hanko: Hanko;\n public invokedAction?: ActionInfo;\n public readonly excludeAutoSteps: AutoStepExclusion;\n\n public readonly autoStep?: TState extends AutoSteppedStates\n ? () => Promise<AnyState>\n : never;\n public readonly passkeyAutofillActivation: TState extends PasskeyAutofillStates\n ? () => Promise<void>\n : never;\n\n /**\n * Constructs a new State instance.\n * @param {Hanko} hanko - The Hanko instance for API interactions.\n * @param {FlowName} flowName - The name of the flow this state belongs to.\n * @param {FlowResponse<TState>} response - The flow response containing state data.\n * @param {StateInitConfig} [options={}] - Configuration options for state initialization.\n */\n constructor(\n hanko: Hanko,\n flowName: FlowName,\n response: FlowResponse<TState>,\n options: StateInitConfig = {},\n ) {\n this.flowName = flowName;\n this.name = response.name;\n this.error = response.error;\n this.payload = response.payload;\n this.csrfToken = response.csrf_token;\n this.status = response.status;\n this.hanko = hanko;\n this.actions = this.buildActionMap(response.actions);\n\n if (this.name in autoSteps) {\n const handler = autoSteps[this.name as AutoSteppedStates];\n (this.autoStep as () => Promise<AnyState>) = () => handler(this as any);\n }\n\n if (this.name in passkeyAutofillActivationHandlers) {\n const handler =\n passkeyAutofillActivationHandlers[this.name as PasskeyAutofillStates];\n (this.passkeyAutofillActivation as () => Promise<void>) = () =>\n handler(this as any);\n }\n\n const {\n dispatchAfterStateChangeEvent = true,\n excludeAutoSteps = null,\n previousAction = null,\n isCached = false,\n cacheKey = \"hanko-flow-state\",\n } = options;\n\n this.excludeAutoSteps = excludeAutoSteps;\n this.previousAction = previousAction;\n this.isCached = isCached;\n this.cacheKey = cacheKey;\n\n if (dispatchAfterStateChangeEvent) {\n this.dispatchAfterStateChangeEvent();\n }\n }\n\n /**\n * Builds the action map for this state, wrapping it in a Proxy to handle undefined actions.\n * @param {Actions} actions - The actions available in this state.\n * @returns {ActionMap<TState>} The action map for the state.\n * @private\n */\n private buildActionMap(actions: Actions[TState]): ActionMap<TState> {\n const actionMap: Partial<ActionMap<TState>> = {};\n\n Object.keys(actions).forEach((actionName) => {\n const key = actionName as keyof Actions[TState];\n const action = actions[key] as ActionType<any>;\n\n actionMap[key] = new Action(action, this);\n });\n\n // Return a Proxy that handles missing keys\n return new Proxy(actionMap as ActionMap<TState>, {\n get: (target: ActionMap<TState>, prop: string | symbol): Action<any> => {\n if (prop in target) {\n return target[prop as keyof ActionMap<TState>];\n }\n\n const actionName = typeof prop === \"string\" ? prop : prop.toString();\n\n return Action.createDisabled(actionName, this);\n },\n });\n }\n\n /**\n * Dispatches an event after the state has changed.\n */\n public dispatchAfterStateChangeEvent() {\n this.hanko.relay.dispatchAfterStateChangeEvent({\n state: this as AnyState,\n });\n }\n\n /**\n * Serializes the current state into a storable format.\n * @returns {SerializedState} The serialized state object.\n */\n public serialize(): SerializedState {\n return {\n flow_name: this.flowName,\n name: this.name,\n error: this.error,\n payload: this.payload,\n csrf_token: this.csrfToken,\n status: this.status,\n previous_action: this.previousAction,\n actions: Object.fromEntries(\n (Object.entries(this.actions) as [string, Action<any>][]).map(\n ([name, action]) => [\n name,\n {\n action: action.name,\n href: action.href,\n inputs: action.inputs,\n description: null,\n },\n ],\n ),\n ),\n };\n }\n\n /**\n * Saves the current state to localStorage.\n * @returns {void}\n */\n public saveToLocalStorage(): void {\n localStorage.setItem(\n this.cacheKey,\n JSON.stringify({ ...this.serialize(), is_cached: true }),\n );\n }\n\n /**\n * Removes the current state from localStorage.\n * @returns {void}\n */\n public removeFromLocalStorage(): void {\n localStorage.removeItem(this.cacheKey);\n }\n\n /**\n * Initializes a flow state, processing auto-steps if applicable.\n * @param {Hanko} hanko - The Hanko instance for API interactions.\n * @param {FlowName} flowName - The name of the flow.\n * @param {FlowResponse<any>} response - The initial flow response.\n * @param {StateInitConfig} [options={}] - Configuration options.\n * @param {boolean} [options.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after state change.\n * @param {AutoStepExclusion} [options.excludeAutoSteps=null] - States to exclude from auto-step processing, or \"all\".\n * @param {ActionInfo} [options.previousAction=null] - Information about the previous action.\n * @param {boolean} [options.isCached=false] - Whether the state is loaded from cache.\n * @param {string} [options.cacheKey=\"hanko-flow-state\"] - Key for localStorage caching.\n * @returns {Promise<AnyState>} A promise resolving to the initialized state.\n */\n public static async initializeFlowState(\n hanko: Hanko,\n flowName: FlowName,\n response: FlowResponse<any>,\n options: StateInitConfig = {},\n ): Promise<AnyState> {\n let state = new State(hanko, flowName, response, options);\n\n if (state.excludeAutoSteps != \"all\") {\n while (\n state &&\n state.autoStep &&\n !state.excludeAutoSteps?.includes(state.name)\n ) {\n const nextState = await state.autoStep();\n if (nextState.name != state.name) {\n state = nextState;\n } else {\n return nextState;\n }\n }\n }\n\n return state;\n }\n\n /**\n * Retrieves and parses state data from localStorage.\n * @param {string} cacheKey - The key used to store the state in localStorage.\n * @returns {SerializedState | undefined} The parsed serialized state, or undefined if not found or invalid.\n */\n public static readFromLocalStorage(\n cacheKey: string,\n ): SerializedState | undefined {\n const raw = localStorage.getItem(cacheKey);\n if (raw) {\n try {\n return JSON.parse(raw) as SerializedState;\n } catch {\n return undefined;\n }\n }\n }\n\n /**\n * Creates a new state instance, using cached or fetched data.\n * @param {Hanko} hanko - The Hanko instance for API interactions.\n * @param {FlowName} flowName - The name of the flow.\n * @param {StateCreateConfig} [config={}] - Configuration options.\n * @param {boolean} [config.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after state change.\n * @param {AutoStepExclusion} [config.excludeAutoSteps=null] - States to exclude from auto-step processing, or \"all\".\n * @param {string} [config.cacheKey=\"hanko-flow-state\"] - Key for localStorage caching.\n * @param {boolean} [config.loadFromCache=true] - Whether to attempt loading from cache.\n * @returns {Promise<AnyState>} A promise resolving to the created state.\n */\n public static async create(\n hanko: Hanko,\n flowName: FlowName,\n config: StateCreateConfig = {},\n ): Promise<AnyState> {\n const { cacheKey = \"hanko-flow-state\", loadFromCache = true } = config;\n if (loadFromCache) {\n const cachedState = State.readFromLocalStorage(cacheKey);\n if (cachedState) {\n return State.deserialize(hanko, cachedState, {\n ...config,\n cacheKey,\n });\n }\n }\n\n const newState = await State.fetchState(hanko, `/${flowName}`);\n return State.initializeFlowState(hanko, flowName, newState, {\n ...config,\n cacheKey,\n });\n }\n\n /**\n * Deserializes a state from a serialized state object.\n * @param {Hanko} hanko - The Hanko instance for API interactions.\n * @param {SerializedState} serializedState - The serialized state data.\n * @param {StateCreateConfig} [config={}] - Configuration options.\n * @param {boolean} [config.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after state change.\n * @param {AutoStepExclusion} [config.excludeAutoSteps=null] - States to exclude from auto-step processing, or \"all\".\n * @param {string} [config.cacheKey=\"hanko-flow-state\"] - Key for localStorage caching.\n * @param {boolean} [config.loadFromCache=true] - Whether to attempt loading from cache.\n * @returns {Promise<AnyState>} A promise resolving to the deserialized state.\n */\n public static async deserialize(\n hanko: Hanko,\n serializedState: SerializedState,\n config: StateCreateConfig = {},\n ): Promise<AnyState> {\n return State.initializeFlowState(\n hanko,\n serializedState.flow_name,\n serializedState,\n {\n ...config,\n previousAction: serializedState.previous_action,\n isCached: serializedState.is_cached,\n },\n );\n }\n\n /**\n * Fetches state data from the server.\n * @param {Hanko} hanko - The Hanko instance for API interactions.\n * @param {string} href - The endpoint to fetch from.\n * @param {any} [body] - Optional request body.\n * @returns {Promise<FlowResponse<any>>} A promise resolving to the flow response.\n */\n static async fetchState(\n hanko: Hanko,\n href: string,\n body?: any,\n ): Promise<FlowResponse<any>> {\n try {\n const response = await hanko.client.post(href, body);\n return response.json();\n } catch (error) {\n return State.createErrorResponse(error);\n }\n }\n\n /**\n * Creates an error flow response.\n * @param {FlowError} error - The error to include in the response.\n * @returns {FlowResponse<\"error\">} A flow response with error details.\n * @private\n */\n private static createErrorResponse(error: FlowError): FlowResponse<\"error\"> {\n return {\n actions: null,\n csrf_token: \"\",\n name: \"error\",\n payload: null,\n status: 0,\n error,\n };\n }\n}\n\n/**\n * Represents an actionable operation within a state.\n * @template TInputs - The type of inputs required for the action.\n * @param {ActionType<TInputs>} action - The action type definition.\n * @param {State} parentState - The state this action belongs to.\n * @param {boolean} [enabled=true] - Whether the action is enabled.\n * @category SDK\n * @subcategory FlowAPI\n */\nexport class Action<TInputs> {\n public readonly enabled: boolean;\n public readonly href: string;\n public readonly name: string;\n public readonly inputs: TInputs;\n private readonly parentState: State;\n\n /**\n * Constructs a new Action instance.\n * @param {ActionType<TInputs>} action - The action type definition.\n * @param {State} parentState - The state this action belongs to.\n * @param {boolean} [enabled=true] - Whether the action is enabled.\n */\n constructor(\n action: ActionType<TInputs>,\n parentState: State,\n enabled: boolean = true,\n ) {\n this.enabled = enabled;\n this.href = action.href;\n this.name = action.action;\n this.inputs = action.inputs;\n this.parentState = parentState;\n }\n\n /**\n * Creates a disabled action instance.\n * @template TInputs - The type of inputs (inferred as empty).\n * @param {string} name - The name of the action.\n * @param {State} parentState - The state this action belongs to.\n * @returns {Action<TInputs>} A disabled action instance.\n */\n static createDisabled<TInputs>(\n name: string,\n parentState: State,\n ): Action<TInputs> {\n return new Action(\n {\n action: name,\n href: \"\", // No valid href since it’s disabled\n inputs: {} as TInputs,\n description: \"Disabled action\",\n },\n parentState,\n false,\n );\n }\n\n /**\n * Executes the action, transitioning to a new state.\n * @param {ExtractInputValues<TInputs>} [inputValues=null] - Values for the action's inputs.\n * @param {ActionRunConfig} [config={}] - Configuration options.\n * @param {boolean} [config.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after state change.\n * @returns {Promise<AnyState>} A promise resolving to the next state.\n * @throws {FlowError} If the action is disabled or already invoked.\n */\n async run(\n inputValues: ExtractInputValues<TInputs> = null,\n config: ActionRunConfig = {},\n ): Promise<AnyState> {\n const {\n name,\n hanko,\n flowName,\n csrfToken,\n invokedAction,\n excludeAutoSteps,\n cacheKey,\n } = this.parentState;\n const { dispatchAfterStateChangeEvent = true } = config;\n\n if (!this.enabled) {\n throw new Error(\n `Action '${this.name}' is not enabled in state '${name}'`,\n );\n }\n\n if (invokedAction) {\n throw new Error(\n `An action '${invokedAction.name}' has already been invoked on state '${invokedAction.relatedStateName}'. No further actions can be run.`,\n );\n }\n\n this.parentState.invokedAction = {\n name: this.name,\n relatedStateName: name,\n };\n\n hanko.relay.dispatchBeforeStateChangeEvent({\n state: this.parentState as AnyState,\n });\n\n // Extract default values from this.inputs\n const defaultValues = Object.keys(this.inputs).reduce(\n (acc, key) => {\n const input = (this.inputs as any)[key] as Input<any>;\n if (input.value !== undefined) {\n acc[key] = input.value;\n }\n return acc;\n },\n {} as Record<string, any>,\n );\n\n // Merge defaults with user-provided inputs\n const mergedInputData = {\n ...defaultValues,\n ...inputValues,\n };\n\n const requestBody = {\n input_data: mergedInputData,\n csrf_token: csrfToken,\n };\n\n const response = await State.fetchState(hanko, this.href, requestBody);\n\n this.parentState.removeFromLocalStorage();\n\n return State.initializeFlowState(hanko, flowName, response, {\n dispatchAfterStateChangeEvent,\n excludeAutoSteps,\n previousAction: invokedAction,\n cacheKey,\n });\n }\n}\n","import { TechnicalError, UnauthorizedError } from \"../Errors\";\nimport { Client } from \"./Client\";\nimport { User } from \"../flow-api/types/payload\";\nimport { Me } from \"../Dto\";\n\n/**\n * A class to manage user information.\n *\n * @category SDK\n * @subcategory Clients\n * @extends {Client}\n */\nclass UserClient extends Client {\n /**\n * Fetches the current user.\n *\n * @return {Promise<User>}\n * @throws {UnauthorizedError}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/IsUserAuthorized\n * @see https://docs.hanko.io/api/public#tag/User-Management/operation/listUser\n */\n async getCurrent(): Promise<User> {\n const meResponse = await this.client.get(\"/me\");\n\n if (meResponse.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!meResponse.ok) {\n throw new TechnicalError();\n }\n\n const me: Me = meResponse.json();\n const userResponse = await this.client.get(`/users/${me.id}`);\n\n if (userResponse.status === 401) {\n this.client.dispatcher.dispatchSessionExpiredEvent();\n throw new UnauthorizedError();\n } else if (!userResponse.ok) {\n throw new TechnicalError();\n }\n\n return userResponse.json();\n }\n\n /**\n * Logs out the current user and expires the existing session cookie. A valid session cookie is required to call the logout endpoint.\n *\n * @return {Promise<void>}\n * @throws {RequestTimeoutError}\n * @throws {TechnicalError}\n */\n async logout(): Promise<void> {\n const logoutResponse = await this.client.post(\"/logout\");\n\n // For cross-domain operations, the frontend SDK creates the cookie by reading the \"X-Auth-Token\" header, and\n // \"Set-Cookie\" headers sent by the backend have no effect due to the browser's security policy, which means that\n // the cookie must also be removed client-side in that case.\n this.client.sessionTokenStorage.removeSessionToken();\n this.client.cookie.removeAuthCookie();\n this.client.dispatcher.dispatchUserLoggedOutEvent();\n\n if (logoutResponse.status === 401) {\n // The user is logged out already\n return;\n } else if (!logoutResponse.ok) {\n throw new TechnicalError();\n }\n }\n}\n\nexport { UserClient };\n","import { Listener } from \"./lib/events/Listener\";\nimport { Relay } from \"./lib/events/Relay\";\nimport { Cookie, CookieSameSite } from \"./lib/Cookie\";\nimport { SessionClient } from \"./lib/client/SessionClient\";\nimport { HttpClient, SessionTokenLocation } from \"./lib/client/HttpClient\";\nimport { FlowName } from \"./lib/flow-api/types/flow\";\nimport { StateCreateConfig, State } from \"./lib/flow-api/State\";\nimport { UserClient } from \"./lib/client/UserClient\";\nimport { SessionCheckResponse } from \"./lib/Dto\";\nimport { User } from \"./lib/flow-api/types/payload\";\n\n/**\n * The options for the Hanko class\n *\n * @interface\n * @property {number=} timeout - The http request timeout in milliseconds. Defaults to 13000ms\n * @property {string=} cookieName - The name of the session cookie set from the SDK. Defaults to \"hanko\"\n * @property {string=} cookieDomain - The domain where the cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.\n * @property {string=} cookieSameSite - Specify whether/when cookies are sent with cross-site requests. Defaults to \"lax\".\n * @property {string=} localStorageKey - The prefix / name of the local storage keys. Defaults to \"hanko\"\n * @property {string=} lang - Used to convey the preferred language to the API, e.g. for translating outgoing emails.\n * It is transmitted to the API in a custom header (X-Language).\n * Should match one of the supported languages (\"bn\", \"de\", \"en\", \"fr\", \"it, \"pt-BR\", \"zh\")\n * if email delivery by Hanko is enabled. If email delivery by Hanko is disabled and the\n * relying party configures a webhook for the \"email.send\" event, then the set language is\n * reflected in the payload of the token contained in the webhook request.\n * @property {number=} sessionCheckInterval - Interval for session validity checks in milliseconds. Must be greater than 3000 (3s), defaults to 3000 otherwise.\n * @property {string=} sessionCheckChannelName - The broadcast channel name for inter-tab communication.\n * @property {string=} sessionTokenLocation - The location where the session token is stored.\n */\nexport interface HankoOptions {\n timeout?: number;\n cookieName?: string;\n cookieDomain?: string;\n cookieSameSite?: CookieSameSite;\n localStorageKey?: string;\n lang?: string;\n sessionCheckInterval?: number;\n sessionCheckChannelName?: string;\n sessionTokenLocation?: SessionTokenLocation;\n}\n\n/**\n * A class that bundles all available SDK functions.\n *\n * @extends {Listener}\n * @param {string} api - The URL of your Hanko API instance\n * @param {HankoOptions=} options - The options that can be used\n */\nclass Hanko extends Listener {\n private readonly session: SessionClient;\n private readonly user: UserClient;\n private readonly cookie: Cookie;\n public readonly client: HttpClient;\n public readonly relay: Relay;\n\n // eslint-disable-next-line require-jsdoc\n constructor(api: string, options?: HankoOptions) {\n super();\n const opts: HankoOptions = {\n timeout: 13000,\n cookieName: \"hanko\",\n localStorageKey: \"hanko\",\n sessionCheckInterval: 30000,\n sessionCheckChannelName: \"hanko-session-check\",\n ...options,\n };\n\n /**\n * @public\n * @type {Client}\n */\n this.client = new HttpClient(api, opts);\n /**\n * @public\n * @type {SessionClient}\n */\n this.session = new SessionClient(api, opts);\n /**\n * @public\n * @type {SessionClient}\n */\n this.user = new UserClient(api, opts);\n /**\n * @public\n * @type {Relay}\n */\n this.relay = new Relay(api, opts);\n /**\n * @public\n * @type {Cookie}\n */\n this.cookie = new Cookie(opts);\n }\n\n /**\n * Sets the preferred language on the underlying sub-clients. The clients'\n * base HttpClient uses this language to transmit an X-Language header to the\n * API which is then used to e.g. translate outgoing emails.\n *\n * @public\n * @param lang {string} - The preferred language to convey to the API.\n */\n setLang(lang: string) {\n this.client.lang = lang;\n }\n\n /**\n * Creates a new flow state for the specified flow.\n *\n * This method initializes a state by either loading from cache (if configured) or fetching from the server.\n * It uses the provided configuration to control caching, event dispatching, and auto-step behavior.\n *\n * @param {FlowName} flowName - The name of the flow to create a state for.\n * @param {StateCreateConfig} [config={}] - Configuration options for state creation.\n * @param {boolean} [config.dispatchAfterStateChangeEvent=true] - Whether to dispatch an event after the state changes.\n * @param {AutoStepExclusion} [config.excludeAutoSteps=null] - States to exclude from auto-step processing, or `\"all\"` to skip all auto-steps.\n * @param {string} [config.cacheKey=\"hanko-flow-state\"] - Key used for caching the state in localStorage.\n * @param {boolean} [config.loadFromCache=true] - Whether to attempt loading the state from cache.\n * @returns {Promise<AnyState>} A promise that resolves to the created flow state.\n * @category SDK\n * @subcategory FlowAPI\n */\n createState(flowName: FlowName, config: StateCreateConfig = {}) {\n return State.create(this, flowName, config);\n }\n\n /**\n * Retrieves the current user's profile information.\n *\n * @public\n * @returns {Promise<User>} A promise that resolves to the user object\n * @throws {UnauthorizedError} If the user is not authenticated\n * @throws {TechnicalError} If an unexpected error occurs\n */\n async getUser(): Promise<User> {\n return this.user.getCurrent();\n }\n\n /**\n * Validates the current session.\n *\n * @public\n * @returns {Promise<SessionCheckResponse>} A promise that resolves to the session check response\n */\n async validateSession(): Promise<SessionCheckResponse> {\n return this.session.validate();\n }\n\n /**\n * Retrieves the current session token from the authentication cookie.\n *\n * @public\n * @returns {string} The session token\n */\n getSessionToken(): string {\n return this.cookie.getAuthCookie();\n }\n\n /**\n * Logs out the current user by invalidating the session.\n *\n * @public\n * @returns {Promise<void>} A promise that resolves when the logout is complete\n */\n async logout(): Promise<void> {\n return this.user.logout();\n }\n}\n\nexport { Hanko };\n"],"names":["Throttle","throttle","func","wait","options","context","args","timeoutID","_options$leading","leading","_options$trailing","trailing","previous","Date","now","apply","remaining","this","window","clearTimeout","setTimeout","executeThrottledFunction","sessionCreatedType","sessionExpiredType","userLoggedOutType","flowAfterStateChangeType","CustomEventWithDetail","_CustomEvent","type","detail","call","_inheritsLoose","CustomEvent","Listener","throttleLimit","_addEventListener","document","addEventListener","bind","_removeEventListener","removeEventListener","_throttle","wrapCallback","callback","wrappedCallback","event","_proto","addEventListenerWithType","_ref","_ref$once","once","_ref$throttle","_this","mapAddEventListenerParams","_ref2","params","onSessionCreated","onSessionExpired","onUserLoggedOut","onUserDeleted","userDeletedType","onAfterStateChange","onBeforeStateChange","flowBeforeStateChangeType","Dispatcher","_dispatchEvent","dispatchEvent","dispatch","dispatchSessionCreatedEvent","dispatchSessionExpiredEvent","dispatchUserLoggedOutEvent","dispatchUserDeletedEvent","dispatchAfterStateChangeEvent","dispatchBeforeStateChangeEvent","HankoError","_Error","message","code","cause","Object","setPrototypeOf","prototype","Error","TechnicalError","_HankoError","_this2","_assertThisInitialized","ConflictError","_HankoError2","userID","_this3","RequestTimeoutError","_this4","_HankoError3","_HankoError4","WebauthnRequestCancelledError","_this5","InvalidPasswordError","_HankoError5","_this6","InvalidPasscodeError","_HankoError6","_this7","InvalidWebauthnCredentialError","_HankoError7","_this8","PasscodeExpiredError","_HankoError8","_this9","MaxNumOfPasscodeAttemptsReachedError","_HankoError9","_this10","NotFoundError","_this11","_HankoError10","_HankoError11","TooManyRequestsError","retryAfter","_this12","UnauthorizedError","_HankoError12","_this13","ForbiddenError","_HankoError13","_this14","UserVerificationError","_HankoError14","_this15","MaxNumOfEmailAddressesReachedError","_HankoError15","_this16","EmailAddressAlreadyExistsError","_HankoError16","_this17","ThirdPartyError","_this18","_HankoError17","assign","target","i","arguments","length","source","key","api","init","converter","defaultAttributes","set","name","value","attributes","expires","toUTCString","encodeURIComponent","replace","decodeURIComponent","escape","stringifiedAttributes","attributeName","split","cookie","write","create","get","cookies","jar","parts","slice","join","found","read","e","remove","withAttributes","withConverter","freeze","path","Cookie","_options$cookieName","_options$cookieSameSi","authCookieName","authCookieDomain","authCookieSameSite","cookieName","cookieDomain","cookieSameSite","getAuthCookie","JSCookie","setAuthCookie","token","defaults","secure","sameSite","undefined","domain","o","removeAuthCookie","SessionStorage","keyName","getSessionToken","sessionStorage","getItem","setSessionToken","setItem","removeSessionToken","removeItem","Headers","xhr","_xhr","getResponseHeader","Response","headers","ok","status","statusText","url","_decodedJSON","responseURL","_proto2","json","JSON","parse","response","parseNumericHeader","result","parseInt","isNaN","HttpClient","timeout","dispatcher","sessionTokenStorage","lang","sessionTokenLocation","_options$timeout","_proto3","_fetch","XMLHttpRequest","bearerToken","getAuthToken","Promise","resolve","reject","open","method","setRequestHeader","withCredentials","onload","self","processHeaders","onerror","ontimeout","send","body","toString","jwt","expirationSeconds","getAllResponseHeaders","forEach","h","header","toLowerCase","startsWith","retention","https","RegExp","match","location","href","getTime","setAuthToken","post","stringify","put","patch","Client","client","validate","SessionClient","SessionState","storageKey","defaultState","expiration","lastCheck","load","item","localStorage","save","session","WindowActivityManager","onActivityCallback","onInactivityCallback","handleFocus","handleBlur","handleVisibilityChange","visibilityState","hasFocus","Scheduler","checkInterval","checkSession","intervalID","scheduleSessionExpiry","timeToExpiration","stop","start","timeToNextCheck","calcTimeToNextCheck","sessionExpiresSoon","is_valid","setInterval","then","_this2$checkSession","_catch","console","log","clearInterval","isRunning","timeSinceLastCheck","SessionChannel","channelName","onLeadershipRequested","channel","handleMessage","data","action","BroadcastChannel","onmessage","msg","postMessage","_Dispatcher","Relay","listener","sessionState","windowActivityManager","scheduler","sessionChannel","isLoggedIn","sessionCheckInterval","getSessionCheckChannelName","sessionCheckChannelName","onChannelSessionExpired","onChannelSessionCreated","onChannelLeadershipRequested","startSessionCheck","_this$sessionState$lo","initializeEventListeners","claims","_this$sessionState$lo2","expiration_time","Math","floor","random","WebauthnSupport","supported","navigator","credentials","PublicKeyCredential","isPlatformAuthenticatorAvailable","isUserVerifyingPlatformAuthenticatorAvailable","isSecurityKeySupported","isExternalCTAP2SecurityKeySupported","isConditionalMediationAvailable","base64urlToBuffer","baseurl64String","padding","base64String","str","atob","buffer","ArrayBuffer","byteView","Uint8Array","charCodeAt","bufferToBase64url","charCode","String","fromCharCode","btoa","copyValue","convertValue","convert","conversionFn","schema2","input","Array","map","v","output","schemaField","entries","derive","schema","required","derived","optional","publicKeyCredentialDescriptorSchema","id","transports","simplifiedExtensionsSchema","appid","appidExclude","credProps","simplifiedClientExtensionResultsSchema","credentialCreationOptions","publicKey","rp","user","displayName","challenge","pubKeyCredParams","excludeCredentials","authenticatorSelection","attestation","extensions","signal","publicKeyCredentialWithAttestation","rawId","authenticatorAttachment","clientDataJSON","attestationObject","_a","getTransports","clientExtensionResults","pkc","getClientExtensionResults","credentialRequestOptions","mediation","rpId","allowCredentials","userVerification","publicKeyCredentialWithAssertion","authenticatorData","signature","userHandle","async","requestJSON","credential","getRequestFromJSON","getResponseToJSON","WebauthnManager","abortController","AbortController","getInstance","instance","createAbortSignal","abort","getWebauthnCredential","getConditionalWebauthnCredential","createWebauthnCredential","createRequestFromJSON","handleCredentialCreation","state","manager","errorCode","errorMessage","attestationResponse","actions","webauthn_verify_attestation_response","run","public_key","back","nextState","error","autoSteps","preflight","register_client_capabilities","_state$actions$regist2","_WebauthnSupport$isPl","_run","webauthn_available","_WebauthnSupport$supp","webauthn_conditional_mediation_available","_WebauthnSupport$isCo","webauthn_platform_authenticator_available","login_passkey","payload","request_options","assertionResponse","webauthn_verify_assertion_response","assertion_response","onboarding_verify_passkey_attestation","creation_options","webauthn_credential_verification","thirdparty","_temp5","_result","_exit2","_exit","_temp3","_result2","_exit3","_temp","isCached","saveToLocalStorage","redirect_url","_temp2","searchParams","updateUrl","search","paramsToDelete","param","newSearch","history","replaceState","pathname","_temp4","exchange_token","success","removeFromLocalStorage","hanko","relay","account_deleted","passkeyAutofillActivationHandlers","login_init","pact","s","_Pact","_settle","observer","onFulfilled","onRejected","State","flowName","csrfToken","previousAction","cacheKey","invokedAction","excludeAutoSteps","autoStep","passkeyAutofillActivation","csrf_token","buildActionMap","handler","_handler","_options$dispatchAfte","_options$previousActi","_options$isCached","_options$cacheKey","_options$excludeAutoS","actionMap","keys","actionName","Action","Proxy","prop","createDisabled","serialize","flow_name","previous_action","fromEntries","inputs","description","_extends","is_cached","initializeFlowState","test","update","stage","shouldContinue","_isSettledPact","updateValue","_resumeAfterUpdate","_resumeAfterTest","_resumeAfterBody","_for","_state$excludeAutoSte","includes","readFromLocalStorage","raw","_unused","config","_config$cacheKey","_config$loadFromCache","loadFromCache","cachedState","deserialize","fetchState","newState","serializedState","createErrorResponse","parentState","enabled","inputValues","_this3$parentState","_config2$dispatchAfte","relatedStateName","mergedInputData","defaultValues","reduce","acc","input_data","getCurrent","meResponse","me","userResponse","logout","logoutResponse","Hanko","_Listener","opts","localStorageKey","UserClient","setLang","createState","getUser","validateSession"],"mappings":"6lDAyBaA,IAAAA,wCAoEV,SAzDMC,SAAP,SACEC,EACAC,EACAC,YAAAA,IAAAA,EAA2B,CAAE,GAE7B,IACgBC,EACHC,EACQC,EAH8BC,EAAPJ,EAApCK,QAAAA,cAAcD,EAAAE,EAAsBN,EAApBO,SAAAA,cAAeD,EAI3BE,EAAG,I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