diff --git a/examples/with-next-ssr-app-directory/.env b/examples/with-next-ssr-app-directory/.env new file mode 100644 index 000000000..4aa149a95 --- /dev/null +++ b/examples/with-next-ssr-app-directory/.env @@ -0,0 +1,5 @@ +NEXT_PUBLIC_SUPERTOKENS_APP_NAME=test +NEXT_PUBLIC_SUPERTOKENS_API_DOMAIN=http://localhost:3000 +NEXT_PUBLIC_SUPERTOKENS_WEBSITE_DOMAIN=http://localhost:3000 +NEXT_PUBLIC_SUPERTOKENS_API_BASE_PATH=/api/auth +NEXT_PUBLIC_SUPERTOKENS_WEBSITE_BASE_PATH=/auth diff --git a/examples/with-next-ssr-app-directory/.eslintrc.json b/examples/with-next-ssr-app-directory/.eslintrc.json new file mode 100644 index 000000000..1c2aa65d7 --- /dev/null +++ b/examples/with-next-ssr-app-directory/.eslintrc.json @@ -0,0 +1,3 @@ +{ + "extends": "next/core-web-vitals" +} diff --git a/examples/with-next-ssr-app-directory/.gitignore b/examples/with-next-ssr-app-directory/.gitignore new file mode 100644 index 000000000..d22ad7987 --- /dev/null +++ b/examples/with-next-ssr-app-directory/.gitignore @@ -0,0 +1,38 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# local env files +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts + +# VSCode +.vscode diff --git a/examples/with-next-ssr-app-directory/README.md b/examples/with-next-ssr-app-directory/README.md new file mode 100644 index 000000000..f552de67b --- /dev/null +++ b/examples/with-next-ssr-app-directory/README.md @@ -0,0 +1,42 @@ +# SuperTokens App with Next.js app directory + +This is a simple application that is protected by SuperTokens. This app uses the Next.js app directory. + +## How to use + +### Using `create-next-app` + +- Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example: + +```bash +npx create-next-app --example with-supertokens with-supertokens-app +``` + +```bash +yarn create next-app --example with-supertokens with-supertokens-app +``` + +```bash +pnpm create next-app --example with-supertokens with-supertokens-app +``` + +- Run `yarn install` + +- Run `npm run dev` to start the application on `http://localhost:3000`. + +### Using `create-supertokens-app` + +- Run the following command + +```bash +npx create-supertokens-app@latest --frontend=next +``` + +- Select the option to use the app directory + +Follow the instructions after `create-supertokens-app` has finished + +## Notes + +- To know more about how this app works and to learn how to customise it based on your use cases refer to the [SuperTokens Documentation](https://supertokens.com/docs/guides) +- We have provided development OAuth keys for the various built-in third party providers in the `/app/config/backend.ts` file. Feel free to use them for development purposes, but **please create your own keys for production use**. diff --git a/examples/with-next-ssr-app-directory/app/actions/serverActionThatLoadsTheSession.ts b/examples/with-next-ssr-app-directory/app/actions/serverActionThatLoadsTheSession.ts new file mode 100644 index 000000000..d6e104ad3 --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/actions/serverActionThatLoadsTheSession.ts @@ -0,0 +1,21 @@ +"use server"; + +import { cookies } from "next/headers"; +import { getServerActionSession, init } from "supertokens-auth-react/nextjs/ssr"; +import { ssrConfig } from "../config/ssr"; + +init(ssrConfig()); + +export async function serverActionThatLoadsTheSession() { + const cookiesStore = await cookies(); + const { status, session } = await getServerActionSession(cookiesStore); + if (status !== "valid") { + // User is not authenticated return early or throw an error + return; + } + + // Perform the authenticated action + const userId = session.userId; + console.log("userId", userId); + return Promise.resolve(true); +} diff --git a/examples/with-next-ssr-app-directory/app/api/auth/[...path]/route.ts b/examples/with-next-ssr-app-directory/app/api/auth/[...path]/route.ts new file mode 100644 index 000000000..a6ed0b8de --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/api/auth/[...path]/route.ts @@ -0,0 +1,161 @@ +import { getAppDirRequestHandler } from "supertokens-node/nextjs"; +import Session, { refreshSessionWithoutRequestResponse } from "supertokens-node/recipe/session"; +import { NextRequest, NextResponse } from "next/server"; +import { ensureSuperTokensInit } from "../../../config/backend"; +import { cookies } from "next/headers"; + +ensureSuperTokensInit(); + +const handleCall = getAppDirRequestHandler(); + +// input +// { refreshSessionWithoutRequestResponse } +// async function +// + +export async function GET(request: NextRequest) { + if (request.method === "GET" && request.url.includes("/session/refresh")) { + return refreshSession(request); + } + const res = await handleCall(request); + if (!res.headers.has("Cache-Control")) { + // This is needed for production deployments with Vercel + res.headers.set("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); + } + return res; +} + +export async function POST(request: NextRequest) { + return handleCall(request); +} + +export async function DELETE(request: NextRequest) { + return handleCall(request); +} + +export async function PUT(request: NextRequest) { + return handleCall(request); +} + +export async function PATCH(request: NextRequest) { + return handleCall(request); +} + +export async function HEAD(request: NextRequest) { + return handleCall(request); +} + +const refreshTokenCookieName = "sRefreshToken"; +const refreshTokenHeaderName = "st-refresh-token"; +async function refreshSession(request: NextRequest) { + console.log("Attempting session refresh"); + const cookiesFromReq = await cookies(); + + const refreshToken = + request.cookies.get(refreshTokenCookieName)?.value || request.headers.get(refreshTokenHeaderName); + if (!refreshToken) { + return NextResponse.redirect(new URL("/auth", request.url)); + } + + const redirectTo = new URL("/", request.url); + + try { + const refreshResponse = await fetch(`http://localhost:3000/api/auth/session/refresh`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Cookie: `sRefreshToken=${refreshToken}`, + }, + credentials: "include", + }); + // console.log("Performed session refresh request"); + // console.log(refreshResponse); + // console.log(refreshResponse.headers); + // console.log(await refreshResponse.text()); + + const setCookieHeaders = refreshResponse.headers.getSetCookie(); + const frontToken = refreshResponse.headers.get("front-token"); + if (!frontToken) { + return NextResponse.redirect(new URL("/auth", request.url)); + } + + // TODO: Check for csrf token + if (!setCookieHeaders.length) { + return NextResponse.redirect(new URL("/auth", request.url)); + } + + const response = NextResponse.redirect(redirectTo); + let sAccessToken: string | null = null; + let sRefreshToken: string | null = null; + for (const header of setCookieHeaders) { + if (header.includes("sAccessToken")) { + const match = header.match(/sAccessToken=([^;]+)/); + sAccessToken = match ? match[1] : null; + } + if (header.includes("sRefreshToken")) { + const match = header.match(/sRefreshToken=([^;]+)/); + sRefreshToken = match ? match[1] : null; + } + response.headers.append("set-cookie", header); + } + + response.headers.append("set-cookie", `sFrontToken=${frontToken}`); + response.headers.append("front-token", frontToken); + response.headers.append("frontToken", frontToken); + if (sAccessToken) { + response.headers.append("sAccessToken", sAccessToken); + + cookiesFromReq.set("sAccessToken", sAccessToken); + } + if (sRefreshToken) { + response.headers.append("sRefreshToken", sRefreshToken); + + cookiesFromReq.set("sRefreshToken", sRefreshToken); + } + + cookiesFromReq.set("sFrontToken", frontToken); + + // console.log(sAccessToken, sRefreshToken); + + return response; + } catch (err) { + console.error("Error refreshing session"); + console.error(err); + return NextResponse.redirect(new URL("/auth", request.url)); + } +} + +// async function saveTokensFromHeaders(response: Response) { +// logDebugMessage("saveTokensFromHeaders: Saving updated tokens from the response headers"); +// +// const refreshToken = response.headers.get("st-refresh-token"); +// if (refreshToken !== null) { +// logDebugMessage("saveTokensFromHeaders: saving new refresh token"); +// await setToken("refresh", refreshToken); +// } +// +// const accessToken = response.headers.get("st-access-token"); +// if (accessToken !== null) { +// logDebugMessage("saveTokensFromHeaders: saving new access token"); +// await setToken("access", accessToken); +// } +// +// const frontToken = response.headers.get("front-token"); +// if (frontToken !== null) { +// logDebugMessage("saveTokensFromHeaders: Setting sFrontToken: " + frontToken); +// await FrontToken.setItem(frontToken); +// updateClockSkewUsingFrontToken({ frontToken, responseHeaders: response.headers }); +// } +// const antiCsrfToken = response.headers.get("anti-csrf"); +// if (antiCsrfToken !== null) { +// // At this point, the session has either been newly created or refreshed. +// // Thus, there's no need to call getLocalSessionState with tryRefresh: true. +// // Calling getLocalSessionState with tryRefresh: true will cause a refresh loop +// // if cookie writes are disabled. +// const tok = await getLocalSessionState(false); +// if (tok.status === "EXISTS") { +// logDebugMessage("saveTokensFromHeaders: Setting anti-csrf token"); +// await AntiCsrfToken.setItem(tok.lastAccessTokenUpdate, antiCsrfToken); +// } +// } +// } diff --git a/examples/with-next-ssr-app-directory/app/api/user/route.ts b/examples/with-next-ssr-app-directory/app/api/user/route.ts new file mode 100644 index 000000000..c052e571f --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/api/user/route.ts @@ -0,0 +1,23 @@ +import { ensureSuperTokensInit } from "@/app/config/backend"; +import { NextResponse, NextRequest } from "next/server"; +import { withSession } from "supertokens-node/nextjs"; + +ensureSuperTokensInit(); + +export function GET(request: NextRequest) { + return withSession(request, async (err, session) => { + if (err) { + return NextResponse.json(err, { status: 500 }); + } + if (!session) { + return new NextResponse("Authentication required", { status: 401 }); + } + + return NextResponse.json({ + note: "Fetch any data from your application for authenticated user after using verifySession middleware", + userId: session.getUserId(), + sessionHandle: session.getHandle(), + accessTokenPayload: session.getAccessTokenPayload(), + }); + }); +} diff --git a/examples/with-next-ssr-app-directory/app/auth/[[...path]]/page.tsx b/examples/with-next-ssr-app-directory/app/auth/[[...path]]/page.tsx new file mode 100644 index 000000000..ab603bd1e --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/auth/[[...path]]/page.tsx @@ -0,0 +1,27 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { redirectToAuth } from "supertokens-auth-react"; +import SuperTokens from "supertokens-auth-react/ui"; +import { PreBuiltUIList } from "../../config/frontend"; + +export default function Auth() { + // if the user visits a page that is not handled by us (like /auth/random), then we redirect them back to the auth page. + const [loaded, setLoaded] = useState(false); + + console.log("running this"); + + useEffect(() => { + if (SuperTokens.canHandleRoute(PreBuiltUIList) === false) { + redirectToAuth({ redirectBack: false }); + } else { + setLoaded(true); + } + }, []); + + if (loaded) { + return SuperTokens.getRoutingComponent(PreBuiltUIList); + } + + return null; +} diff --git a/examples/with-next-ssr-app-directory/app/components/callApiButton.tsx b/examples/with-next-ssr-app-directory/app/components/callApiButton.tsx new file mode 100644 index 000000000..cd3aa30bb --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/components/callApiButton.tsx @@ -0,0 +1,17 @@ +"use client"; + +import styles from "../page.module.css"; + +export const CallAPIButton = () => { + const fetchUserData = async () => { + const userInfoResponse = await fetch("http://localhost:3000/api/user"); + + alert(JSON.stringify(await userInfoResponse.json())); + }; + + return ( +
+ Call API +
+ ); +}; diff --git a/examples/with-next-ssr-app-directory/app/components/home.tsx b/examples/with-next-ssr-app-directory/app/components/home.tsx new file mode 100644 index 000000000..bd0d52e46 --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/components/home.tsx @@ -0,0 +1,47 @@ +import { cookies, headers } from "next/headers"; +import styles from "../page.module.css"; +import { redirect } from "next/navigation"; +import Image from "next/image"; +import { CelebrateIcon, SeparatorLine } from "../../assets/images"; +import { CallAPIButton } from "./callApiButton"; +import { LinksComponent } from "./linksComponent"; +import { SessionAuthForNextJS } from "./sessionAuthForNextJS"; + +import { getServerComponentSession, init } from "supertokens-auth-react/nextjs/ssr"; +import { ssrConfig } from "../config/ssr"; +import { useState } from "react"; +import { MiddlewareServerActionButton } from "./middlewareServerActionButton"; +import { ServerActionButton } from "./serverActionButton"; + +init(ssrConfig()); + +export async function HomePage() { + const cookiesStore = await cookies(); + const session = await getServerComponentSession(cookiesStore); + console.log(session.userId); + + /** + * SessionAuthForNextJS will handle proper redirection for the user based on the different session states. + * It will redirect to the login page if the session does not exist etc. + */ + return ( + +
+
+
+ Login successful Login + successful +
+
+
Your userID is:
+
{session.userId}
+ + +
+
+ + separator +
+
+ ); +} diff --git a/examples/with-next-ssr-app-directory/app/components/linksComponent.tsx b/examples/with-next-ssr-app-directory/app/components/linksComponent.tsx new file mode 100644 index 000000000..2c29291d8 --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/components/linksComponent.tsx @@ -0,0 +1,64 @@ +"use client"; +import styles from "../page.module.css"; +import { BlogsIcon, GuideIcon, SignOutIcon } from "../../assets/images"; +import { recipeDetails } from "../config/frontend"; +import Link from "next/link"; +import Image from "next/image"; +import Session from "supertokens-auth-react/recipe/session"; +import SuperTokens from "supertokens-auth-react"; + +const SignOutLink = (props: { name: string; link: string; icon: string }) => { + return ( +
{ + await Session.signOut(); + SuperTokens.redirectToAuth(); + }} + > + {props.name} +
{props.name}
+
+ ); +}; + +export const LinksComponent = () => { + const links: { + name: string; + link: string; + icon: string; + }[] = [ + { + name: "Blogs", + link: "https://supertokens.com/blog", + icon: BlogsIcon, + }, + { + name: "Guides", + link: recipeDetails.docsLink, + icon: GuideIcon, + }, + { + name: "Sign Out", + link: "", + icon: SignOutIcon, + }, + ]; + + return ( +
+ {links.map((link) => { + if (link.name === "Sign Out") { + return ; + } + + return ( + + {link.name} +
{link.name}
+ + ); + })} +
+ ); +}; diff --git a/examples/with-next-ssr-app-directory/app/components/serverActionButton.tsx b/examples/with-next-ssr-app-directory/app/components/serverActionButton.tsx new file mode 100644 index 000000000..318c1de50 --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/components/serverActionButton.tsx @@ -0,0 +1,23 @@ +"use client"; + +import { serverActionThatLoadsTheSession } from "../actions/serverActionThatLoadsTheSession"; +import { confirmAuthenticationAndCallServerAction, init } from "supertokens-auth-react/nextjs/ssr"; +import styles from "../page.module.css"; +import { ssrConfig } from "../config/ssr"; + +init(ssrConfig()); + +export const ServerActionButton = () => { + return ( +
{ + // The wrapper function ensures that the user is authenticated before calling the server action + const result = await confirmAuthenticationAndCallServerAction(serverActionThatLoadsTheSession); + }} + className={styles.sessionButton} + > + Call Server Action +
+ ); +}; diff --git a/examples/with-next-ssr-app-directory/app/components/sessionAuthForNextJS.tsx b/examples/with-next-ssr-app-directory/app/components/sessionAuthForNextJS.tsx new file mode 100644 index 000000000..721aff640 --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/components/sessionAuthForNextJS.tsx @@ -0,0 +1,19 @@ +"use client"; + +import React, { useState, useEffect } from "react"; +import { SessionAuth } from "supertokens-auth-react/recipe/session"; + +type Props = Parameters[0] & { + children?: React.ReactNode | undefined; +}; + +export const SessionAuthForNextJS = (props: Props) => { + const [loaded, setLoaded] = useState(false); + useEffect(() => { + setLoaded(true); + }, []); + if (!loaded) { + return props.children; + } + return {props.children}; +}; diff --git a/examples/with-next-ssr-app-directory/app/components/supertokensProvider.tsx b/examples/with-next-ssr-app-directory/app/components/supertokensProvider.tsx new file mode 100644 index 000000000..c0a0c7a89 --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/components/supertokensProvider.tsx @@ -0,0 +1,18 @@ +"use client"; +import React from "react"; +import { SuperTokensWrapper } from "supertokens-auth-react"; +import SuperTokensReact from "supertokens-auth-react"; +import { frontendConfig, setRouter } from "../config/frontend"; +import { usePathname, useRouter } from "next/navigation"; + +if (typeof window !== "undefined") { + // we only want to call this init function on the frontend, so we check typeof window !== 'undefined' + SuperTokensReact.init(frontendConfig()); +} else { +} + +export const SuperTokensProvider: React.FC> = ({ children }) => { + setRouter(useRouter(), usePathname() || window.location.pathname); + + return {children}; +}; diff --git a/examples/with-next-ssr-app-directory/app/components/tryRefreshClientComponent.tsx b/examples/with-next-ssr-app-directory/app/components/tryRefreshClientComponent.tsx new file mode 100644 index 000000000..2c8b0f1d8 --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/components/tryRefreshClientComponent.tsx @@ -0,0 +1,31 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import Session from "supertokens-auth-react/recipe/session"; +import SuperTokens from "supertokens-auth-react"; + +export const TryRefreshComponent = () => { + const router = useRouter(); + const [didError, setDidError] = useState(false); + + useEffect(() => { + void Session.attemptRefreshingSession() + .then((hasSession) => { + if (hasSession) { + router.refresh(); + } else { + SuperTokens.redirectToAuth(); + } + }) + .catch(() => { + setDidError(true); + }); + }, [router]); + + if (didError) { + return
Something went wrong, please reload the page
; + } + + return
Loading...
; +}; diff --git a/examples/with-next-ssr-app-directory/app/config/appInfo.ts b/examples/with-next-ssr-app-directory/app/config/appInfo.ts new file mode 100644 index 000000000..a1927699b --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/config/appInfo.ts @@ -0,0 +1,7 @@ +export const appInfo = { + appName: "SuperTokens Next.js demo app", + apiDomain: "http://localhost:3333", + websiteDomain: "http://localhost:3333", + apiBasePath: "/api/auth", + websiteBasePath: "/auth", +}; diff --git a/examples/with-next-ssr-app-directory/app/config/backend.ts b/examples/with-next-ssr-app-directory/app/config/backend.ts new file mode 100644 index 000000000..70bf5fb3f --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/config/backend.ts @@ -0,0 +1,104 @@ +import EmailPasswordNode from "supertokens-node/recipe/emailpassword"; +import ThirdPartyNode from "supertokens-node/recipe/thirdparty"; +import PasswordlessNode from "supertokens-node/recipe/passwordless"; +import SessionNode from "supertokens-node/recipe/session"; +import Dashboard from "supertokens-node/recipe/dashboard"; +import UserRoles from "supertokens-node/recipe/userroles"; +import { appInfo } from "./appInfo"; +import { TypeInput } from "supertokens-node/types"; +import SuperTokens from "supertokens-node"; + +export let backendConfig = (): TypeInput => { + return { + // debug: true, + supertokens: { + // this is the location of the SuperTokens core. + // connectionURI: "https://st-dev-bc3c6f90-79ba-11ef-ab9e-9bd286159eeb.aws.supertokens.io", + connectionURI: "http://localhost:3567", + // apiKey: "e9zZOI7yJ0-G6gms7iGKZ17Pb-", + }, + appInfo, + // recipeList contains all the modules that you want to + // use from SuperTokens. See the full list here: https://supertokens.com/docs/guides + recipeList: [ + EmailPasswordNode.init(), + ThirdPartyNode.init({ + signInAndUpFeature: { + providers: [ + // We have provided you with development keys which you can use for testing. + // IMPORTANT: Please replace them with your own OAuth keys for production use. + { + config: { + thirdPartyId: "google", + clients: [ + { + clientId: + "1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com", + clientSecret: "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", + }, + ], + }, + }, + { + config: { + thirdPartyId: "github", + clients: [ + { + clientId: "467101b197249757c71f", + clientSecret: "e97051221f4b6426e8fe8d51486396703012f5bd", + }, + ], + }, + }, + { + config: { + thirdPartyId: "apple", + clients: [ + { + clientId: "4398792-io.supertokens.example.service", + additionalConfig: { + keyId: "7M48Y4RYDL", + privateKey: + "-----BEGIN PRIVATE KEY-----\nMIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgu8gXs+XYkqXD6Ala9Sf/iJXzhbwcoG5dMh1OonpdJUmgCgYIKoZIzj0DAQehRANCAASfrvlFbFCYqn3I2zeknYXLwtH30JuOKestDbSfZYxZNMqhF/OzdZFTV0zc5u5s3eN+oCWbnvl0hM+9IW0UlkdA\n-----END PRIVATE KEY-----", + teamId: "YWQCXGJRJL", + }, + }, + ], + }, + }, + { + config: { + thirdPartyId: "twitter", + clients: [ + { + clientId: "4398792-WXpqVXRiazdRMGNJdEZIa3RVQXc6MTpjaQ", + clientSecret: "BivMbtwmcygbRLNQ0zk45yxvW246tnYnTFFq-LH39NwZMxFpdC", + }, + ], + }, + }, + ], + }, + }), + PasswordlessNode.init({ + contactMethod: "EMAIL_OR_PHONE", + flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", + }), + SessionNode.init({ + getTokenTransferMethod: () => "header", + }), + Dashboard.init(), + UserRoles.init(), + ], + isInServerlessEnv: true, + framework: "custom", + }; +}; + +let initialized = false; +export function ensureSuperTokensInit() { + if (!initialized) { + SuperTokens.init(backendConfig()); + initialized = true; + } +} diff --git a/examples/with-next-ssr-app-directory/app/config/frontend.tsx b/examples/with-next-ssr-app-directory/app/config/frontend.tsx new file mode 100644 index 000000000..deec8569e --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/config/frontend.tsx @@ -0,0 +1,59 @@ +import EmailPasswordReact from "supertokens-auth-react/recipe/emailpassword"; +import ThirdPartyReact from "supertokens-auth-react/recipe/thirdparty"; +import PasswordlessReact from "supertokens-auth-react/recipe/passwordless"; +import Session from "supertokens-auth-react/recipe/session"; +import { appInfo } from "./appInfo"; +import { useRouter } from "next/navigation"; +import { SuperTokensConfig } from "supertokens-auth-react/lib/build/types"; +import { ThirdPartyPreBuiltUI } from "supertokens-auth-react/recipe/thirdparty/prebuiltui"; +import { PasswordlessPreBuiltUI } from "supertokens-auth-react/recipe/passwordless/prebuiltui"; +import { EmailPasswordPreBuiltUI } from "supertokens-auth-react/recipe/emailpassword/prebuiltui"; + +const routerInfo: { router?: ReturnType; pathName?: string } = {}; + +export function setRouter(router: ReturnType, pathName: string) { + routerInfo.router = router; + routerInfo.pathName = pathName; +} + +export const frontendConfig = (): SuperTokensConfig => { + return { + appInfo, + // enableDebugLogs: true, + recipeList: [ + EmailPasswordReact.init(), + ThirdPartyReact.init({ + signInAndUpFeature: { + providers: [ + ThirdPartyReact.Github.init(), + ThirdPartyReact.Google.init(), + ThirdPartyReact.Apple.init(), + ], + }, + }), + PasswordlessReact.init({ + contactMethod: "EMAIL_OR_PHONE", + }), + Session.init({ + // tokenTransferMethod: "header" + }), + ], + windowHandler: (orig) => { + return { + ...orig, + location: { + ...orig.location, + getPathName: () => routerInfo.pathName!, + assign: (url) => routerInfo.router!.push(url.toString()), + setHref: (url) => routerInfo.router!.push(url.toString()), + }, + }; + }, + }; +}; + +export const recipeDetails = { + docsLink: "https://supertokens.com/docs/thirdpartypasswordless/introduction", +}; + +export const PreBuiltUIList = [EmailPasswordPreBuiltUI, ThirdPartyPreBuiltUI, PasswordlessPreBuiltUI]; diff --git a/examples/with-next-ssr-app-directory/app/config/ssr.ts b/examples/with-next-ssr-app-directory/app/config/ssr.ts new file mode 100644 index 000000000..c6bc60a61 --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/config/ssr.ts @@ -0,0 +1,10 @@ +import { appInfo } from "./appInfo"; +import { SuperTokensConfig } from "supertokens-auth-react/lib/build/types"; + +export const ssrConfig = (): SuperTokensConfig => { + return { + appInfo, + enableDebugLogs: true, + recipeList: [], + }; +}; diff --git a/examples/with-next-ssr-app-directory/app/favicon.ico b/examples/with-next-ssr-app-directory/app/favicon.ico new file mode 100644 index 000000000..718d6fea4 Binary files /dev/null and b/examples/with-next-ssr-app-directory/app/favicon.ico differ diff --git a/examples/with-next-ssr-app-directory/app/globals.css b/examples/with-next-ssr-app-directory/app/globals.css new file mode 100644 index 000000000..34d61c0ff --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/globals.css @@ -0,0 +1,3 @@ +html { + height: 100%; +} diff --git a/examples/with-next-ssr-app-directory/app/layout.tsx b/examples/with-next-ssr-app-directory/app/layout.tsx new file mode 100644 index 000000000..fd4996f9f --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/layout.tsx @@ -0,0 +1,21 @@ +import "./globals.css"; +import type { Metadata } from "next"; +import { Inter } from "next/font/google"; +import { SuperTokensProvider } from "./components/supertokensProvider"; + +const inter = Inter({ subsets: ["latin"] }); + +export const metadata: Metadata = { + title: "SuperTokens 💫", + description: "SuperTokens demo app", +}; + +export default function RootLayout({ children }: { children: React.ReactNode }) { + return ( + + + {children} + + + ); +} diff --git a/examples/with-next-ssr-app-directory/app/page.module.css b/examples/with-next-ssr-app-directory/app/page.module.css new file mode 100644 index 000000000..e63fa0f16 --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/page.module.css @@ -0,0 +1,214 @@ +.main { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + min-height: 100vh; +} + +@font-face { + font-family: Menlo; + src: url("../assets/fonts/MenloRegular.ttf"); +} + +.appContainer { + font-family: Rubik, sans-serif; +} + +.appContainer * { + box-sizing: border-box; +} + +.bold400 { + font-variation-settings: "wght" 400; +} + +.bold500 { + font-variation-settings: "wght" 500; +} + +.bold600 { + font-variation-settings: "wght" 600; +} + +.homeContainer { + min-height: 100vh; + min-width: 100vw; + background: url("../assets/images/background.png"); + background-size: cover; + + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; +} + +.bold700 { + font-variation-settings: "wght" 700; +} + +.mainContainer { + box-shadow: 0px 0px 60px 0px rgba(0, 0, 0, 0.16); + width: min(635px, calc(100% - 24px)); + border-radius: 16px; + margin-block-end: 159px; + background-color: #ffffff; +} + +.successTitle { + line-height: 1; + padding-block: 26px; + background-color: #e7ffed; + text-align: center; + color: #3eb655; + display: flex; + justify-content: center; + align-items: flex-end; + font-size: 20px; +} + +.successIcon { + margin-right: 8px; +} + +.innerContent { + padding-block: 48px; + text-align: center; + display: flex; + flex-direction: column; + align-items: center; +} + +.userId { + position: relative; + padding: 14px 17px; + border-image-slice: 1; + width: min(430px, calc(100% - 30px)); + margin-inline: auto; + margin-block: 11px 23px; + border-radius: 9px; + line-height: 1; + font-family: Menlo, serif; + cursor: text; +} + +.userId:before { + content: ""; + position: absolute; + inset: 0; + border-radius: 9px; + padding: 2px; + background: linear-gradient(90.31deg, #ff9933 0.11%, #ff3f33 99.82%); + mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + -webkit-mask-composite: xor; + mask-composite: exclude; +} + +.topBand, +.bottomBand { + border-radius: inherit; +} + +.topBand { + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; +} + +.bottomBand { + border-top-left-radius: 0; + border-top-right-radius: 0; +} + +.sessionButton { + padding-left: 13px; + padding-right: 13px; + padding-top: 8px; + padding-bottom: 8px; + cursor: pointer; + color: white; + font-weight: bold; + font-size: 17px; + + box-sizing: border-box; + background: #ff9933; + border: 1px solid #ff8a15; + box-shadow: 0px 3px 6px rgba(255, 153, 51, 0.16); + border-radius: 6px; + font-size: 16px; +} + +.bottomCTAContainer { + display: flex; + justify-content: flex-end; + padding-inline: 21px; + background-color: #212d4f; +} + +.viewCode { + padding-block: 11px; + color: #bac9f5; + cursor: pointer; + font-size: 14px; +} + +.bottomLinksContainer { + display: grid; + grid-template-columns: repeat(4, auto); + margin-bottom: 22px; +} + +.linksContainerLink { + display: flex; + align-items: center; + margin-inline-end: 68px; + cursor: pointer; + text-decoration: none; + color: #000000; +} + +.linksContainerLink:last-child { + margin-right: 0; +} + +.truncate { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +.separatorLine { + max-width: 100%; +} + +.linkIcon { + width: 15px; + margin-right: 5px; +} + +@media screen and (max-width: 768px) { + .bottomLinksContainer { + grid-template-columns: repeat(2, 1fr); + column-gap: 64px; + row-gap: 34px; + } + + .linksContainerLink { + margin-inline-end: 0; + } + + .separatorLine { + max-width: 200px; + } +} + +@media screen and (max-width: 480px) { + .homeContainer { + justify-content: start; + padding-block-start: 25px; + } + + .mainContainer { + margin-block-end: 90px; + } +} diff --git a/examples/with-next-ssr-app-directory/app/page.tsx b/examples/with-next-ssr-app-directory/app/page.tsx new file mode 100644 index 000000000..8d9b991c4 --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/page.tsx @@ -0,0 +1,10 @@ +import { HomePage } from "./components/home"; +import styles from "./page.module.css"; + +export default function Home() { + return ( +
+ +
+ ); +} diff --git a/examples/with-next-ssr-app-directory/app/util.ts b/examples/with-next-ssr-app-directory/app/util.ts new file mode 100644 index 000000000..289a6d5c2 --- /dev/null +++ b/examples/with-next-ssr-app-directory/app/util.ts @@ -0,0 +1,31 @@ +import JsonWebToken from "jsonwebtoken"; +import type { JwtHeader, JwtPayload, SigningKeyCallback } from "jsonwebtoken"; +import jwksClient from "jwks-rsa"; +import { appInfo } from "./config/appInfo"; + +const client = jwksClient({ + jwksUri: `${appInfo.apiDomain}${appInfo.apiBasePath}/jwt/jwks.json`, +}); + +async function verifyToken(token: string): Promise { + const getPublicKey = (header: JwtHeader, callback: SigningKeyCallback) => { + client.getSigningKey(header.kid, (err, key) => { + if (err) { + callback(err); + } else { + const signingKey = key?.getPublicKey(); + callback(null, signingKey); + } + }); + }; + + return new Promise((resolve, reject) => { + JsonWebToken.verify(token, getPublicKey, {}, (err, decoded) => { + if (err) { + reject(err); + } else { + resolve(decoded as JwtPayload); + } + }); + }); +} diff --git a/examples/with-next-ssr-app-directory/assets/fonts/MenloRegular.ttf b/examples/with-next-ssr-app-directory/assets/fonts/MenloRegular.ttf new file mode 100644 index 000000000..033dc6d21 Binary files /dev/null and b/examples/with-next-ssr-app-directory/assets/fonts/MenloRegular.ttf differ diff --git a/examples/with-next-ssr-app-directory/assets/images/arrow-right-icon.svg b/examples/with-next-ssr-app-directory/assets/images/arrow-right-icon.svg new file mode 100644 index 000000000..95aa1fec6 --- /dev/null +++ b/examples/with-next-ssr-app-directory/assets/images/arrow-right-icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/examples/with-next-ssr-app-directory/assets/images/background.png b/examples/with-next-ssr-app-directory/assets/images/background.png new file mode 100644 index 000000000..2147c15c2 Binary files /dev/null and b/examples/with-next-ssr-app-directory/assets/images/background.png differ diff --git a/examples/with-next-ssr-app-directory/assets/images/blogs-icon.svg b/examples/with-next-ssr-app-directory/assets/images/blogs-icon.svg new file mode 100644 index 000000000..a2fc9dd62 --- /dev/null +++ b/examples/with-next-ssr-app-directory/assets/images/blogs-icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/examples/with-next-ssr-app-directory/assets/images/celebrate-icon.svg b/examples/with-next-ssr-app-directory/assets/images/celebrate-icon.svg new file mode 100644 index 000000000..3b40b1efa --- /dev/null +++ b/examples/with-next-ssr-app-directory/assets/images/celebrate-icon.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/examples/with-next-ssr-app-directory/assets/images/guide-icon.svg b/examples/with-next-ssr-app-directory/assets/images/guide-icon.svg new file mode 100644 index 000000000..bd85af72b --- /dev/null +++ b/examples/with-next-ssr-app-directory/assets/images/guide-icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/examples/with-next-ssr-app-directory/assets/images/index.ts b/examples/with-next-ssr-app-directory/assets/images/index.ts new file mode 100644 index 000000000..7adf036c4 --- /dev/null +++ b/examples/with-next-ssr-app-directory/assets/images/index.ts @@ -0,0 +1,8 @@ +import SeparatorLine from "./separator-line.svg"; +import ArrowRight from "./arrow-right-icon.svg"; +import SignOutIcon from "./sign-out-icon.svg"; +import GuideIcon from "./guide-icon.svg"; +import BlogsIcon from "./blogs-icon.svg"; +import CelebrateIcon from "./celebrate-icon.svg"; + +export { SeparatorLine, ArrowRight, SignOutIcon, GuideIcon, BlogsIcon, CelebrateIcon }; diff --git a/examples/with-next-ssr-app-directory/assets/images/separator-line.svg b/examples/with-next-ssr-app-directory/assets/images/separator-line.svg new file mode 100644 index 000000000..7127a00dc --- /dev/null +++ b/examples/with-next-ssr-app-directory/assets/images/separator-line.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/examples/with-next-ssr-app-directory/assets/images/sign-out-icon.svg b/examples/with-next-ssr-app-directory/assets/images/sign-out-icon.svg new file mode 100644 index 000000000..6cc4f85fd --- /dev/null +++ b/examples/with-next-ssr-app-directory/assets/images/sign-out-icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/examples/with-next-ssr-app-directory/middleware.ts b/examples/with-next-ssr-app-directory/middleware.ts new file mode 100644 index 000000000..b68939327 --- /dev/null +++ b/examples/with-next-ssr-app-directory/middleware.ts @@ -0,0 +1,14 @@ +import { withSession } from "supertokens-node/nextjs"; +import { ensureSuperTokensInit } from "./app/config/backend"; +import { ssrConfig } from "./app/config/ssr"; +import { superTokensMiddleware } from "supertokens-auth-react/nextjs/middleware"; + +ensureSuperTokensInit(); + +export default superTokensMiddleware(ssrConfig(), withSession); + +export const config = { + matcher: [ + "/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|manifest.json|sw.js|workbox-|public/).*)", + ], +}; diff --git a/examples/with-next-ssr-app-directory/next.config.js b/examples/with-next-ssr-app-directory/next.config.js new file mode 100644 index 000000000..658404ac6 --- /dev/null +++ b/examples/with-next-ssr-app-directory/next.config.js @@ -0,0 +1,4 @@ +/** @type {import('next').NextConfig} */ +const nextConfig = {}; + +module.exports = nextConfig; diff --git a/examples/with-next-ssr-app-directory/package.json b/examples/with-next-ssr-app-directory/package.json new file mode 100644 index 000000000..a282a2c72 --- /dev/null +++ b/examples/with-next-ssr-app-directory/package.json @@ -0,0 +1,29 @@ +{ + "name": "supertokens-app-dir", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev -p 3333", + "build": "next build", + "start": "next start", + "lint": "next lint" + }, + "dependencies": { + "jsonwebtoken": "^9.0.2", + "jwks-rsa": "^3.1.0", + "next": "latest", + "react": "^18", + "react-dom": "^18", + "supertokens-auth-react": "latest", + "supertokens-node": "latest" + }, + "devDependencies": { + "@types/cookie": "^0.5.2", + "@types/node": "^20", + "@types/react": "^18", + "@types/react-dom": "^18", + "eslint": "^8", + "eslint-config-next": "13.5.4", + "typescript": "^5" + } +} diff --git a/examples/with-next-ssr-app-directory/public/next.svg b/examples/with-next-ssr-app-directory/public/next.svg new file mode 100644 index 000000000..5174b28c5 --- /dev/null +++ b/examples/with-next-ssr-app-directory/public/next.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/examples/with-next-ssr-app-directory/public/vercel.svg b/examples/with-next-ssr-app-directory/public/vercel.svg new file mode 100644 index 000000000..d2f842227 --- /dev/null +++ b/examples/with-next-ssr-app-directory/public/vercel.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/examples/with-next-ssr-app-directory/tsconfig.json b/examples/with-next-ssr-app-directory/tsconfig.json new file mode 100644 index 000000000..c265b30bb --- /dev/null +++ b/examples/with-next-ssr-app-directory/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "es5", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "noEmit": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "preserve", + "incremental": true, + "plugins": [ + { + "name": "next" + } + ], + "paths": { + "@/*": ["./*"] + } + }, + "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/examples/with-next-ssr-pages-directory/.env b/examples/with-next-ssr-pages-directory/.env new file mode 100644 index 000000000..9a88ce3f1 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/.env @@ -0,0 +1,14 @@ +# These are all working development keys. +# IMPORTANT: You can use them during development, but for production use, +# make sure to change them to keys issued for your app. + +GOOGLE_CLIENT_ID=1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com +GOOGLE_CLIENT_SECRET=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 + +GITHUB_CLIENT_ID=467101b197249757c71f +GITHUB_CLIENT_SECRET=e97051221f4b6426e8fe8d51486396703012f5bd + +APPLE_CLIENT_ID=4398792-io.supertokens.example.service +APPLE_KEY_ID=7M48Y4RYDL +APPLE_TEAM_ID=YWQCXGJRJL +APPLE_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----\nMIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgu8gXs+XYkqXD6Ala9Sf/iJXzhbwcoG5dMh1OonpdJUmgCgYIKoZIzj0DAQehRANCAASfrvlFbFCYqn3I2zeknYXLwtH30JuOKestDbSfZYxZNMqhF/OzdZFTV0zc5u5s3eN+oCWbnvl0hM+9IW0UlkdA\n-----END PRIVATE KEY----- \ No newline at end of file diff --git a/examples/with-next-ssr-pages-directory/.gitignore b/examples/with-next-ssr-pages-directory/.gitignore new file mode 100644 index 000000000..c87c9b392 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/.gitignore @@ -0,0 +1,36 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# local env files +.env*.local + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts diff --git a/examples/with-next-ssr-pages-directory/assets/fonts/MenloRegular.ttf b/examples/with-next-ssr-pages-directory/assets/fonts/MenloRegular.ttf new file mode 100644 index 000000000..033dc6d21 Binary files /dev/null and b/examples/with-next-ssr-pages-directory/assets/fonts/MenloRegular.ttf differ diff --git a/examples/with-next-ssr-pages-directory/assets/images/arrow-right-icon.svg b/examples/with-next-ssr-pages-directory/assets/images/arrow-right-icon.svg new file mode 100644 index 000000000..95aa1fec6 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/assets/images/arrow-right-icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/examples/with-next-ssr-pages-directory/assets/images/background.png b/examples/with-next-ssr-pages-directory/assets/images/background.png new file mode 100644 index 000000000..2147c15c2 Binary files /dev/null and b/examples/with-next-ssr-pages-directory/assets/images/background.png differ diff --git a/examples/with-next-ssr-pages-directory/assets/images/blogs-icon.svg b/examples/with-next-ssr-pages-directory/assets/images/blogs-icon.svg new file mode 100644 index 000000000..a2fc9dd62 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/assets/images/blogs-icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/examples/with-next-ssr-pages-directory/assets/images/celebrate-icon.svg b/examples/with-next-ssr-pages-directory/assets/images/celebrate-icon.svg new file mode 100644 index 000000000..3b40b1efa --- /dev/null +++ b/examples/with-next-ssr-pages-directory/assets/images/celebrate-icon.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/examples/with-next-ssr-pages-directory/assets/images/guide-icon.svg b/examples/with-next-ssr-pages-directory/assets/images/guide-icon.svg new file mode 100644 index 000000000..bd85af72b --- /dev/null +++ b/examples/with-next-ssr-pages-directory/assets/images/guide-icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/examples/with-next-ssr-pages-directory/assets/images/index.ts b/examples/with-next-ssr-pages-directory/assets/images/index.ts new file mode 100644 index 000000000..7adf036c4 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/assets/images/index.ts @@ -0,0 +1,8 @@ +import SeparatorLine from "./separator-line.svg"; +import ArrowRight from "./arrow-right-icon.svg"; +import SignOutIcon from "./sign-out-icon.svg"; +import GuideIcon from "./guide-icon.svg"; +import BlogsIcon from "./blogs-icon.svg"; +import CelebrateIcon from "./celebrate-icon.svg"; + +export { SeparatorLine, ArrowRight, SignOutIcon, GuideIcon, BlogsIcon, CelebrateIcon }; diff --git a/examples/with-next-ssr-pages-directory/assets/images/separator-line.svg b/examples/with-next-ssr-pages-directory/assets/images/separator-line.svg new file mode 100644 index 000000000..7127a00dc --- /dev/null +++ b/examples/with-next-ssr-pages-directory/assets/images/separator-line.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/examples/with-next-ssr-pages-directory/assets/images/sign-out-icon.svg b/examples/with-next-ssr-pages-directory/assets/images/sign-out-icon.svg new file mode 100644 index 000000000..6cc4f85fd --- /dev/null +++ b/examples/with-next-ssr-pages-directory/assets/images/sign-out-icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/examples/with-next-ssr-pages-directory/config/appInfo.ts b/examples/with-next-ssr-pages-directory/config/appInfo.ts new file mode 100644 index 000000000..13d8a40e5 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/config/appInfo.ts @@ -0,0 +1,12 @@ +const port = process.env.APP_PORT || 3232; + +const apiBasePath = "/api/auth"; + +export const websiteDomain = process.env.APP_URL || process.env.NEXT_PUBLIC_APP_URL || `http://localhost:${port}`; + +export const appInfo = { + appName: "SuperTokens Demo App", + websiteDomain, + apiDomain: websiteDomain, + apiBasePath, +}; diff --git a/examples/with-next-ssr-pages-directory/config/backendConfig.ts b/examples/with-next-ssr-pages-directory/config/backendConfig.ts new file mode 100644 index 000000000..a40a16e15 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/config/backendConfig.ts @@ -0,0 +1,90 @@ +import EmailPasswordNode from "supertokens-node/recipe/emailpassword"; +import ThirdPartyNode from "supertokens-node/recipe/thirdparty"; +import PasswordlessNode from "supertokens-node/recipe/passwordless"; +import SessionNode from "supertokens-node/recipe/session"; +import Dashboard from "supertokens-node/recipe/dashboard"; +import UserRoles from "supertokens-node/recipe/userroles"; +import { TypeInput } from "supertokens-node/types"; +import { appInfo } from "./appInfo"; + +export let backendConfig = (): TypeInput => { + return { + framework: "express", + supertokens: { + // this is the location of the SuperTokens core. + connectionURI: "https://try.supertokens.com", + }, + appInfo, + // recipeList contains all the modules that you want to + // use from SuperTokens. See the full list here: https://supertokens.com/docs/guides + recipeList: [ + EmailPasswordNode.init(), + ThirdPartyNode.init({ + signInAndUpFeature: { + providers: [ + // We have provided you with development keys which you can use for testing. + // IMPORTANT: Please replace them with your own OAuth keys for production use. + { + config: { + thirdPartyId: "google", + clients: [ + { + clientId: + "1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com", + clientSecret: "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", + }, + ], + }, + }, + { + config: { + thirdPartyId: "github", + clients: [ + { + clientId: "467101b197249757c71f", + clientSecret: "e97051221f4b6426e8fe8d51486396703012f5bd", + }, + ], + }, + }, + { + config: { + thirdPartyId: "apple", + clients: [ + { + clientId: "4398792-io.supertokens.example.service", + additionalConfig: { + keyId: "7M48Y4RYDL", + privateKey: + "-----BEGIN PRIVATE KEY-----\nMIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgu8gXs+XYkqXD6Ala9Sf/iJXzhbwcoG5dMh1OonpdJUmgCgYIKoZIzj0DAQehRANCAASfrvlFbFCYqn3I2zeknYXLwtH30JuOKestDbSfZYxZNMqhF/OzdZFTV0zc5u5s3eN+oCWbnvl0hM+9IW0UlkdA\n-----END PRIVATE KEY-----", + teamId: "YWQCXGJRJL", + }, + }, + ], + }, + }, + { + config: { + thirdPartyId: "twitter", + clients: [ + { + clientId: "4398792-WXpqVXRiazdRMGNJdEZIa3RVQXc6MTpjaQ", + clientSecret: "BivMbtwmcygbRLNQ0zk45yxvW246tnYnTFFq-LH39NwZMxFpdC", + }, + ], + }, + }, + ], + }, + }), + PasswordlessNode.init({ + contactMethod: "EMAIL_OR_PHONE", + flowType: "USER_INPUT_CODE_AND_MAGIC_LINK", + }), + SessionNode.init(), + Dashboard.init(), + UserRoles.init(), + ], + isInServerlessEnv: true, + }; +}; diff --git a/examples/with-next-ssr-pages-directory/config/frontendConfig.tsx b/examples/with-next-ssr-pages-directory/config/frontendConfig.tsx new file mode 100644 index 000000000..39538b6b8 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/config/frontendConfig.tsx @@ -0,0 +1,52 @@ +import EmailPasswordReact from "supertokens-auth-react/recipe/emailpassword"; +import ThirdPartyReact from "supertokens-auth-react/recipe/thirdparty"; +import PasswordlessReact from "supertokens-auth-react/recipe/passwordless"; +import { EmailPasswordPreBuiltUI } from "supertokens-auth-react/recipe/emailpassword/prebuiltui"; +import { ThirdPartyPreBuiltUI } from "supertokens-auth-react/recipe/thirdparty/prebuiltui"; +import { PasswordlessPreBuiltUI } from "supertokens-auth-react/recipe/passwordless/prebuiltui"; +import SessionReact from "supertokens-auth-react/recipe/session"; +import { SuperTokensConfig } from "supertokens-auth-react/lib/build/types"; +import { appInfo } from "./appInfo"; +import Router from "next/router"; + +export let frontendConfig = (): SuperTokensConfig => { + return { + appInfo, + // recipeList contains all the modules that you want to + // use from SuperTokens. See the full list here: https://supertokens.com/docs/guides + recipeList: [ + EmailPasswordReact.init(), + ThirdPartyReact.init({ + signInAndUpFeature: { + providers: [ + ThirdPartyReact.Github.init(), + ThirdPartyReact.Google.init(), + ThirdPartyReact.Apple.init(), + ], + }, + }), + PasswordlessReact.init({ + contactMethod: "EMAIL_OR_PHONE", + }), + SessionReact.init(), + ], + // this is so that the SDK uses the next router for navigation + windowHandler: (oI) => { + return { + ...oI, + location: { + ...oI.location, + setHref: (href) => { + Router.push(href); + }, + }, + }; + }, + }; +}; + +export const recipeDetails = { + docsLink: "https://supertokens.com/docs/thirdpartypasswordless/introduction", +}; + +export const PreBuiltUIList = [EmailPasswordPreBuiltUI, ThirdPartyPreBuiltUI, PasswordlessPreBuiltUI]; diff --git a/examples/with-next-ssr-pages-directory/config/ssrConfig.ts b/examples/with-next-ssr-pages-directory/config/ssrConfig.ts new file mode 100644 index 000000000..c6bc60a61 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/config/ssrConfig.ts @@ -0,0 +1,10 @@ +import { appInfo } from "./appInfo"; +import { SuperTokensConfig } from "supertokens-auth-react/lib/build/types"; + +export const ssrConfig = (): SuperTokensConfig => { + return { + appInfo, + enableDebugLogs: true, + recipeList: [], + }; +}; diff --git a/examples/with-next-ssr-pages-directory/middleware.ts b/examples/with-next-ssr-pages-directory/middleware.ts new file mode 100644 index 000000000..b5b3629a6 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/middleware.ts @@ -0,0 +1,85 @@ +import { NextResponse } from "next/server"; +import type { NextRequest } from "next/server"; +import { SessionContainer, VerifySessionOptions } from "supertokens-node/recipe/session"; +import { withSession } from "supertokens-node/nextjs"; +import { ssrConfig } from "./config/ssrConfig"; +import { refreshSession, revokeSession } from "supertokens-auth-react/nextjs/middleware"; +import { SuperTokensConfig } from "supertokens-auth-react/lib/build/types"; + +const CURRENT_PATH_COOKIE_NAME = "sCurrentPath"; +const FORCE_LOGOUT_PATH_PARAM_NAME = "forceLogout"; + +export default superTokensMiddleware(ssrConfig()); + +// This function should be exposed by the node sdk +function superTokensMiddleware( + config: SuperTokensConfig, + options?: VerifySessionOptions +): (request: NextRequest & { session?: SessionContainer }) => Promise { + // Determined by checking if the frontend and backend are on the same domain + const usesTheNextjsApiAsTheAuthenticationServer = true; + + return async (request: NextRequest & { session?: SessionContainer }) => { + if (request.nextUrl.pathname.startsWith("/api/auth/session/refresh") && request.method === "GET") { + return refreshSession(config, request); + } + + if (request.nextUrl.pathname.startsWith("/api") && usesTheNextjsApiAsTheAuthenticationServer) { + if (request.headers.has("x-user-id")) { + console.warn( + "The FE tried to pass x-user-id, which is only supposed to be a backend internal header. Ignoring." + ); + request.headers.delete("x-user-id"); + } + + if (request.nextUrl.pathname.startsWith("/api/auth")) { + // this hits our pages/api/auth/* endpoints + return NextResponse.next(); + } + + return withSession( + request, + async (err, session) => { + if (err) { + return NextResponse.json(err, { status: 500 }); + } + + if (session === undefined) { + return NextResponse.next(); + } + return NextResponse.next({ + headers: { + "x-user-id": session.getUserId(), + }, + }); + }, + options + ); + } + + if ( + request.nextUrl.pathname.startsWith("/auth") && + request.nextUrl.searchParams.get(FORCE_LOGOUT_PATH_PARAM_NAME) === "true" + ) { + return revokeSession(config, request); + } + + // Save the current path so that we can use it during SSR + // Used to redirect the user to the correct path after login/refresh + // https://github.com/vercel/next.js/issues/43704#issuecomment-2090798307 + // TL;DR: You can not access pathname in SSR and requests that originate from redirect() + const response = new Response(null, {}); + response.headers.set("x-middleware-next", "1"); + response.headers.append( + "set-cookie", + `${CURRENT_PATH_COOKIE_NAME}=${request.nextUrl.pathname}; Path=/; HttpOnly; SameSite=Strict` + ); + return response; + }; +} + +export const config = { + matcher: [ + "/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|manifest.json|sw.js|workbox-|public/).*)", + ], +}; diff --git a/examples/with-next-ssr-pages-directory/next.config.js b/examples/with-next-ssr-pages-directory/next.config.js new file mode 100644 index 000000000..b13dbe4e0 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/next.config.js @@ -0,0 +1,6 @@ +/** @type {import('next').NextConfig} */ +const nextConfig = { + reactStrictMode: true, +}; + +module.exports = nextConfig; diff --git a/examples/with-next-ssr-pages-directory/package.json b/examples/with-next-ssr-pages-directory/package.json new file mode 100644 index 000000000..9ed13158d --- /dev/null +++ b/examples/with-next-ssr-pages-directory/package.json @@ -0,0 +1,20 @@ +{ + "private": true, + "scripts": { + "dev": "next dev -p 3232", + "build": "next build", + "start": "next start" + }, + "dependencies": { + "next": "latest", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "supertokens-auth-react": "git+https://github.com/supertokens/supertokens-auth-react.git#feat/nextjs-ssr", + "supertokens-node": "latest" + }, + "devDependencies": { + "@types/node": "18.7.13", + "@types/react": "18.0.17", + "typescript": "^4.8.2" + } +} diff --git a/examples/with-next-ssr-pages-directory/pages/_app.tsx b/examples/with-next-ssr-pages-directory/pages/_app.tsx new file mode 100644 index 000000000..01dd54bba --- /dev/null +++ b/examples/with-next-ssr-pages-directory/pages/_app.tsx @@ -0,0 +1,37 @@ +import "../styles/globals.css"; +import React from "react"; +import { useEffect } from "react"; +import SuperTokensReact, { SuperTokensWrapper } from "supertokens-auth-react"; +import * as SuperTokensConfig from "../config/frontendConfig"; +import Session from "supertokens-auth-react/recipe/session"; + +if (typeof window !== "undefined") { + SuperTokensReact.init(SuperTokensConfig.frontendConfig()); +} + +function MyApp({ Component, pageProps }): JSX.Element { + useEffect(() => { + async function doRefresh() { + if (pageProps.fromSupertokens === "needs-refresh") { + if (await Session.attemptRefreshingSession()) { + location.reload(); + } else { + // user has been logged out + SuperTokensReact.redirectToAuth(); + } + } + } + doRefresh(); + }, [pageProps.fromSupertokens]); + if (pageProps.fromSupertokens === "needs-refresh") { + return null; + } + + return ( + + + + ); +} + +export default MyApp; diff --git a/examples/with-next-ssr-pages-directory/pages/api/auth/[[...path]].ts b/examples/with-next-ssr-pages-directory/pages/api/auth/[[...path]].ts new file mode 100644 index 000000000..dbb392fb9 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/pages/api/auth/[[...path]].ts @@ -0,0 +1,21 @@ +// Next.js API route support: https://nextjs.org/docs/api-routes/introduction +import { superTokensNextWrapper } from "supertokens-node/nextjs"; +import supertokens from "supertokens-node"; +import { middleware } from "supertokens-node/framework/express"; +import { backendConfig } from "../../../config/backendConfig"; + +supertokens.init(backendConfig()); + +export default async function superTokens(req, res) { + await superTokensNextWrapper( + async (next) => { + res.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); + await middleware()(req, res, next); + }, + req, + res + ); + if (!res.writableEnded) { + res.status(404).send("Not found"); + } +} diff --git a/examples/with-next-ssr-pages-directory/pages/api/user.ts b/examples/with-next-ssr-pages-directory/pages/api/user.ts new file mode 100644 index 000000000..eb169559a --- /dev/null +++ b/examples/with-next-ssr-pages-directory/pages/api/user.ts @@ -0,0 +1,23 @@ +import { superTokensNextWrapper } from "supertokens-node/nextjs"; +import { verifySession } from "supertokens-node/recipe/session/framework/express"; +import supertokens from "supertokens-node"; +import { backendConfig } from "../../config/backendConfig"; + +supertokens.init(backendConfig()); + +export default async function user(req, res) { + await superTokensNextWrapper( + async (next) => { + return await verifySession()(req, res, next); + }, + req, + res + ); + + return res.json({ + note: "Fetch any data from your application for authenticated user after using verifySession middleware", + userId: req.session.getUserId(), + sessionHandle: req.session.getHandle(), + accessTokenPayload: req.session.getAccessTokenPayload(), + }); +} diff --git a/examples/with-next-ssr-pages-directory/pages/auth/[[...path]].tsx b/examples/with-next-ssr-pages-directory/pages/auth/[[...path]].tsx new file mode 100644 index 000000000..0ae741a34 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/pages/auth/[[...path]].tsx @@ -0,0 +1,39 @@ +import Head from "next/head"; +import React, { useEffect } from "react"; +import styles from "../../styles/Home.module.css"; +import dynamic from "next/dynamic"; +import SuperTokens from "supertokens-auth-react"; +import { canHandleRoute, getRoutingComponent } from "supertokens-auth-react/ui"; +import { PreBuiltUIList } from "../../config/frontendConfig"; + +const SuperTokensComponentNoSSR = dynamic<{}>(new Promise((res) => res(() => getRoutingComponent(PreBuiltUIList))), { + ssr: false, +}); + +export default function Auth(): JSX.Element { + useEffect(() => { + if (canHandleRoute(PreBuiltUIList) === false) { + SuperTokens.redirectToAuth({ + redirectBack: false, + }); + } + }, []); + + return ( +
+ + SuperTokens 💫 + + + + +
+ +
+
+ ); +} diff --git a/examples/with-next-ssr-pages-directory/pages/index.tsx b/examples/with-next-ssr-pages-directory/pages/index.tsx new file mode 100644 index 000000000..5f7705291 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/pages/index.tsx @@ -0,0 +1,109 @@ +import React from "react"; +import Head from "next/head"; +import styles from "../styles/ProtectedHome.module.css"; +import SessionReact from "supertokens-auth-react/recipe/session"; +import SuperTokensReact from "supertokens-auth-react"; +import { useSessionContext } from "supertokens-auth-react/recipe/session"; +import { BlogsIcon, CelebrateIcon, GuideIcon, SeparatorLine, SignOutIcon } from "../assets/images"; +import Image from "next/image"; +import { recipeDetails } from "../config/frontendConfig"; +import { ssrConfig } from "../config/ssrConfig"; +import { init, getServerSidePropsSession } from "supertokens-auth-react/nextjs/ssr"; + +init(ssrConfig()); + +interface ILink { + name: string; + onClick: () => void; + icon: string; +} + +function ProtectedPage() { + const session = useSessionContext(); + + async function logoutClicked() { + await SessionReact.signOut(); + SuperTokensReact.redirectToAuth(); + } + + async function fetchUserData() { + const res = await fetch("/api/user"); + if (res.status === 200) { + const json = await res.json(); + alert(JSON.stringify(json)); + } + } + + if (session.loading === true) { + return null; + } + + function openLink(url: string) { + window.open(url, "_blank"); + } + + const links: ILink[] = [ + { + name: "Blogs", + onClick: () => openLink("https://supertokens.com/blog"), + icon: BlogsIcon, + }, + { + name: "Guides", + onClick: () => openLink(recipeDetails.docsLink), + icon: GuideIcon, + }, + { + name: "Sign Out", + onClick: logoutClicked, + icon: SignOutIcon, + }, + ]; + + return ( +
+ + SuperTokens 💫 + + +
+
+ Login successful Login successful +
+
+
Your userID is:
+
{session.userId}
+
+ Call API +
+
+
+
+ {links.map((link) => ( +
+ {link.name} +
+ {link.name} +
+
+ ))} +
+ separator +
+ ); +} + +export async function getServerSideProps(ctx) { + const props = await getServerSidePropsSession(ctx.req); + return props; +} + +export default function Home(props) { + console.log(props); + + return ( + + + + ); +} diff --git a/examples/with-next-ssr-pages-directory/public/favicon.ico b/examples/with-next-ssr-pages-directory/public/favicon.ico new file mode 100644 index 000000000..d14dbd1d8 Binary files /dev/null and b/examples/with-next-ssr-pages-directory/public/favicon.ico differ diff --git a/examples/with-next-ssr-pages-directory/public/vercel.svg b/examples/with-next-ssr-pages-directory/public/vercel.svg new file mode 100644 index 000000000..fbf0e25a6 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/public/vercel.svg @@ -0,0 +1,4 @@ + + + \ No newline at end of file diff --git a/examples/with-next-ssr-pages-directory/styles/Home.module.css b/examples/with-next-ssr-pages-directory/styles/Home.module.css new file mode 100644 index 000000000..e69778204 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/styles/Home.module.css @@ -0,0 +1,122 @@ +.container { + min-height: 100vh; + padding: 0 0.5rem; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; +} + +.main { + padding: 5rem 0; + flex: 1; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; +} + +.footer { + width: 100%; + height: 100px; + border-top: 1px solid #eaeaea; + display: flex; + justify-content: center; + align-items: center; +} + +.footer img { + margin-left: 0.5rem; +} + +.footer a { + display: flex; + justify-content: center; + align-items: center; +} + +.title a { + color: #0070f3; + text-decoration: none; +} + +.title a:hover, +.title a:focus, +.title a:active { + text-decoration: underline; +} + +.title { + margin: 0; + line-height: 1.15; + font-size: 4rem; +} + +.title, +.description { + text-align: center; +} + +.description { + line-height: 1.5; + font-size: 1.5rem; +} + +.code { + background: #fafafa; + border-radius: 5px; + padding: 0.75rem; + font-size: 1.1rem; + font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, + monospace; +} + +.grid { + display: flex; + align-items: center; + justify-content: center; + flex-wrap: wrap; + max-width: 800px; + margin-top: 3rem; +} + +.card { + margin: 1rem; + flex-basis: 45%; + padding: 1.5rem; + text-align: left; + color: inherit; + text-decoration: none; + border: 1px solid #eaeaea; + border-radius: 10px; + transition: color 0.15s ease, border-color 0.15s ease; +} + +.card:hover, +.card:focus, +.card:active { + color: #0070f3; + border-color: #0070f3; +} + +.card h3 { + margin: 0 0 1rem 0; + font-size: 1.5rem; +} + +.card p { + margin: 0; + font-size: 1.25rem; + line-height: 1.5; +} + +.logo { + height: 1em; +} + +@media (max-width: 600px) { + .grid { + width: 100%; + flex-direction: column; + } +} diff --git a/examples/with-next-ssr-pages-directory/styles/ProtectedHome.module.css b/examples/with-next-ssr-pages-directory/styles/ProtectedHome.module.css new file mode 100644 index 000000000..74dfbb304 --- /dev/null +++ b/examples/with-next-ssr-pages-directory/styles/ProtectedHome.module.css @@ -0,0 +1,202 @@ +@font-face { + font-family: Menlo; + src: url("../assets/fonts/MenloRegular.ttf"); +} + +.appContainer { + font-family: Rubik, sans-serif; +} + +.appContainer * { + box-sizing: border-box; +} + +.bold400 { + font-variation-settings: "wght" 400; +} + +.bold500 { + font-variation-settings: "wght" 500; +} + +.bold600 { + font-variation-settings: "wght" 600; +} + +.homeContainer { + min-height: 100vh; + background: url("../assets/images/background.png"); + background-size: cover; + + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; +} + +.bold700 { + font-variation-settings: "wght" 700; +} + +.mainContainer { + box-shadow: 0px 0px 60px 0px rgba(0, 0, 0, 0.16); + width: min(635px, calc(100% - 24px)); + border-radius: 16px; + margin-block-end: 159px; + background-color: #ffffff; +} + +.successTitle { + line-height: 1; + padding-block: 26px; + background-color: #e7ffed; + text-align: center; + color: #3eb655; + display: flex; + justify-content: center; + align-items: flex-end; + font-size: 20px; +} + +.successIcon { + margin-right: 8px; +} + +.innerContent { + padding-block: 48px; + text-align: center; + display: flex; + flex-direction: column; + align-items: center; +} + +.userId { + position: relative; + padding: 14px 17px; + border-image-slice: 1; + width: min(430px, calc(100% - 30px)); + margin-inline: auto; + margin-block: 11px 23px; + border-radius: 9px; + line-height: 1; + font-family: Menlo, serif; + cursor: text; +} + +.userId:before { + content: ""; + position: absolute; + inset: 0; + border-radius: 9px; + padding: 2px; + background: linear-gradient(90.31deg, #ff9933 0.11%, #ff3f33 99.82%); + -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + -webkit-mask-composite: xor; + mask-composite: exclude; +} + +.topBand, +.bottomBand { + border-radius: inherit; +} + +.topBand { + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; +} + +.bottomBand { + border-top-left-radius: 0; + border-top-right-radius: 0; +} + +.sessionButton { + padding-left: 13px; + padding-right: 13px; + padding-top: 8px; + padding-bottom: 8px; + cursor: pointer; + color: white; + font-weight: bold; + font-size: 17px; + + box-sizing: border-box; + background: #ff9933; + border: 1px solid #ff8a15; + box-shadow: 0px 3px 6px rgba(255, 153, 51, 0.16); + border-radius: 6px; + font-size: 16px; +} + +.bottomCTAContainer { + display: flex; + justify-content: flex-end; + padding-inline: 21px; + background-color: #212d4f; +} + +.viewCode { + padding-block: 11px; + color: #bac9f5; + cursor: pointer; + font-size: 14px; +} + +.bottomLinksContainer { + display: grid; + grid-template-columns: repeat(4, auto); + margin-bottom: 22px; +} + +.linksContainerLink { + display: flex; + align-items: center; + margin-inline-end: 68px; + cursor: pointer; +} + +.linksContainerLink:last-child { + margin-right: 0; +} + +.truncate { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; +} + +.separatorLine { + max-width: 100%; +} + +.linkIcon { + width: 15px; + margin-right: 5px; +} + +@media screen and (max-width: 768px) { + .bottomLinksContainer { + grid-template-columns: repeat(2, 1fr); + column-gap: 64px; + row-gap: 34px; + } + + .linksContainerLink { + margin-inline-end: 0; + } + + .separatorLine { + max-width: 200px; + } +} + +@media screen and (max-width: 480px) { + .homeContainer { + justify-content: start; + padding-block-start: 25px; + } + + .mainContainer { + margin-block-end: 90px; + } +} diff --git a/examples/with-next-ssr-pages-directory/styles/globals.css b/examples/with-next-ssr-pages-directory/styles/globals.css new file mode 100644 index 000000000..24bdae79c --- /dev/null +++ b/examples/with-next-ssr-pages-directory/styles/globals.css @@ -0,0 +1,16 @@ +html, +body { + padding: 0; + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, + Helvetica Neue, sans-serif; +} + +a { + color: inherit; + text-decoration: none; +} + +* { + box-sizing: border-box; +} diff --git a/examples/with-next-ssr-pages-directory/tsconfig.json b/examples/with-next-ssr-pages-directory/tsconfig.json new file mode 100644 index 000000000..c29a4153c --- /dev/null +++ b/examples/with-next-ssr-pages-directory/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "es5", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": false, + "forceConsistentCasingInFileNames": true, + "noEmit": true, + "incremental": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "preserve" + }, + "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "interfaces.d.ts"], + "exclude": ["node_modules"] +} diff --git a/lib/build/arrowLeftIcon.js b/lib/build/arrowLeftIcon.js index ae4718ff5..1a4a5c431 100644 --- a/lib/build/arrowLeftIcon.js +++ b/lib/build/arrowLeftIcon.js @@ -1,42 +1,31 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var jsxRuntime = require("react/jsx-runtime"); +var utils = require('./utils.js'); +var jsxRuntime = require('react/jsx-runtime'); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Imports. - */ -/* - * Component. - */ -function ArrowLeftIcon(_a) { - var color = _a.color; - return jsxRuntime.jsx( - "svg", - genericComponentOverrideContext.__assign( - { width: "6", height: "8", viewBox: "0 0 6 8", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, - { - children: jsxRuntime.jsx("path", { - d: "M0.372871 3.24407C-0.0875903 3.64284 -0.0875899 4.35716 0.372872 4.75593L3.84535 7.76318C4.49299 8.32406 5.5 7.864 5.5 7.00725L5.5 0.992749C5.5 0.135997 4.49299 -0.324056 3.84535 0.23682L0.372871 3.24407Z", - fill: "".concat(color), - }), - } - ) - ); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Imports. + */ +/* + * Component. + */ +function ArrowLeftIcon(_a) { + var color = _a.color; + return (jsxRuntime.jsx("svg", utils.__assign({ width: "6", height: "8", viewBox: "0 0 6 8", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, { children: jsxRuntime.jsx("path", { d: "M0.372871 3.24407C-0.0875903 3.64284 -0.0875899 4.35716 0.372872 4.75593L3.84535 7.76318C4.49299 8.32406 5.5 7.864 5.5 7.00725L5.5 0.992749C5.5 0.135997 4.49299 -0.324056 3.84535 0.23682L0.372871 3.24407Z", fill: "".concat(color) }) }))); } exports.ArrowLeftIcon = ArrowLeftIcon; diff --git a/lib/build/authCompWrapper.js b/lib/build/authCompWrapper.js index ae3e8d5ec..8a8499fee 100644 --- a/lib/build/authCompWrapper.js +++ b/lib/build/authCompWrapper.js @@ -1,16 +1,12 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var jsxRuntime = require("react/jsx-runtime"); -var uiEntry = require("./index2.js"); +var utils = require('./utils.js'); +var jsxRuntime = require('react/jsx-runtime'); +var uiEntry = require('./index2.js'); -function AuthComponentWrapper(_a) { - var children = _a.children, - recipeComponentOverrides = _a.recipeComponentOverrides; - return jsxRuntime.jsx( - uiEntry.ComponentOverrideContext.Provider, - genericComponentOverrideContext.__assign({ value: recipeComponentOverrides }, { children: children }) - ); +function AuthComponentWrapper(_a) { + var children = _a.children, recipeComponentOverrides = _a.recipeComponentOverrides; + return (jsxRuntime.jsx(uiEntry.ComponentOverrideContext.Provider, utils.__assign({ value: recipeComponentOverrides }, { children: children }))); } exports.AuthComponentWrapper = AuthComponentWrapper; diff --git a/lib/build/authRecipe-shared.js b/lib/build/authRecipe-shared.js index a49f45a02..2609675ca 100644 --- a/lib/build/authRecipe-shared.js +++ b/lib/build/authRecipe-shared.js @@ -1,60 +1,56 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); +var utils = require('./utils.js'); +var superTokens = require('./superTokens.js'); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -function normaliseAuthRecipe(config) { - return genericComponentOverrideContext.normaliseRecipeModuleConfig(config); -} -function selectComponentsToCoverAllFirstFactors(comps, firstFactorIds) { - if (firstFactorIds.length === 0) { - return undefined; - } - var _loop_1 = function (i) { - var c = comps[i]; - // We check what factorIds are left if we select c - var factorIdsLeft = firstFactorIds.filter(function (id) { - return !c.factorIds.includes(id); - }); - if (factorIdsLeft.length === 0) { - return { value: [c] }; - } - // If there are other factors we need to cover, we filter down the component list to things that - // fit the remaining factor ids. This will remove overlapping components - // E.g.: if we just selected the emailpassword+pwless component, the emailpassword sign in/up components - // will be removed, since emailpassword is not in factorIdsLeft - var componentsLeft = comps.filter(function (c) { - return c.factorIds.every(function (id) { - return factorIdsLeft.includes(id); - }); - }); - // if we both have components and factors left after selecting c, we recurse - if (componentsLeft.length !== 0) { - var nextComps = selectComponentsToCoverAllFirstFactors(componentsLeft, factorIdsLeft); - if (nextComps !== undefined) { - return { value: genericComponentOverrideContext.__spreadArray([c], nextComps, true) }; - } - } - }; - for (var i = 0; i < comps.length; ++i) { - var state_1 = _loop_1(i); - if (typeof state_1 === "object") return state_1.value; - } - // if we run out of components, we can't cover all factorids with this set of components - return undefined; +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +function normaliseAuthRecipe(config) { + return superTokens.normaliseRecipeModuleConfig(config); +} +function selectComponentsToCoverAllFirstFactors(comps, firstFactorIds) { + if (firstFactorIds.length === 0) { + return undefined; + } + var _loop_1 = function (i) { + var c = comps[i]; + // We check what factorIds are left if we select c + var factorIdsLeft = firstFactorIds.filter(function (id) { return !c.factorIds.includes(id); }); + if (factorIdsLeft.length === 0) { + return { value: [c] }; + } + // If there are other factors we need to cover, we filter down the component list to things that + // fit the remaining factor ids. This will remove overlapping components + // E.g.: if we just selected the emailpassword+pwless component, the emailpassword sign in/up components + // will be removed, since emailpassword is not in factorIdsLeft + var componentsLeft = comps.filter(function (c) { return c.factorIds.every(function (id) { return factorIdsLeft.includes(id); }); }); + // if we both have components and factors left after selecting c, we recurse + if (componentsLeft.length !== 0) { + var nextComps = selectComponentsToCoverAllFirstFactors(componentsLeft, factorIdsLeft); + if (nextComps !== undefined) { + return { value: utils.__spreadArray([c], nextComps, true) }; + } + } + }; + for (var i = 0; i < comps.length; ++i) { + var state_1 = _loop_1(i); + if (typeof state_1 === "object") + return state_1.value; + } + // if we run out of components, we can't cover all factorids with this set of components + return undefined; } exports.normaliseAuthRecipe = normaliseAuthRecipe; diff --git a/lib/build/authRecipe-shared2.js b/lib/build/authRecipe-shared2.js index 6ac9fc7cf..20f4646d5 100644 --- a/lib/build/authRecipe-shared2.js +++ b/lib/build/authRecipe-shared2.js @@ -1,76 +1,56 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var index = require("./recipeModule-shared.js"); -var types = require("./multifactorauth-shared.js"); +var utils = require('./utils.js'); +var index = require('./recipeModule-shared.js'); +var types = require('./multifactorauth-shared.js'); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var AuthRecipe = /** @class */ (function (_super) { - genericComponentOverrideContext.__extends(AuthRecipe, _super); - function AuthRecipe() { - var _this = (_super !== null && _super.apply(this, arguments)) || this; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _this.getAuthRecipeDefaultRedirectionURL = function (_context) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - throw new Error("Should never come here"); - }); - }); - }; - _this.signOut = function (input) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().signOut({ - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }), - ]; - case 1: - return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - _this.doesSessionExist = function (input) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().doesSessionExist({ - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }), - ]; - case 1: - return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - return _this; - } - return AuthRecipe; -})(index.RecipeModule); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var AuthRecipe = /** @class */ (function (_super) { + utils.__extends(AuthRecipe, _super); + function AuthRecipe() { + var _this = _super !== null && _super.apply(this, arguments) || this; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _this.getAuthRecipeDefaultRedirectionURL = function (_context) { return utils.__awaiter(_this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + throw new Error("Should never come here"); + }); + }); }; + _this.signOut = function (input) { return utils.__awaiter(_this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, types.Session.getInstanceOrThrow().signOut({ + userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext), + })]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); }; + _this.doesSessionExist = function (input) { return utils.__awaiter(_this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, types.Session.getInstanceOrThrow().doesSessionExist({ + userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext), + })]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); }; + return _this; + } + return AuthRecipe; +}(index.RecipeModule)); exports.AuthRecipe = AuthRecipe; diff --git a/lib/build/claims/booleanClaim.d.ts b/lib/build/claims/booleanClaim.d.ts index f5fa724ad..87ae0669b 100644 --- a/lib/build/claims/booleanClaim.d.ts +++ b/lib/build/claims/booleanClaim.d.ts @@ -1,11 +1,9 @@ -import { BooleanClaim as BooleanClaimWebJS } from "supertokens-web-js/recipe/session"; -import type { ValidationFailureCallback } from "../types"; -import type { PrimitiveClaimConfig } from "supertokens-web-js/recipe/session"; -export declare class BooleanClaim extends BooleanClaimWebJS { - constructor( - config: PrimitiveClaimConfig & { - onFailureRedirection?: ValidationFailureCallback; - showAccessDeniedOnFailure?: boolean; - } - ); -} +import { BooleanClaim as BooleanClaimWebJS } from "supertokens-web-js/recipe/session"; +import type { ValidationFailureCallback } from "../types"; +import type { PrimitiveClaimConfig } from "supertokens-web-js/recipe/session"; +export declare class BooleanClaim extends BooleanClaimWebJS { + constructor(config: PrimitiveClaimConfig & { + onFailureRedirection?: ValidationFailureCallback; + showAccessDeniedOnFailure?: boolean; + }); +} diff --git a/lib/build/claims/primitiveArrayClaim.d.ts b/lib/build/claims/primitiveArrayClaim.d.ts index 330562b67..7cca9741a 100644 --- a/lib/build/claims/primitiveArrayClaim.d.ts +++ b/lib/build/claims/primitiveArrayClaim.d.ts @@ -1,11 +1,9 @@ -import { PrimitiveArrayClaim as PrimitiveArrayClaimWebJS } from "supertokens-web-js/recipe/session"; -import type { ValidationFailureCallback } from "../types"; -import type { PrimitiveArrayClaimConfig } from "supertokens-web-js/recipe/session"; -export declare class PrimitiveArrayClaim extends PrimitiveArrayClaimWebJS { - constructor( - config: PrimitiveArrayClaimConfig & { - onFailureRedirection?: ValidationFailureCallback; - showAccessDeniedOnFailure?: boolean; - } - ); -} +import { PrimitiveArrayClaim as PrimitiveArrayClaimWebJS } from "supertokens-web-js/recipe/session"; +import type { ValidationFailureCallback } from "../types"; +import type { PrimitiveArrayClaimConfig } from "supertokens-web-js/recipe/session"; +export declare class PrimitiveArrayClaim extends PrimitiveArrayClaimWebJS { + constructor(config: PrimitiveArrayClaimConfig & { + onFailureRedirection?: ValidationFailureCallback; + showAccessDeniedOnFailure?: boolean; + }); +} diff --git a/lib/build/claims/primitiveClaim.d.ts b/lib/build/claims/primitiveClaim.d.ts index d6bbd0480..645780e22 100644 --- a/lib/build/claims/primitiveClaim.d.ts +++ b/lib/build/claims/primitiveClaim.d.ts @@ -1,11 +1,9 @@ -import { PrimitiveClaim as PrimitiveClaimWebJS } from "supertokens-web-js/recipe/session"; -import type { ValidationFailureCallback } from "../types"; -import type { PrimitiveClaimConfig } from "supertokens-web-js/recipe/session"; -export declare class PrimitiveClaim extends PrimitiveClaimWebJS { - constructor( - config: PrimitiveClaimConfig & { - onFailureRedirection?: ValidationFailureCallback; - showAccessDeniedOnFailure?: boolean; - } - ); -} +import { PrimitiveClaim as PrimitiveClaimWebJS } from "supertokens-web-js/recipe/session"; +import type { ValidationFailureCallback } from "../types"; +import type { PrimitiveClaimConfig } from "supertokens-web-js/recipe/session"; +export declare class PrimitiveClaim extends PrimitiveClaimWebJS { + constructor(config: PrimitiveClaimConfig & { + onFailureRedirection?: ValidationFailureCallback; + showAccessDeniedOnFailure?: boolean; + }); +} diff --git a/lib/build/components/SuperTokensBranding.d.ts b/lib/build/components/SuperTokensBranding.d.ts index 0f81ce774..cee9bd8f4 100644 --- a/lib/build/components/SuperTokensBranding.d.ts +++ b/lib/build/components/SuperTokensBranding.d.ts @@ -1,2 +1,2 @@ -/// -export declare function SuperTokensBranding(): JSX.Element; +/// +export declare function SuperTokensBranding(): JSX.Element; diff --git a/lib/build/components/assets/arrowLeftIcon.d.ts b/lib/build/components/assets/arrowLeftIcon.d.ts index 0524e444e..7dcc6d321 100644 --- a/lib/build/components/assets/arrowLeftIcon.d.ts +++ b/lib/build/components/assets/arrowLeftIcon.d.ts @@ -1,2 +1,4 @@ -/// -export default function ArrowLeftIcon({ color }: { color: string }): JSX.Element; +/// +export default function ArrowLeftIcon({ color }: { + color: string; +}): JSX.Element; diff --git a/lib/build/components/assets/arrowRightIcon.d.ts b/lib/build/components/assets/arrowRightIcon.d.ts index 92171e170..f9d560ba9 100644 --- a/lib/build/components/assets/arrowRightIcon.d.ts +++ b/lib/build/components/assets/arrowRightIcon.d.ts @@ -1,2 +1,4 @@ -/// -export default function ArrowRightIcon({ color }: { color: string }): JSX.Element; +/// +export default function ArrowRightIcon({ color }: { + color: string; +}): JSX.Element; diff --git a/lib/build/components/assets/blockedIcon.d.ts b/lib/build/components/assets/blockedIcon.d.ts index 36a055cab..b3a0759c6 100644 --- a/lib/build/components/assets/blockedIcon.d.ts +++ b/lib/build/components/assets/blockedIcon.d.ts @@ -1 +1 @@ -export declare const BlockedIcon: () => import("react/jsx-runtime").JSX.Element; +export declare const BlockedIcon: () => import("react/jsx-runtime").JSX.Element; diff --git a/lib/build/components/assets/checkedIcon.d.ts b/lib/build/components/assets/checkedIcon.d.ts index c77b17734..dfc818ca7 100644 --- a/lib/build/components/assets/checkedIcon.d.ts +++ b/lib/build/components/assets/checkedIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function CheckedIcon(): JSX.Element; +/// +export default function CheckedIcon(): JSX.Element; diff --git a/lib/build/components/assets/checkedRoundIcon.d.ts b/lib/build/components/assets/checkedRoundIcon.d.ts index d848bf1ff..684e946b1 100644 --- a/lib/build/components/assets/checkedRoundIcon.d.ts +++ b/lib/build/components/assets/checkedRoundIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function CheckedRoundIcon(): JSX.Element; +/// +export default function CheckedRoundIcon(): JSX.Element; diff --git a/lib/build/components/assets/emailLargeIcon.d.ts b/lib/build/components/assets/emailLargeIcon.d.ts index 78e4d6b64..7996cb8f1 100644 --- a/lib/build/components/assets/emailLargeIcon.d.ts +++ b/lib/build/components/assets/emailLargeIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function EmailLargeIcon(): JSX.Element; +/// +export default function EmailLargeIcon(): JSX.Element; diff --git a/lib/build/components/assets/errorIcon.d.ts b/lib/build/components/assets/errorIcon.d.ts index 28939aefc..3cb014e72 100644 --- a/lib/build/components/assets/errorIcon.d.ts +++ b/lib/build/components/assets/errorIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function ErrorIcon(): JSX.Element; +/// +export default function ErrorIcon(): JSX.Element; diff --git a/lib/build/components/assets/errorLargeIcon.d.ts b/lib/build/components/assets/errorLargeIcon.d.ts index a22a990df..b6241efe0 100644 --- a/lib/build/components/assets/errorLargeIcon.d.ts +++ b/lib/build/components/assets/errorLargeIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function ErrorLargeIcon(): JSX.Element; +/// +export default function ErrorLargeIcon(): JSX.Element; diff --git a/lib/build/components/assets/errorRoundIcon.d.ts b/lib/build/components/assets/errorRoundIcon.d.ts index 348bff543..49ebe1034 100644 --- a/lib/build/components/assets/errorRoundIcon.d.ts +++ b/lib/build/components/assets/errorRoundIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function ErrorRoundIcon(): JSX.Element; +/// +export default function ErrorRoundIcon(): JSX.Element; diff --git a/lib/build/components/assets/fingerPrintIcon.d.ts b/lib/build/components/assets/fingerPrintIcon.d.ts index 5d0083e6a..0a4156ed4 100644 --- a/lib/build/components/assets/fingerPrintIcon.d.ts +++ b/lib/build/components/assets/fingerPrintIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function FingerPrintIcon(): JSX.Element; +/// +export default function FingerPrintIcon(): JSX.Element; diff --git a/lib/build/components/assets/heavyArrowLeftIcon.d.ts b/lib/build/components/assets/heavyArrowLeftIcon.d.ts index aa7d7edfe..4c231237c 100644 --- a/lib/build/components/assets/heavyArrowLeftIcon.d.ts +++ b/lib/build/components/assets/heavyArrowLeftIcon.d.ts @@ -1,2 +1,4 @@ -/// -export default function HeavyArrowLeftIcon({ color }: { color: string }): JSX.Element; +/// +export default function HeavyArrowLeftIcon({ color }: { + color: string; +}): JSX.Element; diff --git a/lib/build/components/assets/logoutIcon.d.ts b/lib/build/components/assets/logoutIcon.d.ts index 4f3513ab8..e428254a3 100644 --- a/lib/build/components/assets/logoutIcon.d.ts +++ b/lib/build/components/assets/logoutIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function LogoutIcon(): JSX.Element; +/// +export default function LogoutIcon(): JSX.Element; diff --git a/lib/build/components/assets/multipleDevicesIcon.d.ts b/lib/build/components/assets/multipleDevicesIcon.d.ts index 59f608de3..d2fe6ab20 100644 --- a/lib/build/components/assets/multipleDevicesIcon.d.ts +++ b/lib/build/components/assets/multipleDevicesIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function MultipleDevicesIcon(): JSX.Element; +/// +export default function MultipleDevicesIcon(): JSX.Element; diff --git a/lib/build/components/assets/otpEmailIcon.d.ts b/lib/build/components/assets/otpEmailIcon.d.ts index f1424c14b..8c254b2b5 100644 --- a/lib/build/components/assets/otpEmailIcon.d.ts +++ b/lib/build/components/assets/otpEmailIcon.d.ts @@ -1 +1 @@ -export declare const OTPEmailIcon: () => import("react/jsx-runtime").JSX.Element; +export declare const OTPEmailIcon: () => import("react/jsx-runtime").JSX.Element; diff --git a/lib/build/components/assets/otpSMSIcon.d.ts b/lib/build/components/assets/otpSMSIcon.d.ts index cb6600f53..e1955720e 100644 --- a/lib/build/components/assets/otpSMSIcon.d.ts +++ b/lib/build/components/assets/otpSMSIcon.d.ts @@ -1 +1 @@ -export declare const OTPSMSIcon: () => import("react/jsx-runtime").JSX.Element; +export declare const OTPSMSIcon: () => import("react/jsx-runtime").JSX.Element; diff --git a/lib/build/components/assets/passkeyIcon.d.ts b/lib/build/components/assets/passkeyIcon.d.ts index 685924e88..73757a426 100644 --- a/lib/build/components/assets/passkeyIcon.d.ts +++ b/lib/build/components/assets/passkeyIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function PasskeyIcon(): JSX.Element; +/// +export default function PasskeyIcon(): JSX.Element; diff --git a/lib/build/components/assets/recoverySuccessIcon.d.ts b/lib/build/components/assets/recoverySuccessIcon.d.ts index fd4ceda0b..50dce0213 100644 --- a/lib/build/components/assets/recoverySuccessIcon.d.ts +++ b/lib/build/components/assets/recoverySuccessIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function RecoverySuccessIcon(): JSX.Element; +/// +export default function RecoverySuccessIcon(): JSX.Element; diff --git a/lib/build/components/assets/securityIcon.d.ts b/lib/build/components/assets/securityIcon.d.ts index d99351c57..5962aa229 100644 --- a/lib/build/components/assets/securityIcon.d.ts +++ b/lib/build/components/assets/securityIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function SecurityIcon(): JSX.Element; +/// +export default function SecurityIcon(): JSX.Element; diff --git a/lib/build/components/assets/showPasswordIcon.d.ts b/lib/build/components/assets/showPasswordIcon.d.ts index 4c9c78f4f..de7bb2926 100644 --- a/lib/build/components/assets/showPasswordIcon.d.ts +++ b/lib/build/components/assets/showPasswordIcon.d.ts @@ -1,2 +1,4 @@ -/// -export default function ShowPasswordIcon({ showPassword }: { showPassword: boolean }): JSX.Element; +/// +export default function ShowPasswordIcon({ showPassword }: { + showPassword: boolean; +}): JSX.Element; diff --git a/lib/build/components/assets/smsLargeIcon.d.ts b/lib/build/components/assets/smsLargeIcon.d.ts index 6bf4d9f76..c0c04c33f 100644 --- a/lib/build/components/assets/smsLargeIcon.d.ts +++ b/lib/build/components/assets/smsLargeIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function SMSLargeIcon(): JSX.Element; +/// +export default function SMSLargeIcon(): JSX.Element; diff --git a/lib/build/components/assets/somethingWentWrongIcon.d.ts b/lib/build/components/assets/somethingWentWrongIcon.d.ts index 87e80fe5a..6623b1e50 100644 --- a/lib/build/components/assets/somethingWentWrongIcon.d.ts +++ b/lib/build/components/assets/somethingWentWrongIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function SomethingWentWrongIcon(): JSX.Element; +/// +export default function SomethingWentWrongIcon(): JSX.Element; diff --git a/lib/build/components/assets/spinnerIcon.d.ts b/lib/build/components/assets/spinnerIcon.d.ts index 40e198acb..d87dca28c 100644 --- a/lib/build/components/assets/spinnerIcon.d.ts +++ b/lib/build/components/assets/spinnerIcon.d.ts @@ -1,2 +1,2 @@ -/// -export default function SpinnerIcon(): JSX.Element; +/// +export default function SpinnerIcon(): JSX.Element; diff --git a/lib/build/components/assets/totpIcon.d.ts b/lib/build/components/assets/totpIcon.d.ts index 091d00d00..a5f481041 100644 --- a/lib/build/components/assets/totpIcon.d.ts +++ b/lib/build/components/assets/totpIcon.d.ts @@ -1 +1 @@ -export declare const TOTPIcon: () => import("react/jsx-runtime").JSX.Element; +export declare const TOTPIcon: () => import("react/jsx-runtime").JSX.Element; diff --git a/lib/build/components/authCompWrapper.d.ts b/lib/build/components/authCompWrapper.d.ts index f31497c86..91d8bb638 100644 --- a/lib/build/components/authCompWrapper.d.ts +++ b/lib/build/components/authCompWrapper.d.ts @@ -1,9 +1,6 @@ -import type { PropsWithChildren } from "react"; -declare type AuthComponentWrapperProps = { - recipeComponentOverrides: any; -}; -export default function AuthComponentWrapper({ - children, - recipeComponentOverrides, -}: PropsWithChildren): JSX.Element | null; -export {}; +import type { PropsWithChildren } from "react"; +declare type AuthComponentWrapperProps = { + recipeComponentOverrides: any; +}; +export default function AuthComponentWrapper({ children, recipeComponentOverrides, }: PropsWithChildren): JSX.Element | null; +export {}; diff --git a/lib/build/components/componentOverride/componentOverride.d.ts b/lib/build/components/componentOverride/componentOverride.d.ts index 9d23e0e4a..08b255a3a 100644 --- a/lib/build/components/componentOverride/componentOverride.d.ts +++ b/lib/build/components/componentOverride/componentOverride.d.ts @@ -1,8 +1,5 @@ -import type React from "react"; -export declare type ComponentOverrideProps> = - React.ComponentProps & { - DefaultComponent: TComponent; - }; -export declare type ComponentOverride> = React.ComponentType< - ComponentOverrideProps ->; +import type React from "react"; +export declare type ComponentOverrideProps> = React.ComponentProps & { + DefaultComponent: TComponent; +}; +export declare type ComponentOverride> = React.ComponentType>; diff --git a/lib/build/components/componentOverride/componentOverrideContext.d.ts b/lib/build/components/componentOverride/componentOverrideContext.d.ts index 052f9dc69..740b696a5 100644 --- a/lib/build/components/componentOverride/componentOverrideContext.d.ts +++ b/lib/build/components/componentOverride/componentOverrideContext.d.ts @@ -1,8 +1,8 @@ -import React from "react"; -import type { ComponentOverride } from "./componentOverride"; -export declare type GenericComponentOverrideMap = { - [K in keyof T]?: ComponentOverride; -}; -declare type ContextType = GenericComponentOverrideMap | "IS_DEFAULT"; -export declare const ComponentOverrideContext: React.Context>; -export {}; +import React from "react"; +import type { ComponentOverride } from "./componentOverride"; +export declare type GenericComponentOverrideMap = { + [K in keyof T]?: ComponentOverride; +}; +declare type ContextType = GenericComponentOverrideMap | "IS_DEFAULT"; +export declare const ComponentOverrideContext: React.Context>; +export {}; diff --git a/lib/build/components/componentOverride/genericComponentOverrideContext.d.ts b/lib/build/components/componentOverride/genericComponentOverrideContext.d.ts index 4c2800821..c24aba8c6 100644 --- a/lib/build/components/componentOverride/genericComponentOverrideContext.d.ts +++ b/lib/build/components/componentOverride/genericComponentOverrideContext.d.ts @@ -1,12 +1,4 @@ -import React from "react"; -export declare const createGenericComponentsOverrideContext: >( - v?: T -) => readonly [ - () => T, - React.FC< - React.PropsWithChildren<{ - components: T; - }> - >, - React.Consumer -]; +import React from "react"; +export declare const createGenericComponentsOverrideContext: >(v?: T) => readonly [() => T, React.FC>, React.Consumer]; diff --git a/lib/build/components/componentOverride/useComponentOverride.d.ts b/lib/build/components/componentOverride/useComponentOverride.d.ts index 31ca2c97e..8f7a9deb5 100644 --- a/lib/build/components/componentOverride/useComponentOverride.d.ts +++ b/lib/build/components/componentOverride/useComponentOverride.d.ts @@ -1,5 +1,3 @@ -import type { ComponentOverride } from "./componentOverride"; -import type React from "react"; -export declare const useComponentOverride: >( - overrideKey: string -) => ComponentOverride | null; +import type { ComponentOverride } from "./componentOverride"; +import type React from "react"; +export declare const useComponentOverride: >(overrideKey: string) => ComponentOverride | null; diff --git a/lib/build/components/componentOverride/withOverride.d.ts b/lib/build/components/componentOverride/withOverride.d.ts index 1cdfe669c..4eee45cea 100644 --- a/lib/build/components/componentOverride/withOverride.d.ts +++ b/lib/build/components/componentOverride/withOverride.d.ts @@ -1,5 +1,2 @@ -import React from "react"; -export declare const withOverride: >( - overrideKey: string, - DefaultComponent: TComponent -) => React.ComponentType>; +import React from "react"; +export declare const withOverride: >(overrideKey: string, DefaultComponent: TComponent) => React.ComponentType>; diff --git a/lib/build/components/featureWrapper.d.ts b/lib/build/components/featureWrapper.d.ts index 235a0d9ce..948b71505 100644 --- a/lib/build/components/featureWrapper.d.ts +++ b/lib/build/components/featureWrapper.d.ts @@ -1,19 +1,12 @@ -import type { TranslationStore } from "../translation/translationHelpers"; -import type { PropsWithChildren } from "react"; -declare type FeatureWrapperProps = { - useShadowDom?: boolean; - defaultStore: TranslationStore; -}; -export default function FeatureWrapper({ - children, - useShadowDom, - defaultStore, -}: PropsWithChildren): JSX.Element | null; -declare type WithOrWithoutShadowDomProps = { - useShadowDom?: boolean; -}; -export declare function WithOrWithoutShadowDom({ - children, - useShadowDom, -}: PropsWithChildren): JSX.Element; -export {}; +import type { TranslationStore } from "../translation/translationHelpers"; +import type { PropsWithChildren } from "react"; +declare type FeatureWrapperProps = { + useShadowDom?: boolean; + defaultStore: TranslationStore; +}; +export default function FeatureWrapper({ children, useShadowDom, defaultStore, }: PropsWithChildren): JSX.Element | null; +declare type WithOrWithoutShadowDomProps = { + useShadowDom?: boolean; +}; +export declare function WithOrWithoutShadowDom({ children, useShadowDom, }: PropsWithChildren): JSX.Element; +export {}; diff --git a/lib/build/components/routingComponent.d.ts b/lib/build/components/routingComponent.d.ts index cb43eb986..4291f88d9 100644 --- a/lib/build/components/routingComponent.d.ts +++ b/lib/build/components/routingComponent.d.ts @@ -1,8 +1,8 @@ -/// -import { RecipeRouter } from "../recipe/recipeRouter"; -import type { ReactRouterDomWithCustomHistory } from "../ui/types"; -export declare function RoutingComponent(props: { - getReactRouterDomWithCustomHistory: () => ReactRouterDomWithCustomHistory | undefined; - preBuiltUIList: RecipeRouter[]; - path: string; -}): JSX.Element | null; +/// +import { RecipeRouter } from "../recipe/recipeRouter"; +import type { ReactRouterDomWithCustomHistory } from "../ui/types"; +export declare function RoutingComponent(props: { + getReactRouterDomWithCustomHistory: () => ReactRouterDomWithCustomHistory | undefined; + preBuiltUIList: RecipeRouter[]; + path: string; +}): JSX.Element | null; diff --git a/lib/build/components/superTokensRoute.d.ts b/lib/build/components/superTokensRoute.d.ts index 91216e1bf..7a5e12d93 100644 --- a/lib/build/components/superTokensRoute.d.ts +++ b/lib/build/components/superTokensRoute.d.ts @@ -1,12 +1,8 @@ -/// -import type { RecipeRouter } from "../recipe/recipeRouter"; -import type { ReactRouterDomWithCustomHistory } from "../ui/types"; -export declare function getSuperTokensRoutesForReactRouterDom({ - getReactRouterDomWithCustomHistory, - recipeList, - basePath, -}: { - getReactRouterDomWithCustomHistory: () => ReactRouterDomWithCustomHistory | undefined; - recipeList: RecipeRouter[]; - basePath: string | undefined; -}): JSX.Element[]; +/// +import type { RecipeRouter } from "../recipe/recipeRouter"; +import type { ReactRouterDomWithCustomHistory } from "../ui/types"; +export declare function getSuperTokensRoutesForReactRouterDom({ getReactRouterDomWithCustomHistory, recipeList, basePath, }: { + getReactRouterDomWithCustomHistory: () => ReactRouterDomWithCustomHistory | undefined; + recipeList: RecipeRouter[]; + basePath: string | undefined; +}): JSX.Element[]; diff --git a/lib/build/components/superTokensRouteV6.d.ts b/lib/build/components/superTokensRouteV6.d.ts index 9c56ef2c2..e4695742b 100644 --- a/lib/build/components/superTokensRouteV6.d.ts +++ b/lib/build/components/superTokensRouteV6.d.ts @@ -1,12 +1,8 @@ -/// -import type { RecipeRouter } from "../recipe/recipeRouter"; -import type { ReactRouterDomWithCustomHistory } from "../ui/types"; -export declare function getSuperTokensRoutesForReactRouterDomV6({ - getReactRouterDomWithCustomHistory, - recipeList, - basePath, -}: { - getReactRouterDomWithCustomHistory: () => ReactRouterDomWithCustomHistory | undefined; - recipeList: RecipeRouter[]; - basePath: string | undefined; -}): JSX.Element[]; +/// +import type { RecipeRouter } from "../recipe/recipeRouter"; +import type { ReactRouterDomWithCustomHistory } from "../ui/types"; +export declare function getSuperTokensRoutesForReactRouterDomV6({ getReactRouterDomWithCustomHistory, recipeList, basePath, }: { + getReactRouterDomWithCustomHistory: () => ReactRouterDomWithCustomHistory | undefined; + recipeList: RecipeRouter[]; + basePath: string | undefined; +}): JSX.Element[]; diff --git a/lib/build/components/supertokensWrapper.d.ts b/lib/build/components/supertokensWrapper.d.ts index e5606f3d6..6fe6aa425 100644 --- a/lib/build/components/supertokensWrapper.d.ts +++ b/lib/build/components/supertokensWrapper.d.ts @@ -1,7 +1,5 @@ -import type { UserContext } from "../types"; -import type { PropsWithChildren } from "react"; -export declare const SuperTokensWrapper: React.FC< - PropsWithChildren<{ - userContext?: UserContext; - }> ->; +import type { UserContext } from "../types"; +import type { PropsWithChildren } from "react"; +export declare const SuperTokensWrapper: React.FC>; diff --git a/lib/build/constants.d.ts b/lib/build/constants.d.ts index 8ba89d3bd..0a3832cc1 100644 --- a/lib/build/constants.d.ts +++ b/lib/build/constants.d.ts @@ -1,7 +1,6 @@ -export declare const RECIPE_ID_QUERY_PARAM = "rid"; -export declare const TENANT_ID_QUERY_PARAM = "tenantId"; -export declare const DEFAULT_API_BASE_PATH = "/auth"; -export declare const DEFAULT_WEBSITE_BASE_PATH = "/auth"; -export declare const ST_ROOT_ID = "supertokens-root"; -export declare const SSR_ERROR = - "\nIf you are trying to use this method doing server-side-rendering, please make sure you move this method inside a componentDidMount method or useEffect hook."; +export declare const RECIPE_ID_QUERY_PARAM = "rid"; +export declare const TENANT_ID_QUERY_PARAM = "tenantId"; +export declare const DEFAULT_API_BASE_PATH = "/auth"; +export declare const DEFAULT_WEBSITE_BASE_PATH = "/auth"; +export declare const ST_ROOT_ID = "supertokens-root"; +export declare const SSR_ERROR = "\nIf you are trying to use this method doing server-side-rendering, please make sure you move this method inside a componentDidMount method or useEffect hook."; diff --git a/lib/build/constants.js b/lib/build/constants.js new file mode 100644 index 000000000..b4bc05e79 --- /dev/null +++ b/lib/build/constants.js @@ -0,0 +1,31 @@ +'use strict'; + +var ACCESS_TOKEN_COOKIE_NAME = "sAccessToken"; +var ACCESS_TOKEN_HEADER_NAME = "st-access-token"; +var FRONT_TOKEN_COOKIE_NAME = "sFrontToken"; +var FRONT_TOKEN_HEADER_NAME = "front-token"; +var REFRESH_TOKEN_COOKIE_NAME = "sRefreshToken"; +var REFRESH_TOKEN_HEADER_NAME = "st-refresh-token"; +var ANTI_CSRF_TOKEN_COOKIE_NAME = "sAntiCsrf"; +var ANTI_CSRF_TOKEN_HEADER_NAME = "anti-csrf"; +var REDIRECT_ATTEMPT_MAX_COUNT = 5; +var REDIRECT_ATTEMPT_COUNT_COOKIE_NAME = "stSsrSessionRefreshAttempt"; +var CURRENT_PATH_COOKIE_NAME = "sCurrentPath"; +var FORCE_LOGOUT_PATH_PARAM_NAME = "forceLogout"; +var REDIRECT_PATH_PARAM_NAME = "stRedirectTo"; +var DEFAULT_API_PATH = "/api/auth"; + +exports.ACCESS_TOKEN_COOKIE_NAME = ACCESS_TOKEN_COOKIE_NAME; +exports.ACCESS_TOKEN_HEADER_NAME = ACCESS_TOKEN_HEADER_NAME; +exports.ANTI_CSRF_TOKEN_COOKIE_NAME = ANTI_CSRF_TOKEN_COOKIE_NAME; +exports.ANTI_CSRF_TOKEN_HEADER_NAME = ANTI_CSRF_TOKEN_HEADER_NAME; +exports.CURRENT_PATH_COOKIE_NAME = CURRENT_PATH_COOKIE_NAME; +exports.DEFAULT_API_PATH = DEFAULT_API_PATH; +exports.FORCE_LOGOUT_PATH_PARAM_NAME = FORCE_LOGOUT_PATH_PARAM_NAME; +exports.FRONT_TOKEN_COOKIE_NAME = FRONT_TOKEN_COOKIE_NAME; +exports.FRONT_TOKEN_HEADER_NAME = FRONT_TOKEN_HEADER_NAME; +exports.REDIRECT_ATTEMPT_COUNT_COOKIE_NAME = REDIRECT_ATTEMPT_COUNT_COOKIE_NAME; +exports.REDIRECT_ATTEMPT_MAX_COUNT = REDIRECT_ATTEMPT_MAX_COUNT; +exports.REDIRECT_PATH_PARAM_NAME = REDIRECT_PATH_PARAM_NAME; +exports.REFRESH_TOKEN_COOKIE_NAME = REFRESH_TOKEN_COOKIE_NAME; +exports.REFRESH_TOKEN_HEADER_NAME = REFRESH_TOKEN_HEADER_NAME; diff --git a/lib/build/dateProvider/index.d.ts b/lib/build/dateProvider/index.d.ts index 26e63e67d..1ae1f99e8 100644 --- a/lib/build/dateProvider/index.d.ts +++ b/lib/build/dateProvider/index.d.ts @@ -1 +1 @@ -export { DateProviderReference } from "supertokens-web-js/utils/dateProvider"; +export { DateProviderReference } from "supertokens-web-js/utils/dateProvider"; diff --git a/lib/build/dateProvider/types.d.ts b/lib/build/dateProvider/types.d.ts index 158ae2ca9..d889546ae 100644 --- a/lib/build/dateProvider/types.d.ts +++ b/lib/build/dateProvider/types.d.ts @@ -1 +1 @@ -export { DateProviderInput, DateProviderInterface } from "supertokens-web-js/utils/dateProvider/types"; +export { DateProviderInput, DateProviderInterface } from "supertokens-web-js/utils/dateProvider/types"; diff --git a/lib/build/emailLargeIcon.js b/lib/build/emailLargeIcon.js index a3fb96723..545e9e069 100644 --- a/lib/build/emailLargeIcon.js +++ b/lib/build/emailLargeIcon.js @@ -1,52 +1,30 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var jsxRuntime = require("react/jsx-runtime"); +var utils = require('./utils.js'); +var jsxRuntime = require('react/jsx-runtime'); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Imports. - */ -/* - * Component. - */ -function EmailLargeIcon() { - return jsxRuntime.jsxs( - "svg", - genericComponentOverrideContext.__assign( - { width: "81", height: "74", viewBox: "0 0 81 74", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, - { - children: [ - jsxRuntime.jsx("rect", { - width: "81", - height: "74", - rx: "12", - fill: "#2D3644", - fillOpacity: "0.1", - }), - jsxRuntime.jsx("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M22.304 22.0647C21.4909 22.2023 20.7728 22.5533 20.1863 23.0998C18.7101 24.4753 18.6499 26.6951 20.0512 28.0797C20.366 28.3907 21.5186 29.123 29.4316 34.0394C34.3935 37.1223 38.5814 39.7052 38.7381 39.7792C39.2064 40.0002 39.6687 40.1143 40.2244 40.1458C40.8761 40.1827 41.4402 40.1043 41.985 39.9011C42.2986 39.784 44.5964 38.3819 51.3963 34.1584C56.3443 31.0851 60.5173 28.4732 60.6697 28.3541C61.6877 27.5591 62.2023 26.167 61.9144 24.9866C61.6226 23.7897 60.8986 22.9167 59.7616 22.3906C58.8649 21.9756 60.7985 22.015 40.6942 22.003C25.4606 21.9939 22.667 22.0033 22.304 22.0647ZM19.0395 30.4626C18.9759 30.522 18.9942 48.1686 19.0584 48.6611C19.1774 49.5735 19.5459 50.2964 20.1994 50.8994C20.8308 51.482 21.6026 51.8339 22.511 51.9535C22.8345 51.9961 27.7369 52.0074 40.7771 51.9956C57.6349 51.9804 58.6205 51.9745 58.9603 51.8882C60.2693 51.5556 61.3138 50.6712 61.7699 49.5095C62.0053 48.9096 62 49.1399 62 39.5359C62 32.263 61.986 30.4234 61.9309 30.4431C61.8929 30.4567 57.8079 32.987 52.8531 36.066C46.8009 39.8271 43.6631 41.747 43.2918 41.9165C42.9361 42.0787 42.4928 42.2268 42.0483 42.3318C41.4278 42.4783 41.273 42.4951 40.5284 42.4969C40.0474 42.498 39.5717 42.4714 39.3954 42.4335C38.8623 42.319 38.0528 42.0686 37.6821 41.9036C37.4845 41.8156 33.2326 39.2037 28.2334 36.0994C23.2342 32.995 19.129 30.4488 19.1107 30.4412C19.0924 30.4335 19.0604 30.4432 19.0395 30.4626Z", - fill: "#2D3644", - }), - ], - } - ) - ); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Imports. + */ +/* + * Component. + */ +function EmailLargeIcon() { + return (jsxRuntime.jsxs("svg", utils.__assign({ width: "81", height: "74", viewBox: "0 0 81 74", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, { children: [jsxRuntime.jsx("rect", { width: "81", height: "74", rx: "12", fill: "#2D3644", fillOpacity: "0.1" }), jsxRuntime.jsx("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M22.304 22.0647C21.4909 22.2023 20.7728 22.5533 20.1863 23.0998C18.7101 24.4753 18.6499 26.6951 20.0512 28.0797C20.366 28.3907 21.5186 29.123 29.4316 34.0394C34.3935 37.1223 38.5814 39.7052 38.7381 39.7792C39.2064 40.0002 39.6687 40.1143 40.2244 40.1458C40.8761 40.1827 41.4402 40.1043 41.985 39.9011C42.2986 39.784 44.5964 38.3819 51.3963 34.1584C56.3443 31.0851 60.5173 28.4732 60.6697 28.3541C61.6877 27.5591 62.2023 26.167 61.9144 24.9866C61.6226 23.7897 60.8986 22.9167 59.7616 22.3906C58.8649 21.9756 60.7985 22.015 40.6942 22.003C25.4606 21.9939 22.667 22.0033 22.304 22.0647ZM19.0395 30.4626C18.9759 30.522 18.9942 48.1686 19.0584 48.6611C19.1774 49.5735 19.5459 50.2964 20.1994 50.8994C20.8308 51.482 21.6026 51.8339 22.511 51.9535C22.8345 51.9961 27.7369 52.0074 40.7771 51.9956C57.6349 51.9804 58.6205 51.9745 58.9603 51.8882C60.2693 51.5556 61.3138 50.6712 61.7699 49.5095C62.0053 48.9096 62 49.1399 62 39.5359C62 32.263 61.986 30.4234 61.9309 30.4431C61.8929 30.4567 57.8079 32.987 52.8531 36.066C46.8009 39.8271 43.6631 41.747 43.2918 41.9165C42.9361 42.0787 42.4928 42.2268 42.0483 42.3318C41.4278 42.4783 41.273 42.4951 40.5284 42.4969C40.0474 42.498 39.5717 42.4714 39.3954 42.4335C38.8623 42.319 38.0528 42.0686 37.6821 41.9036C37.4845 41.8156 33.2326 39.2037 28.2334 36.0994C23.2342 32.995 19.129 30.4488 19.1107 30.4412C19.0924 30.4335 19.0604 30.4432 19.0395 30.4626Z", fill: "#2D3644" })] }))); } exports.EmailLargeIcon = EmailLargeIcon; diff --git a/lib/build/emailpassword-shared.js b/lib/build/emailpassword-shared.js index 8b040120d..ff7bc2287 100644 --- a/lib/build/emailpassword-shared.js +++ b/lib/build/emailpassword-shared.js @@ -1,45 +1,28 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var jsxRuntime = require("react/jsx-runtime"); -require("./index2.js"); -var translationContext = require("./translationContext.js"); +var utils = require('./utils.js'); +var jsxRuntime = require('react/jsx-runtime'); +require('./index2.js'); +var translationContext = require('./translationContext.js'); -/* - * Component. - */ -function Button(_a) { - var type = _a.type, - label = _a.label, - disabled = _a.disabled, - isLoading = _a.isLoading, - onClick = _a.onClick, - isGreyedOut = _a.isGreyedOut, - icon = _a.icon; - var t = translationContext.useTranslation(); - if (disabled === undefined) { - disabled = false; - } - // Determine the data-supertokens attribute - var dataSupertokens = "button"; - if (isGreyedOut) { - dataSupertokens += " buttonGreyedOut"; - } - if (icon) { - dataSupertokens += " buttonWithIcon"; - } - return jsxRuntime.jsxs( - "button", - genericComponentOverrideContext.__assign( - { type: type, disabled: disabled, onClick: onClick, "data-supertokens": dataSupertokens }, - { - children: [ - icon && jsxRuntime.jsx("div", { children: icon() }), - jsxRuntime.jsxs("div", { children: [t(label), isLoading && "..."] }), - ], - } - ) - ); +/* + * Component. + */ +function Button(_a) { + var type = _a.type, label = _a.label, disabled = _a.disabled, isLoading = _a.isLoading, onClick = _a.onClick, isGreyedOut = _a.isGreyedOut, icon = _a.icon; + var t = translationContext.useTranslation(); + if (disabled === undefined) { + disabled = false; + } + // Determine the data-supertokens attribute + var dataSupertokens = "button"; + if (isGreyedOut) { + dataSupertokens += " buttonGreyedOut"; + } + if (icon) { + dataSupertokens += " buttonWithIcon"; + } + return (jsxRuntime.jsxs("button", utils.__assign({ type: type, disabled: disabled, onClick: onClick, "data-supertokens": dataSupertokens }, { children: [icon && jsxRuntime.jsx("div", { children: icon() }), jsxRuntime.jsxs("div", { children: [t(label), isLoading && "..."] })] }))); } exports.Button = Button; diff --git a/lib/build/emailpassword-shared2.js b/lib/build/emailpassword-shared2.js index bd3b554b5..7d16271fd 100644 --- a/lib/build/emailpassword-shared2.js +++ b/lib/build/emailpassword-shared2.js @@ -1,10 +1,8 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); +var genericComponentOverrideContext = require('./genericComponentOverrideContext.js'); -var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), - useContext = _a[0], - Provider = _a[1]; +var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), useContext = _a[0], Provider = _a[1]; exports.Provider = Provider; exports.useContext = useContext; diff --git a/lib/build/emailpassword-shared3.js b/lib/build/emailpassword-shared3.js index 4cce69e81..e70574118 100644 --- a/lib/build/emailpassword-shared3.js +++ b/lib/build/emailpassword-shared3.js @@ -1,585 +1,466 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var EmailPasswordWebJS = require("supertokens-web-js/recipe/emailpassword"); -var index = require("./authRecipe-shared2.js"); -var types = require("./multifactorauth-shared.js"); -var constants = require("./emailpassword-shared4.js"); -var utils = require("./authRecipe-shared.js"); -var validators = require("./emailpassword-shared5.js"); +var utils = require('./utils.js'); +var EmailPasswordWebJS = require('supertokens-web-js/recipe/emailpassword'); +var index = require('./authRecipe-shared2.js'); +var types = require('./multifactorauth-shared.js'); +var constants = require('./emailpassword-shared4.js'); +var utils$1 = require('./authRecipe-shared.js'); +var validators = require('./emailpassword-shared5.js'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } -var EmailPasswordWebJS__default = /*#__PURE__*/ _interopDefault(EmailPasswordWebJS); +var EmailPasswordWebJS__default = /*#__PURE__*/_interopDefault(EmailPasswordWebJS); -var getFunctionOverrides = function (onHandleEvent) { - return function (originalImp) { - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, originalImp), { - submitNewPassword: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - originalImp.submitNewPassword( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, input), - { formFields: [input.formFields[0]] } - ) - ), - ]; - case 1: - response = _a.sent(); - if (response.status === "OK") { - onHandleEvent({ - action: "PASSWORD_RESET_SUCCESSFUL", - userContext: input.userContext, - }); - } - return [2 /*return*/, response]; - } - }); - }); - }, - sendPasswordResetEmail: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, originalImp.sendPasswordResetEmail(input)]; - case 1: - response = _a.sent(); - if (response.status === "OK") { - onHandleEvent({ - action: "RESET_PASSWORD_EMAIL_SENT", - email: input.formFields.find(function (_a) { - var id = _a.id; - return id === "email"; - }).value, - userContext: input.userContext, - }); - } - return [2 /*return*/, response]; - } - }); - }); - }, - signUp: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var payloadBeforeCall, response, payloadAfterCall; - return genericComponentOverrideContext.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _c.trys.push([0, 2, , 3]); - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ - userContext: input.userContext, - }), - ]; - case 1: - payloadBeforeCall = _c.sent(); - return [3 /*break*/, 3]; - case 2: - _c.sent(); - // If getAccessTokenPayloadSecurely threw, that generally means we have no active session - payloadBeforeCall = undefined; - return [3 /*break*/, 3]; - case 3: - return [4 /*yield*/, originalImp.signUp(input)]; - case 4: - response = _c.sent(); - if (!(response.status === "OK")) return [3 /*break*/, 9]; - payloadAfterCall = void 0; - _c.label = 5; - case 5: - _c.trys.push([5, 7, , 8]); - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ - userContext: input.userContext, - }), - ]; - case 6: - payloadAfterCall = _c.sent(); - return [3 /*break*/, 8]; - case 7: - _c.sent(); - // If getAccessTokenPayloadSecurely threw, that generally means we have no active session - payloadAfterCall = undefined; - return [3 /*break*/, 8]; - case 8: - onHandleEvent({ - action: "SUCCESS", - isNewRecipeUser: true, - createdNewSession: - payloadAfterCall !== undefined && - (payloadBeforeCall === undefined || - payloadBeforeCall.sessionHandle !== payloadAfterCall.sessionHandle), - user: response.user, - userContext: input.userContext, - }); - _c.label = 9; - case 9: - return [2 /*return*/, response]; - } - }); - }); - }, - signIn: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var payloadBeforeCall, response, payloadAfterCall; - return genericComponentOverrideContext.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _c.trys.push([0, 2, , 3]); - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ - userContext: input.userContext, - }), - ]; - case 1: - payloadBeforeCall = _c.sent(); - return [3 /*break*/, 3]; - case 2: - _c.sent(); - // If getAccessTokenPayloadSecurely threw, that generally means we have no active session - payloadBeforeCall = undefined; - return [3 /*break*/, 3]; - case 3: - return [4 /*yield*/, originalImp.signIn(input)]; - case 4: - response = _c.sent(); - if (!(response.status === "OK")) return [3 /*break*/, 9]; - payloadAfterCall = void 0; - _c.label = 5; - case 5: - _c.trys.push([5, 7, , 8]); - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ - userContext: input.userContext, - }), - ]; - case 6: - payloadAfterCall = _c.sent(); - return [3 /*break*/, 8]; - case 7: - _c.sent(); - // If getAccessTokenPayloadSecurely threw, that generally means we have no active session - payloadAfterCall = undefined; - return [3 /*break*/, 8]; - case 8: - onHandleEvent({ - action: "SUCCESS", - isNewRecipeUser: false, - createdNewSession: - payloadAfterCall !== undefined && - (payloadBeforeCall === undefined || - payloadBeforeCall.sessionHandle !== payloadAfterCall.sessionHandle), - user: response.user, - userContext: input.userContext, - }); - _c.label = 9; - case 9: - return [2 /*return*/, response]; - } - }); - }); - }, - }); - }; +var getFunctionOverrides = function (onHandleEvent) { + return function (originalImp) { return (utils.__assign(utils.__assign({}, originalImp), { submitNewPassword: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, originalImp.submitNewPassword(utils.__assign(utils.__assign({}, input), { formFields: [input.formFields[0]] }))]; + case 1: + response = _a.sent(); + if (response.status === "OK") { + onHandleEvent({ + action: "PASSWORD_RESET_SUCCESSFUL", + userContext: input.userContext, + }); + } + return [2 /*return*/, response]; + } + }); + }); + }, sendPasswordResetEmail: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, originalImp.sendPasswordResetEmail(input)]; + case 1: + response = _a.sent(); + if (response.status === "OK") { + onHandleEvent({ + action: "RESET_PASSWORD_EMAIL_SENT", + email: input.formFields.find(function (_a) { + var id = _a.id; + return id === "email"; + }).value, + userContext: input.userContext, + }); + } + return [2 /*return*/, response]; + } + }); + }); + }, signUp: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var payloadBeforeCall, response, payloadAfterCall; + return utils.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _c.trys.push([0, 2, , 3]); + return [4 /*yield*/, types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ + userContext: input.userContext, + })]; + case 1: + payloadBeforeCall = _c.sent(); + return [3 /*break*/, 3]; + case 2: + _c.sent(); + // If getAccessTokenPayloadSecurely threw, that generally means we have no active session + payloadBeforeCall = undefined; + return [3 /*break*/, 3]; + case 3: return [4 /*yield*/, originalImp.signUp(input)]; + case 4: + response = _c.sent(); + if (!(response.status === "OK")) return [3 /*break*/, 9]; + payloadAfterCall = void 0; + _c.label = 5; + case 5: + _c.trys.push([5, 7, , 8]); + return [4 /*yield*/, types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ + userContext: input.userContext, + })]; + case 6: + payloadAfterCall = _c.sent(); + return [3 /*break*/, 8]; + case 7: + _c.sent(); + // If getAccessTokenPayloadSecurely threw, that generally means we have no active session + payloadAfterCall = undefined; + return [3 /*break*/, 8]; + case 8: + onHandleEvent({ + action: "SUCCESS", + isNewRecipeUser: true, + createdNewSession: payloadAfterCall !== undefined && + (payloadBeforeCall === undefined || + payloadBeforeCall.sessionHandle !== payloadAfterCall.sessionHandle), + user: response.user, + userContext: input.userContext, + }); + _c.label = 9; + case 9: return [2 /*return*/, response]; + } + }); + }); + }, signIn: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var payloadBeforeCall, response, payloadAfterCall; + return utils.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _c.trys.push([0, 2, , 3]); + return [4 /*yield*/, types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ + userContext: input.userContext, + })]; + case 1: + payloadBeforeCall = _c.sent(); + return [3 /*break*/, 3]; + case 2: + _c.sent(); + // If getAccessTokenPayloadSecurely threw, that generally means we have no active session + payloadBeforeCall = undefined; + return [3 /*break*/, 3]; + case 3: return [4 /*yield*/, originalImp.signIn(input)]; + case 4: + response = _c.sent(); + if (!(response.status === "OK")) return [3 /*break*/, 9]; + payloadAfterCall = void 0; + _c.label = 5; + case 5: + _c.trys.push([5, 7, , 8]); + return [4 /*yield*/, types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ + userContext: input.userContext, + })]; + case 6: + payloadAfterCall = _c.sent(); + return [3 /*break*/, 8]; + case 7: + _c.sent(); + // If getAccessTokenPayloadSecurely threw, that generally means we have no active session + payloadAfterCall = undefined; + return [3 /*break*/, 8]; + case 8: + onHandleEvent({ + action: "SUCCESS", + isNewRecipeUser: false, + createdNewSession: payloadAfterCall !== undefined && + (payloadBeforeCall === undefined || + payloadBeforeCall.sessionHandle !== payloadAfterCall.sessionHandle), + user: response.user, + userContext: input.userContext, + }); + _c.label = 9; + case 9: return [2 /*return*/, response]; + } + }); + }); + } })); }; }; -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -function normaliseEmailPasswordConfig(config) { - if (config === undefined) { - config = {}; - } - var signInAndUpFeature = normaliseSignInAndUpFeature(config.signInAndUpFeature); - var signUpPasswordField = signInAndUpFeature.signUpForm.formFields.find(function (field) { - return field.id === "password"; - }); - var signUpEmailField = signInAndUpFeature.signUpForm.formFields.find(function (field) { - return field.id === "email"; - }); - var resetPasswordUsingTokenFeature = normaliseResetPasswordUsingTokenFeature( - signUpPasswordField.validate, - signUpEmailField, - config.resetPasswordUsingTokenFeature - ); - var override = genericComponentOverrideContext.__assign( - { - functions: function (originalImplementation) { - return originalImplementation; - }, - }, - config.override - ); - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, utils.normaliseAuthRecipe(config)), - { - signInAndUpFeature: signInAndUpFeature, - resetPasswordUsingTokenFeature: resetPasswordUsingTokenFeature, - override: override, - } - ); -} -function normaliseSignInAndUpFeature(config) { - if (config === undefined) { - config = {}; - } - var signUpForm = normaliseSignUpFormFeatureConfig(config.signUpForm); - /* - * Default Sign In corresponds to computed Sign Up fields filtered by email and password only. - * i.e. If the user overrides sign Up fields, that is propagated to default sign In fields. - * Exception made of the password validator which only verifies that the value is not empty for login - * https://github.com/supertokens/supertokens-auth-react/issues/21 - */ - var defaultSignInFields = signUpForm.formFields.reduce(function (signInFieldsAccumulator, field) { - if (field.id === "email") { - return genericComponentOverrideContext.__spreadArray( - genericComponentOverrideContext.__spreadArray([], signInFieldsAccumulator, true), - [field], - false - ); - } - if (field.id === "password") { - return genericComponentOverrideContext.__spreadArray( - genericComponentOverrideContext.__spreadArray([], signInFieldsAccumulator, true), - [ - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, field), { - autoComplete: "current-password", - validate: validators.defaultLoginPasswordValidator, - }), - ], - false - ); - } - return signInFieldsAccumulator; - }, []); - var signInForm = normaliseSignInFormFeatureConfig(defaultSignInFields, config.signInForm); - return { - signUpForm: signUpForm, - signInForm: signInForm, - }; -} -function normaliseSignUpFormFeatureConfig(config) { - if (config === undefined) { - config = {}; - } - var defaultFormFields = getDefaultFormFields(); - var userFormFields = []; - if (config.formFields !== undefined) { - userFormFields = config.formFields; - } - var formFields = mergeFormFields(defaultFormFields, userFormFields); - var style = config.style !== undefined ? config.style : ""; - return { - style: style, - formFields: formFields, - }; -} -function normaliseSignInFormFeatureConfig(defaultFormFields, config) { - if (config === undefined) { - config = {}; - } - var userFormFields = []; - if (config.formFields !== undefined) { - userFormFields = config.formFields - // Filter on email and password only. - .filter(function (field) { - return constants.MANDATORY_FORM_FIELDS_ID_ARRAY.includes(field.id); - }) - // Sign In fields are never optional. - .map(function (field) { - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, field), { - optional: false, - }); - }); - } - var formFields = mergeFormFields(defaultFormFields, userFormFields); - var style = config.style !== undefined ? config.style : ""; - return { - style: style, - formFields: formFields, - }; -} -function getDefaultFormFields() { - return [getDefaultEmailFormField(), getDefaultPasswordFormField()]; -} -function getDefaultEmailFormField() { - return { - id: "email", - label: "EMAIL_PASSWORD_EMAIL_LABEL", - placeholder: "EMAIL_PASSWORD_EMAIL_PLACEHOLDER", - validate: validators.defaultEmailValidator, - optional: false, - autoComplete: "email", - }; -} -function getDefaultPasswordFormField() { - return { - id: "password", - label: "EMAIL_PASSWORD_PASSWORD_LABEL", - placeholder: "EMAIL_PASSWORD_PASSWORD_PLACEHOLDER", - validate: validators.defaultPasswordValidator, - optional: false, - autoComplete: "new-password", - }; -} -function normaliseResetPasswordUsingTokenFeature(signUpPasswordFieldValidate, signUpEmailField, config) { - if (config === undefined) { - config = {}; - } - var disableDefaultUI = config.disableDefaultUI === true; - var submitNewPasswordFormStyle = - config.submitNewPasswordForm !== undefined && config.submitNewPasswordForm.style !== undefined - ? config.submitNewPasswordForm.style - : ""; - var submitNewPasswordForm = { - style: submitNewPasswordFormStyle, - formFields: [ - { - id: "password", - label: "EMAIL_PASSWORD_NEW_PASSWORD_LABEL", - placeholder: "EMAIL_PASSWORD_NEW_PASSWORD_PLACEHOLDER", - validate: signUpPasswordFieldValidate, - optional: false, - autoComplete: "new-password", - }, - { - id: "confirm-password", - label: "EMAIL_PASSWORD_CONFIRM_PASSWORD_LABEL", - placeholder: "EMAIL_PASSWORD_CONFIRM_PASSWORD_PLACEHOLDER", - validate: signUpPasswordFieldValidate, - optional: false, - autoComplete: "new-password", - }, - ], - }; - var enterEmailFormStyle = - config.enterEmailForm !== undefined && config.enterEmailForm.style !== undefined - ? config.enterEmailForm.style - : ""; - var enterEmailForm = { - style: enterEmailFormStyle, - formFields: [ - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, getDefaultEmailFormField()), - { validate: signUpEmailField.validate, placeholder: "", autofocus: true } - ), - ], - }; - return { - disableDefaultUI: disableDefaultUI, - submitNewPasswordForm: submitNewPasswordForm, - enterEmailForm: enterEmailForm, - }; -} -/* - * mergeFormFields by keeping the provided order, defaultFormFields or merged first, and unmerged userFormFields after. - */ -function mergeFormFields(defaultFormFields, userFormFields) { - // Create a new array with default fields. - var mergedFormFields = defaultFormFields; - // Loop through user provided fields. - for (var i = 0; i < userFormFields.length; i++) { - var userField = userFormFields[i]; - var isNewField = true; - // Loop through the merged fields array. - for (var j = 0; j < mergedFormFields.length; j++) { - var mergedField = mergedFormFields[j]; - // If id is equal, merge the fields - if (userField.id === mergedField.id) { - // Make sure that email and password are kept mandatory. - var optional = mergedField.optional; // Init with default value. - // If user provided value, overwrite. - if (userField.optional !== undefined) { - optional = userField.optional; - } - // If "email" or "password", always mandatory. - if (constants.MANDATORY_FORM_FIELDS_ID_ARRAY.includes(userField.id)) { - optional = false; - } - // Merge. - mergedFormFields[j] = genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, mergedFormFields[j]), - userField - ), - { optional: optional } - ); - isNewField = false; - break; - } - } - // If new field, push to mergeFormFields. - if (isNewField) { - mergedFormFields.push( - genericComponentOverrideContext.__assign( - { optional: false, placeholder: userField.label, validate: validators.defaultValidate }, - userField - ) - ); - } - } - return mergedFormFields.map(function (field) { - return getFormattedFormField(field); - }); -} -function getFormattedFormField(field) { - var _this = this; - // Fields with the 'nonOptionalErrorMsg' property must have a valid message defined - if (field.optional === false && field.nonOptionalErrorMsg === "") { - throw new Error("nonOptionalErrorMsg for field ".concat(field.id, " cannot be an empty string")); - } - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, field), { - validate: function (value) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - // Absent or not optional empty field - if (value === "" && field.optional === false) { - if (field.nonOptionalErrorMsg !== undefined) { - return [2 /*return*/, field.nonOptionalErrorMsg]; - } - return [2 /*return*/, "ERROR_NON_OPTIONAL"]; - } - return [4 /*yield*/, field.validate(value)]; - case 1: - return [2 /*return*/, _a.sent()]; - } - }); - }); - }, - }); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +function normaliseEmailPasswordConfig(config) { + if (config === undefined) { + config = {}; + } + var signInAndUpFeature = normaliseSignInAndUpFeature(config.signInAndUpFeature); + var signUpPasswordField = signInAndUpFeature.signUpForm.formFields.find(function (field) { + return field.id === "password"; + }); + var signUpEmailField = signInAndUpFeature.signUpForm.formFields.find(function (field) { + return field.id === "email"; + }); + var resetPasswordUsingTokenFeature = normaliseResetPasswordUsingTokenFeature(signUpPasswordField.validate, signUpEmailField, config.resetPasswordUsingTokenFeature); + var override = utils.__assign({ functions: function (originalImplementation) { return originalImplementation; } }, config.override); + return utils.__assign(utils.__assign({}, utils$1.normaliseAuthRecipe(config)), { signInAndUpFeature: signInAndUpFeature, resetPasswordUsingTokenFeature: resetPasswordUsingTokenFeature, override: override }); +} +function normaliseSignInAndUpFeature(config) { + if (config === undefined) { + config = {}; + } + var signUpForm = normaliseSignUpFormFeatureConfig(config.signUpForm); + /* + * Default Sign In corresponds to computed Sign Up fields filtered by email and password only. + * i.e. If the user overrides sign Up fields, that is propagated to default sign In fields. + * Exception made of the password validator which only verifies that the value is not empty for login + * https://github.com/supertokens/supertokens-auth-react/issues/21 + */ + var defaultSignInFields = signUpForm.formFields.reduce(function (signInFieldsAccumulator, field) { + if (field.id === "email") { + return utils.__spreadArray(utils.__spreadArray([], signInFieldsAccumulator, true), [field], false); + } + if (field.id === "password") { + return utils.__spreadArray(utils.__spreadArray([], signInFieldsAccumulator, true), [ + utils.__assign(utils.__assign({}, field), { autoComplete: "current-password", validate: validators.defaultLoginPasswordValidator }), + ], false); + } + return signInFieldsAccumulator; + }, []); + var signInForm = normaliseSignInFormFeatureConfig(defaultSignInFields, config.signInForm); + return { + signUpForm: signUpForm, + signInForm: signInForm, + }; +} +function normaliseSignUpFormFeatureConfig(config) { + if (config === undefined) { + config = {}; + } + var defaultFormFields = getDefaultFormFields(); + var userFormFields = []; + if (config.formFields !== undefined) { + userFormFields = config.formFields; + } + var formFields = mergeFormFields(defaultFormFields, userFormFields); + var style = config.style !== undefined ? config.style : ""; + return { + style: style, + formFields: formFields, + }; +} +function normaliseSignInFormFeatureConfig(defaultFormFields, config) { + if (config === undefined) { + config = {}; + } + var userFormFields = []; + if (config.formFields !== undefined) { + userFormFields = config.formFields + // Filter on email and password only. + .filter(function (field) { return constants.MANDATORY_FORM_FIELDS_ID_ARRAY.includes(field.id); }) + // Sign In fields are never optional. + .map(function (field) { return (utils.__assign(utils.__assign({}, field), { optional: false })); }); + } + var formFields = mergeFormFields(defaultFormFields, userFormFields); + var style = config.style !== undefined ? config.style : ""; + return { + style: style, + formFields: formFields, + }; +} +function getDefaultFormFields() { + return [getDefaultEmailFormField(), getDefaultPasswordFormField()]; +} +function getDefaultEmailFormField() { + return { + id: "email", + label: "EMAIL_PASSWORD_EMAIL_LABEL", + placeholder: "EMAIL_PASSWORD_EMAIL_PLACEHOLDER", + validate: validators.defaultEmailValidator, + optional: false, + autoComplete: "email", + }; +} +function getDefaultPasswordFormField() { + return { + id: "password", + label: "EMAIL_PASSWORD_PASSWORD_LABEL", + placeholder: "EMAIL_PASSWORD_PASSWORD_PLACEHOLDER", + validate: validators.defaultPasswordValidator, + optional: false, + autoComplete: "new-password", + }; +} +function normaliseResetPasswordUsingTokenFeature(signUpPasswordFieldValidate, signUpEmailField, config) { + if (config === undefined) { + config = {}; + } + var disableDefaultUI = config.disableDefaultUI === true; + var submitNewPasswordFormStyle = config.submitNewPasswordForm !== undefined && config.submitNewPasswordForm.style !== undefined + ? config.submitNewPasswordForm.style + : ""; + var submitNewPasswordForm = { + style: submitNewPasswordFormStyle, + formFields: [ + { + id: "password", + label: "EMAIL_PASSWORD_NEW_PASSWORD_LABEL", + placeholder: "EMAIL_PASSWORD_NEW_PASSWORD_PLACEHOLDER", + validate: signUpPasswordFieldValidate, + optional: false, + autoComplete: "new-password", + }, + { + id: "confirm-password", + label: "EMAIL_PASSWORD_CONFIRM_PASSWORD_LABEL", + placeholder: "EMAIL_PASSWORD_CONFIRM_PASSWORD_PLACEHOLDER", + validate: signUpPasswordFieldValidate, + optional: false, + autoComplete: "new-password", + }, + ], + }; + var enterEmailFormStyle = config.enterEmailForm !== undefined && config.enterEmailForm.style !== undefined + ? config.enterEmailForm.style + : ""; + var enterEmailForm = { + style: enterEmailFormStyle, + formFields: [ + utils.__assign(utils.__assign({}, getDefaultEmailFormField()), { validate: signUpEmailField.validate, placeholder: "", autofocus: true }), + ], + }; + return { + disableDefaultUI: disableDefaultUI, + submitNewPasswordForm: submitNewPasswordForm, + enterEmailForm: enterEmailForm, + }; +} +/* + * mergeFormFields by keeping the provided order, defaultFormFields or merged first, and unmerged userFormFields after. + */ +function mergeFormFields(defaultFormFields, userFormFields) { + // Create a new array with default fields. + var mergedFormFields = defaultFormFields; + // Loop through user provided fields. + for (var i = 0; i < userFormFields.length; i++) { + var userField = userFormFields[i]; + var isNewField = true; + // Loop through the merged fields array. + for (var j = 0; j < mergedFormFields.length; j++) { + var mergedField = mergedFormFields[j]; + // If id is equal, merge the fields + if (userField.id === mergedField.id) { + // Make sure that email and password are kept mandatory. + var optional = mergedField.optional; // Init with default value. + // If user provided value, overwrite. + if (userField.optional !== undefined) { + optional = userField.optional; + } + // If "email" or "password", always mandatory. + if (constants.MANDATORY_FORM_FIELDS_ID_ARRAY.includes(userField.id)) { + optional = false; + } + // Merge. + mergedFormFields[j] = utils.__assign(utils.__assign(utils.__assign({}, mergedFormFields[j]), userField), { optional: optional }); + isNewField = false; + break; + } + } + // If new field, push to mergeFormFields. + if (isNewField) { + mergedFormFields.push(utils.__assign({ optional: false, placeholder: userField.label, validate: validators.defaultValidate }, userField)); + } + } + return mergedFormFields.map(function (field) { return getFormattedFormField(field); }); +} +function getFormattedFormField(field) { + var _this = this; + // Fields with the 'nonOptionalErrorMsg' property must have a valid message defined + if (field.optional === false && field.nonOptionalErrorMsg === "") { + throw new Error("nonOptionalErrorMsg for field ".concat(field.id, " cannot be an empty string")); + } + return utils.__assign(utils.__assign({}, field), { validate: function (value) { return utils.__awaiter(_this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + // Absent or not optional empty field + if (value === "" && field.optional === false) { + if (field.nonOptionalErrorMsg !== undefined) { + return [2 /*return*/, field.nonOptionalErrorMsg]; + } + return [2 /*return*/, "ERROR_NON_OPTIONAL"]; + } + return [4 /*yield*/, field.validate(value)]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); } }); } -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Class. - */ -var EmailPassword = /** @class */ (function (_super) { - genericComponentOverrideContext.__extends(EmailPassword, _super); - function EmailPassword(config, webJSRecipe) { - if (webJSRecipe === void 0) { - webJSRecipe = EmailPasswordWebJS__default.default; - } - var _this = _super.call(this, config) || this; - _this.webJSRecipe = webJSRecipe; - _this.recipeID = EmailPassword.RECIPE_ID; - _this.firstFactorIds = [types.FactorIds.EMAILPASSWORD]; - _this.getDefaultRedirectionURL = function (context) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - if (context.action === "RESET_PASSWORD") { - return [ - 2 /*return*/, - genericComponentOverrideContext.getDefaultRedirectionURLForPath( - this.config, - constants.DEFAULT_RESET_PASSWORD_PATH, - context - ), - ]; - } - return [2 /*return*/, this.getAuthRecipeDefaultRedirectionURL(context)]; - }); - }); - }; - return _this; - } - EmailPassword.prototype.getFirstFactorsForAuthPage = function () { - return this.firstFactorIds; - }; - EmailPassword.init = function (config) { - var normalisedConfig = normaliseEmailPasswordConfig(config); - return { - recipeID: EmailPassword.RECIPE_ID, - authReact: function (appInfo) { - EmailPassword.instance = new EmailPassword( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, normalisedConfig), - { appInfo: appInfo, recipeId: EmailPassword.RECIPE_ID } - ) - ); - return EmailPassword.instance; - }, - webJS: EmailPasswordWebJS__default.default.init( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, normalisedConfig), - { - override: { - functions: function (originalImpl, builder) { - var functions = getFunctionOverrides(normalisedConfig.onHandleEvent); - builder.override(functions); - builder.override(normalisedConfig.override.functions); - return originalImpl; - }, - }, - } - ) - ), - }; - }; - EmailPassword.getInstanceOrThrow = function () { - if (EmailPassword.instance === undefined) { - var error = - "No instance of EmailPassword found. Make sure to call the EmailPassword.init method." + - "See https://supertokens.io/docs/emailpassword/quick-setup/frontend"; - // eslint-disable-next-line supertokens-auth-react/no-direct-window-object - if (typeof window === "undefined") { - error = error + genericComponentOverrideContext.SSR_ERROR; - } - throw Error(error); - } - return EmailPassword.instance; - }; - /* - * Tests methods. - */ - EmailPassword.reset = function () { - if (!genericComponentOverrideContext.isTest()) { - return; - } - EmailPassword.instance = undefined; - return; - }; - EmailPassword.RECIPE_ID = "emailpassword"; - return EmailPassword; -})(index.AuthRecipe); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Class. + */ +var EmailPassword = /** @class */ (function (_super) { + utils.__extends(EmailPassword, _super); + function EmailPassword(config, webJSRecipe) { + if (webJSRecipe === void 0) { webJSRecipe = EmailPasswordWebJS__default.default; } + var _this = _super.call(this, config) || this; + _this.webJSRecipe = webJSRecipe; + _this.recipeID = EmailPassword.RECIPE_ID; + _this.firstFactorIds = [types.FactorIds.EMAILPASSWORD]; + _this.getDefaultRedirectionURL = function (context) { return utils.__awaiter(_this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + if (context.action === "RESET_PASSWORD") { + return [2 /*return*/, utils.getDefaultRedirectionURLForPath(this.config, constants.DEFAULT_RESET_PASSWORD_PATH, context)]; + } + return [2 /*return*/, this.getAuthRecipeDefaultRedirectionURL(context)]; + }); + }); }; + return _this; + } + EmailPassword.prototype.getFirstFactorsForAuthPage = function () { + return this.firstFactorIds; + }; + EmailPassword.init = function (config) { + var normalisedConfig = normaliseEmailPasswordConfig(config); + return { + recipeID: EmailPassword.RECIPE_ID, + authReact: function (appInfo) { + EmailPassword.instance = new EmailPassword(utils.__assign(utils.__assign({}, normalisedConfig), { appInfo: appInfo, recipeId: EmailPassword.RECIPE_ID })); + return EmailPassword.instance; + }, + webJS: EmailPasswordWebJS__default.default.init(utils.__assign(utils.__assign({}, normalisedConfig), { override: { + functions: function (originalImpl, builder) { + var functions = getFunctionOverrides(normalisedConfig.onHandleEvent); + builder.override(functions); + builder.override(normalisedConfig.override.functions); + return originalImpl; + }, + } })), + }; + }; + EmailPassword.getInstanceOrThrow = function () { + if (EmailPassword.instance === undefined) { + var error = "No instance of EmailPassword found. Make sure to call the EmailPassword.init method." + + "See https://supertokens.io/docs/emailpassword/quick-setup/frontend"; + // eslint-disable-next-line supertokens-auth-react/no-direct-window-object + if (typeof window === "undefined") { + error = error + utils.SSR_ERROR; + } + throw Error(error); + } + return EmailPassword.instance; + }; + /* + * Tests methods. + */ + EmailPassword.reset = function () { + if (!utils.isTest()) { + return; + } + EmailPassword.instance = undefined; + return; + }; + EmailPassword.RECIPE_ID = "emailpassword"; + return EmailPassword; +}(index.AuthRecipe)); exports.EmailPassword = EmailPassword; diff --git a/lib/build/emailpassword-shared4.js b/lib/build/emailpassword-shared4.js index 8b145c4f7..5ba637358 100644 --- a/lib/build/emailpassword-shared4.js +++ b/lib/build/emailpassword-shared4.js @@ -1,20 +1,20 @@ -"use strict"; +'use strict'; -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var MANDATORY_FORM_FIELDS_ID_ARRAY = ["email", "password"]; +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var MANDATORY_FORM_FIELDS_ID_ARRAY = ["email", "password"]; var DEFAULT_RESET_PASSWORD_PATH = "/reset-password"; exports.DEFAULT_RESET_PASSWORD_PATH = DEFAULT_RESET_PASSWORD_PATH; diff --git a/lib/build/emailpassword-shared5.js b/lib/build/emailpassword-shared5.js index 97e3b35d7..db8b2a290 100644 --- a/lib/build/emailpassword-shared5.js +++ b/lib/build/emailpassword-shared5.js @@ -1,99 +1,99 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); +var utils = require('./utils.js'); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * defaultEmailValidator. - */ -function defaultEmailValidator(value) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var defaultEmailValidatorRegexp; - return genericComponentOverrideContext.__generator(this, function (_a) { - if (typeof value !== "string") { - return [2 /*return*/, "ERROR_EMAIL_NON_STRING"]; - } - value = value.trim(); - defaultEmailValidatorRegexp = - // eslint-disable-next-line no-useless-escape - /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - // We check if the email syntax is correct - // As per https://github.com/supertokens/supertokens-auth-react/issues/5#issuecomment-709512438 - // Regex from https://stackoverflow.com/a/46181/3867175 - if (value.match(defaultEmailValidatorRegexp) === null) { - return [2 /*return*/, "ERROR_EMAIL_INVALID"]; - } - return [2 /*return*/, undefined]; - }); - }); -} -/* - * defaultPasswordValidator. - * min 8 characters. - * Contains lowercase, uppercase, and numbers. - */ -function defaultPasswordValidator(value) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - if (typeof value !== "string") { - return [2 /*return*/, "ERROR_PASSWORD_NON_STRING"]; - } - // length >= 8 && < 100 - // must have a number and a character - // as per https://github.com/supertokens/supertokens-auth-react/issues/5#issuecomment-709512438 - if (value.length < 8) { - return [2 /*return*/, "ERROR_PASSWORD_TOO_SHORT"]; - } - if (value.length >= 100) { - return [2 /*return*/, "ERROR_PASSWORD_TOO_LONG"]; - } - if (value.match(/^.*[A-Za-z]+.*$/) === null) { - return [2 /*return*/, "ERROR_PASSWORD_NO_ALPHA"]; - } - if (value.match(/^.*[0-9]+.*$/) === null) { - return [2 /*return*/, "ERROR_PASSWORD_NO_NUM"]; - } - return [2 /*return*/, undefined]; - }); - }); -} -/* - * defaultLoginPasswordValidator. - * type string - */ -function defaultLoginPasswordValidator(value) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - if (typeof value !== "string") { - return [2 /*return*/, "ERROR_PASSWORD_NON_STRING"]; - } - return [2 /*return*/, undefined]; - }); - }); -} -/* - * defaultValidate - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -function defaultValidate(_) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [2 /*return*/, undefined]; - }); - }); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * defaultEmailValidator. + */ +function defaultEmailValidator(value) { + return utils.__awaiter(this, void 0, void 0, function () { + var defaultEmailValidatorRegexp; + return utils.__generator(this, function (_a) { + if (typeof value !== "string") { + return [2 /*return*/, "ERROR_EMAIL_NON_STRING"]; + } + value = value.trim(); + defaultEmailValidatorRegexp = + // eslint-disable-next-line no-useless-escape + /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + // We check if the email syntax is correct + // As per https://github.com/supertokens/supertokens-auth-react/issues/5#issuecomment-709512438 + // Regex from https://stackoverflow.com/a/46181/3867175 + if (value.match(defaultEmailValidatorRegexp) === null) { + return [2 /*return*/, "ERROR_EMAIL_INVALID"]; + } + return [2 /*return*/, undefined]; + }); + }); +} +/* + * defaultPasswordValidator. + * min 8 characters. + * Contains lowercase, uppercase, and numbers. + */ +function defaultPasswordValidator(value) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + if (typeof value !== "string") { + return [2 /*return*/, "ERROR_PASSWORD_NON_STRING"]; + } + // length >= 8 && < 100 + // must have a number and a character + // as per https://github.com/supertokens/supertokens-auth-react/issues/5#issuecomment-709512438 + if (value.length < 8) { + return [2 /*return*/, "ERROR_PASSWORD_TOO_SHORT"]; + } + if (value.length >= 100) { + return [2 /*return*/, "ERROR_PASSWORD_TOO_LONG"]; + } + if (value.match(/^.*[A-Za-z]+.*$/) === null) { + return [2 /*return*/, "ERROR_PASSWORD_NO_ALPHA"]; + } + if (value.match(/^.*[0-9]+.*$/) === null) { + return [2 /*return*/, "ERROR_PASSWORD_NO_NUM"]; + } + return [2 /*return*/, undefined]; + }); + }); +} +/* + * defaultLoginPasswordValidator. + * type string + */ +function defaultLoginPasswordValidator(value) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + if (typeof value !== "string") { + return [2 /*return*/, "ERROR_PASSWORD_NON_STRING"]; + } + return [2 /*return*/, undefined]; + }); + }); +} +/* + * defaultValidate + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function defaultValidate(_) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, undefined]; + }); + }); } exports.defaultEmailValidator = defaultEmailValidator; diff --git a/lib/build/emailpassword-shared6.js b/lib/build/emailpassword-shared6.js index b8dc26b72..b72d567a8 100644 --- a/lib/build/emailpassword-shared6.js +++ b/lib/build/emailpassword-shared6.js @@ -1,931 +1,372 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var jsxRuntime = require("react/jsx-runtime"); -var React = require("react"); -var constants = require("./emailpassword-shared4.js"); -var button = require("./emailpassword-shared.js"); -require("./index2.js"); -var translationContext = require("./translationContext.js"); +var utils = require('./utils.js'); +var jsxRuntime = require('react/jsx-runtime'); +var React = require('react'); +var constants = require('./emailpassword-shared4.js'); +var button = require('./emailpassword-shared.js'); +require('./index2.js'); +var translationContext = require('./translationContext.js'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } -var React__default = /*#__PURE__*/ _interopDefault(React); +var React__default = /*#__PURE__*/_interopDefault(React); -/* - * Component. - */ -function FormRow(_a) { - var children = _a.children, - hasError = _a.hasError; - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": ["formRow", hasError ? "hasError" : ""].join(" ") }, - { children: children } - ) - ); +/* + * Component. + */ +function FormRow(_a) { + var children = _a.children, hasError = _a.hasError; + return jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": ["formRow", hasError ? "hasError" : ""].join(" ") }, { children: children })); } -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Imports. - */ -/* - * Component. - */ -function CheckedIcon() { - return jsxRuntime.jsx( - "svg", - genericComponentOverrideContext.__assign( - { - xmlns: "http://www.w3.org/2000/svg", - width: "14.862", - height: "12.033", - viewBox: "0 0 14.862 12.033", - "data-supertokens": "checkedIcon", - }, - { - children: jsxRuntime.jsx("path", { - fill: "rgb(var(--palette-primary))", - d: "M12.629 49L5.06 56.572l-2.829-2.829L0 55.977l5.057 5.057.654-.651 9.152-9.152z", - transform: "translate(0 -49)", - }), - } - ) - ); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Imports. + */ +/* + * Component. + */ +function CheckedIcon() { + return (jsxRuntime.jsx("svg", utils.__assign({ xmlns: "http://www.w3.org/2000/svg", width: "14.862", height: "12.033", viewBox: "0 0 14.862 12.033", "data-supertokens": "checkedIcon" }, { children: jsxRuntime.jsx("path", { fill: "rgb(var(--palette-primary))", d: "M12.629 49L5.06 56.572l-2.829-2.829L0 55.977l5.057 5.057.654-.651 9.152-9.152z", transform: "translate(0 -49)" }) }))); } -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Imports. - */ -/* - * Component. - */ -function ErrorIcon() { - return jsxRuntime.jsx( - "svg", - genericComponentOverrideContext.__assign( - { - xmlns: "http://www.w3.org/2000/svg", - width: "17", - height: "15", - viewBox: "0 0 17 15", - "data-supertokens": "errorIcon", - }, - { - children: jsxRuntime.jsxs("g", { - children: [ - jsxRuntime.jsx( - "g", - genericComponentOverrideContext.__assign( - { className: "Asdf", fill: "rgb(var(--palette-error))" }, - { - children: jsxRuntime.jsx("path", { - d: "M13.568 14.75H3.432c-.63 0-1.195-.325-1.512-.869-.317-.544-.32-1.196-.01-1.744l5.067-8.943c.315-.556.884-.887 1.523-.887.639 0 1.208.331 1.523.887l5.067 8.943c.31.548.307 1.2-.01 1.744s-.882.869-1.512.869z", - transform: "translate(-824.894 -352.829) translate(824.894 352.829)", - }), - } - ) - ), - jsxRuntime.jsx( - "text", - genericComponentOverrideContext.__assign( - { - fill: "#fff", - fontSize: "10px", - fontWeight: "700", - transform: "translate(-824.894 -352.829) translate(832.014 365.198)", - }, - { - children: jsxRuntime.jsx( - "tspan", - genericComponentOverrideContext.__assign({ x: "0", y: "0" }, { children: "!" }) - ), - } - ) - ), - ], - }), - } - ) - ); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Imports. + */ +/* + * Component. + */ +function ErrorIcon() { + return (jsxRuntime.jsx("svg", utils.__assign({ xmlns: "http://www.w3.org/2000/svg", width: "17", height: "15", viewBox: "0 0 17 15", "data-supertokens": "errorIcon" }, { children: jsxRuntime.jsxs("g", { children: [jsxRuntime.jsx("g", utils.__assign({ className: "Asdf", fill: "rgb(var(--palette-error))" }, { children: jsxRuntime.jsx("path", { d: "M13.568 14.75H3.432c-.63 0-1.195-.325-1.512-.869-.317-.544-.32-1.196-.01-1.744l5.067-8.943c.315-.556.884-.887 1.523-.887.639 0 1.208.331 1.523.887l5.067 8.943c.31.548.307 1.2-.01 1.744s-.882.869-1.512.869z", transform: "translate(-824.894 -352.829) translate(824.894 352.829)" }) })), jsxRuntime.jsx("text", utils.__assign({ fill: "#fff", fontSize: "10px", fontWeight: "700", transform: "translate(-824.894 -352.829) translate(832.014 365.198)" }, { children: jsxRuntime.jsx("tspan", utils.__assign({ x: "0", y: "0" }, { children: "!" })) }))] }) }))); } -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Imports. - */ -/* - * Component. - */ -function ShowPasswordIcon(_a) { - var showPassword = _a.showPassword; - if (showPassword === true) { - return jsxRuntime.jsx("div", { - children: jsxRuntime.jsx( - "svg", - genericComponentOverrideContext.__assign( - { - xmlns: "http://www.w3.org/2000/svg", - width: "18.391", - height: "16.276", - viewBox: "0 0 18.391 16.276", - "data-supertokens": "showPasswordIcon show", - }, - { - children: jsxRuntime.jsxs("g", { - children: [ - jsxRuntime.jsx("g", { - children: jsxRuntime.jsx("g", { - children: jsxRuntime.jsx("g", { - children: jsxRuntime.jsx("path", { - fill: "rgb(var(--palette-textPrimary))", - d: "M29.289 100.33c-2.4-3.63-5.619-5.63-9.069-5.63s-6.67 2-9.069 5.63a.767.767 0 0 0 0 .845c2.4 3.63 5.619 5.63 9.069 5.63s6.67-2 9.069-5.63a.767.767 0 0 0 0-.845zm-9.069 4.944c-2.785 0-5.435-1.6-7.5-4.519 2.065-2.92 4.715-4.519 7.5-4.519s5.435 1.6 7.5 4.519c-2.064 2.92-4.711 4.519-7.5 4.519z", - transform: - "translate(-822 -420.048) translate(822 422.035) translate(-11.025 -94.7)", - }), - }), - }), - }), - jsxRuntime.jsxs( - "g", - genericComponentOverrideContext.__assign( - { - fill: "rgb(var(--palette-textPrimary))", - stroke: "rgb(var(--palette-inputBackground))", - transform: "translate(-822 -420.048) translate(827.164 424.055)", - }, - { - children: [ - jsxRuntime.jsx("circle", { - cx: "4.036", - cy: "4.036", - r: "4.036", - stroke: "none", - }), - jsxRuntime.jsx("circle", { - cx: "4.036", - cy: "4.036", - r: "3.536", - fill: "none", - }), - ], - } - ) - ), - jsxRuntime.jsx("path", { - fill: "none", - stroke: "#707070", - strokeLinecap: "round", - strokeWidth: "2.25px", - d: "M11.981 0L0 11.981", - transform: "translate(-822 -420.048) translate(825.084 421.639)", - }), - jsxRuntime.jsx("path", { - fill: "none", - stroke: "rgb(var(--palette-inputBackground))", - strokeLinecap: "round", - d: "M13.978 0L0 13.978", - transform: "translate(-822 -420.048) translate(825.084 421.639)", - }), - ], - }), - } - ) - ), - }); - } - return jsxRuntime.jsx("div", { - children: jsxRuntime.jsx( - "svg", - genericComponentOverrideContext.__assign( - { - xmlns: "http://www.w3.org/2000/svg", - width: "18.281", - height: "12.033", - viewBox: "0 0 18.281 12.033", - "data-supertokens": "showPasswordIcon hide", - }, - { - children: jsxRuntime.jsxs("g", { - children: [ - jsxRuntime.jsx("g", { - children: jsxRuntime.jsx("g", { - children: jsxRuntime.jsx("g", { - children: jsxRuntime.jsx("path", { - fill: "rgb(var(--palette-textPrimary))", - d: "M29.18 100.3c-2.384-3.608-5.586-5.6-9.015-5.6s-6.63 1.989-9.015 5.6a.763.763 0 0 0 0 .84c2.384 3.608 5.586 5.6 9.015 5.6s6.63-1.989 9.015-5.6a.763.763 0 0 0 0-.84zm-9.015 4.914c-2.769 0-5.4-1.589-7.459-4.492 2.052-2.9 4.686-4.492 7.459-4.492s5.4 1.589 7.459 4.492c-2.056 2.899-4.686 4.489-7.458 4.489z", - transform: - "translate(-822 -422.088) translate(822 422.088) translate(-11.025 -94.7)", - }), - }), - }), - }), - jsxRuntime.jsxs( - "g", - genericComponentOverrideContext.__assign( - { - fill: "rgb(var(--palette-textPrimary))", - stroke: "rgb(var(--palette-inputBackground))", - transform: "translate(-822 -422.088) translate(827.133 424.096)", - }, - { - children: [ - jsxRuntime.jsx("circle", { - cx: "4.012", - cy: "4.012", - r: "4.012", - stroke: "none", - }), - jsxRuntime.jsx("circle", { - cx: "4.012", - cy: "4.012", - r: "3.512", - fill: "none", - }), - ], - } - ) - ), - ], - }), - } - ) - ), - }); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Imports. + */ +/* + * Component. + */ +function ShowPasswordIcon(_a) { + var showPassword = _a.showPassword; + if (showPassword === true) { + return (jsxRuntime.jsx("div", { children: jsxRuntime.jsx("svg", utils.__assign({ xmlns: "http://www.w3.org/2000/svg", width: "18.391", height: "16.276", viewBox: "0 0 18.391 16.276", "data-supertokens": "showPasswordIcon show" }, { children: jsxRuntime.jsxs("g", { children: [jsxRuntime.jsx("g", { children: jsxRuntime.jsx("g", { children: jsxRuntime.jsx("g", { children: jsxRuntime.jsx("path", { fill: "rgb(var(--palette-textPrimary))", d: "M29.289 100.33c-2.4-3.63-5.619-5.63-9.069-5.63s-6.67 2-9.069 5.63a.767.767 0 0 0 0 .845c2.4 3.63 5.619 5.63 9.069 5.63s6.67-2 9.069-5.63a.767.767 0 0 0 0-.845zm-9.069 4.944c-2.785 0-5.435-1.6-7.5-4.519 2.065-2.92 4.715-4.519 7.5-4.519s5.435 1.6 7.5 4.519c-2.064 2.92-4.711 4.519-7.5 4.519z", transform: "translate(-822 -420.048) translate(822 422.035) translate(-11.025 -94.7)" }) }) }) }), jsxRuntime.jsxs("g", utils.__assign({ fill: "rgb(var(--palette-textPrimary))", stroke: "rgb(var(--palette-inputBackground))", transform: "translate(-822 -420.048) translate(827.164 424.055)" }, { children: [jsxRuntime.jsx("circle", { cx: "4.036", cy: "4.036", r: "4.036", stroke: "none" }), jsxRuntime.jsx("circle", { cx: "4.036", cy: "4.036", r: "3.536", fill: "none" })] })), jsxRuntime.jsx("path", { fill: "none", stroke: "#707070", strokeLinecap: "round", strokeWidth: "2.25px", d: "M11.981 0L0 11.981", transform: "translate(-822 -420.048) translate(825.084 421.639)" }), jsxRuntime.jsx("path", { fill: "none", stroke: "rgb(var(--palette-inputBackground))", strokeLinecap: "round", d: "M13.978 0L0 13.978", transform: "translate(-822 -420.048) translate(825.084 421.639)" })] }) })) })); + } + return (jsxRuntime.jsx("div", { children: jsxRuntime.jsx("svg", utils.__assign({ xmlns: "http://www.w3.org/2000/svg", width: "18.281", height: "12.033", viewBox: "0 0 18.281 12.033", "data-supertokens": "showPasswordIcon hide" }, { children: jsxRuntime.jsxs("g", { children: [jsxRuntime.jsx("g", { children: jsxRuntime.jsx("g", { children: jsxRuntime.jsx("g", { children: jsxRuntime.jsx("path", { fill: "rgb(var(--palette-textPrimary))", d: "M29.18 100.3c-2.384-3.608-5.586-5.6-9.015-5.6s-6.63 1.989-9.015 5.6a.763.763 0 0 0 0 .84c2.384 3.608 5.586 5.6 9.015 5.6s6.63-1.989 9.015-5.6a.763.763 0 0 0 0-.84zm-9.015 4.914c-2.769 0-5.4-1.589-7.459-4.492 2.052-2.9 4.686-4.492 7.459-4.492s5.4 1.589 7.459 4.492c-2.056 2.899-4.686 4.489-7.458 4.489z", transform: "translate(-822 -422.088) translate(822 422.088) translate(-11.025 -94.7)" }) }) }) }), jsxRuntime.jsxs("g", utils.__assign({ fill: "rgb(var(--palette-textPrimary))", stroke: "rgb(var(--palette-inputBackground))", transform: "translate(-822 -422.088) translate(827.133 424.096)" }, { children: [jsxRuntime.jsx("circle", { cx: "4.012", cy: "4.012", r: "4.012", stroke: "none" }), jsxRuntime.jsx("circle", { cx: "4.012", cy: "4.012", r: "3.512", fill: "none" })] }))] }) })) })); } -var Input = function (_a) { - var type = _a.type, - name = _a.name, - hasError = _a.hasError, - autoComplete = _a.autoComplete, - onInputFocus = _a.onInputFocus, - onInputBlur = _a.onInputBlur, - onChange = _a.onChange, - value = _a.value, - placeholder = _a.placeholder, - validated = _a.validated, - autofocus = _a.autofocus; - var t = translationContext.useTranslation(); - var _b = React.useState(false), - showPassword = _b[0], - setShowPassword = _b[1]; - /* - * Method. - */ - function handleFocus() { - if (onInputFocus !== undefined) { - onInputFocus(value); - } - } - function handleBlur() { - if (onInputBlur !== undefined) { - onInputBlur(value); - } - } - function handleChange(event) { - if (onChange) { - onChange(event.target.value); - } - } - if (autoComplete === undefined) { - autoComplete = "off"; - } - var inputType = type; - if (type === "password" && showPassword === true) { - inputType = "text"; - } - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "inputContainer" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": ["inputWrapper", hasError ? "inputError" : ""].join(" ") }, - { - children: [ - jsxRuntime.jsx("input", { - autoFocus: autofocus, - autoComplete: autoComplete, - "data-supertokens": "input input-".concat(name), - className: "supertokens-input", - onFocus: handleFocus, - onBlur: handleBlur, - type: inputType, - name: name, - placeholder: t(placeholder), - onChange: handleChange, - value: value, - }), - hasError === true && - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "inputAdornment inputAdornmentError" }, - { children: jsxRuntime.jsx(ErrorIcon, {}) } - ) - ), - validated === true && - hasError === false && - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "inputAdornment inputAdornmentSuccess" }, - { children: jsxRuntime.jsx(CheckedIcon, {}) } - ) - ), - type === "password" && - value.length > 0 && - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { - onClick: function () { - return setShowPassword(showPassword === false); - }, - "data-supertokens": "inputAdornment showPassword", - }, - { - children: jsxRuntime.jsx(ShowPasswordIcon, { - showPassword: showPassword, - }), - } - ) - ), - ], - } - ) - ), - } - ) - ); +var Input = function (_a) { + var type = _a.type, name = _a.name, hasError = _a.hasError, autoComplete = _a.autoComplete, onInputFocus = _a.onInputFocus, onInputBlur = _a.onInputBlur, onChange = _a.onChange, value = _a.value, placeholder = _a.placeholder, validated = _a.validated, autofocus = _a.autofocus; + var t = translationContext.useTranslation(); + var _b = React.useState(false), showPassword = _b[0], setShowPassword = _b[1]; + /* + * Method. + */ + function handleFocus() { + if (onInputFocus !== undefined) { + onInputFocus(value); + } + } + function handleBlur() { + if (onInputBlur !== undefined) { + onInputBlur(value); + } + } + function handleChange(event) { + if (onChange) { + onChange(event.target.value); + } + } + if (autoComplete === undefined) { + autoComplete = "off"; + } + var inputType = type; + if (type === "password" && showPassword === true) { + inputType = "text"; + } + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "inputContainer" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": ["inputWrapper", hasError ? "inputError" : ""].join(" ") }, { children: [jsxRuntime.jsx("input", { autoFocus: autofocus, autoComplete: autoComplete, "data-supertokens": "input input-".concat(name), className: "supertokens-input", onFocus: handleFocus, onBlur: handleBlur, type: inputType, name: name, placeholder: t(placeholder), onChange: handleChange, value: value }), hasError === true && (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "inputAdornment inputAdornmentError" }, { children: jsxRuntime.jsx(ErrorIcon, {}) }))), validated === true && hasError === false && (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "inputAdornment inputAdornmentSuccess" }, { children: jsxRuntime.jsx(CheckedIcon, {}) }))), type === "password" && value.length > 0 && (jsxRuntime.jsx("div", utils.__assign({ onClick: function () { return setShowPassword(showPassword === false); }, "data-supertokens": "inputAdornment showPassword" }, { children: jsxRuntime.jsx(ShowPasswordIcon, { showPassword: showPassword }) })))] })) }))); }; -function InputError(_a) { - var error = _a.error; - var t = translationContext.useTranslation(); - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign({ "data-supertokens": "inputErrorMessage" }, { children: t(error) }) - ); +function InputError(_a) { + var error = _a.error; + var t = translationContext.useTranslation(); + return jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "inputErrorMessage" }, { children: t(error) })); } -function Label(_a) { - var value = _a.value, - showIsRequired = _a.showIsRequired; - var t = translationContext.useTranslation(); - return jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "label" }, - { children: [t(value), showIsRequired && value && value.trim() !== "" && " *"] } - ) - ); +function Label(_a) { + var value = _a.value, showIsRequired = _a.showIsRequired; + var t = translationContext.useTranslation(); + return (jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "label" }, { children: [t(value), showIsRequired && value && value.trim() !== "" && " *"] }))); } -var fetchDefaultValue = function (field) { - if (field.getDefaultValue !== undefined) { - var defaultValue = field.getDefaultValue(); - if (typeof defaultValue !== "string") { - throw new Error("getDefaultValue for ".concat(field.id, " must return a string")); - } else { - return defaultValue; - } - } - return ""; -}; -function InputComponentWrapper(props) { - var field = props.field, - type = props.type, - fstate = props.fstate, - onInputFocus = props.onInputFocus, - onInputBlur = props.onInputBlur, - onInputChange = props.onInputChange; - var useCallbackOnInputFocus = React.useCallback( - function (value) { - onInputFocus({ - id: field.id, - value: value, - }); - }, - [onInputFocus, field.id] - ); - var useCallbackOnInputBlur = React.useCallback( - function (value) { - onInputBlur({ - id: field.id, - value: value, - }); - }, - [onInputBlur, field.id] - ); - var useCallbackOnInputChange = React.useCallback( - function (value) { - onInputChange({ - id: field.id, - value: value, - }); - }, - [onInputChange, field.id] - ); - return field.inputComponent !== undefined - ? jsxRuntime.jsx( - field.inputComponent, - { - type: type, - name: field.id, - validated: fstate.validated === true, - placeholder: field.placeholder, - value: fstate.value, - autoComplete: field.autoComplete, - autofocus: field.autofocus, - onInputFocus: useCallbackOnInputFocus, - onInputBlur: useCallbackOnInputBlur, - onChange: useCallbackOnInputChange, - hasError: fstate.error !== undefined, - }, - field.id - ) - : jsxRuntime.jsx( - Input, - { - type: type, - name: field.id, - validated: fstate.validated === true, - placeholder: field.placeholder, - value: fstate.value, - autoComplete: field.autoComplete, - onInputFocus: useCallbackOnInputFocus, - onInputBlur: useCallbackOnInputBlur, - onChange: useCallbackOnInputChange, - autofocus: field.autofocus, - hasError: fstate.error !== undefined, - }, - field.id - ); -} -var FormBase = function (props) { - var footer = props.footer, - buttonLabel = props.buttonLabel, - showLabels = props.showLabels, - validateOnBlur = props.validateOnBlur, - formFields = props.formFields; - var unmounting = React.useRef(new AbortController()); - React.useEffect( - function () { - // We need this because in some cases this gets called multiple times - unmounting.current = new AbortController(); - return function () { - unmounting.current.abort(); - }; - }, - [unmounting] - ); - var _a = React.useState( - props.formFields.map(function (f) { - return { id: f.id, value: fetchDefaultValue(f) }; - }) - ), - fieldStates = _a[0], - setFieldStates = _a[1]; - React.useEffect( - function () { - setFieldStates(function (fs) { - var ret = fs; - var fieldsWithoutState = props.formFields.filter(function (f) { - return !fieldStates.some(function (s) { - return f.id === s.id; - }); - }); - // If there is a formfield missing from the states array, we fill with the default value - if (fieldsWithoutState.length > 0) { - fs = genericComponentOverrideContext.__spreadArray( - genericComponentOverrideContext.__spreadArray([], fs, true), - fieldsWithoutState.map(function (f) { - return { id: f.id, value: fetchDefaultValue(f) }; - }), - true - ); - } - // If a field has been removed from formFields, we want to remove it from the states array as well. - if ( - fieldStates.some(function (s) { - return !props.formFields.some(function (f) { - return f.id === s.id; - }); - }) - ) { - ret = fs.filter(function (s) { - return props.formFields.some(function (f) { - return f.id === s.id; - }); - }); - } - return ret; - }); - }, - [props.formFields, setFieldStates] - ); - var _b = React.useState(false), - isLoading = _b[0], - setIsLoading = _b[1]; - var updateFieldState = React.useCallback( - function (id, update) { - setFieldStates(function (os) { - var field = os.find(function (f) { - return f.id === id; - }); - if (field === undefined) { - return genericComponentOverrideContext.__spreadArray( - genericComponentOverrideContext.__spreadArray([], os, true), - [update({ id: id, value: "" })], - false - ); - } - return os - .filter(function (f) { - return f.id !== field.id; - }) - .concat(update(field)); - }); - }, - [setFieldStates] - ); - var onInputFocus = React.useCallback( - function (field) { - updateFieldState(field.id, function (os) { - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, os), { - validated: false, - }); - }); - }, - [updateFieldState] - ); - var onInputBlur = React.useCallback( - function (field) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var fieldConfig, error, _a; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!validateOnBlur) { - return [2 /*return*/]; - } - fieldConfig = props.formFields.find(function (f) { - return f.id === field.id; - }); - if (!(fieldConfig && field.value !== "")) return [3 /*break*/, 2]; - return [4 /*yield*/, fieldConfig.validate(field.value)]; - case 1: - _a = _b.sent(); - return [3 /*break*/, 3]; - case 2: - _a = undefined; - _b.label = 3; - case 3: - error = _a; - updateFieldState(field.id, function (os) { - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, os), - { error: error, validated: error === undefined && field.value.length !== 0 } - ); - }); - return [2 /*return*/]; - } - }); - }); - }, - [validateOnBlur, updateFieldState, props.formFields] - ); - var onInputChange = React.useCallback( - function (field) { - if (typeof field.value !== "string") { - throw new Error("".concat(field.id, " value must be a string")); - } - updateFieldState(field.id, function (os) { - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, os), { - value: field.value, - error: undefined, - }); - }); - props.clearError(); - }, - [updateFieldState] - ); - var onFormSubmit = React.useCallback( - function (e) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var apiFields, - fieldUpdates, - _a, - result, - generalError, - fetchError, - _loop_1, - _i, - _b, - field, - errorFields_1, - getErrorMessage_1; - return genericComponentOverrideContext.__generator(this, function (_c) { - switch (_c.label) { - case 0: - // Prevent default event propagation. - e.preventDefault(); - // Set loading state. - setIsLoading(true); - setFieldStates(function (os) { - return os.map(function (fs) { - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, fs), - { error: undefined } - ); - }); - }); - apiFields = - formFields === null || formFields === void 0 - ? void 0 - : formFields.map(function (field) { - var fieldState = - fieldStates === null || fieldStates === void 0 - ? void 0 - : fieldStates.find(function (fs) { - return fs.id === field.id; - }); - return { - id: field.id, - value: fieldState === undefined ? "" : fieldState.value, - }; - }); - fieldUpdates = []; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [ - 4 /*yield*/, - genericComponentOverrideContext.handleCallAPI({ - apiFields: apiFields, - fieldUpdates: fieldUpdates, - callAPI: props.callAPI, - }), - ]; - case 2: - (_a = _c.sent()), - (result = _a.result), - (generalError = _a.generalError), - (fetchError = _a.fetchError); - if ( - unmounting === null || unmounting === void 0 - ? void 0 - : unmounting.current.signal.aborted - ) { - return [2 /*return*/]; - } - if (generalError !== undefined || (result !== undefined && result.status !== "OK")) { - _loop_1 = function (field) { - var update = fieldUpdates.find(function (f) { - return f.id === field.id; - }); - if ((update || field.clearOnSubmit === true) && updateFieldState) { - // We can do these one by one, it's almost never more than one field - updateFieldState(field.id, function (os) { - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, os), - { value: update ? update.value : "" } - ); - }); - } - }; - for (_i = 0, _b = formFields || []; _i < _b.length; _i++) { - field = _b[_i]; - _loop_1(field); - } - } - if (generalError !== undefined) { - props.onError(generalError.message); - } else if (fetchError !== undefined) { - if (props.onFetchError) { - props.onFetchError(fetchError); - } else { - throw fetchError; - } - } else { - // If successful - if (result.status === "OK") { - setIsLoading(false); - props.clearError(); - if (props.onSuccess !== undefined) { - props.onSuccess(result); - } - } - if ( - unmounting === null || unmounting === void 0 - ? void 0 - : unmounting.current.signal.aborted - ) { - return [2 /*return*/]; - } - // If field error. - if (result.status === "FIELD_ERROR") { - errorFields_1 = result.formFields; - getErrorMessage_1 = function (fs) { - var _a; - var errorMessage = - (_a = errorFields_1.find(function (ef) { - return ef.id === fs.id; - })) === null || _a === void 0 - ? void 0 - : _a.error; - if (errorMessage === "Field is not optional") { - var fieldConfigData = - formFields === null || formFields === void 0 - ? void 0 - : formFields.find(function (f) { - return f.id === fs.id; - }); - // replace non-optional server error message from nonOptionalErrorMsg - if ( - (fieldConfigData === null || fieldConfigData === void 0 - ? void 0 - : fieldConfigData.nonOptionalErrorMsg) !== undefined - ) { - return fieldConfigData === null || fieldConfigData === void 0 - ? void 0 - : fieldConfigData.nonOptionalErrorMsg; - } - } - return errorMessage; - }; - setFieldStates(function (os) { - return os.map(function (fs) { - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, fs), - { error: getErrorMessage_1(fs) } - ); - }); - }); - } - } - return [3 /*break*/, 5]; - case 3: - _c.sent(); - props.onError("SOMETHING_WENT_WRONG_ERROR"); - return [3 /*break*/, 5]; - case 4: - setIsLoading(false); - return [7 /*endfinally*/]; - case 5: - return [2 /*return*/]; - } - }); - }); - }, - [setIsLoading, setFieldStates, props, formFields, fieldStates, updateFieldState] - ); - return jsxRuntime.jsx( - FormStateContext.Provider, - genericComponentOverrideContext.__assign( - { value: fieldStates }, - { - children: jsxRuntime.jsxs( - "form", - genericComponentOverrideContext.__assign( - { - autoComplete: "on", - noValidate: true, - onSubmit: onFormSubmit, - "data-supertokens": props.formDataSupertokens, - }, - { - children: [ - formFields - .filter(function (f) { - return f.hidden !== true; - }) - .map(function (field) { - var type = "text"; - // If email or password, replace field type. - if (constants.MANDATORY_FORM_FIELDS_ID_ARRAY.includes(field.id)) { - type = field.id; - } - if (field.id === "confirm-password") { - type = "password"; - } - var fstate = fieldStates.find(function (s) { - return s.id === field.id; - }) || { - id: field.id, - value: fetchDefaultValue(field), - }; - return jsxRuntime.jsx( - FormRow, - genericComponentOverrideContext.__assign( - { hasError: fstate.error !== undefined }, - { - children: jsxRuntime.jsxs(React.Fragment, { - children: [ - showLabels && - (field.labelComponent !== undefined - ? field.labelComponent - : jsxRuntime.jsx(Label, { - value: field.label, - showIsRequired: field.showIsRequired, - })), - jsxRuntime.jsx(InputComponentWrapper, { - type: type, - field: field, - fstate: fstate, - onInputFocus: onInputFocus, - onInputBlur: onInputBlur, - onInputChange: onInputChange, - }), - fstate.error && - jsxRuntime.jsx(InputError, { error: fstate.error }), - ], - }), - } - ), - field.id - ); - }), - jsxRuntime.jsx( - FormRow, - { - children: jsxRuntime.jsxs(React.Fragment, { - children: [ - jsxRuntime.jsx(button.Button, { - disabled: isLoading, - isLoading: isLoading, - type: "submit", - label: buttonLabel, - }), - footer, - ], - }), - }, - "form-button" - ), - ], - } - ) - ), - } - ) - ); -}; -var FormStateContext = React__default.default.createContext(undefined); -var useFormFields = function () { - var ctx = React.useContext(FormStateContext); - if (ctx === undefined) { - throw new Error("useFormState used outside FormBase"); - } - return ctx; +var fetchDefaultValue = function (field) { + if (field.getDefaultValue !== undefined) { + var defaultValue = field.getDefaultValue(); + if (typeof defaultValue !== "string") { + throw new Error("getDefaultValue for ".concat(field.id, " must return a string")); + } + else { + return defaultValue; + } + } + return ""; +}; +function InputComponentWrapper(props) { + var field = props.field, type = props.type, fstate = props.fstate, onInputFocus = props.onInputFocus, onInputBlur = props.onInputBlur, onInputChange = props.onInputChange; + var useCallbackOnInputFocus = React.useCallback(function (value) { + onInputFocus({ + id: field.id, + value: value, + }); + }, [onInputFocus, field.id]); + var useCallbackOnInputBlur = React.useCallback(function (value) { + onInputBlur({ + id: field.id, + value: value, + }); + }, [onInputBlur, field.id]); + var useCallbackOnInputChange = React.useCallback(function (value) { + onInputChange({ + id: field.id, + value: value, + }); + }, [onInputChange, field.id]); + return field.inputComponent !== undefined ? (jsxRuntime.jsx(field.inputComponent, { type: type, name: field.id, validated: fstate.validated === true, placeholder: field.placeholder, value: fstate.value, autoComplete: field.autoComplete, autofocus: field.autofocus, onInputFocus: useCallbackOnInputFocus, onInputBlur: useCallbackOnInputBlur, onChange: useCallbackOnInputChange, hasError: fstate.error !== undefined }, field.id)) : (jsxRuntime.jsx(Input, { type: type, name: field.id, validated: fstate.validated === true, placeholder: field.placeholder, value: fstate.value, autoComplete: field.autoComplete, onInputFocus: useCallbackOnInputFocus, onInputBlur: useCallbackOnInputBlur, onChange: useCallbackOnInputChange, autofocus: field.autofocus, hasError: fstate.error !== undefined }, field.id)); +} +var FormBase = function (props) { + var footer = props.footer, buttonLabel = props.buttonLabel, showLabels = props.showLabels, validateOnBlur = props.validateOnBlur, formFields = props.formFields; + var unmounting = React.useRef(new AbortController()); + React.useEffect(function () { + // We need this because in some cases this gets called multiple times + unmounting.current = new AbortController(); + return function () { + unmounting.current.abort(); + }; + }, [unmounting]); + var _a = React.useState(props.formFields.map(function (f) { return ({ id: f.id, value: fetchDefaultValue(f) }); })), fieldStates = _a[0], setFieldStates = _a[1]; + React.useEffect(function () { + setFieldStates(function (fs) { + var ret = fs; + var fieldsWithoutState = props.formFields.filter(function (f) { return !fieldStates.some(function (s) { return f.id === s.id; }); }); + // If there is a formfield missing from the states array, we fill with the default value + if (fieldsWithoutState.length > 0) { + fs = utils.__spreadArray(utils.__spreadArray([], fs, true), fieldsWithoutState.map(function (f) { return ({ id: f.id, value: fetchDefaultValue(f) }); }), true); + } + // If a field has been removed from formFields, we want to remove it from the states array as well. + if (fieldStates.some(function (s) { return !props.formFields.some(function (f) { return f.id === s.id; }); })) { + ret = fs.filter(function (s) { return props.formFields.some(function (f) { return f.id === s.id; }); }); + } + return ret; + }); + }, [props.formFields, setFieldStates]); + var _b = React.useState(false), isLoading = _b[0], setIsLoading = _b[1]; + var updateFieldState = React.useCallback(function (id, update) { + setFieldStates(function (os) { + var field = os.find(function (f) { return f.id === id; }); + if (field === undefined) { + return utils.__spreadArray(utils.__spreadArray([], os, true), [update({ id: id, value: "" })], false); + } + return os.filter(function (f) { return f.id !== field.id; }).concat(update(field)); + }); + }, [setFieldStates]); + var onInputFocus = React.useCallback(function (field) { + updateFieldState(field.id, function (os) { return (utils.__assign(utils.__assign({}, os), { validated: false })); }); + }, [updateFieldState]); + var onInputBlur = React.useCallback(function (field) { return utils.__awaiter(void 0, void 0, void 0, function () { + var fieldConfig, error, _a; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!validateOnBlur) { + return [2 /*return*/]; + } + fieldConfig = props.formFields.find(function (f) { return f.id === field.id; }); + if (!(fieldConfig && field.value !== "")) return [3 /*break*/, 2]; + return [4 /*yield*/, fieldConfig.validate(field.value)]; + case 1: + _a = _b.sent(); + return [3 /*break*/, 3]; + case 2: + _a = undefined; + _b.label = 3; + case 3: + error = _a; + updateFieldState(field.id, function (os) { return (utils.__assign(utils.__assign({}, os), { error: error, validated: error === undefined && field.value.length !== 0 })); }); + return [2 /*return*/]; + } + }); + }); }, [validateOnBlur, updateFieldState, props.formFields]); + var onInputChange = React.useCallback(function (field) { + if (typeof field.value !== "string") { + throw new Error("".concat(field.id, " value must be a string")); + } + updateFieldState(field.id, function (os) { return (utils.__assign(utils.__assign({}, os), { value: field.value, error: undefined })); }); + props.clearError(); + }, [updateFieldState]); + var onFormSubmit = React.useCallback(function (e) { return utils.__awaiter(void 0, void 0, void 0, function () { + var apiFields, fieldUpdates, _a, result, generalError, fetchError, _loop_1, _i, _b, field, errorFields_1, getErrorMessage_1; + return utils.__generator(this, function (_c) { + switch (_c.label) { + case 0: + // Prevent default event propagation. + e.preventDefault(); + // Set loading state. + setIsLoading(true); + setFieldStates(function (os) { return os.map(function (fs) { return (utils.__assign(utils.__assign({}, fs), { error: undefined })); }); }); + apiFields = formFields === null || formFields === void 0 ? void 0 : formFields.map(function (field) { + var fieldState = fieldStates === null || fieldStates === void 0 ? void 0 : fieldStates.find(function (fs) { return fs.id === field.id; }); + return { + id: field.id, + value: fieldState === undefined ? "" : fieldState.value, + }; + }); + fieldUpdates = []; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, utils.handleCallAPI({ + apiFields: apiFields, + fieldUpdates: fieldUpdates, + callAPI: props.callAPI, + })]; + case 2: + _a = _c.sent(), result = _a.result, generalError = _a.generalError, fetchError = _a.fetchError; + if (unmounting === null || unmounting === void 0 ? void 0 : unmounting.current.signal.aborted) { + return [2 /*return*/]; + } + if (generalError !== undefined || (result !== undefined && result.status !== "OK")) { + _loop_1 = function (field) { + var update = fieldUpdates.find(function (f) { return f.id === field.id; }); + if ((update || field.clearOnSubmit === true) && updateFieldState) { + // We can do these one by one, it's almost never more than one field + updateFieldState(field.id, function (os) { return (utils.__assign(utils.__assign({}, os), { value: update ? update.value : "" })); }); + } + }; + for (_i = 0, _b = formFields || []; _i < _b.length; _i++) { + field = _b[_i]; + _loop_1(field); + } + } + if (generalError !== undefined) { + props.onError(generalError.message); + } + else if (fetchError !== undefined) { + if (props.onFetchError) { + props.onFetchError(fetchError); + } + else { + throw fetchError; + } + } + else { + // If successful + if (result.status === "OK") { + setIsLoading(false); + props.clearError(); + if (props.onSuccess !== undefined) { + props.onSuccess(result); + } + } + if (unmounting === null || unmounting === void 0 ? void 0 : unmounting.current.signal.aborted) { + return [2 /*return*/]; + } + // If field error. + if (result.status === "FIELD_ERROR") { + errorFields_1 = result.formFields; + getErrorMessage_1 = function (fs) { + var _a; + var errorMessage = (_a = errorFields_1.find(function (ef) { return ef.id === fs.id; })) === null || _a === void 0 ? void 0 : _a.error; + if (errorMessage === "Field is not optional") { + var fieldConfigData = formFields === null || formFields === void 0 ? void 0 : formFields.find(function (f) { return f.id === fs.id; }); + // replace non-optional server error message from nonOptionalErrorMsg + if ((fieldConfigData === null || fieldConfigData === void 0 ? void 0 : fieldConfigData.nonOptionalErrorMsg) !== undefined) { + return fieldConfigData === null || fieldConfigData === void 0 ? void 0 : fieldConfigData.nonOptionalErrorMsg; + } + } + return errorMessage; + }; + setFieldStates(function (os) { return os.map(function (fs) { return (utils.__assign(utils.__assign({}, fs), { error: getErrorMessage_1(fs) })); }); }); + } + } + return [3 /*break*/, 5]; + case 3: + _c.sent(); + props.onError("SOMETHING_WENT_WRONG_ERROR"); + return [3 /*break*/, 5]; + case 4: + setIsLoading(false); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }, [setIsLoading, setFieldStates, props, formFields, fieldStates, updateFieldState]); + return (jsxRuntime.jsx(FormStateContext.Provider, utils.__assign({ value: fieldStates }, { children: jsxRuntime.jsxs("form", utils.__assign({ autoComplete: "on", noValidate: true, onSubmit: onFormSubmit, "data-supertokens": props.formDataSupertokens }, { children: [formFields + .filter(function (f) { return f.hidden !== true; }) + .map(function (field) { + var type = "text"; + // If email or password, replace field type. + if (constants.MANDATORY_FORM_FIELDS_ID_ARRAY.includes(field.id)) { + type = field.id; + } + if (field.id === "confirm-password") { + type = "password"; + } + var fstate = fieldStates.find(function (s) { return s.id === field.id; }) || { + id: field.id, + value: fetchDefaultValue(field), + }; + return (jsxRuntime.jsx(FormRow, utils.__assign({ hasError: fstate.error !== undefined }, { children: jsxRuntime.jsxs(React.Fragment, { children: [showLabels && + (field.labelComponent !== undefined ? (field.labelComponent) : (jsxRuntime.jsx(Label, { value: field.label, showIsRequired: field.showIsRequired }))), jsxRuntime.jsx(InputComponentWrapper, { type: type, field: field, fstate: fstate, onInputFocus: onInputFocus, onInputBlur: onInputBlur, onInputChange: onInputChange }), fstate.error && jsxRuntime.jsx(InputError, { error: fstate.error })] }) }), field.id)); + }), jsxRuntime.jsx(FormRow, { children: jsxRuntime.jsxs(React.Fragment, { children: [jsxRuntime.jsx(button.Button, { disabled: isLoading, isLoading: isLoading, type: "submit", label: buttonLabel }), footer] }) }, "form-button")] })) }))); +}; +var FormStateContext = React__default.default.createContext(undefined); +var useFormFields = function () { + var ctx = React.useContext(FormStateContext); + if (ctx === undefined) { + throw new Error("useFormState used outside FormBase"); + } + return ctx; }; exports.ErrorIcon = ErrorIcon; diff --git a/lib/build/emailpassword.js b/lib/build/emailpassword.js index bdb7516d4..a6922cf71 100644 --- a/lib/build/emailpassword.js +++ b/lib/build/emailpassword.js @@ -1,155 +1,113 @@ -"use strict"; +'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, '__esModule', { value: true }); -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var componentOverrideContext = require("./emailpassword-shared2.js"); -var recipe = require("./emailpassword-shared3.js"); -require("supertokens-web-js"); -require("supertokens-web-js/utils/cookieHandler"); -require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -require("supertokens-web-js/utils/windowHandler"); -require("supertokens-web-js/recipe/multitenancy"); -require("supertokens-web-js/utils"); -require("react"); -require("supertokens-web-js/lib/build/error"); -require("supertokens-web-js/utils/normalisedURLDomain"); -require("supertokens-web-js/utils/normalisedURLPath"); -require("react/jsx-runtime"); -require("supertokens-web-js/recipe/emailpassword"); -require("./authRecipe-shared2.js"); -require("./recipeModule-shared.js"); -require("./multifactorauth-shared.js"); -require("supertokens-web-js/recipe/session"); -require("./oauth2provider-shared.js"); -require("supertokens-web-js/recipe/oauth2provider"); -require("./emailpassword-shared4.js"); -require("./authRecipe-shared.js"); -require("./emailpassword-shared5.js"); +var utils = require('./utils.js'); +var componentOverrideContext = require('./emailpassword-shared2.js'); +var recipe = require('./emailpassword-shared3.js'); +require('react'); +require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('supertokens-web-js/utils/normalisedURLPath'); +require('supertokens-web-js/utils/windowHandler'); +require('crypto'); +require('./genericComponentOverrideContext.js'); +require('react/jsx-runtime'); +require('supertokens-web-js/recipe/emailpassword'); +require('./authRecipe-shared2.js'); +require('./recipeModule-shared.js'); +require('./superTokens.js'); +require('supertokens-web-js'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('supertokens-web-js/recipe/multitenancy'); +require('supertokens-web-js/utils'); +require('./multifactorauth-shared.js'); +require('supertokens-web-js/recipe/session'); +require('./oauth2provider-shared.js'); +require('supertokens-web-js/recipe/oauth2provider'); +require('./emailpassword-shared4.js'); +require('./authRecipe-shared.js'); +require('./emailpassword-shared5.js'); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var Wrapper = /** @class */ (function () { - function Wrapper() {} - Wrapper.init = function (config) { - return recipe.EmailPassword.init(config); - }; - Wrapper.signOut = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.EmailPassword.getInstanceOrThrow().signOut({ - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }), - ]; - }); - }); - }; - Wrapper.submitNewPassword = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.EmailPassword.getInstanceOrThrow().webJSRecipe.submitNewPassword( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext(input.userContext), - }) - ), - ]; - }); - }); - }; - Wrapper.sendPasswordResetEmail = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.EmailPassword.getInstanceOrThrow().webJSRecipe.sendPasswordResetEmail( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext(input.userContext), - }) - ), - ]; - }); - }); - }; - Wrapper.signUp = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.EmailPassword.getInstanceOrThrow().webJSRecipe.signUp( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext(input.userContext), - }) - ), - ]; - }); - }); - }; - Wrapper.signIn = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.EmailPassword.getInstanceOrThrow().webJSRecipe.signIn( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext(input.userContext), - }) - ), - ]; - }); - }); - }; - Wrapper.doesEmailExist = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.EmailPassword.getInstanceOrThrow().webJSRecipe.doesEmailExist( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext(input.userContext), - }) - ), - ]; - }); - }); - }; - Wrapper.getResetPasswordTokenFromURL = function (input) { - return recipe.EmailPassword.getInstanceOrThrow().webJSRecipe.getResetPasswordTokenFromURL( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ); - }; - Wrapper.ComponentsOverrideProvider = componentOverrideContext.Provider; - return Wrapper; -})(); -var init = Wrapper.init; -var signOut = Wrapper.signOut; -var submitNewPassword = Wrapper.submitNewPassword; -var sendPasswordResetEmail = Wrapper.sendPasswordResetEmail; -var signUp = Wrapper.signUp; -var signIn = Wrapper.signIn; -var doesEmailExist = Wrapper.doesEmailExist; -var getResetPasswordTokenFromURL = Wrapper.getResetPasswordTokenFromURL; +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var Wrapper = /** @class */ (function () { + function Wrapper() { + } + Wrapper.init = function (config) { + return recipe.EmailPassword.init(config); + }; + Wrapper.signOut = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.EmailPassword.getInstanceOrThrow().signOut({ + userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext), + })]; + }); + }); + }; + Wrapper.submitNewPassword = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.EmailPassword.getInstanceOrThrow().webJSRecipe.submitNewPassword(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input.userContext) }))]; + }); + }); + }; + Wrapper.sendPasswordResetEmail = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.EmailPassword.getInstanceOrThrow().webJSRecipe.sendPasswordResetEmail(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input.userContext) }))]; + }); + }); + }; + Wrapper.signUp = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.EmailPassword.getInstanceOrThrow().webJSRecipe.signUp(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input.userContext) }))]; + }); + }); + }; + Wrapper.signIn = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.EmailPassword.getInstanceOrThrow().webJSRecipe.signIn(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input.userContext) }))]; + }); + }); + }; + Wrapper.doesEmailExist = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.EmailPassword.getInstanceOrThrow().webJSRecipe.doesEmailExist(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input.userContext) }))]; + }); + }); + }; + Wrapper.getResetPasswordTokenFromURL = function (input) { + return recipe.EmailPassword.getInstanceOrThrow().webJSRecipe.getResetPasswordTokenFromURL(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) })); + }; + Wrapper.ComponentsOverrideProvider = componentOverrideContext.Provider; + return Wrapper; +}()); +var init = Wrapper.init; +var signOut = Wrapper.signOut; +var submitNewPassword = Wrapper.submitNewPassword; +var sendPasswordResetEmail = Wrapper.sendPasswordResetEmail; +var signUp = Wrapper.signUp; +var signIn = Wrapper.signIn; +var doesEmailExist = Wrapper.doesEmailExist; +var getResetPasswordTokenFromURL = Wrapper.getResetPasswordTokenFromURL; var EmailPasswordComponentsOverrideProvider = Wrapper.ComponentsOverrideProvider; exports.EmailPasswordComponentsOverrideProvider = EmailPasswordComponentsOverrideProvider; diff --git a/lib/build/emailpasswordprebuiltui.js b/lib/build/emailpasswordprebuiltui.js index 74b0615ef..b1a8bf081 100644 --- a/lib/build/emailpasswordprebuiltui.js +++ b/lib/build/emailpasswordprebuiltui.js @@ -1,74 +1,67 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var jsxRuntime = require("react/jsx-runtime"); -var NormalisedURLPath = require("supertokens-web-js/utils/normalisedURLPath"); -var uiEntry = require("./index2.js"); -require("./multifactorauth.js"); -var componentOverrideContext = require("./emailpassword-shared2.js"); -var React = require("react"); -var translations = require("./emailverification-shared2.js"); -var translationContext = require("./translationContext.js"); -var arrowLeftIcon = require("./arrowLeftIcon.js"); -var formBase = require("./emailpassword-shared6.js"); -var STGeneralError = require("supertokens-web-js/utils/error"); -var button = require("./emailpassword-shared.js"); -var authCompWrapper = require("./authCompWrapper.js"); -var emailverification = require("./emailverification.js"); -var recipe$1 = require("./emailverification-shared.js"); -var session = require("./session.js"); -var types = require("./multifactorauth-shared.js"); -var recipe = require("./emailpassword-shared3.js"); -var STGeneralError$1 = require("supertokens-web-js/lib/build/error"); -var constants = require("./emailpassword-shared4.js"); -require("supertokens-web-js"); -require("supertokens-web-js/utils/cookieHandler"); -require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -require("supertokens-web-js/utils/windowHandler"); -require("supertokens-web-js/recipe/multitenancy"); -require("supertokens-web-js/utils"); -require("supertokens-web-js/utils/normalisedURLDomain"); -require("react-dom"); -require("./multitenancy-shared.js"); -require("./multifactorauth-shared2.js"); -require("supertokens-web-js/recipe/multifactorauth"); -require("supertokens-web-js/utils/sessionClaimValidatorStore"); -require("./recipeModule-shared.js"); -require("./oauth2provider-shared.js"); -require("supertokens-web-js/recipe/oauth2provider"); -require("./authRecipe-shared.js"); -require("supertokens-web-js/lib/build/normalisedURLPath"); -require("./multifactorauth-shared3.js"); -require("supertokens-web-js/recipe/emailverification"); -require("supertokens-web-js/recipe/session"); -require("./session-shared.js"); -require("supertokens-web-js/recipe/emailpassword"); -require("./authRecipe-shared2.js"); -require("./emailpassword-shared5.js"); +var utils = require('./utils.js'); +var jsxRuntime = require('react/jsx-runtime'); +var NormalisedURLPath = require('supertokens-web-js/utils/normalisedURLPath'); +var uiEntry = require('./index2.js'); +require('./multifactorauth.js'); +var componentOverrideContext = require('./emailpassword-shared2.js'); +var React = require('react'); +var superTokens = require('./superTokens.js'); +var translations = require('./emailverification-shared2.js'); +var translationContext = require('./translationContext.js'); +var arrowLeftIcon = require('./arrowLeftIcon.js'); +var formBase = require('./emailpassword-shared6.js'); +var STGeneralError = require('supertokens-web-js/utils/error'); +var button = require('./emailpassword-shared.js'); +var authCompWrapper = require('./authCompWrapper.js'); +var emailverification = require('./emailverification.js'); +var recipe$1 = require('./emailverification-shared.js'); +var session = require('./session.js'); +var types = require('./multifactorauth-shared.js'); +var recipe = require('./emailpassword-shared3.js'); +var STGeneralError$1 = require('supertokens-web-js/lib/build/error'); +var constants = require('./emailpassword-shared4.js'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('supertokens-web-js/utils/windowHandler'); +require('crypto'); +require('react-dom'); +require('./multitenancy-shared.js'); +require('./genericComponentOverrideContext.js'); +require('./multifactorauth-shared2.js'); +require('supertokens-web-js/recipe/multifactorauth'); +require('supertokens-web-js/utils'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('supertokens-web-js/utils/sessionClaimValidatorStore'); +require('./recipeModule-shared.js'); +require('./oauth2provider-shared.js'); +require('supertokens-web-js/recipe/oauth2provider'); +require('./authRecipe-shared.js'); +require('supertokens-web-js/lib/build/normalisedURLPath'); +require('./multifactorauth-shared3.js'); +require('supertokens-web-js'); +require('supertokens-web-js/recipe/multitenancy'); +require('supertokens-web-js/recipe/emailverification'); +require('supertokens-web-js/recipe/session'); +require('./session-shared.js'); +require('supertokens-web-js/recipe/emailpassword'); +require('./authRecipe-shared2.js'); +require('./emailpassword-shared5.js'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { - if (k !== "default") { + if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: function () { - return e[k]; - }, - } - ); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); } }); } @@ -76,1453 +69,690 @@ function _interopNamespace(e) { return Object.freeze(n); } -var NormalisedURLPath__default = /*#__PURE__*/ _interopDefault(NormalisedURLPath); -var React__namespace = /*#__PURE__*/ _interopNamespace(React); -var STGeneralError__default = /*#__PURE__*/ _interopDefault(STGeneralError); -var STGeneralError__default$1 = /*#__PURE__*/ _interopDefault(STGeneralError$1); +var NormalisedURLPath__default = /*#__PURE__*/_interopDefault(NormalisedURLPath); +var React__namespace = /*#__PURE__*/_interopNamespace(React); +var STGeneralError__default = /*#__PURE__*/_interopDefault(STGeneralError); +var STGeneralError__default$1 = /*#__PURE__*/_interopDefault(STGeneralError$1); -/* - * Component. - */ -function BackToSignInButton(_a) { - var onClick = _a.onClick; - var t = translationContext.useTranslation(); - return jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "secondaryText secondaryLinkWithLeftArrow", onClick: onClick }, - { - children: [ - jsxRuntime.jsx(arrowLeftIcon.ArrowLeftIcon, { color: "rgb(var(--palette-secondaryText))" }), - t("EMAIL_PASSWORD_RESET_SIGN_IN_LINK"), - ], - } - ) - ); +/* + * Component. + */ +function BackToSignInButton(_a) { + var onClick = _a.onClick; + var t = translationContext.useTranslation(); + return (jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "secondaryText secondaryLinkWithLeftArrow", onClick: onClick }, { children: [jsxRuntime.jsx(arrowLeftIcon.ArrowLeftIcon, { color: "rgb(var(--palette-secondaryText))" }), t("EMAIL_PASSWORD_RESET_SIGN_IN_LINK")] }))); } -var EmailPasswordResetPasswordEmail = function (props) { - var t = translationContext.useTranslation(); - var userContext = uiEntry.useUserContext(); - var _a = React.useState("READY"), - status = _a[0], - setStatus = _a[1]; - var _b = React.useState(""), - emailFieldValue = _b[0], - setEmailFieldValue = _b[1]; - var onSuccess = function () { - setStatus("SENT"); - }; - var resend = function () { - setStatus("READY"); - }; - var formFields = props.formFields; - var emailSuccessText = - t("EMAIL_PASSWORD_RESET_SEND_BEFORE_EMAIL") + - (emailFieldValue !== undefined && emailFieldValue.length > 0 - ? emailFieldValue - : t("EMAIL_PASSWORD_RESET_SEND_FALLBACK_EMAIL")) + - t("EMAIL_PASSWORD_RESET_SEND_AFTER_EMAIL"); - if (status === "SENT") { - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row" }, - { - children: [ - jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "primaryText enterEmailSuccessMessage" }, - { - children: [ - emailSuccessText, - jsxRuntime.jsx( - "span", - genericComponentOverrideContext.__assign( - { - "data-supertokens": "link resendEmailLink", - onClick: resend, - }, - { children: t("EMAIL_PASSWORD_RESET_RESEND_LINK") } - ) - ), - ], - } - ) - ), - jsxRuntime.jsx(BackToSignInButton, { onClick: props.onBackButtonClicked }), - ], - } - ) - ), - } - ) - ); - } - // Otherwise, return Form. - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container resetPasswordEmailForm" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row" }, - { - children: [ - jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle withBackButton" }, - { - children: [ - jsxRuntime.jsx(uiEntry.BackButton, { - onClick: props.onBackButtonClicked, - }), - t("EMAIL_PASSWORD_RESET_HEADER_TITLE"), - jsxRuntime.jsx("span", { - "data-supertokens": "backButtonPlaceholder backButtonCommon", - }), - ], - } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerSubtitle secondaryText" }, - { children: t("EMAIL_PASSWORD_RESET_HEADER_SUBTITLE") } - ) - ), - props.error !== undefined && - jsxRuntime.jsx(uiEntry.GeneralError, { error: props.error }), - jsxRuntime.jsx(formBase.FormBase, { - clearError: props.clearError, - onError: props.onError, - formFields: formFields, - buttonLabel: "EMAIL_PASSWORD_RESET_SEND_BTN", - onSuccess: onSuccess, - callAPI: function (formFields) { - return genericComponentOverrideContext.__awaiter( - void 0, - void 0, - void 0, - function () { - var validationErrors, emailField, resp; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - genericComponentOverrideContext.validateForm( - formFields, - props.config.resetPasswordUsingTokenFeature - .enterEmailForm.formFields - ), - ]; - case 1: - validationErrors = _a.sent(); - if (validationErrors.length > 0) { - return [ - 2 /*return*/, - { - status: "FIELD_ERROR", - formFields: validationErrors, - }, - ]; - } - emailField = formFields.find(function (field) { - return field.id === "email"; - }); - if (emailField !== undefined) { - setEmailFieldValue(emailField.value); - } - return [ - 4 /*yield*/, - props.recipeImplementation.sendPasswordResetEmail({ - formFields: formFields, - userContext: userContext, - }), - ]; - case 2: - resp = _a.sent(); - if (resp.status === "PASSWORD_RESET_NOT_ALLOWED") { - return [ - 2 /*return*/, - { - status: "FIELD_ERROR", - formFields: [ - { id: "email", error: resp.reason }, - ], - }, - ]; - } - return [2 /*return*/, resp]; - } - }); - } - ); - }, - showLabels: true, - validateOnBlur: true, - }), - ], - } - ) - ), - } - ) - ); -}; +var EmailPasswordResetPasswordEmail = function (props) { + var t = translationContext.useTranslation(); + var userContext = uiEntry.useUserContext(); + var _a = React.useState("READY"), status = _a[0], setStatus = _a[1]; + var _b = React.useState(""), emailFieldValue = _b[0], setEmailFieldValue = _b[1]; + var onSuccess = function () { + setStatus("SENT"); + }; + var resend = function () { + setStatus("READY"); + }; + var formFields = props.formFields; + var emailSuccessText = t("EMAIL_PASSWORD_RESET_SEND_BEFORE_EMAIL") + + (emailFieldValue !== undefined && emailFieldValue.length > 0 + ? emailFieldValue + : t("EMAIL_PASSWORD_RESET_SEND_FALLBACK_EMAIL")) + + t("EMAIL_PASSWORD_RESET_SEND_AFTER_EMAIL"); + if (status === "SENT") { + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "row" }, { children: [jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "primaryText enterEmailSuccessMessage" }, { children: [emailSuccessText, jsxRuntime.jsx("span", utils.__assign({ "data-supertokens": "link resendEmailLink", onClick: resend }, { children: t("EMAIL_PASSWORD_RESET_RESEND_LINK") }))] })), jsxRuntime.jsx(BackToSignInButton, { onClick: props.onBackButtonClicked })] })) }))); + } + // Otherwise, return Form. + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container resetPasswordEmailForm" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "row" }, { children: [jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "headerTitle withBackButton" }, { children: [jsxRuntime.jsx(uiEntry.BackButton, { onClick: props.onBackButtonClicked }), t("EMAIL_PASSWORD_RESET_HEADER_TITLE"), jsxRuntime.jsx("span", { "data-supertokens": "backButtonPlaceholder backButtonCommon" })] })), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerSubtitle secondaryText" }, { children: t("EMAIL_PASSWORD_RESET_HEADER_SUBTITLE") })), props.error !== undefined && jsxRuntime.jsx(uiEntry.GeneralError, { error: props.error }), jsxRuntime.jsx(formBase.FormBase, { clearError: props.clearError, onError: props.onError, formFields: formFields, buttonLabel: "EMAIL_PASSWORD_RESET_SEND_BTN", onSuccess: onSuccess, callAPI: function (formFields) { return utils.__awaiter(void 0, void 0, void 0, function () { + var validationErrors, emailField, resp; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, utils.validateForm(formFields, props.config.resetPasswordUsingTokenFeature.enterEmailForm.formFields)]; + case 1: + validationErrors = _a.sent(); + if (validationErrors.length > 0) { + return [2 /*return*/, { + status: "FIELD_ERROR", + formFields: validationErrors, + }]; + } + emailField = formFields.find(function (field) { + return field.id === "email"; + }); + if (emailField !== undefined) { + setEmailFieldValue(emailField.value); + } + return [4 /*yield*/, props.recipeImplementation.sendPasswordResetEmail({ + formFields: formFields, + userContext: userContext, + })]; + case 2: + resp = _a.sent(); + if (resp.status === "PASSWORD_RESET_NOT_ALLOWED") { + return [2 /*return*/, { + status: "FIELD_ERROR", + formFields: [{ id: "email", error: resp.reason }], + }]; + } + return [2 /*return*/, resp]; + } + }); + }); }, showLabels: true, validateOnBlur: true })] })) }))); +}; var ResetPasswordEmail = uiEntry.withOverride("EmailPasswordResetPasswordEmail", EmailPasswordResetPasswordEmail); -var EmailPasswordSubmitNewPassword = function (props) { - var t = translationContext.useTranslation(); - var userContext = uiEntry.useUserContext(); - var _a = React.useState("READY"), - status = _a[0], - setStatus = _a[1]; - var onSuccess = function () { - setStatus("SUCCESS"); - }; - var formFields = props.formFields, - onSignInClicked = props.onSignInClicked; - if (status === "SUCCESS") { - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row" }, - { - children: [ - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle" }, - { children: t("EMAIL_PASSWORD_RESET_SUBMIT_PW_SUCCESS_HEADER_TITLE") } - ) - ), - jsxRuntime.jsx( - formBase.FormRow, - { - children: jsxRuntime.jsxs(React.Fragment, { - children: [ - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { - "data-supertokens": - "primaryText submitNewPasswordSuccessMessage", - }, - { - children: t( - "EMAIL_PASSWORD_RESET_SUBMIT_PW_SUCCESS_DESC" - ), - } - ) - ), - jsxRuntime.jsx(button.Button, { - disabled: false, - isLoading: false, - type: "button", - onClick: onSignInClicked, - label: "EMAIL_PASSWORD_RESET_SUBMIT_PW_SUCCESS_SIGN_IN_BTN", - }), - ], - }), - }, - "form-button" - ), - ], - } - ) - ), - } - ) - ); - } - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container resetPasswordPasswordForm" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row" }, - { - children: [ - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle" }, - { children: t("EMAIL_PASSWORD_RESET_SUBMIT_PW_HEADER_TITLE") } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerSubtitle secondaryText" }, - { children: t("EMAIL_PASSWORD_RESET_SUBMIT_PW_HEADER_SUBTITLE") } - ) - ), - props.error !== undefined && - jsxRuntime.jsx(uiEntry.GeneralError, { error: props.error }), - jsxRuntime.jsx(formBase.FormBase, { - formFields: formFields, - clearError: props.clearError, - onError: props.onError, - buttonLabel: "EMAIL_PASSWORD_RESET_SUBMIT_PW_CHANGE_PW_BTN", - onSuccess: onSuccess, - validateOnBlur: true, - callAPI: function (fields) { - return genericComponentOverrideContext.__awaiter( - void 0, - void 0, - void 0, - function () { - var validationErrors, response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - genericComponentOverrideContext.validateForm( - fields, - props.config.resetPasswordUsingTokenFeature - .submitNewPasswordForm.formFields - ), - ]; - case 1: - validationErrors = _a.sent(); - if (validationErrors.length > 0) { - return [ - 2 /*return*/, - { - status: "FIELD_ERROR", - formFields: validationErrors, - }, - ]; - } - // Verify that both passwords match. - if (fields[0].value !== fields[1].value) { - return [ - 2 /*return*/, - { - status: "FIELD_ERROR", - formFields: [ - { - id: fields[1].id, - error: "ERROR_CONFIRM_PASSWORD_NO_MATCH", - }, - ], - }, - ]; - } - return [ - 4 /*yield*/, - props.recipeImplementation.submitNewPassword({ - formFields: fields, - userContext: userContext, - }), - ]; - case 2: - response = _a.sent(); - if ( - response.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR" - ) { - throw new STGeneralError__default.default( - "EMAIL_PASSWORD_RESET_PASSWORD_INVALID_TOKEN_ERROR" - ); - } - return [ - 2 /*return*/, - response.status === "FIELD_ERROR" - ? response - : { - status: "OK", - }, - ]; - } - }); - } - ); - }, - showLabels: true, - }), - ], - } - ) - ), - } - ) - ); -}; +var EmailPasswordSubmitNewPassword = function (props) { + var t = translationContext.useTranslation(); + var userContext = uiEntry.useUserContext(); + var _a = React.useState("READY"), status = _a[0], setStatus = _a[1]; + var onSuccess = function () { + setStatus("SUCCESS"); + }; + var formFields = props.formFields, onSignInClicked = props.onSignInClicked; + if (status === "SUCCESS") { + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "row" }, { children: [jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerTitle" }, { children: t("EMAIL_PASSWORD_RESET_SUBMIT_PW_SUCCESS_HEADER_TITLE") })), jsxRuntime.jsx(formBase.FormRow, { children: jsxRuntime.jsxs(React.Fragment, { children: [jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "primaryText submitNewPasswordSuccessMessage" }, { children: t("EMAIL_PASSWORD_RESET_SUBMIT_PW_SUCCESS_DESC") })), jsxRuntime.jsx(button.Button, { disabled: false, isLoading: false, type: "button", onClick: onSignInClicked, label: "EMAIL_PASSWORD_RESET_SUBMIT_PW_SUCCESS_SIGN_IN_BTN" })] }) }, "form-button")] })) }))); + } + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container resetPasswordPasswordForm" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "row" }, { children: [jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerTitle" }, { children: t("EMAIL_PASSWORD_RESET_SUBMIT_PW_HEADER_TITLE") })), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerSubtitle secondaryText" }, { children: t("EMAIL_PASSWORD_RESET_SUBMIT_PW_HEADER_SUBTITLE") })), props.error !== undefined && jsxRuntime.jsx(uiEntry.GeneralError, { error: props.error }), jsxRuntime.jsx(formBase.FormBase, { formFields: formFields, clearError: props.clearError, onError: props.onError, buttonLabel: "EMAIL_PASSWORD_RESET_SUBMIT_PW_CHANGE_PW_BTN", onSuccess: onSuccess, validateOnBlur: true, callAPI: function (fields) { return utils.__awaiter(void 0, void 0, void 0, function () { + var validationErrors, response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, utils.validateForm(fields, props.config.resetPasswordUsingTokenFeature.submitNewPasswordForm.formFields)]; + case 1: + validationErrors = _a.sent(); + if (validationErrors.length > 0) { + return [2 /*return*/, { + status: "FIELD_ERROR", + formFields: validationErrors, + }]; + } + // Verify that both passwords match. + if (fields[0].value !== fields[1].value) { + return [2 /*return*/, { + status: "FIELD_ERROR", + formFields: [ + { + id: fields[1].id, + error: "ERROR_CONFIRM_PASSWORD_NO_MATCH", + }, + ], + }]; + } + return [4 /*yield*/, props.recipeImplementation.submitNewPassword({ + formFields: fields, + userContext: userContext, + })]; + case 2: + response = _a.sent(); + if (response.status === "RESET_PASSWORD_INVALID_TOKEN_ERROR") { + throw new STGeneralError__default.default("EMAIL_PASSWORD_RESET_PASSWORD_INVALID_TOKEN_ERROR"); + } + return [2 /*return*/, response.status === "FIELD_ERROR" + ? response + : { + status: "OK", + }]; + } + }); + }); }, showLabels: true })] })) }))); +}; var SubmitNewPassword = uiEntry.withOverride("EmailPasswordSubmitNewPassword", EmailPasswordSubmitNewPassword); -/* - * Component. - */ -function ResetPasswordUsingTokenTheme(props) { - /* - * Render. - */ - // If no token, return SubmitNewPassword. - if (props.submitNewPasswordForm !== undefined) { - return jsxRuntime.jsx( - SubmitNewPassword, - genericComponentOverrideContext.__assign({}, props.submitNewPasswordForm) - ); - } - // Otherwise, return EnterEmail. - return jsxRuntime.jsx(ResetPasswordEmail, genericComponentOverrideContext.__assign({}, props.enterEmailForm)); -} -function ResetPasswordUsingTokenThemeWrapper(props) { - var rootStyle = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().rootStyle; - var userStyles = props.submitNewPasswordForm - ? props.config.resetPasswordUsingTokenFeature.submitNewPasswordForm.style - : props.config.resetPasswordUsingTokenFeature.enterEmailForm.style; - return jsxRuntime.jsx( - uiEntry.UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - translations.ThemeBase, - genericComponentOverrideContext.__assign( - { userStyles: [rootStyle, props.config.recipeRootStyle, userStyles] }, - { - children: jsxRuntime.jsx( - ResetPasswordUsingTokenTheme, - genericComponentOverrideContext.__assign({}, props) - ), - } - ) - ), - } - ) - ); +/* + * Component. + */ +function ResetPasswordUsingTokenTheme(props) { + /* + * Render. + */ + // If no token, return SubmitNewPassword. + if (props.submitNewPasswordForm !== undefined) { + return jsxRuntime.jsx(SubmitNewPassword, utils.__assign({}, props.submitNewPasswordForm)); + } + // Otherwise, return EnterEmail. + return jsxRuntime.jsx(ResetPasswordEmail, utils.__assign({}, props.enterEmailForm)); +} +function ResetPasswordUsingTokenThemeWrapper(props) { + var rootStyle = superTokens.SuperTokens.getInstanceOrThrow().rootStyle; + var userStyles = props.submitNewPasswordForm + ? props.config.resetPasswordUsingTokenFeature.submitNewPasswordForm.style + : props.config.resetPasswordUsingTokenFeature.enterEmailForm.style; + return (jsxRuntime.jsx(uiEntry.UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(translations.ThemeBase, utils.__assign({ userStyles: [rootStyle, props.config.recipeRootStyle, userStyles] }, { children: jsxRuntime.jsx(ResetPasswordUsingTokenTheme, utils.__assign({}, props)) })) }))); } -var defaultTranslationsEmailPassword = { - en: genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, uiEntry.defaultTranslationsCommon.en), - translations.defaultTranslationsEmailVerification.en - ), - { - EMAIL_PASSWORD_EMAIL_LABEL: "Email", - EMAIL_PASSWORD_EMAIL_PLACEHOLDER: "Email address", - EMAIL_PASSWORD_PASSWORD_LABEL: "Password", - EMAIL_PASSWORD_PASSWORD_PLACEHOLDER: "Password", - EMAIL_PASSWORD_SIGN_IN_FORGOT_PW_LINK: "Forgot password?", - EMAIL_PASSWORD_SIGN_IN_SUBMIT_BTN: "SIGN IN", - EMAIL_PASSWORD_SIGN_IN_WRONG_CREDENTIALS_ERROR: "Incorrect email and password combination", - EMAIL_PASSWORD_SIGN_UP_SUBMIT_BTN: "SIGN UP", - EMAIL_PASSWORD_EMAIL_ALREADY_EXISTS: "This email already exists. Please sign in instead", - EMAIL_PASSWORD_RESET_HEADER_TITLE: "Reset your password", - EMAIL_PASSWORD_RESET_HEADER_SUBTITLE: "We will send you an email to reset your password", - EMAIL_PASSWORD_RESET_SEND_FALLBACK_EMAIL: "your account", - EMAIL_PASSWORD_RESET_SEND_BEFORE_EMAIL: "A password reset email has been sent to ", - EMAIL_PASSWORD_RESET_SEND_AFTER_EMAIL: ", if it exists in our system. ", - EMAIL_PASSWORD_RESET_RESEND_LINK: "Resend or change email", - EMAIL_PASSWORD_RESET_SEND_BTN: "Email me", - EMAIL_PASSWORD_RESET_SIGN_IN_LINK: "Sign In", - EMAIL_PASSWORD_RESET_SUBMIT_PW_SUCCESS_HEADER_TITLE: "Success!", - EMAIL_PASSWORD_RESET_SUBMIT_PW_SUCCESS_DESC: "Your password has been updated successfully", - EMAIL_PASSWORD_RESET_SUBMIT_PW_SUCCESS_SIGN_IN_BTN: "SIGN IN", - EMAIL_PASSWORD_NEW_PASSWORD_LABEL: "New password", - EMAIL_PASSWORD_NEW_PASSWORD_PLACEHOLDER: "New password", - EMAIL_PASSWORD_CONFIRM_PASSWORD_LABEL: "Confirm password", - EMAIL_PASSWORD_CONFIRM_PASSWORD_PLACEHOLDER: "Confirm your password", - EMAIL_PASSWORD_RESET_SUBMIT_PW_HEADER_TITLE: "Change your password", - EMAIL_PASSWORD_RESET_SUBMIT_PW_HEADER_SUBTITLE: "Enter a new password below to change your password", - EMAIL_PASSWORD_RESET_SUBMIT_PW_CHANGE_PW_BTN: "CHANGE PASSWORD", - EMAIL_PASSWORD_RESET_PASSWORD_INVALID_TOKEN_ERROR: "Invalid password reset token", - ERROR_EMAIL_NON_STRING: "Email must be of type string", - ERROR_EMAIL_INVALID: "Email is invalid", - ERROR_PASSWORD_NON_STRING: "Password must be of type string", - ERROR_PASSWORD_TOO_SHORT: "Password must contain at least 8 characters, including a number", - ERROR_PASSWORD_TOO_LONG: "Password's length must be lesser than 100 characters", - ERROR_PASSWORD_NO_ALPHA: "Password must contain at least one alphabet", - ERROR_PASSWORD_NO_NUM: "Password must contain at least one number", - ERROR_CONFIRM_PASSWORD_NO_MATCH: "Confirmation password doesn't match", - ERROR_NON_OPTIONAL: "Field is not optional", - /* - * The following are error messages from our backend SDK. - * These are returned as full messages to preserver compatibilty, but they work just like the keys above. - * They are shown as is by default (setting the value to undefined will display the raw translation key) - */ - "This email already exists. Please sign in instead.": undefined, - "Field is not optional": undefined, - "Password must contain at least 8 characters, including a number": undefined, - "Password's length must be lesser than 100 characters": undefined, - "Password must contain at least one alphabet": undefined, - "Password must contain at least one number": undefined, - "Email is invalid": undefined, - "Reset password link was not created because of account take over risk. Please contact support. (ERR_CODE_001)": - undefined, - "Cannot sign up due to security reasons. Please try logging in, use a different login method or contact support. (ERR_CODE_007)": - undefined, - "Cannot sign in due to security reasons. Please try resetting your password, use a different login method or contact support. (ERR_CODE_008)": - undefined, - "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_009)": undefined, - "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_010)": undefined, - "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_011)": undefined, - "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_012)": undefined, - "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_013)": undefined, - "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_014)": undefined, - "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_015)": undefined, - "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_016)": undefined, - } - ), +var defaultTranslationsEmailPassword = { + en: utils.__assign(utils.__assign(utils.__assign({}, uiEntry.defaultTranslationsCommon.en), translations.defaultTranslationsEmailVerification.en), { EMAIL_PASSWORD_EMAIL_LABEL: "Email", EMAIL_PASSWORD_EMAIL_PLACEHOLDER: "Email address", EMAIL_PASSWORD_PASSWORD_LABEL: "Password", EMAIL_PASSWORD_PASSWORD_PLACEHOLDER: "Password", EMAIL_PASSWORD_SIGN_IN_FORGOT_PW_LINK: "Forgot password?", EMAIL_PASSWORD_SIGN_IN_SUBMIT_BTN: "SIGN IN", EMAIL_PASSWORD_SIGN_IN_WRONG_CREDENTIALS_ERROR: "Incorrect email and password combination", EMAIL_PASSWORD_SIGN_UP_SUBMIT_BTN: "SIGN UP", EMAIL_PASSWORD_EMAIL_ALREADY_EXISTS: "This email already exists. Please sign in instead", EMAIL_PASSWORD_RESET_HEADER_TITLE: "Reset your password", EMAIL_PASSWORD_RESET_HEADER_SUBTITLE: "We will send you an email to reset your password", EMAIL_PASSWORD_RESET_SEND_FALLBACK_EMAIL: "your account", EMAIL_PASSWORD_RESET_SEND_BEFORE_EMAIL: "A password reset email has been sent to ", EMAIL_PASSWORD_RESET_SEND_AFTER_EMAIL: ", if it exists in our system. ", EMAIL_PASSWORD_RESET_RESEND_LINK: "Resend or change email", EMAIL_PASSWORD_RESET_SEND_BTN: "Email me", EMAIL_PASSWORD_RESET_SIGN_IN_LINK: "Sign In", EMAIL_PASSWORD_RESET_SUBMIT_PW_SUCCESS_HEADER_TITLE: "Success!", EMAIL_PASSWORD_RESET_SUBMIT_PW_SUCCESS_DESC: "Your password has been updated successfully", EMAIL_PASSWORD_RESET_SUBMIT_PW_SUCCESS_SIGN_IN_BTN: "SIGN IN", EMAIL_PASSWORD_NEW_PASSWORD_LABEL: "New password", EMAIL_PASSWORD_NEW_PASSWORD_PLACEHOLDER: "New password", EMAIL_PASSWORD_CONFIRM_PASSWORD_LABEL: "Confirm password", EMAIL_PASSWORD_CONFIRM_PASSWORD_PLACEHOLDER: "Confirm your password", EMAIL_PASSWORD_RESET_SUBMIT_PW_HEADER_TITLE: "Change your password", EMAIL_PASSWORD_RESET_SUBMIT_PW_HEADER_SUBTITLE: "Enter a new password below to change your password", EMAIL_PASSWORD_RESET_SUBMIT_PW_CHANGE_PW_BTN: "CHANGE PASSWORD", EMAIL_PASSWORD_RESET_PASSWORD_INVALID_TOKEN_ERROR: "Invalid password reset token", ERROR_EMAIL_NON_STRING: "Email must be of type string", ERROR_EMAIL_INVALID: "Email is invalid", ERROR_PASSWORD_NON_STRING: "Password must be of type string", ERROR_PASSWORD_TOO_SHORT: "Password must contain at least 8 characters, including a number", ERROR_PASSWORD_TOO_LONG: "Password's length must be lesser than 100 characters", ERROR_PASSWORD_NO_ALPHA: "Password must contain at least one alphabet", ERROR_PASSWORD_NO_NUM: "Password must contain at least one number", ERROR_CONFIRM_PASSWORD_NO_MATCH: "Confirmation password doesn't match", ERROR_NON_OPTIONAL: "Field is not optional", + /* + * The following are error messages from our backend SDK. + * These are returned as full messages to preserver compatibilty, but they work just like the keys above. + * They are shown as is by default (setting the value to undefined will display the raw translation key) + */ + "This email already exists. Please sign in instead.": undefined, "Field is not optional": undefined, "Password must contain at least 8 characters, including a number": undefined, "Password's length must be lesser than 100 characters": undefined, "Password must contain at least one alphabet": undefined, "Password must contain at least one number": undefined, "Email is invalid": undefined, "Reset password link was not created because of account take over risk. Please contact support. (ERR_CODE_001)": undefined, "Cannot sign up due to security reasons. Please try logging in, use a different login method or contact support. (ERR_CODE_007)": undefined, "Cannot sign in due to security reasons. Please try resetting your password, use a different login method or contact support. (ERR_CODE_008)": undefined, "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_009)": undefined, "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_010)": undefined, "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_011)": undefined, "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_012)": undefined, "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_013)": undefined, "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_014)": undefined, "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_015)": undefined, "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_016)": undefined }), }; -var ResetPasswordUsingToken$1 = function (props) { - var token = genericComponentOverrideContext.getQueryParams("token"); - var userContext = uiEntry.useUserContext(); - if (props.userContext !== undefined) { - userContext = props.userContext; - } - var _a = React__namespace.useState(), - error = _a[0], - setError = _a[1]; - var enterEmailFormFeature = props.recipe.config.resetPasswordUsingTokenFeature.enterEmailForm; - var submitNewPasswordFormFeature = props.recipe.config.resetPasswordUsingTokenFeature.submitNewPasswordForm; - var submitNewPasswordForm = - token === undefined || token === null - ? undefined - : { - error: error, - onError: function (error) { - return setError(error); - }, - clearError: function () { - return setError(undefined); - }, - styleFromInit: submitNewPasswordFormFeature.style, - formFields: submitNewPasswordFormFeature.formFields, - recipeImplementation: props.recipe.webJSRecipe, - config: props.recipe.config, - onSignInClicked: function () { - void genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToAuth({ - show: "signin", - navigate: props.navigate, - redirectBack: false, - userContext: userContext, - }); - }, - token: token, - }; - var enterEmailForm = { - onBackButtonClicked: function () { - return genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToAuth({ - show: "signin", - navigate: props.navigate, - redirectBack: false, - userContext: userContext, - }); - }, - error: error, - onError: function (error) { - return setError(error); - }, - clearError: function () { - return setError(undefined); - }, - styleFromInit: enterEmailFormFeature.style, - formFields: enterEmailFormFeature.formFields, - recipeImplementation: props.recipe.webJSRecipe, - config: props.recipe.config, - }; - var childProps = { - config: props.recipe.config, - submitNewPasswordForm: submitNewPasswordForm, - enterEmailForm: enterEmailForm, - }; - var recipeComponentOverrides = props.useComponentOverrides(); - return jsxRuntime.jsx( - uiEntry.ComponentOverrideContext.Provider, - genericComponentOverrideContext.__assign( - { value: recipeComponentOverrides }, - { - children: jsxRuntime.jsx( - uiEntry.FeatureWrapper, - genericComponentOverrideContext.__assign( - { - useShadowDom: genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().useShadowDom, - defaultStore: defaultTranslationsEmailPassword, - }, - { - children: jsxRuntime.jsxs(React.Fragment, { - children: [ - props.children === undefined && - jsxRuntime.jsx( - ResetPasswordUsingTokenThemeWrapper, - genericComponentOverrideContext.__assign({}, childProps) - ), - props.children && - React__namespace.Children.map(props.children, function (child) { - if (React__namespace.isValidElement(child)) { - return React__namespace.cloneElement(child, childProps); - } - return child; - }), - ], - }), - } - ) - ), - } - ) - ); +var ResetPasswordUsingToken$1 = function (props) { + var token = utils.getQueryParams("token"); + var userContext = uiEntry.useUserContext(); + if (props.userContext !== undefined) { + userContext = props.userContext; + } + var _a = React__namespace.useState(), error = _a[0], setError = _a[1]; + var enterEmailFormFeature = props.recipe.config.resetPasswordUsingTokenFeature.enterEmailForm; + var submitNewPasswordFormFeature = props.recipe.config.resetPasswordUsingTokenFeature.submitNewPasswordForm; + var submitNewPasswordForm = token === undefined || token === null + ? undefined + : { + error: error, + onError: function (error) { return setError(error); }, + clearError: function () { return setError(undefined); }, + styleFromInit: submitNewPasswordFormFeature.style, + formFields: submitNewPasswordFormFeature.formFields, + recipeImplementation: props.recipe.webJSRecipe, + config: props.recipe.config, + onSignInClicked: function () { + void superTokens.SuperTokens.getInstanceOrThrow().redirectToAuth({ + show: "signin", + navigate: props.navigate, + redirectBack: false, + userContext: userContext, + }); + }, + token: token, + }; + var enterEmailForm = { + onBackButtonClicked: function () { + return superTokens.SuperTokens.getInstanceOrThrow().redirectToAuth({ + show: "signin", + navigate: props.navigate, + redirectBack: false, + userContext: userContext, + }); + }, + error: error, + onError: function (error) { return setError(error); }, + clearError: function () { return setError(undefined); }, + styleFromInit: enterEmailFormFeature.style, + formFields: enterEmailFormFeature.formFields, + recipeImplementation: props.recipe.webJSRecipe, + config: props.recipe.config, + }; + var childProps = { + config: props.recipe.config, + submitNewPasswordForm: submitNewPasswordForm, + enterEmailForm: enterEmailForm, + }; + var recipeComponentOverrides = props.useComponentOverrides(); + return (jsxRuntime.jsx(uiEntry.ComponentOverrideContext.Provider, utils.__assign({ value: recipeComponentOverrides }, { children: jsxRuntime.jsx(uiEntry.FeatureWrapper, utils.__assign({ useShadowDom: superTokens.SuperTokens.getInstanceOrThrow().useShadowDom, defaultStore: defaultTranslationsEmailPassword }, { children: jsxRuntime.jsxs(React.Fragment, { children: [props.children === undefined && jsxRuntime.jsx(ResetPasswordUsingTokenThemeWrapper, utils.__assign({}, childProps)), props.children && + React__namespace.Children.map(props.children, function (child) { + if (React__namespace.isValidElement(child)) { + return React__namespace.cloneElement(child, childProps); + } + return child; + })] }) })) }))); }; -var SignInForm = uiEntry.withOverride("EmailPasswordSignInForm", function EmailPasswordSignInForm(props) { - var _this = this; - var userContext = uiEntry.useUserContext(); - return jsxRuntime.jsx(formBase.FormBase, { - formFields: props.formFields, - clearError: props.clearError, - onError: props.onError, - onFetchError: props.onFetchError, - buttonLabel: "EMAIL_PASSWORD_SIGN_IN_SUBMIT_BTN", - onSuccess: props.onSuccess, - callAPI: function (formFields) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var validationErrors, response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - genericComponentOverrideContext.validateForm( - formFields, - props.config.signInAndUpFeature.signInForm.formFields - ), - ]; - case 1: - validationErrors = _a.sent(); - if (validationErrors.length > 0) { - return [ - 2 /*return*/, - { - status: "FIELD_ERROR", - formFields: validationErrors, - }, - ]; - } - return [ - 4 /*yield*/, - props.recipeImplementation.signIn({ - formFields: formFields, - shouldTryLinkingWithSessionUser: false, - userContext: userContext, - }), - ]; - case 2: - response = _a.sent(); - if (response.status === "WRONG_CREDENTIALS_ERROR") { - throw new STGeneralError__default.default( - "EMAIL_PASSWORD_SIGN_IN_WRONG_CREDENTIALS_ERROR" - ); - } else if (response.status === "SIGN_IN_NOT_ALLOWED") { - throw new STGeneralError__default.default(response.reason); - } else { - return [2 /*return*/, response]; - } - } - }); - }); - }, - validateOnBlur: false, - showLabels: true, - footer: props.footer, - }); -}); -function SignInTheme(props) { - var rootStyle = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().rootStyle; - var activeStyle = props.config.signInAndUpFeature.signInForm.style; - return jsxRuntime.jsx( - uiEntry.UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - translations.ThemeBase, - genericComponentOverrideContext.__assign( - { userStyles: [rootStyle, props.config.recipeRootStyle, activeStyle] }, - { children: jsxRuntime.jsx(SignInForm, genericComponentOverrideContext.__assign({}, props)) } - ) - ), - } - ) - ); +var SignInForm = uiEntry.withOverride("EmailPasswordSignInForm", function EmailPasswordSignInForm(props) { + var _this = this; + var userContext = uiEntry.useUserContext(); + return (jsxRuntime.jsx(formBase.FormBase, { formFields: props.formFields, clearError: props.clearError, onError: props.onError, onFetchError: props.onFetchError, buttonLabel: "EMAIL_PASSWORD_SIGN_IN_SUBMIT_BTN", onSuccess: props.onSuccess, callAPI: function (formFields) { return utils.__awaiter(_this, void 0, void 0, function () { + var validationErrors, response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, utils.validateForm(formFields, props.config.signInAndUpFeature.signInForm.formFields)]; + case 1: + validationErrors = _a.sent(); + if (validationErrors.length > 0) { + return [2 /*return*/, { + status: "FIELD_ERROR", + formFields: validationErrors, + }]; + } + return [4 /*yield*/, props.recipeImplementation.signIn({ + formFields: formFields, + shouldTryLinkingWithSessionUser: false, + userContext: userContext, + })]; + case 2: + response = _a.sent(); + if (response.status === "WRONG_CREDENTIALS_ERROR") { + throw new STGeneralError__default.default("EMAIL_PASSWORD_SIGN_IN_WRONG_CREDENTIALS_ERROR"); + } + else if (response.status === "SIGN_IN_NOT_ALLOWED") { + throw new STGeneralError__default.default(response.reason); + } + else { + return [2 /*return*/, response]; + } + } + }); + }); }, validateOnBlur: false, showLabels: true, footer: props.footer })); +}); +function SignInTheme(props) { + var rootStyle = superTokens.SuperTokens.getInstanceOrThrow().rootStyle; + var activeStyle = props.config.signInAndUpFeature.signInForm.style; + return (jsxRuntime.jsx(uiEntry.UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(translations.ThemeBase, utils.__assign({ userStyles: [rootStyle, props.config.recipeRootStyle, activeStyle] }, { children: jsxRuntime.jsx(SignInForm, utils.__assign({}, props)) })) }))); } -function useChildProps$1(recipe$2, onAuthSuccess, error, onError, clearError, userContext, navigate) { - var _this = this; - var session$1 = uiEntry.useSessionContext(); - var recipeImplementation = React.useMemo( - function () { - return getModifiedRecipeImplementation$1(recipe$2.webJSRecipe); - }, - [recipe$2] - ); - var rethrowInRender = genericComponentOverrideContext.useRethrowInRender(); - var t = translationContext.useTranslation(); - var onSignInSuccess = React.useCallback( - function () { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var payloadAfterCall; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 2, , 3]); - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ - userContext: userContext, - }), - ]; - case 1: - payloadAfterCall = _b.sent(); - return [3 /*break*/, 3]; - case 2: - _b.sent(); - payloadAfterCall = undefined; - return [3 /*break*/, 3]; - case 3: - return [ - 2 /*return*/, - onAuthSuccess({ - createdNewUser: false, - isNewRecipeUser: false, - newSessionCreated: - session$1.loading || - !session$1.doesSessionExist || - (payloadAfterCall !== undefined && - session$1.accessTokenPayload.sessionHandle !== - payloadAfterCall.sessionHandle), - recipeId: recipe.EmailPassword.RECIPE_ID, - }).catch(rethrowInRender), - ]; - } - }); - }); - }, - [recipe$2, userContext, navigate] - ); - return React.useMemo( - function () { - var onForgotPasswordClick = function () { - return recipe$2.redirect( - { - action: "RESET_PASSWORD", - tenantIdFromQueryParams: genericComponentOverrideContext.getTenantIdFromQueryParams(), - }, - navigate, - undefined, - userContext - ); - }; - var signInAndUpFeature = recipe$2.config.signInAndUpFeature; - var signInFeature = signInAndUpFeature.signInForm; - var formFields = signInFeature.formFields.map(function (f) { - return f.id !== "password" - ? f - : genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, f), { - labelComponent: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "formLabelWithLinkWrapper" }, - { - children: [ - jsxRuntime.jsx(formBase.Label, { - value: f.label, - "data-supertokens": "passwordInputLabel", - }), - jsxRuntime.jsx( - "a", - genericComponentOverrideContext.__assign( - { - onClick: onForgotPasswordClick, - "data-supertokens": - "link linkButton formLabelLinkBtn forgotPasswordLink", - }, - { children: t("EMAIL_PASSWORD_SIGN_IN_FORGOT_PW_LINK") } - ) - ), - ], - } - ) - ), - }); - }); - return { - recipeImplementation: recipeImplementation, - config: recipe$2.config, - styleFromInit: signInFeature.style, - formFields: formFields, - error: error, - clearError: clearError, - onError: onError, - onFetchError: function (err) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var invalidClaims, evInstance; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if ( - !( - err.status === - types.Session.getInstanceOrThrow().config.invalidClaimStatusCode - ) - ) - return [3 /*break*/, 5]; - return [ - 4 /*yield*/, - session.getInvalidClaimsFromResponse({ - response: err, - userContext: userContext, - }), - ]; - case 1: - invalidClaims = _b.sent(); - if ( - !invalidClaims.some(function (i) { - return i.id === emailverification.EmailVerificationClaim.id; - }) - ) - return [3 /*break*/, 5]; - _b.label = 2; - case 2: - _b.trys.push([2, 4, , 5]); - evInstance = recipe$1.EmailVerification.getInstanceOrThrow(); - return [ - 4 /*yield*/, - evInstance.redirect( - { - action: "VERIFY_EMAIL", - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - }, - navigate, - undefined, - userContext - ), - ]; - case 3: - _b.sent(); - return [2 /*return*/]; - case 4: - _b.sent(); - return [3 /*break*/, 5]; - case 5: - onError("SOMETHING_WENT_WRONG_ERROR"); - return [2 /*return*/]; - } - }); - }); - }, - onSuccess: onSignInSuccess, - onForgotPasswordClick: onForgotPasswordClick, - userContext: userContext, - }; - }, - [recipe$2, error, userContext] - ); -} -var SignInFeature = function (props) { - var childProps = useChildProps$1( - props.recipe, - props.onAuthSuccess, - props.error, - props.onError, - props.clearError, - props.userContext, - props.navigate - ); - var recipeComponentOverrides = props.useComponentOverrides(); - return jsxRuntime.jsx( - authCompWrapper.AuthComponentWrapper, - genericComponentOverrideContext.__assign( - { recipeComponentOverrides: recipeComponentOverrides }, - { - children: jsxRuntime.jsxs(React.Fragment, { - children: [ - props.children === undefined && - jsxRuntime.jsx(SignInTheme, genericComponentOverrideContext.__assign({}, childProps)), - props.children && - React__namespace.Children.map(props.children, function (child) { - if (React__namespace.isValidElement(child)) { - return React__namespace.cloneElement( - child, - genericComponentOverrideContext.__assign({}, childProps) - ); - } - return child; - }), - ], - }), - } - ) - ); -}; -var getModifiedRecipeImplementation$1 = function (origImpl) { - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, origImpl), { - signIn: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - origImpl.signIn( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, input), - { shouldTryLinkingWithSessionUser: false } - ) - ), - ]; - case 1: - response = _a.sent(); - return [2 /*return*/, response]; - } - }); - }); - }, - signUp: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - origImpl.signUp( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, input), - { shouldTryLinkingWithSessionUser: false } - ) - ), - ]; - case 1: - response = _a.sent(); - return [2 /*return*/, response]; - } - }); - }); - }, - }); +function useChildProps$1(recipe$2, onAuthSuccess, error, onError, clearError, userContext, navigate) { + var _this = this; + var session$1 = uiEntry.useSessionContext(); + var recipeImplementation = React.useMemo(function () { return getModifiedRecipeImplementation$1(recipe$2.webJSRecipe); }, [recipe$2]); + var rethrowInRender = utils.useRethrowInRender(); + var t = translationContext.useTranslation(); + var onSignInSuccess = React.useCallback(function () { return utils.__awaiter(_this, void 0, void 0, function () { + var payloadAfterCall; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _b.trys.push([0, 2, , 3]); + return [4 /*yield*/, types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ + userContext: userContext, + })]; + case 1: + payloadAfterCall = _b.sent(); + return [3 /*break*/, 3]; + case 2: + _b.sent(); + payloadAfterCall = undefined; + return [3 /*break*/, 3]; + case 3: return [2 /*return*/, onAuthSuccess({ + createdNewUser: false, + isNewRecipeUser: false, + newSessionCreated: session$1.loading || + !session$1.doesSessionExist || + (payloadAfterCall !== undefined && + session$1.accessTokenPayload.sessionHandle !== payloadAfterCall.sessionHandle), + recipeId: recipe.EmailPassword.RECIPE_ID, + }).catch(rethrowInRender)]; + } + }); + }); }, [recipe$2, userContext, navigate]); + return React.useMemo(function () { + var onForgotPasswordClick = function () { + return recipe$2.redirect({ action: "RESET_PASSWORD", tenantIdFromQueryParams: utils.getTenantIdFromQueryParams() }, navigate, undefined, userContext); + }; + var signInAndUpFeature = recipe$2.config.signInAndUpFeature; + var signInFeature = signInAndUpFeature.signInForm; + var formFields = signInFeature.formFields.map(function (f) { + return f.id !== "password" + ? f + : utils.__assign(utils.__assign({}, f), { labelComponent: (jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "formLabelWithLinkWrapper" }, { children: [jsxRuntime.jsx(formBase.Label, { value: f.label, "data-supertokens": "passwordInputLabel" }), jsxRuntime.jsx("a", utils.__assign({ onClick: onForgotPasswordClick, "data-supertokens": "link linkButton formLabelLinkBtn forgotPasswordLink" }, { children: t("EMAIL_PASSWORD_SIGN_IN_FORGOT_PW_LINK") }))] }))) }); + }); + return { + recipeImplementation: recipeImplementation, + config: recipe$2.config, + styleFromInit: signInFeature.style, + formFields: formFields, + error: error, + clearError: clearError, + onError: onError, + onFetchError: function (err) { return utils.__awaiter(_this, void 0, void 0, function () { + var invalidClaims, evInstance; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!(err.status === types.Session.getInstanceOrThrow().config.invalidClaimStatusCode)) return [3 /*break*/, 5]; + return [4 /*yield*/, session.getInvalidClaimsFromResponse({ response: err, userContext: userContext })]; + case 1: + invalidClaims = _b.sent(); + if (!invalidClaims.some(function (i) { return i.id === emailverification.EmailVerificationClaim.id; })) return [3 /*break*/, 5]; + _b.label = 2; + case 2: + _b.trys.push([2, 4, , 5]); + evInstance = recipe$1.EmailVerification.getInstanceOrThrow(); + return [4 /*yield*/, evInstance.redirect({ + action: "VERIFY_EMAIL", + tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), + }, navigate, undefined, userContext)]; + case 3: + _b.sent(); + return [2 /*return*/]; + case 4: + _b.sent(); + return [3 /*break*/, 5]; + case 5: + onError("SOMETHING_WENT_WRONG_ERROR"); + return [2 /*return*/]; + } + }); + }); }, + onSuccess: onSignInSuccess, + onForgotPasswordClick: onForgotPasswordClick, + userContext: userContext, + }; + }, [recipe$2, error, userContext]); +} +var SignInFeature = function (props) { + var childProps = useChildProps$1(props.recipe, props.onAuthSuccess, props.error, props.onError, props.clearError, props.userContext, props.navigate); + var recipeComponentOverrides = props.useComponentOverrides(); + return (jsxRuntime.jsx(authCompWrapper.AuthComponentWrapper, utils.__assign({ recipeComponentOverrides: recipeComponentOverrides }, { children: jsxRuntime.jsxs(React.Fragment, { children: [props.children === undefined && jsxRuntime.jsx(SignInTheme, utils.__assign({}, childProps)), props.children && + React__namespace.Children.map(props.children, function (child) { + if (React__namespace.isValidElement(child)) { + return React__namespace.cloneElement(child, utils.__assign({}, childProps)); + } + return child; + })] }) }))); +}; +var getModifiedRecipeImplementation$1 = function (origImpl) { + return utils.__assign(utils.__assign({}, origImpl), { signIn: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, origImpl.signIn(utils.__assign(utils.__assign({}, input), { shouldTryLinkingWithSessionUser: false }))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response]; + } + }); + }); + }, signUp: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, origImpl.signUp(utils.__assign(utils.__assign({}, input), { shouldTryLinkingWithSessionUser: false }))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response]; + } + }); + }); + } }); }; -var SignUpForm = uiEntry.withOverride("EmailPasswordSignUpForm", function EmailPasswordSignUpForm(props) { - var _this = this; - var userContext = uiEntry.useUserContext(); - return jsxRuntime.jsx(formBase.FormBase, { - formFields: props.formFields, - clearError: props.clearError, - onError: props.onError, - onFetchError: props.onFetchError, - buttonLabel: "EMAIL_PASSWORD_SIGN_UP_SUBMIT_BTN", - onSuccess: props.onSuccess, - callAPI: function (formFields) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var validationErrors, res; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - genericComponentOverrideContext.validateForm( - formFields, - props.config.signInAndUpFeature.signUpForm.formFields - ), - ]; - case 1: - validationErrors = _a.sent(); - if (validationErrors.length > 0) { - return [ - 2 /*return*/, - { - status: "FIELD_ERROR", - formFields: validationErrors, - }, - ]; - } - return [ - 4 /*yield*/, - props.recipeImplementation.signUp({ - formFields: formFields, - shouldTryLinkingWithSessionUser: false, - userContext: userContext, - }), - ]; - case 2: - res = _a.sent(); - if (res.status === "SIGN_UP_NOT_ALLOWED") { - throw new STGeneralError__default$1.default(res.reason); - } - return [2 /*return*/, res]; - } - }); - }); - }, - validateOnBlur: true, - showLabels: true, - footer: props.footer, - }); -}); -function SignUpTheme(props) { - var rootStyle = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().rootStyle; - var activeStyle = props.config.signInAndUpFeature.signUpForm.style; - return jsxRuntime.jsx( - uiEntry.UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - translations.ThemeBase, - genericComponentOverrideContext.__assign( - { userStyles: [rootStyle, props.config.recipeRootStyle, activeStyle] }, - { children: jsxRuntime.jsx(SignUpForm, genericComponentOverrideContext.__assign({}, props)) } - ) - ), - } - ) - ); +var SignUpForm = uiEntry.withOverride("EmailPasswordSignUpForm", function EmailPasswordSignUpForm(props) { + var _this = this; + var userContext = uiEntry.useUserContext(); + return (jsxRuntime.jsx(formBase.FormBase, { formFields: props.formFields, clearError: props.clearError, onError: props.onError, onFetchError: props.onFetchError, buttonLabel: "EMAIL_PASSWORD_SIGN_UP_SUBMIT_BTN", onSuccess: props.onSuccess, callAPI: function (formFields) { return utils.__awaiter(_this, void 0, void 0, function () { + var validationErrors, res; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, utils.validateForm(formFields, props.config.signInAndUpFeature.signUpForm.formFields)]; + case 1: + validationErrors = _a.sent(); + if (validationErrors.length > 0) { + return [2 /*return*/, { + status: "FIELD_ERROR", + formFields: validationErrors, + }]; + } + return [4 /*yield*/, props.recipeImplementation.signUp({ + formFields: formFields, + shouldTryLinkingWithSessionUser: false, + userContext: userContext, + })]; + case 2: + res = _a.sent(); + if (res.status === "SIGN_UP_NOT_ALLOWED") { + throw new STGeneralError__default$1.default(res.reason); + } + return [2 /*return*/, res]; + } + }); + }); }, validateOnBlur: true, showLabels: true, footer: props.footer })); +}); +function SignUpTheme(props) { + var rootStyle = superTokens.SuperTokens.getInstanceOrThrow().rootStyle; + var activeStyle = props.config.signInAndUpFeature.signUpForm.style; + return (jsxRuntime.jsx(uiEntry.UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(translations.ThemeBase, utils.__assign({ userStyles: [rootStyle, props.config.recipeRootStyle, activeStyle] }, { children: jsxRuntime.jsx(SignUpForm, utils.__assign({}, props)) })) }))); } -function useChildProps(recipe, onAuthSuccess, error, onError, clearError, userContext, navigate) { - var _this = this; - var session$1 = uiEntry.useSessionContext(); - var recipeImplementation = React.useMemo( - function () { - return recipe && getModifiedRecipeImplementation(recipe.webJSRecipe); - }, - [recipe] - ); - var rethrowInRender = genericComponentOverrideContext.useRethrowInRender(); - var onSignUpSuccess = React.useCallback( - function (result) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var payloadAfterCall; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 2, , 3]); - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ - userContext: userContext, - }), - ]; - case 1: - payloadAfterCall = _b.sent(); - return [3 /*break*/, 3]; - case 2: - _b.sent(); - payloadAfterCall = undefined; - return [3 /*break*/, 3]; - case 3: - return [ - 2 /*return*/, - onAuthSuccess({ - createdNewUser: result.user.loginMethods.length === 1, - isNewRecipeUser: true, - newSessionCreated: - session$1.loading || - !session$1.doesSessionExist || - (payloadAfterCall !== undefined && - session$1.accessTokenPayload.sessionHandle !== - payloadAfterCall.sessionHandle), - recipeId: recipe.recipeID, - }).catch(rethrowInRender), - ]; - } - }); - }); - }, - [recipe, userContext, navigate] - ); - return React.useMemo( - function () { - var signInAndUpFeature = recipe.config.signInAndUpFeature; - var signUpFeature = signInAndUpFeature.signUpForm; - return { - recipeImplementation: recipeImplementation, - config: recipe.config, - styleFromInit: signUpFeature.style, - formFields: getThemeSignUpFeatureFormFields(signUpFeature.formFields, recipe, userContext), - onFetchError: function (err) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var invalidClaims, evInstance; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if ( - !( - err.status === - types.Session.getInstanceOrThrow().config.invalidClaimStatusCode - ) - ) - return [3 /*break*/, 5]; - return [ - 4 /*yield*/, - session.getInvalidClaimsFromResponse({ - response: err, - userContext: userContext, - }), - ]; - case 1: - invalidClaims = _b.sent(); - if ( - !invalidClaims.some(function (i) { - return i.id === emailverification.EmailVerificationClaim.id; - }) - ) - return [3 /*break*/, 5]; - _b.label = 2; - case 2: - _b.trys.push([2, 4, , 5]); - evInstance = recipe$1.EmailVerification.getInstanceOrThrow(); - return [ - 4 /*yield*/, - evInstance.redirect( - { - action: "VERIFY_EMAIL", - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - }, - navigate, - undefined, - userContext - ), - ]; - case 3: - _b.sent(); - return [2 /*return*/]; - case 4: - _b.sent(); - return [3 /*break*/, 5]; - case 5: - onError("SOMETHING_WENT_WRONG_ERROR"); - return [2 /*return*/]; - } - }); - }); - }, - onSuccess: onSignUpSuccess, - userContext: userContext, - error: error, - onError: onError, - clearError: clearError, - }; - }, - [recipe, error, userContext] - ); -} -var SignUpFeature = function (props) { - var userContext = uiEntry.useUserContext(); - if (props.userContext !== undefined) { - userContext = props.userContext; - } - var childProps = useChildProps( - props.recipe, - props.onAuthSuccess, - props.error, - props.onError, - props.clearError, - userContext, - props.navigate - ); - var recipeComponentOverrides = props.useComponentOverrides(); - return jsxRuntime.jsx( - authCompWrapper.AuthComponentWrapper, - genericComponentOverrideContext.__assign( - { recipeComponentOverrides: recipeComponentOverrides }, - { - children: jsxRuntime.jsxs(React.Fragment, { - children: [ - props.children === undefined && - jsxRuntime.jsx(SignUpTheme, genericComponentOverrideContext.__assign({}, childProps)), - props.children && - React__namespace.Children.map(props.children, function (child) { - if (React__namespace.isValidElement(child)) { - return React__namespace.cloneElement( - child, - genericComponentOverrideContext.__assign({}, childProps) - ); - } - return child; - }), - ], - }), - } - ) - ); -}; -var getModifiedRecipeImplementation = function (origImpl) { - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, origImpl), { - signIn: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - origImpl.signIn( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, input), - { shouldTryLinkingWithSessionUser: false } - ) - ), - ]; - case 1: - response = _a.sent(); - return [2 /*return*/, response]; - } - }); - }); - }, - signUp: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - origImpl.signUp( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, input), - { shouldTryLinkingWithSessionUser: false } - ) - ), - ]; - case 1: - response = _a.sent(); - return [2 /*return*/, response]; - } - }); - }); - }, - }); -}; -function getThemeSignUpFeatureFormFields(formFields, recipe, userContext) { - var _this = this; - var emailPasswordOnly = formFields.length === 2; - return formFields.map(function (field) { - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, field), { - showIsRequired: (function () { - // If email and password only, do not show required indicator (*). - if (emailPasswordOnly) { - return false; - } - // Otherwise, show for all non optional fields (including email and password). - return field.optional === false; - })(), - validate: (function () { - // If field is not email, return field validate unchanged. - if (field.id !== "email") { - return field.validate; - } - // Otherwise, if email, use syntax validate method and check if email exists. - return function (value) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var error, emailExists, err_1; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, field.validate(value)]; - case 1: - error = _a.sent(); - if (error !== undefined) { - return [2 /*return*/, error]; - } - if (typeof value !== "string") { - return [2 /*return*/, "GENERAL_ERROR_EMAIL_NON_STRING"]; - } - _a.label = 2; - case 2: - _a.trys.push([2, 4, , 5]); - return [ - 4 /*yield*/, - recipe.webJSRecipe.doesEmailExist({ - email: value, - userContext: userContext, - }), - ]; - case 3: - emailExists = _a.sent().doesExist; - if (emailExists) { - return [2 /*return*/, "EMAIL_PASSWORD_EMAIL_ALREADY_EXISTS"]; - } - return [3 /*break*/, 5]; - case 4: - err_1 = _a.sent(); - if (STGeneralError__default.default.isThisError(err_1)) { - return [2 /*return*/, err_1.message]; - } - return [3 /*break*/, 5]; - case 5: - return [2 /*return*/, undefined]; - } - }); - }); - }; - })(), - }); - }); +function useChildProps(recipe, onAuthSuccess, error, onError, clearError, userContext, navigate) { + var _this = this; + var session$1 = uiEntry.useSessionContext(); + var recipeImplementation = React.useMemo(function () { return recipe && getModifiedRecipeImplementation(recipe.webJSRecipe); }, [recipe]); + var rethrowInRender = utils.useRethrowInRender(); + var onSignUpSuccess = React.useCallback(function (result) { return utils.__awaiter(_this, void 0, void 0, function () { + var payloadAfterCall; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _b.trys.push([0, 2, , 3]); + return [4 /*yield*/, types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ + userContext: userContext, + })]; + case 1: + payloadAfterCall = _b.sent(); + return [3 /*break*/, 3]; + case 2: + _b.sent(); + payloadAfterCall = undefined; + return [3 /*break*/, 3]; + case 3: return [2 /*return*/, onAuthSuccess({ + createdNewUser: result.user.loginMethods.length === 1, + isNewRecipeUser: true, + newSessionCreated: session$1.loading || + !session$1.doesSessionExist || + (payloadAfterCall !== undefined && + session$1.accessTokenPayload.sessionHandle !== payloadAfterCall.sessionHandle), + recipeId: recipe.recipeID, + }).catch(rethrowInRender)]; + } + }); + }); }, [recipe, userContext, navigate]); + return React.useMemo(function () { + var signInAndUpFeature = recipe.config.signInAndUpFeature; + var signUpFeature = signInAndUpFeature.signUpForm; + return { + recipeImplementation: recipeImplementation, + config: recipe.config, + styleFromInit: signUpFeature.style, + formFields: getThemeSignUpFeatureFormFields(signUpFeature.formFields, recipe, userContext), + onFetchError: function (err) { return utils.__awaiter(_this, void 0, void 0, function () { + var invalidClaims, evInstance; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!(err.status === types.Session.getInstanceOrThrow().config.invalidClaimStatusCode)) return [3 /*break*/, 5]; + return [4 /*yield*/, session.getInvalidClaimsFromResponse({ response: err, userContext: userContext })]; + case 1: + invalidClaims = _b.sent(); + if (!invalidClaims.some(function (i) { return i.id === emailverification.EmailVerificationClaim.id; })) return [3 /*break*/, 5]; + _b.label = 2; + case 2: + _b.trys.push([2, 4, , 5]); + evInstance = recipe$1.EmailVerification.getInstanceOrThrow(); + return [4 /*yield*/, evInstance.redirect({ + action: "VERIFY_EMAIL", + tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), + }, navigate, undefined, userContext)]; + case 3: + _b.sent(); + return [2 /*return*/]; + case 4: + _b.sent(); + return [3 /*break*/, 5]; + case 5: + onError("SOMETHING_WENT_WRONG_ERROR"); + return [2 /*return*/]; + } + }); + }); }, + onSuccess: onSignUpSuccess, + userContext: userContext, + error: error, + onError: onError, + clearError: clearError, + }; + }, [recipe, error, userContext]); +} +var SignUpFeature = function (props) { + var userContext = uiEntry.useUserContext(); + if (props.userContext !== undefined) { + userContext = props.userContext; + } + var childProps = useChildProps(props.recipe, props.onAuthSuccess, props.error, props.onError, props.clearError, userContext, props.navigate); + var recipeComponentOverrides = props.useComponentOverrides(); + return (jsxRuntime.jsx(authCompWrapper.AuthComponentWrapper, utils.__assign({ recipeComponentOverrides: recipeComponentOverrides }, { children: jsxRuntime.jsxs(React.Fragment, { children: [props.children === undefined && jsxRuntime.jsx(SignUpTheme, utils.__assign({}, childProps)), props.children && + React__namespace.Children.map(props.children, function (child) { + if (React__namespace.isValidElement(child)) { + return React__namespace.cloneElement(child, utils.__assign({}, childProps)); + } + return child; + })] }) }))); +}; +var getModifiedRecipeImplementation = function (origImpl) { + return utils.__assign(utils.__assign({}, origImpl), { signIn: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, origImpl.signIn(utils.__assign(utils.__assign({}, input), { shouldTryLinkingWithSessionUser: false }))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response]; + } + }); + }); + }, signUp: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, origImpl.signUp(utils.__assign(utils.__assign({}, input), { shouldTryLinkingWithSessionUser: false }))]; + case 1: + response = _a.sent(); + return [2 /*return*/, response]; + } + }); + }); + } }); +}; +function getThemeSignUpFeatureFormFields(formFields, recipe, userContext) { + var _this = this; + var emailPasswordOnly = formFields.length === 2; + return formFields.map(function (field) { return (utils.__assign(utils.__assign({}, field), { showIsRequired: (function () { + // If email and password only, do not show required indicator (*). + if (emailPasswordOnly) { + return false; + } + // Otherwise, show for all non optional fields (including email and password). + return field.optional === false; + })(), validate: (function () { + // If field is not email, return field validate unchanged. + if (field.id !== "email") { + return field.validate; + } + // Otherwise, if email, use syntax validate method and check if email exists. + return function (value) { return utils.__awaiter(_this, void 0, void 0, function () { + var error, emailExists, err_1; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, field.validate(value)]; + case 1: + error = _a.sent(); + if (error !== undefined) { + return [2 /*return*/, error]; + } + if (typeof value !== "string") { + return [2 /*return*/, "GENERAL_ERROR_EMAIL_NON_STRING"]; + } + _a.label = 2; + case 2: + _a.trys.push([2, 4, , 5]); + return [4 /*yield*/, recipe.webJSRecipe.doesEmailExist({ + email: value, + userContext: userContext, + })]; + case 3: + emailExists = (_a.sent()).doesExist; + if (emailExists) { + return [2 /*return*/, "EMAIL_PASSWORD_EMAIL_ALREADY_EXISTS"]; + } + return [3 /*break*/, 5]; + case 4: + err_1 = _a.sent(); + if (STGeneralError__default.default.isThisError(err_1)) { + return [2 /*return*/, err_1.message]; + } + return [3 /*break*/, 5]; + case 5: return [2 /*return*/, undefined]; + } + }); + }); }; + })() })); }); } -var EmailPasswordPreBuiltUI = /** @class */ (function (_super) { - genericComponentOverrideContext.__extends(EmailPasswordPreBuiltUI, _super); - function EmailPasswordPreBuiltUI(recipeInstance) { - var _this = _super.call(this) || this; - _this.recipeInstance = recipeInstance; - _this.languageTranslations = defaultTranslationsEmailPassword; - // Instance methods - _this.getFeatures = function (useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = componentOverrideContext.useContext; - } - var features = {}; - if (_this.recipeInstance.config.resetPasswordUsingTokenFeature.disableDefaultUI !== true) { - var normalisedFullPath = _this.recipeInstance.config.appInfo.websiteBasePath.appendPath( - new NormalisedURLPath__default.default(constants.DEFAULT_RESET_PASSWORD_PATH) - ); - features[normalisedFullPath.getAsStringDangerous()] = { - matches: genericComponentOverrideContext.matchRecipeIdUsingQueryParams( - _this.recipeInstance.config.recipeId - ), - component: function (props) { - return _this.getFeatureComponent("resetpassword", props, useComponentOverrides); - }, - recipeID: recipe.EmailPassword.RECIPE_ID, - }; - } - return features; - }; - _this.getFeatureComponent = function (componentName, props, useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = componentOverrideContext.useContext; - } - if (componentName === "resetpassword") { - return jsxRuntime.jsx( - uiEntry.UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - ResetPasswordUsingToken$1, - genericComponentOverrideContext.__assign({ recipe: _this.recipeInstance }, props, { - useComponentOverrides: useComponentOverrides, - }) - ), - } - ) - ); - } else { - throw new Error("Should never come here."); - } - }; - _this.requiresSignUpPage = true; - return _this; - } - // Static methods - EmailPasswordPreBuiltUI.getInstanceOrInitAndGetInstance = function () { - if (EmailPasswordPreBuiltUI.instance === undefined) { - var recipeInstance = recipe.EmailPassword.getInstanceOrThrow(); - EmailPasswordPreBuiltUI.instance = new EmailPasswordPreBuiltUI(recipeInstance); - } - return EmailPasswordPreBuiltUI.instance; - }; - EmailPasswordPreBuiltUI.getFeatures = function (useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = componentOverrideContext.useContext; - } - return EmailPasswordPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatures(useComponentOverrides); - }; - EmailPasswordPreBuiltUI.getFeatureComponent = function (componentName, props, useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = componentOverrideContext.useContext; - } - return EmailPasswordPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent( - componentName, - props, - useComponentOverrides - ); - }; - EmailPasswordPreBuiltUI.prototype.getAuthComponents = function () { - var _this = this; - return [ - { - factorIds: [types.FactorIds.EMAILPASSWORD], - displayOrder: 2, - type: "SIGN_UP", - component: function (props) { - return jsxRuntime.jsx( - SignUpFeature, - genericComponentOverrideContext.__assign( - { - recipe: _this.recipeInstance, - useComponentOverrides: componentOverrideContext.useContext, - }, - props - ), - "emailpassword-sign-up" - ); - }, - }, - { - factorIds: [types.FactorIds.EMAILPASSWORD], - displayOrder: 2, - type: "SIGN_IN", - component: function (props) { - return jsxRuntime.jsx( - SignInFeature, - genericComponentOverrideContext.__assign( - { - recipe: _this.recipeInstance, - useComponentOverrides: componentOverrideContext.useContext, - }, - props - ), - "emailpassword-sign-in" - ); - }, - }, - ]; - }; - // For tests - EmailPasswordPreBuiltUI.reset = function () { - if (!genericComponentOverrideContext.isTest()) { - return; - } - EmailPasswordPreBuiltUI.instance = undefined; - return; - }; - EmailPasswordPreBuiltUI.ResetPasswordUsingToken = function (prop) { - return EmailPasswordPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent("resetpassword", prop); - }; - EmailPasswordPreBuiltUI.ResetPasswordUsingTokenTheme = ResetPasswordUsingTokenThemeWrapper; - return EmailPasswordPreBuiltUI; -})(uiEntry.RecipeRouter); +var EmailPasswordPreBuiltUI = /** @class */ (function (_super) { + utils.__extends(EmailPasswordPreBuiltUI, _super); + function EmailPasswordPreBuiltUI(recipeInstance) { + var _this = _super.call(this) || this; + _this.recipeInstance = recipeInstance; + _this.languageTranslations = defaultTranslationsEmailPassword; + // Instance methods + _this.getFeatures = function (useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = componentOverrideContext.useContext; } + var features = {}; + if (_this.recipeInstance.config.resetPasswordUsingTokenFeature.disableDefaultUI !== true) { + var normalisedFullPath = _this.recipeInstance.config.appInfo.websiteBasePath.appendPath(new NormalisedURLPath__default.default(constants.DEFAULT_RESET_PASSWORD_PATH)); + features[normalisedFullPath.getAsStringDangerous()] = { + matches: utils.matchRecipeIdUsingQueryParams(_this.recipeInstance.config.recipeId), + component: function (props) { return _this.getFeatureComponent("resetpassword", props, useComponentOverrides); }, + recipeID: recipe.EmailPassword.RECIPE_ID, + }; + } + return features; + }; + _this.getFeatureComponent = function (componentName, props, useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = componentOverrideContext.useContext; } + if (componentName === "resetpassword") { + return (jsxRuntime.jsx(uiEntry.UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(ResetPasswordUsingToken$1, utils.__assign({ recipe: _this.recipeInstance }, props, { useComponentOverrides: useComponentOverrides })) }))); + } + else { + throw new Error("Should never come here."); + } + }; + _this.requiresSignUpPage = true; + return _this; + } + // Static methods + EmailPasswordPreBuiltUI.getInstanceOrInitAndGetInstance = function () { + if (EmailPasswordPreBuiltUI.instance === undefined) { + var recipeInstance = recipe.EmailPassword.getInstanceOrThrow(); + EmailPasswordPreBuiltUI.instance = new EmailPasswordPreBuiltUI(recipeInstance); + } + return EmailPasswordPreBuiltUI.instance; + }; + EmailPasswordPreBuiltUI.getFeatures = function (useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = componentOverrideContext.useContext; } + return EmailPasswordPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatures(useComponentOverrides); + }; + EmailPasswordPreBuiltUI.getFeatureComponent = function (componentName, props, useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = componentOverrideContext.useContext; } + return EmailPasswordPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent(componentName, props, useComponentOverrides); + }; + EmailPasswordPreBuiltUI.prototype.getAuthComponents = function () { + var _this = this; + return [ + { + factorIds: [types.FactorIds.EMAILPASSWORD], + displayOrder: 2, + type: "SIGN_UP", + component: function (props) { return (jsxRuntime.jsx(SignUpFeature, utils.__assign({ recipe: _this.recipeInstance, useComponentOverrides: componentOverrideContext.useContext }, props), "emailpassword-sign-up")); }, + }, + { + factorIds: [types.FactorIds.EMAILPASSWORD], + displayOrder: 2, + type: "SIGN_IN", + component: function (props) { return (jsxRuntime.jsx(SignInFeature, utils.__assign({ recipe: _this.recipeInstance, useComponentOverrides: componentOverrideContext.useContext }, props), "emailpassword-sign-in")); }, + }, + ]; + }; + // For tests + EmailPasswordPreBuiltUI.reset = function () { + if (!utils.isTest()) { + return; + } + EmailPasswordPreBuiltUI.instance = undefined; + return; + }; + EmailPasswordPreBuiltUI.ResetPasswordUsingToken = function (prop) { + return EmailPasswordPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent("resetpassword", prop); + }; + EmailPasswordPreBuiltUI.ResetPasswordUsingTokenTheme = ResetPasswordUsingTokenThemeWrapper; + return EmailPasswordPreBuiltUI; +}(uiEntry.RecipeRouter)); var ResetPasswordUsingToken = EmailPasswordPreBuiltUI.ResetPasswordUsingToken; exports.EmailPasswordPreBuiltUI = EmailPasswordPreBuiltUI; diff --git a/lib/build/emailverification-shared.js b/lib/build/emailverification-shared.js index 1c7d9189f..c0ce7553c 100644 --- a/lib/build/emailverification-shared.js +++ b/lib/build/emailverification-shared.js @@ -1,305 +1,233 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var EmailVerificationWebJS = require("supertokens-web-js/recipe/emailverification"); -var postSuperTokensInitCallbacks = require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -var sessionClaimValidatorStore = require("supertokens-web-js/utils/sessionClaimValidatorStore"); -var index = require("./recipeModule-shared.js"); +var genericComponentOverrideContext = require('./genericComponentOverrideContext.js'); +var utils = require('./utils.js'); +var EmailVerificationWebJS = require('supertokens-web-js/recipe/emailverification'); +var postSuperTokensInitCallbacks = require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +var sessionClaimValidatorStore = require('supertokens-web-js/utils/sessionClaimValidatorStore'); +var index = require('./recipeModule-shared.js'); +var superTokens = require('./superTokens.js'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } -var EmailVerificationWebJS__default = /*#__PURE__*/ _interopDefault(EmailVerificationWebJS); +var EmailVerificationWebJS__default = /*#__PURE__*/_interopDefault(EmailVerificationWebJS); -var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), - useContext = _a[0], - Provider = _a[1]; +var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), useContext = _a[0], Provider = _a[1]; -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ var DEFAULT_VERIFY_EMAIL_PATH = "/verify-email"; -var EmailVerificationClaimClass = /** @class */ (function (_super) { - genericComponentOverrideContext.__extends(EmailVerificationClaimClass, _super); - function EmailVerificationClaimClass(getRecipeImpl, onFailureRedirection) { - var _this = _super.call(this, getRecipeImpl) || this; - var validatorsWithCallbacks = genericComponentOverrideContext.__assign({}, _this.validators); - var _loop_1 = function (key) { - var validator = validatorsWithCallbacks[key]; - validatorsWithCallbacks[key] = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, validator.apply(void 0, args)), - { - onFailureRedirection: function (args) { - if (onFailureRedirection !== undefined) { - return onFailureRedirection(args); - } - var recipe = EmailVerification.getInstanceOrThrow(); - if (recipe.config.mode === "REQUIRED") { - return recipe.getRedirectUrl( - { - action: "VERIFY_EMAIL", - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - }, - args.userContext - ); - } - return undefined; - }, - showAccessDeniedOnFailure: false, - } - ); - }; - }; - for (var key in validatorsWithCallbacks) { - _loop_1(key); - } - _this.validators = validatorsWithCallbacks; - return _this; - } - return EmailVerificationClaimClass; -})(EmailVerificationWebJS.EmailVerificationClaimClass); +var EmailVerificationClaimClass = /** @class */ (function (_super) { + utils.__extends(EmailVerificationClaimClass, _super); + function EmailVerificationClaimClass(getRecipeImpl, onFailureRedirection) { + var _this = _super.call(this, getRecipeImpl) || this; + var validatorsWithCallbacks = utils.__assign({}, _this.validators); + var _loop_1 = function (key) { + var validator = validatorsWithCallbacks[key]; + validatorsWithCallbacks[key] = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return utils.__assign(utils.__assign({}, validator.apply(void 0, args)), { onFailureRedirection: function (args) { + if (onFailureRedirection !== undefined) { + return onFailureRedirection(args); + } + var recipe = EmailVerification.getInstanceOrThrow(); + if (recipe.config.mode === "REQUIRED") { + return recipe.getRedirectUrl({ action: "VERIFY_EMAIL", tenantIdFromQueryParams: utils.getTenantIdFromQueryParams() }, args.userContext); + } + return undefined; + }, showAccessDeniedOnFailure: false }); + }; + }; + for (var key in validatorsWithCallbacks) { + _loop_1(key); + } + _this.validators = validatorsWithCallbacks; + return _this; + } + return EmailVerificationClaimClass; +}(EmailVerificationWebJS.EmailVerificationClaimClass)); -var getFunctionOverrides = function (onHandleEvent) { - return function (originalImp) { - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, originalImp), { - verifyEmail: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, originalImp.verifyEmail(input)]; - case 1: - response = _a.sent(); - if (response.status === "OK") { - onHandleEvent({ - action: "EMAIL_VERIFIED_SUCCESSFUL", - userContext: input.userContext, - }); - } - return [2 /*return*/, response]; - } - }); - }); - }, - sendVerificationEmail: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, originalImp.sendVerificationEmail(input)]; - case 1: - response = _a.sent(); - if (response.status === "OK") { - onHandleEvent({ - action: "VERIFY_EMAIL_SENT", - userContext: input.userContext, - }); - } - return [2 /*return*/, response]; - } - }); - }); - }, - }); - }; +var getFunctionOverrides = function (onHandleEvent) { + return function (originalImp) { return (utils.__assign(utils.__assign({}, originalImp), { verifyEmail: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, originalImp.verifyEmail(input)]; + case 1: + response = _a.sent(); + if (response.status === "OK") { + onHandleEvent({ + action: "EMAIL_VERIFIED_SUCCESSFUL", + userContext: input.userContext, + }); + } + return [2 /*return*/, response]; + } + }); + }); + }, sendVerificationEmail: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, originalImp.sendVerificationEmail(input)]; + case 1: + response = _a.sent(); + if (response.status === "OK") { + onHandleEvent({ + action: "VERIFY_EMAIL_SENT", + userContext: input.userContext, + }); + } + return [2 /*return*/, response]; + } + }); + }); + } })); }; }; -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -function normaliseEmailVerificationFeature(config) { - if (config === undefined) { - config = {}; - } - var disableDefaultUI = config.disableDefaultUI === true; - var mode = config.mode === undefined ? "REQUIRED" : config.mode; - var sendVerifyEmailScreenStyle = - config.sendVerifyEmailScreen !== undefined && config.sendVerifyEmailScreen.style !== undefined - ? config.sendVerifyEmailScreen.style - : ""; - var sendVerifyEmailScreen = { - style: sendVerifyEmailScreenStyle, - }; - var verifyEmailLinkClickedScreenStyle = - config.verifyEmailLinkClickedScreen !== undefined && config.verifyEmailLinkClickedScreen.style !== undefined - ? config.verifyEmailLinkClickedScreen.style - : ""; - var verifyEmailLinkClickedScreen = { - style: verifyEmailLinkClickedScreenStyle, - }; - var override = genericComponentOverrideContext.__assign( - { - functions: function (originalImplementation) { - return originalImplementation; - }, - }, - config.override - ); - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign( - {}, - genericComponentOverrideContext.normaliseRecipeModuleConfig(config) - ), - { - disableDefaultUI: disableDefaultUI, - mode: mode, - sendVerifyEmailScreen: sendVerifyEmailScreen, - verifyEmailLinkClickedScreen: verifyEmailLinkClickedScreen, - override: override, - } - ); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +function normaliseEmailVerificationFeature(config) { + if (config === undefined) { + config = {}; + } + var disableDefaultUI = config.disableDefaultUI === true; + var mode = config.mode === undefined ? "REQUIRED" : config.mode; + var sendVerifyEmailScreenStyle = config.sendVerifyEmailScreen !== undefined && config.sendVerifyEmailScreen.style !== undefined + ? config.sendVerifyEmailScreen.style + : ""; + var sendVerifyEmailScreen = { + style: sendVerifyEmailScreenStyle, + }; + var verifyEmailLinkClickedScreenStyle = config.verifyEmailLinkClickedScreen !== undefined && config.verifyEmailLinkClickedScreen.style !== undefined + ? config.verifyEmailLinkClickedScreen.style + : ""; + var verifyEmailLinkClickedScreen = { + style: verifyEmailLinkClickedScreenStyle, + }; + var override = utils.__assign({ functions: function (originalImplementation) { return originalImplementation; } }, config.override); + return utils.__assign(utils.__assign({}, superTokens.normaliseRecipeModuleConfig(config)), { disableDefaultUI: disableDefaultUI, mode: mode, sendVerifyEmailScreen: sendVerifyEmailScreen, verifyEmailLinkClickedScreen: verifyEmailLinkClickedScreen, override: override }); } -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var EmailVerification = /** @class */ (function (_super) { - genericComponentOverrideContext.__extends(EmailVerification, _super); - function EmailVerification(config, webJSRecipe) { - if (webJSRecipe === void 0) { - webJSRecipe = EmailVerificationWebJS__default.default; - } - var _this = _super.call(this, config) || this; - _this.webJSRecipe = webJSRecipe; - _this.recipeID = EmailVerification.RECIPE_ID; - _this.getDefaultRedirectionURL = function (context) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - if (context.action === "VERIFY_EMAIL") { - return [ - 2 /*return*/, - genericComponentOverrideContext.getDefaultRedirectionURLForPath( - this.config, - DEFAULT_VERIFY_EMAIL_PATH, - context - ), - ]; - } else { - return [2 /*return*/, "/"]; - } - }); - }); - }; - postSuperTokensInitCallbacks.PostSuperTokensInitCallbacks.addPostInitCallback(function () { - var isVerifiedValidator = EmailVerification.EmailVerificationClaim.validators.isVerified(10); - sessionClaimValidatorStore.SessionClaimValidatorStore.addClaimValidatorFromOtherRecipe(isVerifiedValidator); - }); - return _this; - } - EmailVerification.init = function (config) { - var normalisedConfig = normaliseEmailVerificationFeature(config); - return { - recipeID: EmailVerification.RECIPE_ID, - authReact: function (appInfo) { - EmailVerification.instance = new EmailVerification( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, normalisedConfig), - { appInfo: appInfo, recipeId: EmailVerification.RECIPE_ID } - ) - ); - return EmailVerification.instance; - }, - webJS: EmailVerificationWebJS__default.default.init( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, normalisedConfig), - { - override: { - functions: function (originalImpl, builder) { - var functions = getFunctionOverrides(normalisedConfig.onHandleEvent); - builder.override(functions); - builder.override(normalisedConfig.override.functions); - return originalImpl; - }, - }, - } - ) - ), - }; - }; - EmailVerification.getInstanceOrThrow = function () { - if (EmailVerification.instance === undefined) { - var error = "No instance of EmailVerification found. Make sure to call the EmailVerification.init method."; - // eslint-disable-next-line supertokens-auth-react/no-direct-window-object - if (typeof window === "undefined") { - error = error + genericComponentOverrideContext.SSR_ERROR; - } - throw Error(error); - } - return EmailVerification.instance; - }; - EmailVerification.prototype.isEmailVerified = function (userContext) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - this.webJSRecipe.isEmailVerified({ - userContext: userContext, - }), - ]; - case 1: - return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - EmailVerification.reset = function () { - if (!genericComponentOverrideContext.isTest()) { - return; - } - EmailVerification.instance = undefined; - return; - }; - EmailVerification.RECIPE_ID = "emailverification"; - EmailVerification.EmailVerificationClaim = new EmailVerificationClaimClass(function () { - return EmailVerification.getInstanceOrThrow().webJSRecipe; - }); - return EmailVerification; -})(index.RecipeModule); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var EmailVerification = /** @class */ (function (_super) { + utils.__extends(EmailVerification, _super); + function EmailVerification(config, webJSRecipe) { + if (webJSRecipe === void 0) { webJSRecipe = EmailVerificationWebJS__default.default; } + var _this = _super.call(this, config) || this; + _this.webJSRecipe = webJSRecipe; + _this.recipeID = EmailVerification.RECIPE_ID; + _this.getDefaultRedirectionURL = function (context) { return utils.__awaiter(_this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + if (context.action === "VERIFY_EMAIL") { + return [2 /*return*/, utils.getDefaultRedirectionURLForPath(this.config, DEFAULT_VERIFY_EMAIL_PATH, context)]; + } + else { + return [2 /*return*/, "/"]; + } + }); + }); }; + postSuperTokensInitCallbacks.PostSuperTokensInitCallbacks.addPostInitCallback(function () { + var isVerifiedValidator = EmailVerification.EmailVerificationClaim.validators.isVerified(10); + sessionClaimValidatorStore.SessionClaimValidatorStore.addClaimValidatorFromOtherRecipe(isVerifiedValidator); + }); + return _this; + } + EmailVerification.init = function (config) { + var normalisedConfig = normaliseEmailVerificationFeature(config); + return { + recipeID: EmailVerification.RECIPE_ID, + authReact: function (appInfo) { + EmailVerification.instance = new EmailVerification(utils.__assign(utils.__assign({}, normalisedConfig), { appInfo: appInfo, recipeId: EmailVerification.RECIPE_ID })); + return EmailVerification.instance; + }, + webJS: EmailVerificationWebJS__default.default.init(utils.__assign(utils.__assign({}, normalisedConfig), { override: { + functions: function (originalImpl, builder) { + var functions = getFunctionOverrides(normalisedConfig.onHandleEvent); + builder.override(functions); + builder.override(normalisedConfig.override.functions); + return originalImpl; + }, + } })), + }; + }; + EmailVerification.getInstanceOrThrow = function () { + if (EmailVerification.instance === undefined) { + var error = "No instance of EmailVerification found. Make sure to call the EmailVerification.init method."; + // eslint-disable-next-line supertokens-auth-react/no-direct-window-object + if (typeof window === "undefined") { + error = error + utils.SSR_ERROR; + } + throw Error(error); + } + return EmailVerification.instance; + }; + EmailVerification.prototype.isEmailVerified = function (userContext) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.webJSRecipe.isEmailVerified({ + userContext: userContext, + })]; + case 1: return [2 /*return*/, _a.sent()]; + } + }); + }); + }; + EmailVerification.reset = function () { + if (!utils.isTest()) { + return; + } + EmailVerification.instance = undefined; + return; + }; + EmailVerification.RECIPE_ID = "emailverification"; + EmailVerification.EmailVerificationClaim = new EmailVerificationClaimClass(function () { return EmailVerification.getInstanceOrThrow().webJSRecipe; }); + return EmailVerification; +}(index.RecipeModule)); exports.DEFAULT_VERIFY_EMAIL_PATH = DEFAULT_VERIFY_EMAIL_PATH; exports.EmailVerification = EmailVerification; diff --git a/lib/build/emailverification-shared2.js b/lib/build/emailverification-shared2.js index 5950573f8..e28e0073c 100644 --- a/lib/build/emailverification-shared2.js +++ b/lib/build/emailverification-shared2.js @@ -1,43 +1,19 @@ -"use strict"; +'use strict'; -var jsxRuntime = require("react/jsx-runtime"); -var React = require("react"); -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var uiEntry = require("./index2.js"); +var jsxRuntime = require('react/jsx-runtime'); +var React = require('react'); +var utils = require('./utils.js'); +var uiEntry = require('./index2.js'); -var styles = - '/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.\n *\n * This software is licensed under the Apache License, Version 2.0 (the\n * "License") as published by the Apache Software Foundation.\n *\n * You may not use this file except in compliance with the License. You may\n * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n[data-supertokens~="container"] {\n --palette-background: 255, 255, 255;\n --palette-inputBackground: 250, 250, 250;\n --palette-inputBorder: 224, 224, 224;\n --palette-primary: 28, 34, 42;\n --palette-primaryBorder: 45, 54, 68;\n --palette-success: 65, 167, 0;\n --palette-successBackground: 217, 255, 191;\n --palette-error: 255, 23, 23;\n --palette-errorBackground: 255, 241, 235;\n --palette-textTitle: 0, 0, 0;\n --palette-textLabel: 0, 0, 0;\n --palette-textInput: 0, 0, 0;\n --palette-textPrimary: 128, 128, 128;\n --palette-textLink: 0, 122, 255;\n --palette-buttonText: 255, 255, 255;\n --palette-textGray: 54, 54, 54;\n --palette-superTokensBrandingBackground: 242, 245, 246;\n --palette-superTokensBrandingText: 173, 189, 196;\n --palette-buttonGreyedOut: 221, 221, 221;\n --palette-caution: 124, 96, 62;\n --palette-errorDark: 207, 54, 68;\n\n --font-size-0: 12px;\n --font-size-1: 14px;\n --font-size-2: 16px;\n --font-size-3: 19px;\n --font-size-4: 24px;\n --font-size-5: 28px;\n}\n\n/*\n * Default styles.\n */\n\n@keyframes slideTop {\n 0% {\n transform: translateY(-5px);\n }\n 100% {\n transform: translateY(0px);\n }\n}\n\n@keyframes swing-in-top-fwd {\n 0% {\n transform: rotateX(-100deg);\n transform-origin: top;\n opacity: 0;\n }\n 100% {\n transform: rotateX(0deg);\n transform-origin: top;\n opacity: 1;\n }\n}\n\n[data-supertokens~="container"] {\n font-family: "Arial", sans-serif;\n margin: 12px auto;\n margin-top: 26px;\n margin-bottom: 26px;\n width: 420px;\n text-align: center;\n border-radius: 8px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.16);\n background-color: rgb(var(--palette-background));\n}\n\n@media (max-width: 440px) {\n [data-supertokens~="container"] {\n width: 95vw;\n }\n}\n\n[data-supertokens~="row"] {\n margin: 0 auto;\n width: 76%;\n padding-top: 30px;\n padding-bottom: 10px;\n}\n\n[data-supertokens~="superTokensBranding"] {\n display: block;\n margin: 10px auto 0;\n background: rgb(var(--palette-superTokensBrandingBackground));\n color: rgb(var(--palette-superTokensBrandingText));\n text-decoration: none;\n width: -webkit-fit-content;\n width: fit-content;\n border-radius: 6px 6px 0 0;\n padding: 4px 9px;\n font-weight: 400;\n font-size: var(--font-size-0);\n letter-spacing: 0.4px;\n}\n\n[data-supertokens~="generalError"] {\n background: rgb(var(--palette-errorBackground));\n padding-top: 10px;\n padding-bottom: 10px;\n margin-bottom: 10px;\n margin-top: 24px;\n padding-left: 18px;\n padding-right: 18px;\n letter-spacing: 0.2px;\n font-size: var(--font-size-1);\n border-radius: 8px;\n color: rgb(var(--palette-error));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n word-wrap: break-word;\n}\n\n[data-supertokens~="headerTitle"] {\n font-size: var(--font-size-4);\n line-height: 27.6px;\n letter-spacing: 0.58px;\n font-weight: 700;\n margin-bottom: 20px;\n color: rgb(var(--palette-textTitle));\n}\n\n[data-supertokens~="headerSubtitle"] {\n font-weight: 400;\n color: rgb(var(--palette-textGray));\n margin-bottom: 21px;\n}\n\n[data-supertokens~="headerSubtitle"][data-supertokens~="secondaryText"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n}\n\n[data-supertokens~="privacyPolicyAndTermsAndConditions"] {\n max-width: 300px;\n margin-top: 10px;\n}\n\n[data-supertokens~="privacyPolicyAndTermsAndConditions"] a {\n line-height: 21px;\n}\n\n/* TODO: split the link style into separate things*/\n\n/* We add this before primary and secondary text, because if they are applied to the same element the other ones take priority */\n\n[data-supertokens~="link"] {\n padding-left: 3px;\n padding-right: 3px;\n color: rgb(var(--palette-textLink));\n font-size: var(--font-size-1);\n cursor: pointer;\n letter-spacing: 0.16px;\n line-height: 26px;\n}\n\n[data-supertokens~="primaryText"] {\n font-size: var(--font-size-2);\n font-weight: 400;\n letter-spacing: 0.4px;\n line-height: 21px;\n color: rgb(var(--palette-textLabel));\n}\n\n[data-supertokens~="secondaryText"] {\n font-size: var(--font-size-1);\n font-weight: 400;\n letter-spacing: 0.4px;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~="secondaryText"] strong {\n font-weight: 600;\n}\n\n[data-supertokens~="divider"] {\n margin-top: 1.5em;\n margin-bottom: 1.5em;\n border-bottom: 0.3px solid #dddddd;\n align-items: center;\n padding-bottom: 5px;\n flex: 3 3;\n}\n\n[data-supertokens~="headerTinyTitle"] {\n margin-top: 24px;\n font-size: var(--font-size-5);\n letter-spacing: 1.1px;\n font-weight: 700;\n line-height: 28px;\n}\n\n[data-supertokens~="secondaryLinkWithArrow"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n}\n\n[data-supertokens~="secondaryLinkWithArrow"]:hover {\n position: relative;\n left: 2px;\n word-spacing: 4px;\n}\n\n[data-supertokens~="generalSuccess"] {\n color: rgb(var(--palette-success));\n font-size: var(--font-size-1);\n background: rgb(var(--palette-successBackground));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n padding: 9px 15px 9px 15px;\n border-radius: 6px;\n display: inline-block;\n}\n\n[data-supertokens~="spinner"] {\n width: 80px;\n height: auto;\n padding-top: 20px;\n padding-bottom: 40px;\n margin: 0 auto;\n}\n\n[data-supertokens~="error"] {\n color: rgb(var(--palette-error));\n}\n\n[data-supertokens~="linkButton"] {\n font-family: "Arial", sans-serif;\n background-color: transparent;\n border: 0;\n}\n\n[data-supertokens~="secondaryLinkWithLeftArrow"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n margin-top: 10px;\n margin-bottom: 40px;\n cursor: pointer;\n}\n\n[data-supertokens~="secondaryLinkWithLeftArrow"] svg {\n margin-right: 0.3em;\n}\n\n[data-supertokens~="secondaryLinkWithLeftArrow"]:hover svg {\n position: relative;\n left: -4px;\n}\n\n[data-supertokens~="button"] {\n font-family: "Arial", sans-serif;\n background-color: rgb(var(--palette-primary));\n color: rgb(var(--palette-buttonText));\n width: 100%;\n height: 34px;\n font-weight: 600;\n border-width: 1px;\n border-style: solid;\n border-radius: 6px;\n border-color: rgb(var(--palette-primaryBorder));\n background-position: center;\n transition: all 0.4s;\n background-size: 12000%;\n cursor: pointer;\n}\n\n[data-supertokens~="buttonGreyedOut"] {\n background-color: rgb(var(--palette-buttonGreyedOut));\n border-color: rgb(var(--palette-buttonGreyedOut));\n}\n\n[data-supertokens~="buttonWithIcon"] {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n}\n\n[data-supertokens~="button"]:disabled {\n border: none;\n cursor: no-drop;\n}\n\n[data-supertokens~="button"]:active {\n outline: none;\n transition: all 0s;\n background-size: 100%;\n filter: brightness(0.85);\n}\n\n[data-supertokens~="button"]:focus {\n outline: none;\n}\n\n[data-supertokens~="backButtonCommon"] {\n width: 16px;\n height: 13px;\n}\n\n[data-supertokens~="backButton"] {\n cursor: pointer;\n border: none;\n background-color: transparent;\n padding: 0px;\n}\n\n[data-supertokens~="backButtonPlaceholder"] {\n display: block;\n}\n\n[data-supertokens~="delayedRender"] {\n animation-duration: 0.1s;\n animation-name: animate-fade;\n animation-delay: 0.2s;\n animation-fill-mode: backwards;\n}\n\n@keyframes animate-fade {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n\n[data-supertokens~="footerLinkGroupVert"] {\n display: flex;\n flex-direction: column;\n margin-top: 10px;\n gap: 24px;\n}\n\n[data-supertokens~="footerLinkGroupVert"] > div {\n cursor: pointer;\n margin: 0;\n}\n\n[data-supertokens~="footerLinkGroupVert"] [data-supertokens~="secondaryText"] {\n font-weight: 400;\n}\n\n[data-supertokens~="footerLinkGroupVert"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n font-weight: 400;\n position: relative;\n left: -6px; /* half the width of the left arrow */\n}\n\n@media (max-width: 360px) {\n [data-supertokens~="footerLinkGroupVert"] {\n flex-direction: column;\n }\n [data-supertokens~="footerLinkGroupVert"] > div {\n margin: 0 auto;\n }\n}\n\n[data-supertokens~="footerLinkGroupVert"] div:only-child {\n margin-left: auto;\n margin-right: auto;\n margin-top: 14px;\n}\n\n[data-supertokens~="withBackButton"] {\n position: relative;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n[data-supertokens~="dividerWithOr"] {\n padding-top: 5px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~="dividerText"] {\n flex: 1 1;\n font-weight: 400;\n font-size: var(--font-size-1);\n}\n\n[data-supertokens~="formLabelWithLinkWrapper"] {\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n[data-supertokens~="formLabelLinkBtn"] {\n width: auto;\n margin-top: 0;\n line-height: 24px;\n font-size: var(--font-size-0);\n}\n\n[data-supertokens~="formLabelLinkBtn"]:hover {\n text-decoration: underline;\n}\n\n[data-supertokens~="formLabelLinkBtn"]:disabled {\n color: rgb(var(--palette-textPrimary));\n cursor: default;\n text-decoration: none;\n}\n\n[data-supertokens~="authComponentList"] {\n padding-bottom: 20px;\n}\n\n[data-supertokens~="authPageTitleOAuthClient"] {\n color: rgb(var(--palette-textGray));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 10px 0 25px;\n}\n\n[data-supertokens~="authPageTitleOAuthClientUrl"] {\n text-decoration: none;\n}\n\n[data-supertokens~="authPageTitleOAuthClientLogo"] {\n width: 44px;\n height: 44px;\n margin-bottom: 10px;\n}\n\n[data-supertokens~="authPageTitleOAuthClient"] [data-supertokens~="authPageTitleOAuthClientName"] {\n color: rgb(var(--palette-textTitle));\n}\n\n[data-supertokens~="buttonWithArrow"] {\n border-radius: 6px;\n border: 1px solid #d0d5dd;\n width: 100%;\n color: rgb(var(--palette-textGray));\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n margin: 24px 0;\n min-height: 48px;\n cursor: pointer;\n}\n\n[data-supertokens~="buttonWithArrow"]:hover {\n background-color: rgb(var(--palette-inputBackground));\n}\n\n[data-supertokens~="buttonWithArrow"] [data-supertokens~="secondaryText"] {\n font-weight: 700;\n font-size: var(--font-size-2);\n color: rgb(var(--palette-textGray));\n margin: 0;\n}\n\n[data-supertokens~="buttonWithArrow"]:hover [data-supertokens~="secondaryLinkWithRightArrow"] ~ svg {\n position: relative;\n left: 2px;\n}\n\n[data-supertokens~="buttonWithArrow"]:hover [data-supertokens~="secondaryLinkWithLeftArrow"] svg {\n position: relative;\n left: -2px;\n}\n\n[data-supertokens~="buttonWithArrow"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n display: flex;\n align-items: center;\n}\n\n[data-supertokens~="inputContainer"] {\n margin-top: 6px;\n}\n\n[data-supertokens~="inputWrapper"] {\n box-sizing: border-box;\n width: 100%;\n display: flex;\n align-items: center;\n background-color: rgb(var(--palette-inputBackground));\n height: 34px;\n border-radius: 6px;\n border: 1px solid rgb(var(--palette-inputBorder));\n}\n\n[data-supertokens~="inputWrapper"][focus-within] {\n background-color: rgba(var(--palette-inputBackground), 0.25);\n border: 1px solid rgb(var(--palette-primary));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-primary), 0.25);\n outline: none;\n}\n\n[data-supertokens~="inputWrapper"]:focus-within {\n background-color: rgba(var(--palette-inputBackground), 0.25);\n border: 1px solid rgb(var(--palette-primary));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-primary), 0.25);\n outline: none;\n}\n\n[data-supertokens~="inputError"] {\n border: 1px solid rgb(var(--palette-error));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-error), 0.25);\n outline: none;\n}\n\n[data-supertokens~="inputError"][focus-within] {\n border: 1px solid rgb(var(--palette-error));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-error), 0.25);\n outline: none;\n}\n\n[data-supertokens~="inputError"]:focus-within {\n border: 1px solid rgb(var(--palette-error));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-error), 0.25);\n outline: none;\n}\n\n[data-supertokens~="input"] {\n box-sizing: border-box;\n padding-left: 15px;\n filter: none;\n color: rgb(var(--palette-textInput));\n background-color: transparent;\n border-radius: 6px;\n font-size: var(--font-size-1);\n border: none;\n padding-right: 25px;\n letter-spacing: 1.2px;\n flex: 9 1 75%;\n width: 75%;\n height: 32px;\n}\n\n[data-supertokens~="input"]:focus {\n border: none;\n outline: none;\n}\n\n[data-supertokens~="input"]:-webkit-autofill,\n[data-supertokens~="input"]:-webkit-autofill:hover,\n[data-supertokens~="input"]:-webkit-autofill:focus,\n[data-supertokens~="input"]:-webkit-autofill:active {\n -webkit-text-fill-color: rgb(var(--palette-textInput));\n box-shadow: 0 0 0 30px rgb(var(--palette-inputBackground)) inset;\n}\n\n[data-supertokens~="inputAdornment"] {\n justify-content: center;\n margin-right: 5px;\n}\n\n[data-supertokens~="showPassword"] {\n cursor: pointer;\n}\n\n[data-supertokens~="enterEmailSuccessMessage"] {\n margin-top: 15px;\n margin-bottom: 15px;\n word-break: break-word;\n}\n\n[data-supertokens~="submitNewPasswordSuccessMessage"] {\n margin-top: 15px;\n margin-bottom: 15px;\n}\n\n[data-supertokens~="inputErrorMessage"] {\n padding-top: 5px;\n padding-bottom: 5px;\n color: rgb(var(--palette-error));\n line-height: 24px;\n font-weight: 400;\n font-size: var(--font-size-1);\n text-align: left;\n animation: slideTop 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;\n max-width: 330px;\n}\n\n@media (max-width: 440px) {\n [data-supertokens~="inputErrorMessage"] {\n max-width: 250px;\n }\n}\n\n[data-supertokens~="inputErrorSymbol"] {\n margin-right: 5px;\n top: 1px;\n position: relative;\n left: 2px;\n}\n\n[data-supertokens~="label"] {\n text-align: left;\n font-weight: 700;\n font-size: var(--font-size-0);\n line-height: 24px;\n color: rgb(var(--palette-textLabel));\n}\n\n[data-supertokens~="formRow"] {\n display: flex;\n flex-direction: column;\n padding-top: 0px;\n padding-bottom: 20px;\n}\n\n[data-supertokens~="formRow"][data-supertokens~="hasError"] {\n padding-bottom: 0;\n}\n\n[data-supertokens~="formRow"]:last-child {\n padding-bottom: 0;\n}\n\n[data-supertokens~="sendVerifyEmailIcon"] {\n margin-top: 11px;\n}\n\n[data-supertokens~="primaryText"][data-supertokens~="sendVerifyEmailText"] {\n text-align: center;\n letter-spacing: 0.8px;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~="secondaryLinkWithArrow"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n font-weight: 700;\n}\n\n[data-supertokens~="sendVerifyEmailResend"] {\n margin-top: 13px;\n font-weight: 400;\n}\n\n[data-supertokens~="sendVerifyEmailResend"]:hover {\n text-decoration: underline;\n}\n\n[data-supertokens~="noFormRow"] {\n padding-bottom: 25px;\n}\n\n[data-supertokens~="emailVerificationButtonWrapper"] {\n padding-top: 25px;\n max-width: 96px;\n margin: 0 auto;\n}\n\n[data-supertokens~="resendEmailLink"] {\n display: inline-block;\n}\n\n[data-supertokens~="resetPasswordEmailForm"] {\n padding-bottom: 20px;\n}\n\n[data-supertokens~="resetPasswordPasswordForm"] {\n padding-bottom: 20px;\n}\n'; +var styles = "/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.\n *\n * This software is licensed under the Apache License, Version 2.0 (the\n * \"License\") as published by the Apache Software Foundation.\n *\n * You may not use this file except in compliance with the License. You may\n * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n[data-supertokens~=\"container\"] {\n --palette-background: 255, 255, 255;\n --palette-inputBackground: 250, 250, 250;\n --palette-inputBorder: 224, 224, 224;\n --palette-primary: 28, 34, 42;\n --palette-primaryBorder: 45, 54, 68;\n --palette-success: 65, 167, 0;\n --palette-successBackground: 217, 255, 191;\n --palette-error: 255, 23, 23;\n --palette-errorBackground: 255, 241, 235;\n --palette-textTitle: 0, 0, 0;\n --palette-textLabel: 0, 0, 0;\n --palette-textInput: 0, 0, 0;\n --palette-textPrimary: 128, 128, 128;\n --palette-textLink: 0, 122, 255;\n --palette-buttonText: 255, 255, 255;\n --palette-textGray: 54, 54, 54;\n --palette-superTokensBrandingBackground: 242, 245, 246;\n --palette-superTokensBrandingText: 173, 189, 196;\n --palette-buttonGreyedOut: 221, 221, 221;\n --palette-caution: 124, 96, 62;\n --palette-errorDark: 207, 54, 68;\n\n --font-size-0: 12px;\n --font-size-1: 14px;\n --font-size-2: 16px;\n --font-size-3: 19px;\n --font-size-4: 24px;\n --font-size-5: 28px;\n}\n\n/*\n * Default styles.\n */\n\n@keyframes slideTop {\n 0% {\n transform: translateY(-5px);\n }\n 100% {\n transform: translateY(0px);\n }\n}\n\n@keyframes swing-in-top-fwd {\n 0% {\n transform: rotateX(-100deg);\n transform-origin: top;\n opacity: 0;\n }\n 100% {\n transform: rotateX(0deg);\n transform-origin: top;\n opacity: 1;\n }\n}\n\n[data-supertokens~=\"container\"] {\n font-family: \"Arial\", sans-serif;\n margin: 12px auto;\n margin-top: 26px;\n margin-bottom: 26px;\n width: 420px;\n text-align: center;\n border-radius: 8px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.16);\n background-color: rgb(var(--palette-background));\n}\n\n@media (max-width: 440px) {\n [data-supertokens~=\"container\"] {\n width: 95vw;\n }\n}\n\n[data-supertokens~=\"row\"] {\n margin: 0 auto;\n width: 76%;\n padding-top: 30px;\n padding-bottom: 10px;\n}\n\n[data-supertokens~=\"superTokensBranding\"] {\n display: block;\n margin: 10px auto 0;\n background: rgb(var(--palette-superTokensBrandingBackground));\n color: rgb(var(--palette-superTokensBrandingText));\n text-decoration: none;\n width: -webkit-fit-content;\n width: -moz-fit-content;\n width: fit-content;\n border-radius: 6px 6px 0 0;\n padding: 4px 9px;\n font-weight: 400;\n font-size: var(--font-size-0);\n letter-spacing: 0.4px;\n}\n\n[data-supertokens~=\"generalError\"] {\n background: rgb(var(--palette-errorBackground));\n padding-top: 10px;\n padding-bottom: 10px;\n margin-bottom: 10px;\n margin-top: 24px;\n padding-left: 18px;\n padding-right: 18px;\n letter-spacing: 0.2px;\n font-size: var(--font-size-1);\n border-radius: 8px;\n color: rgb(var(--palette-error));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n word-wrap: break-word;\n}\n\n[data-supertokens~=\"headerTitle\"] {\n font-size: var(--font-size-4);\n line-height: 27.6px;\n letter-spacing: 0.58px;\n font-weight: 700;\n margin-bottom: 20px;\n color: rgb(var(--palette-textTitle));\n}\n\n[data-supertokens~=\"headerSubtitle\"] {\n font-weight: 400;\n color: rgb(var(--palette-textGray));\n margin-bottom: 21px;\n}\n\n[data-supertokens~=\"headerSubtitle\"][data-supertokens~=\"secondaryText\"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n}\n\n[data-supertokens~=\"privacyPolicyAndTermsAndConditions\"] {\n max-width: 300px;\n margin-top: 10px;\n}\n\n[data-supertokens~=\"privacyPolicyAndTermsAndConditions\"] a {\n line-height: 21px;\n}\n\n/* TODO: split the link style into separate things*/\n\n/* We add this before primary and secondary text, because if they are applied to the same element the other ones take priority */\n\n[data-supertokens~=\"link\"] {\n padding-left: 3px;\n padding-right: 3px;\n color: rgb(var(--palette-textLink));\n font-size: var(--font-size-1);\n cursor: pointer;\n letter-spacing: 0.16px;\n line-height: 26px;\n}\n\n[data-supertokens~=\"primaryText\"] {\n font-size: var(--font-size-2);\n font-weight: 400;\n letter-spacing: 0.4px;\n line-height: 21px;\n color: rgb(var(--palette-textLabel));\n}\n\n[data-supertokens~=\"secondaryText\"] {\n font-size: var(--font-size-1);\n font-weight: 400;\n letter-spacing: 0.4px;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~=\"secondaryText\"] strong {\n font-weight: 600;\n}\n\n[data-supertokens~=\"divider\"] {\n margin-top: 1.5em;\n margin-bottom: 1.5em;\n border-bottom: 0.3px solid #dddddd;\n align-items: center;\n padding-bottom: 5px;\n flex: 3 3;\n}\n\n[data-supertokens~=\"headerTinyTitle\"] {\n margin-top: 24px;\n font-size: var(--font-size-5);\n letter-spacing: 1.1px;\n font-weight: 700;\n line-height: 28px;\n}\n\n[data-supertokens~=\"secondaryLinkWithArrow\"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n}\n\n[data-supertokens~=\"secondaryLinkWithArrow\"]:hover {\n position: relative;\n left: 2px;\n word-spacing: 4px;\n}\n\n[data-supertokens~=\"generalSuccess\"] {\n color: rgb(var(--palette-success));\n font-size: var(--font-size-1);\n background: rgb(var(--palette-successBackground));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n padding: 9px 15px 9px 15px;\n border-radius: 6px;\n display: inline-block;\n}\n\n[data-supertokens~=\"spinner\"] {\n width: 80px;\n height: auto;\n padding-top: 20px;\n padding-bottom: 40px;\n margin: 0 auto;\n}\n\n[data-supertokens~=\"error\"] {\n color: rgb(var(--palette-error));\n}\n\n[data-supertokens~=\"linkButton\"] {\n font-family: \"Arial\", sans-serif;\n background-color: transparent;\n border: 0;\n}\n\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n margin-top: 10px;\n margin-bottom: 40px;\n cursor: pointer;\n}\n\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"] svg {\n margin-right: 0.3em;\n}\n\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"]:hover svg {\n position: relative;\n left: -4px;\n}\n\n[data-supertokens~=\"button\"] {\n font-family: \"Arial\", sans-serif;\n background-color: rgb(var(--palette-primary));\n color: rgb(var(--palette-buttonText));\n width: 100%;\n height: 34px;\n font-weight: 600;\n border-width: 1px;\n border-style: solid;\n border-radius: 6px;\n border-color: rgb(var(--palette-primaryBorder));\n background-position: center;\n transition: all 0.4s;\n background-size: 12000%;\n cursor: pointer;\n}\n\n[data-supertokens~=\"buttonGreyedOut\"] {\n background-color: rgb(var(--palette-buttonGreyedOut));\n border-color: rgb(var(--palette-buttonGreyedOut));\n}\n\n[data-supertokens~=\"buttonWithIcon\"] {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n}\n\n[data-supertokens~=\"button\"]:disabled {\n border: none;\n cursor: no-drop;\n}\n\n[data-supertokens~=\"button\"]:active {\n outline: none;\n transition: all 0s;\n background-size: 100%;\n filter: brightness(0.85);\n}\n\n[data-supertokens~=\"button\"]:focus {\n outline: none;\n}\n\n[data-supertokens~=\"backButtonCommon\"] {\n width: 16px;\n height: 13px;\n}\n\n[data-supertokens~=\"backButton\"] {\n cursor: pointer;\n border: none;\n background-color: transparent;\n padding: 0px;\n}\n\n[data-supertokens~=\"backButtonPlaceholder\"] {\n display: block;\n}\n\n[data-supertokens~=\"delayedRender\"] {\n animation-duration: 0.1s;\n animation-name: animate-fade;\n animation-delay: 0.2s;\n animation-fill-mode: backwards;\n}\n\n@keyframes animate-fade {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] {\n display: flex;\n flex-direction: column;\n margin-top: 10px;\n gap: 24px;\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] > div {\n cursor: pointer;\n margin: 0;\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] [data-supertokens~=\"secondaryText\"] {\n font-weight: 400;\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n font-weight: 400;\n position: relative;\n left: -6px; /* half the width of the left arrow */\n}\n\n@media (max-width: 360px) {\n [data-supertokens~=\"footerLinkGroupVert\"] {\n flex-direction: column;\n }\n [data-supertokens~=\"footerLinkGroupVert\"] > div {\n margin: 0 auto;\n }\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] div:only-child {\n margin-left: auto;\n margin-right: auto;\n margin-top: 14px;\n}\n\n[data-supertokens~=\"withBackButton\"] {\n position: relative;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n[data-supertokens~=\"dividerWithOr\"] {\n padding-top: 5px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~=\"dividerText\"] {\n flex: 1 1;\n font-weight: 400;\n font-size: var(--font-size-1);\n}\n\n[data-supertokens~=\"formLabelWithLinkWrapper\"] {\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n[data-supertokens~=\"formLabelLinkBtn\"] {\n width: auto;\n margin-top: 0;\n line-height: 24px;\n font-size: var(--font-size-0);\n}\n\n[data-supertokens~=\"formLabelLinkBtn\"]:hover {\n text-decoration: underline;\n}\n\n[data-supertokens~=\"formLabelLinkBtn\"]:disabled {\n color: rgb(var(--palette-textPrimary));\n cursor: default;\n text-decoration: none;\n}\n\n[data-supertokens~=\"authComponentList\"] {\n padding-bottom: 20px;\n}\n\n[data-supertokens~=\"authPageTitleOAuthClient\"] {\n color: rgb(var(--palette-textGray));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 10px 0 25px;\n}\n\n[data-supertokens~=\"authPageTitleOAuthClientUrl\"] {\n text-decoration: none;\n}\n\n[data-supertokens~=\"authPageTitleOAuthClientLogo\"] {\n width: 44px;\n height: 44px;\n margin-bottom: 10px;\n}\n\n[data-supertokens~=\"authPageTitleOAuthClient\"] [data-supertokens~=\"authPageTitleOAuthClientName\"] {\n color: rgb(var(--palette-textTitle));\n}\n\n[data-supertokens~=\"buttonWithArrow\"] {\n border-radius: 6px;\n border: 1px solid #d0d5dd;\n width: 100%;\n color: rgb(var(--palette-textGray));\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n margin: 24px 0;\n min-height: 48px;\n cursor: pointer;\n}\n\n[data-supertokens~=\"buttonWithArrow\"]:hover {\n background-color: rgb(var(--palette-inputBackground));\n}\n\n[data-supertokens~=\"buttonWithArrow\"] [data-supertokens~=\"secondaryText\"] {\n font-weight: 700;\n font-size: var(--font-size-2);\n color: rgb(var(--palette-textGray));\n margin: 0;\n}\n\n[data-supertokens~=\"buttonWithArrow\"]:hover [data-supertokens~=\"secondaryLinkWithRightArrow\"] ~ svg {\n position: relative;\n left: 2px;\n}\n\n[data-supertokens~=\"buttonWithArrow\"]:hover [data-supertokens~=\"secondaryLinkWithLeftArrow\"] svg {\n position: relative;\n left: -2px;\n}\n\n[data-supertokens~=\"buttonWithArrow\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n display: flex;\n align-items: center;\n}\n\n[data-supertokens~=\"inputContainer\"] {\n margin-top: 6px;\n}\n\n[data-supertokens~=\"inputWrapper\"] {\n box-sizing: border-box;\n width: 100%;\n display: flex;\n align-items: center;\n background-color: rgb(var(--palette-inputBackground));\n height: 34px;\n border-radius: 6px;\n border: 1px solid rgb(var(--palette-inputBorder));\n}\n\n[data-supertokens~=\"inputWrapper\"][focus-within] {\n background-color: rgba(var(--palette-inputBackground), 0.25);\n border: 1px solid rgb(var(--palette-primary));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-primary), 0.25);\n outline: none;\n}\n\n[data-supertokens~=\"inputWrapper\"]:focus-within {\n background-color: rgba(var(--palette-inputBackground), 0.25);\n border: 1px solid rgb(var(--palette-primary));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-primary), 0.25);\n outline: none;\n}\n\n[data-supertokens~=\"inputError\"] {\n border: 1px solid rgb(var(--palette-error));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-error), 0.25);\n outline: none;\n}\n\n[data-supertokens~=\"inputError\"][focus-within] {\n border: 1px solid rgb(var(--palette-error));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-error), 0.25);\n outline: none;\n}\n\n[data-supertokens~=\"inputError\"]:focus-within {\n border: 1px solid rgb(var(--palette-error));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-error), 0.25);\n outline: none;\n}\n\n[data-supertokens~=\"input\"] {\n box-sizing: border-box;\n padding-left: 15px;\n filter: none;\n color: rgb(var(--palette-textInput));\n background-color: transparent;\n border-radius: 6px;\n font-size: var(--font-size-1);\n border: none;\n padding-right: 25px;\n letter-spacing: 1.2px;\n flex: 9 1 75%;\n width: 75%;\n height: 32px;\n}\n\n[data-supertokens~=\"input\"]:focus {\n border: none;\n outline: none;\n}\n\n[data-supertokens~=\"input\"]:-webkit-autofill,\n[data-supertokens~=\"input\"]:-webkit-autofill:hover,\n[data-supertokens~=\"input\"]:-webkit-autofill:focus,\n[data-supertokens~=\"input\"]:-webkit-autofill:active {\n -webkit-text-fill-color: rgb(var(--palette-textInput));\n box-shadow: 0 0 0 30px rgb(var(--palette-inputBackground)) inset;\n}\n\n[data-supertokens~=\"inputAdornment\"] {\n justify-content: center;\n margin-right: 5px;\n}\n\n[data-supertokens~=\"showPassword\"] {\n cursor: pointer;\n}\n\n[data-supertokens~=\"enterEmailSuccessMessage\"] {\n margin-top: 15px;\n margin-bottom: 15px;\n word-break: break-word;\n}\n\n[data-supertokens~=\"submitNewPasswordSuccessMessage\"] {\n margin-top: 15px;\n margin-bottom: 15px;\n}\n\n[data-supertokens~=\"inputErrorMessage\"] {\n padding-top: 5px;\n padding-bottom: 5px;\n color: rgb(var(--palette-error));\n line-height: 24px;\n font-weight: 400;\n font-size: var(--font-size-1);\n text-align: left;\n animation: slideTop 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;\n max-width: 330px;\n}\n\n@media (max-width: 440px) {\n [data-supertokens~=\"inputErrorMessage\"] {\n max-width: 250px;\n }\n}\n\n[data-supertokens~=\"inputErrorSymbol\"] {\n margin-right: 5px;\n top: 1px;\n position: relative;\n left: 2px;\n}\n\n[data-supertokens~=\"label\"] {\n text-align: left;\n font-weight: 700;\n font-size: var(--font-size-0);\n line-height: 24px;\n color: rgb(var(--palette-textLabel));\n}\n\n[data-supertokens~=\"formRow\"] {\n display: flex;\n flex-direction: column;\n padding-top: 0px;\n padding-bottom: 20px;\n}\n\n[data-supertokens~=\"formRow\"][data-supertokens~=\"hasError\"] {\n padding-bottom: 0;\n}\n\n[data-supertokens~=\"formRow\"]:last-child {\n padding-bottom: 0;\n}\n\n[data-supertokens~=\"sendVerifyEmailIcon\"] {\n margin-top: 11px;\n}\n\n[data-supertokens~=\"primaryText\"][data-supertokens~=\"sendVerifyEmailText\"] {\n text-align: center;\n letter-spacing: 0.8px;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~=\"secondaryLinkWithArrow\"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n font-weight: 700;\n}\n\n[data-supertokens~=\"sendVerifyEmailResend\"] {\n margin-top: 13px;\n font-weight: 400;\n}\n\n[data-supertokens~=\"sendVerifyEmailResend\"]:hover {\n text-decoration: underline;\n}\n\n[data-supertokens~=\"noFormRow\"] {\n padding-bottom: 25px;\n}\n\n[data-supertokens~=\"emailVerificationButtonWrapper\"] {\n padding-top: 25px;\n max-width: 96px;\n margin: 0 auto;\n}\n\n[data-supertokens~=\"resendEmailLink\"] {\n display: inline-block;\n}\n\n[data-supertokens~=\"resetPasswordEmailForm\"] {\n padding-bottom: 20px;\n}\n\n[data-supertokens~=\"resetPasswordPasswordForm\"] {\n padding-bottom: 20px;\n}\n"; -var ThemeBase = function (_a) { - var children = _a.children, - userStyles = _a.userStyles; - return jsxRuntime.jsxs(React.Fragment, { - children: [children, jsxRuntime.jsxs("style", { children: [styles, userStyles.join("\n")] })], - }); +var ThemeBase = function (_a) { + var children = _a.children, userStyles = _a.userStyles; + return (jsxRuntime.jsxs(React.Fragment, { children: [children, jsxRuntime.jsxs("style", { children: [styles, userStyles.join("\n")] })] })); }; -var defaultTranslationsEmailVerification = { - en: genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, uiEntry.defaultTranslationsCommon.en), - { - EMAIL_VERIFICATION_RESEND_SUCCESS: "Email resent", - EMAIL_VERIFICATION_SEND_TITLE: "Verify your email!", - EMAIL_VERIFICATION_SEND_DESC_START: "", - EMAIL_VERIFICATION_SEND_DESC_STRONG: "Please click on the link", - EMAIL_VERIFICATION_SEND_DESC_END: " in the email we just sent you to confirm your email address.", - EMAIL_VERIFICATION_RESEND_BTN: "Resend Email", - EMAIL_VERIFICATION_LOGOUT: "Logout ", - EMAIL_VERIFICATION_SUCCESS: "Email verification successful!", - EMAIL_VERIFICATION_CONTINUE_BTN: "CONTINUE", - EMAIL_VERIFICATION_CONTINUE_LINK: "Continue", - EMAIL_VERIFICATION_EXPIRED: "The email verification link has expired", - EMAIL_VERIFICATION_ERROR_TITLE: "Something went wrong", - EMAIL_VERIFICATION_ERROR_DESC: "We encountered an unexpected error. Please contact support for assistance", - EMAIL_VERIFICATION_LINK_CLICKED_HEADER: "Verify your email address", - EMAIL_VERIFICATION_LINK_CLICKED_DESC: "Please click on the button below to verify your email address", - EMAIL_VERIFICATION_LINK_CLICKED_CONTINUE_BUTTON: "CONTINUE", - } - ), +var defaultTranslationsEmailVerification = { + en: utils.__assign(utils.__assign({}, uiEntry.defaultTranslationsCommon.en), { EMAIL_VERIFICATION_RESEND_SUCCESS: "Email resent", EMAIL_VERIFICATION_SEND_TITLE: "Verify your email!", EMAIL_VERIFICATION_SEND_DESC_START: "", EMAIL_VERIFICATION_SEND_DESC_STRONG: "Please click on the link", EMAIL_VERIFICATION_SEND_DESC_END: " in the email we just sent you to confirm your email address.", EMAIL_VERIFICATION_RESEND_BTN: "Resend Email", EMAIL_VERIFICATION_LOGOUT: "Logout ", EMAIL_VERIFICATION_SUCCESS: "Email verification successful!", EMAIL_VERIFICATION_CONTINUE_BTN: "CONTINUE", EMAIL_VERIFICATION_CONTINUE_LINK: "Continue", EMAIL_VERIFICATION_EXPIRED: "The email verification link has expired", EMAIL_VERIFICATION_ERROR_TITLE: "Something went wrong", EMAIL_VERIFICATION_ERROR_DESC: "We encountered an unexpected error. Please contact support for assistance", EMAIL_VERIFICATION_LINK_CLICKED_HEADER: "Verify your email address", EMAIL_VERIFICATION_LINK_CLICKED_DESC: "Please click on the button below to verify your email address", EMAIL_VERIFICATION_LINK_CLICKED_CONTINUE_BUTTON: "CONTINUE" }), }; exports.ThemeBase = ThemeBase; diff --git a/lib/build/emailverification.js b/lib/build/emailverification.js index 90ef1abb0..73fc673ff 100644 --- a/lib/build/emailverification.js +++ b/lib/build/emailverification.js @@ -1,110 +1,81 @@ -"use strict"; +'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, '__esModule', { value: true }); -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var recipe = require("./emailverification-shared.js"); -require("supertokens-web-js"); -require("supertokens-web-js/utils/cookieHandler"); -require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -require("supertokens-web-js/utils/windowHandler"); -require("supertokens-web-js/recipe/multitenancy"); -require("supertokens-web-js/utils"); -require("react"); -require("supertokens-web-js/lib/build/error"); -require("supertokens-web-js/utils/normalisedURLDomain"); -require("supertokens-web-js/utils/normalisedURLPath"); -require("react/jsx-runtime"); -require("supertokens-web-js/recipe/emailverification"); -require("supertokens-web-js/utils/sessionClaimValidatorStore"); -require("./recipeModule-shared.js"); +var utils = require('./utils.js'); +var recipe = require('./emailverification-shared.js'); +require('react'); +require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('supertokens-web-js/utils/normalisedURLPath'); +require('supertokens-web-js/utils/windowHandler'); +require('crypto'); +require('./genericComponentOverrideContext.js'); +require('react/jsx-runtime'); +require('supertokens-web-js/recipe/emailverification'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('supertokens-web-js/utils/sessionClaimValidatorStore'); +require('./recipeModule-shared.js'); +require('./superTokens.js'); +require('supertokens-web-js'); +require('supertokens-web-js/recipe/multitenancy'); +require('supertokens-web-js/utils'); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var Wrapper = /** @class */ (function () { - function Wrapper() {} - Wrapper.init = function (config) { - return recipe.EmailVerification.init(config); - }; - Wrapper.isEmailVerified = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.EmailVerification.getInstanceOrThrow().webJSRecipe.isEmailVerified( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ), - ]; - }); - }); - }; - Wrapper.verifyEmail = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.EmailVerification.getInstanceOrThrow().webJSRecipe.verifyEmail( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ), - ]; - }); - }); - }; - Wrapper.sendVerificationEmail = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.EmailVerification.getInstanceOrThrow().webJSRecipe.sendVerificationEmail( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ), - ]; - }); - }); - }; - Wrapper.getEmailVerificationTokenFromURL = function (input) { - return recipe.EmailVerification.getInstanceOrThrow().webJSRecipe.getEmailVerificationTokenFromURL( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ); - }; - Wrapper.EmailVerificationClaim = recipe.EmailVerification.EmailVerificationClaim; - Wrapper.ComponentsOverrideProvider = recipe.Provider; - return Wrapper; -})(); -var init = Wrapper.init; -var isEmailVerified = Wrapper.isEmailVerified; -var verifyEmail = Wrapper.verifyEmail; -var sendVerificationEmail = Wrapper.sendVerificationEmail; -var getEmailVerificationTokenFromURL = Wrapper.getEmailVerificationTokenFromURL; -var EmailVerificationComponentsOverrideProvider = Wrapper.ComponentsOverrideProvider; +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var Wrapper = /** @class */ (function () { + function Wrapper() { + } + Wrapper.init = function (config) { + return recipe.EmailVerification.init(config); + }; + Wrapper.isEmailVerified = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.EmailVerification.getInstanceOrThrow().webJSRecipe.isEmailVerified(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) }))]; + }); + }); + }; + Wrapper.verifyEmail = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.EmailVerification.getInstanceOrThrow().webJSRecipe.verifyEmail(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) }))]; + }); + }); + }; + Wrapper.sendVerificationEmail = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.EmailVerification.getInstanceOrThrow().webJSRecipe.sendVerificationEmail(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) }))]; + }); + }); + }; + Wrapper.getEmailVerificationTokenFromURL = function (input) { + return recipe.EmailVerification.getInstanceOrThrow().webJSRecipe.getEmailVerificationTokenFromURL(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) })); + }; + Wrapper.EmailVerificationClaim = recipe.EmailVerification.EmailVerificationClaim; + Wrapper.ComponentsOverrideProvider = recipe.Provider; + return Wrapper; +}()); +var init = Wrapper.init; +var isEmailVerified = Wrapper.isEmailVerified; +var verifyEmail = Wrapper.verifyEmail; +var sendVerificationEmail = Wrapper.sendVerificationEmail; +var getEmailVerificationTokenFromURL = Wrapper.getEmailVerificationTokenFromURL; +var EmailVerificationComponentsOverrideProvider = Wrapper.ComponentsOverrideProvider; var EmailVerificationClaim = recipe.EmailVerification.EmailVerificationClaim; exports.EmailVerificationClaim = EmailVerificationClaim; diff --git a/lib/build/emailverificationprebuiltui.js b/lib/build/emailverificationprebuiltui.js index 9253f8436..67ee50760 100644 --- a/lib/build/emailverificationprebuiltui.js +++ b/lib/build/emailverificationprebuiltui.js @@ -1,63 +1,56 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var jsxRuntime = require("react/jsx-runtime"); -var NormalisedURLPath = require("supertokens-web-js/utils/normalisedURLPath"); -var uiEntry = require("./index2.js"); -var session = require("./session.js"); -var recipe = require("./emailverification-shared.js"); -var React = require("react"); -var types = require("./multifactorauth-shared.js"); -var translations = require("./emailverification-shared2.js"); -var STGeneralError = require("supertokens-web-js/utils/error"); -var emailLargeIcon = require("./emailLargeIcon.js"); -var translationContext = require("./translationContext.js"); -var button = require("./emailpassword-shared.js"); -require("supertokens-web-js"); -require("supertokens-web-js/utils/cookieHandler"); -require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -require("supertokens-web-js/utils/windowHandler"); -require("supertokens-web-js/recipe/multitenancy"); -require("supertokens-web-js/utils"); -require("supertokens-web-js/lib/build/error"); -require("supertokens-web-js/utils/normalisedURLDomain"); -require("react-dom"); -require("./multitenancy-shared.js"); -require("./multifactorauth-shared2.js"); -require("supertokens-web-js/recipe/multifactorauth"); -require("supertokens-web-js/utils/sessionClaimValidatorStore"); -require("./recipeModule-shared.js"); -require("./oauth2provider-shared.js"); -require("supertokens-web-js/recipe/oauth2provider"); -require("./authRecipe-shared.js"); -require("supertokens-web-js/lib/build/normalisedURLPath"); -require("supertokens-web-js/recipe/session"); -require("./session-shared.js"); -require("supertokens-web-js/recipe/emailverification"); +var utils = require('./utils.js'); +var jsxRuntime = require('react/jsx-runtime'); +var NormalisedURLPath = require('supertokens-web-js/utils/normalisedURLPath'); +var uiEntry = require('./index2.js'); +var session = require('./session.js'); +var recipe = require('./emailverification-shared.js'); +var React = require('react'); +var superTokens = require('./superTokens.js'); +var types = require('./multifactorauth-shared.js'); +var translations = require('./emailverification-shared2.js'); +var STGeneralError = require('supertokens-web-js/utils/error'); +var emailLargeIcon = require('./emailLargeIcon.js'); +var translationContext = require('./translationContext.js'); +var button = require('./emailpassword-shared.js'); +require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('supertokens-web-js/utils/windowHandler'); +require('crypto'); +require('react-dom'); +require('./multitenancy-shared.js'); +require('./genericComponentOverrideContext.js'); +require('./multifactorauth-shared2.js'); +require('supertokens-web-js/recipe/multifactorauth'); +require('supertokens-web-js/utils'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('supertokens-web-js/utils/sessionClaimValidatorStore'); +require('./recipeModule-shared.js'); +require('./oauth2provider-shared.js'); +require('supertokens-web-js/recipe/oauth2provider'); +require('./authRecipe-shared.js'); +require('supertokens-web-js/lib/build/normalisedURLPath'); +require('supertokens-web-js/recipe/session'); +require('./session-shared.js'); +require('supertokens-web-js/recipe/emailverification'); +require('supertokens-web-js'); +require('supertokens-web-js/recipe/multitenancy'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { - if (k !== "default") { + if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: function () { - return e[k]; - }, - } - ); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); } }); } @@ -65,1125 +58,496 @@ function _interopNamespace(e) { return Object.freeze(n); } -var NormalisedURLPath__default = /*#__PURE__*/ _interopDefault(NormalisedURLPath); -var React__namespace = /*#__PURE__*/ _interopNamespace(React); -var STGeneralError__default = /*#__PURE__*/ _interopDefault(STGeneralError); +var NormalisedURLPath__default = /*#__PURE__*/_interopDefault(NormalisedURLPath); +var React__namespace = /*#__PURE__*/_interopNamespace(React); +var STGeneralError__default = /*#__PURE__*/_interopDefault(STGeneralError); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Imports. - */ -/* - * Component. - */ -function ArrowRightIcon(_a) { - var color = _a.color; - return jsxRuntime.jsx( - "svg", - genericComponentOverrideContext.__assign( - { width: "6", height: "8", viewBox: "0 0 6 8", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, - { - children: jsxRuntime.jsx("path", { - d: "M5.62713 3.24407C6.08759 3.64284 6.08759 4.35716 5.62713 4.75593L2.15465 7.76318C1.50701 8.32406 0.5 7.864 0.5 7.00725L0.5 0.992749C0.5 0.135997 1.50701 -0.324056 2.15465 0.23682L5.62713 3.24407Z", - fill: "".concat(color), - }), - } - ) - ); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Imports. + */ +/* + * Component. + */ +function ArrowRightIcon(_a) { + var color = _a.color; + return (jsxRuntime.jsx("svg", utils.__assign({ width: "6", height: "8", viewBox: "0 0 6 8", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, { children: jsxRuntime.jsx("path", { d: "M5.62713 3.24407C6.08759 3.64284 6.08759 4.35716 5.62713 4.75593L2.15465 7.76318C1.50701 8.32406 0.5 7.864 0.5 7.00725L0.5 0.992749C0.5 0.135997 1.50701 -0.324056 2.15465 0.23682L5.62713 3.24407Z", fill: "".concat(color) }) }))); } -var EmailVerificationSendVerifyEmail = function (props) { - var t = translationContext.useTranslation(); - var userContext = uiEntry.useUserContext(); - var _a = React.useState("READY"), - status = _a[0], - setStatus = _a[1]; - var _b = React.useState(undefined), - errorMessage = _b[0], - setErrorMessage = _b[1]; - var resendEmail = function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var response, e_1; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 5, , 6]); - return [ - 4 /*yield*/, - props.recipeImplementation.sendVerificationEmail({ - userContext: userContext, - }), - ]; - case 1: - response = _a.sent(); - if (!(response.status === "EMAIL_ALREADY_VERIFIED_ERROR")) return [3 /*break*/, 3]; - return [4 /*yield*/, props.onEmailAlreadyVerified()]; - case 2: - _a.sent(); - return [3 /*break*/, 4]; - case 3: - if (response.status === "OK") { - setStatus("EMAIL_RESENT"); - } - _a.label = 4; - case 4: - return [3 /*break*/, 6]; - case 5: - e_1 = _a.sent(); - if (STGeneralError__default.default.isThisError(e_1)) { - setErrorMessage(e_1.message); - } - setStatus("ERROR"); - return [2 /*return*/, handleSendError()]; - case 6: - return [2 /*return*/]; - } - }); - }); - }; - var logout = function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var e_2; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 2, , 3]); - return [4 /*yield*/, props.signOut()]; - case 1: - _a.sent(); - return [3 /*break*/, 3]; - case 2: - e_2 = _a.sent(); - if (STGeneralError__default.default.isThisError(e_2)) { - setErrorMessage(e_2.message); - } - setStatus("ERROR"); - return [3 /*break*/, 3]; - case 3: - return [2 /*return*/]; - } - }); - }); - }; - var sendVerificationEmail = React.useCallback( - function () { - return props.recipeImplementation.sendVerificationEmail({ - userContext: userContext, - }); - }, - [props.config, props.recipeImplementation] - ); - var checkSendResponse = React.useCallback( - function (response) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(response.status === "EMAIL_ALREADY_VERIFIED_ERROR")) return [3 /*break*/, 2]; - return [4 /*yield*/, props.onEmailAlreadyVerified()]; - case 1: - _a.sent(); - _a.label = 2; - case 2: - return [2 /*return*/]; - } - }); - }); - }, - [props.config, props.recipeImplementation, props.onEmailAlreadyVerified] - ); - var handleSendError = React.useCallback(function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().doesSessionExist({ userContext: userContext }), - ]; - case 1: - if (!(_a.sent() !== true)) return [3 /*break*/, 3]; - return [4 /*yield*/, props.redirectToAuth()]; - case 2: - _a.sent(); - _a.label = 3; - case 3: - return [2 /*return*/]; - } - }); - }); - }, []); - genericComponentOverrideContext.useOnMountAPICall(sendVerificationEmail, checkSendResponse, handleSendError); - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row" }, - { - children: [ - status === "ERROR" && - jsxRuntime.jsx(uiEntry.GeneralError, { - error: errorMessage === undefined ? "SOMETHING_WENT_WRONG_ERROR" : errorMessage, - }), - status === "EMAIL_RESENT" && - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "generalSuccess" }, - { children: t("EMAIL_VERIFICATION_RESEND_SUCCESS") } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "sendVerifyEmailIcon" }, - { children: jsxRuntime.jsx(emailLargeIcon.EmailLargeIcon, {}) } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle headerTinyTitle" }, - { children: t("EMAIL_VERIFICATION_SEND_TITLE") } - ) - ), - jsxRuntime.jsx("div", { "data-supertokens": "divider" }), - jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "primaryText sendVerifyEmailText" }, - { - children: [ - t("EMAIL_VERIFICATION_SEND_DESC_START"), - jsxRuntime.jsx("strong", { - children: t("EMAIL_VERIFICATION_SEND_DESC_STRONG"), - }), - t("EMAIL_VERIFICATION_SEND_DESC_END"), - ], - } - ) - ), - jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "buttonWithArrow", onClick: logout }, - { - children: [ - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { - "data-supertokens": - "secondaryText secondaryLinkWithRightArrow", - }, - { children: t("EMAIL_VERIFICATION_LOGOUT") } - ) - ), - jsxRuntime.jsx(ArrowRightIcon, { - color: "rgb(var(--palette-textGray))", - }), - ], - } - ) - ), - status !== "EMAIL_RESENT" && - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "link sendVerifyEmailResend", onClick: resendEmail }, - { children: t("EMAIL_VERIFICATION_RESEND_BTN") } - ) - ), - ], - } - ) - ), - } - ) - ); -}; +var EmailVerificationSendVerifyEmail = function (props) { + var t = translationContext.useTranslation(); + var userContext = uiEntry.useUserContext(); + var _a = React.useState("READY"), status = _a[0], setStatus = _a[1]; + var _b = React.useState(undefined), errorMessage = _b[0], setErrorMessage = _b[1]; + var resendEmail = function () { return utils.__awaiter(void 0, void 0, void 0, function () { + var response, e_1; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 5, , 6]); + return [4 /*yield*/, props.recipeImplementation.sendVerificationEmail({ + userContext: userContext, + })]; + case 1: + response = _a.sent(); + if (!(response.status === "EMAIL_ALREADY_VERIFIED_ERROR")) return [3 /*break*/, 3]; + return [4 /*yield*/, props.onEmailAlreadyVerified()]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + if (response.status === "OK") { + setStatus("EMAIL_RESENT"); + } + _a.label = 4; + case 4: return [3 /*break*/, 6]; + case 5: + e_1 = _a.sent(); + if (STGeneralError__default.default.isThisError(e_1)) { + setErrorMessage(e_1.message); + } + setStatus("ERROR"); + return [2 /*return*/, handleSendError()]; + case 6: return [2 /*return*/]; + } + }); + }); }; + var logout = function () { return utils.__awaiter(void 0, void 0, void 0, function () { + var e_2; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, props.signOut()]; + case 1: + _a.sent(); + return [3 /*break*/, 3]; + case 2: + e_2 = _a.sent(); + if (STGeneralError__default.default.isThisError(e_2)) { + setErrorMessage(e_2.message); + } + setStatus("ERROR"); + return [3 /*break*/, 3]; + case 3: return [2 /*return*/]; + } + }); + }); }; + var sendVerificationEmail = React.useCallback(function () { + return props.recipeImplementation.sendVerificationEmail({ + userContext: userContext, + }); + }, [props.config, props.recipeImplementation]); + var checkSendResponse = React.useCallback(function (response) { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(response.status === "EMAIL_ALREADY_VERIFIED_ERROR")) return [3 /*break*/, 2]; + return [4 /*yield*/, props.onEmailAlreadyVerified()]; + case 1: + _a.sent(); + _a.label = 2; + case 2: return [2 /*return*/]; + } + }); + }); }, [props.config, props.recipeImplementation, props.onEmailAlreadyVerified]); + var handleSendError = React.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, types.Session.getInstanceOrThrow().doesSessionExist({ userContext: userContext })]; + case 1: + if (!((_a.sent()) !== true)) return [3 /*break*/, 3]; + return [4 /*yield*/, props.redirectToAuth()]; + case 2: + _a.sent(); + _a.label = 3; + case 3: return [2 /*return*/]; + } + }); + }); }, []); + utils.useOnMountAPICall(sendVerificationEmail, checkSendResponse, handleSendError); + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "row" }, { children: [status === "ERROR" && (jsxRuntime.jsx(uiEntry.GeneralError, { error: errorMessage === undefined ? "SOMETHING_WENT_WRONG_ERROR" : errorMessage })), status === "EMAIL_RESENT" && (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "generalSuccess" }, { children: t("EMAIL_VERIFICATION_RESEND_SUCCESS") }))), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "sendVerifyEmailIcon" }, { children: jsxRuntime.jsx(emailLargeIcon.EmailLargeIcon, {}) })), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerTitle headerTinyTitle" }, { children: t("EMAIL_VERIFICATION_SEND_TITLE") })), jsxRuntime.jsx("div", { "data-supertokens": "divider" }), jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "primaryText sendVerifyEmailText" }, { children: [t("EMAIL_VERIFICATION_SEND_DESC_START"), jsxRuntime.jsx("strong", { children: t("EMAIL_VERIFICATION_SEND_DESC_STRONG") }), t("EMAIL_VERIFICATION_SEND_DESC_END")] })), jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "buttonWithArrow", onClick: logout }, { children: [jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "secondaryText secondaryLinkWithRightArrow" }, { children: t("EMAIL_VERIFICATION_LOGOUT") })), jsxRuntime.jsx(ArrowRightIcon, { color: "rgb(var(--palette-textGray))" })] })), status !== "EMAIL_RESENT" && (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "link sendVerifyEmailResend", onClick: resendEmail }, { children: t("EMAIL_VERIFICATION_RESEND_BTN") })))] })) }))); +}; var SendVerifyEmail = uiEntry.withOverride("EmailVerificationSendVerifyEmail", EmailVerificationSendVerifyEmail); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Imports. - */ -/* - * Component. - */ -function CheckedRoundIcon() { - return jsxRuntime.jsx( - "svg", - genericComponentOverrideContext.__assign( - { - xmlns: "http://www.w3.org/2000/svg", - width: "33", - height: "33", - viewBox: "0 0 33 33", - "data-supertokens": "checkedRoundIcon", - }, - { - children: jsxRuntime.jsxs( - "g", - genericComponentOverrideContext.__assign( - { fill: "rgb(var(--palette-success))", stroke: "rgb(var(--palette-success))" }, - { - children: [ - jsxRuntime.jsx("path", { - d: "M6.715 15.334a1.135 1.135 0 0 1 1.605-1.605l4.558 4.558 9.573-9.573a1.135 1.135 0 0 1 1.605 1.605L13.748 20.627a1.231 1.231 0 0 1-1.741 0z", - transform: "translate(-.5 -.5) translate(1.242 1.703)", - }), - jsxRuntime.jsx("path", { - fillRule: "evenodd", - d: "M17 1a16 16 0 1 0 16 16A16 16 0 0 0 17 1zM3.462 17A13.538 13.538 0 1 1 17 30.538 13.538 13.538 0 0 1 3.462 17z", - transform: "translate(-.5 -.5)", - }), - ], - } - ) - ), - } - ) - ); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Imports. + */ +/* + * Component. + */ +function CheckedRoundIcon() { + return (jsxRuntime.jsx("svg", utils.__assign({ xmlns: "http://www.w3.org/2000/svg", width: "33", height: "33", viewBox: "0 0 33 33", "data-supertokens": "checkedRoundIcon" }, { children: jsxRuntime.jsxs("g", utils.__assign({ fill: "rgb(var(--palette-success))", stroke: "rgb(var(--palette-success))" }, { children: [jsxRuntime.jsx("path", { d: "M6.715 15.334a1.135 1.135 0 0 1 1.605-1.605l4.558 4.558 9.573-9.573a1.135 1.135 0 0 1 1.605 1.605L13.748 20.627a1.231 1.231 0 0 1-1.741 0z", transform: "translate(-.5 -.5) translate(1.242 1.703)" }), jsxRuntime.jsx("path", { fillRule: "evenodd", d: "M17 1a16 16 0 1 0 16 16A16 16 0 0 0 17 1zM3.462 17A13.538 13.538 0 1 1 17 30.538 13.538 13.538 0 0 1 3.462 17z", transform: "translate(-.5 -.5)" })] })) }))); } -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Imports. - */ -/* - * Component. - */ -function ErrorLargeIcon() { - return jsxRuntime.jsx( - "svg", - genericComponentOverrideContext.__assign( - { - xmlns: "http://www.w3.org/2000/svg", - width: "33", - height: "30", - viewBox: "0 0 33 30", - "data-supertokens": "errorLargeIcon", - }, - { - children: jsxRuntime.jsxs("g", { - children: [ - jsxRuntime.jsx( - "g", - genericComponentOverrideContext.__assign( - { fill: "rgb(var(--palette-error))" }, - { - children: jsxRuntime.jsx("path", { - d: "M29.617 29.75H3.383c-.626 0-1.189-.321-1.507-.86-.318-.537-.328-1.186-.027-1.733l13.118-23.85c.312-.568.885-.907 1.533-.907.648 0 1.221.339 1.533.907l13.118 23.85c.301.547.291 1.196-.027 1.734s-.881.859-1.507.859z", - transform: "translate(-824.894 -352.483) translate(824.894 352.483)", - }), - } - ) - ), - jsxRuntime.jsx( - "text", - genericComponentOverrideContext.__assign( - { - fill: "#fff", - "font-family": "Arial-Bold, Arial", - "font-size": "18px", - fontWeight: "700", - transform: "translate(-824.894 -352.483) translate(838.997 377.437)", - }, - { - children: jsxRuntime.jsx( - "tspan", - genericComponentOverrideContext.__assign({ x: "0", y: "0" }, { children: "!" }) - ), - } - ) - ), - ], - }), - } - ) - ); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Imports. + */ +/* + * Component. + */ +function ErrorLargeIcon() { + return (jsxRuntime.jsx("svg", utils.__assign({ xmlns: "http://www.w3.org/2000/svg", width: "33", height: "30", viewBox: "0 0 33 30", "data-supertokens": "errorLargeIcon" }, { children: jsxRuntime.jsxs("g", { children: [jsxRuntime.jsx("g", utils.__assign({ fill: "rgb(var(--palette-error))" }, { children: jsxRuntime.jsx("path", { d: "M29.617 29.75H3.383c-.626 0-1.189-.321-1.507-.86-.318-.537-.328-1.186-.027-1.733l13.118-23.85c.312-.568.885-.907 1.533-.907.648 0 1.221.339 1.533.907l13.118 23.85c.301.547.291 1.196-.027 1.734s-.881.859-1.507.859z", transform: "translate(-824.894 -352.483) translate(824.894 352.483)" }) })), jsxRuntime.jsx("text", utils.__assign({ fill: "#fff", "font-family": "Arial-Bold, Arial", "font-size": "18px", fontWeight: "700", transform: "translate(-824.894 -352.483) translate(838.997 377.437)" }, { children: jsxRuntime.jsx("tspan", utils.__assign({ x: "0", y: "0" }, { children: "!" })) }))] }) }))); } -var EmailVerificationVerifyEmailLinkClicked = function (props) { - var t = translationContext.useTranslation(); - var sessionContext = uiEntry.useSessionContext(); - var userContext = uiEntry.useUserContext(); - var _a = React.useState("LOADING"), - status = _a[0], - setStatus = _a[1]; - var _b = React.useState(undefined), - errorMessage = _b[0], - setErrorMessage = _b[1]; - var _c = React.useState(false), - verifyLoading = _c[0], - setVerifyLoading = _c[1]; - var verifyEmailOnMount = React.useCallback( - function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - if (sessionContext.loading === true) { - // This callback should only be called if the session is already loaded - throw new Error("Should never come here"); - } - // If there is no active session we know that the verification was started elsewhere, since it requires a session - // otherwise we assume it's the same session. The main purpose of this is to prevent mail scanners - // from accidentally validating an email address - if (!sessionContext.doesSessionExist) { - return [2 /*return*/, "INTERACTION_REQUIRED"]; - } - return [ - 2 /*return*/, - props.recipeImplementation.verifyEmail({ - userContext: userContext, - }), - ]; - }); - }); - }, - [props.recipeImplementation, sessionContext] - ); - var handleVerifyResp = React.useCallback( - function (response) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - if (response === "INTERACTION_REQUIRED") { - setStatus("INTERACTION_REQUIRED"); - } else if (response.status === "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR") { - setStatus("INVALID"); - } else { - setStatus("SUCCESSFUL"); - } - return [2 /*return*/]; - }); - }); - }, - [setStatus] - ); - var handleError = React.useCallback( - function (err) { - if (STGeneralError__default.default.isThisError(err)) { - setErrorMessage(err.message); - } - setStatus("GENERAL_ERROR"); - }, - [setStatus, setErrorMessage] - ); - genericComponentOverrideContext.useOnMountAPICall( - verifyEmailOnMount, - handleVerifyResp, - handleError, - sessionContext.loading === false - ); - var onTokenInvalidRedirect = props.onTokenInvalidRedirect, - onSuccess = props.onSuccess; - if (status === "LOADING") { - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container" }, - { - children: jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row" }, - { - children: jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "spinner" }, - { children: jsxRuntime.jsx(uiEntry.SpinnerIcon, {}) } - ) - ), - } - ) - ), - } - ) - ); - } - if (status === "INTERACTION_REQUIRED") { - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row noFormRow" }, - { - children: [ - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle" }, - { children: t("EMAIL_VERIFICATION_LINK_CLICKED_HEADER") } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerSubtitle secondaryText" }, - { children: t("EMAIL_VERIFICATION_LINK_CLICKED_DESC") } - ) - ), - jsxRuntime.jsx(button.Button, { - isLoading: verifyLoading, - onClick: function () { - return genericComponentOverrideContext.__awaiter( - void 0, - void 0, - void 0, - function () { - var resp, err_1; - return genericComponentOverrideContext.__generator( - this, - function (_a) { - switch (_a.label) { - case 0: - setVerifyLoading(true); - _a.label = 1; - case 1: - _a.trys.push([1, 4, , 5]); - return [ - 4 /*yield*/, - props.recipeImplementation.verifyEmail({ - userContext: userContext, - }), - ]; - case 2: - resp = _a.sent(); - return [4 /*yield*/, handleVerifyResp(resp)]; - case 3: - _a.sent(); - return [3 /*break*/, 5]; - case 4: - err_1 = _a.sent(); - void handleError(err_1); - return [3 /*break*/, 5]; - case 5: - return [2 /*return*/]; - } - } - ); - } - ); - }, - type: "button", - label: "EMAIL_VERIFICATION_LINK_CLICKED_CONTINUE_BUTTON", - }), - ], - } - ) - ), - } - ) - ); - } - if (status === "SUCCESSFUL") { - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row noFormRow" }, - { - children: [ - jsxRuntime.jsx(CheckedRoundIcon, {}), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle headerTinyTitle" }, - { children: t("EMAIL_VERIFICATION_SUCCESS") } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "emailVerificationButtonWrapper" }, - { - children: jsxRuntime.jsx(button.Button, { - isLoading: false, - onClick: onSuccess, - type: "button", - label: "EMAIL_VERIFICATION_CONTINUE_BTN", - }), - } - ) - ), - ], - } - ) - ), - } - ) - ); - } - if (status === "INVALID") { - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row noFormRow" }, - { - children: [ - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle headerTinyTitle" }, - { children: t("EMAIL_VERIFICATION_EXPIRED") } - ) - ), - jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { - onClick: onTokenInvalidRedirect, - "data-supertokens": "secondaryText secondaryLinkWithArrow", - }, - { - children: [ - t("EMAIL_VERIFICATION_CONTINUE_LINK"), - " ", - jsxRuntime.jsx(ArrowRightIcon, { - color: "rgb(var(--palette-textPrimary))", - }), - ], - } - ) - ), - ], - } - ) - ), - } - ) - ); - } - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row noFormRow" }, - { - children: [ - jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle error" }, - { - children: [ - jsxRuntime.jsx(ErrorLargeIcon, {}), - t("EMAIL_VERIFICATION_ERROR_TITLE"), - ], - } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "primaryText" }, - { - children: t( - errorMessage === undefined - ? "EMAIL_VERIFICATION_ERROR_DESC" - : errorMessage - ), - } - ) - ), - ], - } - ) - ), - } - ) - ); -}; -var VerifyEmailLinkClicked = uiEntry.withOverride( - "EmailVerificationVerifyEmailLinkClicked", - EmailVerificationVerifyEmailLinkClicked -); +var EmailVerificationVerifyEmailLinkClicked = function (props) { + var t = translationContext.useTranslation(); + var sessionContext = uiEntry.useSessionContext(); + var userContext = uiEntry.useUserContext(); + var _a = React.useState("LOADING"), status = _a[0], setStatus = _a[1]; + var _b = React.useState(undefined), errorMessage = _b[0], setErrorMessage = _b[1]; + var _c = React.useState(false), verifyLoading = _c[0], setVerifyLoading = _c[1]; + var verifyEmailOnMount = React.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + if (sessionContext.loading === true) { + // This callback should only be called if the session is already loaded + throw new Error("Should never come here"); + } + // If there is no active session we know that the verification was started elsewhere, since it requires a session + // otherwise we assume it's the same session. The main purpose of this is to prevent mail scanners + // from accidentally validating an email address + if (!sessionContext.doesSessionExist) { + return [2 /*return*/, "INTERACTION_REQUIRED"]; + } + return [2 /*return*/, props.recipeImplementation.verifyEmail({ + userContext: userContext, + })]; + }); + }); }, [props.recipeImplementation, sessionContext]); + var handleVerifyResp = React.useCallback(function (response) { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + if (response === "INTERACTION_REQUIRED") { + setStatus("INTERACTION_REQUIRED"); + } + else if (response.status === "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR") { + setStatus("INVALID"); + } + else { + setStatus("SUCCESSFUL"); + } + return [2 /*return*/]; + }); + }); }, [setStatus]); + var handleError = React.useCallback(function (err) { + if (STGeneralError__default.default.isThisError(err)) { + setErrorMessage(err.message); + } + setStatus("GENERAL_ERROR"); + }, [setStatus, setErrorMessage]); + utils.useOnMountAPICall(verifyEmailOnMount, handleVerifyResp, handleError, sessionContext.loading === false); + var onTokenInvalidRedirect = props.onTokenInvalidRedirect, onSuccess = props.onSuccess; + if (status === "LOADING") { + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container" }, { children: jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "row" }, { children: jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "spinner" }, { children: jsxRuntime.jsx(uiEntry.SpinnerIcon, {}) })) })) }))); + } + if (status === "INTERACTION_REQUIRED") { + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "row noFormRow" }, { children: [jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerTitle" }, { children: t("EMAIL_VERIFICATION_LINK_CLICKED_HEADER") })), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerSubtitle secondaryText" }, { children: t("EMAIL_VERIFICATION_LINK_CLICKED_DESC") })), jsxRuntime.jsx(button.Button, { isLoading: verifyLoading, onClick: function () { return utils.__awaiter(void 0, void 0, void 0, function () { + var resp, err_1; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + setVerifyLoading(true); + _a.label = 1; + case 1: + _a.trys.push([1, 4, , 5]); + return [4 /*yield*/, props.recipeImplementation.verifyEmail({ + userContext: userContext, + })]; + case 2: + resp = _a.sent(); + return [4 /*yield*/, handleVerifyResp(resp)]; + case 3: + _a.sent(); + return [3 /*break*/, 5]; + case 4: + err_1 = _a.sent(); + void handleError(err_1); + return [3 /*break*/, 5]; + case 5: return [2 /*return*/]; + } + }); + }); }, type: "button", label: "EMAIL_VERIFICATION_LINK_CLICKED_CONTINUE_BUTTON" })] })) }))); + } + if (status === "SUCCESSFUL") { + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "row noFormRow" }, { children: [jsxRuntime.jsx(CheckedRoundIcon, {}), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerTitle headerTinyTitle" }, { children: t("EMAIL_VERIFICATION_SUCCESS") })), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "emailVerificationButtonWrapper" }, { children: jsxRuntime.jsx(button.Button, { isLoading: false, onClick: onSuccess, type: "button", label: "EMAIL_VERIFICATION_CONTINUE_BTN" }) }))] })) }))); + } + if (status === "INVALID") { + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "row noFormRow" }, { children: [jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerTitle headerTinyTitle" }, { children: t("EMAIL_VERIFICATION_EXPIRED") })), jsxRuntime.jsxs("div", utils.__assign({ onClick: onTokenInvalidRedirect, "data-supertokens": "secondaryText secondaryLinkWithArrow" }, { children: [t("EMAIL_VERIFICATION_CONTINUE_LINK"), " ", jsxRuntime.jsx(ArrowRightIcon, { color: "rgb(var(--palette-textPrimary))" })] }))] })) }))); + } + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "row noFormRow" }, { children: [jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "headerTitle error" }, { children: [jsxRuntime.jsx(ErrorLargeIcon, {}), t("EMAIL_VERIFICATION_ERROR_TITLE")] })), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "primaryText" }, { children: t(errorMessage === undefined ? "EMAIL_VERIFICATION_ERROR_DESC" : errorMessage) }))] })) }))); +}; +var VerifyEmailLinkClicked = uiEntry.withOverride("EmailVerificationVerifyEmailLinkClicked", EmailVerificationVerifyEmailLinkClicked); -function EmailVerificationTheme(props) { - var sessionContext = session.useSessionContext(); - // If we have a token, return VerifyEmailLinkClicked. - if (props.verifyEmailLinkClickedScreen !== undefined) { - return jsxRuntime.jsx( - VerifyEmailLinkClicked, - genericComponentOverrideContext.__assign({}, props.verifyEmailLinkClickedScreen) - ); - } - // If we have an active session, we want to send the verification email - if (sessionContext.loading === false && sessionContext.doesSessionExist === true) { - return jsxRuntime.jsx( - SendVerifyEmail, - genericComponentOverrideContext.__assign({}, props.sendVerifyEmailScreen) - ); - } - // Otherwise, return an empty screen, waiting for the feature component to redirection to complete. - return jsxRuntime.jsx(jsxRuntime.Fragment, {}); -} -function EmailVerificationThemeWrapper(props) { - var rootStyle = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().rootStyle; - return jsxRuntime.jsx( - uiEntry.UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - translations.ThemeBase, - genericComponentOverrideContext.__assign( - { - userStyles: [ - rootStyle, - props.config.recipeRootStyle, - props.verifyEmailLinkClickedScreen === undefined - ? props.config.sendVerifyEmailScreen.style - : props.config.verifyEmailLinkClickedScreen.style, - ], - }, - { - children: jsxRuntime.jsx( - EmailVerificationTheme, - genericComponentOverrideContext.__assign({}, props) - ), - } - ) - ), - } - ) - ); +function EmailVerificationTheme(props) { + var sessionContext = session.useSessionContext(); + // If we have a token, return VerifyEmailLinkClicked. + if (props.verifyEmailLinkClickedScreen !== undefined) { + return jsxRuntime.jsx(VerifyEmailLinkClicked, utils.__assign({}, props.verifyEmailLinkClickedScreen)); + } + // If we have an active session, we want to send the verification email + if (sessionContext.loading === false && sessionContext.doesSessionExist === true) { + return jsxRuntime.jsx(SendVerifyEmail, utils.__assign({}, props.sendVerifyEmailScreen)); + } + // Otherwise, return an empty screen, waiting for the feature component to redirection to complete. + return jsxRuntime.jsx(jsxRuntime.Fragment, {}); +} +function EmailVerificationThemeWrapper(props) { + var rootStyle = superTokens.SuperTokens.getInstanceOrThrow().rootStyle; + return (jsxRuntime.jsx(uiEntry.UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(translations.ThemeBase, utils.__assign({ userStyles: [ + rootStyle, + props.config.recipeRootStyle, + props.verifyEmailLinkClickedScreen === undefined + ? props.config.sendVerifyEmailScreen.style + : props.config.verifyEmailLinkClickedScreen.style, + ] }, { children: jsxRuntime.jsx(EmailVerificationTheme, utils.__assign({}, props)) })) }))); } -var EmailVerification$1 = function (props) { - var _a; - var sessionContext = React.useContext(uiEntry.SessionContext); - var _b = React.useState("LOADING"), - status = _b[0], - setStatus = _b[1]; - var rethrowInRender = genericComponentOverrideContext.useRethrowInRender(); - var recipeComponentOverrides = props.useComponentOverrides(); - var userContext = uiEntry.useUserContext(); - if (props.userContext !== undefined) { - userContext = props.userContext; - } - var redirectToAuthWithHistory = React.useCallback( - function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - uiEntry.redirectToAuth({ redirectBack: false, navigate: props.navigate }), - ]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }, - [props.navigate] - ); - var modifiedRecipeImplementation = React.useMemo( - function () { - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, props.recipe.webJSRecipe), - { - sendVerificationEmail: function (input) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, props.recipe.webJSRecipe.sendVerificationEmail(input)]; - case 1: - response = _a.sent(); - genericComponentOverrideContext.clearQueryParams(["token"]); - return [2 /*return*/, response]; - } - }); - }); - }, - } - ); - }, - [props.recipe] - ); - var onSuccess = React.useCallback( - function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - types.Session.getInstanceOrThrow() - .validateGlobalClaimsAndHandleSuccessRedirection( - undefined, - props.recipe.recipeID, - undefined, - userContext, - props.navigate - ) - .catch(rethrowInRender), - ]; - }); - }); - }, - [props.recipe, props.navigate, userContext] - ); - var fetchIsEmailVerified = React.useCallback( - function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var token; - var _a; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (sessionContext.loading === true) { - // This callback should only be called if the session is already loaded - throw new Error("Should never come here"); - } - token = - (_a = genericComponentOverrideContext.getQueryParams("token")) !== null && _a !== void 0 - ? _a - : undefined; - if (!(token === undefined)) return [3 /*break*/, 4]; - if (!!sessionContext.doesSessionExist) return [3 /*break*/, 2]; - return [4 /*yield*/, redirectToAuthWithHistory()]; - case 1: - _b.sent(); - return [3 /*break*/, 4]; - case 2: - return [ - 4 /*yield*/, - props.recipe.webJSRecipe.isEmailVerified({ userContext: userContext }), - ]; - case 3: - // we check if the email is already verified, and if it is, then we redirect the user - return [2 /*return*/, _b.sent().isVerified]; - case 4: - return [2 /*return*/, false]; - } - }); - }); - }, - [props.recipe, sessionContext, redirectToAuthWithHistory] - ); - var checkIsEmailVerified = React.useCallback( - function (isVerified) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - if (isVerified) { - return [2 /*return*/, onSuccess()]; - } - setStatus("READY"); - return [2 /*return*/]; - }); - }); - }, - [props.recipe, setStatus, onSuccess] - ); - var handleError = React.useCallback( - function (err) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().doesSessionExist({ userContext: userContext }), - ]; - case 1: - if (!_a.sent()) return [3 /*break*/, 2]; - throw err; - case 2: - return [4 /*yield*/, redirectToAuthWithHistory()]; - case 3: - _a.sent(); - _a.label = 4; - case 4: - return [2 /*return*/]; - } - }); - }); - }, - [redirectToAuthWithHistory] - ); - genericComponentOverrideContext.useOnMountAPICall( - fetchIsEmailVerified, - checkIsEmailVerified, - handleError, - sessionContext.loading === false - ); - var signOut = React.useCallback( - function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var session; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - session = types.Session.getInstanceOrThrow(); - return [4 /*yield*/, session.signOut({ userContext: userContext })]; - case 1: - _a.sent(); - return [2 /*return*/, redirectToAuthWithHistory()]; - } - }); - }); - }, - [redirectToAuthWithHistory, userContext] - ); - if (status === "LOADING") { - return jsxRuntime.jsx(React.Fragment, {}); - } - var sendVerifyEmailScreenFeature = props.recipe.config.sendVerifyEmailScreen; - var sendVerifyEmailScreen = { - styleFromInit: sendVerifyEmailScreenFeature.style, - recipeImplementation: modifiedRecipeImplementation, - config: props.recipe.config, - signOut: signOut, - onEmailAlreadyVerified: onSuccess, - redirectToAuth: redirectToAuthWithHistory, - }; - var verifyEmailLinkClickedScreenFeature = props.recipe.config.verifyEmailLinkClickedScreen; - var token = - (_a = genericComponentOverrideContext.getQueryParams("token")) !== null && _a !== void 0 ? _a : undefined; - var verifyEmailLinkClickedScreen = - token === undefined - ? undefined - : { - styleFromInit: verifyEmailLinkClickedScreenFeature.style, - onTokenInvalidRedirect: redirectToAuthWithHistory, - onSuccess: onSuccess, - recipeImplementation: modifiedRecipeImplementation, - config: props.recipe.config, - token: token, - }; - var childProps = { - config: props.recipe.config, - sendVerifyEmailScreen: sendVerifyEmailScreen, - verifyEmailLinkClickedScreen: verifyEmailLinkClickedScreen, - hasToken: token !== undefined, - }; - return jsxRuntime.jsx( - uiEntry.ComponentOverrideContext.Provider, - genericComponentOverrideContext.__assign( - { value: recipeComponentOverrides }, - { - children: jsxRuntime.jsx( - uiEntry.FeatureWrapper, - genericComponentOverrideContext.__assign( - { - useShadowDom: genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().useShadowDom, - defaultStore: translations.defaultTranslationsEmailVerification, - }, - { - children: jsxRuntime.jsxs(React.Fragment, { - children: [ - props.children === undefined && - jsxRuntime.jsx( - EmailVerificationThemeWrapper, - genericComponentOverrideContext.__assign({}, childProps) - ), - props.children && - React__namespace.Children.map(props.children, function (child) { - if (React__namespace.isValidElement(child)) { - return React__namespace.cloneElement(child, childProps); - } - return child; - }), - ], - }), - } - ) - ), - } - ) - ); +var EmailVerification$1 = function (props) { + var _a; + var sessionContext = React.useContext(uiEntry.SessionContext); + var _b = React.useState("LOADING"), status = _b[0], setStatus = _b[1]; + var rethrowInRender = utils.useRethrowInRender(); + var recipeComponentOverrides = props.useComponentOverrides(); + var userContext = uiEntry.useUserContext(); + if (props.userContext !== undefined) { + userContext = props.userContext; + } + var redirectToAuthWithHistory = React.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, uiEntry.redirectToAuth({ redirectBack: false, navigate: props.navigate })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }, [props.navigate]); + var modifiedRecipeImplementation = React.useMemo(function () { return (utils.__assign(utils.__assign({}, props.recipe.webJSRecipe), { sendVerificationEmail: function (input) { return utils.__awaiter(void 0, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, props.recipe.webJSRecipe.sendVerificationEmail(input)]; + case 1: + response = _a.sent(); + utils.clearQueryParams(["token"]); + return [2 /*return*/, response]; + } + }); + }); } })); }, [props.recipe]); + var onSuccess = React.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, types.Session.getInstanceOrThrow() + .validateGlobalClaimsAndHandleSuccessRedirection(undefined, props.recipe.recipeID, undefined, userContext, props.navigate) + .catch(rethrowInRender)]; + }); + }); }, [props.recipe, props.navigate, userContext]); + var fetchIsEmailVerified = React.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + var token; + var _a; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (sessionContext.loading === true) { + // This callback should only be called if the session is already loaded + throw new Error("Should never come here"); + } + token = (_a = utils.getQueryParams("token")) !== null && _a !== void 0 ? _a : undefined; + if (!(token === undefined)) return [3 /*break*/, 4]; + if (!!sessionContext.doesSessionExist) return [3 /*break*/, 2]; + return [4 /*yield*/, redirectToAuthWithHistory()]; + case 1: + _b.sent(); + return [3 /*break*/, 4]; + case 2: return [4 /*yield*/, props.recipe.webJSRecipe.isEmailVerified({ userContext: userContext })]; + case 3: + // we check if the email is already verified, and if it is, then we redirect the user + return [2 /*return*/, (_b.sent()).isVerified]; + case 4: return [2 /*return*/, false]; + } + }); + }); }, [props.recipe, sessionContext, redirectToAuthWithHistory]); + var checkIsEmailVerified = React.useCallback(function (isVerified) { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + if (isVerified) { + return [2 /*return*/, onSuccess()]; + } + setStatus("READY"); + return [2 /*return*/]; + }); + }); }, [props.recipe, setStatus, onSuccess]); + var handleError = React.useCallback(function (err) { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, types.Session.getInstanceOrThrow().doesSessionExist({ userContext: userContext })]; + case 1: + if (!_a.sent()) return [3 /*break*/, 2]; + throw err; + case 2: return [4 /*yield*/, redirectToAuthWithHistory()]; + case 3: + _a.sent(); + _a.label = 4; + case 4: return [2 /*return*/]; + } + }); + }); }, [redirectToAuthWithHistory]); + utils.useOnMountAPICall(fetchIsEmailVerified, checkIsEmailVerified, handleError, sessionContext.loading === false); + var signOut = React.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + var session; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + session = types.Session.getInstanceOrThrow(); + return [4 /*yield*/, session.signOut({ userContext: userContext })]; + case 1: + _a.sent(); + return [2 /*return*/, redirectToAuthWithHistory()]; + } + }); + }); }, [redirectToAuthWithHistory, userContext]); + if (status === "LOADING") { + return jsxRuntime.jsx(React.Fragment, {}); + } + var sendVerifyEmailScreenFeature = props.recipe.config.sendVerifyEmailScreen; + var sendVerifyEmailScreen = { + styleFromInit: sendVerifyEmailScreenFeature.style, + recipeImplementation: modifiedRecipeImplementation, + config: props.recipe.config, + signOut: signOut, + onEmailAlreadyVerified: onSuccess, + redirectToAuth: redirectToAuthWithHistory, + }; + var verifyEmailLinkClickedScreenFeature = props.recipe.config.verifyEmailLinkClickedScreen; + var token = (_a = utils.getQueryParams("token")) !== null && _a !== void 0 ? _a : undefined; + var verifyEmailLinkClickedScreen = token === undefined + ? undefined + : { + styleFromInit: verifyEmailLinkClickedScreenFeature.style, + onTokenInvalidRedirect: redirectToAuthWithHistory, + onSuccess: onSuccess, + recipeImplementation: modifiedRecipeImplementation, + config: props.recipe.config, + token: token, + }; + var childProps = { + config: props.recipe.config, + sendVerifyEmailScreen: sendVerifyEmailScreen, + verifyEmailLinkClickedScreen: verifyEmailLinkClickedScreen, + hasToken: token !== undefined, + }; + return (jsxRuntime.jsx(uiEntry.ComponentOverrideContext.Provider, utils.__assign({ value: recipeComponentOverrides }, { children: jsxRuntime.jsx(uiEntry.FeatureWrapper, utils.__assign({ useShadowDom: superTokens.SuperTokens.getInstanceOrThrow().useShadowDom, defaultStore: translations.defaultTranslationsEmailVerification }, { children: jsxRuntime.jsxs(React.Fragment, { children: [props.children === undefined && jsxRuntime.jsx(EmailVerificationThemeWrapper, utils.__assign({}, childProps)), props.children && + React__namespace.Children.map(props.children, function (child) { + if (React__namespace.isValidElement(child)) { + return React__namespace.cloneElement(child, childProps); + } + return child; + })] }) })) }))); }; -var EmailVerificationPreBuiltUI = /** @class */ (function (_super) { - genericComponentOverrideContext.__extends(EmailVerificationPreBuiltUI, _super); - function EmailVerificationPreBuiltUI(recipeInstance) { - var _this = _super.call(this) || this; - _this.recipeInstance = recipeInstance; - _this.languageTranslations = translations.defaultTranslationsEmailVerification; - // Instance methods - _this.getFeatures = function (useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = recipe.useContext; - } - var features = {}; - if (_this.recipeInstance.config.disableDefaultUI !== true) { - var normalisedFullPath = _this.recipeInstance.config.appInfo.websiteBasePath.appendPath( - new NormalisedURLPath__default.default(recipe.DEFAULT_VERIFY_EMAIL_PATH) - ); - features[normalisedFullPath.getAsStringDangerous()] = { - matches: genericComponentOverrideContext.matchRecipeIdUsingQueryParams( - _this.recipeInstance.config.recipeId - ), - component: function (props) { - return _this.getFeatureComponent("emailverification", props, useComponentOverrides); - }, - recipeID: recipe.EmailVerification.RECIPE_ID, - }; - } - return features; - }; - _this.getFeatureComponent = function ( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _, - props, - useComponentOverrides - ) { - if (useComponentOverrides === void 0) { - useComponentOverrides = recipe.useContext; - } - return jsxRuntime.jsx( - uiEntry.UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - session.SessionAuth, - genericComponentOverrideContext.__assign( - { - requireAuth: false, - overrideGlobalClaimValidators: function () { - return []; - }, - }, - { - children: jsxRuntime.jsx(uiEntry.UserContextContext.Consumer, { - children: function (value) { - return jsxRuntime.jsx( - EmailVerification$1, - genericComponentOverrideContext.__assign( - { - recipe: _this.recipeInstance, - useComponentOverrides: useComponentOverrides, - }, - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, props), - { - // We do this to make sure it does not add another provider - userContext: value, - } - ) - ) - ); - }, - }), - } - ) - ), - } - ) - ); - }; - return _this; - } - // Static methods - EmailVerificationPreBuiltUI.getInstanceOrInitAndGetInstance = function () { - if (EmailVerificationPreBuiltUI.instance === undefined) { - var recipeInstance = recipe.EmailVerification.getInstanceOrThrow(); - EmailVerificationPreBuiltUI.instance = new EmailVerificationPreBuiltUI(recipeInstance); - } - return EmailVerificationPreBuiltUI.instance; - }; - EmailVerificationPreBuiltUI.getFeatures = function (useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = recipe.useContext; - } - return EmailVerificationPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatures(useComponentOverrides); - }; - EmailVerificationPreBuiltUI.getFeatureComponent = function (componentName, props, useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = recipe.useContext; - } - return EmailVerificationPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent( - componentName, - props, - useComponentOverrides - ); - }; - EmailVerificationPreBuiltUI.prototype.getAuthComponents = function () { - return []; - }; - // For tests - EmailVerificationPreBuiltUI.reset = function () { - if (!genericComponentOverrideContext.isTest()) { - return; - } - EmailVerificationPreBuiltUI.instance = undefined; - return; - }; - EmailVerificationPreBuiltUI.EmailVerification = function (props) { - return EmailVerificationPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent( - "emailverification", - props - ); - }; - EmailVerificationPreBuiltUI.EmailVerificationTheme = EmailVerificationTheme; - return EmailVerificationPreBuiltUI; -})(uiEntry.RecipeRouter); +var EmailVerificationPreBuiltUI = /** @class */ (function (_super) { + utils.__extends(EmailVerificationPreBuiltUI, _super); + function EmailVerificationPreBuiltUI(recipeInstance) { + var _this = _super.call(this) || this; + _this.recipeInstance = recipeInstance; + _this.languageTranslations = translations.defaultTranslationsEmailVerification; + // Instance methods + _this.getFeatures = function (useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = recipe.useContext; } + var features = {}; + if (_this.recipeInstance.config.disableDefaultUI !== true) { + var normalisedFullPath = _this.recipeInstance.config.appInfo.websiteBasePath.appendPath(new NormalisedURLPath__default.default(recipe.DEFAULT_VERIFY_EMAIL_PATH)); + features[normalisedFullPath.getAsStringDangerous()] = { + matches: utils.matchRecipeIdUsingQueryParams(_this.recipeInstance.config.recipeId), + component: function (props) { return _this.getFeatureComponent("emailverification", props, useComponentOverrides); }, + recipeID: recipe.EmailVerification.RECIPE_ID, + }; + } + return features; + }; + _this.getFeatureComponent = function ( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _, props, useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = recipe.useContext; } + return (jsxRuntime.jsx(uiEntry.UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(session.SessionAuth, utils.__assign({ requireAuth: false, overrideGlobalClaimValidators: function () { return []; } }, { children: jsxRuntime.jsx(uiEntry.UserContextContext.Consumer, { children: function (value) { + return (jsxRuntime.jsx(EmailVerification$1, utils.__assign({ recipe: _this.recipeInstance, useComponentOverrides: useComponentOverrides }, utils.__assign(utils.__assign({}, props), { + // We do this to make sure it does not add another provider + userContext: value })))); + } }) })) }))); + }; + return _this; + } + // Static methods + EmailVerificationPreBuiltUI.getInstanceOrInitAndGetInstance = function () { + if (EmailVerificationPreBuiltUI.instance === undefined) { + var recipeInstance = recipe.EmailVerification.getInstanceOrThrow(); + EmailVerificationPreBuiltUI.instance = new EmailVerificationPreBuiltUI(recipeInstance); + } + return EmailVerificationPreBuiltUI.instance; + }; + EmailVerificationPreBuiltUI.getFeatures = function (useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = recipe.useContext; } + return EmailVerificationPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatures(useComponentOverrides); + }; + EmailVerificationPreBuiltUI.getFeatureComponent = function (componentName, props, useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = recipe.useContext; } + return EmailVerificationPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent(componentName, props, useComponentOverrides); + }; + EmailVerificationPreBuiltUI.prototype.getAuthComponents = function () { + return []; + }; + // For tests + EmailVerificationPreBuiltUI.reset = function () { + if (!utils.isTest()) { + return; + } + EmailVerificationPreBuiltUI.instance = undefined; + return; + }; + EmailVerificationPreBuiltUI.EmailVerification = function (props) { + return EmailVerificationPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent("emailverification", props); + }; + EmailVerificationPreBuiltUI.EmailVerificationTheme = EmailVerificationTheme; + return EmailVerificationPreBuiltUI; +}(uiEntry.RecipeRouter)); var EmailVerification = EmailVerificationPreBuiltUI.EmailVerification; exports.EmailVerification = EmailVerification; diff --git a/lib/build/genericComponentOverrideContext.js b/lib/build/genericComponentOverrideContext.js index 5f2ecdb46..6eeec5f12 100644 --- a/lib/build/genericComponentOverrideContext.js +++ b/lib/build/genericComponentOverrideContext.js @@ -1,1557 +1,24 @@ -"use strict"; - -var SuperTokensWebJS = require("supertokens-web-js"); -var cookieHandler = require("supertokens-web-js/utils/cookieHandler"); -var postSuperTokensInitCallbacks = require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -var windowHandler = require("supertokens-web-js/utils/windowHandler"); -var MultitenancyWebJS = require("supertokens-web-js/recipe/multitenancy"); -var utils = require("supertokens-web-js/utils"); -var React = require("react"); -var STGeneralError = require("supertokens-web-js/lib/build/error"); -var NormalisedURLDomain = require("supertokens-web-js/utils/normalisedURLDomain"); -var NormalisedURLPath = require("supertokens-web-js/utils/normalisedURLPath"); -var jsxRuntime = require("react/jsx-runtime"); - -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} - -var SuperTokensWebJS__default = /*#__PURE__*/ _interopDefault(SuperTokensWebJS); -var MultitenancyWebJS__default = /*#__PURE__*/ _interopDefault(MultitenancyWebJS); -var React__default = /*#__PURE__*/ _interopDefault(React); -var STGeneralError__default = /*#__PURE__*/ _interopDefault(STGeneralError); -var NormalisedURLDomain__default = /*#__PURE__*/ _interopDefault(NormalisedURLDomain); -var NormalisedURLPath__default = /*#__PURE__*/ _interopDefault(NormalisedURLPath); - -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ - -var extendStatics = function (d, b) { - extendStatics = - Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && - function (d, b) { - d.__proto__ = b; - }) || - function (d, b) { - for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; - }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new __()); -} - -exports.__assign = function () { - exports.__assign = - Object.assign || - function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return exports.__assign.apply(this, arguments); -}; - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; - } - return t; -} - -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { - label: 0, - sent: function () { - if (t[0] & 1) throw t[1]; - return t[1]; - }, - trys: [], - ops: [], - }, - f, - y, - t, - g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); - return ( - (g.next = verb(0)), - (g["throw"] = verb(1)), - (g["return"] = verb(2)), - typeof Symbol === "function" && - (g[Symbol.iterator] = function () { - return this; - }), - g - ); - function verb(n) { - return function (v) { - return step([n, v]); - }; - } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while ((g && ((g = 0), op[0] && (_ = 0)), _)) - try { - if ( - ((f = 1), - y && - (t = - op[0] & 2 - ? y["return"] - : op[0] - ? y["throw"] || ((t = y["return"]) && t.call(y), 0) - : y.next) && - !(t = t.call(y, op[1])).done) - ) - return t; - if (((y = 0), t)) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) - for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} - -typeof SuppressedError === "function" - ? SuppressedError - : function (error, suppressed, message) { - var e = new Error(message); - return (e.name = "SuppressedError"), (e.error = error), (e.suppressed = suppressed), e; - }; - -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Consts. - */ -var RECIPE_ID_QUERY_PARAM = "rid"; -var TENANT_ID_QUERY_PARAM = "tenantId"; -var DEFAULT_API_BASE_PATH = "/auth"; -var DEFAULT_WEBSITE_BASE_PATH = "/auth"; -var ST_ROOT_ID = "supertokens-root"; -var SSR_ERROR = - "\nIf you are trying to use this method doing server-side-rendering, please make sure you move this method inside a componentDidMount method or useEffect hook."; - -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var package_version = "0.49.1"; - -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var SUPERTOKENS_DEBUG_NAMESPACE = "com.supertokens.auth-react"; -var __debugLogsEnabled = false; -function enableLogging() { - __debugLogsEnabled = true; -} -function logDebugMessage(message) { - if (__debugLogsEnabled) { - // eslint-disable-next-line no-console - console.log( - "" - .concat(SUPERTOKENS_DEBUG_NAMESPACE, ' {t: "') - .concat(new Date().toISOString(), '", message: "') - .concat(message, '", supertokens-auth-react-ver: "') - .concat(package_version, '"}') - ); - } -} - -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * getRecipeIdFromPath - * Input: - * Output: The "rid" query param if present, null otherwise. - */ -function getRecipeIdFromSearch(search) { - var urlParams = new URLSearchParams(search); - return urlParams.get(RECIPE_ID_QUERY_PARAM); -} -function clearQueryParams(paramNames) { - var newURL = new URL(windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getHref()); - for (var _i = 0, paramNames_1 = paramNames; _i < paramNames_1.length; _i++) { - var param = paramNames_1[_i]; - newURL.searchParams.delete(param); - } - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.history.replaceState( - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.history.getState(), - "", - newURL.toString() - ); -} -function updateQueryParam(name, value) { - var newURL = new URL(windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getHref()); - newURL.searchParams.set(name, value); - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.history.replaceState( - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.history.getState(), - "", - newURL.toString() - ); -} -function clearErrorQueryParam() { - clearQueryParams(["error", "message"]); -} -function getQueryParams(param) { - var urlParams = new URLSearchParams( - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getSearch() - ); - return urlParams.get(param); -} -function getURLHash() { - // By default it is returined with the "#" at the beginning, we cut that off here. - return windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getHash().substr(1); -} -function getRedirectToPathFromURL() { - var redirectToPath = getQueryParams("redirectToPath"); - if (redirectToPath === null) { - return undefined; - } else { - try { - var url = void 0; - try { - url = new URL(redirectToPath); - } catch (error) { - var fakeDomain = redirectToPath.startsWith("/") ? "http://localhost" : "http://localhost/"; - url = new URL("".concat(fakeDomain).concat(redirectToPath)); - } - // Prevent Open redirects by normalising path. - var normalisedURLPath = new NormalisedURLPath__default.default(redirectToPath).getAsStringDangerous(); - var pathQueryParams = url.search || ""; // url.search contains the leading ? - var pathHash = url.hash || ""; // url.hash contains the leading # - var pathWithQueryParamsAndHash = normalisedURLPath + pathQueryParams + pathHash; - // Ensure a leading "/" if `normalisedUrlPath` is empty but `pathWithQueryParamsAndHash` is not to ensure proper redirection. - // Example: "?test=1" will not redirect the user to `/?test=1` if we don't add a leading "/". - if ( - normalisedURLPath.length === 0 && - pathWithQueryParamsAndHash.length > 0 && - !pathWithQueryParamsAndHash.startsWith("/") - ) { - return "/" + pathWithQueryParamsAndHash; - } - return pathWithQueryParamsAndHash; - } catch (_a) { - return undefined; - } - } -} -function getTenantIdFromQueryParams() { - var _a; - return (_a = getQueryParams(TENANT_ID_QUERY_PARAM)) !== null && _a !== void 0 ? _a : undefined; -} -function getDefaultRedirectionURLForPath(config, defaultPath, context, extraQueryParams) { - var redirectPath = config.appInfo.websiteBasePath - .appendPath(new NormalisedURLPath__default.default(defaultPath)) - .getAsStringDangerous(); - var queryParams = new URLSearchParams(); - if (context.tenantIdFromQueryParams !== undefined) { - queryParams.set(TENANT_ID_QUERY_PARAM, context.tenantIdFromQueryParams); - } - if (extraQueryParams !== undefined) { - Object.entries(extraQueryParams).forEach(function (_a) { - var key = _a[0], - value = _a[1]; - if (value !== undefined) { - queryParams.set(key, value); - } - }); - } - if (queryParams.toString() !== "") { - return "".concat(redirectPath, "?").concat(queryParams.toString()); - } - return redirectPath; -} -/* - * isTest - */ -function isTest() { - try { - return process.env.TEST_MODE === "testing" || process.env.REACT_APP_TEST_MODE === "testing"; - } catch (err) { - // can get Uncaught ReferenceError: process is not defined error - return false; - } -} -function normaliseInputAppInfoOrThrowError(appInfo) { - if (appInfo === undefined) { - throw new Error("Please provide the appInfo object when calling supertokens.init"); - } - if (appInfo.apiDomain === undefined) { - throw new Error("Please provide your apiDomain inside the appInfo object when calling supertokens.init"); - } - if (appInfo.appName === undefined) { - throw new Error("Please provide your appName inside the appInfo object when calling supertokens.init"); - } - if (appInfo.websiteDomain === undefined) { - throw new Error("Please provide your websiteDomain inside the appInfo object when calling supertokens.init"); - } - var apiGatewayPath = new NormalisedURLPath__default.default(""); - if (appInfo.apiGatewayPath !== undefined) { - apiGatewayPath = new NormalisedURLPath__default.default(appInfo.apiGatewayPath); - } - return { - appName: appInfo.appName, - apiDomain: new NormalisedURLDomain__default.default(appInfo.apiDomain), - websiteDomain: new NormalisedURLDomain__default.default(appInfo.websiteDomain), - apiBasePath: apiGatewayPath.appendPath( - getNormalisedURLPathOrDefault(DEFAULT_API_BASE_PATH, appInfo.apiBasePath) - ), - websiteBasePath: getNormalisedURLPathOrDefault(DEFAULT_WEBSITE_BASE_PATH, appInfo.websiteBasePath), - }; -} -function getNormalisedURLPathOrDefault(defaultPath, path) { - if (path !== undefined) { - return new NormalisedURLPath__default.default(path); - } else { - return new NormalisedURLPath__default.default(defaultPath); - } -} -/* - * validateForm - */ -// We check that the number of fields in input and config form field is the same. -// We check that each item in the config form field is also present in the input form field -function validateForm(inputs, configFormFields) { - return __awaiter(this, void 0, void 0, function () { - var validationErrors, _loop_1, i; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - validationErrors = []; - if (configFormFields.length !== inputs.length) { - throw Error("Are you sending too many / too few formFields?"); - } - _loop_1 = function (i) { - var field, input, value, error; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - field = configFormFields[i]; - input = inputs.find(function (i) { - return i.id === field.id; - }); - value = input.value; - if (input.id === "email") { - value = value.trim(); - } - return [4 /*yield*/, field.validate(value)]; - case 1: - error = _b.sent(); - // If error, add it. - if (error !== undefined) { - validationErrors.push({ - error: error, - id: field.id, - }); - } - return [2 /*return*/]; - } - }); - }; - i = 0; - _a.label = 1; - case 1: - if (!(i < configFormFields.length)) return [3 /*break*/, 4]; - return [5 /*yield**/, _loop_1(i)]; - case 2: - _a.sent(); - _a.label = 3; - case 3: - i++; - return [3 /*break*/, 1]; - case 4: - return [2 /*return*/, validationErrors]; - } - }); - }); -} -/* - * getCurrentNormalisedUrlPath - */ -function getCurrentNormalisedUrlPath() { - return new NormalisedURLPath__default.default( - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getPathName() - ); -} -function getCurrentNormalisedUrlPathWithQueryParamsAndFragments() { - var normalisedUrlPath = getCurrentNormalisedUrlPath().getAsStringDangerous(); - return ( - normalisedUrlPath + - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getSearch() + - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getHash() - ); -} -function appendQueryParamsToURL(stringUrl, queryParams) { - if (queryParams === undefined) { - return stringUrl; - } - try { - var url_1 = new URL(stringUrl); - Object.entries(queryParams).forEach(function (_a) { - var key = _a[0], - value = _a[1]; - url_1.searchParams.set(key, value); - }); - return url_1.href; - } catch (e) { - var fakeDomain = stringUrl.startsWith("/") ? "http://localhost" : "http://localhost/"; - var url_2 = new URL("".concat(fakeDomain).concat(stringUrl)); - Object.entries(queryParams).forEach(function (_a) { - var key = _a[0], - value = _a[1]; - url_2.searchParams.set(key, value); - }); - return "".concat(url_2.pathname).concat(url_2.search).concat(url_2.hash); - } -} -function appendTrailingSlashToURL(stringUrl) { - return stringUrl.endsWith("/") ? stringUrl : stringUrl + "/"; -} -/* - * Default method for matching recipe route based on query params. - */ -function matchRecipeIdUsingQueryParams(recipeId) { - return function () { - var recipeIdFromSearch = getRecipeIdFromSearch( - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getSearch() - ); - return recipeIdFromSearch === recipeId; - }; -} -function redirectWithFullPageReload(to) { - if (to.trim() === "") { - to = "/"; - } - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.setHref(to); -} -function redirectWithNavigate(to, navigate) { - if (to.trim() === "") { - to = "/"; - } - if ("push" in navigate) { - // we are using react-router-dom that is before v6 - navigate.push(to); - } else { - // in react-router-dom v6, it is just navigate(to) - navigate(to); - } -} -function getOriginOfPage() { - return new NormalisedURLDomain__default.default( - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getOrigin() - ); -} -function getLocalStorage(key) { - return __awaiter(this, void 0, void 0, function () { - var res; - return __generator(this, function (_a) { - res = windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.localStorage.getItem(key); - if (res === null || res === undefined) { - return [2 /*return*/, null]; - } - return [2 /*return*/, res]; - }); - }); -} -function setLocalStorage(key, value) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.localStorage.setItem( - key, - value - ), - ]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); -} -function removeFromLocalStorage(key) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.localStorage.removeItem( - key - ), - ]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); -} -function mergeObjects(obj1, obj2) { - var res = exports.__assign({}, obj1); - for (var key in obj2) { - if (typeof res[key] === "object" && typeof obj2[key] === "object") { - res[key] = mergeObjects(res[key], obj2[key]); - } else { - res[key] = obj2[key]; - } - } - return res; -} -function normaliseCookieScopeOrThrowError(cookieScope) { - function helper(cookieScope) { - cookieScope = cookieScope.trim().toLowerCase(); - // first we convert it to a URL so that we can use the URL class - if (cookieScope.startsWith(".")) { - cookieScope = cookieScope.substr(1); - } - if (!cookieScope.startsWith("http://") && !cookieScope.startsWith("https://")) { - cookieScope = "http://" + cookieScope; - } - try { - var urlObj = new URL(cookieScope); - cookieScope = urlObj.hostname; - // remove leading dot - if (cookieScope.startsWith(".")) { - cookieScope = cookieScope.substr(1); - } - return cookieScope; - } catch (err) { - throw new Error("Please provide a valid cookie scope"); - } - } - function isAnIpAddress(ipaddress) { - return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test( - ipaddress - ); - } - var noDotNormalised = helper(cookieScope); - if (noDotNormalised === "localhost" || isAnIpAddress(noDotNormalised)) { - return noDotNormalised; - } - if (cookieScope.startsWith(".")) { - return "." + noDotNormalised; - } - return noDotNormalised; -} -function getDefaultCookieScope() { - try { - return normaliseCookieScopeOrThrowError( - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getHostName() - ); - } catch (_a) { - return undefined; - } -} -function getCookieValue(name) { - return __awaiter(this, void 0, void 0, function () { - var value, _a, parts, last, temp; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = "; "; - return [ - 4 /*yield*/, - cookieHandler.CookieHandlerReference.getReferenceOrThrow().cookieHandler.getCookie(), - ]; - case 1: - value = _a + _b.sent(); - parts = value.split("; " + name + "="); - if (parts.length >= 2) { - last = parts.pop(); - if (last !== undefined) { - temp = last.split(";").shift(); - if (temp === undefined) { - return [2 /*return*/, null]; - } - return [2 /*return*/, temp]; - } - } - return [2 /*return*/, null]; - } - }); - }); -} -// undefined value will remove the cookie -function setFrontendCookie(name, value, scope) { - return __awaiter(this, void 0, void 0, function () { - var expires, cookieVal; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - expires = "Thu, 01 Jan 1970 00:00:01 GMT"; - cookieVal = ""; - if (value !== undefined) { - cookieVal = value; - expires = undefined; // set cookie without expiry - } - if ( - !( - scope === "localhost" || - scope === - windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getHostName() || - scope === undefined - ) - ) - return [3 /*break*/, 5]; - if (!(expires !== undefined)) return [3 /*break*/, 2]; - return [ - 4 /*yield*/, - cookieHandler.CookieHandlerReference.getReferenceOrThrow().cookieHandler.setCookie( - "".concat(name, "=").concat(cookieVal, ";expires=").concat(expires, ";path=/;samesite=lax") - ), - ]; - case 1: - _a.sent(); - return [3 /*break*/, 4]; - case 2: - return [ - 4 /*yield*/, - cookieHandler.CookieHandlerReference.getReferenceOrThrow().cookieHandler.setCookie( - "" - .concat(name, "=") - .concat(cookieVal, ";expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;samesite=lax") - ), - ]; - case 3: - _a.sent(); - _a.label = 4; - case 4: - return [3 /*break*/, 9]; - case 5: - if (!(expires !== undefined)) return [3 /*break*/, 7]; - return [ - 4 /*yield*/, - cookieHandler.CookieHandlerReference.getReferenceOrThrow().cookieHandler.setCookie( - "" - .concat(name, "=") - .concat(cookieVal, ";expires=") - .concat(expires, ";domain=") - .concat(scope, ";path=/;samesite=lax") - ), - ]; - case 6: - _a.sent(); - return [3 /*break*/, 9]; - case 7: - return [ - 4 /*yield*/, - cookieHandler.CookieHandlerReference.getReferenceOrThrow().cookieHandler.setCookie( - "" - .concat(name, "=") - .concat(cookieVal, ";domain=") - .concat(scope, ";expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;samesite=lax") - ), - ]; - case 8: - _a.sent(); - _a.label = 9; - case 9: - return [2 /*return*/]; - } - }); - }); -} -function getNormalisedUserContext(userContext) { - return userContext === undefined ? {} : userContext; -} -/** - * This function handles calling APIs that should only be called once during mount (mostly on mount of a route/feature component). - * It's split into multiple callbacks (fetch + handleResponse/handleError) because we expect fetch to take longer and - * and the component may be unmounted during the first fetch, in which case we want to avoid updating state/redirecting. - * This is especially relevant for development in strict mode with React 18 (and in the future for concurrent rendering). - * - * @param fetch This is a callback that is only called once on mount. Mostly it's for consuming tokens/doing one time only API calls - * @param handleResponse This is called with the result of the first (fetch) call if it succeeds. - * @param handleError This is called with the error of the first (fetch) call if it rejects. - * @param startLoading Will start the whole process if this is set to true (or omitted). Mostly used to wait for session loading. - */ -var useOnMountAPICall = function (fetch, handleResponse, handleError, startLoading) { - if (startLoading === void 0) { - startLoading = true; - } - var consumeReq = React.useRef(); - var _a = React.useState(undefined), - error = _a[0], - setError = _a[1]; - React.useEffect( - function () { - var effect = function (signal) { - return __awaiter(void 0, void 0, void 0, function () { - var resp, err_1, err_2; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 2, , 9]); - if (consumeReq.current === undefined) { - consumeReq.current = fetch(); - } - return [4 /*yield*/, consumeReq.current]; - case 1: - resp = _a.sent(); - if (!signal.aborted) { - void handleResponse(resp); - } - return [3 /*break*/, 9]; - case 2: - err_1 = _a.sent(); - if (!!signal.aborted) return [3 /*break*/, 8]; - if (!(handleError !== undefined)) return [3 /*break*/, 7]; - _a.label = 3; - case 3: - _a.trys.push([3, 5, , 6]); - return [4 /*yield*/, handleError(err_1, resp)]; - case 4: - _a.sent(); - return [3 /*break*/, 6]; - case 5: - err_2 = _a.sent(); - setError(err_2); - return [3 /*break*/, 6]; - case 6: - return [3 /*break*/, 8]; - case 7: - setError(err_1); - _a.label = 8; - case 8: - return [3 /*break*/, 9]; - case 9: - return [2 /*return*/]; - } - }); - }); - }; - if (startLoading) { - var ctrl_1 = new AbortController(); - void effect(ctrl_1.signal); - return function () { - ctrl_1.abort(); - }; - } - return; - }, - [setError, consumeReq, fetch, handleResponse, handleError, startLoading] - ); - if (error) { - throw error; - } -}; -function useRethrowInRender() { - var _a = React.useState(undefined), - error = _a[0], - setError = _a[1]; - if (error) { - throw error; - } - return setError; -} -var handleCallAPI = function (_a) { - var apiFields = _a.apiFields, - fieldUpdates = _a.fieldUpdates, - callAPI = _a.callAPI; - return __awaiter(void 0, void 0, void 0, function () { - var result, generalError, fetchError, e_1; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 2, , 3]); - return [ - 4 /*yield*/, - callAPI(apiFields || [], function (id, value) { - return fieldUpdates.push({ id: id, value: value }); - }), - ]; - case 1: - result = _b.sent(); - return [3 /*break*/, 3]; - case 2: - e_1 = _b.sent(); - if (STGeneralError__default.default.isThisError(e_1)) { - generalError = e_1; - } else if (e_1 instanceof Response) { - fetchError = e_1; - } else { - throw e_1; - } - return [3 /*break*/, 3]; - case 3: - return [ - 2 /*return*/, - { - result: result, - generalError: generalError, - fetchError: fetchError, - }, - ]; - } - }); - }); -}; - -var BaseRecipeModule = /** @class */ (function () { - /* - * Constructor. - */ - function BaseRecipeModule(config) { - this.config = config; - } - return BaseRecipeModule; -})(); - -function normaliseRecipeModuleConfig(config) { - var _this = this; - if (config === undefined) { - config = {}; - } - var onHandleEvent = config.onHandleEvent, - getRedirectionURL = config.getRedirectionURL, - preAPIHook = config.preAPIHook, - postAPIHook = config.postAPIHook; - if (onHandleEvent === undefined) { - // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function - onHandleEvent = function (_) {}; - } - if (getRedirectionURL === undefined) { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getRedirectionURL = function (_) { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, undefined]; - }); - }); - }; - } - if (preAPIHook === undefined) { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - preAPIHook = function (context) { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/, context]; - }); - }); - }; - } - if (postAPIHook === undefined) { - // eslint-disable-next-line @typescript-eslint/no-empty-function - postAPIHook = function () { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - return [2 /*return*/]; - }); - }); - }; - } - var rootStyle = config.style === undefined ? "" : config.style; - return exports.__assign(exports.__assign({}, config), { - getRedirectionURL: getRedirectionURL, - onHandleEvent: onHandleEvent, - preAPIHook: preAPIHook, - postAPIHook: postAPIHook, - recipeRootStyle: rootStyle, - }); -} - -function normaliseMultitenancyConfig(config) { - return exports.__assign(exports.__assign({}, normaliseRecipeModuleConfig(config)), { - override: exports.__assign( - { - functions: function (originalImplementation) { - return originalImplementation; - }, - }, - config === null || config === void 0 ? void 0 : config.override - ), - }); -} -function hasIntersectingRecipes(tenantMethods, recipeList) { - return tenantMethods.firstFactors.some(function (factorId) { - return recipeList.some(function (r) { - return r.firstFactorIds.includes(factorId); - }); - }); -} - -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Class. - */ -var Multitenancy = /** @class */ (function (_super) { - __extends(Multitenancy, _super); - function Multitenancy(config, webJSRecipe) { - if (webJSRecipe === void 0) { - webJSRecipe = MultitenancyWebJS__default.default; - } - var _this = _super.call(this, config) || this; - _this.webJSRecipe = webJSRecipe; - _this.recipeID = Multitenancy.RECIPE_ID; - _this.dynamicLoginMethodsCache = {}; - return _this; - } - Multitenancy.prototype.getCurrentDynamicLoginMethods = function (input) { - var _a; - return __awaiter(this, void 0, void 0, function () { - var userContext, tenantId, tenantMethods; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - if (SuperTokens.usesDynamicLoginMethods === false) { - return [2 /*return*/, undefined]; - } - userContext = utils.getNormalisedUserContext(input.userContext); - return [4 /*yield*/, Multitenancy.getInstanceOrThrow().webJSRecipe.getTenantId()]; - case 1: - tenantId = (_a = _b.sent()) !== null && _a !== void 0 ? _a : "public"; - if (this.dynamicLoginMethodsCache[tenantId] === undefined) { - this.dynamicLoginMethodsCache[tenantId] = Multitenancy.getDynamicLoginMethods({ - tenantId: tenantId, - userContext: userContext, - }); - } - return [4 /*yield*/, this.dynamicLoginMethodsCache[tenantId]]; - case 2: - tenantMethods = _b.sent(); - if ( - !hasIntersectingRecipes( - tenantMethods, - SuperTokens.getInstanceOrThrow().recipeList.filter(function (recipe) { - return "firstFactorIds" in recipe; - }) - ) - ) { - throw new Error( - "Initialized recipes have no overlap with core recipes or could not load login methods" - ); - } - return [2 /*return*/, tenantMethods]; - } - }); - }); - }; - Multitenancy.getDynamicLoginMethods = function (input) { - return __awaiter(this, void 0, void 0, function () { - var _a, thirdParty, firstFactors; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - return [4 /*yield*/, MultitenancyWebJS__default.default.getLoginMethods(input)]; - case 1: - (_a = _b.sent()), (thirdParty = _a.thirdParty), (firstFactors = _a.firstFactors); - return [ - 2 /*return*/, - { - thirdparty: thirdParty, - firstFactors: firstFactors, - }, - ]; - } - }); - }); - }; - Multitenancy.init = function (config) { - var normalisedConfig = normaliseMultitenancyConfig(config); - return { - recipeID: Multitenancy.RECIPE_ID, - authReact: function (appInfo) { - Multitenancy.instance = new Multitenancy( - exports.__assign(exports.__assign({}, normalisedConfig), { - appInfo: appInfo, - recipeId: Multitenancy.RECIPE_ID, - }) - ); - return Multitenancy.instance; - }, - webJS: MultitenancyWebJS__default.default.init(exports.__assign({}, normalisedConfig)), - }; - }; - Multitenancy.getInstanceOrThrow = function () { - if (Multitenancy.instance === undefined) { - var error = - "No instance of Multitenancy found. Make sure to call the Multitenancy.init method." + - "See https://supertokens.io/docs/multitenancy/quick-setup/frontend"; - // eslint-disable-next-line supertokens-auth-react/no-direct-window-object - if (typeof window === "undefined") { - error = error + SSR_ERROR; - } - throw Error(error); - } - return Multitenancy.instance; - }; - /* - * Tests methods. - */ - Multitenancy.reset = function () { - if (!isTest()) { - return; - } - Multitenancy.instance = undefined; - return; - }; - Multitenancy.RECIPE_ID = "multitenancy"; - return Multitenancy; -})(BaseRecipeModule); - -var TranslationController = /** @class */ (function () { - function TranslationController() { - this.handlers = new Map(); - } - TranslationController.prototype.emit = function (event, detail) { - var handlerList = this.handlers.get(event) || []; - for (var _i = 0, handlerList_1 = handlerList; _i < handlerList_1.length; _i++) { - var h = handlerList_1[_i]; - h(event, detail); - } - }; - TranslationController.prototype.on = function (event, handler) { - var handlerList = this.handlers.get(event) || []; - this.handlers.set(event, handlerList.concat(handler)); - }; - TranslationController.prototype.off = function (event, handler) { - var handlerList = this.handlers.get(event) || []; - this.handlers.set( - event, - handlerList.filter(function (h) { - return h !== handler; - }) - ); - }; - return TranslationController; -})(); -var CURRENT_LANGUAGE_COOKIE_NAME = "sCurrLanguage"; -function saveCurrentLanguage(language, cookieDomain) { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 2, , 3]); - return [4 /*yield*/, setFrontendCookie(CURRENT_LANGUAGE_COOKIE_NAME, language, cookieDomain)]; - case 1: - _b.sent(); - return [3 /*break*/, 3]; - case 2: - _b.sent(); - return [3 /*break*/, 3]; - case 3: - return [2 /*return*/]; - } - }); - }); -} -function getCurrentLanguageFromCookie() { - return __awaiter(this, void 0, void 0, function () { - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 2, , 3]); - return [4 /*yield*/, getCookieValue(CURRENT_LANGUAGE_COOKIE_NAME)]; - case 1: - return [2 /*return*/, _b.sent()]; - case 2: - _b.sent(); - // This can throw if we are not in a browser - // Since this is just loading a preference we can safely ignore the exception - return [2 /*return*/, null]; - case 3: - return [2 /*return*/]; - } - }); - }); -} - -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Class. - */ -var SuperTokens = /** @class */ (function () { - /* - * Constructor. - */ - function SuperTokens(config) { - var _this = this; - var _a, _b, _c, _d; - this.recipeList = []; - this.changeLanguage = function (lang) { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - saveCurrentLanguage(lang, this.languageTranslations.currentLanguageCookieScope), - ]; - case 1: - _a.sent(); - this.languageTranslations.translationEventSource.emit("LanguageChange", lang); - return [2 /*return*/]; - } - }); - }); - }; - this.redirectToAuth = function (options) { - return __awaiter(_this, void 0, void 0, function () { - var queryParams, redirectUrl; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - queryParams = options.queryParams === undefined ? {} : options.queryParams; - if (options.show !== undefined) { - queryParams.show = options.show; - } - if (options.redirectBack === true) { - queryParams.redirectToPath = getCurrentNormalisedUrlPathWithQueryParamsAndFragments(); - } - return [ - 4 /*yield*/, - this.getRedirectUrl( - { - action: "TO_AUTH", - showSignIn: options.show === "signin", - tenantIdFromQueryParams: getTenantIdFromQueryParams(), - }, - options.userContext - ), - ]; - case 1: - redirectUrl = _a.sent(); - if (redirectUrl === null) { - logDebugMessage("Skipping redirection because the user override returned null"); - return [2 /*return*/]; - } - redirectUrl = appendQueryParamsToURL(redirectUrl, queryParams); - return [2 /*return*/, this.redirectToUrl(redirectUrl, options.navigate)]; - } - }); - }); - }; - this.redirectToUrl = function (redirectUrl, navigate) { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - doRedirection(this.appInfo, redirectUrl, navigate); - return [2 /*return*/]; - }); - }); - }; - this.redirect = function (context, navigate, queryParams, userContext) { - return __awaiter(_this, void 0, void 0, function () { - var redirectUrl; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, this.getRedirectUrl(context, getNormalisedUserContext(userContext))]; - case 1: - redirectUrl = _a.sent(); - if (redirectUrl === null) { - logDebugMessage( - "Skipping redirection because the user override returned null for context ".concat( - JSON.stringify(context, null, 2) - ) - ); - return [2 /*return*/]; - } - redirectUrl = appendQueryParamsToURL(redirectUrl, queryParams); - return [ - 2 /*return*/, - SuperTokens.getInstanceOrThrow().redirectToUrl(redirectUrl, navigate), - ]; - } - }); - }); - }; - this.appInfo = normaliseInputAppInfoOrThrowError(config.appInfo); - if (config.recipeList === undefined || config.recipeList.length === 0) { - throw new Error( - "Please provide at least one recipe to the supertokens.init function call. See https://supertokens.io/docs/emailpassword/quick-setup/frontend" - ); - } - var translationConfig = config.languageTranslations === undefined ? {} : config.languageTranslations; - this.languageTranslations = { - defaultLanguage: translationConfig.defaultLanguage === undefined ? "en" : translationConfig.defaultLanguage, - currentLanguageCookieScope: - translationConfig.currentLanguageCookieScope !== undefined - ? normaliseCookieScopeOrThrowError(translationConfig.currentLanguageCookieScope) - : getDefaultCookieScope(), - userTranslationStore: translationConfig.translations !== undefined ? translationConfig.translations : {}, - translationEventSource: new TranslationController(), - userTranslationFunc: translationConfig.translationFunc, - }; - var enableDebugLogs = Boolean(config === null || config === void 0 ? void 0 : config.enableDebugLogs); - if (enableDebugLogs) { - enableLogging(); - } - this.userGetRedirectionURL = config.getRedirectionURL; - this.recipeList = config.recipeList.map(function (_a) { - var authReact = _a.authReact; - return authReact(_this.appInfo, enableDebugLogs); - }); - this.rootStyle = (_a = config.style) !== null && _a !== void 0 ? _a : ""; - this.privacyPolicyLink = config.privacyPolicyLink; - this.termsOfServiceLink = config.termsOfServiceLink; - this.useShadowDom = (_b = config.useShadowDom) !== null && _b !== void 0 ? _b : true; - this.defaultToSignUp = (_c = config.defaultToSignUp) !== null && _c !== void 0 ? _c : false; - this.disableAuthRoute = (_d = config.disableAuthRoute) !== null && _d !== void 0 ? _d : false; - } - /* - * Static Methods. - */ - SuperTokens.init = function (config) { - var _a; - cookieHandler.CookieHandlerReference.init(config.cookieHandler); - windowHandler.WindowHandlerReference.init(config.windowHandler); - if (SuperTokens.instance !== undefined) { - console.warn("SuperTokens was already initialized"); - return; - } - SuperTokens.usesDynamicLoginMethods = - (_a = config.usesDynamicLoginMethods) !== null && _a !== void 0 ? _a : false; - var recipes = - config.recipeList.find(function (recipe) { - return recipe.recipeID === Multitenancy.RECIPE_ID; - }) !== undefined - ? config.recipeList - : config.recipeList.concat(Multitenancy.init({})); - SuperTokensWebJS__default.default.init( - exports.__assign(exports.__assign({}, config), { - recipeList: recipes.map(function (_a) { - var webJS = _a.webJS; - return webJS; - }), - }) - ); - SuperTokens.instance = new SuperTokens(exports.__assign(exports.__assign({}, config), { recipeList: recipes })); - postSuperTokensInitCallbacks.PostSuperTokensInitCallbacks.runPostInitCallbacks(); - }; - SuperTokens.getInstanceOrThrow = function () { - if (SuperTokens.instance === undefined) { - var error = "SuperTokens must be initialized before calling this method."; - // eslint-disable-next-line supertokens-auth-react/no-direct-window-object - if (typeof window === "undefined") { - error = error + SSR_ERROR; - } - throw new Error(error); - } - return SuperTokens.instance; - }; - SuperTokens.prototype.getRecipeOrThrow = function (recipeId) { - var recipe = this.recipeList.find(function (recipe) { - return recipe.config.recipeId === recipeId; - }); - if (recipe === undefined) { - throw new Error("Missing recipe: ".concat(recipeId)); - } - return recipe; - }; - SuperTokens.prototype.loadTranslation = function (store) { - this.languageTranslations.translationEventSource.emit("TranslationLoaded", store); - }; - SuperTokens.prototype.getRedirectUrl = function (context, userContext) { - var _a; - return __awaiter(this, void 0, void 0, function () { - var userRes, redirectUrl, basePath; - var _b; - return __generator(this, function (_c) { - switch (_c.label) { - case 0: - if (!this.userGetRedirectionURL) return [3 /*break*/, 2]; - return [4 /*yield*/, this.userGetRedirectionURL(context, userContext)]; - case 1: - userRes = _c.sent(); - if (userRes !== undefined) { - return [2 /*return*/, userRes]; - } - _c.label = 2; - case 2: - if (context.action === "TO_AUTH") { - redirectUrl = this.appInfo.websiteBasePath.getAsStringDangerous(); - basePath = appendTrailingSlashToURL(redirectUrl); - if (context.tenantIdFromQueryParams) { - return [ - 2 /*return*/, - appendQueryParamsToURL( - basePath, - ((_b = {}), (_b[TENANT_ID_QUERY_PARAM] = context.tenantIdFromQueryParams), _b) - ), - ]; - } - return [2 /*return*/, basePath]; - } else if (context.action === "SUCCESS") { - return [2 /*return*/, (_a = context.redirectToPath) !== null && _a !== void 0 ? _a : "/"]; - } - throw new Error("Should never come here: unexpected redirection context"); - } - }); - }); - }; - /* - * Tests methods. - */ - SuperTokens.reset = function () { - if (!isTest()) { - return; - } - SuperTokens.instance = undefined; - return; - }; - SuperTokens.usesDynamicLoginMethods = false; - return SuperTokens; -})(); -function doRedirection(appInfo, redirectUrl, navigate) { - try { - new URL(redirectUrl); // If full URL, no error thrown, skip in app redirection. - } catch (e) { - // For multi tenancy, If mismatch between websiteDomain and current location, prepend URL relative path with websiteDomain. - var origin_1 = getOriginOfPage().getAsStringDangerous(); - if (origin_1 !== appInfo.websiteDomain.getAsStringDangerous()) { - redirectUrl = "".concat(appInfo.websiteDomain.getAsStringDangerous()).concat(redirectUrl); - redirectWithFullPageReload(redirectUrl); - return; - } - // If navigate was provided, use to redirect without reloading. - if (navigate !== undefined) { - redirectWithNavigate(redirectUrl, navigate); - return; - } - } - // Otherwise, redirect in app. - redirectWithFullPageReload(redirectUrl); -} - -var createGenericComponentsOverrideContext = function (v) { - if (v === void 0) { - v = {}; - } - var genericContext = React__default.default.createContext(v); - var useComponentsOverrideContext = function () { - return React__default.default.useContext(genericContext); - }; - var Provider = function (_a) { - var children = _a.children, - components = _a.components; - return jsxRuntime.jsx(genericContext.Provider, exports.__assign({ value: components }, { children: children })); - }; - return [useComponentsOverrideContext, Provider, genericContext.Consumer]; +'use strict'; + +var utils = require('./utils.js'); +var jsxRuntime = require('react/jsx-runtime'); +var React = require('react'); + +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } + +var React__default = /*#__PURE__*/_interopDefault(React); + +var createGenericComponentsOverrideContext = function (v) { + if (v === void 0) { v = {}; } + var genericContext = React__default.default.createContext(v); + var useComponentsOverrideContext = function () { + return React__default.default.useContext(genericContext); + }; + var Provider = function (_a) { + var children = _a.children, components = _a.components; + return jsxRuntime.jsx(genericContext.Provider, utils.__assign({ value: components }, { children: children })); + }; + return [useComponentsOverrideContext, Provider, genericContext.Consumer]; }; -exports.BaseRecipeModule = BaseRecipeModule; -exports.Multitenancy = Multitenancy; -exports.SSR_ERROR = SSR_ERROR; -exports.ST_ROOT_ID = ST_ROOT_ID; -exports.SuperTokens = SuperTokens; -exports.__awaiter = __awaiter; -exports.__extends = __extends; -exports.__generator = __generator; -exports.__rest = __rest; -exports.__spreadArray = __spreadArray; -exports.appendQueryParamsToURL = appendQueryParamsToURL; -exports.clearErrorQueryParam = clearErrorQueryParam; -exports.clearQueryParams = clearQueryParams; exports.createGenericComponentsOverrideContext = createGenericComponentsOverrideContext; -exports.getCurrentLanguageFromCookie = getCurrentLanguageFromCookie; -exports.getCurrentNormalisedUrlPath = getCurrentNormalisedUrlPath; -exports.getCurrentNormalisedUrlPathWithQueryParamsAndFragments = getCurrentNormalisedUrlPathWithQueryParamsAndFragments; -exports.getDefaultRedirectionURLForPath = getDefaultRedirectionURLForPath; -exports.getLocalStorage = getLocalStorage; -exports.getNormalisedUserContext = getNormalisedUserContext; -exports.getQueryParams = getQueryParams; -exports.getRedirectToPathFromURL = getRedirectToPathFromURL; -exports.getTenantIdFromQueryParams = getTenantIdFromQueryParams; -exports.getURLHash = getURLHash; -exports.handleCallAPI = handleCallAPI; -exports.isTest = isTest; -exports.logDebugMessage = logDebugMessage; -exports.matchRecipeIdUsingQueryParams = matchRecipeIdUsingQueryParams; -exports.mergeObjects = mergeObjects; -exports.normaliseRecipeModuleConfig = normaliseRecipeModuleConfig; -exports.redirectWithFullPageReload = redirectWithFullPageReload; -exports.removeFromLocalStorage = removeFromLocalStorage; -exports.setLocalStorage = setLocalStorage; -exports.updateQueryParam = updateQueryParam; -exports.useOnMountAPICall = useOnMountAPICall; -exports.useRethrowInRender = useRethrowInRender; -exports.validateForm = validateForm; diff --git a/lib/build/index.d.ts b/lib/build/index.d.ts index 3e0395d4b..a805832c5 100644 --- a/lib/build/index.d.ts +++ b/lib/build/index.d.ts @@ -1,35 +1,33 @@ -/// -import type { TranslationStore } from "./translation/translationHelpers"; -import type { Navigate, SuperTokensConfig, UserContext } from "./types"; -export default class SuperTokensAPIWrapper { - static SuperTokensWrapper: import("react").FC< - import("react").PropsWithChildren<{ - userContext?: UserContext | undefined; - }> - >; - static init(config: SuperTokensConfig): void; - static changeLanguage(language: string): Promise; - static loadTranslation(store: TranslationStore): void; - static redirectToAuth: (options?: { - show?: "signin" | "signup"; - navigate?: Navigate; - queryParams?: any; - redirectBack?: boolean; - userContext?: UserContext; - }) => Promise; - static useTranslation: () => import("./translation/translationHelpers").TranslationFunc; - static useUserContext: () => UserContext; -} -export declare const init: typeof SuperTokensAPIWrapper.init; -export declare const changeLanguage: typeof SuperTokensAPIWrapper.changeLanguage; -export declare const loadTranslation: typeof SuperTokensAPIWrapper.loadTranslation; -export declare const redirectToAuth: (options?: { - show?: "signin" | "signup"; - navigate?: Navigate; - queryParams?: any; - redirectBack?: boolean; - userContext?: UserContext; -}) => Promise; -export { SuperTokensWrapper } from "./components/supertokensWrapper"; -export { useTranslation } from "./translation/translationContext"; -export { useUserContext } from "./usercontext"; +/// +import type { TranslationStore } from "./translation/translationHelpers"; +import type { Navigate, SuperTokensConfig, UserContext } from "./types"; +export default class SuperTokensAPIWrapper { + static SuperTokensWrapper: import("react").FC>; + static init(config: SuperTokensConfig): void; + static changeLanguage(language: string): Promise; + static loadTranslation(store: TranslationStore): void; + static redirectToAuth: (options?: { + show?: "signin" | "signup"; + navigate?: Navigate; + queryParams?: any; + redirectBack?: boolean; + userContext?: UserContext; + }) => Promise; + static useTranslation: () => import("./translation/translationHelpers").TranslationFunc; + static useUserContext: () => UserContext; +} +export declare const init: typeof SuperTokensAPIWrapper.init; +export declare const changeLanguage: typeof SuperTokensAPIWrapper.changeLanguage; +export declare const loadTranslation: typeof SuperTokensAPIWrapper.loadTranslation; +export declare const redirectToAuth: (options?: { + show?: "signin" | "signup"; + navigate?: Navigate; + queryParams?: any; + redirectBack?: boolean; + userContext?: UserContext; +}) => Promise; +export { SuperTokensWrapper } from "./components/supertokensWrapper"; +export { useTranslation } from "./translation/translationContext"; +export { useUserContext } from "./usercontext"; diff --git a/lib/build/index.js b/lib/build/index.js index ef0f8b34a..d113cacce 100644 --- a/lib/build/index.js +++ b/lib/build/index.js @@ -1,33 +1,38 @@ -"use strict"; +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +require('./utils.js'); +var uiEntry = require('./index2.js'); +require('./superTokens.js'); +var translationContext = require('./translationContext.js'); +require('react'); +require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('supertokens-web-js/utils/normalisedURLPath'); +require('supertokens-web-js/utils/windowHandler'); +require('crypto'); +require('react/jsx-runtime'); +require('react-dom'); +require('./multitenancy-shared.js'); +require('./genericComponentOverrideContext.js'); +require('./multifactorauth-shared2.js'); +require('supertokens-web-js/recipe/multifactorauth'); +require('supertokens-web-js/utils'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('supertokens-web-js/utils/sessionClaimValidatorStore'); +require('./recipeModule-shared.js'); +require('./multifactorauth-shared.js'); +require('supertokens-web-js/recipe/session'); +require('./oauth2provider-shared.js'); +require('supertokens-web-js/recipe/oauth2provider'); +require('./authRecipe-shared.js'); +require('supertokens-web-js/lib/build/normalisedURLPath'); +require('supertokens-web-js'); +require('supertokens-web-js/recipe/multitenancy'); -Object.defineProperty(exports, "__esModule", { value: true }); -require("./genericComponentOverrideContext.js"); -var uiEntry = require("./index2.js"); -var translationContext = require("./translationContext.js"); -require("supertokens-web-js"); -require("supertokens-web-js/utils/cookieHandler"); -require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -require("supertokens-web-js/utils/windowHandler"); -require("supertokens-web-js/recipe/multitenancy"); -require("supertokens-web-js/utils"); -require("react"); -require("supertokens-web-js/lib/build/error"); -require("supertokens-web-js/utils/normalisedURLDomain"); -require("supertokens-web-js/utils/normalisedURLPath"); -require("react/jsx-runtime"); -require("react-dom"); -require("./multitenancy-shared.js"); -require("./multifactorauth-shared2.js"); -require("supertokens-web-js/recipe/multifactorauth"); -require("supertokens-web-js/utils/sessionClaimValidatorStore"); -require("./recipeModule-shared.js"); -require("./multifactorauth-shared.js"); -require("supertokens-web-js/recipe/session"); -require("./oauth2provider-shared.js"); -require("supertokens-web-js/recipe/oauth2provider"); -require("./authRecipe-shared.js"); -require("supertokens-web-js/lib/build/normalisedURLPath"); exports.SuperTokensWrapper = uiEntry.SuperTokensWrapper; exports.changeLanguage = uiEntry.changeLanguage; diff --git a/lib/build/index2.js b/lib/build/index2.js index 10b2c2aed..0eda402bd 100644 --- a/lib/build/index2.js +++ b/lib/build/index2.js @@ -1,2769 +1,1545 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var jsxRuntime = require("react/jsx-runtime"); -var React = require("react"); -var NormalisedURLPath = require("supertokens-web-js/utils/normalisedURLPath"); -var translationContext = require("./translationContext.js"); -var windowHandler = require("supertokens-web-js/utils/windowHandler"); -var reactDom = require("react-dom"); -var componentOverrideContext = require("./multitenancy-shared.js"); -var recipe$1 = require("./multifactorauth-shared2.js"); -var types = require("./multifactorauth-shared.js"); -var recipe = require("./oauth2provider-shared.js"); -var utils = require("./authRecipe-shared.js"); -var NormalisedURLPath$1 = require("supertokens-web-js/lib/build/normalisedURLPath"); +var utils = require('./utils.js'); +var jsxRuntime = require('react/jsx-runtime'); +var React = require('react'); +var superTokens = require('./superTokens.js'); +var NormalisedURLPath = require('supertokens-web-js/utils/normalisedURLPath'); +var translationContext = require('./translationContext.js'); +var windowHandler = require('supertokens-web-js/utils/windowHandler'); +var reactDom = require('react-dom'); +var componentOverrideContext = require('./multitenancy-shared.js'); +var recipe$1 = require('./multifactorauth-shared2.js'); +var types = require('./multifactorauth-shared.js'); +var recipe = require('./oauth2provider-shared.js'); +var genericComponentOverrideContext = require('./genericComponentOverrideContext.js'); +var utils$1 = require('./authRecipe-shared.js'); +var NormalisedURLPath$1 = require('supertokens-web-js/lib/build/normalisedURLPath'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } -var React__default = /*#__PURE__*/ _interopDefault(React); -var NormalisedURLPath__default = /*#__PURE__*/ _interopDefault(NormalisedURLPath); -var NormalisedURLPath__default$1 = /*#__PURE__*/ _interopDefault(NormalisedURLPath$1); +var React__default = /*#__PURE__*/_interopDefault(React); +var NormalisedURLPath__default = /*#__PURE__*/_interopDefault(NormalisedURLPath); +var NormalisedURLPath__default$1 = /*#__PURE__*/_interopDefault(NormalisedURLPath$1); var ComponentOverrideContext = React__default.default.createContext("IS_DEFAULT"); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Imports. - */ -/* - * Component. - */ -function SpinnerIcon() { - return jsxRuntime.jsx( - "svg", - genericComponentOverrideContext.__assign( - { version: "1.1", viewBox: "25 25 50 50", "data-supertokens": "spinnerIcon" }, - { - children: jsxRuntime.jsxs( - "circle", - genericComponentOverrideContext.__assign( - { - cx: "50", - cy: "50", - r: "20", - fill: "none", - stroke: "rgb(var(--palette-primary))", - strokeWidth: "5", - strokeLinecap: "round", - strokeDashoffset: "0", - strokeDasharray: "100, 200", - }, - { - children: [ - jsxRuntime.jsx("animateTransform", { - attributeName: "transform", - attributeType: "XML", - type: "rotate", - from: "0 50 50", - to: "360 50 50", - dur: "4s", - repeatCount: "indefinite", - }), - jsxRuntime.jsx("animate", { - attributeName: "stroke-dashoffset", - values: "0;-30;-124", - dur: "2s", - repeatCount: "indefinite", - }), - jsxRuntime.jsx("animate", { - attributeName: "stroke-dasharray", - values: "0,200;110,200;110,200", - dur: "2s", - repeatCount: "indefinite", - }), - ], - } - ) - ), - } - ) - ); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Imports. + */ +/* + * Component. + */ +function SpinnerIcon() { + return (jsxRuntime.jsx("svg", utils.__assign({ version: "1.1", viewBox: "25 25 50 50", "data-supertokens": "spinnerIcon" }, { children: jsxRuntime.jsxs("circle", utils.__assign({ cx: "50", cy: "50", r: "20", fill: "none", stroke: "rgb(var(--palette-primary))", strokeWidth: "5", strokeLinecap: "round", strokeDashoffset: "0", strokeDasharray: "100, 200" }, { children: [jsxRuntime.jsx("animateTransform", { attributeName: "transform", attributeType: "XML", type: "rotate", from: "0 50 50", to: "360 50 50", dur: "4s", repeatCount: "indefinite" }), jsxRuntime.jsx("animate", { attributeName: "stroke-dashoffset", values: "0;-30;-124", dur: "2s", repeatCount: "indefinite" }), jsxRuntime.jsx("animate", { attributeName: "stroke-dasharray", values: "0,200;110,200;110,200", dur: "2s", repeatCount: "indefinite" })] })) }))); } -var useComponentOverride = function (overrideKey) { - var ctx = React.useContext(ComponentOverrideContext); - if (ctx === "IS_DEFAULT") { - throw new Error("Cannot use component override outside ComponentOverrideContext provider."); - } - var OverrideComponent = ctx[overrideKey]; - return OverrideComponent === undefined ? null : OverrideComponent; +var useComponentOverride = function (overrideKey) { + var ctx = React.useContext(ComponentOverrideContext); + if (ctx === "IS_DEFAULT") { + throw new Error("Cannot use component override outside ComponentOverrideContext provider."); + } + var OverrideComponent = ctx[overrideKey]; + return OverrideComponent === undefined ? null : OverrideComponent; }; -var withOverride = function (overrideKey, DefaultComponent) { - var finalKey = overrideKey + "_Override"; - DefaultComponent.displayName = finalKey; - return function (props) { - var OverrideComponent = useComponentOverride(finalKey); - if (OverrideComponent !== null) { - return jsxRuntime.jsx( - OverrideComponent, - genericComponentOverrideContext.__assign({ DefaultComponent: DefaultComponent }, props) - ); - } - return jsxRuntime.jsx(DefaultComponent, genericComponentOverrideContext.__assign({}, props)); - }; +var withOverride = function (overrideKey, DefaultComponent) { + var finalKey = overrideKey + "_Override"; + DefaultComponent.displayName = finalKey; + return function (props) { + var OverrideComponent = useComponentOverride(finalKey); + if (OverrideComponent !== null) { + return jsxRuntime.jsx(OverrideComponent, utils.__assign({ DefaultComponent: DefaultComponent }, props)); + } + return jsxRuntime.jsx(DefaultComponent, utils.__assign({}, props)); + }; }; -var styles$1 = - '[data-supertokens~="container"] {\n --palette-background: 255, 255, 255;\n --palette-inputBackground: 250, 250, 250;\n --palette-inputBorder: 224, 224, 224;\n --palette-primary: 28, 34, 42;\n --palette-primaryBorder: 45, 54, 68;\n --palette-success: 65, 167, 0;\n --palette-successBackground: 217, 255, 191;\n --palette-error: 255, 23, 23;\n --palette-errorBackground: 255, 241, 235;\n --palette-textTitle: 0, 0, 0;\n --palette-textLabel: 0, 0, 0;\n --palette-textInput: 0, 0, 0;\n --palette-textPrimary: 128, 128, 128;\n --palette-textLink: 0, 122, 255;\n --palette-buttonText: 255, 255, 255;\n --palette-textGray: 54, 54, 54;\n --palette-superTokensBrandingBackground: 242, 245, 246;\n --palette-superTokensBrandingText: 173, 189, 196;\n --palette-buttonGreyedOut: 221, 221, 221;\n --palette-caution: 124, 96, 62;\n --palette-errorDark: 207, 54, 68;\n\n --font-size-0: 12px;\n --font-size-1: 14px;\n --font-size-2: 16px;\n --font-size-3: 19px;\n --font-size-4: 24px;\n --font-size-5: 28px;\n}\n/*\n * Default styles.\n */\n@keyframes slideTop {\n 0% {\n transform: translateY(-5px);\n }\n 100% {\n transform: translateY(0px);\n }\n}\n@keyframes swing-in-top-fwd {\n 0% {\n transform: rotateX(-100deg);\n transform-origin: top;\n opacity: 0;\n }\n 100% {\n transform: rotateX(0deg);\n transform-origin: top;\n opacity: 1;\n }\n}\n[data-supertokens~="container"] {\n font-family: "Arial", sans-serif;\n margin: 12px auto;\n margin-top: 26px;\n margin-bottom: 26px;\n width: 420px;\n text-align: center;\n border-radius: 8px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.16);\n background-color: rgb(var(--palette-background));\n}\n@media (max-width: 440px) {\n [data-supertokens~="container"] {\n width: 95vw;\n }\n}\n[data-supertokens~="row"] {\n margin: 0 auto;\n width: 76%;\n padding-top: 30px;\n padding-bottom: 10px;\n}\n[data-supertokens~="superTokensBranding"] {\n display: block;\n margin: 10px auto 0;\n background: rgb(var(--palette-superTokensBrandingBackground));\n color: rgb(var(--palette-superTokensBrandingText));\n text-decoration: none;\n width: -webkit-fit-content;\n width: fit-content;\n border-radius: 6px 6px 0 0;\n padding: 4px 9px;\n font-weight: 400;\n font-size: var(--font-size-0);\n letter-spacing: 0.4px;\n}\n[data-supertokens~="generalError"] {\n background: rgb(var(--palette-errorBackground));\n padding-top: 10px;\n padding-bottom: 10px;\n margin-bottom: 10px;\n margin-top: 24px;\n padding-left: 18px;\n padding-right: 18px;\n letter-spacing: 0.2px;\n font-size: var(--font-size-1);\n border-radius: 8px;\n color: rgb(var(--palette-error));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n word-wrap: break-word;\n}\n[data-supertokens~="headerTitle"] {\n font-size: var(--font-size-4);\n line-height: 27.6px;\n letter-spacing: 0.58px;\n font-weight: 700;\n margin-bottom: 20px;\n color: rgb(var(--palette-textTitle));\n}\n[data-supertokens~="headerSubtitle"] {\n font-weight: 400;\n color: rgb(var(--palette-textGray));\n margin-bottom: 21px;\n}\n[data-supertokens~="headerSubtitle"][data-supertokens~="secondaryText"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n}\n[data-supertokens~="privacyPolicyAndTermsAndConditions"] {\n max-width: 300px;\n margin-top: 10px;\n}\n[data-supertokens~="privacyPolicyAndTermsAndConditions"] a {\n line-height: 21px;\n}\n/* TODO: split the link style into separate things*/\n/* We add this before primary and secondary text, because if they are applied to the same element the other ones take priority */\n[data-supertokens~="link"] {\n padding-left: 3px;\n padding-right: 3px;\n color: rgb(var(--palette-textLink));\n font-size: var(--font-size-1);\n cursor: pointer;\n letter-spacing: 0.16px;\n line-height: 26px;\n}\n[data-supertokens~="primaryText"] {\n font-size: var(--font-size-2);\n font-weight: 400;\n letter-spacing: 0.4px;\n line-height: 21px;\n color: rgb(var(--palette-textLabel));\n}\n[data-supertokens~="secondaryText"] {\n font-size: var(--font-size-1);\n font-weight: 400;\n letter-spacing: 0.4px;\n color: rgb(var(--palette-textPrimary));\n}\n[data-supertokens~="secondaryText"] strong {\n font-weight: 600;\n}\n[data-supertokens~="divider"] {\n margin-top: 1.5em;\n margin-bottom: 1.5em;\n border-bottom: 0.3px solid #dddddd;\n align-items: center;\n padding-bottom: 5px;\n flex: 3 3;\n}\n[data-supertokens~="headerTinyTitle"] {\n margin-top: 24px;\n font-size: var(--font-size-5);\n letter-spacing: 1.1px;\n font-weight: 700;\n line-height: 28px;\n}\n[data-supertokens~="secondaryLinkWithArrow"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n}\n[data-supertokens~="secondaryLinkWithArrow"]:hover {\n position: relative;\n left: 2px;\n word-spacing: 4px;\n}\n[data-supertokens~="generalSuccess"] {\n color: rgb(var(--palette-success));\n font-size: var(--font-size-1);\n background: rgb(var(--palette-successBackground));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n padding: 9px 15px 9px 15px;\n border-radius: 6px;\n display: inline-block;\n}\n[data-supertokens~="spinner"] {\n width: 80px;\n height: auto;\n padding-top: 20px;\n padding-bottom: 40px;\n margin: 0 auto;\n}\n[data-supertokens~="error"] {\n color: rgb(var(--palette-error));\n}\n[data-supertokens~="linkButton"] {\n font-family: "Arial", sans-serif;\n background-color: transparent;\n border: 0;\n}\n[data-supertokens~="secondaryLinkWithLeftArrow"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n margin-top: 10px;\n margin-bottom: 40px;\n cursor: pointer;\n}\n[data-supertokens~="secondaryLinkWithLeftArrow"] svg {\n margin-right: 0.3em;\n}\n[data-supertokens~="secondaryLinkWithLeftArrow"]:hover svg {\n position: relative;\n left: -4px;\n}\n[data-supertokens~="button"] {\n font-family: "Arial", sans-serif;\n background-color: rgb(var(--palette-primary));\n color: rgb(var(--palette-buttonText));\n width: 100%;\n height: 34px;\n font-weight: 600;\n border-width: 1px;\n border-style: solid;\n border-radius: 6px;\n border-color: rgb(var(--palette-primaryBorder));\n background-position: center;\n transition: all 0.4s;\n background-size: 12000%;\n cursor: pointer;\n}\n[data-supertokens~="buttonGreyedOut"] {\n background-color: rgb(var(--palette-buttonGreyedOut));\n border-color: rgb(var(--palette-buttonGreyedOut));\n}\n[data-supertokens~="buttonWithIcon"] {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n}\n[data-supertokens~="button"]:disabled {\n border: none;\n cursor: no-drop;\n}\n[data-supertokens~="button"]:active {\n outline: none;\n transition: all 0s;\n background-size: 100%;\n filter: brightness(0.85);\n}\n[data-supertokens~="button"]:focus {\n outline: none;\n}\n[data-supertokens~="backButtonCommon"] {\n width: 16px;\n height: 13px;\n}\n[data-supertokens~="backButton"] {\n cursor: pointer;\n border: none;\n background-color: transparent;\n padding: 0px;\n}\n[data-supertokens~="backButtonPlaceholder"] {\n display: block;\n}\n[data-supertokens~="delayedRender"] {\n animation-duration: 0.1s;\n animation-name: animate-fade;\n animation-delay: 0.2s;\n animation-fill-mode: backwards;\n}\n@keyframes animate-fade {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n[data-supertokens~="footerLinkGroupVert"] {\n display: flex;\n flex-direction: column;\n margin-top: 10px;\n gap: 24px;\n}\n[data-supertokens~="footerLinkGroupVert"] > div {\n cursor: pointer;\n margin: 0;\n}\n[data-supertokens~="footerLinkGroupVert"] [data-supertokens~="secondaryText"] {\n font-weight: 400;\n}\n[data-supertokens~="footerLinkGroupVert"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n font-weight: 400;\n position: relative;\n left: -6px; /* half the width of the left arrow */\n}\n@media (max-width: 360px) {\n [data-supertokens~="footerLinkGroupVert"] {\n flex-direction: column;\n }\n [data-supertokens~="footerLinkGroupVert"] > div {\n margin: 0 auto;\n }\n}\n[data-supertokens~="footerLinkGroupVert"] div:only-child {\n margin-left: auto;\n margin-right: auto;\n margin-top: 14px;\n}\n[data-supertokens~="withBackButton"] {\n position: relative;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n[data-supertokens~="dividerWithOr"] {\n padding-top: 5px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n color: rgb(var(--palette-textPrimary));\n}\n[data-supertokens~="dividerText"] {\n flex: 1 1;\n font-weight: 400;\n font-size: var(--font-size-1);\n}\n[data-supertokens~="formLabelWithLinkWrapper"] {\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n[data-supertokens~="formLabelLinkBtn"] {\n width: auto;\n margin-top: 0;\n line-height: 24px;\n font-size: var(--font-size-0);\n}\n[data-supertokens~="formLabelLinkBtn"]:hover {\n text-decoration: underline;\n}\n[data-supertokens~="formLabelLinkBtn"]:disabled {\n color: rgb(var(--palette-textPrimary));\n cursor: default;\n text-decoration: none;\n}\n[data-supertokens~="authComponentList"] {\n padding-bottom: 20px;\n}\n[data-supertokens~="authPageTitleOAuthClient"] {\n color: rgb(var(--palette-textGray));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 10px 0 25px;\n}\n[data-supertokens~="authPageTitleOAuthClientUrl"] {\n text-decoration: none;\n}\n[data-supertokens~="authPageTitleOAuthClientLogo"] {\n width: 44px;\n height: 44px;\n margin-bottom: 10px;\n}\n[data-supertokens~="authPageTitleOAuthClient"] [data-supertokens~="authPageTitleOAuthClientName"] {\n color: rgb(var(--palette-textTitle));\n}\n[data-supertokens~="buttonWithArrow"] {\n border-radius: 6px;\n border: 1px solid #d0d5dd;\n width: 100%;\n color: rgb(var(--palette-textGray));\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n margin: 24px 0;\n min-height: 48px;\n cursor: pointer;\n}\n[data-supertokens~="buttonWithArrow"]:hover {\n background-color: rgb(var(--palette-inputBackground));\n}\n[data-supertokens~="buttonWithArrow"] [data-supertokens~="secondaryText"] {\n font-weight: 700;\n font-size: var(--font-size-2);\n color: rgb(var(--palette-textGray));\n margin: 0;\n}\n[data-supertokens~="buttonWithArrow"]:hover [data-supertokens~="secondaryLinkWithRightArrow"] ~ svg {\n position: relative;\n left: 2px;\n}\n[data-supertokens~="buttonWithArrow"]:hover [data-supertokens~="secondaryLinkWithLeftArrow"] svg {\n position: relative;\n left: -2px;\n}\n[data-supertokens~="buttonWithArrow"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n display: flex;\n align-items: center;\n}\n'; +var styles$1 = "[data-supertokens~=\"container\"] {\n --palette-background: 255, 255, 255;\n --palette-inputBackground: 250, 250, 250;\n --palette-inputBorder: 224, 224, 224;\n --palette-primary: 28, 34, 42;\n --palette-primaryBorder: 45, 54, 68;\n --palette-success: 65, 167, 0;\n --palette-successBackground: 217, 255, 191;\n --palette-error: 255, 23, 23;\n --palette-errorBackground: 255, 241, 235;\n --palette-textTitle: 0, 0, 0;\n --palette-textLabel: 0, 0, 0;\n --palette-textInput: 0, 0, 0;\n --palette-textPrimary: 128, 128, 128;\n --palette-textLink: 0, 122, 255;\n --palette-buttonText: 255, 255, 255;\n --palette-textGray: 54, 54, 54;\n --palette-superTokensBrandingBackground: 242, 245, 246;\n --palette-superTokensBrandingText: 173, 189, 196;\n --palette-buttonGreyedOut: 221, 221, 221;\n --palette-caution: 124, 96, 62;\n --palette-errorDark: 207, 54, 68;\n\n --font-size-0: 12px;\n --font-size-1: 14px;\n --font-size-2: 16px;\n --font-size-3: 19px;\n --font-size-4: 24px;\n --font-size-5: 28px;\n}\n/*\n * Default styles.\n */\n@keyframes slideTop {\n 0% {\n transform: translateY(-5px);\n }\n 100% {\n transform: translateY(0px);\n }\n}\n@keyframes swing-in-top-fwd {\n 0% {\n transform: rotateX(-100deg);\n transform-origin: top;\n opacity: 0;\n }\n 100% {\n transform: rotateX(0deg);\n transform-origin: top;\n opacity: 1;\n }\n}\n[data-supertokens~=\"container\"] {\n font-family: \"Arial\", sans-serif;\n margin: 12px auto;\n margin-top: 26px;\n margin-bottom: 26px;\n width: 420px;\n text-align: center;\n border-radius: 8px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.16);\n background-color: rgb(var(--palette-background));\n}\n@media (max-width: 440px) {\n [data-supertokens~=\"container\"] {\n width: 95vw;\n }\n}\n[data-supertokens~=\"row\"] {\n margin: 0 auto;\n width: 76%;\n padding-top: 30px;\n padding-bottom: 10px;\n}\n[data-supertokens~=\"superTokensBranding\"] {\n display: block;\n margin: 10px auto 0;\n background: rgb(var(--palette-superTokensBrandingBackground));\n color: rgb(var(--palette-superTokensBrandingText));\n text-decoration: none;\n width: -webkit-fit-content;\n width: -moz-fit-content;\n width: fit-content;\n border-radius: 6px 6px 0 0;\n padding: 4px 9px;\n font-weight: 400;\n font-size: var(--font-size-0);\n letter-spacing: 0.4px;\n}\n[data-supertokens~=\"generalError\"] {\n background: rgb(var(--palette-errorBackground));\n padding-top: 10px;\n padding-bottom: 10px;\n margin-bottom: 10px;\n margin-top: 24px;\n padding-left: 18px;\n padding-right: 18px;\n letter-spacing: 0.2px;\n font-size: var(--font-size-1);\n border-radius: 8px;\n color: rgb(var(--palette-error));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n word-wrap: break-word;\n}\n[data-supertokens~=\"headerTitle\"] {\n font-size: var(--font-size-4);\n line-height: 27.6px;\n letter-spacing: 0.58px;\n font-weight: 700;\n margin-bottom: 20px;\n color: rgb(var(--palette-textTitle));\n}\n[data-supertokens~=\"headerSubtitle\"] {\n font-weight: 400;\n color: rgb(var(--palette-textGray));\n margin-bottom: 21px;\n}\n[data-supertokens~=\"headerSubtitle\"][data-supertokens~=\"secondaryText\"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n}\n[data-supertokens~=\"privacyPolicyAndTermsAndConditions\"] {\n max-width: 300px;\n margin-top: 10px;\n}\n[data-supertokens~=\"privacyPolicyAndTermsAndConditions\"] a {\n line-height: 21px;\n}\n/* TODO: split the link style into separate things*/\n/* We add this before primary and secondary text, because if they are applied to the same element the other ones take priority */\n[data-supertokens~=\"link\"] {\n padding-left: 3px;\n padding-right: 3px;\n color: rgb(var(--palette-textLink));\n font-size: var(--font-size-1);\n cursor: pointer;\n letter-spacing: 0.16px;\n line-height: 26px;\n}\n[data-supertokens~=\"primaryText\"] {\n font-size: var(--font-size-2);\n font-weight: 400;\n letter-spacing: 0.4px;\n line-height: 21px;\n color: rgb(var(--palette-textLabel));\n}\n[data-supertokens~=\"secondaryText\"] {\n font-size: var(--font-size-1);\n font-weight: 400;\n letter-spacing: 0.4px;\n color: rgb(var(--palette-textPrimary));\n}\n[data-supertokens~=\"secondaryText\"] strong {\n font-weight: 600;\n}\n[data-supertokens~=\"divider\"] {\n margin-top: 1.5em;\n margin-bottom: 1.5em;\n border-bottom: 0.3px solid #dddddd;\n align-items: center;\n padding-bottom: 5px;\n flex: 3 3;\n}\n[data-supertokens~=\"headerTinyTitle\"] {\n margin-top: 24px;\n font-size: var(--font-size-5);\n letter-spacing: 1.1px;\n font-weight: 700;\n line-height: 28px;\n}\n[data-supertokens~=\"secondaryLinkWithArrow\"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n}\n[data-supertokens~=\"secondaryLinkWithArrow\"]:hover {\n position: relative;\n left: 2px;\n word-spacing: 4px;\n}\n[data-supertokens~=\"generalSuccess\"] {\n color: rgb(var(--palette-success));\n font-size: var(--font-size-1);\n background: rgb(var(--palette-successBackground));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n padding: 9px 15px 9px 15px;\n border-radius: 6px;\n display: inline-block;\n}\n[data-supertokens~=\"spinner\"] {\n width: 80px;\n height: auto;\n padding-top: 20px;\n padding-bottom: 40px;\n margin: 0 auto;\n}\n[data-supertokens~=\"error\"] {\n color: rgb(var(--palette-error));\n}\n[data-supertokens~=\"linkButton\"] {\n font-family: \"Arial\", sans-serif;\n background-color: transparent;\n border: 0;\n}\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n margin-top: 10px;\n margin-bottom: 40px;\n cursor: pointer;\n}\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"] svg {\n margin-right: 0.3em;\n}\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"]:hover svg {\n position: relative;\n left: -4px;\n}\n[data-supertokens~=\"button\"] {\n font-family: \"Arial\", sans-serif;\n background-color: rgb(var(--palette-primary));\n color: rgb(var(--palette-buttonText));\n width: 100%;\n height: 34px;\n font-weight: 600;\n border-width: 1px;\n border-style: solid;\n border-radius: 6px;\n border-color: rgb(var(--palette-primaryBorder));\n background-position: center;\n transition: all 0.4s;\n background-size: 12000%;\n cursor: pointer;\n}\n[data-supertokens~=\"buttonGreyedOut\"] {\n background-color: rgb(var(--palette-buttonGreyedOut));\n border-color: rgb(var(--palette-buttonGreyedOut));\n}\n[data-supertokens~=\"buttonWithIcon\"] {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n}\n[data-supertokens~=\"button\"]:disabled {\n border: none;\n cursor: no-drop;\n}\n[data-supertokens~=\"button\"]:active {\n outline: none;\n transition: all 0s;\n background-size: 100%;\n filter: brightness(0.85);\n}\n[data-supertokens~=\"button\"]:focus {\n outline: none;\n}\n[data-supertokens~=\"backButtonCommon\"] {\n width: 16px;\n height: 13px;\n}\n[data-supertokens~=\"backButton\"] {\n cursor: pointer;\n border: none;\n background-color: transparent;\n padding: 0px;\n}\n[data-supertokens~=\"backButtonPlaceholder\"] {\n display: block;\n}\n[data-supertokens~=\"delayedRender\"] {\n animation-duration: 0.1s;\n animation-name: animate-fade;\n animation-delay: 0.2s;\n animation-fill-mode: backwards;\n}\n@keyframes animate-fade {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n[data-supertokens~=\"footerLinkGroupVert\"] {\n display: flex;\n flex-direction: column;\n margin-top: 10px;\n gap: 24px;\n}\n[data-supertokens~=\"footerLinkGroupVert\"] > div {\n cursor: pointer;\n margin: 0;\n}\n[data-supertokens~=\"footerLinkGroupVert\"] [data-supertokens~=\"secondaryText\"] {\n font-weight: 400;\n}\n[data-supertokens~=\"footerLinkGroupVert\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n font-weight: 400;\n position: relative;\n left: -6px; /* half the width of the left arrow */\n}\n@media (max-width: 360px) {\n [data-supertokens~=\"footerLinkGroupVert\"] {\n flex-direction: column;\n }\n [data-supertokens~=\"footerLinkGroupVert\"] > div {\n margin: 0 auto;\n }\n}\n[data-supertokens~=\"footerLinkGroupVert\"] div:only-child {\n margin-left: auto;\n margin-right: auto;\n margin-top: 14px;\n}\n[data-supertokens~=\"withBackButton\"] {\n position: relative;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n[data-supertokens~=\"dividerWithOr\"] {\n padding-top: 5px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n color: rgb(var(--palette-textPrimary));\n}\n[data-supertokens~=\"dividerText\"] {\n flex: 1 1;\n font-weight: 400;\n font-size: var(--font-size-1);\n}\n[data-supertokens~=\"formLabelWithLinkWrapper\"] {\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n[data-supertokens~=\"formLabelLinkBtn\"] {\n width: auto;\n margin-top: 0;\n line-height: 24px;\n font-size: var(--font-size-0);\n}\n[data-supertokens~=\"formLabelLinkBtn\"]:hover {\n text-decoration: underline;\n}\n[data-supertokens~=\"formLabelLinkBtn\"]:disabled {\n color: rgb(var(--palette-textPrimary));\n cursor: default;\n text-decoration: none;\n}\n[data-supertokens~=\"authComponentList\"] {\n padding-bottom: 20px;\n}\n[data-supertokens~=\"authPageTitleOAuthClient\"] {\n color: rgb(var(--palette-textGray));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 10px 0 25px;\n}\n[data-supertokens~=\"authPageTitleOAuthClientUrl\"] {\n text-decoration: none;\n}\n[data-supertokens~=\"authPageTitleOAuthClientLogo\"] {\n width: 44px;\n height: 44px;\n margin-bottom: 10px;\n}\n[data-supertokens~=\"authPageTitleOAuthClient\"] [data-supertokens~=\"authPageTitleOAuthClientName\"] {\n color: rgb(var(--palette-textTitle));\n}\n[data-supertokens~=\"buttonWithArrow\"] {\n border-radius: 6px;\n border: 1px solid #d0d5dd;\n width: 100%;\n color: rgb(var(--palette-textGray));\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n margin: 24px 0;\n min-height: 48px;\n cursor: pointer;\n}\n[data-supertokens~=\"buttonWithArrow\"]:hover {\n background-color: rgb(var(--palette-inputBackground));\n}\n[data-supertokens~=\"buttonWithArrow\"] [data-supertokens~=\"secondaryText\"] {\n font-weight: 700;\n font-size: var(--font-size-2);\n color: rgb(var(--palette-textGray));\n margin: 0;\n}\n[data-supertokens~=\"buttonWithArrow\"]:hover [data-supertokens~=\"secondaryLinkWithRightArrow\"] ~ svg {\n position: relative;\n left: 2px;\n}\n[data-supertokens~=\"buttonWithArrow\"]:hover [data-supertokens~=\"secondaryLinkWithLeftArrow\"] svg {\n position: relative;\n left: -2px;\n}\n[data-supertokens~=\"buttonWithArrow\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n display: flex;\n align-items: center;\n}\n"; -var ThemeBase$1 = function (_a) { - var children = _a.children, - userStyles = _a.userStyles; - return jsxRuntime.jsxs(React.Fragment, { - children: [children, jsxRuntime.jsxs("style", { children: [styles$1, userStyles.join("\n")] })], - }); +var ThemeBase$1 = function (_a) { + var children = _a.children, userStyles = _a.userStyles; + return (jsxRuntime.jsxs(React.Fragment, { children: [children, jsxRuntime.jsxs("style", { children: [styles$1, userStyles.join("\n")] })] })); }; -var MultitenancyDynamicLoginMethodsSpinnerTheme = function () { - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container delayedRender" }, - { - children: jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row" }, - { - children: jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "spinner delayedRender" }, - { children: jsxRuntime.jsx(SpinnerIcon, {}) } - ) - ), - } - ) - ), - } - ) - ); -}; -var DynamicLoginMethodsSpinnerThemeWithOverride = withOverride( - "MultitenancyDynamicLoginMethodsSpinnerTheme", - MultitenancyDynamicLoginMethodsSpinnerTheme -); -var DynamicLoginMethodsSpinnerTheme = function (props) { - var rootStyle = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().rootStyle; - return jsxRuntime.jsx( - ThemeBase$1, - genericComponentOverrideContext.__assign( - { userStyles: [rootStyle, props.config.recipeRootStyle] }, - { children: jsxRuntime.jsx(DynamicLoginMethodsSpinnerThemeWithOverride, {}) } - ) - ); +var MultitenancyDynamicLoginMethodsSpinnerTheme = function () { + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container delayedRender" }, { children: jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "row" }, { children: jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "spinner delayedRender" }, { children: jsxRuntime.jsx(SpinnerIcon, {}) })) })) }))); +}; +var DynamicLoginMethodsSpinnerThemeWithOverride = withOverride("MultitenancyDynamicLoginMethodsSpinnerTheme", MultitenancyDynamicLoginMethodsSpinnerTheme); +var DynamicLoginMethodsSpinnerTheme = function (props) { + var rootStyle = superTokens.SuperTokens.getInstanceOrThrow().rootStyle; + return (jsxRuntime.jsx(ThemeBase$1, utils.__assign({ userStyles: [rootStyle, props.config.recipeRootStyle] }, { children: jsxRuntime.jsx(DynamicLoginMethodsSpinnerThemeWithOverride, {}) }))); }; -// TODO: move this to the root components dir and rename (incl. the override) -// This is a special "feature" component: -// - it's used inside FeatureWrapper & RoutingComponent (meaning it can't use FeatureWrapper) -// - it's not used in any specific route (multitenancy doesn't have a pre-built UI) -var DynamicLoginMethodsSpinner = function () { - var recipe = genericComponentOverrideContext.Multitenancy.getInstanceOrThrow(); - var recipeComponentOverrides = componentOverrideContext.useContext(); - return jsxRuntime.jsx( - ComponentOverrideContext.Provider, - genericComponentOverrideContext.__assign( - { value: recipeComponentOverrides }, - { - children: jsxRuntime.jsx( - WithOrWithoutShadowDom, - genericComponentOverrideContext.__assign( - { useShadowDom: genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().useShadowDom }, - { children: jsxRuntime.jsx(DynamicLoginMethodsSpinnerTheme, { config: recipe.config }) } - ) - ), - } - ) - ); +// TODO: move this to the root components dir and rename (incl. the override) +// This is a special "feature" component: +// - it's used inside FeatureWrapper & RoutingComponent (meaning it can't use FeatureWrapper) +// - it's not used in any specific route (multitenancy doesn't have a pre-built UI) +var DynamicLoginMethodsSpinner = function () { + var recipe = superTokens.Multitenancy.getInstanceOrThrow(); + var recipeComponentOverrides = componentOverrideContext.useContext(); + return (jsxRuntime.jsx(ComponentOverrideContext.Provider, utils.__assign({ value: recipeComponentOverrides }, { children: jsxRuntime.jsx(WithOrWithoutShadowDom, utils.__assign({ useShadowDom: superTokens.SuperTokens.getInstanceOrThrow().useShadowDom }, { children: jsxRuntime.jsx(DynamicLoginMethodsSpinnerTheme, { config: recipe.config }) })) }))); }; -var dynamicLoginMethodsContext = React__default.default.createContext(undefined); -var useDynamicLoginMethods = function () { - var value = React__default.default.useContext(dynamicLoginMethodsContext); - if (value === undefined) { - throw new Error("useDynamicLoginMethods used outside of a valid provider (FeatureWrapper)"); - } - return value; -}; -var DynamicLoginMethodsProvider = function (_a) { - var value = _a.value, - children = _a.children; - var contextValue = value === undefined ? { loaded: false } : { loaded: true, loginMethods: value }; - return jsxRuntime.jsx( - dynamicLoginMethodsContext.Provider, - genericComponentOverrideContext.__assign({ value: contextValue }, { children: children }) - ); +var dynamicLoginMethodsContext = React__default.default.createContext(undefined); +var useDynamicLoginMethods = function () { + var value = React__default.default.useContext(dynamicLoginMethodsContext); + if (value === undefined) { + throw new Error("useDynamicLoginMethods used outside of a valid provider (FeatureWrapper)"); + } + return value; +}; +var DynamicLoginMethodsProvider = function (_a) { + var value = _a.value, children = _a.children; + var contextValue = value === undefined ? { loaded: false } : { loaded: true, loginMethods: value }; + return jsxRuntime.jsx(dynamicLoginMethodsContext.Provider, utils.__assign({ value: contextValue }, { children: children })); }; -var UserContextContext = React__default.default.createContext(undefined); -var useUserContext = function () { - return React__default.default.useContext(UserContextContext); -}; -var UserContextProvider = function (_a) { - var children = _a.children, - userContext = _a.userContext; - var currentUserContext = React.useState(genericComponentOverrideContext.getNormalisedUserContext(userContext))[0]; - return jsxRuntime.jsx( - UserContextContext.Provider, - genericComponentOverrideContext.__assign({ value: currentUserContext }, { children: children }) - ); +var UserContextContext = React__default.default.createContext(undefined); +var useUserContext = function () { + return React__default.default.useContext(UserContextContext); +}; +var UserContextProvider = function (_a) { + var children = _a.children, userContext = _a.userContext; + var currentUserContext = React.useState(utils.getNormalisedUserContext(userContext))[0]; + return jsxRuntime.jsx(UserContextContext.Provider, utils.__assign({ value: currentUserContext }, { children: children })); }; -function FeatureWrapper(_a) { - var children = _a.children, - useShadowDom = _a.useShadowDom, - defaultStore = _a.defaultStore; - var userContext = useUserContext(); - var rethrowInRender = genericComponentOverrideContext.useRethrowInRender(); - var _b = React.useState(undefined), - loadedDynamicLoginMethods = _b[0], - setLoadedDynamicLoginMethods = _b[1]; - var st = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow(); - React.useEffect( - function () { - if (loadedDynamicLoginMethods) { - return; - } - genericComponentOverrideContext.Multitenancy.getInstanceOrThrow() - .getCurrentDynamicLoginMethods({ userContext: userContext }) - .then( - function (loginMethods) { - return setLoadedDynamicLoginMethods(loginMethods); - }, - function (err) { - return rethrowInRender(err); - } - ); - }, - [loadedDynamicLoginMethods, setLoadedDynamicLoginMethods] - ); - if (genericComponentOverrideContext.SuperTokens.usesDynamicLoginMethods && !loadedDynamicLoginMethods) { - return jsxRuntime.jsx(DynamicLoginMethodsSpinner, {}); - } - return jsxRuntime.jsx( - DynamicLoginMethodsProvider, - genericComponentOverrideContext.__assign( - { value: loadedDynamicLoginMethods }, - { - children: jsxRuntime.jsx( - translationContext.TranslationContextProvider, - genericComponentOverrideContext.__assign( - { - defaultLanguage: st.languageTranslations.defaultLanguage, - defaultStore: genericComponentOverrideContext.mergeObjects( - defaultStore, - st.languageTranslations.userTranslationStore - ), - translationControlEventSource: st.languageTranslations.translationEventSource, - userTranslationFunc: st.languageTranslations.userTranslationFunc, - }, - { - children: jsxRuntime.jsx( - WithOrWithoutShadowDom, - genericComponentOverrideContext.__assign( - { useShadowDom: useShadowDom }, - { children: children } - ) - ), - } - ) - ), - } - ) - ); -} -function WithShadowDom(_a) { - var children = _a.children; - var rootDiv = React.useRef(null); - var _b = React.useState(), - shadowRoot = _b[0], - setShadowRoot = _b[1]; - React.useEffect( - function () { - if (rootDiv.current) { - // defaults from react-shadow - setShadowRoot(function (os) { - return ( - os || - rootDiv.current.shadowRoot || - rootDiv.current.attachShadow({ mode: "open", delegatesFocus: false }) - ); - }); - } - }, - [rootDiv] - ); - // Otherwise, use shadow dom. - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { id: genericComponentOverrideContext.ST_ROOT_ID, ref: rootDiv }, - { children: shadowRoot && reactDom.createPortal(children, shadowRoot) } - ) - ); -} -function WithOrWithoutShadowDom(_a) { - var children = _a.children, - useShadowDom = _a.useShadowDom; - // If explicitely specified to not use shadow dom. - if (useShadowDom === false) { - return jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { id: genericComponentOverrideContext.ST_ROOT_ID }, - { children: [children, jsxRuntime.jsx(DisableAutoFillInput, {})] } - ) - ); - } - return jsxRuntime.jsxs(WithShadowDom, { children: [children, jsxRuntime.jsx(DisableAutoFillInput, {})] }); -} -function DisableAutoFillInput() { - /* eslint-disable react/jsx-no-literals */ - return jsxRuntime.jsx( - "style", - genericComponentOverrideContext.__assign( - { type: "text/css" }, - { - children: - "input.supertokens-input:-webkit-autofill,input.supertokens-input:-webkit-autofill:focus,input.supertokens-input:-webkit-autofill:hover,select:-webkit-autofill,select:-webkit-autofill:focus,select:-webkit-autofill:hover,textarea:-webkit-autofill,textarea:-webkit-autofill:focus,textarea:-webkit-autofill:hover{transition:background-color 5000s ease-in-out 0s}", - } - ) - ); - /* eslint-enable react/jsx-no-literals */ +function FeatureWrapper(_a) { + var children = _a.children, useShadowDom = _a.useShadowDom, defaultStore = _a.defaultStore; + var userContext = useUserContext(); + var rethrowInRender = utils.useRethrowInRender(); + var _b = React.useState(undefined), loadedDynamicLoginMethods = _b[0], setLoadedDynamicLoginMethods = _b[1]; + var st = superTokens.SuperTokens.getInstanceOrThrow(); + React.useEffect(function () { + if (loadedDynamicLoginMethods) { + return; + } + superTokens.Multitenancy.getInstanceOrThrow() + .getCurrentDynamicLoginMethods({ userContext: userContext }) + .then(function (loginMethods) { return setLoadedDynamicLoginMethods(loginMethods); }, function (err) { return rethrowInRender(err); }); + }, [loadedDynamicLoginMethods, setLoadedDynamicLoginMethods]); + if (superTokens.SuperTokens.usesDynamicLoginMethods && !loadedDynamicLoginMethods) { + return jsxRuntime.jsx(DynamicLoginMethodsSpinner, {}); + } + return (jsxRuntime.jsx(DynamicLoginMethodsProvider, utils.__assign({ value: loadedDynamicLoginMethods }, { children: jsxRuntime.jsx(translationContext.TranslationContextProvider, utils.__assign({ defaultLanguage: st.languageTranslations.defaultLanguage, defaultStore: utils.mergeObjects(defaultStore, st.languageTranslations.userTranslationStore), translationControlEventSource: st.languageTranslations.translationEventSource, userTranslationFunc: st.languageTranslations.userTranslationFunc }, { children: jsxRuntime.jsx(WithOrWithoutShadowDom, utils.__assign({ useShadowDom: useShadowDom }, { children: children })) })) }))); +} +function WithShadowDom(_a) { + var children = _a.children; + var rootDiv = React.useRef(null); + var _b = React.useState(), shadowRoot = _b[0], setShadowRoot = _b[1]; + React.useEffect(function () { + if (rootDiv.current) { + // defaults from react-shadow + setShadowRoot(function (os) { + return os || + rootDiv.current.shadowRoot || + rootDiv.current.attachShadow({ mode: "open", delegatesFocus: false }); + }); + } + }, [rootDiv]); + // Otherwise, use shadow dom. + return (jsxRuntime.jsx("div", utils.__assign({ id: utils.ST_ROOT_ID, ref: rootDiv }, { children: shadowRoot && reactDom.createPortal(children, shadowRoot) }))); +} +function WithOrWithoutShadowDom(_a) { + var children = _a.children, useShadowDom = _a.useShadowDom; + // If explicitely specified to not use shadow dom. + if (useShadowDom === false) { + return (jsxRuntime.jsxs("div", utils.__assign({ id: utils.ST_ROOT_ID }, { children: [children, jsxRuntime.jsx(DisableAutoFillInput, {})] }))); + } + return (jsxRuntime.jsxs(WithShadowDom, { children: [children, jsxRuntime.jsx(DisableAutoFillInput, {})] })); +} +function DisableAutoFillInput() { + /* eslint-disable react/jsx-no-literals */ + return (jsxRuntime.jsx("style", utils.__assign({ type: "text/css" }, { children: "input.supertokens-input:-webkit-autofill,input.supertokens-input:-webkit-autofill:focus,input.supertokens-input:-webkit-autofill:hover,select:-webkit-autofill,select:-webkit-autofill:focus,select:-webkit-autofill:hover,textarea:-webkit-autofill,textarea:-webkit-autofill:focus,textarea:-webkit-autofill:hover{transition:background-color 5000s ease-in-out 0s}" }))); + /* eslint-enable react/jsx-no-literals */ } -var defaultTranslationsCommon = { - en: { - AUTH_PAGE_HEADER_TITLE_SIGN_IN_AND_UP: "Sign Up / Sign In", - AUTH_PAGE_HEADER_TITLE_SIGN_IN: "Sign In", - AUTH_PAGE_HEADER_TITLE_SIGN_UP: "Sign Up", - AUTH_PAGE_HEADER_TITLE_SIGN_IN_UP_TO_APP: " to continue to ", - AUTH_PAGE_HEADER_SUBTITLE_SIGN_IN_START: "Not registered yet?", - AUTH_PAGE_HEADER_SUBTITLE_SIGN_IN_SIGN_UP_LINK: "Sign Up", - AUTH_PAGE_HEADER_SUBTITLE_SIGN_IN_END: "", - AUTH_PAGE_HEADER_SUBTITLE_SIGN_UP_START: "Already have an account?", - AUTH_PAGE_HEADER_SUBTITLE_SIGN_UP_SIGN_IN_LINK: "Sign In", - AUTH_PAGE_HEADER_SUBTITLE_SIGN_UP_END: "", - AUTH_PAGE_FOOTER_START: "By continuing, you agree to our ", - AUTH_PAGE_FOOTER_TOS: "Terms of Service", - AUTH_PAGE_FOOTER_AND: " and ", - AUTH_PAGE_FOOTER_PP: "Privacy Policy", - AUTH_PAGE_FOOTER_END: "", - DIVIDER_OR: "or", - BRANDING_POWERED_BY_START: "Powered by ", - BRANDING_POWERED_BY_END: "", - SOMETHING_WENT_WRONG_ERROR: "Something went wrong. Please try again.", - SOMETHING_WENT_WRONG_ERROR_RELOAD: "Something went wrong. Please try again later or reload the page.", - }, +var defaultTranslationsCommon = { + en: { + AUTH_PAGE_HEADER_TITLE_SIGN_IN_AND_UP: "Sign Up / Sign In", + AUTH_PAGE_HEADER_TITLE_SIGN_IN: "Sign In", + AUTH_PAGE_HEADER_TITLE_SIGN_UP: "Sign Up", + AUTH_PAGE_HEADER_TITLE_SIGN_IN_UP_TO_APP: " to continue to ", + AUTH_PAGE_HEADER_SUBTITLE_SIGN_IN_START: "Not registered yet?", + AUTH_PAGE_HEADER_SUBTITLE_SIGN_IN_SIGN_UP_LINK: "Sign Up", + AUTH_PAGE_HEADER_SUBTITLE_SIGN_IN_END: "", + AUTH_PAGE_HEADER_SUBTITLE_SIGN_UP_START: "Already have an account?", + AUTH_PAGE_HEADER_SUBTITLE_SIGN_UP_SIGN_IN_LINK: "Sign In", + AUTH_PAGE_HEADER_SUBTITLE_SIGN_UP_END: "", + AUTH_PAGE_FOOTER_START: "By continuing, you agree to our ", + AUTH_PAGE_FOOTER_TOS: "Terms of Service", + AUTH_PAGE_FOOTER_AND: " and ", + AUTH_PAGE_FOOTER_PP: "Privacy Policy", + AUTH_PAGE_FOOTER_END: "", + DIVIDER_OR: "or", + BRANDING_POWERED_BY_START: "Powered by ", + BRANDING_POWERED_BY_END: "", + SOMETHING_WENT_WRONG_ERROR: "Something went wrong. Please try again.", + SOMETHING_WENT_WRONG_ERROR_RELOAD: "Something went wrong. Please try again later or reload the page.", + }, }; -var SessionContext = React__default.default.createContext({ - loading: true, - isDefault: true, +var SessionContext = React__default.default.createContext({ + loading: true, + isDefault: true, }); -var useSessionContext = function () { - var ctx = React__default.default.useContext(SessionContext); - if (ctx.isDefault === true) { - throw new Error("Cannot use useSessionContext outside auth wrapper components."); - } - return ctx; +var useSessionContext = function () { + var ctx = React__default.default.useContext(SessionContext); + if (ctx.isDefault === true) { + throw new Error("Cannot use useSessionContext outside auth wrapper components."); + } + return ctx; }; -var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), - useContext = _a[0], - Provider = _a[1]; +var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), useContext = _a[0], Provider = _a[1]; -function SuperTokensBranding() { - var t = translationContext.useTranslation(); - return jsxRuntime.jsxs( - "a", - genericComponentOverrideContext.__assign( - { - "data-supertokens": "superTokensBranding", - href: "https://supertokens.com?utm_campaign=poweredby", - target: "_blank", - }, - { - children: [ - t("BRANDING_POWERED_BY_START"), - jsxRuntime.jsx("strong", { children: "SuperTokens" }), - t("BRANDING_POWERED_BY_END"), - ], - } - ) - ); +function SuperTokensBranding() { + var t = translationContext.useTranslation(); + return (jsxRuntime.jsxs("a", utils.__assign({ "data-supertokens": "superTokensBranding", href: "https://supertokens.com?utm_campaign=poweredby", target: "_blank" }, { children: [t("BRANDING_POWERED_BY_START"), jsxRuntime.jsx("strong", { children: "SuperTokens" }), t("BRANDING_POWERED_BY_END")] }))); } -function UserContextWrapper(props) { - /** - * If we receive a userContext as a props we should assume that the user - * is either trying to use a theme component as standalone or that they - * want to override an existing value for userContext. - * - * In this case we should always return a Provider with the value of userContext - */ - if (props.userContext !== undefined) { - return jsxRuntime.jsx( - UserContextProvider, - genericComponentOverrideContext.__assign({ userContext: props.userContext }, { children: props.children }) - ); - } - return jsxRuntime.jsx(UserContextContext.Consumer, { - children: function (value) { - /** - * value is undefined only if there is no Provider in the tree. In this case it is safe to - * assume that the theme component is not being rendered by the SDK and that the user is not - * using this as a child of one of the pre-built feature components. - * - * In this case we return a provider so that the userContext hook can be used by the children - * of this theme component - */ - if (value === undefined) { - return jsxRuntime.jsx(UserContextProvider, { children: props.children }); - } - /** - * If value is not undefined then a provider exists in the tree. This means that this component - * is either being rendered by the SDK or the user has added it as a child of the pre-built - * feature components. In either case the userContext hook will be available so simply - * return the theme component. - */ - return props.children; - }, - }); +function UserContextWrapper(props) { + /** + * If we receive a userContext as a props we should assume that the user + * is either trying to use a theme component as standalone or that they + * want to override an existing value for userContext. + * + * In this case we should always return a Provider with the value of userContext + */ + if (props.userContext !== undefined) { + return jsxRuntime.jsx(UserContextProvider, utils.__assign({ userContext: props.userContext }, { children: props.children })); + } + return (jsxRuntime.jsx(UserContextContext.Consumer, { children: function (value) { + /** + * value is undefined only if there is no Provider in the tree. In this case it is safe to + * assume that the theme component is not being rendered by the SDK and that the user is not + * using this as a child of one of the pre-built feature components. + * + * In this case we return a provider so that the userContext hook can be used by the children + * of this theme component + */ + if (value === undefined) { + return jsxRuntime.jsx(UserContextProvider, { children: props.children }); + } + /** + * If value is not undefined then a provider exists in the tree. This means that this component + * is either being rendered by the SDK or the user has added it as a child of the pre-built + * feature components. In either case the userContext hook will be available so simply + * return the theme component. + */ + return props.children; + } })); } -function GeneralError(_a) { - var error = _a.error; - var t = translationContext.useTranslation(); - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign({ "data-supertokens": "generalError" }, { children: t(error) }) - ); +function GeneralError(_a) { + var error = _a.error; + var t = translationContext.useTranslation(); + return jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "generalError" }, { children: t(error) })); } -var styles = - '[data-supertokens~="container"] {\n --palette-background: 255, 255, 255;\n --palette-inputBackground: 250, 250, 250;\n --palette-inputBorder: 224, 224, 224;\n --palette-primary: 28, 34, 42;\n --palette-primaryBorder: 45, 54, 68;\n --palette-success: 65, 167, 0;\n --palette-successBackground: 217, 255, 191;\n --palette-error: 255, 23, 23;\n --palette-errorBackground: 255, 241, 235;\n --palette-textTitle: 0, 0, 0;\n --palette-textLabel: 0, 0, 0;\n --palette-textInput: 0, 0, 0;\n --palette-textPrimary: 128, 128, 128;\n --palette-textLink: 0, 122, 255;\n --palette-buttonText: 255, 255, 255;\n --palette-textGray: 54, 54, 54;\n --palette-superTokensBrandingBackground: 242, 245, 246;\n --palette-superTokensBrandingText: 173, 189, 196;\n --palette-buttonGreyedOut: 221, 221, 221;\n --palette-caution: 124, 96, 62;\n --palette-errorDark: 207, 54, 68;\n\n --font-size-0: 12px;\n --font-size-1: 14px;\n --font-size-2: 16px;\n --font-size-3: 19px;\n --font-size-4: 24px;\n --font-size-5: 28px;\n}\n/*\n * Default styles.\n */\n@keyframes slideTop {\n 0% {\n transform: translateY(-5px);\n }\n 100% {\n transform: translateY(0px);\n }\n}\n@keyframes swing-in-top-fwd {\n 0% {\n transform: rotateX(-100deg);\n transform-origin: top;\n opacity: 0;\n }\n 100% {\n transform: rotateX(0deg);\n transform-origin: top;\n opacity: 1;\n }\n}\n[data-supertokens~="container"] {\n font-family: "Arial", sans-serif;\n margin: 12px auto;\n margin-top: 26px;\n margin-bottom: 26px;\n width: 420px;\n text-align: center;\n border-radius: 8px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.16);\n background-color: rgb(var(--palette-background));\n}\n@media (max-width: 440px) {\n [data-supertokens~="container"] {\n width: 95vw;\n }\n}\n[data-supertokens~="row"] {\n margin: 0 auto;\n width: 76%;\n padding-top: 30px;\n padding-bottom: 10px;\n}\n[data-supertokens~="superTokensBranding"] {\n display: block;\n margin: 10px auto 0;\n background: rgb(var(--palette-superTokensBrandingBackground));\n color: rgb(var(--palette-superTokensBrandingText));\n text-decoration: none;\n width: -webkit-fit-content;\n width: fit-content;\n border-radius: 6px 6px 0 0;\n padding: 4px 9px;\n font-weight: 400;\n font-size: var(--font-size-0);\n letter-spacing: 0.4px;\n}\n[data-supertokens~="generalError"] {\n background: rgb(var(--palette-errorBackground));\n padding-top: 10px;\n padding-bottom: 10px;\n margin-bottom: 10px;\n margin-top: 24px;\n padding-left: 18px;\n padding-right: 18px;\n letter-spacing: 0.2px;\n font-size: var(--font-size-1);\n border-radius: 8px;\n color: rgb(var(--palette-error));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n word-wrap: break-word;\n}\n[data-supertokens~="headerTitle"] {\n font-size: var(--font-size-4);\n line-height: 27.6px;\n letter-spacing: 0.58px;\n font-weight: 700;\n margin-bottom: 20px;\n color: rgb(var(--palette-textTitle));\n}\n[data-supertokens~="headerSubtitle"] {\n font-weight: 400;\n color: rgb(var(--palette-textGray));\n margin-bottom: 21px;\n}\n[data-supertokens~="headerSubtitle"][data-supertokens~="secondaryText"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n}\n[data-supertokens~="privacyPolicyAndTermsAndConditions"] {\n max-width: 300px;\n margin-top: 10px;\n}\n[data-supertokens~="privacyPolicyAndTermsAndConditions"] a {\n line-height: 21px;\n}\n/* TODO: split the link style into separate things*/\n/* We add this before primary and secondary text, because if they are applied to the same element the other ones take priority */\n[data-supertokens~="link"] {\n padding-left: 3px;\n padding-right: 3px;\n color: rgb(var(--palette-textLink));\n font-size: var(--font-size-1);\n cursor: pointer;\n letter-spacing: 0.16px;\n line-height: 26px;\n}\n[data-supertokens~="primaryText"] {\n font-size: var(--font-size-2);\n font-weight: 400;\n letter-spacing: 0.4px;\n line-height: 21px;\n color: rgb(var(--palette-textLabel));\n}\n[data-supertokens~="secondaryText"] {\n font-size: var(--font-size-1);\n font-weight: 400;\n letter-spacing: 0.4px;\n color: rgb(var(--palette-textPrimary));\n}\n[data-supertokens~="secondaryText"] strong {\n font-weight: 600;\n}\n[data-supertokens~="divider"] {\n margin-top: 1.5em;\n margin-bottom: 1.5em;\n border-bottom: 0.3px solid #dddddd;\n align-items: center;\n padding-bottom: 5px;\n flex: 3 3;\n}\n[data-supertokens~="headerTinyTitle"] {\n margin-top: 24px;\n font-size: var(--font-size-5);\n letter-spacing: 1.1px;\n font-weight: 700;\n line-height: 28px;\n}\n[data-supertokens~="secondaryLinkWithArrow"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n}\n[data-supertokens~="secondaryLinkWithArrow"]:hover {\n position: relative;\n left: 2px;\n word-spacing: 4px;\n}\n[data-supertokens~="generalSuccess"] {\n color: rgb(var(--palette-success));\n font-size: var(--font-size-1);\n background: rgb(var(--palette-successBackground));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n padding: 9px 15px 9px 15px;\n border-radius: 6px;\n display: inline-block;\n}\n[data-supertokens~="spinner"] {\n width: 80px;\n height: auto;\n padding-top: 20px;\n padding-bottom: 40px;\n margin: 0 auto;\n}\n[data-supertokens~="error"] {\n color: rgb(var(--palette-error));\n}\n[data-supertokens~="linkButton"] {\n font-family: "Arial", sans-serif;\n background-color: transparent;\n border: 0;\n}\n[data-supertokens~="secondaryLinkWithLeftArrow"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n margin-top: 10px;\n margin-bottom: 40px;\n cursor: pointer;\n}\n[data-supertokens~="secondaryLinkWithLeftArrow"] svg {\n margin-right: 0.3em;\n}\n[data-supertokens~="secondaryLinkWithLeftArrow"]:hover svg {\n position: relative;\n left: -4px;\n}\n[data-supertokens~="button"] {\n font-family: "Arial", sans-serif;\n background-color: rgb(var(--palette-primary));\n color: rgb(var(--palette-buttonText));\n width: 100%;\n height: 34px;\n font-weight: 600;\n border-width: 1px;\n border-style: solid;\n border-radius: 6px;\n border-color: rgb(var(--palette-primaryBorder));\n background-position: center;\n transition: all 0.4s;\n background-size: 12000%;\n cursor: pointer;\n}\n[data-supertokens~="buttonGreyedOut"] {\n background-color: rgb(var(--palette-buttonGreyedOut));\n border-color: rgb(var(--palette-buttonGreyedOut));\n}\n[data-supertokens~="buttonWithIcon"] {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n}\n[data-supertokens~="button"]:disabled {\n border: none;\n cursor: no-drop;\n}\n[data-supertokens~="button"]:active {\n outline: none;\n transition: all 0s;\n background-size: 100%;\n filter: brightness(0.85);\n}\n[data-supertokens~="button"]:focus {\n outline: none;\n}\n[data-supertokens~="backButtonCommon"] {\n width: 16px;\n height: 13px;\n}\n[data-supertokens~="backButton"] {\n cursor: pointer;\n border: none;\n background-color: transparent;\n padding: 0px;\n}\n[data-supertokens~="backButtonPlaceholder"] {\n display: block;\n}\n[data-supertokens~="delayedRender"] {\n animation-duration: 0.1s;\n animation-name: animate-fade;\n animation-delay: 0.2s;\n animation-fill-mode: backwards;\n}\n@keyframes animate-fade {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n[data-supertokens~="footerLinkGroupVert"] {\n display: flex;\n flex-direction: column;\n margin-top: 10px;\n gap: 24px;\n}\n[data-supertokens~="footerLinkGroupVert"] > div {\n cursor: pointer;\n margin: 0;\n}\n[data-supertokens~="footerLinkGroupVert"] [data-supertokens~="secondaryText"] {\n font-weight: 400;\n}\n[data-supertokens~="footerLinkGroupVert"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n font-weight: 400;\n position: relative;\n left: -6px; /* half the width of the left arrow */\n}\n@media (max-width: 360px) {\n [data-supertokens~="footerLinkGroupVert"] {\n flex-direction: column;\n }\n [data-supertokens~="footerLinkGroupVert"] > div {\n margin: 0 auto;\n }\n}\n[data-supertokens~="footerLinkGroupVert"] div:only-child {\n margin-left: auto;\n margin-right: auto;\n margin-top: 14px;\n}\n[data-supertokens~="withBackButton"] {\n position: relative;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n[data-supertokens~="dividerWithOr"] {\n padding-top: 5px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n color: rgb(var(--palette-textPrimary));\n}\n[data-supertokens~="dividerText"] {\n flex: 1 1;\n font-weight: 400;\n font-size: var(--font-size-1);\n}\n[data-supertokens~="formLabelWithLinkWrapper"] {\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n[data-supertokens~="formLabelLinkBtn"] {\n width: auto;\n margin-top: 0;\n line-height: 24px;\n font-size: var(--font-size-0);\n}\n[data-supertokens~="formLabelLinkBtn"]:hover {\n text-decoration: underline;\n}\n[data-supertokens~="formLabelLinkBtn"]:disabled {\n color: rgb(var(--palette-textPrimary));\n cursor: default;\n text-decoration: none;\n}\n[data-supertokens~="authComponentList"] {\n padding-bottom: 20px;\n}\n[data-supertokens~="authPageTitleOAuthClient"] {\n color: rgb(var(--palette-textGray));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 10px 0 25px;\n}\n[data-supertokens~="authPageTitleOAuthClientUrl"] {\n text-decoration: none;\n}\n[data-supertokens~="authPageTitleOAuthClientLogo"] {\n width: 44px;\n height: 44px;\n margin-bottom: 10px;\n}\n[data-supertokens~="authPageTitleOAuthClient"] [data-supertokens~="authPageTitleOAuthClientName"] {\n color: rgb(var(--palette-textTitle));\n}\n[data-supertokens~="buttonWithArrow"] {\n border-radius: 6px;\n border: 1px solid #d0d5dd;\n width: 100%;\n color: rgb(var(--palette-textGray));\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n margin: 24px 0;\n min-height: 48px;\n cursor: pointer;\n}\n[data-supertokens~="buttonWithArrow"]:hover {\n background-color: rgb(var(--palette-inputBackground));\n}\n[data-supertokens~="buttonWithArrow"] [data-supertokens~="secondaryText"] {\n font-weight: 700;\n font-size: var(--font-size-2);\n color: rgb(var(--palette-textGray));\n margin: 0;\n}\n[data-supertokens~="buttonWithArrow"]:hover [data-supertokens~="secondaryLinkWithRightArrow"] ~ svg {\n position: relative;\n left: 2px;\n}\n[data-supertokens~="buttonWithArrow"]:hover [data-supertokens~="secondaryLinkWithLeftArrow"] svg {\n position: relative;\n left: -2px;\n}\n[data-supertokens~="buttonWithArrow"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n display: flex;\n align-items: center;\n}\n'; +var styles = "[data-supertokens~=\"container\"] {\n --palette-background: 255, 255, 255;\n --palette-inputBackground: 250, 250, 250;\n --palette-inputBorder: 224, 224, 224;\n --palette-primary: 28, 34, 42;\n --palette-primaryBorder: 45, 54, 68;\n --palette-success: 65, 167, 0;\n --palette-successBackground: 217, 255, 191;\n --palette-error: 255, 23, 23;\n --palette-errorBackground: 255, 241, 235;\n --palette-textTitle: 0, 0, 0;\n --palette-textLabel: 0, 0, 0;\n --palette-textInput: 0, 0, 0;\n --palette-textPrimary: 128, 128, 128;\n --palette-textLink: 0, 122, 255;\n --palette-buttonText: 255, 255, 255;\n --palette-textGray: 54, 54, 54;\n --palette-superTokensBrandingBackground: 242, 245, 246;\n --palette-superTokensBrandingText: 173, 189, 196;\n --palette-buttonGreyedOut: 221, 221, 221;\n --palette-caution: 124, 96, 62;\n --palette-errorDark: 207, 54, 68;\n\n --font-size-0: 12px;\n --font-size-1: 14px;\n --font-size-2: 16px;\n --font-size-3: 19px;\n --font-size-4: 24px;\n --font-size-5: 28px;\n}\n/*\n * Default styles.\n */\n@keyframes slideTop {\n 0% {\n transform: translateY(-5px);\n }\n 100% {\n transform: translateY(0px);\n }\n}\n@keyframes swing-in-top-fwd {\n 0% {\n transform: rotateX(-100deg);\n transform-origin: top;\n opacity: 0;\n }\n 100% {\n transform: rotateX(0deg);\n transform-origin: top;\n opacity: 1;\n }\n}\n[data-supertokens~=\"container\"] {\n font-family: \"Arial\", sans-serif;\n margin: 12px auto;\n margin-top: 26px;\n margin-bottom: 26px;\n width: 420px;\n text-align: center;\n border-radius: 8px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.16);\n background-color: rgb(var(--palette-background));\n}\n@media (max-width: 440px) {\n [data-supertokens~=\"container\"] {\n width: 95vw;\n }\n}\n[data-supertokens~=\"row\"] {\n margin: 0 auto;\n width: 76%;\n padding-top: 30px;\n padding-bottom: 10px;\n}\n[data-supertokens~=\"superTokensBranding\"] {\n display: block;\n margin: 10px auto 0;\n background: rgb(var(--palette-superTokensBrandingBackground));\n color: rgb(var(--palette-superTokensBrandingText));\n text-decoration: none;\n width: -webkit-fit-content;\n width: -moz-fit-content;\n width: fit-content;\n border-radius: 6px 6px 0 0;\n padding: 4px 9px;\n font-weight: 400;\n font-size: var(--font-size-0);\n letter-spacing: 0.4px;\n}\n[data-supertokens~=\"generalError\"] {\n background: rgb(var(--palette-errorBackground));\n padding-top: 10px;\n padding-bottom: 10px;\n margin-bottom: 10px;\n margin-top: 24px;\n padding-left: 18px;\n padding-right: 18px;\n letter-spacing: 0.2px;\n font-size: var(--font-size-1);\n border-radius: 8px;\n color: rgb(var(--palette-error));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n word-wrap: break-word;\n}\n[data-supertokens~=\"headerTitle\"] {\n font-size: var(--font-size-4);\n line-height: 27.6px;\n letter-spacing: 0.58px;\n font-weight: 700;\n margin-bottom: 20px;\n color: rgb(var(--palette-textTitle));\n}\n[data-supertokens~=\"headerSubtitle\"] {\n font-weight: 400;\n color: rgb(var(--palette-textGray));\n margin-bottom: 21px;\n}\n[data-supertokens~=\"headerSubtitle\"][data-supertokens~=\"secondaryText\"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n}\n[data-supertokens~=\"privacyPolicyAndTermsAndConditions\"] {\n max-width: 300px;\n margin-top: 10px;\n}\n[data-supertokens~=\"privacyPolicyAndTermsAndConditions\"] a {\n line-height: 21px;\n}\n/* TODO: split the link style into separate things*/\n/* We add this before primary and secondary text, because if they are applied to the same element the other ones take priority */\n[data-supertokens~=\"link\"] {\n padding-left: 3px;\n padding-right: 3px;\n color: rgb(var(--palette-textLink));\n font-size: var(--font-size-1);\n cursor: pointer;\n letter-spacing: 0.16px;\n line-height: 26px;\n}\n[data-supertokens~=\"primaryText\"] {\n font-size: var(--font-size-2);\n font-weight: 400;\n letter-spacing: 0.4px;\n line-height: 21px;\n color: rgb(var(--palette-textLabel));\n}\n[data-supertokens~=\"secondaryText\"] {\n font-size: var(--font-size-1);\n font-weight: 400;\n letter-spacing: 0.4px;\n color: rgb(var(--palette-textPrimary));\n}\n[data-supertokens~=\"secondaryText\"] strong {\n font-weight: 600;\n}\n[data-supertokens~=\"divider\"] {\n margin-top: 1.5em;\n margin-bottom: 1.5em;\n border-bottom: 0.3px solid #dddddd;\n align-items: center;\n padding-bottom: 5px;\n flex: 3 3;\n}\n[data-supertokens~=\"headerTinyTitle\"] {\n margin-top: 24px;\n font-size: var(--font-size-5);\n letter-spacing: 1.1px;\n font-weight: 700;\n line-height: 28px;\n}\n[data-supertokens~=\"secondaryLinkWithArrow\"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n}\n[data-supertokens~=\"secondaryLinkWithArrow\"]:hover {\n position: relative;\n left: 2px;\n word-spacing: 4px;\n}\n[data-supertokens~=\"generalSuccess\"] {\n color: rgb(var(--palette-success));\n font-size: var(--font-size-1);\n background: rgb(var(--palette-successBackground));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n padding: 9px 15px 9px 15px;\n border-radius: 6px;\n display: inline-block;\n}\n[data-supertokens~=\"spinner\"] {\n width: 80px;\n height: auto;\n padding-top: 20px;\n padding-bottom: 40px;\n margin: 0 auto;\n}\n[data-supertokens~=\"error\"] {\n color: rgb(var(--palette-error));\n}\n[data-supertokens~=\"linkButton\"] {\n font-family: \"Arial\", sans-serif;\n background-color: transparent;\n border: 0;\n}\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n margin-top: 10px;\n margin-bottom: 40px;\n cursor: pointer;\n}\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"] svg {\n margin-right: 0.3em;\n}\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"]:hover svg {\n position: relative;\n left: -4px;\n}\n[data-supertokens~=\"button\"] {\n font-family: \"Arial\", sans-serif;\n background-color: rgb(var(--palette-primary));\n color: rgb(var(--palette-buttonText));\n width: 100%;\n height: 34px;\n font-weight: 600;\n border-width: 1px;\n border-style: solid;\n border-radius: 6px;\n border-color: rgb(var(--palette-primaryBorder));\n background-position: center;\n transition: all 0.4s;\n background-size: 12000%;\n cursor: pointer;\n}\n[data-supertokens~=\"buttonGreyedOut\"] {\n background-color: rgb(var(--palette-buttonGreyedOut));\n border-color: rgb(var(--palette-buttonGreyedOut));\n}\n[data-supertokens~=\"buttonWithIcon\"] {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n}\n[data-supertokens~=\"button\"]:disabled {\n border: none;\n cursor: no-drop;\n}\n[data-supertokens~=\"button\"]:active {\n outline: none;\n transition: all 0s;\n background-size: 100%;\n filter: brightness(0.85);\n}\n[data-supertokens~=\"button\"]:focus {\n outline: none;\n}\n[data-supertokens~=\"backButtonCommon\"] {\n width: 16px;\n height: 13px;\n}\n[data-supertokens~=\"backButton\"] {\n cursor: pointer;\n border: none;\n background-color: transparent;\n padding: 0px;\n}\n[data-supertokens~=\"backButtonPlaceholder\"] {\n display: block;\n}\n[data-supertokens~=\"delayedRender\"] {\n animation-duration: 0.1s;\n animation-name: animate-fade;\n animation-delay: 0.2s;\n animation-fill-mode: backwards;\n}\n@keyframes animate-fade {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n[data-supertokens~=\"footerLinkGroupVert\"] {\n display: flex;\n flex-direction: column;\n margin-top: 10px;\n gap: 24px;\n}\n[data-supertokens~=\"footerLinkGroupVert\"] > div {\n cursor: pointer;\n margin: 0;\n}\n[data-supertokens~=\"footerLinkGroupVert\"] [data-supertokens~=\"secondaryText\"] {\n font-weight: 400;\n}\n[data-supertokens~=\"footerLinkGroupVert\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n font-weight: 400;\n position: relative;\n left: -6px; /* half the width of the left arrow */\n}\n@media (max-width: 360px) {\n [data-supertokens~=\"footerLinkGroupVert\"] {\n flex-direction: column;\n }\n [data-supertokens~=\"footerLinkGroupVert\"] > div {\n margin: 0 auto;\n }\n}\n[data-supertokens~=\"footerLinkGroupVert\"] div:only-child {\n margin-left: auto;\n margin-right: auto;\n margin-top: 14px;\n}\n[data-supertokens~=\"withBackButton\"] {\n position: relative;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n[data-supertokens~=\"dividerWithOr\"] {\n padding-top: 5px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n color: rgb(var(--palette-textPrimary));\n}\n[data-supertokens~=\"dividerText\"] {\n flex: 1 1;\n font-weight: 400;\n font-size: var(--font-size-1);\n}\n[data-supertokens~=\"formLabelWithLinkWrapper\"] {\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n[data-supertokens~=\"formLabelLinkBtn\"] {\n width: auto;\n margin-top: 0;\n line-height: 24px;\n font-size: var(--font-size-0);\n}\n[data-supertokens~=\"formLabelLinkBtn\"]:hover {\n text-decoration: underline;\n}\n[data-supertokens~=\"formLabelLinkBtn\"]:disabled {\n color: rgb(var(--palette-textPrimary));\n cursor: default;\n text-decoration: none;\n}\n[data-supertokens~=\"authComponentList\"] {\n padding-bottom: 20px;\n}\n[data-supertokens~=\"authPageTitleOAuthClient\"] {\n color: rgb(var(--palette-textGray));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 10px 0 25px;\n}\n[data-supertokens~=\"authPageTitleOAuthClientUrl\"] {\n text-decoration: none;\n}\n[data-supertokens~=\"authPageTitleOAuthClientLogo\"] {\n width: 44px;\n height: 44px;\n margin-bottom: 10px;\n}\n[data-supertokens~=\"authPageTitleOAuthClient\"] [data-supertokens~=\"authPageTitleOAuthClientName\"] {\n color: rgb(var(--palette-textTitle));\n}\n[data-supertokens~=\"buttonWithArrow\"] {\n border-radius: 6px;\n border: 1px solid #d0d5dd;\n width: 100%;\n color: rgb(var(--palette-textGray));\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n margin: 24px 0;\n min-height: 48px;\n cursor: pointer;\n}\n[data-supertokens~=\"buttonWithArrow\"]:hover {\n background-color: rgb(var(--palette-inputBackground));\n}\n[data-supertokens~=\"buttonWithArrow\"] [data-supertokens~=\"secondaryText\"] {\n font-weight: 700;\n font-size: var(--font-size-2);\n color: rgb(var(--palette-textGray));\n margin: 0;\n}\n[data-supertokens~=\"buttonWithArrow\"]:hover [data-supertokens~=\"secondaryLinkWithRightArrow\"] ~ svg {\n position: relative;\n left: 2px;\n}\n[data-supertokens~=\"buttonWithArrow\"]:hover [data-supertokens~=\"secondaryLinkWithLeftArrow\"] svg {\n position: relative;\n left: -2px;\n}\n[data-supertokens~=\"buttonWithArrow\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n display: flex;\n align-items: center;\n}\n"; -var ThemeBase = function (_a) { - var children = _a.children, - userStyles = _a.userStyles; - return jsxRuntime.jsxs(React.Fragment, { - children: [children, jsxRuntime.jsxs("style", { children: [styles, userStyles.join("\n")] })], - }); +var ThemeBase = function (_a) { + var children = _a.children, userStyles = _a.userStyles; + return (jsxRuntime.jsxs(React.Fragment, { children: [children, jsxRuntime.jsxs("style", { children: [styles, userStyles.join("\n")] })] })); }; -var AuthPageComponentList = withOverride("AuthPageComponentList", function AuthPageComponentList(props) { - var t = translationContext.useTranslation(); - var list = [props.authComponents[0]]; - var _loop_1 = function (i) { - list.push(function () { - return jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "dividerWithOr" }, - { - children: [ - jsxRuntime.jsx("div", { "data-supertokens": "divider" }), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "dividerText" }, - { children: t("DIVIDER_OR") } - ) - ), - jsxRuntime.jsx("div", { "data-supertokens": "divider" }), - ], - } - ), - "divider-".concat(i) - ); - }); - list.push(props.authComponents[i]); - }; - for (var i = 1; i < props.authComponents.length; ++i) { - _loop_1(i); - } - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "authComponentList" }, - { - children: list.map(function (i) { - return i(genericComponentOverrideContext.__assign({}, props)); - }), - } - ) - ); +var AuthPageComponentList = withOverride("AuthPageComponentList", function AuthPageComponentList(props) { + var t = translationContext.useTranslation(); + var list = [props.authComponents[0]]; + var _loop_1 = function (i) { + list.push(function () { return (jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "dividerWithOr" }, { children: [jsxRuntime.jsx("div", { "data-supertokens": "divider" }), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "dividerText" }, { children: t("DIVIDER_OR") })), jsxRuntime.jsx("div", { "data-supertokens": "divider" })] }), "divider-".concat(i))); }); + list.push(props.authComponents[i]); + }; + for (var i = 1; i < props.authComponents.length; ++i) { + _loop_1(i); + } + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "authComponentList" }, { children: list.map(function (i) { + return i(utils.__assign({}, props)); + }) }))); }); -var AuthPageFooter = withOverride("AuthPageFooter", function AuthPageFooter(_a) { - var hasSeparateSignUpView = _a.hasSeparateSignUpView, - isSignUp = _a.isSignUp, - termsOfServiceLink = _a.termsOfServiceLink, - privacyPolicyLink = _a.privacyPolicyLink; - var t = translationContext.useTranslation(); - if (termsOfServiceLink === undefined && privacyPolicyLink === undefined) { - return null; - } - if (hasSeparateSignUpView && !isSignUp) { - return null; - } - return jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "secondaryText privacyPolicyAndTermsAndConditions" }, - { - children: [ - t("AUTH_PAGE_FOOTER_START"), - termsOfServiceLink !== undefined && - jsxRuntime.jsx( - "a", - genericComponentOverrideContext.__assign( - { - "data-supertokens": "link", - href: termsOfServiceLink, - target: "_blank", - rel: "noopener noreferer", - }, - { children: t("AUTH_PAGE_FOOTER_TOS") } - ) - ), - termsOfServiceLink !== undefined && privacyPolicyLink !== undefined && t("AUTH_PAGE_FOOTER_AND"), - privacyPolicyLink !== undefined && - jsxRuntime.jsx( - "a", - genericComponentOverrideContext.__assign( - { - "data-supertokens": "link", - href: privacyPolicyLink, - target: "_blank", - rel: "noopener noreferer", - }, - { children: t("AUTH_PAGE_FOOTER_PP") } - ) - ), - t("AUTH_PAGE_FOOTER_END"), - ], - } - ) - ); +var AuthPageFooter = withOverride("AuthPageFooter", function AuthPageFooter(_a) { + var hasSeparateSignUpView = _a.hasSeparateSignUpView, isSignUp = _a.isSignUp, termsOfServiceLink = _a.termsOfServiceLink, privacyPolicyLink = _a.privacyPolicyLink; + var t = translationContext.useTranslation(); + if (termsOfServiceLink === undefined && privacyPolicyLink === undefined) { + return null; + } + if (hasSeparateSignUpView && !isSignUp) { + return null; + } + return (jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "secondaryText privacyPolicyAndTermsAndConditions" }, { children: [t("AUTH_PAGE_FOOTER_START"), termsOfServiceLink !== undefined && (jsxRuntime.jsx("a", utils.__assign({ "data-supertokens": "link", href: termsOfServiceLink, target: "_blank", rel: "noopener noreferer" }, { children: t("AUTH_PAGE_FOOTER_TOS") }))), termsOfServiceLink !== undefined && privacyPolicyLink !== undefined && t("AUTH_PAGE_FOOTER_AND"), privacyPolicyLink !== undefined && (jsxRuntime.jsx("a", utils.__assign({ "data-supertokens": "link", href: privacyPolicyLink, target: "_blank", rel: "noopener noreferer" }, { children: t("AUTH_PAGE_FOOTER_PP") }))), t("AUTH_PAGE_FOOTER_END")] }))); }); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Imports. - */ -/* - * Component. - */ -function HeavyArrowLeftIcon(_a) { - var color = _a.color; - return jsxRuntime.jsx( - "svg", - genericComponentOverrideContext.__assign( - { - xmlns: "http://www.w3.org/2000/svg", - width: "16", - height: "13", - viewBox: "0 0 16 13", - "data-supertokens": "heavyArrowLeftIcon", - }, - { - children: jsxRuntime.jsx("path", { - fill: color, - d: "M13 6.8h.022H3.8l2.9 2.9a.761.761 0 0 1 0 1.07l-.451.451a.754.754 0 0 1-1.064 0L.22 6.254a.759.759 0 0 1 0-1.068L5.186.22a.755.755 0 0 1 1.064 0l.45.451a.746.746 0 0 1 .22.532.724.724 0 0 1-.22.522l-2.93 2.92h9.24a.781.781 0 0 1 .764.773v.638A.766.766 0 0 1 13 6.8z", - transform: "translate(1.182 .708)", - }), - } - ) - ); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Imports. + */ +/* + * Component. + */ +function HeavyArrowLeftIcon(_a) { + var color = _a.color; + return (jsxRuntime.jsx("svg", utils.__assign({ xmlns: "http://www.w3.org/2000/svg", width: "16", height: "13", viewBox: "0 0 16 13", "data-supertokens": "heavyArrowLeftIcon" }, { children: jsxRuntime.jsx("path", { fill: color, d: "M13 6.8h.022H3.8l2.9 2.9a.761.761 0 0 1 0 1.07l-.451.451a.754.754 0 0 1-1.064 0L.22 6.254a.759.759 0 0 1 0-1.068L5.186.22a.755.755 0 0 1 1.064 0l.45.451a.746.746 0 0 1 .22.532.724.724 0 0 1-.22.522l-2.93 2.92h9.24a.781.781 0 0 1 .764.773v.638A.766.766 0 0 1 13 6.8z", transform: "translate(1.182 .708)" }) }))); } -/* - * Component. - */ -function BackButton(_a) { - var onClick = _a.onClick; - return jsxRuntime.jsx( - "button", - genericComponentOverrideContext.__assign( - { onClick: onClick, "data-supertokens": "backButton backButtonCommon" }, - { children: jsxRuntime.jsx(HeavyArrowLeftIcon, { color: "rgb(var(--palette-textTitle))" }) } - ) - ); +/* + * Component. + */ +function BackButton(_a) { + var onClick = _a.onClick; + return (jsxRuntime.jsx("button", utils.__assign({ onClick: onClick, "data-supertokens": "backButton backButtonCommon" }, { children: jsxRuntime.jsx(HeavyArrowLeftIcon, { color: "rgb(var(--palette-textTitle))" }) }))); } -var AuthPageHeader = withOverride("AuthPageHeader", function AuthPageHeader(_a) { - var onSignInUpSwitcherClick = _a.onSignInUpSwitcherClick, - hasSeparateSignUpView = _a.hasSeparateSignUpView, - isSignUp = _a.isSignUp, - showBackButton = _a.showBackButton, - resetFactorList = _a.resetFactorList, - oauth2ClientInfo = _a.oauth2ClientInfo, - headerLabel = _a.headerLabel, - _b = _a.hideSignInSwitcher, - hideSignInSwitcher = _b === void 0 ? false : _b; - var t = translationContext.useTranslation(); - return jsxRuntime.jsxs(React.Fragment, { - children: [ - (oauth2ClientInfo === null || oauth2ClientInfo === void 0 ? void 0 : oauth2ClientInfo.logoUri) && - jsxRuntime.jsx("img", { - src: oauth2ClientInfo.logoUri, - alt: oauth2ClientInfo.clientName, - "data-supertokens": "authPageTitleOAuthClientLogo", - }), - jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle withBackButton" }, - { - children: [ - showBackButton - ? jsxRuntime.jsx(BackButton, { onClick: resetFactorList }) - : jsxRuntime.jsx("span", { - "data-supertokens": "backButtonPlaceholder backButtonCommon", - }), - headerLabel !== undefined - ? t(headerLabel) - : !hasSeparateSignUpView - ? t("AUTH_PAGE_HEADER_TITLE_SIGN_IN_AND_UP") - : isSignUp - ? t("AUTH_PAGE_HEADER_TITLE_SIGN_UP") - : t("AUTH_PAGE_HEADER_TITLE_SIGN_IN"), - jsxRuntime.jsx("span", { "data-supertokens": "backButtonPlaceholder backButtonCommon" }), - ], - } - ) - ), - oauth2ClientInfo && - oauth2ClientInfo.clientName !== undefined && - oauth2ClientInfo.clientName.length > 0 && - jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "authPageTitleOAuthClient" }, - { - children: [ - t("AUTH_PAGE_HEADER_TITLE_SIGN_IN_UP_TO_APP"), - oauth2ClientInfo.clientUri !== undefined - ? jsxRuntime.jsx( - "a", - genericComponentOverrideContext.__assign( - { - "data-supertokens": "authPageTitleOAuthClientUrl link", - href: oauth2ClientInfo.clientUri, - }, - { children: oauth2ClientInfo.clientName } - ) - ) - : jsxRuntime.jsx( - "span", - genericComponentOverrideContext.__assign( - { "data-supertokens": "authPageTitleOAuthClientName" }, - { children: oauth2ClientInfo.clientName } - ) - ), - ], - } - ) - ), - !hideSignInSwitcher && - hasSeparateSignUpView && - (!isSignUp - ? jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerSubtitle secondaryText" }, - { - children: [ - t("AUTH_PAGE_HEADER_SUBTITLE_SIGN_IN_START"), - jsxRuntime.jsx( - "span", - genericComponentOverrideContext.__assign( - { "data-supertokens": "link", onClick: onSignInUpSwitcherClick }, - { children: t("AUTH_PAGE_HEADER_SUBTITLE_SIGN_IN_SIGN_UP_LINK") } - ) - ), - t("AUTH_PAGE_HEADER_SUBTITLE_SIGN_IN_END"), - ], - } - ) - ) - : jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerSubtitle secondaryText" }, - { - children: [ - t("AUTH_PAGE_HEADER_SUBTITLE_SIGN_UP_START"), - jsxRuntime.jsx( - "span", - genericComponentOverrideContext.__assign( - { "data-supertokens": "link", onClick: onSignInUpSwitcherClick }, - { children: t("AUTH_PAGE_HEADER_SUBTITLE_SIGN_UP_SIGN_IN_LINK") } - ) - ), - t("AUTH_PAGE_HEADER_SUBTITLE_SIGN_UP_END"), - ], - } - ) - )), - jsxRuntime.jsx("div", { "data-supertokens": "divider" }), - ], - }); +var AuthPageHeader = withOverride("AuthPageHeader", function AuthPageHeader(_a) { + var onSignInUpSwitcherClick = _a.onSignInUpSwitcherClick, hasSeparateSignUpView = _a.hasSeparateSignUpView, isSignUp = _a.isSignUp, showBackButton = _a.showBackButton, resetFactorList = _a.resetFactorList, oauth2ClientInfo = _a.oauth2ClientInfo, headerLabel = _a.headerLabel, _b = _a.hideSignInSwitcher, hideSignInSwitcher = _b === void 0 ? false : _b; + var t = translationContext.useTranslation(); + return (jsxRuntime.jsxs(React.Fragment, { children: [(oauth2ClientInfo === null || oauth2ClientInfo === void 0 ? void 0 : oauth2ClientInfo.logoUri) && (jsxRuntime.jsx("img", { src: oauth2ClientInfo.logoUri, alt: oauth2ClientInfo.clientName, "data-supertokens": "authPageTitleOAuthClientLogo" })), jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "headerTitle withBackButton" }, { children: [showBackButton ? (jsxRuntime.jsx(BackButton, { onClick: resetFactorList })) : (jsxRuntime.jsx("span", { "data-supertokens": "backButtonPlaceholder backButtonCommon" })), headerLabel !== undefined + ? t(headerLabel) + : !hasSeparateSignUpView + ? t("AUTH_PAGE_HEADER_TITLE_SIGN_IN_AND_UP") + : isSignUp + ? t("AUTH_PAGE_HEADER_TITLE_SIGN_UP") + : t("AUTH_PAGE_HEADER_TITLE_SIGN_IN"), jsxRuntime.jsx("span", { "data-supertokens": "backButtonPlaceholder backButtonCommon" })] })), oauth2ClientInfo && + oauth2ClientInfo.clientName !== undefined && + oauth2ClientInfo.clientName.length > 0 && (jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "authPageTitleOAuthClient" }, { children: [t("AUTH_PAGE_HEADER_TITLE_SIGN_IN_UP_TO_APP"), oauth2ClientInfo.clientUri !== undefined ? (jsxRuntime.jsx("a", utils.__assign({ "data-supertokens": "authPageTitleOAuthClientUrl link", href: oauth2ClientInfo.clientUri }, { children: oauth2ClientInfo.clientName }))) : (jsxRuntime.jsx("span", utils.__assign({ "data-supertokens": "authPageTitleOAuthClientName" }, { children: oauth2ClientInfo.clientName })))] }))), !hideSignInSwitcher && + hasSeparateSignUpView && + (!isSignUp ? (jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "headerSubtitle secondaryText" }, { children: [t("AUTH_PAGE_HEADER_SUBTITLE_SIGN_IN_START"), jsxRuntime.jsx("span", utils.__assign({ "data-supertokens": "link", onClick: onSignInUpSwitcherClick }, { children: t("AUTH_PAGE_HEADER_SUBTITLE_SIGN_IN_SIGN_UP_LINK") })), t("AUTH_PAGE_HEADER_SUBTITLE_SIGN_IN_END")] }))) : (jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "headerSubtitle secondaryText" }, { children: [t("AUTH_PAGE_HEADER_SUBTITLE_SIGN_UP_START"), jsxRuntime.jsx("span", utils.__assign({ "data-supertokens": "link", onClick: onSignInUpSwitcherClick }, { children: t("AUTH_PAGE_HEADER_SUBTITLE_SIGN_UP_SIGN_IN_LINK") })), t("AUTH_PAGE_HEADER_SUBTITLE_SIGN_UP_END")] })))), jsxRuntime.jsx("div", { "data-supertokens": "divider" })] })); }); -function AuthPageTheme(props) { - if (props.fullPageCompWithPreloadedInfo) { - return jsxRuntime.jsx(jsxRuntime.Fragment, { - children: props.fullPageCompWithPreloadedInfo.component( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, props), { - preloadInfo: props.fullPageCompWithPreloadedInfo.preloadInfo, - showBackButton: props.showBackButton, - }) - ), - }); - } - return jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { - "data-supertokens": "container authPage ".concat( - props.factorIds.length > 1 ? "multiFactor" : "singleFactor" - ), - }, - { - children: [ - jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row" }, - { - children: [ - jsxRuntime.jsx(AuthPageHeader, { - factorIds: props.factorIds, - isSignUp: props.isSignUp, - onSignInUpSwitcherClick: props.onSignInUpSwitcherClick, - hasSeparateSignUpView: props.hasSeparateSignUpView, - resetFactorList: props.resetFactorList, - showBackButton: props.showBackButton, - oauth2ClientInfo: props.oauth2ClientInfo, - }), - props.error !== undefined && jsxRuntime.jsx(GeneralError, { error: props.error }), - jsxRuntime.jsx( - AuthPageComponentList, - genericComponentOverrideContext.__assign({}, props) - ), - jsxRuntime.jsx(AuthPageFooter, { - factorIds: props.factorIds, - isSignUp: props.isSignUp, - hasSeparateSignUpView: props.hasSeparateSignUpView, - privacyPolicyLink: props.privacyPolicyLink, - termsOfServiceLink: props.termsOfServiceLink, - }), - ], - } - ) - ), - jsxRuntime.jsx(SuperTokensBranding, {}), - ], - } - ) - ); -} -function AuthPageThemeWrapper(props) { - var rootStyle = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().rootStyle; - return jsxRuntime.jsx( - UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - ThemeBase, - genericComponentOverrideContext.__assign( - { userStyles: [rootStyle] }, - { children: jsxRuntime.jsx(AuthPageTheme, genericComponentOverrideContext.__assign({}, props)) } - ) - ), - } - ) - ); +function AuthPageTheme(props) { + if (props.fullPageCompWithPreloadedInfo) { + return (jsxRuntime.jsx(jsxRuntime.Fragment, { children: props.fullPageCompWithPreloadedInfo.component(utils.__assign(utils.__assign({}, props), { preloadInfo: props.fullPageCompWithPreloadedInfo.preloadInfo, showBackButton: props.showBackButton })) })); + } + return (jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "container authPage ".concat(props.factorIds.length > 1 ? "multiFactor" : "singleFactor") }, { children: [jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "row" }, { children: [jsxRuntime.jsx(AuthPageHeader, { factorIds: props.factorIds, isSignUp: props.isSignUp, onSignInUpSwitcherClick: props.onSignInUpSwitcherClick, hasSeparateSignUpView: props.hasSeparateSignUpView, resetFactorList: props.resetFactorList, showBackButton: props.showBackButton, oauth2ClientInfo: props.oauth2ClientInfo }), props.error !== undefined && jsxRuntime.jsx(GeneralError, { error: props.error }), jsxRuntime.jsx(AuthPageComponentList, utils.__assign({}, props)), jsxRuntime.jsx(AuthPageFooter, { factorIds: props.factorIds, isSignUp: props.isSignUp, hasSeparateSignUpView: props.hasSeparateSignUpView, privacyPolicyLink: props.privacyPolicyLink, termsOfServiceLink: props.termsOfServiceLink })] })), jsxRuntime.jsx(SuperTokensBranding, {})] }))); +} +function AuthPageThemeWrapper(props) { + var rootStyle = superTokens.SuperTokens.getInstanceOrThrow().rootStyle; + return (jsxRuntime.jsx(UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(ThemeBase, utils.__assign({ userStyles: [rootStyle] }, { children: jsxRuntime.jsx(AuthPageTheme, utils.__assign({}, props)) })) }))); } -var errorQSMap = { - signin: "SOMETHING_WENT_WRONG_ERROR", - no_email_present: "THIRD_PARTY_ERROR_NO_EMAIL", - restart_link: "ERROR_SIGN_IN_UP_LINK", -}; -var AuthPageWrapper = function (props) { - var authRecipeComponentOverrides = useContext(); - return jsxRuntime.jsx( - UserContextProvider, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - SessionAuthWrapper, - genericComponentOverrideContext.__assign( - { requireAuth: false, doRedirection: false }, - { - children: jsxRuntime.jsx( - ComponentOverrideContext.Provider, - genericComponentOverrideContext.__assign( - { value: authRecipeComponentOverrides }, - { - children: jsxRuntime.jsx( - AuthPageInner, - genericComponentOverrideContext.__assign({}, props) - ), - } - ) - ), - } - ) - ), - } - ) - ); -}; -var AuthPageInner = function (props) { - var _a, _b, _c, _d, _e; - if (props.factors !== undefined && props.factors.length === 0) { - throw new Error("The factors array cannot be empty"); - } - var windowHandler$1 = windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler; - var search = new URLSearchParams(windowHandler$1.location.getSearch()); - var showStringFromQS = search.get("show"); - var isSignUpFromQS = - props.useSignUpStateFromQueryString !== true || showStringFromQS === null - ? undefined - : showStringFromQS === "signup"; - var errorFromQS = - search.get("error") !== null - ? (_b = (_a = search.get("message")) !== null && _a !== void 0 ? _a : search.get("error")) !== null && - _b !== void 0 - ? _b - : undefined - : undefined; - errorFromQS = - errorFromQS !== undefined - ? (_c = errorQSMap[errorFromQS]) !== null && _c !== void 0 - ? _c - : errorFromQS - : undefined; - var showStringFromQSRef = React.useRef(showStringFromQS); - var errorFromQSRef = React.useRef(errorFromQS); - var loginChallenge = search.get("loginChallenge"); - var forceFreshAuth = search.get("forceFreshAuth") === "true"; - var sessionContext = useSessionContext(); - var userContext = useUserContext(); - var rethrowInRender = genericComponentOverrideContext.useRethrowInRender(); - var _f = React.useState(undefined), - loadedDynamicLoginMethods = _f[0], - setLoadedDynamicLoginMethods = _f[1]; - var _g = React.useState(undefined), - oauth2ClientInfo = _g[0], - setOAuth2ClientInfo = _g[1]; - var _h = React.useState(errorFromQS), - error = _h[0], - setError = _h[1]; - var _j = React.useState(false), - sessionLoadedAndNotRedirecting = _j[0], - setSessionLoadedAndNotRedirecting = _j[1]; - var st = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow(); - var _k = React.useState(props.factors), - factorList = _k[0], - setFactorList = _k[1]; - var _l = React.useState( - (_e = (_d = props.isSignUp) !== null && _d !== void 0 ? _d : isSignUpFromQS) !== null && _e !== void 0 - ? _e - : st.defaultToSignUp - ), - isSignUp = _l[0], - setIsSignUp = _l[1]; - // We use this to signal that we need to update the components we show on screen - var _m = React.useState(0), - rebuildReqCount = _m[0], - setRebuildReqCount = _m[1]; - var lastBuild = React.useRef({ buildReq: undefined }); - React.useEffect(function () { - if (props.useSignUpStateFromQueryString && showStringFromQSRef.current !== showStringFromQS) { - var isSignUpFromQS_1 = - props.useSignUpStateFromQueryString !== true || showStringFromQS === null - ? undefined - : showStringFromQS === "signup"; - showStringFromQSRef.current = showStringFromQS; - var newIsSignUpVal = - isSignUpFromQS_1 !== null && isSignUpFromQS_1 !== void 0 ? isSignUpFromQS_1 : st.defaultToSignUp; - if (isSignUp !== newIsSignUpVal) { - setIsSignUp(newIsSignUpVal); - setRebuildReqCount(function (v) { - return v + 1; - }); - } - } - }); - React.useEffect(function () { - if (errorFromQSRef.current !== errorFromQS) { - errorFromQSRef.current = errorFromQS; - setError(errorFromQS); - } - }); - var onSignInUpSwitcherClick = React.useCallback( - function () { - if (props.useSignUpStateFromQueryString === true) { - genericComponentOverrideContext.updateQueryParam("show", isSignUp ? "signin" : "signup"); - } - setError(undefined); - setIsSignUp(!isSignUp); - setRebuildReqCount(function (v) { - return v + 1; - }); - }, - [isSignUp, setIsSignUp, setRebuildReqCount, setError, props.useSignUpStateFromQueryString] - ); - React.useEffect( - function () { - if (loadedDynamicLoginMethods) { - return; - } - genericComponentOverrideContext.Multitenancy.getInstanceOrThrow() - .getCurrentDynamicLoginMethods({ userContext: userContext }) - .then( - function (loginMethods) { - return setLoadedDynamicLoginMethods(loginMethods); - }, - function (err) { - return rethrowInRender(err); - } - ); - }, - [loadedDynamicLoginMethods, setLoadedDynamicLoginMethods] - ); - genericComponentOverrideContext.useOnMountAPICall( - function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var oauth2Recipe; - return genericComponentOverrideContext.__generator(this, function (_a) { - if (oauth2ClientInfo) { - return [2 /*return*/]; - } - oauth2Recipe = recipe.OAuth2Provider.getInstance(); - if (oauth2Recipe !== undefined && loginChallenge !== null) { - return [ - 2 /*return*/, - oauth2Recipe.webJSRecipe.getLoginChallengeInfo({ - loginChallenge: loginChallenge, - userContext: userContext, - }), - ]; - } - return [2 /*return*/, undefined]; - }); - }); - }, - function (info) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - if (info !== undefined) { - if (info.status === "OK") { - setOAuth2ClientInfo(info.info); - } else { - setError("SOMETHING_WENT_WRONG_ERROR"); - } - } - return [2 /*return*/]; - }); - }); - }, - function () { - genericComponentOverrideContext.clearQueryParams(["loginChallenge"]); - setError("SOMETHING_WENT_WRONG_ERROR"); - } - ); - React.useEffect( - function () { - if (sessionLoadedAndNotRedirecting) { - return; - } - // we want to do this just once, so we supply it with only the loading state. - // if we supply it with props, sessionContext, then once the user signs in, then this will route the - // user to the dashboard, as opposed to the sign up / sign in functions. - if (sessionContext.loading === false) { - if (sessionContext.doesSessionExist) { - if (props.onSessionAlreadyExists !== undefined) { - props.onSessionAlreadyExists(); - } else if (props.redirectOnSessionExists !== false && !forceFreshAuth) { - types.Session.getInstanceOrThrow().config.onHandleEvent({ - action: "SESSION_ALREADY_EXISTS", - }); - var oauth2Recipe_1 = recipe.OAuth2Provider.getInstance(); - if (loginChallenge !== null && oauth2Recipe_1 !== undefined) { - (function () { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var frontendRedirectTo; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - oauth2Recipe_1.webJSRecipe.getRedirectURLToContinueOAuthFlow({ - loginChallenge: loginChallenge, - userContext: userContext, - }), - ]; - case 1: - frontendRedirectTo = _a.sent().frontendRedirectTo; - return [ - 2 /*return*/, - types.Session.getInstanceOrThrow().validateGlobalClaimsAndHandleSuccessRedirection( - { - // We get here if the user was redirected to the auth screen with an already existing session - // and a loginChallenge (we check the forceFreshAuth queryparam above) - action: "SUCCESS_OAUTH2", - frontendRedirectTo: frontendRedirectTo, - // We can use these defaults, since this is not the result of a sign in/up call - createdNewUser: false, - isNewRecipeUser: false, - newSessionCreated: false, - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - recipeId: types.Session.RECIPE_ID, - }, - types.Session.RECIPE_ID, - genericComponentOverrideContext.getRedirectToPathFromURL(), - userContext, - props.navigate - ), - ]; - } - }); - }); - })().catch(rethrowInRender); - } else { - void types.Session.getInstanceOrThrow() - .validateGlobalClaimsAndHandleSuccessRedirection( - undefined, - types.Session.RECIPE_ID, - genericComponentOverrideContext.getRedirectToPathFromURL(), - userContext, - props.navigate - ) - .catch(rethrowInRender); - } - } else { - setSessionLoadedAndNotRedirecting(true); - } - } else { - setSessionLoadedAndNotRedirecting(true); - } - } - }, - [sessionContext.loading] - ); - var _o = React.useState(), - authComponentListInfo = _o[0], - setAuthComponentListInfo = _o[1]; - var showUseAnotherLink = - factorList !== undefined && - (props.factors === undefined || - props.factors.some(function (id) { - return !factorList.includes(id); - })); - var stInstance = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow(); - var privacyPolicyLink = stInstance.privacyPolicyLink; - var termsOfServiceLink = stInstance.termsOfServiceLink; - React.useEffect( - function () { - var abortCtl = new AbortController(); - if (lastBuild.current.buildReq === rebuildReqCount) { - return; - } - if ( - sessionLoadedAndNotRedirecting && - (loadedDynamicLoginMethods !== undefined || - !genericComponentOverrideContext.SuperTokens.usesDynamicLoginMethods) - ) { - void buildAndSetChildProps( - props.preBuiltUIList, - loadedDynamicLoginMethods, - userContext, - factorList, - isSignUp, - setAuthComponentListInfo, - abortCtl.signal - ).then(function () { - lastBuild.current.buildReq = rebuildReqCount; - }, rethrowInRender); - } - return function () { - abortCtl.abort(); - }; - }, - [ - sessionLoadedAndNotRedirecting, - rebuildReqCount, - setRebuildReqCount, - props.preBuiltUIList, - loadedDynamicLoginMethods, - userContext, - factorList, - isSignUp, - setAuthComponentListInfo, - rethrowInRender, - ] - ); - var onAuthSuccess = React.useCallback( - function (ctx) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var oauth2Recipe, frontendRedirectTo; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - oauth2Recipe = recipe.OAuth2Provider.getInstance(); - if (loginChallenge === null || oauth2Recipe === undefined) { - return [ - 2 /*return*/, - types.Session.getInstanceOrThrow().validateGlobalClaimsAndHandleSuccessRedirection( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, ctx), - { - action: "SUCCESS", - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - redirectToPath: - genericComponentOverrideContext.getRedirectToPathFromURL(), - } - ), - ctx.recipeId, - genericComponentOverrideContext.getRedirectToPathFromURL(), - userContext, - props.navigate - ), - ]; - } - return [ - 4 /*yield*/, - oauth2Recipe.webJSRecipe.getRedirectURLToContinueOAuthFlow({ - loginChallenge: loginChallenge, - userContext: userContext, - }), - ]; - case 1: - frontendRedirectTo = _a.sent().frontendRedirectTo; - return [ - 2 /*return*/, - types.Session.getInstanceOrThrow().validateGlobalClaimsAndHandleSuccessRedirection( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, ctx), - { - action: "SUCCESS_OAUTH2", - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - frontendRedirectTo: frontendRedirectTo, - } - ), - ctx.recipeId, - genericComponentOverrideContext.getRedirectToPathFromURL(), - userContext, - props.navigate - ), - ]; - } - }); - }); - }, - [loginChallenge] - ); - var childProps = - authComponentListInfo !== undefined && - (loginChallenge === null || oauth2ClientInfo !== undefined || recipe.OAuth2Provider.getInstance() === undefined) - ? genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, authComponentListInfo), - { - oauth2ClientInfo: oauth2ClientInfo, - onAuthSuccess: onAuthSuccess, - error: error, - onError: function (err) { - setError(err); - }, - clearError: function () { - return setError(undefined); - }, - navigate: props.navigate, - onSignInUpSwitcherClick: onSignInUpSwitcherClick, - privacyPolicyLink: privacyPolicyLink, - rebuildAuthPage: function () { - return setRebuildReqCount(function (v) { - return v + 1; - }); - }, - setFactorList: function (factorIds) { - setFactorList(factorIds); - setRebuildReqCount(function (v) { - return v + 1; - }); - }, - resetFactorList: function () { - setFactorList(props.factors); - setRebuildReqCount(function (v) { - return v + 1; - }); - }, - showBackButton: showUseAnotherLink, - termsOfServiceLink: termsOfServiceLink, - userContext: userContext, - } - ) - : undefined; - var mergedTranslations = React.useMemo( - function () { - var res = defaultTranslationsCommon; - if (authComponentListInfo !== undefined) { - for (var _i = 0, _a = props.preBuiltUIList; _i < _a.length; _i++) { - var ui = _a[_i]; - res = genericComponentOverrideContext.mergeObjects(res, ui.languageTranslations); - } - } - res = genericComponentOverrideContext.mergeObjects(res, st.languageTranslations.userTranslationStore); - return res; - }, - [st.languageTranslations.userTranslationStore, authComponentListInfo] - ); - if (childProps === undefined) { - return jsxRuntime.jsx(DynamicLoginMethodsSpinner, {}); - } else { - return jsxRuntime.jsx( - DynamicLoginMethodsProvider, - genericComponentOverrideContext.__assign( - { value: loadedDynamicLoginMethods }, - { - children: jsxRuntime.jsx( - translationContext.TranslationContextProvider, - genericComponentOverrideContext.__assign( - { - defaultLanguage: st.languageTranslations.defaultLanguage, - defaultStore: mergedTranslations, - translationControlEventSource: st.languageTranslations.translationEventSource, - userTranslationFunc: st.languageTranslations.userTranslationFunc, - }, - { - children: jsxRuntime.jsx( - WithOrWithoutShadowDom, - genericComponentOverrideContext.__assign( - { useShadowDom: st.useShadowDom }, - { - children: jsxRuntime.jsxs(React.Fragment, { - children: [ - props.children === undefined && - jsxRuntime.jsx( - AuthPageThemeWrapper, - genericComponentOverrideContext.__assign({}, childProps) - ), - props.children && - React__default.default.Children.map( - props.children, - function (child) { - if (React__default.default.isValidElement(child)) { - return React__default.default.cloneElement( - child, - childProps - ); - } - return child; - } - ), - ], - }), - } - ) - ), - } - ) - ), - } - ) - ); - } -}; -function buildAndSetChildProps( - recipeRouters, - loadedDynamicLoginMethods, - userContext, - factorListState, - isSignUpState, - setComponentListInfo, - abort -) { - var _a, _b, _c, _d, _e; - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var authRecipesInited, - firstFactors, - missingPreBuiltUIs, - thirdPartyPreBuiltUI, - hasSeparateSignUpView, - isSignUp, - authComps, - _i, - recipeRouters_1, - ui, - _f, - authComps_1, - a, - preloadRes, - partialAuthComps, - selectedComponents, - availableFactors, - _g, - partialAuthComps_1, - comp, - _h, - _j, - id, - source; - return genericComponentOverrideContext.__generator(this, function (_k) { - switch (_k.label) { - case 0: - authRecipesInited = - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().recipeList.filter(function ( - recipe - ) { - return "firstFactorIds" in recipe; - }); - firstFactors = - (_c = - (_a = - factorListState !== null && factorListState !== void 0 - ? factorListState - : loadedDynamicLoginMethods === null || loadedDynamicLoginMethods === void 0 - ? void 0 - : loadedDynamicLoginMethods.firstFactors) !== null && _a !== void 0 - ? _a - : (_b = recipe$1.MultiFactorAuth.getInstance()) === null || _b === void 0 - ? void 0 - : _b.config.firstFactors) !== null && _c !== void 0 - ? _c - : authRecipesInited.reduce(function (acc, recipe) { - return genericComponentOverrideContext.__spreadArray( - genericComponentOverrideContext.__spreadArray([], acc, true), - recipe.getFirstFactorsForAuthPage(), - true - ); - }, []); - if ( - factorListState === undefined && - (loadedDynamicLoginMethods === null || loadedDynamicLoginMethods === void 0 - ? void 0 - : loadedDynamicLoginMethods.firstFactors) === undefined && - ((_d = recipe$1.MultiFactorAuth.getInstance()) === null || _d === void 0 - ? void 0 - : _d.config.firstFactors) === undefined - ) { - missingPreBuiltUIs = authRecipesInited.filter(function (recipe) { - return !recipeRouters.some(function (router) { - return router.recipeInstance.recipeID === recipe.recipeID; - }); - }); - if (missingPreBuiltUIs.length > 0) { - // In this case we'd most likely throw anyway (except in the case of EP+Pwless), but we want to provide a better error message - throw new Error( - "Factor list not set but PreBuiltUI not added for ".concat( - missingPreBuiltUIs.map(function (r) { - return r.recipeID; - }) - ) - ); - } - } - if (firstFactors.length === 0) { - throw new Error("There are no enabled factors to show"); - } - if (firstFactors.includes(types.FactorIds.THIRDPARTY)) { - thirdPartyPreBuiltUI = recipeRouters.find(function (r) { - return r.recipeInstance.recipeID === types.FactorIds.THIRDPARTY; - }); - // here we ignore if we couldn't find the necessary prebuilt UI, because we want to throw in the standard location - if (thirdPartyPreBuiltUI !== undefined) { - // We remove the thirdparty factor if: - // We have no provider defined on the client side and - // We have no provider defined for the tenant either - if ( - thirdPartyPreBuiltUI.recipeInstance.config.signInAndUpFeature.providers.length === 0 && - (!genericComponentOverrideContext.SuperTokens.usesDynamicLoginMethods || - loadedDynamicLoginMethods.thirdparty.providers.length === 0) - ) { - firstFactors = firstFactors.filter(function (f) { - return f !== types.FactorIds.THIRDPARTY; - }); - if (firstFactors.length === 0) { - throw new Error( - "The only enabled first factor is thirdparty, but no providers were defined. Please define at least one provider." - ); - } - } - } - } - hasSeparateSignUpView = recipeRouters.some(function (ui) { - return ( - ui.requiresSignUpPage && - ui.recipeInstance.firstFactorIds.some(function (id) { - return firstFactors.includes(id); - }) - ); - }); - isSignUp = hasSeparateSignUpView && isSignUpState; - authComps = []; - for (_i = 0, recipeRouters_1 = recipeRouters; _i < recipeRouters_1.length; _i++) { - ui = recipeRouters_1[_i]; - authComps.push.apply(authComps, ui.getAuthComponents()); - } - (_f = 0), (authComps_1 = authComps); - _k.label = 1; - case 1: - if (!(_f < authComps_1.length)) return [3 /*break*/, 4]; - a = authComps_1[_f]; - if (!(a.type === "FULL_PAGE")) return [3 /*break*/, 3]; - return [4 /*yield*/, a.preloadInfoAndRunChecks(firstFactors, userContext, isSignUp)]; - case 2: - preloadRes = _k.sent(); - // We skip setting if the auth page unmounted while we were checking - // if we should show any full page comps - if (abort.aborted) { - return [2 /*return*/]; - } - if (preloadRes.shouldDisplay) { - setComponentListInfo({ - authComponents: [], - fullPageCompWithPreloadedInfo: { - component: a.component, - preloadInfo: preloadRes.preloadInfo, - }, - isSignUp: isSignUp, - hasSeparateSignUpView: hasSeparateSignUpView, - factorIds: firstFactors, - }); - return [2 /*return*/]; - } - _k.label = 3; - case 3: - _f++; - return [3 /*break*/, 1]; - case 4: - if (abort.aborted) { - // We stop if the auth page unmounted while we were checking if we should show any full page comps - return [2 /*return*/]; - } - partialAuthComps = authComps.filter(function (c) { - return ( - c.type !== "FULL_PAGE" && - c.factorIds.every(function (id) { - return firstFactors.includes(id); - }) - ); - }); - partialAuthComps = partialAuthComps.filter( - function (c) { - return ( - c.type === "SIGN_IN_UP" || // sign in+up components show in all cases - (isSignUp ? c.type === "SIGN_UP" : c.type === "SIGN_IN") - ); - } // otherwise we check if the sign up state is appropriate - ); - // We sort the auth components by the number of factors they cover, DESC - // This helps us choose combination components (ep+pwless) first - partialAuthComps.sort(function (a, b) { - return b.factorIds.length - a.factorIds.length; - }); - selectedComponents = utils.selectComponentsToCoverAllFirstFactors(partialAuthComps, firstFactors); - if (selectedComponents === undefined) { - availableFactors = new Set(); - for (_g = 0, partialAuthComps_1 = partialAuthComps; _g < partialAuthComps_1.length; _g++) { - comp = partialAuthComps_1[_g]; - for (_h = 0, _j = comp.factorIds; _h < _j.length; _h++) { - id = _j[_h]; - availableFactors.add(id); - } - } - source = - factorListState !== undefined - ? "local state or props" - : (loadedDynamicLoginMethods === null || loadedDynamicLoginMethods === void 0 - ? void 0 - : loadedDynamicLoginMethods.firstFactors) !== undefined - ? "dynamic tenant configuration" - : ((_e = recipe$1.MultiFactorAuth.getInstance()) === null || _e === void 0 - ? void 0 - : _e.config.firstFactors) !== undefined - ? "the config passed to the MFA recipe" - : "all recipes initialized"; - throw new Error( - "Couldn't cover all first factors: " - .concat(firstFactors.join(", "), " (from ") - .concat(source, "), available components: ") - .concat(Array.from(availableFactors).join(", "), ".\n") + - "You may have missed adding a recipe into the list of prebuiltUIs passed to list of prebuiltUIs passed to getSuperTokensRoutesForReactRouterDom, canHandleRoute, handleRoute functions or the AuthPage component.\n" + - "Another common error is adding a non-existent factor id into the list, e.g.: passwordless instead of otp-email/phone" - ); - } - setComponentListInfo({ - authComponents: selectedComponents - .sort(function (a, b) { - return a.displayOrder - b.displayOrder; - }) - .map(function (w) { - return w.component; - }), - factorIds: firstFactors, - hasSeparateSignUpView: hasSeparateSignUpView, - isSignUp: isSignUp, - }); - return [2 /*return*/]; - } - }); - }); +var errorQSMap = { + signin: "SOMETHING_WENT_WRONG_ERROR", + no_email_present: "THIRD_PARTY_ERROR_NO_EMAIL", + restart_link: "ERROR_SIGN_IN_UP_LINK", +}; +var AuthPageWrapper = function (props) { + var authRecipeComponentOverrides = useContext(); + return (jsxRuntime.jsx(UserContextProvider, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(SessionAuthWrapper, utils.__assign({ requireAuth: false, doRedirection: false }, { children: jsxRuntime.jsx(ComponentOverrideContext.Provider, utils.__assign({ value: authRecipeComponentOverrides }, { children: jsxRuntime.jsx(AuthPageInner, utils.__assign({}, props)) })) })) }))); +}; +var AuthPageInner = function (props) { + var _a, _b, _c, _d, _e; + if (props.factors !== undefined && props.factors.length === 0) { + throw new Error("The factors array cannot be empty"); + } + var windowHandler$1 = windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler; + var search = new URLSearchParams(windowHandler$1.location.getSearch()); + var showStringFromQS = search.get("show"); + var isSignUpFromQS = props.useSignUpStateFromQueryString !== true || showStringFromQS === null + ? undefined + : showStringFromQS === "signup"; + var errorFromQS = search.get("error") !== null ? (_b = (_a = search.get("message")) !== null && _a !== void 0 ? _a : search.get("error")) !== null && _b !== void 0 ? _b : undefined : undefined; + errorFromQS = errorFromQS !== undefined ? (_c = errorQSMap[errorFromQS]) !== null && _c !== void 0 ? _c : errorFromQS : undefined; + var showStringFromQSRef = React.useRef(showStringFromQS); + var errorFromQSRef = React.useRef(errorFromQS); + var loginChallenge = search.get("loginChallenge"); + var forceFreshAuth = search.get("forceFreshAuth") === "true"; + var sessionContext = useSessionContext(); + var userContext = useUserContext(); + var rethrowInRender = utils.useRethrowInRender(); + var _f = React.useState(undefined), loadedDynamicLoginMethods = _f[0], setLoadedDynamicLoginMethods = _f[1]; + var _g = React.useState(undefined), oauth2ClientInfo = _g[0], setOAuth2ClientInfo = _g[1]; + var _h = React.useState(errorFromQS), error = _h[0], setError = _h[1]; + var _j = React.useState(false), sessionLoadedAndNotRedirecting = _j[0], setSessionLoadedAndNotRedirecting = _j[1]; + var st = superTokens.SuperTokens.getInstanceOrThrow(); + var _k = React.useState(props.factors), factorList = _k[0], setFactorList = _k[1]; + var _l = React.useState((_e = (_d = props.isSignUp) !== null && _d !== void 0 ? _d : isSignUpFromQS) !== null && _e !== void 0 ? _e : st.defaultToSignUp), isSignUp = _l[0], setIsSignUp = _l[1]; + // We use this to signal that we need to update the components we show on screen + var _m = React.useState(0), rebuildReqCount = _m[0], setRebuildReqCount = _m[1]; + var lastBuild = React.useRef({ buildReq: undefined }); + React.useEffect(function () { + if (props.useSignUpStateFromQueryString && showStringFromQSRef.current !== showStringFromQS) { + var isSignUpFromQS_1 = props.useSignUpStateFromQueryString !== true || showStringFromQS === null + ? undefined + : showStringFromQS === "signup"; + showStringFromQSRef.current = showStringFromQS; + var newIsSignUpVal = isSignUpFromQS_1 !== null && isSignUpFromQS_1 !== void 0 ? isSignUpFromQS_1 : st.defaultToSignUp; + if (isSignUp !== newIsSignUpVal) { + setIsSignUp(newIsSignUpVal); + setRebuildReqCount(function (v) { return v + 1; }); + } + } + }); + React.useEffect(function () { + if (errorFromQSRef.current !== errorFromQS) { + errorFromQSRef.current = errorFromQS; + setError(errorFromQS); + } + }); + var onSignInUpSwitcherClick = React.useCallback(function () { + if (props.useSignUpStateFromQueryString === true) { + utils.updateQueryParam("show", isSignUp ? "signin" : "signup"); + } + setError(undefined); + setIsSignUp(!isSignUp); + setRebuildReqCount(function (v) { return v + 1; }); + }, [isSignUp, setIsSignUp, setRebuildReqCount, setError, props.useSignUpStateFromQueryString]); + React.useEffect(function () { + if (loadedDynamicLoginMethods) { + return; + } + superTokens.Multitenancy.getInstanceOrThrow() + .getCurrentDynamicLoginMethods({ userContext: userContext }) + .then(function (loginMethods) { return setLoadedDynamicLoginMethods(loginMethods); }, function (err) { return rethrowInRender(err); }); + }, [loadedDynamicLoginMethods, setLoadedDynamicLoginMethods]); + utils.useOnMountAPICall(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + var oauth2Recipe; + return utils.__generator(this, function (_a) { + if (oauth2ClientInfo) { + return [2 /*return*/]; + } + oauth2Recipe = recipe.OAuth2Provider.getInstance(); + if (oauth2Recipe !== undefined && loginChallenge !== null) { + return [2 /*return*/, oauth2Recipe.webJSRecipe.getLoginChallengeInfo({ loginChallenge: loginChallenge, userContext: userContext })]; + } + return [2 /*return*/, undefined]; + }); + }); }, function (info) { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + if (info !== undefined) { + if (info.status === "OK") { + setOAuth2ClientInfo(info.info); + } + else { + setError("SOMETHING_WENT_WRONG_ERROR"); + } + } + return [2 /*return*/]; + }); + }); }, function () { + utils.clearQueryParams(["loginChallenge"]); + setError("SOMETHING_WENT_WRONG_ERROR"); + }); + React.useEffect(function () { + if (sessionLoadedAndNotRedirecting) { + return; + } + // we want to do this just once, so we supply it with only the loading state. + // if we supply it with props, sessionContext, then once the user signs in, then this will route the + // user to the dashboard, as opposed to the sign up / sign in functions. + if (sessionContext.loading === false) { + if (sessionContext.doesSessionExist) { + if (props.onSessionAlreadyExists !== undefined) { + props.onSessionAlreadyExists(); + } + else if (props.redirectOnSessionExists !== false && !forceFreshAuth) { + types.Session.getInstanceOrThrow().config.onHandleEvent({ + action: "SESSION_ALREADY_EXISTS", + }); + var oauth2Recipe_1 = recipe.OAuth2Provider.getInstance(); + if (loginChallenge !== null && oauth2Recipe_1 !== undefined) { + (function () { + return utils.__awaiter(this, void 0, void 0, function () { + var frontendRedirectTo; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, oauth2Recipe_1.webJSRecipe.getRedirectURLToContinueOAuthFlow({ + loginChallenge: loginChallenge, + userContext: userContext, + })]; + case 1: + frontendRedirectTo = (_a.sent()).frontendRedirectTo; + return [2 /*return*/, types.Session.getInstanceOrThrow().validateGlobalClaimsAndHandleSuccessRedirection({ + // We get here if the user was redirected to the auth screen with an already existing session + // and a loginChallenge (we check the forceFreshAuth queryparam above) + action: "SUCCESS_OAUTH2", + frontendRedirectTo: frontendRedirectTo, + // We can use these defaults, since this is not the result of a sign in/up call + createdNewUser: false, + isNewRecipeUser: false, + newSessionCreated: false, + tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), + recipeId: types.Session.RECIPE_ID, + }, types.Session.RECIPE_ID, utils.getRedirectToPathFromURL(), userContext, props.navigate)]; + } + }); + }); + })().catch(rethrowInRender); + } + else { + void types.Session.getInstanceOrThrow() + .validateGlobalClaimsAndHandleSuccessRedirection(undefined, types.Session.RECIPE_ID, utils.getRedirectToPathFromURL(), userContext, props.navigate) + .catch(rethrowInRender); + } + } + else { + setSessionLoadedAndNotRedirecting(true); + } + } + else { + setSessionLoadedAndNotRedirecting(true); + } + } + }, [sessionContext.loading]); + var _o = React.useState(), authComponentListInfo = _o[0], setAuthComponentListInfo = _o[1]; + var showUseAnotherLink = factorList !== undefined && + (props.factors === undefined || props.factors.some(function (id) { return !factorList.includes(id); })); + var stInstance = superTokens.SuperTokens.getInstanceOrThrow(); + var privacyPolicyLink = stInstance.privacyPolicyLink; + var termsOfServiceLink = stInstance.termsOfServiceLink; + React.useEffect(function () { + var abortCtl = new AbortController(); + if (lastBuild.current.buildReq === rebuildReqCount) { + return; + } + if (sessionLoadedAndNotRedirecting && + (loadedDynamicLoginMethods !== undefined || !superTokens.SuperTokens.usesDynamicLoginMethods)) { + void buildAndSetChildProps(props.preBuiltUIList, loadedDynamicLoginMethods, userContext, factorList, isSignUp, setAuthComponentListInfo, abortCtl.signal).then(function () { + lastBuild.current.buildReq = rebuildReqCount; + }, rethrowInRender); + } + return function () { + abortCtl.abort(); + }; + }, [ + sessionLoadedAndNotRedirecting, + rebuildReqCount, + setRebuildReqCount, + props.preBuiltUIList, + loadedDynamicLoginMethods, + userContext, + factorList, + isSignUp, + setAuthComponentListInfo, + rethrowInRender, + ]); + var onAuthSuccess = React.useCallback(function (ctx) { return utils.__awaiter(void 0, void 0, void 0, function () { + var oauth2Recipe, frontendRedirectTo; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + oauth2Recipe = recipe.OAuth2Provider.getInstance(); + if (loginChallenge === null || oauth2Recipe === undefined) { + return [2 /*return*/, types.Session.getInstanceOrThrow().validateGlobalClaimsAndHandleSuccessRedirection(utils.__assign(utils.__assign({}, ctx), { action: "SUCCESS", tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), redirectToPath: utils.getRedirectToPathFromURL() }), ctx.recipeId, utils.getRedirectToPathFromURL(), userContext, props.navigate)]; + } + return [4 /*yield*/, oauth2Recipe.webJSRecipe.getRedirectURLToContinueOAuthFlow({ + loginChallenge: loginChallenge, + userContext: userContext, + })]; + case 1: + frontendRedirectTo = (_a.sent()).frontendRedirectTo; + return [2 /*return*/, types.Session.getInstanceOrThrow().validateGlobalClaimsAndHandleSuccessRedirection(utils.__assign(utils.__assign({}, ctx), { action: "SUCCESS_OAUTH2", tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), frontendRedirectTo: frontendRedirectTo }), ctx.recipeId, utils.getRedirectToPathFromURL(), userContext, props.navigate)]; + } + }); + }); }, [loginChallenge]); + var childProps = authComponentListInfo !== undefined && + (loginChallenge === null || oauth2ClientInfo !== undefined || recipe.OAuth2Provider.getInstance() === undefined) + ? utils.__assign(utils.__assign({}, authComponentListInfo), { oauth2ClientInfo: oauth2ClientInfo, onAuthSuccess: onAuthSuccess, error: error, onError: function (err) { + setError(err); + }, clearError: function () { return setError(undefined); }, navigate: props.navigate, onSignInUpSwitcherClick: onSignInUpSwitcherClick, privacyPolicyLink: privacyPolicyLink, rebuildAuthPage: function () { return setRebuildReqCount(function (v) { return v + 1; }); }, setFactorList: function (factorIds) { + setFactorList(factorIds); + setRebuildReqCount(function (v) { return v + 1; }); + }, resetFactorList: function () { + setFactorList(props.factors); + setRebuildReqCount(function (v) { return v + 1; }); + }, showBackButton: showUseAnotherLink, termsOfServiceLink: termsOfServiceLink, userContext: userContext }) : undefined; + var mergedTranslations = React.useMemo(function () { + var res = defaultTranslationsCommon; + if (authComponentListInfo !== undefined) { + for (var _i = 0, _a = props.preBuiltUIList; _i < _a.length; _i++) { + var ui = _a[_i]; + res = utils.mergeObjects(res, ui.languageTranslations); + } + } + res = utils.mergeObjects(res, st.languageTranslations.userTranslationStore); + return res; + }, [st.languageTranslations.userTranslationStore, authComponentListInfo]); + if (childProps === undefined) { + return jsxRuntime.jsx(DynamicLoginMethodsSpinner, {}); + } + else { + return (jsxRuntime.jsx(DynamicLoginMethodsProvider, utils.__assign({ value: loadedDynamicLoginMethods }, { children: jsxRuntime.jsx(translationContext.TranslationContextProvider, utils.__assign({ defaultLanguage: st.languageTranslations.defaultLanguage, defaultStore: mergedTranslations, translationControlEventSource: st.languageTranslations.translationEventSource, userTranslationFunc: st.languageTranslations.userTranslationFunc }, { children: jsxRuntime.jsx(WithOrWithoutShadowDom, utils.__assign({ useShadowDom: st.useShadowDom }, { children: jsxRuntime.jsxs(React.Fragment, { children: [props.children === undefined && jsxRuntime.jsx(AuthPageThemeWrapper, utils.__assign({}, childProps)), props.children && + React__default.default.Children.map(props.children, function (child) { + if (React__default.default.isValidElement(child)) { + return React__default.default.cloneElement(child, childProps); + } + return child; + })] }) })) })) }))); + } +}; +function buildAndSetChildProps(recipeRouters, loadedDynamicLoginMethods, userContext, factorListState, isSignUpState, setComponentListInfo, abort) { + var _a, _b, _c, _d, _e; + return utils.__awaiter(this, void 0, void 0, function () { + var authRecipesInited, firstFactors, missingPreBuiltUIs, thirdPartyPreBuiltUI, hasSeparateSignUpView, isSignUp, authComps, _i, recipeRouters_1, ui, _f, authComps_1, a, preloadRes, partialAuthComps, selectedComponents, availableFactors, _g, partialAuthComps_1, comp, _h, _j, id, source; + return utils.__generator(this, function (_k) { + switch (_k.label) { + case 0: + authRecipesInited = superTokens.SuperTokens.getInstanceOrThrow().recipeList.filter(function (recipe) { return "firstFactorIds" in recipe; }); + firstFactors = (_c = (_a = factorListState !== null && factorListState !== void 0 ? factorListState : loadedDynamicLoginMethods === null || loadedDynamicLoginMethods === void 0 ? void 0 : loadedDynamicLoginMethods.firstFactors) !== null && _a !== void 0 ? _a : (_b = recipe$1.MultiFactorAuth.getInstance()) === null || _b === void 0 ? void 0 : _b.config.firstFactors) !== null && _c !== void 0 ? _c : authRecipesInited.reduce(function (acc, recipe) { return utils.__spreadArray(utils.__spreadArray([], acc, true), recipe.getFirstFactorsForAuthPage(), true); }, []); + if (factorListState === undefined && + (loadedDynamicLoginMethods === null || loadedDynamicLoginMethods === void 0 ? void 0 : loadedDynamicLoginMethods.firstFactors) === undefined && + ((_d = recipe$1.MultiFactorAuth.getInstance()) === null || _d === void 0 ? void 0 : _d.config.firstFactors) === undefined) { + missingPreBuiltUIs = authRecipesInited.filter(function (recipe) { return !recipeRouters.some(function (router) { return router.recipeInstance.recipeID === recipe.recipeID; }); }); + if (missingPreBuiltUIs.length > 0) { + // In this case we'd most likely throw anyway (except in the case of EP+Pwless), but we want to provide a better error message + throw new Error("Factor list not set but PreBuiltUI not added for ".concat(missingPreBuiltUIs.map(function (r) { return r.recipeID; }))); + } + } + if (firstFactors.length === 0) { + throw new Error("There are no enabled factors to show"); + } + if (firstFactors.includes(types.FactorIds.THIRDPARTY)) { + thirdPartyPreBuiltUI = recipeRouters.find(function (r) { return r.recipeInstance.recipeID === types.FactorIds.THIRDPARTY; }); + // here we ignore if we couldn't find the necessary prebuilt UI, because we want to throw in the standard location + if (thirdPartyPreBuiltUI !== undefined) { + // We remove the thirdparty factor if: + // We have no provider defined on the client side and + // We have no provider defined for the tenant either + if (thirdPartyPreBuiltUI.recipeInstance.config.signInAndUpFeature.providers.length === 0 && + (!superTokens.SuperTokens.usesDynamicLoginMethods || loadedDynamicLoginMethods.thirdparty.providers.length === 0)) { + firstFactors = firstFactors.filter(function (f) { return f !== types.FactorIds.THIRDPARTY; }); + if (firstFactors.length === 0) { + throw new Error("The only enabled first factor is thirdparty, but no providers were defined. Please define at least one provider."); + } + } + } + } + hasSeparateSignUpView = recipeRouters.some(function (ui) { + return ui.requiresSignUpPage && + ui.recipeInstance.firstFactorIds.some(function (id) { return firstFactors.includes(id); }); + }); + isSignUp = hasSeparateSignUpView && isSignUpState; + authComps = []; + for (_i = 0, recipeRouters_1 = recipeRouters; _i < recipeRouters_1.length; _i++) { + ui = recipeRouters_1[_i]; + authComps.push.apply(authComps, ui.getAuthComponents()); + } + _f = 0, authComps_1 = authComps; + _k.label = 1; + case 1: + if (!(_f < authComps_1.length)) return [3 /*break*/, 4]; + a = authComps_1[_f]; + if (!(a.type === "FULL_PAGE")) return [3 /*break*/, 3]; + return [4 /*yield*/, a.preloadInfoAndRunChecks(firstFactors, userContext, isSignUp)]; + case 2: + preloadRes = _k.sent(); + // We skip setting if the auth page unmounted while we were checking + // if we should show any full page comps + if (abort.aborted) { + return [2 /*return*/]; + } + if (preloadRes.shouldDisplay) { + setComponentListInfo({ + authComponents: [], + fullPageCompWithPreloadedInfo: { + component: a.component, + preloadInfo: preloadRes.preloadInfo, + }, + isSignUp: isSignUp, + hasSeparateSignUpView: hasSeparateSignUpView, + factorIds: firstFactors, + }); + return [2 /*return*/]; + } + _k.label = 3; + case 3: + _f++; + return [3 /*break*/, 1]; + case 4: + if (abort.aborted) { + // We stop if the auth page unmounted while we were checking if we should show any full page comps + return [2 /*return*/]; + } + partialAuthComps = authComps.filter(function (c) { return c.type !== "FULL_PAGE" && c.factorIds.every(function (id) { return firstFactors.includes(id); }); }); + partialAuthComps = partialAuthComps.filter(function (c) { + return c.type === "SIGN_IN_UP" || // sign in+up components show in all cases + (isSignUp ? c.type === "SIGN_UP" : c.type === "SIGN_IN"); + } // otherwise we check if the sign up state is appropriate + ); + // We sort the auth components by the number of factors they cover, DESC + // This helps us choose combination components (ep+pwless) first + partialAuthComps.sort(function (a, b) { return b.factorIds.length - a.factorIds.length; }); + selectedComponents = utils$1.selectComponentsToCoverAllFirstFactors(partialAuthComps, firstFactors); + if (selectedComponents === undefined) { + availableFactors = new Set(); + for (_g = 0, partialAuthComps_1 = partialAuthComps; _g < partialAuthComps_1.length; _g++) { + comp = partialAuthComps_1[_g]; + for (_h = 0, _j = comp.factorIds; _h < _j.length; _h++) { + id = _j[_h]; + availableFactors.add(id); + } + } + source = factorListState !== undefined + ? "local state or props" + : (loadedDynamicLoginMethods === null || loadedDynamicLoginMethods === void 0 ? void 0 : loadedDynamicLoginMethods.firstFactors) !== undefined + ? "dynamic tenant configuration" + : ((_e = recipe$1.MultiFactorAuth.getInstance()) === null || _e === void 0 ? void 0 : _e.config.firstFactors) !== undefined + ? "the config passed to the MFA recipe" + : "all recipes initialized"; + throw new Error("Couldn't cover all first factors: ".concat(firstFactors.join(", "), " (from ").concat(source, "), available components: ").concat(Array.from(availableFactors).join(", "), ".\n") + + "You may have missed adding a recipe into the list of prebuiltUIs passed to list of prebuiltUIs passed to getSuperTokensRoutesForReactRouterDom, canHandleRoute, handleRoute functions or the AuthPage component.\n" + + "Another common error is adding a non-existent factor id into the list, e.g.: passwordless instead of otp-email/phone"); + } + setComponentListInfo({ + authComponents: selectedComponents.sort(function (a, b) { return a.displayOrder - b.displayOrder; }).map(function (w) { return w.component; }), + factorIds: firstFactors, + hasSeparateSignUpView: hasSeparateSignUpView, + isSignUp: isSignUp, + }); + return [2 /*return*/]; + } + }); + }); } -// The related ADR: https://supertokens.com/docs/contribute/decisions/multitenancy/0006 -var priorityOrder = [ - { - rid: "thirdpartyemailpassword", - includes: ["thirdparty", "emailpassword"], - factorsProvided: [types.FactorIds.THIRDPARTY, types.FactorIds.EMAILPASSWORD], - }, - { - rid: "thirdpartypasswordless", - includes: ["thirdparty", "passwordless"], - factorsProvided: [ - types.FactorIds.THIRDPARTY, - types.FactorIds.OTP_PHONE, - types.FactorIds.OTP_EMAIL, - types.FactorIds.LINK_PHONE, - types.FactorIds.LINK_EMAIL, - ], - }, - { rid: "emailpassword", includes: ["emailpassword"], factorsProvided: [types.FactorIds.EMAILPASSWORD] }, - { - rid: "passwordless", - includes: ["passwordless"], - factorsProvided: [ - types.FactorIds.OTP_PHONE, - types.FactorIds.OTP_EMAIL, - types.FactorIds.LINK_PHONE, - types.FactorIds.LINK_EMAIL, - ], - }, - { rid: "thirdparty", includes: ["thirdparty"], factorsProvided: [types.FactorIds.THIRDPARTY] }, -]; -function chooseComponentBasedOnFirstFactors(firstFactors, routeComponents) { - var fallbackRid; - var fallbackComponent; - var _loop_1 = function (rid, factorsProvided) { - if ( - firstFactors.every(function (factor) { - return factorsProvided.includes(factor); - }) - ) { - var matchingComp = routeComponents.find(function (comp) { - return comp.recipeID === rid; - }); - if (matchingComp) { - fallbackRid = rid; - fallbackComponent = matchingComp; - if (firstFactors.length === factorsProvided.length) { - genericComponentOverrideContext.logDebugMessage( - "Rendering ".concat(rid, " because it matches factors: ").concat(firstFactors, " exactly") - ); - return { value: matchingComp }; - } - } - } - }; - // We first try to find an exact match, and fall back on something that covers all factors (but maybe more) - /* - Examples: - 1. firstFactors: emailpassword, route components from: thirdparty -> - - no matches found, throwing error +// The related ADR: https://supertokens.com/docs/contribute/decisions/multitenancy/0006 +var priorityOrder = [ + { + rid: "thirdpartyemailpassword", + includes: ["thirdparty", "emailpassword"], + factorsProvided: [types.FactorIds.THIRDPARTY, types.FactorIds.EMAILPASSWORD], + }, + { + rid: "thirdpartypasswordless", + includes: ["thirdparty", "passwordless"], + factorsProvided: [ + types.FactorIds.THIRDPARTY, + types.FactorIds.OTP_PHONE, + types.FactorIds.OTP_EMAIL, + types.FactorIds.LINK_PHONE, + types.FactorIds.LINK_EMAIL, + ], + }, + { rid: "emailpassword", includes: ["emailpassword"], factorsProvided: [types.FactorIds.EMAILPASSWORD] }, + { + rid: "passwordless", + includes: ["passwordless"], + factorsProvided: [types.FactorIds.OTP_PHONE, types.FactorIds.OTP_EMAIL, types.FactorIds.LINK_PHONE, types.FactorIds.LINK_EMAIL], + }, + { rid: "thirdparty", includes: ["thirdparty"], factorsProvided: [types.FactorIds.THIRDPARTY] }, +]; +function chooseComponentBasedOnFirstFactors(firstFactors, routeComponents) { + var fallbackRid; + var fallbackComponent; + var _loop_1 = function (rid, factorsProvided) { + if (firstFactors.every(function (factor) { return factorsProvided.includes(factor); })) { + var matchingComp = routeComponents.find(function (comp) { return comp.recipeID === rid; }); + if (matchingComp) { + fallbackRid = rid; + fallbackComponent = matchingComp; + if (firstFactors.length === factorsProvided.length) { + utils.logDebugMessage("Rendering ".concat(rid, " because it matches factors: ").concat(firstFactors, " exactly")); + return { value: matchingComp }; + } + } + } + }; + // We first try to find an exact match, and fall back on something that covers all factors (but maybe more) + /* + Examples: + 1. firstFactors: emailpassword, route components from: thirdparty -> + - no matches found, throwing error - 2. firstFactors: emailpassword, route components from: thirdpartyemailpassword -> - - we find thirdpartyemailpassword covers all first factors, save it as fallback - - we check all other recipes, bot nothing else has matching components - - return fallback from TPEP + 2. firstFactors: emailpassword, route components from: thirdpartyemailpassword -> + - we find thirdpartyemailpassword covers all first factors, save it as fallback + - we check all other recipes, bot nothing else has matching components + - return fallback from TPEP - 3. firstFactors: emailpassword, route components from: thirdpartyemailpassword, emailpassword -> - - we find thirdpartyemailpassword covers all first factors, save it as fallback - - we find emailpassword as an exact match and return it + 3. firstFactors: emailpassword, route components from: thirdpartyemailpassword, emailpassword -> + - we find thirdpartyemailpassword covers all first factors, save it as fallback + - we find emailpassword as an exact match and return it - 4. firstFactors: otp-phone, route components from: thirdpartypasswordless, passwordless, thirdparty -> - - we find thirdpartypasswordless covers all first factors (but more), save it as fallback - - we find passwordless that covers all factors (but more), saving it as a fallback. - Keep in mind, that the passwordless and thirdpartypasswordless recipe provides 4 factors, so this is not an exact match. - - no other recipes have matching components, so we return the fallback from passwordless + 4. firstFactors: otp-phone, route components from: thirdpartypasswordless, passwordless, thirdparty -> + - we find thirdpartypasswordless covers all first factors (but more), save it as fallback + - we find passwordless that covers all factors (but more), saving it as a fallback. + Keep in mind, that the passwordless and thirdpartypasswordless recipe provides 4 factors, so this is not an exact match. + - no other recipes have matching components, so we return the fallback from passwordless - 5. firstFactors: thirdparty, otp-phone, route components from: thirdpartypasswordless, passwordless, thirdparty -> - - we find thirdpartypasswordless covers all first factors (but more), save it as fallback - this is not an exact match, because thirdpartypasswordless provides multiple passwordless factors. - - no other recipes cover all factors, so we return the fallback from thirdpartypasswordless - */ - for (var _i = 0, priorityOrder_1 = priorityOrder; _i < priorityOrder_1.length; _i++) { - var _a = priorityOrder_1[_i], - rid = _a.rid, - factorsProvided = _a.factorsProvided; - var state_1 = _loop_1(rid, factorsProvided); - if (typeof state_1 === "object") return state_1.value; - } - if (fallbackComponent !== undefined) { - genericComponentOverrideContext.logDebugMessage( - "Rendering ".concat(fallbackRid, " to cover ").concat(firstFactors, " as a fallback") - ); - return fallbackComponent; - } - // We may get here if: - // - The backend/tenantconfig is older and didn't have the firstFactors array defined - // - There is a configuration error - // We choose not to throw in the configuration error case because: - // - we can't tell these cases apart after the firstFactors array was made a requrired prop - // - we want to maintain backwards compatbility - // Here we replicate the old logic we had before the firstFactors array - var enabledLoginMethods = []; - if (firstFactors.includes(types.FactorIds.EMAILPASSWORD)) { - enabledLoginMethods.push("emailpassword"); - } - if (firstFactors.includes(types.FactorIds.THIRDPARTY)) { - enabledLoginMethods.push("thirdparty"); - } - if ( - [ - types.FactorIds.OTP_PHONE, - types.FactorIds.OTP_EMAIL, - types.FactorIds.LINK_PHONE, - types.FactorIds.LINK_EMAIL, - ].some(function (pwlessFactorId) { - return firstFactors.includes(pwlessFactorId); - }) - ) { - enabledLoginMethods.push("passwordless"); - } - genericComponentOverrideContext.logDebugMessage( - "Choosing component using fallback logic w/ ".concat(enabledLoginMethods.join(", "), " enabled") - ); - var enabledRecipeCount = enabledLoginMethods.length; - var _loop_2 = function (rid, includes) { - if ( - enabledRecipeCount === includes.length && - includes.every(function (subRId) { - return enabledLoginMethods.includes(subRId); - }) - ) { - var matchingComp = routeComponents.find(function (comp) { - return comp.recipeID === rid; - }); - if (matchingComp) { - return { value: matchingComp }; - } - } - }; - // We try and choose which component to show based on the enabled login methods - // We first try to find an exact match (a recipe that covers all enabled login methods and nothing else) - for (var _b = 0, priorityOrder_2 = priorityOrder; _b < priorityOrder_2.length; _b++) { - var _c = priorityOrder_2[_b], - rid = _c.rid, - includes = _c.includes; - var state_2 = _loop_2(rid, includes); - if (typeof state_2 === "object") return state_2.value; - } - var _loop_3 = function (rid, includes) { - if ( - includes.some(function (subRId) { - return enabledLoginMethods.includes(subRId); - }) - ) { - var matchingComp = routeComponents.find(function (comp) { - return comp.recipeID === rid; - }); - if (matchingComp) { - return { value: matchingComp }; - } - } - }; - // We try to find a partial match (so any recipe that overlaps with the enabled login methods) - for (var _d = 0, priorityOrder_3 = priorityOrder; _d < priorityOrder_3.length; _d++) { - var _e = priorityOrder_3[_d], - rid = _e.rid, - includes = _e.includes; - var state_3 = _loop_3(rid, includes); - if (typeof state_3 === "object") return state_3.value; - } - throw new Error("No enabled recipes overlap with the requested firstFactors: " + firstFactors); -} -var RecipeRouter = /** @class */ (function () { - function RecipeRouter() { - var _this = this; - this.getPathsToFeatureComponentWithRecipeIdMap = function () { - // Memoized version of the map. - if (_this.pathsToFeatureComponentWithRecipeIdMap !== undefined) { - return _this.pathsToFeatureComponentWithRecipeIdMap; - } - var pathsToFeatureComponentWithRecipeIdMap = {}; - var features = _this.getFeatures(); - var featurePaths = Object.keys(features); - for (var j = 0; j < featurePaths.length; j++) { - // If no components yet for this route, initialize empty array. - var featurePath = featurePaths[j]; - if (pathsToFeatureComponentWithRecipeIdMap[featurePath] === undefined) { - pathsToFeatureComponentWithRecipeIdMap[featurePath] = []; - } - pathsToFeatureComponentWithRecipeIdMap[featurePath].push(features[featurePath]); - } - _this.pathsToFeatureComponentWithRecipeIdMap = pathsToFeatureComponentWithRecipeIdMap; - return _this.pathsToFeatureComponentWithRecipeIdMap; - }; - this.requiresSignUpPage = false; - } - RecipeRouter.getMatchingComponentForRouteAndRecipeIdFromPreBuiltUIList = function ( - normalisedUrl, - preBuiltUIList, - defaultToStaticList, - dynamicLoginMethods - ) { - var path = normalisedUrl.getAsStringDangerous(); - // We check if we are on the auth page to later see if we should take first factors into account. - var isAuthPage = - path === - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().appInfo.websiteBasePath.getAsStringDangerous(); - // We get all components that can handle the current path - var routeComponents = preBuiltUIList.reduce(function (components, c) { - var routes = c.getPathsToFeatureComponentWithRecipeIdMap(); - var _loop_4 = function (routePath, routeComps) { - if ( - routePath === path || - new RegExp("^" + routePath.replace(/:\w+/g, "[^/]+").replace(/\/\*/g, "/[^/]+") + "$").test(path) - ) { - components = components.concat( - routeComps.map(function (c) { - return { comp: c, route: routePath }; - }) - ); - } - }; - for (var _i = 0, _a = Object.entries(routes); _i < _a.length; _i++) { - var _b = _a[_i], - routePath = _b[0], - routeComps = _b[1]; - _loop_4(routePath, routeComps); - } - return components; - }, []); - // We check the query params to see if any recipe was requested by id - var componentMatchingRid = routeComponents.find(function (c) { - return c.comp.matches(); - }); - // We default to to one requested by id or the first in the list - // i.e.: the first prebuilt ui in the list the user provided that can handle this route. - var defaultComp; - if (routeComponents.length === 0) { - defaultComp = undefined; - } else if (componentMatchingRid !== undefined) { - defaultComp = componentMatchingRid.comp; - } else { - defaultComp = routeComponents[0].comp; - } - // We check if any non-auth recipe (emailverification, totp) can handle this - // There should be no overlap between the routes handled by those and the auth recipes - // so if there is a match we can return early - var matchingNonAuthComponent = routeComponents.find(function (comp) { - var ridlist = priorityOrder.map(function (a) { - return a.rid; - }); - return ( - !ridlist.includes(comp.comp.recipeID) || - comp.route !== - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().appInfo.websiteBasePath.getAsStringDangerous() - ); - }); - if (matchingNonAuthComponent) { - return matchingNonAuthComponent.comp; - } - // We use this option in `canHandleRoute`, because it may be called by custom UIs before - // dynamic login methods are loaded. - if (defaultToStaticList) { - return defaultComp; - } - var mfaRecipe = recipe$1.MultiFactorAuth.getInstance(); - if (genericComponentOverrideContext.SuperTokens.usesDynamicLoginMethods === false) { - // If we are not using dynamic login methods, we can use the rid requested by the app - if (componentMatchingRid) { - return componentMatchingRid.comp; - } - // if we have a static firstFactors config we take it into account on the auth page - // Other pages shouldn't care about this configuration. - // Embedded components are not affected, since this is only called by the routing component. - if (isAuthPage && mfaRecipe && mfaRecipe.config.firstFactors !== undefined) { - return chooseComponentBasedOnFirstFactors( - mfaRecipe.config.firstFactors, - routeComponents.map(function (c) { - return c.comp; - }) - ); - } else { - return defaultComp; - } - } - if (dynamicLoginMethods === undefined) { - throw new Error( - "Should never come here: dynamic login methods info has not been loaded but recipeRouter rendered" - ); - } - // If we are using dynamic login methods, we check that the requested rid belongs to an enabled recipe - if ( - componentMatchingRid && // if we find a component matching by rid - (!priorityOrder - .map(function (a) { - return a.rid; - }) - .includes(componentMatchingRid.comp.recipeID) || // from a non-auth recipe - priorityOrder.some(function (a) { - return ( - a.rid === componentMatchingRid.comp.recipeID && - a.factorsProvided.some(function (factorId) { - return dynamicLoginMethods.firstFactors.includes(factorId); - }) - ); - })) // or an enabled auth recipe - ) { - return componentMatchingRid.comp; - } - // if we have a firstFactors config for the tenant we take it into account on the auth page - // Other pages shouldn't care about this configuration. - // Embedded components are not affected, since this is only called by the routing component. - if (isAuthPage) { - return chooseComponentBasedOnFirstFactors( - dynamicLoginMethods.firstFactors, - routeComponents.map(function (c) { - return c.comp; - }) - ); - } - return undefined; - }; - return RecipeRouter; -})(); + 5. firstFactors: thirdparty, otp-phone, route components from: thirdpartypasswordless, passwordless, thirdparty -> + - we find thirdpartypasswordless covers all first factors (but more), save it as fallback + this is not an exact match, because thirdpartypasswordless provides multiple passwordless factors. + - no other recipes cover all factors, so we return the fallback from thirdpartypasswordless + */ + for (var _i = 0, priorityOrder_1 = priorityOrder; _i < priorityOrder_1.length; _i++) { + var _a = priorityOrder_1[_i], rid = _a.rid, factorsProvided = _a.factorsProvided; + var state_1 = _loop_1(rid, factorsProvided); + if (typeof state_1 === "object") + return state_1.value; + } + if (fallbackComponent !== undefined) { + utils.logDebugMessage("Rendering ".concat(fallbackRid, " to cover ").concat(firstFactors, " as a fallback")); + return fallbackComponent; + } + // We may get here if: + // - The backend/tenantconfig is older and didn't have the firstFactors array defined + // - There is a configuration error + // We choose not to throw in the configuration error case because: + // - we can't tell these cases apart after the firstFactors array was made a requrired prop + // - we want to maintain backwards compatbility + // Here we replicate the old logic we had before the firstFactors array + var enabledLoginMethods = []; + if (firstFactors.includes(types.FactorIds.EMAILPASSWORD)) { + enabledLoginMethods.push("emailpassword"); + } + if (firstFactors.includes(types.FactorIds.THIRDPARTY)) { + enabledLoginMethods.push("thirdparty"); + } + if ([types.FactorIds.OTP_PHONE, types.FactorIds.OTP_EMAIL, types.FactorIds.LINK_PHONE, types.FactorIds.LINK_EMAIL].some(function (pwlessFactorId) { + return firstFactors.includes(pwlessFactorId); + })) { + enabledLoginMethods.push("passwordless"); + } + utils.logDebugMessage("Choosing component using fallback logic w/ ".concat(enabledLoginMethods.join(", "), " enabled")); + var enabledRecipeCount = enabledLoginMethods.length; + var _loop_2 = function (rid, includes) { + if (enabledRecipeCount === includes.length && + includes.every(function (subRId) { return enabledLoginMethods.includes(subRId); })) { + var matchingComp = routeComponents.find(function (comp) { return comp.recipeID === rid; }); + if (matchingComp) { + return { value: matchingComp }; + } + } + }; + // We try and choose which component to show based on the enabled login methods + // We first try to find an exact match (a recipe that covers all enabled login methods and nothing else) + for (var _b = 0, priorityOrder_2 = priorityOrder; _b < priorityOrder_2.length; _b++) { + var _c = priorityOrder_2[_b], rid = _c.rid, includes = _c.includes; + var state_2 = _loop_2(rid, includes); + if (typeof state_2 === "object") + return state_2.value; + } + var _loop_3 = function (rid, includes) { + if (includes.some(function (subRId) { return enabledLoginMethods.includes(subRId); })) { + var matchingComp = routeComponents.find(function (comp) { return comp.recipeID === rid; }); + if (matchingComp) { + return { value: matchingComp }; + } + } + }; + // We try to find a partial match (so any recipe that overlaps with the enabled login methods) + for (var _d = 0, priorityOrder_3 = priorityOrder; _d < priorityOrder_3.length; _d++) { + var _e = priorityOrder_3[_d], rid = _e.rid, includes = _e.includes; + var state_3 = _loop_3(rid, includes); + if (typeof state_3 === "object") + return state_3.value; + } + throw new Error("No enabled recipes overlap with the requested firstFactors: " + firstFactors); +} +var RecipeRouter = /** @class */ (function () { + function RecipeRouter() { + var _this = this; + this.getPathsToFeatureComponentWithRecipeIdMap = function () { + // Memoized version of the map. + if (_this.pathsToFeatureComponentWithRecipeIdMap !== undefined) { + return _this.pathsToFeatureComponentWithRecipeIdMap; + } + var pathsToFeatureComponentWithRecipeIdMap = {}; + var features = _this.getFeatures(); + var featurePaths = Object.keys(features); + for (var j = 0; j < featurePaths.length; j++) { + // If no components yet for this route, initialize empty array. + var featurePath = featurePaths[j]; + if (pathsToFeatureComponentWithRecipeIdMap[featurePath] === undefined) { + pathsToFeatureComponentWithRecipeIdMap[featurePath] = []; + } + pathsToFeatureComponentWithRecipeIdMap[featurePath].push(features[featurePath]); + } + _this.pathsToFeatureComponentWithRecipeIdMap = pathsToFeatureComponentWithRecipeIdMap; + return _this.pathsToFeatureComponentWithRecipeIdMap; + }; + this.requiresSignUpPage = false; + } + RecipeRouter.getMatchingComponentForRouteAndRecipeIdFromPreBuiltUIList = function (normalisedUrl, preBuiltUIList, defaultToStaticList, dynamicLoginMethods) { + var path = normalisedUrl.getAsStringDangerous(); + // We check if we are on the auth page to later see if we should take first factors into account. + var isAuthPage = path === superTokens.SuperTokens.getInstanceOrThrow().appInfo.websiteBasePath.getAsStringDangerous(); + // We get all components that can handle the current path + var routeComponents = preBuiltUIList.reduce(function (components, c) { + var routes = c.getPathsToFeatureComponentWithRecipeIdMap(); + var _loop_4 = function (routePath, routeComps) { + if (routePath === path || + new RegExp("^" + routePath.replace(/:\w+/g, "[^/]+").replace(/\/\*/g, "/[^/]+") + "$").test(path)) { + components = components.concat(routeComps.map(function (c) { + return { comp: c, route: routePath }; + })); + } + }; + for (var _i = 0, _a = Object.entries(routes); _i < _a.length; _i++) { + var _b = _a[_i], routePath = _b[0], routeComps = _b[1]; + _loop_4(routePath, routeComps); + } + return components; + }, []); + // We check the query params to see if any recipe was requested by id + var componentMatchingRid = routeComponents.find(function (c) { return c.comp.matches(); }); + // We default to to one requested by id or the first in the list + // i.e.: the first prebuilt ui in the list the user provided that can handle this route. + var defaultComp; + if (routeComponents.length === 0) { + defaultComp = undefined; + } + else if (componentMatchingRid !== undefined) { + defaultComp = componentMatchingRid.comp; + } + else { + defaultComp = routeComponents[0].comp; + } + // We check if any non-auth recipe (emailverification, totp) can handle this + // There should be no overlap between the routes handled by those and the auth recipes + // so if there is a match we can return early + var matchingNonAuthComponent = routeComponents.find(function (comp) { + var ridlist = priorityOrder.map(function (a) { return a.rid; }); + return (!ridlist.includes(comp.comp.recipeID) || + comp.route !== superTokens.SuperTokens.getInstanceOrThrow().appInfo.websiteBasePath.getAsStringDangerous()); + }); + if (matchingNonAuthComponent) { + return matchingNonAuthComponent.comp; + } + // We use this option in `canHandleRoute`, because it may be called by custom UIs before + // dynamic login methods are loaded. + if (defaultToStaticList) { + return defaultComp; + } + var mfaRecipe = recipe$1.MultiFactorAuth.getInstance(); + if (superTokens.SuperTokens.usesDynamicLoginMethods === false) { + // If we are not using dynamic login methods, we can use the rid requested by the app + if (componentMatchingRid) { + return componentMatchingRid.comp; + } + // if we have a static firstFactors config we take it into account on the auth page + // Other pages shouldn't care about this configuration. + // Embedded components are not affected, since this is only called by the routing component. + if (isAuthPage && mfaRecipe && mfaRecipe.config.firstFactors !== undefined) { + return chooseComponentBasedOnFirstFactors(mfaRecipe.config.firstFactors, routeComponents.map(function (c) { return c.comp; })); + } + else { + return defaultComp; + } + } + if (dynamicLoginMethods === undefined) { + throw new Error("Should never come here: dynamic login methods info has not been loaded but recipeRouter rendered"); + } + // If we are using dynamic login methods, we check that the requested rid belongs to an enabled recipe + if (componentMatchingRid && // if we find a component matching by rid + (!priorityOrder.map(function (a) { return a.rid; }).includes(componentMatchingRid.comp.recipeID) || // from a non-auth recipe + priorityOrder.some(function (a) { + return a.rid === componentMatchingRid.comp.recipeID && + a.factorsProvided.some(function (factorId) { return dynamicLoginMethods.firstFactors.includes(factorId); }); + })) // or an enabled auth recipe + ) { + return componentMatchingRid.comp; + } + // if we have a firstFactors config for the tenant we take it into account on the auth page + // Other pages shouldn't care about this configuration. + // Embedded components are not affected, since this is only called by the routing component. + if (isAuthPage) { + return chooseComponentBasedOnFirstFactors(dynamicLoginMethods.firstFactors, routeComponents.map(function (c) { return c.comp; })); + } + return undefined; + }; + return RecipeRouter; +}()); -function RoutingComponent(props) { - var _a, _b; - var userContext = useUserContext(); - var rethrowInRender = genericComponentOverrideContext.useRethrowInRender(); - var _c = React.useState(undefined), - loadedDynamicLoginMethods = _c[0], - setLoadedDynamicLoginMethods = _c[1]; - var navigate = - (_a = props.getReactRouterDomWithCustomHistory()) === null || _a === void 0 ? void 0 : _a.useHistoryCustom(); - var path = props.path; - var isAuthPage = - path === - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().appInfo.websiteBasePath.getAsStringDangerous(); - var location = - (_b = props.getReactRouterDomWithCustomHistory()) === null || _b === void 0 ? void 0 : _b.useLocation(); - var componentToRender = React__default.default.useMemo( - function () { - if (isAuthPage) { - return; - } - var normalizedPath = new NormalisedURLPath__default.default(path); - // During development, this runs twice so as to warn devs of if there - // are any side effects that happen here. So in tests, it will result in - // the console log twice - if ( - loadedDynamicLoginMethods !== undefined || - genericComponentOverrideContext.SuperTokens.usesDynamicLoginMethods === false - ) { - var result = RecipeRouter.getMatchingComponentForRouteAndRecipeIdFromPreBuiltUIList( - normalizedPath, - props.preBuiltUIList, - false, - loadedDynamicLoginMethods - ); - if ( - result === undefined && - genericComponentOverrideContext.SuperTokens.usesDynamicLoginMethods === true - ) { - void redirectToAuth({ navigate: navigate, redirectBack: false }); - } - return result; - } - return undefined; - // location dependency needs to be kept in order to get new component on url change - // eslint-disable-next-line react-hooks/exhaustive-deps - }, - [path, location, loadedDynamicLoginMethods, props.preBuiltUIList] - ); - React.useEffect( - function () { - if (loadedDynamicLoginMethods) { - return; - } - genericComponentOverrideContext.Multitenancy.getInstanceOrThrow() - .getCurrentDynamicLoginMethods({ userContext: userContext }) - .then( - function (loginMethods) { - return setLoadedDynamicLoginMethods(loginMethods); - }, - function (err) { - return rethrowInRender(err); - } - ); - }, - [loadedDynamicLoginMethods, setLoadedDynamicLoginMethods] - ); - if (isAuthPage) { - return jsxRuntime.jsx(AuthPageWrapper, { - preBuiltUIList: props.preBuiltUIList, - navigate: navigate, - useSignUpStateFromQueryString: true, - }); - } - if ( - genericComponentOverrideContext.SuperTokens.usesDynamicLoginMethods && - loadedDynamicLoginMethods === undefined - ) { - return jsxRuntime.jsx(DynamicLoginMethodsSpinner, {}); - } - if ( - componentToRender === undefined || - (loadedDynamicLoginMethods === undefined && genericComponentOverrideContext.SuperTokens.usesDynamicLoginMethods) - ) { - return null; - } - return jsxRuntime.jsx(componentToRender.component, { navigate: navigate }); +function RoutingComponent(props) { + var _a, _b; + var userContext = useUserContext(); + var rethrowInRender = utils.useRethrowInRender(); + var _c = React.useState(undefined), loadedDynamicLoginMethods = _c[0], setLoadedDynamicLoginMethods = _c[1]; + var navigate = (_a = props.getReactRouterDomWithCustomHistory()) === null || _a === void 0 ? void 0 : _a.useHistoryCustom(); + var path = props.path; + var isAuthPage = path === superTokens.SuperTokens.getInstanceOrThrow().appInfo.websiteBasePath.getAsStringDangerous(); + var location = (_b = props.getReactRouterDomWithCustomHistory()) === null || _b === void 0 ? void 0 : _b.useLocation(); + var componentToRender = React__default.default.useMemo(function () { + if (isAuthPage) { + return; + } + var normalizedPath = new NormalisedURLPath__default.default(path); + // During development, this runs twice so as to warn devs of if there + // are any side effects that happen here. So in tests, it will result in + // the console log twice + if (loadedDynamicLoginMethods !== undefined || superTokens.SuperTokens.usesDynamicLoginMethods === false) { + var result = RecipeRouter.getMatchingComponentForRouteAndRecipeIdFromPreBuiltUIList(normalizedPath, props.preBuiltUIList, false, loadedDynamicLoginMethods); + if (result === undefined && superTokens.SuperTokens.usesDynamicLoginMethods === true) { + void redirectToAuth({ navigate: navigate, redirectBack: false }); + } + return result; + } + return undefined; + // location dependency needs to be kept in order to get new component on url change + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [path, location, loadedDynamicLoginMethods, props.preBuiltUIList]); + React.useEffect(function () { + if (loadedDynamicLoginMethods) { + return; + } + superTokens.Multitenancy.getInstanceOrThrow() + .getCurrentDynamicLoginMethods({ userContext: userContext }) + .then(function (loginMethods) { return setLoadedDynamicLoginMethods(loginMethods); }, function (err) { return rethrowInRender(err); }); + }, [loadedDynamicLoginMethods, setLoadedDynamicLoginMethods]); + if (isAuthPage) { + return (jsxRuntime.jsx(AuthPageWrapper, { preBuiltUIList: props.preBuiltUIList, navigate: navigate, useSignUpStateFromQueryString: true })); + } + if (superTokens.SuperTokens.usesDynamicLoginMethods && loadedDynamicLoginMethods === undefined) { + return jsxRuntime.jsx(DynamicLoginMethodsSpinner, {}); + } + if (componentToRender === undefined || + (loadedDynamicLoginMethods === undefined && superTokens.SuperTokens.usesDynamicLoginMethods)) { + return null; + } + return jsxRuntime.jsx(componentToRender.component, { navigate: navigate }); } -/* - * Component. - */ -function getSuperTokensRoutesForReactRouterDom$1(_a) { - var getReactRouterDomWithCustomHistory = _a.getReactRouterDomWithCustomHistory, - recipeList = _a.recipeList, - basePath = _a.basePath; - var routerInfo = getReactRouterDomWithCustomHistory(); - if (routerInfo === undefined) { - return []; - } - var Route = routerInfo.router.Route; - var routes = Object.values( - recipeList.reduce(function (routes, recipe) { - var pathsToFeatureComponentWithRecipeIdMap = recipe.getPathsToFeatureComponentWithRecipeIdMap(); - Object.keys(pathsToFeatureComponentWithRecipeIdMap).forEach(function (path) { - path = path === "" ? "/" : path; - var pathForRouter = getPathForRouter$1(basePath, path); - if (!(path in routes)) { - routes[path] = jsxRuntime.jsx( - Route, - genericComponentOverrideContext.__assign( - { exact: true, path: pathForRouter }, - { - children: jsxRuntime.jsx(RoutingComponent, { - getReactRouterDomWithCustomHistory: getReactRouterDomWithCustomHistory, - preBuiltUIList: recipeList, - path: path, - }), - } - ), - "st-".concat(path) - ); - } - }); - return routes; - }, {}) - ); - if ( - !genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().disableAuthRoute && - recipeList.some(function (ui) { - return ui.getAuthComponents().length !== 0; - }) - ) { - var path = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow() - .appInfo.websiteBasePath.appendPath(new NormalisedURLPath__default$1.default("/")) - .getAsStringDangerous(); - routes.push( - jsxRuntime.jsx( - Route, - genericComponentOverrideContext.__assign( - { exact: true, path: getPathForRouter$1(basePath, path) }, - { - children: jsxRuntime.jsx(RoutingComponent, { - getReactRouterDomWithCustomHistory: getReactRouterDomWithCustomHistory, - preBuiltUIList: recipeList, - path: path, - }), - } - ), - "st-/auth" - ) - ); - } - return routes; -} -function getPathForRouter$1(basePath, path) { - var pathForRouter = path; - if (basePath !== undefined) { - if (pathForRouter.startsWith(basePath)) { - pathForRouter = pathForRouter.slice(basePath.length); - if (!pathForRouter.startsWith("/")) { - pathForRouter = "/" + pathForRouter; - } - } else { - throw new Error("basePath has to be a prefix of websiteBasePath passed to SuperTokens.init"); - } - } - return pathForRouter; +/* + * Component. + */ +function getSuperTokensRoutesForReactRouterDom$1(_a) { + var getReactRouterDomWithCustomHistory = _a.getReactRouterDomWithCustomHistory, recipeList = _a.recipeList, basePath = _a.basePath; + var routerInfo = getReactRouterDomWithCustomHistory(); + if (routerInfo === undefined) { + return []; + } + var Route = routerInfo.router.Route; + var routes = Object.values(recipeList.reduce(function (routes, recipe) { + var pathsToFeatureComponentWithRecipeIdMap = recipe.getPathsToFeatureComponentWithRecipeIdMap(); + Object.keys(pathsToFeatureComponentWithRecipeIdMap).forEach(function (path) { + path = path === "" ? "/" : path; + var pathForRouter = getPathForRouter$1(basePath, path); + if (!(path in routes)) { + routes[path] = (jsxRuntime.jsx(Route, utils.__assign({ exact: true, path: pathForRouter }, { children: jsxRuntime.jsx(RoutingComponent, { getReactRouterDomWithCustomHistory: getReactRouterDomWithCustomHistory, preBuiltUIList: recipeList, path: path }) }), "st-".concat(path))); + } + }); + return routes; + }, {})); + if (!superTokens.SuperTokens.getInstanceOrThrow().disableAuthRoute && + recipeList.some(function (ui) { return ui.getAuthComponents().length !== 0; })) { + var path = superTokens.SuperTokens.getInstanceOrThrow() + .appInfo.websiteBasePath.appendPath(new NormalisedURLPath__default$1.default("/")) + .getAsStringDangerous(); + routes.push(jsxRuntime.jsx(Route, utils.__assign({ exact: true, path: getPathForRouter$1(basePath, path) }, { children: jsxRuntime.jsx(RoutingComponent, { getReactRouterDomWithCustomHistory: getReactRouterDomWithCustomHistory, preBuiltUIList: recipeList, path: path }) }), "st-/auth")); + } + return routes; +} +function getPathForRouter$1(basePath, path) { + var pathForRouter = path; + if (basePath !== undefined) { + if (pathForRouter.startsWith(basePath)) { + pathForRouter = pathForRouter.slice(basePath.length); + if (!pathForRouter.startsWith("/")) { + pathForRouter = "/" + pathForRouter; + } + } + else { + throw new Error("basePath has to be a prefix of websiteBasePath passed to SuperTokens.init"); + } + } + return pathForRouter; } -/* - * Component. - */ -function getSuperTokensRoutesForReactRouterDomV6(_a) { - var getReactRouterDomWithCustomHistory = _a.getReactRouterDomWithCustomHistory, - recipeList = _a.recipeList, - basePath = _a.basePath; - var routerInfo = getReactRouterDomWithCustomHistory(); - if (routerInfo === undefined) { - return []; - } - var Route = routerInfo.router.Route; - var routes = Object.values( - recipeList.reduce(function (routes, recipe) { - var pathsToFeatureComponentWithRecipeIdMap = recipe.getPathsToFeatureComponentWithRecipeIdMap(); - Object.keys(pathsToFeatureComponentWithRecipeIdMap).forEach(function (path) { - path = path === "" ? "/" : path; - var pathForRouter = getPathForRouter(basePath, path); - if (!(path in routes)) { - routes[path] = jsxRuntime.jsx( - Route, - { - path: pathForRouter, - element: jsxRuntime.jsx(RoutingComponent, { - getReactRouterDomWithCustomHistory: getReactRouterDomWithCustomHistory, - preBuiltUIList: recipeList, - path: path, - }), - }, - "st-".concat(path) - ); - } - }); - return routes; - }, {}) - ); - if ( - !genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().disableAuthRoute && - recipeList.some(function (ui) { - return ui.getAuthComponents().length !== 0; - }) - ) { - var path = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow() - .appInfo.websiteBasePath.appendPath(new NormalisedURLPath__default$1.default("/")) - .getAsStringDangerous(); - routes.push( - jsxRuntime.jsx( - Route, - { - path: getPathForRouter(basePath, path), - element: jsxRuntime.jsx(RoutingComponent, { - getReactRouterDomWithCustomHistory: getReactRouterDomWithCustomHistory, - preBuiltUIList: recipeList, - path: path, - }), - }, - "st-/auth" - ) - ); - } - return routes; -} -function getPathForRouter(basePath, path) { - if (basePath !== undefined) { - if (path.startsWith(basePath)) { - path = path.slice(basePath.length); - if (!path.startsWith("/")) { - path = "/" + path; - } - } else { - throw new Error("basePath has to be a prefix of websiteBasePath passed to SuperTokens.init"); - } - } - return path; +/* + * Component. + */ +function getSuperTokensRoutesForReactRouterDomV6(_a) { + var getReactRouterDomWithCustomHistory = _a.getReactRouterDomWithCustomHistory, recipeList = _a.recipeList, basePath = _a.basePath; + var routerInfo = getReactRouterDomWithCustomHistory(); + if (routerInfo === undefined) { + return []; + } + var Route = routerInfo.router.Route; + var routes = Object.values(recipeList.reduce(function (routes, recipe) { + var pathsToFeatureComponentWithRecipeIdMap = recipe.getPathsToFeatureComponentWithRecipeIdMap(); + Object.keys(pathsToFeatureComponentWithRecipeIdMap).forEach(function (path) { + path = path === "" ? "/" : path; + var pathForRouter = getPathForRouter(basePath, path); + if (!(path in routes)) { + routes[path] = (jsxRuntime.jsx(Route, { path: pathForRouter, element: jsxRuntime.jsx(RoutingComponent, { getReactRouterDomWithCustomHistory: getReactRouterDomWithCustomHistory, preBuiltUIList: recipeList, path: path }) }, "st-".concat(path))); + } + }); + return routes; + }, {})); + if (!superTokens.SuperTokens.getInstanceOrThrow().disableAuthRoute && + recipeList.some(function (ui) { return ui.getAuthComponents().length !== 0; })) { + var path = superTokens.SuperTokens.getInstanceOrThrow() + .appInfo.websiteBasePath.appendPath(new NormalisedURLPath__default$1.default("/")) + .getAsStringDangerous(); + routes.push(jsxRuntime.jsx(Route, { path: getPathForRouter(basePath, path), element: jsxRuntime.jsx(RoutingComponent, { getReactRouterDomWithCustomHistory: getReactRouterDomWithCustomHistory, preBuiltUIList: recipeList, path: path }) }, "st-/auth")); + } + return routes; +} +function getPathForRouter(basePath, path) { + if (basePath !== undefined) { + if (path.startsWith(basePath)) { + path = path.slice(basePath.length); + if (!path.startsWith("/")) { + path = "/" + path; + } + } + else { + throw new Error("basePath has to be a prefix of websiteBasePath passed to SuperTokens.init"); + } + } + return path; } -var UI = /** @class */ (function () { - function UI() {} - UI.getSuperTokensRoutesForReactRouterDom = function (reactRouterDom, preBuiltUiClassList, basePath) { - if (preBuiltUiClassList === void 0) { - preBuiltUiClassList = []; - } - if (reactRouterDom === undefined || preBuiltUiClassList.length === 0) { - throw new Error( - // eslint-disable-next-line @typescript-eslint/quotes - 'Please use getSuperTokensRoutesForReactRouterDom like getSuperTokensRoutesForReactRouterDom(require("react-router-dom"), [EmailPasswordPreBuiltUI]) in your render function' - ); - } - var recipeList = preBuiltUiClassList.map(function (r) { - return r.getInstanceOrInitAndGetInstance(); - }); - if (UI.reactRouterDomIsV6 === undefined) { - UI.reactRouterDomIsV6 = reactRouterDom.withRouter === undefined; - } - if (UI.reactRouterDomIsV6) { - if (UI.reactRouterDom === undefined) { - // this function wraps the react-router-dom v6 useNavigate function in a way - // that enforces that it runs within a useEffect. The reason we do this is - // cause of https://github.com/remix-run/react-router/issues/7460 - // which gets shown when visiting a social auth callback url like - // /auth/callback/github, without a valid code or state. This then - // doesn't navigate the user to the auth page. - var useNavigateHookForRRDV6 = function () { - var navigateHook = reactRouterDom.useNavigate(); - var _a = React__default.default.useState(undefined), - to = _a[0], - setTo = _a[1]; - React__default.default.useEffect( - function () { - if (to !== undefined) { - setTo(undefined); - navigateHook(to); - } - }, - [to, navigateHook, setTo] - ); - return setTo; - }; - UI.reactRouterDom = { - router: reactRouterDom, - useHistoryCustom: useNavigateHookForRRDV6, - useLocation: reactRouterDom.useLocation, - }; - } - return getSuperTokensRoutesForReactRouterDomV6({ - getReactRouterDomWithCustomHistory: UI.getReactRouterDomWithCustomHistory, - recipeList: recipeList, - basePath: basePath, - }); - } - if (UI.reactRouterDom === undefined) { - UI.reactRouterDom = { - router: reactRouterDom, - useHistoryCustom: reactRouterDom.useHistory, - useLocation: reactRouterDom.useLocation, - }; - } - return getSuperTokensRoutesForReactRouterDom$1({ - getReactRouterDomWithCustomHistory: UI.getReactRouterDomWithCustomHistory, - recipeList: recipeList, - basePath: basePath, - }); - }; - UI.canHandleRoute = function (preBuiltUiClassList) { - var recipeList = preBuiltUiClassList.map(function (r) { - return r.getInstanceOrInitAndGetInstance(); - }); - var path = genericComponentOverrideContext.getCurrentNormalisedUrlPath().getAsStringDangerous(); - var isAuthPage = - path === - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().appInfo.websiteBasePath.getAsStringDangerous(); - if (isAuthPage) { - return !genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().disableAuthRoute; - } - return ( - RecipeRouter.getMatchingComponentForRouteAndRecipeIdFromPreBuiltUIList( - genericComponentOverrideContext.getCurrentNormalisedUrlPath(), - recipeList, - true - ) !== undefined - ); - }; - UI.getRoutingComponent = function (preBuiltUiClassList) { - var recipeList = preBuiltUiClassList.map(function (r) { - return r.getInstanceOrInitAndGetInstance(); - }); - return jsxRuntime.jsx(RoutingComponent, { - getReactRouterDomWithCustomHistory: UI.getReactRouterDomWithCustomHistory, - path: genericComponentOverrideContext.getCurrentNormalisedUrlPath().getAsStringDangerous(), - preBuiltUIList: recipeList, - }); - }; - UI.getReactRouterDomWithCustomHistory = function () { - return UI.reactRouterDom; - }; - UI.AuthPage = function (props) { - return jsxRuntime.jsx( - AuthPageWrapper, - genericComponentOverrideContext.__assign({}, props, { - preBuiltUIList: props.preBuiltUIList.map(function (r) { - return r.getInstanceOrInitAndGetInstance(); - }), - }) - ); - }; - UI.AuthPageTheme = AuthPageTheme; - UI.AuthPageFooter = AuthPageFooter; - UI.AuthPageHeader = AuthPageHeader; - UI.AuthPageComponentList = AuthPageComponentList; - UI.AuthRecipeComponentsOverrideContextProvider = Provider; - return UI; -})(); -var getSuperTokensRoutesForReactRouterDom = UI.getSuperTokensRoutesForReactRouterDom; -var canHandleRoute = UI.canHandleRoute; -var getRoutingComponent = UI.getRoutingComponent; +var UI = /** @class */ (function () { + function UI() { + } + UI.getSuperTokensRoutesForReactRouterDom = function (reactRouterDom, preBuiltUiClassList, basePath) { + if (preBuiltUiClassList === void 0) { preBuiltUiClassList = []; } + if (reactRouterDom === undefined || preBuiltUiClassList.length === 0) { + throw new Error( + // eslint-disable-next-line @typescript-eslint/quotes + 'Please use getSuperTokensRoutesForReactRouterDom like getSuperTokensRoutesForReactRouterDom(require("react-router-dom"), [EmailPasswordPreBuiltUI]) in your render function'); + } + var recipeList = preBuiltUiClassList.map(function (r) { return r.getInstanceOrInitAndGetInstance(); }); + if (UI.reactRouterDomIsV6 === undefined) { + UI.reactRouterDomIsV6 = reactRouterDom.withRouter === undefined; + } + if (UI.reactRouterDomIsV6) { + if (UI.reactRouterDom === undefined) { + // this function wraps the react-router-dom v6 useNavigate function in a way + // that enforces that it runs within a useEffect. The reason we do this is + // cause of https://github.com/remix-run/react-router/issues/7460 + // which gets shown when visiting a social auth callback url like + // /auth/callback/github, without a valid code or state. This then + // doesn't navigate the user to the auth page. + var useNavigateHookForRRDV6 = function () { + var navigateHook = reactRouterDom.useNavigate(); + var _a = React__default.default.useState(undefined), to = _a[0], setTo = _a[1]; + React__default.default.useEffect(function () { + if (to !== undefined) { + setTo(undefined); + navigateHook(to); + } + }, [to, navigateHook, setTo]); + return setTo; + }; + UI.reactRouterDom = { + router: reactRouterDom, + useHistoryCustom: useNavigateHookForRRDV6, + useLocation: reactRouterDom.useLocation, + }; + } + return getSuperTokensRoutesForReactRouterDomV6({ + getReactRouterDomWithCustomHistory: UI.getReactRouterDomWithCustomHistory, + recipeList: recipeList, + basePath: basePath, + }); + } + if (UI.reactRouterDom === undefined) { + UI.reactRouterDom = { + router: reactRouterDom, + useHistoryCustom: reactRouterDom.useHistory, + useLocation: reactRouterDom.useLocation, + }; + } + return getSuperTokensRoutesForReactRouterDom$1({ + getReactRouterDomWithCustomHistory: UI.getReactRouterDomWithCustomHistory, + recipeList: recipeList, + basePath: basePath, + }); + }; + UI.canHandleRoute = function (preBuiltUiClassList) { + var recipeList = preBuiltUiClassList.map(function (r) { return r.getInstanceOrInitAndGetInstance(); }); + var path = utils.getCurrentNormalisedUrlPath().getAsStringDangerous(); + var isAuthPage = path === superTokens.SuperTokens.getInstanceOrThrow().appInfo.websiteBasePath.getAsStringDangerous(); + if (isAuthPage) { + return !superTokens.SuperTokens.getInstanceOrThrow().disableAuthRoute; + } + return (RecipeRouter.getMatchingComponentForRouteAndRecipeIdFromPreBuiltUIList(utils.getCurrentNormalisedUrlPath(), recipeList, true) !== undefined); + }; + UI.getRoutingComponent = function (preBuiltUiClassList) { + var recipeList = preBuiltUiClassList.map(function (r) { return r.getInstanceOrInitAndGetInstance(); }); + return (jsxRuntime.jsx(RoutingComponent, { getReactRouterDomWithCustomHistory: UI.getReactRouterDomWithCustomHistory, path: utils.getCurrentNormalisedUrlPath().getAsStringDangerous(), preBuiltUIList: recipeList })); + }; + UI.getReactRouterDomWithCustomHistory = function () { + return UI.reactRouterDom; + }; + UI.AuthPage = function (props) { return (jsxRuntime.jsx(AuthPageWrapper, utils.__assign({}, props, { preBuiltUIList: props.preBuiltUIList.map(function (r) { return r.getInstanceOrInitAndGetInstance(); }) }))); }; + UI.AuthPageTheme = AuthPageTheme; + UI.AuthPageFooter = AuthPageFooter; + UI.AuthPageHeader = AuthPageHeader; + UI.AuthPageComponentList = AuthPageComponentList; + UI.AuthRecipeComponentsOverrideContextProvider = Provider; + return UI; +}()); +var getSuperTokensRoutesForReactRouterDom = UI.getSuperTokensRoutesForReactRouterDom; +var canHandleRoute = UI.canHandleRoute; +var getRoutingComponent = UI.getRoutingComponent; var AuthPage = UI.AuthPage; -var SessionAuth = function (_a) { - var _b; - var children = _a.children, - props = genericComponentOverrideContext.__rest(_a, ["children"]); - var requireAuth = React.useRef(props.requireAuth); - if (props.requireAuth !== requireAuth.current) { - throw new Error( - // eslint-disable-next-line @typescript-eslint/quotes - 'requireAuth prop should not change. If you are seeing this, it probably means that you are using SessionAuth in multiple routes with different values for requireAuth. To solve this, try adding the "key" prop to all uses of SessionAuth like ' - ); - } - // Reusing the parent context was removed because it caused a redirect loop in an edge case - // because it'd also reuse the invalid claims part until it loaded. - var _c = React.useState({ loading: true }), - context = _c[0], - setContext = _c[1]; - var setContextIfChanged = React.useCallback( - function (newValue) { - setContext(function (oldValue) { - // We can't do this check before re-validation because there are be validators that depend on the current time - // Since the context is constructed by the same functions the property order should be stable, meaning that - // a simple JSON string check should be sufficient. - // Plus since this is just an optimization it is fine to have false positives, - // and this method won't have false negatives (where we'd miss an update). - if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) { - return newValue; - } - return oldValue; - }); - }, - [setContext] - ); - var session = React.useRef(); - // We store this here, to prevent the list of called hooks changing even if a navigate hook is added later to SuperTokens. - var navigateHookRef = React.useRef( - (_b = UI.getReactRouterDomWithCustomHistory()) === null || _b === void 0 ? void 0 : _b.useHistoryCustom - ); - var navigate; - try { - if (navigateHookRef.current) { - navigate = navigateHookRef.current(); - } - } catch (_d) { - // We catch and ignore errors here, because this is may throw if - // the app is using react-router-dom but added a session auth outside of the router. - } - var userContext = useUserContext(); - var rethrowInRender = genericComponentOverrideContext.useRethrowInRender(); - var redirectToLogin = React.useCallback(function () { - void genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToAuth({ - navigate: navigate, - userContext: userContext, - redirectBack: true, - }); - }, []); - var buildContext = React.useCallback(function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var sessionExists, invalidClaims, err_1, err_2; - var _a; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (session.current === undefined) { - session.current = types.Session.getInstanceOrThrow(); - } - return [ - 4 /*yield*/, - session.current.doesSessionExist({ - userContext: userContext, - }), - ]; - case 1: - sessionExists = _b.sent(); - if (sessionExists === false) { - return [ - 2 /*return*/, - { - loading: false, - doesSessionExist: false, - accessTokenPayload: {}, - invalidClaims: [], - userId: "", - }, - ]; - } - _b.label = 2; - case 2: - _b.trys.push([2, 4, , 6]); - return [ - 4 /*yield*/, - session.current.validateClaims({ - overrideGlobalClaimValidators: props.overrideGlobalClaimValidators, - userContext: userContext, - }), - ]; - case 3: - invalidClaims = _b.sent(); - return [3 /*break*/, 6]; - case 4: - err_1 = _b.sent(); - return [ - 4 /*yield*/, - session.current.doesSessionExist({ - userContext: userContext, - }), - ]; - case 5: - // These errors should only come from getAccessTokenPayloadSecurely inside validateClaims if refreshing a claim cleared the session - // Which means that the session was most likely cleared, meaning returning false is right. - // This might also happen if the user provides an override or a custom claim validator that throws (or if we have a bug) - // In which case the session will not be cleared so we rethrow the error - if (_b.sent()) { - throw err_1; - } - return [ - 2 /*return*/, - { - loading: false, - doesSessionExist: false, - accessTokenPayload: {}, - invalidClaims: [], - userId: "", - }, - ]; - case 6: - _b.trys.push([6, 9, , 11]); - _a = { - loading: false, - doesSessionExist: true, - invalidClaims: invalidClaims, - }; - return [ - 4 /*yield*/, - session.current.getAccessTokenPayloadSecurely({ - userContext: userContext, - }), - ]; - case 7: - _a.accessTokenPayload = _b.sent(); - return [ - 4 /*yield*/, - session.current.getUserId({ - userContext: userContext, - }), - ]; - case 8: - return [2 /*return*/, ((_a.userId = _b.sent()), _a)]; - case 9: - err_2 = _b.sent(); - return [ - 4 /*yield*/, - session.current.doesSessionExist({ - userContext: userContext, - }), - ]; - case 10: - if (_b.sent()) { - throw err_2; - } - // This means that loading the access token or the userId failed - // This may happen if the server cleared the error since the validation was done which should be extremely rare - return [ - 2 /*return*/, - { - loading: false, - doesSessionExist: false, - accessTokenPayload: {}, - invalidClaims: [], - userId: "", - }, - ]; - case 11: - return [2 /*return*/]; - } - }); - }); - }, []); - var setInitialContextAndMaybeRedirect = React.useCallback( - function (toSetContext) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var failureRedirectInfo, err_3; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (context.loading === false) { - return [2 /*return*/]; - } - if (!(props.doRedirection !== false)) return [3 /*break*/, 8]; - if (!toSetContext.doesSessionExist && props.requireAuth !== false) { - redirectToLogin(); - return [2 /*return*/]; - } - if (!(toSetContext.invalidClaims.length !== 0)) return [3 /*break*/, 8]; - failureRedirectInfo = void 0; - _a.label = 1; - case 1: - _a.trys.push([1, 6, , 7]); - return [ - 4 /*yield*/, - types.getFailureRedirectionInfo({ - invalidClaims: toSetContext.invalidClaims, - overrideGlobalClaimValidators: props.overrideGlobalClaimValidators, - userContext: userContext, - }), - ]; - case 2: - failureRedirectInfo = _a.sent(); - if (!(failureRedirectInfo.redirectPath !== undefined)) return [3 /*break*/, 5]; - if ( - !types.validateAndCompareOnFailureRedirectionURLToCurrent( - failureRedirectInfo.redirectPath - ) - ) - return [3 /*break*/, 3]; - setContextIfChanged(toSetContext); - return [2 /*return*/]; - case 3: - return [ - 4 /*yield*/, - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToUrl( - failureRedirectInfo.redirectPath, - navigate - ), - ]; - case 4: - return [2 /*return*/, _a.sent()]; - case 5: - return [3 /*break*/, 7]; - case 6: - err_3 = _a.sent(); - rethrowInRender(err_3); - throw err_3; - case 7: - if ( - props.accessDeniedScreen !== undefined && - failureRedirectInfo.failedClaim !== undefined - ) { - console.warn({ - message: "Showing access denied screen because a claim validator failed", - claimValidationError: failureRedirectInfo.failedClaim, - }); - return [ - 2 /*return*/, - setContextIfChanged( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, toSetContext), - { accessDeniedValidatorError: failureRedirectInfo.failedClaim } - ) - ), - ]; - } - _a.label = 8; - case 8: - setContextIfChanged(toSetContext); - return [2 /*return*/]; - } - }); - }); - }, - [ - context.loading, - props.doRedirection, - props.requireAuth, - props.overrideGlobalClaimValidators, - props.accessDeniedScreen, - redirectToLogin, - userContext, - navigate, - ] - ); - genericComponentOverrideContext.useOnMountAPICall(buildContext, setInitialContextAndMaybeRedirect); - // subscribe to events on mount - React.useEffect( - function () { - function onHandleEvent(event) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var _a, invalidClaims, failureRedirectInfo, err_4; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = event.action; - switch (_a) { - case "SESSION_CREATED": - return [3 /*break*/, 1]; - case "REFRESH_SESSION": - return [3 /*break*/, 1]; - case "ACCESS_TOKEN_PAYLOAD_UPDATED": - return [3 /*break*/, 1]; - case "API_INVALID_CLAIM": - return [3 /*break*/, 1]; - case "SIGN_OUT": - return [3 /*break*/, 11]; - case "UNAUTHORISED": - return [3 /*break*/, 12]; - } - return [3 /*break*/, 13]; - case 1: - return [ - 4 /*yield*/, - session.current.validateClaims({ - overrideGlobalClaimValidators: props.overrideGlobalClaimValidators, - userContext: userContext, - }), - ]; - case 2: - invalidClaims = _b.sent(); - if (!(props.doRedirection !== false)) return [3 /*break*/, 10]; - failureRedirectInfo = void 0; - _b.label = 3; - case 3: - _b.trys.push([3, 8, , 9]); - return [ - 4 /*yield*/, - types.getFailureRedirectionInfo({ - invalidClaims: invalidClaims, - overrideGlobalClaimValidators: props.overrideGlobalClaimValidators, - userContext: userContext, - }), - ]; - case 4: - failureRedirectInfo = _b.sent(); - if (!failureRedirectInfo.redirectPath) return [3 /*break*/, 7]; - if ( - !types.validateAndCompareOnFailureRedirectionURLToCurrent( - failureRedirectInfo.redirectPath - ) - ) - return [3 /*break*/, 5]; - setContextIfChanged( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, event.sessionContext), - { loading: false, invalidClaims: invalidClaims } - ) - ); - return [3 /*break*/, 7]; - case 5: - return [ - 4 /*yield*/, - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToUrl( - failureRedirectInfo.redirectPath, - navigate - ), - ]; - case 6: - return [2 /*return*/, _b.sent()]; - case 7: - return [3 /*break*/, 9]; - case 8: - err_4 = _b.sent(); - rethrowInRender(err_4); - throw err_4; - case 9: - if ( - props.accessDeniedScreen !== undefined && - failureRedirectInfo.failedClaim !== undefined - ) { - console.warn({ - message: "Showing access denied screen because a claim validator failed", - claimValidationError: failureRedirectInfo.failedClaim, - }); - return [ - 2 /*return*/, - setContextIfChanged( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, event.sessionContext), - { - loading: false, - invalidClaims: invalidClaims, - accessDeniedValidatorError: failureRedirectInfo.failedClaim, - } - ) - ), - ]; - } - _b.label = 10; - case 10: - setContextIfChanged( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, event.sessionContext), - { loading: false, invalidClaims: invalidClaims } - ) - ); - return [2 /*return*/]; - case 11: - setContextIfChanged( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, event.sessionContext), - { loading: false, invalidClaims: [] } - ) - ); - return [2 /*return*/]; - case 12: - setContextIfChanged( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, event.sessionContext), - { loading: false, invalidClaims: [] } - ) - ); - if (props.onSessionExpired !== undefined) { - props.onSessionExpired(); - } else if (props.requireAuth !== false && props.doRedirection !== false) { - redirectToLogin(); - } - return [2 /*return*/]; - case 13: - return [2 /*return*/]; - } - }); - }); - } - if (session.current === undefined) { - session.current = types.Session.getInstanceOrThrow(); - } - if (context.loading === false) { - // we return here cause addEventListener returns a function that removes - // the listener, and this function will be called by useEffect when - // onHandleEvent changes or if the component is unmounting. - return session.current.addEventListener(onHandleEvent); - } - return undefined; - }, - [props, setContextIfChanged, context.loading, userContext, navigate, redirectToLogin] - ); - if (props.requireAuth !== false && (context.loading || !context.doesSessionExist)) { - return null; - } - if (!context.loading && context.accessDeniedValidatorError && props.accessDeniedScreen) { - return jsxRuntime.jsx(props.accessDeniedScreen, { - userContext: userContext, - navigate: navigate, - validationError: context.accessDeniedValidatorError, - }); - } - return jsxRuntime.jsx( - SessionContext.Provider, - genericComponentOverrideContext.__assign({ value: context }, { children: children }) - ); -}; -var SessionAuthWrapper = function (props) { - return jsxRuntime.jsx( - UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { children: jsxRuntime.jsx(SessionAuth, genericComponentOverrideContext.__assign({}, props)) } - ) - ); +var SessionAuth = function (_a) { + var _b; + var children = _a.children, props = utils.__rest(_a, ["children"]); + var requireAuth = React.useRef(props.requireAuth); + if (props.requireAuth !== requireAuth.current) { + throw new Error( + // eslint-disable-next-line @typescript-eslint/quotes + 'requireAuth prop should not change. If you are seeing this, it probably means that you are using SessionAuth in multiple routes with different values for requireAuth. To solve this, try adding the "key" prop to all uses of SessionAuth like '); + } + // Reusing the parent context was removed because it caused a redirect loop in an edge case + // because it'd also reuse the invalid claims part until it loaded. + var _c = React.useState({ loading: true }), context = _c[0], setContext = _c[1]; + var setContextIfChanged = React.useCallback(function (newValue) { + setContext(function (oldValue) { + // We can't do this check before re-validation because there are be validators that depend on the current time + // Since the context is constructed by the same functions the property order should be stable, meaning that + // a simple JSON string check should be sufficient. + // Plus since this is just an optimization it is fine to have false positives, + // and this method won't have false negatives (where we'd miss an update). + if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) { + return newValue; + } + return oldValue; + }); + }, [setContext]); + var session = React.useRef(); + // We store this here, to prevent the list of called hooks changing even if a navigate hook is added later to SuperTokens. + var navigateHookRef = React.useRef((_b = UI.getReactRouterDomWithCustomHistory()) === null || _b === void 0 ? void 0 : _b.useHistoryCustom); + var navigate; + try { + if (navigateHookRef.current) { + navigate = navigateHookRef.current(); + } + } + catch (_d) { + // We catch and ignore errors here, because this is may throw if + // the app is using react-router-dom but added a session auth outside of the router. + } + var userContext = useUserContext(); + var rethrowInRender = utils.useRethrowInRender(); + var redirectToLogin = React.useCallback(function () { + void superTokens.SuperTokens.getInstanceOrThrow().redirectToAuth({ navigate: navigate, userContext: userContext, redirectBack: true }); + }, []); + var buildContext = React.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + var sessionExists, invalidClaims, err_1, err_2; + var _a; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (session.current === undefined) { + session.current = types.Session.getInstanceOrThrow(); + } + return [4 /*yield*/, session.current.doesSessionExist({ + userContext: userContext, + })]; + case 1: + sessionExists = _b.sent(); + if (sessionExists === false) { + return [2 /*return*/, { + loading: false, + doesSessionExist: false, + accessTokenPayload: {}, + invalidClaims: [], + userId: "", + }]; + } + _b.label = 2; + case 2: + _b.trys.push([2, 4, , 6]); + return [4 /*yield*/, session.current.validateClaims({ + overrideGlobalClaimValidators: props.overrideGlobalClaimValidators, + userContext: userContext, + })]; + case 3: + invalidClaims = _b.sent(); + return [3 /*break*/, 6]; + case 4: + err_1 = _b.sent(); + return [4 /*yield*/, session.current.doesSessionExist({ + userContext: userContext, + })]; + case 5: + // These errors should only come from getAccessTokenPayloadSecurely inside validateClaims if refreshing a claim cleared the session + // Which means that the session was most likely cleared, meaning returning false is right. + // This might also happen if the user provides an override or a custom claim validator that throws (or if we have a bug) + // In which case the session will not be cleared so we rethrow the error + if (_b.sent()) { + throw err_1; + } + return [2 /*return*/, { + loading: false, + doesSessionExist: false, + accessTokenPayload: {}, + invalidClaims: [], + userId: "", + }]; + case 6: + _b.trys.push([6, 9, , 11]); + _a = { + loading: false, + doesSessionExist: true, + invalidClaims: invalidClaims + }; + return [4 /*yield*/, session.current.getAccessTokenPayloadSecurely({ + userContext: userContext, + })]; + case 7: + _a.accessTokenPayload = _b.sent(); + return [4 /*yield*/, session.current.getUserId({ + userContext: userContext, + })]; + case 8: return [2 /*return*/, (_a.userId = _b.sent(), + _a)]; + case 9: + err_2 = _b.sent(); + return [4 /*yield*/, session.current.doesSessionExist({ + userContext: userContext, + })]; + case 10: + if (_b.sent()) { + throw err_2; + } + // This means that loading the access token or the userId failed + // This may happen if the server cleared the error since the validation was done which should be extremely rare + return [2 /*return*/, { + loading: false, + doesSessionExist: false, + accessTokenPayload: {}, + invalidClaims: [], + userId: "", + }]; + case 11: return [2 /*return*/]; + } + }); + }); }, []); + var setInitialContextAndMaybeRedirect = React.useCallback(function (toSetContext) { return utils.__awaiter(void 0, void 0, void 0, function () { + var failureRedirectInfo, err_3; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (context.loading === false) { + return [2 /*return*/]; + } + if (!(props.doRedirection !== false)) return [3 /*break*/, 8]; + if (!toSetContext.doesSessionExist && props.requireAuth !== false) { + redirectToLogin(); + return [2 /*return*/]; + } + if (!(toSetContext.invalidClaims.length !== 0)) return [3 /*break*/, 8]; + failureRedirectInfo = void 0; + _a.label = 1; + case 1: + _a.trys.push([1, 6, , 7]); + return [4 /*yield*/, types.getFailureRedirectionInfo({ + invalidClaims: toSetContext.invalidClaims, + overrideGlobalClaimValidators: props.overrideGlobalClaimValidators, + userContext: userContext, + })]; + case 2: + failureRedirectInfo = _a.sent(); + if (!(failureRedirectInfo.redirectPath !== undefined)) return [3 /*break*/, 5]; + if (!types.validateAndCompareOnFailureRedirectionURLToCurrent(failureRedirectInfo.redirectPath)) return [3 /*break*/, 3]; + setContextIfChanged(toSetContext); + return [2 /*return*/]; + case 3: return [4 /*yield*/, superTokens.SuperTokens.getInstanceOrThrow().redirectToUrl(failureRedirectInfo.redirectPath, navigate)]; + case 4: return [2 /*return*/, _a.sent()]; + case 5: return [3 /*break*/, 7]; + case 6: + err_3 = _a.sent(); + rethrowInRender(err_3); + throw err_3; + case 7: + if (props.accessDeniedScreen !== undefined && failureRedirectInfo.failedClaim !== undefined) { + console.warn({ + message: "Showing access denied screen because a claim validator failed", + claimValidationError: failureRedirectInfo.failedClaim, + }); + return [2 /*return*/, setContextIfChanged(utils.__assign(utils.__assign({}, toSetContext), { accessDeniedValidatorError: failureRedirectInfo.failedClaim }))]; + } + _a.label = 8; + case 8: + setContextIfChanged(toSetContext); + return [2 /*return*/]; + } + }); + }); }, [ + context.loading, + props.doRedirection, + props.requireAuth, + props.overrideGlobalClaimValidators, + props.accessDeniedScreen, + redirectToLogin, + userContext, + navigate, + ]); + utils.useOnMountAPICall(buildContext, setInitialContextAndMaybeRedirect); + // subscribe to events on mount + React.useEffect(function () { + function onHandleEvent(event) { + return utils.__awaiter(this, void 0, void 0, function () { + var _a, invalidClaims, failureRedirectInfo, err_4; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = event.action; + switch (_a) { + case "SESSION_CREATED": return [3 /*break*/, 1]; + case "REFRESH_SESSION": return [3 /*break*/, 1]; + case "ACCESS_TOKEN_PAYLOAD_UPDATED": return [3 /*break*/, 1]; + case "API_INVALID_CLAIM": return [3 /*break*/, 1]; + case "SIGN_OUT": return [3 /*break*/, 11]; + case "UNAUTHORISED": return [3 /*break*/, 12]; + } + return [3 /*break*/, 13]; + case 1: return [4 /*yield*/, session.current.validateClaims({ + overrideGlobalClaimValidators: props.overrideGlobalClaimValidators, + userContext: userContext, + })]; + case 2: + invalidClaims = _b.sent(); + if (!(props.doRedirection !== false)) return [3 /*break*/, 10]; + failureRedirectInfo = void 0; + _b.label = 3; + case 3: + _b.trys.push([3, 8, , 9]); + return [4 /*yield*/, types.getFailureRedirectionInfo({ + invalidClaims: invalidClaims, + overrideGlobalClaimValidators: props.overrideGlobalClaimValidators, + userContext: userContext, + })]; + case 4: + failureRedirectInfo = _b.sent(); + if (!failureRedirectInfo.redirectPath) return [3 /*break*/, 7]; + if (!types.validateAndCompareOnFailureRedirectionURLToCurrent(failureRedirectInfo.redirectPath)) return [3 /*break*/, 5]; + setContextIfChanged(utils.__assign(utils.__assign({}, event.sessionContext), { loading: false, invalidClaims: invalidClaims })); + return [3 /*break*/, 7]; + case 5: return [4 /*yield*/, superTokens.SuperTokens.getInstanceOrThrow().redirectToUrl(failureRedirectInfo.redirectPath, navigate)]; + case 6: return [2 /*return*/, _b.sent()]; + case 7: return [3 /*break*/, 9]; + case 8: + err_4 = _b.sent(); + rethrowInRender(err_4); + throw err_4; + case 9: + if (props.accessDeniedScreen !== undefined && failureRedirectInfo.failedClaim !== undefined) { + console.warn({ + message: "Showing access denied screen because a claim validator failed", + claimValidationError: failureRedirectInfo.failedClaim, + }); + return [2 /*return*/, setContextIfChanged(utils.__assign(utils.__assign({}, event.sessionContext), { loading: false, invalidClaims: invalidClaims, accessDeniedValidatorError: failureRedirectInfo.failedClaim }))]; + } + _b.label = 10; + case 10: + setContextIfChanged(utils.__assign(utils.__assign({}, event.sessionContext), { loading: false, invalidClaims: invalidClaims })); + return [2 /*return*/]; + case 11: + setContextIfChanged(utils.__assign(utils.__assign({}, event.sessionContext), { loading: false, invalidClaims: [] })); + return [2 /*return*/]; + case 12: + setContextIfChanged(utils.__assign(utils.__assign({}, event.sessionContext), { loading: false, invalidClaims: [] })); + if (props.onSessionExpired !== undefined) { + props.onSessionExpired(); + } + else if (props.requireAuth !== false && props.doRedirection !== false) { + redirectToLogin(); + } + return [2 /*return*/]; + case 13: return [2 /*return*/]; + } + }); + }); + } + if (session.current === undefined) { + session.current = types.Session.getInstanceOrThrow(); + } + if (context.loading === false) { + // we return here cause addEventListener returns a function that removes + // the listener, and this function will be called by useEffect when + // onHandleEvent changes or if the component is unmounting. + return session.current.addEventListener(onHandleEvent); + } + return undefined; + }, [props, setContextIfChanged, context.loading, userContext, navigate, redirectToLogin]); + if (props.requireAuth !== false && (context.loading || !context.doesSessionExist)) { + return null; + } + if (!context.loading && context.accessDeniedValidatorError && props.accessDeniedScreen) { + return (jsxRuntime.jsx(props.accessDeniedScreen, { userContext: userContext, navigate: navigate, validationError: context.accessDeniedValidatorError })); + } + return jsxRuntime.jsx(SessionContext.Provider, utils.__assign({ value: context }, { children: children })); +}; +var SessionAuthWrapper = function (props) { + return (jsxRuntime.jsx(UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(SessionAuth, utils.__assign({}, props)) }))); }; -var SuperTokensWrapper = function (props) { - return jsxRuntime.jsx( - SessionAuthWrapper, - genericComponentOverrideContext.__assign({}, props, { requireAuth: false, doRedirection: false }) - ); +var SuperTokensWrapper = function (props) { + return jsxRuntime.jsx(SessionAuthWrapper, utils.__assign({}, props, { requireAuth: false, doRedirection: false })); }; -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * API Wrapper exposed to user. - */ -var SuperTokensAPIWrapper = /** @class */ (function () { - function SuperTokensAPIWrapper() {} - SuperTokensAPIWrapper.init = function (config) { - genericComponentOverrideContext.SuperTokens.init(config); - }; - SuperTokensAPIWrapper.changeLanguage = function (language) { - return genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().changeLanguage(language); - }; - SuperTokensAPIWrapper.loadTranslation = function (store) { - return genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().loadTranslation(store); - }; - var _a; - _a = SuperTokensAPIWrapper; - SuperTokensAPIWrapper.SuperTokensWrapper = SuperTokensWrapper; - SuperTokensAPIWrapper.redirectToAuth = function (options) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var _b; - return genericComponentOverrideContext.__generator(_a, function (_c) { - return [ - 2 /*return*/, - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToAuth( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, options), - { - redirectBack: - (_b = options === null || options === void 0 ? void 0 : options.redirectBack) !== - null && _b !== void 0 - ? _b - : true, - userContext: genericComponentOverrideContext.getNormalisedUserContext( - options === null || options === void 0 ? void 0 : options.userContext - ), - } - ) - ), - ]; - }); - }); - }; - SuperTokensAPIWrapper.useTranslation = translationContext.useTranslation; - SuperTokensAPIWrapper.useUserContext = useUserContext; - return SuperTokensAPIWrapper; -})(); -var init = SuperTokensAPIWrapper.init; -var changeLanguage = SuperTokensAPIWrapper.changeLanguage; -var loadTranslation = SuperTokensAPIWrapper.loadTranslation; +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * API Wrapper exposed to user. + */ +var SuperTokensAPIWrapper = /** @class */ (function () { + function SuperTokensAPIWrapper() { + } + SuperTokensAPIWrapper.init = function (config) { + superTokens.SuperTokens.init(config); + }; + SuperTokensAPIWrapper.changeLanguage = function (language) { + return superTokens.SuperTokens.getInstanceOrThrow().changeLanguage(language); + }; + SuperTokensAPIWrapper.loadTranslation = function (store) { + return superTokens.SuperTokens.getInstanceOrThrow().loadTranslation(store); + }; + var _a; + _a = SuperTokensAPIWrapper; + SuperTokensAPIWrapper.SuperTokensWrapper = SuperTokensWrapper; + SuperTokensAPIWrapper.redirectToAuth = function (options) { return utils.__awaiter(void 0, void 0, void 0, function () { + var _b; + return utils.__generator(_a, function (_c) { + return [2 /*return*/, superTokens.SuperTokens.getInstanceOrThrow().redirectToAuth(utils.__assign(utils.__assign({}, options), { redirectBack: (_b = options === null || options === void 0 ? void 0 : options.redirectBack) !== null && _b !== void 0 ? _b : true, userContext: utils.getNormalisedUserContext(options === null || options === void 0 ? void 0 : options.userContext) }))]; + }); + }); }; + SuperTokensAPIWrapper.useTranslation = translationContext.useTranslation; + SuperTokensAPIWrapper.useUserContext = useUserContext; + return SuperTokensAPIWrapper; +}()); +var init = SuperTokensAPIWrapper.init; +var changeLanguage = SuperTokensAPIWrapper.changeLanguage; +var loadTranslation = SuperTokensAPIWrapper.loadTranslation; var redirectToAuth = SuperTokensAPIWrapper.redirectToAuth; exports.AuthPage = AuthPage; diff --git a/lib/build/logger.d.ts b/lib/build/logger.d.ts index a5e767ecb..91bd657ca 100644 --- a/lib/build/logger.d.ts +++ b/lib/build/logger.d.ts @@ -1,2 +1,2 @@ -export declare function enableLogging(): void; -export declare function logDebugMessage(message: string): void; +export declare function enableLogging(): void; +export declare function logDebugMessage(message: string): void; diff --git a/lib/build/multifactorauth-shared.js b/lib/build/multifactorauth-shared.js index a8b16358d..64f5dbcc2 100644 --- a/lib/build/multifactorauth-shared.js +++ b/lib/build/multifactorauth-shared.js @@ -1,586 +1,426 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var WebJSSessionRecipe = require("supertokens-web-js/recipe/session"); -var recipe = require("./oauth2provider-shared.js"); -var index = require("./recipeModule-shared.js"); -var utils = require("supertokens-web-js/utils"); -var windowHandler = require("supertokens-web-js/utils/windowHandler"); +var utils = require('./utils.js'); +var WebJSSessionRecipe = require('supertokens-web-js/recipe/session'); +var superTokens = require('./superTokens.js'); +var recipe = require('./oauth2provider-shared.js'); +var index = require('./recipeModule-shared.js'); +var utils$1 = require('supertokens-web-js/utils'); +var windowHandler = require('supertokens-web-js/utils/windowHandler'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } -var WebJSSessionRecipe__default = /*#__PURE__*/ _interopDefault(WebJSSessionRecipe); +var WebJSSessionRecipe__default = /*#__PURE__*/_interopDefault(WebJSSessionRecipe); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -function normaliseSessionConfig(config) { - var _a, _b, _c; - if (config === undefined) { - config = {}; - } - var accessDeniedScreenStyle = - (_b = (_a = config.accessDeniedScreen) === null || _a === void 0 ? void 0 : _a.style) !== null && _b !== void 0 - ? _b - : ""; - var accessDeniedScreen = { - style: accessDeniedScreenStyle, - }; - var override = genericComponentOverrideContext.__assign( - { - functions: function (originalImplementation) { - return originalImplementation; - }, - }, - config.override - ); - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign( - {}, - genericComponentOverrideContext.normaliseRecipeModuleConfig(config) - ), - { - // TODO: ideally we'd get the default (or normalized) value from supertokens-website - invalidClaimStatusCode: (_c = config.invalidClaimStatusCode) !== null && _c !== void 0 ? _c : 403, - accessDeniedScreen: accessDeniedScreen, - override: override, - } - ); -} -var getFailureRedirectionInfo = function (_a) { - var invalidClaims = _a.invalidClaims, - overrideGlobalClaimValidators = _a.overrideGlobalClaimValidators, - userContext = _a.userContext; - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var globalValidators, failedClaim, _loop_1, _i, globalValidators_1, validator, state_1; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - globalValidators = utils.getGlobalClaimValidators({ - overrideGlobalClaimValidators: overrideGlobalClaimValidators, - userContext: userContext, - }); - failedClaim = undefined; - _loop_1 = function (validator) { - var claim, failureCallback, redirectPath; - return genericComponentOverrideContext.__generator(this, function (_c) { - switch (_c.label) { - case 0: - claim = invalidClaims.find(function (c) { - return c.id === validator.id; - }); - if (!(claim !== undefined)) return [3 /*break*/, 2]; - failureCallback = validator.onFailureRedirection; - if (!failureCallback) return [3 /*break*/, 2]; - return [ - 4 /*yield*/, - failureCallback({ reason: claim.reason, userContext: userContext }), - ]; - case 1: - redirectPath = _c.sent(); - if (redirectPath !== undefined) { - return [ - 2 /*return*/, - { - value: { - redirectPath: redirectPath, - failedClaim: claim, - }, - }, - ]; - } - _c.label = 2; - case 2: - if (validator.showAccessDeniedOnFailure !== false && failedClaim === undefined) { - failedClaim = claim; - } - return [2 /*return*/]; - } - }); - }; - (_i = 0), (globalValidators_1 = globalValidators); - _b.label = 1; - case 1: - if (!(_i < globalValidators_1.length)) return [3 /*break*/, 4]; - validator = globalValidators_1[_i]; - return [5 /*yield**/, _loop_1(validator)]; - case 2: - state_1 = _b.sent(); - if (typeof state_1 === "object") return [2 /*return*/, state_1.value]; - _b.label = 3; - case 3: - _i++; - return [3 /*break*/, 1]; - case 4: - return [ - 2 /*return*/, - { - redirectPath: undefined, - failedClaim: failedClaim, - }, - ]; - } - }); - }); -}; -function validateAndCompareOnFailureRedirectionURLToCurrent(redirectURL) { - var currentUrl = windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getHref(); - var fullRedirectURL; - try { - new URL(redirectURL); - // if the url is a full, valid url, we can use that - fullRedirectURL = redirectURL; - } catch (_a) { - // If we get here, we know it's not full url - // We check if it's an absolute path - if (!redirectURL.startsWith("/")) { - throw new Error("onFailureRedirectionURL returned a relative url: ".concat(redirectURL)); - } - var appInfo = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().appInfo; - // otherwise we prepend the websiteDomain - fullRedirectURL = "".concat(appInfo.websiteDomain.getAsStringDangerous()).concat(redirectURL); - } - return currentUrl === fullRedirectURL; +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +function normaliseSessionConfig(config) { + var _a, _b, _c; + if (config === undefined) { + config = {}; + } + var accessDeniedScreenStyle = (_b = (_a = config.accessDeniedScreen) === null || _a === void 0 ? void 0 : _a.style) !== null && _b !== void 0 ? _b : ""; + var accessDeniedScreen = { + style: accessDeniedScreenStyle, + }; + var override = utils.__assign({ functions: function (originalImplementation) { return originalImplementation; } }, config.override); + return utils.__assign(utils.__assign({}, superTokens.normaliseRecipeModuleConfig(config)), { + // TODO: ideally we'd get the default (or normalized) value from supertokens-website + invalidClaimStatusCode: (_c = config.invalidClaimStatusCode) !== null && _c !== void 0 ? _c : 403, accessDeniedScreen: accessDeniedScreen, override: override }); +} +var getFailureRedirectionInfo = function (_a) { + var invalidClaims = _a.invalidClaims, overrideGlobalClaimValidators = _a.overrideGlobalClaimValidators, userContext = _a.userContext; + return utils.__awaiter(void 0, void 0, void 0, function () { + var globalValidators, failedClaim, _loop_1, _i, globalValidators_1, validator, state_1; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + globalValidators = utils$1.getGlobalClaimValidators({ + overrideGlobalClaimValidators: overrideGlobalClaimValidators, + userContext: userContext, + }); + failedClaim = undefined; + _loop_1 = function (validator) { + var claim, failureCallback, redirectPath; + return utils.__generator(this, function (_c) { + switch (_c.label) { + case 0: + claim = invalidClaims.find(function (c) { return c.id === validator.id; }); + if (!(claim !== undefined)) return [3 /*break*/, 2]; + failureCallback = validator.onFailureRedirection; + if (!failureCallback) return [3 /*break*/, 2]; + return [4 /*yield*/, failureCallback({ reason: claim.reason, userContext: userContext })]; + case 1: + redirectPath = _c.sent(); + if (redirectPath !== undefined) { + return [2 /*return*/, { value: { + redirectPath: redirectPath, + failedClaim: claim, + } }]; + } + _c.label = 2; + case 2: + if (validator.showAccessDeniedOnFailure !== false && failedClaim === undefined) { + failedClaim = claim; + } + return [2 /*return*/]; + } + }); + }; + _i = 0, globalValidators_1 = globalValidators; + _b.label = 1; + case 1: + if (!(_i < globalValidators_1.length)) return [3 /*break*/, 4]; + validator = globalValidators_1[_i]; + return [5 /*yield**/, _loop_1(validator)]; + case 2: + state_1 = _b.sent(); + if (typeof state_1 === "object") + return [2 /*return*/, state_1.value]; + _b.label = 3; + case 3: + _i++; + return [3 /*break*/, 1]; + case 4: return [2 /*return*/, { + redirectPath: undefined, + failedClaim: failedClaim, + }]; + } + }); + }); +}; +function validateAndCompareOnFailureRedirectionURLToCurrent(redirectURL) { + var currentUrl = windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.location.getHref(); + var fullRedirectURL; + try { + new URL(redirectURL); + // if the url is a full, valid url, we can use that + fullRedirectURL = redirectURL; + } + catch (_a) { + // If we get here, we know it's not full url + // We check if it's an absolute path + if (!redirectURL.startsWith("/")) { + throw new Error("onFailureRedirectionURL returned a relative url: ".concat(redirectURL)); + } + var appInfo = superTokens.SuperTokens.getInstanceOrThrow().appInfo; + // otherwise we prepend the websiteDomain + fullRedirectURL = "".concat(appInfo.websiteDomain.getAsStringDangerous()).concat(redirectURL); + } + return currentUrl === fullRedirectURL; } -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var Session = /** @class */ (function (_super) { - genericComponentOverrideContext.__extends(Session, _super); - function Session(config, webJSRecipe) { - if (webJSRecipe === void 0) { - webJSRecipe = WebJSSessionRecipe__default.default; - } - var _this = _super.call(this, config) || this; - _this.webJSRecipe = webJSRecipe; - _this.recipeID = Session.RECIPE_ID; - _this.eventListeners = new Set(); - _this.getUserId = function (input) { - return _this.webJSRecipe.getUserId(input); - }; - _this.getAccessToken = function (input) { - return _this.webJSRecipe.getAccessToken(input); - }; - _this.getClaimValue = function (input) { - return _this.webJSRecipe.getClaimValue(input); - }; - _this.getAccessTokenPayloadSecurely = function (input) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [2 /*return*/, this.webJSRecipe.getAccessTokenPayloadSecurely(input)]; - }); - }); - }; - _this.doesSessionExist = function (input) { - return _this.webJSRecipe.doesSessionExist(input); - }; - _this.signOut = function (input) { - return _this.webJSRecipe.signOut(input); - }; - _this.attemptRefreshingSession = function () { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [2 /*return*/, this.webJSRecipe.attemptRefreshingSession()]; - }); - }); - }; - _this.validateClaims = function (input) { - return _this.webJSRecipe.validateClaims(input); - }; - _this.getInvalidClaimsFromResponse = function (input) { - return _this.webJSRecipe.getInvalidClaimsFromResponse(input); - }; - /** - * @returns Function to remove event listener - */ - _this.addEventListener = function (listener) { - _this.eventListeners.add(listener); - return function () { - return _this.eventListeners.delete(listener); - }; - }; - _this.validateGlobalClaimsAndHandleSuccessRedirection = function ( - // We redefine recipeId to be a string here, because everywhere in the SDK we treat - // it as a string (e.g.: when defining it in recipes), but we want to type it more - // strictly in the callbacks the app provides to help integrating our SDK. - // This is the "meeting point" between the two types, so we need to cast between them here. - successRedirectContext, - fallbackRecipeId, - redirectToPath, - userContext, - navigate - ) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var invalidClaims, jsonContext, failureRedirectInfo, successContextStr, storedContext; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - userContext = genericComponentOverrideContext.getNormalisedUserContext(userContext); - return [4 /*yield*/, this.doesSessionExist({ userContext: userContext })]; - case 1: - // First we check if there is an active session - if (!_a.sent()) { - // If there is none, we have no way of checking claims, so we redirect to the auth page - // This can happen e.g.: if the user clicked on the email verification link in a browser without an active session - return [ - 2 /*return*/, - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToAuth({ - navigate: navigate, - redirectBack: false, - userContext: userContext, - }), - ]; - } - return [4 /*yield*/, this.validateClaims({ userContext: userContext })]; - case 2: - invalidClaims = _a.sent(); - if (!(invalidClaims.length > 0)) return [3 /*break*/, 6]; - if (!(successRedirectContext !== undefined)) return [3 /*break*/, 4]; - jsonContext = JSON.stringify({ - successRedirectContext: successRedirectContext, - redirectToPath: redirectToPath, - }); - return [ - 4 /*yield*/, - genericComponentOverrideContext.setLocalStorage( - "supertokens-success-redirection-context", - jsonContext - ), - ]; - case 3: - _a.sent(); - _a.label = 4; - case 4: - return [ - 4 /*yield*/, - getFailureRedirectionInfo({ - invalidClaims: invalidClaims, - userContext: userContext, - }), - ]; - case 5: - failureRedirectInfo = _a.sent(); - // if redirectPath is string that means failed claim had callback that returns path, we redirect there otherwise continue - if (failureRedirectInfo.redirectPath !== undefined) { - // the validation part can throw, but this is handled in all places where this is called, - // since getFailureRedirectionInfo can also throw - if ( - validateAndCompareOnFailureRedirectionURLToCurrent(failureRedirectInfo.redirectPath) - ) { - throw new Error( - "onFailureRedirectionURL returned the current URL (".concat( - failureRedirectInfo.redirectPath, - ") during success redirection. This indicates that the user is in a stuck state." - ) - ); - } - return [ - 2 /*return*/, - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToUrl( - failureRedirectInfo.redirectPath, - navigate - ), - ]; - } - _a.label = 6; - case 6: - if (!(successRedirectContext === undefined)) return [3 /*break*/, 13]; - return [ - 4 /*yield*/, - genericComponentOverrideContext.getLocalStorage( - "supertokens-success-redirection-context" - ), - ]; - case 7: - successContextStr = _a.sent(); - if (!(successContextStr !== null)) return [3 /*break*/, 12]; - _a.label = 8; - case 8: - _a.trys.push([8, , 9, 11]); - storedContext = JSON.parse(successContextStr); - successRedirectContext = storedContext.successRedirectContext; - // if we have a redirectToPath set in the queryparams that takes priority over the stored value - if (redirectToPath === undefined) { - redirectToPath = storedContext.redirectToPath; - } - return [3 /*break*/, 11]; - case 9: - return [ - 4 /*yield*/, - genericComponentOverrideContext.removeFromLocalStorage( - "supertokens-success-redirection-context" - ), - ]; - case 10: - _a.sent(); - return [7 /*endfinally*/]; - case 11: - return [3 /*break*/, 13]; - case 12: - // If there was nothing in localstorage we set a default - // this can happen if the user visited email verification screen without an auth recipe redirecting them there - // but already had the email verified and an active session - successRedirectContext = { - recipeId: fallbackRecipeId, - action: "SUCCESS", - createdNewUser: false, - isNewRecipeUser: false, - newSessionCreated: false, - tenantIdFromQueryParams: genericComponentOverrideContext.getTenantIdFromQueryParams(), - }; - _a.label = 13; - case 13: - if (successRedirectContext === undefined) { - throw new Error("This should never happen: successRedirectContext undefined "); - } - if (successRedirectContext.action === "SUCCESS_OAUTH2") { - return [ - 2 /*return*/, - recipe.OAuth2Provider.getInstanceOrThrow().redirect( - successRedirectContext, - navigate, - {}, - userContext - ), - ]; - } - if (successRedirectContext.action === "SUCCESS" && redirectToPath !== undefined) { - successRedirectContext.redirectToPath = redirectToPath; - } - return [ - 2 /*return*/, - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirect( - successRedirectContext, - navigate, - {}, - userContext - ), - ]; - } - }); - }); - }; - /** - * This should only get called if validateGlobalClaimsAndHandleSuccessRedirection couldn't get a redirectInfo - * @returns "/" - */ - _this.getDefaultRedirectionURL = function () { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - // We do not use the util here, since we are redirecting outside of the SDK routes - return [2 /*return*/, "/"]; - }); - }); - }; - _this.notifyListeners = function (event) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var sessionContext; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, this.getSessionContext(event)]; - case 1: - sessionContext = _a.sent(); - // We copy this.eventListeners into a new array to "freeze" it for the loop - // We do this to avoid an infinite loop in case one of the listeners causes a new listener to be added (e.g.: through re-rendering) - Array.from(this.eventListeners).forEach(function (listener) { - return listener( - genericComponentOverrideContext.__assign({ sessionContext: sessionContext }, event) - ); - }); - return [2 /*return*/]; - } - }); - }); - }; - return _this; - } - Session.prototype.getSessionContext = function (_a) { - var action = _a.action, - userContext = _a.userContext; - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var _b, userId, accessTokenPayload; - return genericComponentOverrideContext.__generator(this, function (_c) { - switch (_c.label) { - case 0: - if ( - !( - action === "SESSION_CREATED" || - action === "REFRESH_SESSION" || - action === "API_INVALID_CLAIM" || - action === "ACCESS_TOKEN_PAYLOAD_UPDATED" - ) - ) - return [3 /*break*/, 2]; - return [ - 4 /*yield*/, - Promise.all([ - this.getUserId({ - userContext: userContext, - }), - this.getAccessTokenPayloadSecurely({ - userContext: userContext, - }), - ]), - ]; - case 1: - (_b = _c.sent()), (userId = _b[0]), (accessTokenPayload = _b[1]); - return [ - 2 /*return*/, - { - doesSessionExist: true, - accessTokenPayload: accessTokenPayload, - userId: userId, - }, - ]; - case 2: - if (action === "SIGN_OUT" || action === "UNAUTHORISED") { - return [ - 2 /*return*/, - { - doesSessionExist: false, - accessTokenPayload: {}, - userId: "", - }, - ]; - } - throw new Error("Unhandled recipe event: ".concat(action)); - } - }); - }); - }; - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - Session.addAxiosInterceptors = function (axiosInstance, userContext) { - return WebJSSessionRecipe__default.default.addAxiosInterceptors(axiosInstance, userContext); - }; - Session.init = function (config) { - var _this = this; - var normalisedConfig = normaliseSessionConfig(config); - return { - recipeID: Session.RECIPE_ID, - authReact: function (appInfo) { - Session.instance = new Session( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, normalisedConfig), - { appInfo: appInfo, recipeId: Session.RECIPE_ID } - ) - ); - return Session.instance; - }, - webJS: WebJSSessionRecipe__default.default.init( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, normalisedConfig), - { - onHandleEvent: function (event) { - if (normalisedConfig.onHandleEvent !== undefined) { - normalisedConfig.onHandleEvent(event); - } - void Session.getInstanceOrThrow().notifyListeners(event); - }, - preAPIHook: function (context) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - response = genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, context), - { - requestInit: genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, context.requestInit), - { - headers: genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign( - {}, - context.requestInit.headers - ), - { rid: Session.RECIPE_ID } - ), - } - ), - } - ); - if (normalisedConfig.preAPIHook === undefined) { - return [2 /*return*/, response]; - } else { - return [2 /*return*/, normalisedConfig.preAPIHook(context)]; - } - }); - }); - }, - } - ) - ), - }; - }; - Session.getInstanceOrThrow = function () { - if (Session.instance === undefined) { - throw Error( - "No instance of Session found. Make sure to call the Session.init method. See https://supertokens.io/docs/emailpassword/quick-setup/frontend" - ); - } - return Session.instance; - }; - Session.getInstance = function () { - return Session.instance; - }; - Session.reset = function () { - if (!genericComponentOverrideContext.isTest()) { - return; - } - Session.instance = undefined; - return; - }; - Session.RECIPE_ID = "session"; - return Session; -})(index.RecipeModule); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var Session = /** @class */ (function (_super) { + utils.__extends(Session, _super); + function Session(config, webJSRecipe) { + if (webJSRecipe === void 0) { webJSRecipe = WebJSSessionRecipe__default.default; } + var _this = _super.call(this, config) || this; + _this.webJSRecipe = webJSRecipe; + _this.recipeID = Session.RECIPE_ID; + _this.eventListeners = new Set(); + _this.getUserId = function (input) { + return _this.webJSRecipe.getUserId(input); + }; + _this.getAccessToken = function (input) { + return _this.webJSRecipe.getAccessToken(input); + }; + _this.getClaimValue = function (input) { + return _this.webJSRecipe.getClaimValue(input); + }; + _this.getAccessTokenPayloadSecurely = function (input) { return utils.__awaiter(_this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, this.webJSRecipe.getAccessTokenPayloadSecurely(input)]; + }); + }); }; + _this.doesSessionExist = function (input) { + return _this.webJSRecipe.doesSessionExist(input); + }; + _this.signOut = function (input) { + return _this.webJSRecipe.signOut(input); + }; + _this.attemptRefreshingSession = function () { return utils.__awaiter(_this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, this.webJSRecipe.attemptRefreshingSession()]; + }); + }); }; + _this.validateClaims = function (input) { + return _this.webJSRecipe.validateClaims(input); + }; + _this.getInvalidClaimsFromResponse = function (input) { + return _this.webJSRecipe.getInvalidClaimsFromResponse(input); + }; + /** + * @returns Function to remove event listener + */ + _this.addEventListener = function (listener) { + _this.eventListeners.add(listener); + return function () { return _this.eventListeners.delete(listener); }; + }; + _this.validateGlobalClaimsAndHandleSuccessRedirection = function ( + // We redefine recipeId to be a string here, because everywhere in the SDK we treat + // it as a string (e.g.: when defining it in recipes), but we want to type it more + // strictly in the callbacks the app provides to help integrating our SDK. + // This is the "meeting point" between the two types, so we need to cast between them here. + successRedirectContext, fallbackRecipeId, redirectToPath, userContext, navigate) { return utils.__awaiter(_this, void 0, void 0, function () { + var invalidClaims, jsonContext, failureRedirectInfo, successContextStr, storedContext; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + userContext = utils.getNormalisedUserContext(userContext); + return [4 /*yield*/, this.doesSessionExist({ userContext: userContext })]; + case 1: + // First we check if there is an active session + if (!(_a.sent())) { + // If there is none, we have no way of checking claims, so we redirect to the auth page + // This can happen e.g.: if the user clicked on the email verification link in a browser without an active session + return [2 /*return*/, superTokens.SuperTokens.getInstanceOrThrow().redirectToAuth({ + navigate: navigate, + redirectBack: false, + userContext: userContext, + })]; + } + return [4 /*yield*/, this.validateClaims({ userContext: userContext })]; + case 2: + invalidClaims = _a.sent(); + if (!(invalidClaims.length > 0)) return [3 /*break*/, 6]; + if (!(successRedirectContext !== undefined)) return [3 /*break*/, 4]; + jsonContext = JSON.stringify({ successRedirectContext: successRedirectContext, redirectToPath: redirectToPath }); + return [4 /*yield*/, utils.setLocalStorage("supertokens-success-redirection-context", jsonContext)]; + case 3: + _a.sent(); + _a.label = 4; + case 4: return [4 /*yield*/, getFailureRedirectionInfo({ + invalidClaims: invalidClaims, + userContext: userContext, + })]; + case 5: + failureRedirectInfo = _a.sent(); + // if redirectPath is string that means failed claim had callback that returns path, we redirect there otherwise continue + if (failureRedirectInfo.redirectPath !== undefined) { + // the validation part can throw, but this is handled in all places where this is called, + // since getFailureRedirectionInfo can also throw + if (validateAndCompareOnFailureRedirectionURLToCurrent(failureRedirectInfo.redirectPath)) { + throw new Error("onFailureRedirectionURL returned the current URL (".concat(failureRedirectInfo.redirectPath, ") during success redirection. This indicates that the user is in a stuck state.")); + } + return [2 /*return*/, superTokens.SuperTokens.getInstanceOrThrow().redirectToUrl(failureRedirectInfo.redirectPath, navigate)]; + } + _a.label = 6; + case 6: + if (!(successRedirectContext === undefined)) return [3 /*break*/, 13]; + return [4 /*yield*/, utils.getLocalStorage("supertokens-success-redirection-context")]; + case 7: + successContextStr = _a.sent(); + if (!(successContextStr !== null)) return [3 /*break*/, 12]; + _a.label = 8; + case 8: + _a.trys.push([8, , 9, 11]); + storedContext = JSON.parse(successContextStr); + successRedirectContext = storedContext.successRedirectContext; + // if we have a redirectToPath set in the queryparams that takes priority over the stored value + if (redirectToPath === undefined) { + redirectToPath = storedContext.redirectToPath; + } + return [3 /*break*/, 11]; + case 9: return [4 /*yield*/, utils.removeFromLocalStorage("supertokens-success-redirection-context")]; + case 10: + _a.sent(); + return [7 /*endfinally*/]; + case 11: return [3 /*break*/, 13]; + case 12: + // If there was nothing in localstorage we set a default + // this can happen if the user visited email verification screen without an auth recipe redirecting them there + // but already had the email verified and an active session + successRedirectContext = { + recipeId: fallbackRecipeId, + action: "SUCCESS", + createdNewUser: false, + isNewRecipeUser: false, + newSessionCreated: false, + tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), + }; + _a.label = 13; + case 13: + if (successRedirectContext === undefined) { + throw new Error("This should never happen: successRedirectContext undefined "); + } + if (successRedirectContext.action === "SUCCESS_OAUTH2") { + return [2 /*return*/, recipe.OAuth2Provider.getInstanceOrThrow().redirect(successRedirectContext, navigate, {}, userContext)]; + } + if (successRedirectContext.action === "SUCCESS" && redirectToPath !== undefined) { + successRedirectContext.redirectToPath = redirectToPath; + } + return [2 /*return*/, superTokens.SuperTokens.getInstanceOrThrow().redirect(successRedirectContext, navigate, {}, userContext)]; + } + }); + }); }; + /** + * This should only get called if validateGlobalClaimsAndHandleSuccessRedirection couldn't get a redirectInfo + * @returns "/" + */ + _this.getDefaultRedirectionURL = function () { return utils.__awaiter(_this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + // We do not use the util here, since we are redirecting outside of the SDK routes + return [2 /*return*/, "/"]; + }); + }); }; + _this.notifyListeners = function (event) { return utils.__awaiter(_this, void 0, void 0, function () { + var sessionContext; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, this.getSessionContext(event)]; + case 1: + sessionContext = _a.sent(); + // We copy this.eventListeners into a new array to "freeze" it for the loop + // We do this to avoid an infinite loop in case one of the listeners causes a new listener to be added (e.g.: through re-rendering) + Array.from(this.eventListeners).forEach(function (listener) { + return listener(utils.__assign({ sessionContext: sessionContext }, event)); + }); + return [2 /*return*/]; + } + }); + }); }; + return _this; + } + Session.prototype.getSessionContext = function (_a) { + var action = _a.action, userContext = _a.userContext; + return utils.__awaiter(this, void 0, void 0, function () { + var _b, userId, accessTokenPayload; + return utils.__generator(this, function (_c) { + switch (_c.label) { + case 0: + if (!(action === "SESSION_CREATED" || + action === "REFRESH_SESSION" || + action === "API_INVALID_CLAIM" || + action === "ACCESS_TOKEN_PAYLOAD_UPDATED")) return [3 /*break*/, 2]; + return [4 /*yield*/, Promise.all([ + this.getUserId({ + userContext: userContext, + }), + this.getAccessTokenPayloadSecurely({ + userContext: userContext, + }), + ])]; + case 1: + _b = _c.sent(), userId = _b[0], accessTokenPayload = _b[1]; + return [2 /*return*/, { + doesSessionExist: true, + accessTokenPayload: accessTokenPayload, + userId: userId, + }]; + case 2: + if (action === "SIGN_OUT" || action === "UNAUTHORISED") { + return [2 /*return*/, { + doesSessionExist: false, + accessTokenPayload: {}, + userId: "", + }]; + } + throw new Error("Unhandled recipe event: ".concat(action)); + } + }); + }); + }; + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + Session.addAxiosInterceptors = function (axiosInstance, userContext) { + return WebJSSessionRecipe__default.default.addAxiosInterceptors(axiosInstance, userContext); + }; + Session.init = function (config) { + var _this = this; + var normalisedConfig = normaliseSessionConfig(config); + return { + recipeID: Session.RECIPE_ID, + authReact: function (appInfo) { + Session.instance = new Session(utils.__assign(utils.__assign({}, normalisedConfig), { appInfo: appInfo, recipeId: Session.RECIPE_ID })); + return Session.instance; + }, + webJS: WebJSSessionRecipe__default.default.init(utils.__assign(utils.__assign({}, normalisedConfig), { onHandleEvent: function (event) { + if (normalisedConfig.onHandleEvent !== undefined) { + normalisedConfig.onHandleEvent(event); + } + void Session.getInstanceOrThrow().notifyListeners(event); + }, preAPIHook: function (context) { return utils.__awaiter(_this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + response = utils.__assign(utils.__assign({}, context), { requestInit: utils.__assign(utils.__assign({}, context.requestInit), { headers: utils.__assign(utils.__assign({}, context.requestInit.headers), { rid: Session.RECIPE_ID }) }) }); + if (normalisedConfig.preAPIHook === undefined) { + return [2 /*return*/, response]; + } + else { + return [2 /*return*/, normalisedConfig.preAPIHook(context)]; + } + }); + }); } })), + }; + }; + Session.getInstanceOrThrow = function () { + if (Session.instance === undefined) { + throw Error("No instance of Session found. Make sure to call the Session.init method. See https://supertokens.io/docs/emailpassword/quick-setup/frontend"); + } + return Session.instance; + }; + Session.getInstance = function () { + return Session.instance; + }; + Session.reset = function () { + if (!utils.isTest()) { + return; + } + Session.instance = undefined; + return; + }; + Session.RECIPE_ID = "session"; + return Session; +}(index.RecipeModule)); -/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var FactorIds = { - EMAILPASSWORD: "emailpassword", - OTP_EMAIL: "otp-email", - OTP_PHONE: "otp-phone", - LINK_EMAIL: "link-email", - LINK_PHONE: "link-phone", - THIRDPARTY: "thirdparty", - TOTP: "totp", - WEBAUTHN: "webauthn", +/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var FactorIds = { + EMAILPASSWORD: "emailpassword", + OTP_EMAIL: "otp-email", + OTP_PHONE: "otp-phone", + LINK_EMAIL: "link-email", + LINK_PHONE: "link-phone", + THIRDPARTY: "thirdparty", + TOTP: "totp", + WEBAUTHN: "webauthn", }; exports.FactorIds = FactorIds; diff --git a/lib/build/multifactorauth-shared2.js b/lib/build/multifactorauth-shared2.js index d5e65825c..581861f3c 100644 --- a/lib/build/multifactorauth-shared2.js +++ b/lib/build/multifactorauth-shared2.js @@ -1,699 +1,443 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var MultiFactorAuthWebJS = require("supertokens-web-js/recipe/multifactorauth"); -var utils = require("supertokens-web-js/utils"); -var postSuperTokensInitCallbacks = require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -var sessionClaimValidatorStore = require("supertokens-web-js/utils/sessionClaimValidatorStore"); -var windowHandler = require("supertokens-web-js/utils/windowHandler"); -var index = require("./recipeModule-shared.js"); -var types = require("./multifactorauth-shared.js"); +var utils = require('./utils.js'); +var MultiFactorAuthWebJS = require('supertokens-web-js/recipe/multifactorauth'); +var utils$1 = require('supertokens-web-js/utils'); +var postSuperTokensInitCallbacks = require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +var sessionClaimValidatorStore = require('supertokens-web-js/utils/sessionClaimValidatorStore'); +var windowHandler = require('supertokens-web-js/utils/windowHandler'); +var superTokens = require('./superTokens.js'); +var index = require('./recipeModule-shared.js'); +var types = require('./multifactorauth-shared.js'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } -var MultiFactorAuthWebJS__default = /*#__PURE__*/ _interopDefault(MultiFactorAuthWebJS); +var MultiFactorAuthWebJS__default = /*#__PURE__*/_interopDefault(MultiFactorAuthWebJS); -/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var DEFAULT_FACTOR_CHOOSER_PATH = "/mfa"; +/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var DEFAULT_FACTOR_CHOOSER_PATH = "/mfa"; var MFA_INFO_CACHE_KEY = "st-mfa-info-cache"; -// This is a simple in-memory lock using a promise -// We do not need anything more complex than this, since the cache we are locking is in sessionStorage anyway. -var lockProm = undefined; -var getFunctionOverrides = function ( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _onHandleEvent -) { - return function (originalImp) { - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, originalImp), { - resyncSessionAndFetchMFAInfo: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var stWindow, stored, parsed, unlock, stored_1, parsed, val; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - stWindow = windowHandler.WindowHandlerReference.getReferenceOrThrow(); - // If someone is refreshing from the server we wait for it to finish. - return [4 /*yield*/, lockProm]; - case 1: - // If someone is refreshing from the server we wait for it to finish. - _a.sent(); - return [4 /*yield*/, stWindow.windowHandler.sessionStorage.getItem(MFA_INFO_CACHE_KEY)]; - case 2: - stored = _a.sent(); - if (stored !== null) { - parsed = JSON.parse(stored); - if (parsed.t > Date.now() - 1000) { - return [ - 2 /*return*/, - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, parsed.v), - { - // Adding a fake response is not great, but we do want to add something and this way it's detectable by the app - // so they could even add specific handling for it if they preferred. - fetchResponse: new Response(null, { status: 304 }), - } - ), - ]; - } - } - _a.label = 3; - case 3: - if (!(lockProm !== undefined)) return [3 /*break*/, 5]; - return [4 /*yield*/, lockProm]; - case 4: - _a.sent(); - return [3 /*break*/, 3]; - case 5: - lockProm = new Promise(function (res) { - return (unlock = res); - }); - _a.label = 6; - case 6: - _a.trys.push([6, , 11, 12]); - return [4 /*yield*/, stWindow.windowHandler.sessionStorage.getItem(MFA_INFO_CACHE_KEY)]; - case 7: - stored_1 = _a.sent(); - if (stored_1 !== null) { - parsed = JSON.parse(stored_1); - if (parsed.t > Date.now() - 1000) { - return [ - 2 /*return*/, - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, parsed.v), - { - // Adding a fake response is not great, but we do want to add something and this way it's detectable by the app - // so they could even add specific handling for it if they preferred. - fetchResponse: new Response(null, { status: 304 }), - } - ), - ]; - } - } - return [4 /*yield*/, originalImp.resyncSessionAndFetchMFAInfo(input)]; - case 8: - val = _a.sent(); - if (!(val.status === "OK")) return [3 /*break*/, 10]; - // We are not storing the fetchResponse - return [ - 4 /*yield*/, - stWindow.windowHandler.sessionStorage.setItem( - MFA_INFO_CACHE_KEY, - JSON.stringify({ - t: Date.now(), - v: { - emails: val.emails, - phoneNumbers: val.phoneNumbers, - factors: val.factors, - status: val.status, - }, - }) - ), - ]; - case 9: - // We are not storing the fetchResponse - _a.sent(); - _a.label = 10; - case 10: - return [2 /*return*/, val]; - case 11: - // Release the lock - lockProm = undefined; - unlock(); - return [7 /*endfinally*/]; - case 12: - return [2 /*return*/]; - } - }); - }); - }, - }); - }; +// This is a simple in-memory lock using a promise +// We do not need anything more complex than this, since the cache we are locking is in sessionStorage anyway. +var lockProm = undefined; +var getFunctionOverrides = function ( +// eslint-disable-next-line @typescript-eslint/no-unused-vars +_onHandleEvent) { + return function (originalImp) { return (utils.__assign(utils.__assign({}, originalImp), { resyncSessionAndFetchMFAInfo: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var stWindow, stored, parsed, unlock, stored_1, parsed, val; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + stWindow = windowHandler.WindowHandlerReference.getReferenceOrThrow(); + // If someone is refreshing from the server we wait for it to finish. + return [4 /*yield*/, lockProm]; + case 1: + // If someone is refreshing from the server we wait for it to finish. + _a.sent(); + return [4 /*yield*/, stWindow.windowHandler.sessionStorage.getItem(MFA_INFO_CACHE_KEY)]; + case 2: + stored = _a.sent(); + if (stored !== null) { + parsed = JSON.parse(stored); + if (parsed.t > Date.now() - 1000) { + return [2 /*return*/, utils.__assign(utils.__assign({}, parsed.v), { + // Adding a fake response is not great, but we do want to add something and this way it's detectable by the app + // so they could even add specific handling for it if they preferred. + fetchResponse: new Response(null, { status: 304 }) })]; + } + } + _a.label = 3; + case 3: + if (!(lockProm !== undefined)) return [3 /*break*/, 5]; + return [4 /*yield*/, lockProm]; + case 4: + _a.sent(); + return [3 /*break*/, 3]; + case 5: + lockProm = new Promise(function (res) { return (unlock = res); }); + _a.label = 6; + case 6: + _a.trys.push([6, , 11, 12]); + return [4 /*yield*/, stWindow.windowHandler.sessionStorage.getItem(MFA_INFO_CACHE_KEY)]; + case 7: + stored_1 = _a.sent(); + if (stored_1 !== null) { + parsed = JSON.parse(stored_1); + if (parsed.t > Date.now() - 1000) { + return [2 /*return*/, utils.__assign(utils.__assign({}, parsed.v), { + // Adding a fake response is not great, but we do want to add something and this way it's detectable by the app + // so they could even add specific handling for it if they preferred. + fetchResponse: new Response(null, { status: 304 }) })]; + } + } + return [4 /*yield*/, originalImp.resyncSessionAndFetchMFAInfo(input)]; + case 8: + val = _a.sent(); + if (!(val.status === "OK")) return [3 /*break*/, 10]; + // We are not storing the fetchResponse + return [4 /*yield*/, stWindow.windowHandler.sessionStorage.setItem(MFA_INFO_CACHE_KEY, JSON.stringify({ + t: Date.now(), + v: { + emails: val.emails, + phoneNumbers: val.phoneNumbers, + factors: val.factors, + status: val.status, + }, + }))]; + case 9: + // We are not storing the fetchResponse + _a.sent(); + _a.label = 10; + case 10: return [2 /*return*/, val]; + case 11: + // Release the lock + lockProm = undefined; + unlock(); + return [7 /*endfinally*/]; + case 12: return [2 /*return*/]; + } + }); + }); + } })); }; }; -var MultiFactorAuthClaimClass = /** @class */ (function () { - function MultiFactorAuthClaimClass(getRecipe, getRedirectURL, onFailureRedirection) { - var _this = this; - this.webJSClaim = new MultiFactorAuthWebJS.MultiFactorAuthClaimClass(function () { - return getRecipe().webJSRecipe; - }); - this.refresh = this.webJSClaim.refresh; - this.getLastFetchedTime = this.webJSClaim.getLastFetchedTime; - this.getValueFromPayload = this.webJSClaim.getValueFromPayload; - this.id = this.webJSClaim.id; - var defaultOnFailureRedirection = function (_a) { - var reason = _a.reason, - userContext = _a.userContext; - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var recipe, nextFactorOptions, availableFactors, mfaInfo_1, availableFactors; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - recipe = getRecipe(); - nextFactorOptions = - reason.oneOf || - reason.allOfInAnyOrder || - (reason.factorId !== undefined ? [reason.factorId] : undefined); - if (!(nextFactorOptions !== undefined)) return [3 /*break*/, 1]; - genericComponentOverrideContext.logDebugMessage( - "Redirecting to MFA on next array from validation failure: " + - nextFactorOptions.join(", ") - ); - availableFactors = recipe - .getSecondaryFactors(userContext) - .filter(function (v) { - return nextFactorOptions.factors.next.includes(v.id); - }) - .map(function (v) { - return v.id; - }); - // In this case we got here from a validator that defined the list of validators - if (availableFactors.length === 1) { - return [ - 2 /*return*/, - getRedirectURL( - { action: "GO_TO_FACTOR", factorId: availableFactors[0] }, - userContext - ), - ]; - } else { - return [ - 2 /*return*/, - getRedirectURL( - { action: "FACTOR_CHOOSER", nextFactorOptions: nextFactorOptions }, - userContext - ), - ]; - } - case 1: - return [ - 4 /*yield*/, - recipe.webJSRecipe.resyncSessionAndFetchMFAInfo({ userContext: userContext }), - ]; - case 2: - mfaInfo_1 = _b.sent(); - availableFactors = recipe - .getSecondaryFactors(userContext) - .filter(function (v) { - return mfaInfo_1.factors.next.includes(v.id); - }) - .map(function (v) { - return v.id; - }); - genericComponentOverrideContext.logDebugMessage( - "Redirecting to MFA on next array from backend: " + availableFactors.join(", ") - ); - if (availableFactors.length === 1) { - return [ - 2 /*return*/, - getRedirectURL( - { action: "GO_TO_FACTOR", factorId: availableFactors[0] }, - userContext - ), - ]; - } else { - return [2 /*return*/, getRedirectURL({ action: "FACTOR_CHOOSER" }, userContext)]; - } - case 3: - // If this happens the user can't complete sign-in (the claim validator fails, but there is no valid next factor for us) - // Returning undefined here will make SessionAuth render an access denied screen. - return [2 /*return*/, undefined]; - } - }); - }); - }; - this.validators = genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, this.webJSClaim.validators), - { - hasCompletedMFARequirementsForAuth: function (doRedirection, showAccessDeniedOnFailure) { - if (doRedirection === void 0) { - doRedirection = true; - } - if (showAccessDeniedOnFailure === void 0) { - showAccessDeniedOnFailure = true; - } - var orig = _this.webJSClaim.validators.hasCompletedMFARequirementsForAuth(); - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, orig), - { - showAccessDeniedOnFailure: showAccessDeniedOnFailure, - onFailureRedirection: - onFailureRedirection !== null && onFailureRedirection !== void 0 - ? onFailureRedirection - : function (_a) { - var reason = _a.reason, - userContext = _a.userContext; - return doRedirection - ? defaultOnFailureRedirection({ - reason: reason, - userContext: userContext, - }) - : undefined; - }, - } - ); - }, - hasCompletedFactors: function (requirements, doRedirection, showAccessDeniedOnFailure) { - if (doRedirection === void 0) { - doRedirection = true; - } - if (showAccessDeniedOnFailure === void 0) { - showAccessDeniedOnFailure = true; - } - var orig = _this.webJSClaim.validators.hasCompletedFactors(requirements); - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, orig), - { - showAccessDeniedOnFailure: showAccessDeniedOnFailure, - onFailureRedirection: - onFailureRedirection !== null && onFailureRedirection !== void 0 - ? onFailureRedirection - : function (_a) { - var reason = _a.reason, - userContext = _a.userContext; - return doRedirection - ? defaultOnFailureRedirection({ - reason: reason, - userContext: userContext, - }) - : undefined; - }, - } - ); - }, - } - ); - } - return MultiFactorAuthClaimClass; -})(); +var MultiFactorAuthClaimClass = /** @class */ (function () { + function MultiFactorAuthClaimClass(getRecipe, getRedirectURL, onFailureRedirection) { + var _this = this; + this.webJSClaim = new MultiFactorAuthWebJS.MultiFactorAuthClaimClass(function () { return getRecipe().webJSRecipe; }); + this.refresh = this.webJSClaim.refresh; + this.getLastFetchedTime = this.webJSClaim.getLastFetchedTime; + this.getValueFromPayload = this.webJSClaim.getValueFromPayload; + this.id = this.webJSClaim.id; + var defaultOnFailureRedirection = function (_a) { + var reason = _a.reason, userContext = _a.userContext; + return utils.__awaiter(_this, void 0, void 0, function () { + var recipe, nextFactorOptions, availableFactors, mfaInfo_1, availableFactors; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + recipe = getRecipe(); + nextFactorOptions = reason.oneOf || + reason.allOfInAnyOrder || + (reason.factorId !== undefined ? [reason.factorId] : undefined); + if (!(nextFactorOptions !== undefined)) return [3 /*break*/, 1]; + utils.logDebugMessage("Redirecting to MFA on next array from validation failure: " + nextFactorOptions.join(", ")); + availableFactors = recipe + .getSecondaryFactors(userContext) + .filter(function (v) { return nextFactorOptions.factors.next.includes(v.id); }) + .map(function (v) { return v.id; }); + // In this case we got here from a validator that defined the list of validators + if (availableFactors.length === 1) { + return [2 /*return*/, getRedirectURL({ action: "GO_TO_FACTOR", factorId: availableFactors[0] }, userContext)]; + } + else { + return [2 /*return*/, getRedirectURL({ action: "FACTOR_CHOOSER", nextFactorOptions: nextFactorOptions }, userContext)]; + } + case 1: return [4 /*yield*/, recipe.webJSRecipe.resyncSessionAndFetchMFAInfo({ userContext: userContext })]; + case 2: + mfaInfo_1 = _b.sent(); + availableFactors = recipe + .getSecondaryFactors(userContext) + .filter(function (v) { return mfaInfo_1.factors.next.includes(v.id); }) + .map(function (v) { return v.id; }); + utils.logDebugMessage("Redirecting to MFA on next array from backend: " + availableFactors.join(", ")); + if (availableFactors.length === 1) { + return [2 /*return*/, getRedirectURL({ action: "GO_TO_FACTOR", factorId: availableFactors[0] }, userContext)]; + } + else { + return [2 /*return*/, getRedirectURL({ action: "FACTOR_CHOOSER" }, userContext)]; + } + case 3: + // If this happens the user can't complete sign-in (the claim validator fails, but there is no valid next factor for us) + // Returning undefined here will make SessionAuth render an access denied screen. + return [2 /*return*/, undefined]; + } + }); + }); + }; + this.validators = utils.__assign(utils.__assign({}, this.webJSClaim.validators), { hasCompletedMFARequirementsForAuth: function (doRedirection, showAccessDeniedOnFailure) { + if (doRedirection === void 0) { doRedirection = true; } + if (showAccessDeniedOnFailure === void 0) { showAccessDeniedOnFailure = true; } + var orig = _this.webJSClaim.validators.hasCompletedMFARequirementsForAuth(); + return utils.__assign(utils.__assign({}, orig), { showAccessDeniedOnFailure: showAccessDeniedOnFailure, onFailureRedirection: onFailureRedirection !== null && onFailureRedirection !== void 0 ? onFailureRedirection : (function (_a) { + var reason = _a.reason, userContext = _a.userContext; + return doRedirection ? defaultOnFailureRedirection({ reason: reason, userContext: userContext }) : undefined; + }) }); + }, hasCompletedFactors: function (requirements, doRedirection, showAccessDeniedOnFailure) { + if (doRedirection === void 0) { doRedirection = true; } + if (showAccessDeniedOnFailure === void 0) { showAccessDeniedOnFailure = true; } + var orig = _this.webJSClaim.validators.hasCompletedFactors(requirements); + return utils.__assign(utils.__assign({}, orig), { showAccessDeniedOnFailure: showAccessDeniedOnFailure, onFailureRedirection: onFailureRedirection !== null && onFailureRedirection !== void 0 ? onFailureRedirection : (function (_a) { + var reason = _a.reason, userContext = _a.userContext; + return doRedirection ? defaultOnFailureRedirection({ reason: reason, userContext: userContext }) : undefined; + }) }); + } }); + } + return MultiFactorAuthClaimClass; +}()); -/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -function normaliseMultiFactorAuthFeature(config) { - var _a; - if (config === undefined) { - config = {}; - } - var disableDefaultUI = config.disableDefaultUI === true; - var override = genericComponentOverrideContext.__assign( - { - functions: function (originalImplementation) { - return originalImplementation; - }, - }, - config.override - ); - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign( - {}, - genericComponentOverrideContext.normaliseRecipeModuleConfig(config) - ), - { - disableDefaultUI: disableDefaultUI, - firstFactors: config === null || config === void 0 ? void 0 : config.firstFactors, - getSecondaryFactorInfo: function (orig) { - return orig; - }, - factorChooserScreen: (_a = config.factorChooserScreen) !== null && _a !== void 0 ? _a : {}, - override: override, - } - ); -} -function getAvailableFactors(factors, nextArrayQueryParam, recipe, userContext) { - genericComponentOverrideContext.logDebugMessage( - "getAvailableFactors: allowed to setup: ".concat(factors.allowedToSetup) - ); - genericComponentOverrideContext.logDebugMessage( - "getAvailableFactors: already setup: ".concat(factors.alreadySetup) - ); - genericComponentOverrideContext.logDebugMessage("getAvailableFactors: next from factorInfo: ".concat(factors.next)); - genericComponentOverrideContext.logDebugMessage( - "getAvailableFactors: nextArrayQueryParam: ".concat(nextArrayQueryParam) - ); - genericComponentOverrideContext.logDebugMessage( - "getAvailableFactors: secondary factors: ".concat( - recipe.getSecondaryFactors(userContext).map(function (f) { - return f.id; - }) - ) - ); - // There are 3 cases here: - // 1. The app provided an array of factors to show (nextArrayQueryParam) -> we show whatever is in the array - // 2. no app provided list and validator passed -> we show all factors available to set up or complete - // 3. no app provided list and validator failing -> we show whatever the BE tells us to (this is already filtered by allowedToSetup&alreadySetup on the BE) - var nextArr = nextArrayQueryParam !== undefined ? nextArrayQueryParam.split(",") : factors.next; - var availableFactors = recipe.getSecondaryFactors(userContext).filter(function (_a) { - var id = _a.id; - return nextArr.length === 0 - ? factors.allowedToSetup.includes(id) || factors.alreadySetup.includes(id) - : nextArr.includes(id); - }); - return availableFactors; +/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +function normaliseMultiFactorAuthFeature(config) { + var _a; + if (config === undefined) { + config = {}; + } + var disableDefaultUI = config.disableDefaultUI === true; + var override = utils.__assign({ functions: function (originalImplementation) { return originalImplementation; } }, config.override); + return utils.__assign(utils.__assign({}, superTokens.normaliseRecipeModuleConfig(config)), { disableDefaultUI: disableDefaultUI, firstFactors: config === null || config === void 0 ? void 0 : config.firstFactors, getSecondaryFactorInfo: function (orig) { return orig; }, factorChooserScreen: (_a = config.factorChooserScreen) !== null && _a !== void 0 ? _a : {}, override: override }); +} +function getAvailableFactors(factors, nextArrayQueryParam, recipe, userContext) { + utils.logDebugMessage("getAvailableFactors: allowed to setup: ".concat(factors.allowedToSetup)); + utils.logDebugMessage("getAvailableFactors: already setup: ".concat(factors.alreadySetup)); + utils.logDebugMessage("getAvailableFactors: next from factorInfo: ".concat(factors.next)); + utils.logDebugMessage("getAvailableFactors: nextArrayQueryParam: ".concat(nextArrayQueryParam)); + utils.logDebugMessage("getAvailableFactors: secondary factors: ".concat(recipe.getSecondaryFactors(userContext).map(function (f) { return f.id; }))); + // There are 3 cases here: + // 1. The app provided an array of factors to show (nextArrayQueryParam) -> we show whatever is in the array + // 2. no app provided list and validator passed -> we show all factors available to set up or complete + // 3. no app provided list and validator failing -> we show whatever the BE tells us to (this is already filtered by allowedToSetup&alreadySetup on the BE) + var nextArr = nextArrayQueryParam !== undefined ? nextArrayQueryParam.split(",") : factors.next; + var availableFactors = recipe + .getSecondaryFactors(userContext) + .filter(function (_a) { + var id = _a.id; + return nextArr.length === 0 + ? factors.allowedToSetup.includes(id) || factors.alreadySetup.includes(id) + : nextArr.includes(id); + }); + return availableFactors; } -/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var MultiFactorAuth = /** @class */ (function (_super) { - genericComponentOverrideContext.__extends(MultiFactorAuth, _super); - function MultiFactorAuth(config, webJSRecipe) { - if (webJSRecipe === void 0) { - webJSRecipe = MultiFactorAuthWebJS__default.default; - } - var _this = _super.call(this, config) || this; - _this.webJSRecipe = webJSRecipe; - _this.recipeID = MultiFactorAuth.RECIPE_ID; - _this.secondaryFactors = []; - _this.getDefaultRedirectionURL = function (context, userContext) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var nParam, redirectInfo; - return genericComponentOverrideContext.__generator(this, function (_b) { - if (context.action === "FACTOR_CHOOSER") { - nParam = - context.nextFactorOptions && context.nextFactorOptions.length > 0 - ? context.nextFactorOptions.join(",") - : undefined; - return [ - 2 /*return*/, - genericComponentOverrideContext.getDefaultRedirectionURLForPath( - this.config, - DEFAULT_FACTOR_CHOOSER_PATH, - context, - { - n: nParam, - stepUp: context.stepUp ? "true" : undefined, - } - ), - ]; - } else if (context.action === "GO_TO_FACTOR") { - redirectInfo = this.getSecondaryFactors(userContext).find(function (f) { - return f.id === context.factorId; - }); - if (redirectInfo !== undefined) { - return [ - 2 /*return*/, - genericComponentOverrideContext.getDefaultRedirectionURLForPath( - this.config, - redirectInfo.path, - context, - { - setup: context.forceSetup ? "true" : undefined, - stepUp: context.stepUp ? "true" : undefined, - } - ), - ]; - } - throw new Error("Requested redirect to unknown factor id: " + context.factorId); - } else { - return [2 /*return*/, "/"]; - } - }); - }); - }; - postSuperTokensInitCallbacks.PostSuperTokensInitCallbacks.addPostInitCallback(function () { - var defaultFactorsValidator = - MultiFactorAuth.MultiFactorAuthClaim.validators.hasCompletedMFARequirementsForAuth(); - sessionClaimValidatorStore.SessionClaimValidatorStore.addClaimValidatorFromOtherRecipe( - defaultFactorsValidator - ); - types.Session.getInstanceOrThrow().addEventListener(function () { - // We clear the cache if the session updated, since that may mean that the MFA info has changed - var stWindow = windowHandler.WindowHandlerReference.getReferenceOrThrow(); - stWindow.windowHandler.sessionStorage.removeItemSync(MFA_INFO_CACHE_KEY); - }); - }); - return _this; - } - MultiFactorAuth.init = function (config) { - var normalisedConfig = normaliseMultiFactorAuthFeature(config); - return { - recipeID: MultiFactorAuth.RECIPE_ID, - authReact: function (appInfo) { - MultiFactorAuth.instance = new MultiFactorAuth( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, normalisedConfig), - { appInfo: appInfo, recipeId: MultiFactorAuth.RECIPE_ID } - ) - ); - return MultiFactorAuth.instance; - }, - webJS: MultiFactorAuthWebJS__default.default.init( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, normalisedConfig), - { - override: { - functions: function (originalImpl, builder) { - var functions = getFunctionOverrides(normalisedConfig.onHandleEvent); - builder.override(functions); - builder.override(normalisedConfig.override.functions); - return originalImpl; - }, - }, - } - ) - ), - }; - }; - MultiFactorAuth.getInstance = function () { - return MultiFactorAuth.instance; - }; - MultiFactorAuth.getInstanceOrThrow = function () { - if (MultiFactorAuth.instance === undefined) { - var error = "No instance of MultiFactorAuth found. Make sure to call the MultiFactorAuth.init method."; - // eslint-disable-next-line supertokens-auth-react/no-direct-window-object - if (typeof window === "undefined") { - error = error + genericComponentOverrideContext.SSR_ERROR; - } - throw Error(error); - } - return MultiFactorAuth.instance; - }; - MultiFactorAuth.prototype.addMFAFactors = function (secondaryFactors) { - this.secondaryFactors = genericComponentOverrideContext.__spreadArray( - genericComponentOverrideContext.__spreadArray( - [], - this.secondaryFactors.filter(function (factor) { - return secondaryFactors.every(function (newFactor) { - return factor.id !== newFactor.id; - }); - }), - true - ), - secondaryFactors, - true - ); - }; - MultiFactorAuth.prototype.isFirstFactorEnabledOnClient = function (factorId) { - return this.config.firstFactors === undefined || this.config.firstFactors.includes(factorId); - }; - MultiFactorAuth.prototype.getSecondaryFactors = function (userContext) { - return this.config.getSecondaryFactorInfo(this.secondaryFactors, userContext); - }; - MultiFactorAuth.prototype.redirectToFactor = function (_b) { - var factorId = _b.factorId, - forceSetup = _b.forceSetup, - stepUp = _b.stepUp, - redirectBack = _b.redirectBack, - navigate = _b.navigate, - userContext = _b.userContext; - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var url, redirectUrl, redirectUrl; - return genericComponentOverrideContext.__generator(this, function (_c) { - switch (_c.label) { - case 0: - return [ - 4 /*yield*/, - this.getRedirectUrl( - { - action: "GO_TO_FACTOR", - forceSetup: forceSetup, - stepUp: stepUp, - factorId: factorId, - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - }, - utils.getNormalisedUserContext(userContext) - ), - ]; - case 1: - url = _c.sent(); - if (url === null) { - return [2 /*return*/]; - } - // If redirectBack was set to true we always set redirectToPath to that value - // otherwise we try and get it from the query params, finally falling back to not setting it. - // Example: - // 1. If the app calls this on pathX and with redirectBack=false, we redirect to /auth/mfa/factor-id - // 2. If the app calls this on pathX and with redirectBack=true, we redirect to /auth/mfa/factor-id?redirectToPath=pathX - // 3. If: - // - the app redirects to the factor chooser with redirectBack=true from path=X, they end up on /auth/mfa?redirectToPath=pathX - // - the factor chooser screen then calls this with redirectBack=false, then they end up on /auth/mfa/factor-id?redirectToPath=pathX - // 4. In the unlikely case that the app itself uses a `redirectToPath` query param internally - // and is on a custom path that has a redirectToPath set to pathX when calling this function, - // then we keep that in the query params if redirectBack is set to false. - if (redirectBack) { - redirectUrl = - genericComponentOverrideContext.getCurrentNormalisedUrlPathWithQueryParamsAndFragments(); - url = genericComponentOverrideContext.appendQueryParamsToURL(url, { - redirectToPath: redirectUrl, - }); - } else { - redirectUrl = genericComponentOverrideContext.getRedirectToPathFromURL(); - if (redirectUrl) { - url = genericComponentOverrideContext.appendQueryParamsToURL(url, { - redirectToPath: redirectUrl, - }); - } - } - return [ - 2 /*return*/, - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToUrl( - url, - navigate - ), - ]; - } - }); - }); - }; - MultiFactorAuth.prototype.redirectToFactorChooser = function (_b) { - var _c = _b.redirectBack, - redirectBack = _c === void 0 ? false : _c, - _d = _b.nextFactorOptions, - nextFactorOptions = _d === void 0 ? [] : _d, - stepUp = _b.stepUp, - navigate = _b.navigate, - userContext = _b.userContext; - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var url, redirectUrl, redirectUrl; - return genericComponentOverrideContext.__generator(this, function (_e) { - switch (_e.label) { - case 0: - return [ - 4 /*yield*/, - this.getRedirectUrl( - { - action: "FACTOR_CHOOSER", - nextFactorOptions: nextFactorOptions, - stepUp: stepUp, - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - }, - utils.getNormalisedUserContext(userContext) - ), - ]; - case 1: - url = _e.sent(); - if (url === null) { - return [2 /*return*/]; - } - if (redirectBack) { - redirectUrl = - genericComponentOverrideContext.getCurrentNormalisedUrlPathWithQueryParamsAndFragments(); - url = genericComponentOverrideContext.appendQueryParamsToURL(url, { - redirectToPath: redirectUrl, - }); - } else { - redirectUrl = genericComponentOverrideContext.getRedirectToPathFromURL(); - if (redirectUrl) { - url = genericComponentOverrideContext.appendQueryParamsToURL(url, { - redirectToPath: redirectUrl, - }); - } - } - return [ - 2 /*return*/, - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToUrl( - url, - navigate - ), - ]; - } - }); - }); - }; - /* - * Tests methods. - */ - MultiFactorAuth.reset = function () { - if (!genericComponentOverrideContext.isTest()) { - return; - } - MultiFactorAuth.instance = undefined; - return; - }; - var _a; - _a = MultiFactorAuth; - MultiFactorAuth.RECIPE_ID = "multifactorauth"; - MultiFactorAuth.MultiFactorAuthClaim = new MultiFactorAuthClaimClass( - function () { - return MultiFactorAuth.getInstanceOrThrow(); - }, - function (context, userContext) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(_a, function (_b) { - switch (_b.label) { - case 0: - return [ - 4 /*yield*/, - this.getInstanceOrThrow().getRedirectUrl( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, context), - { - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - } - ), - userContext - ), - ]; - case 1: - return [2 /*return*/, _b.sent() || undefined]; - } - }); - }); - } - ); - return MultiFactorAuth; -})(index.RecipeModule); +/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var MultiFactorAuth = /** @class */ (function (_super) { + utils.__extends(MultiFactorAuth, _super); + function MultiFactorAuth(config, webJSRecipe) { + if (webJSRecipe === void 0) { webJSRecipe = MultiFactorAuthWebJS__default.default; } + var _this = _super.call(this, config) || this; + _this.webJSRecipe = webJSRecipe; + _this.recipeID = MultiFactorAuth.RECIPE_ID; + _this.secondaryFactors = []; + _this.getDefaultRedirectionURL = function (context, userContext) { return utils.__awaiter(_this, void 0, void 0, function () { + var nParam, redirectInfo; + return utils.__generator(this, function (_b) { + if (context.action === "FACTOR_CHOOSER") { + nParam = context.nextFactorOptions && context.nextFactorOptions.length > 0 + ? context.nextFactorOptions.join(",") + : undefined; + return [2 /*return*/, utils.getDefaultRedirectionURLForPath(this.config, DEFAULT_FACTOR_CHOOSER_PATH, context, { + n: nParam, + stepUp: context.stepUp ? "true" : undefined, + })]; + } + else if (context.action === "GO_TO_FACTOR") { + redirectInfo = this.getSecondaryFactors(userContext).find(function (f) { return f.id === context.factorId; }); + if (redirectInfo !== undefined) { + return [2 /*return*/, utils.getDefaultRedirectionURLForPath(this.config, redirectInfo.path, context, { + setup: context.forceSetup ? "true" : undefined, + stepUp: context.stepUp ? "true" : undefined, + })]; + } + throw new Error("Requested redirect to unknown factor id: " + context.factorId); + } + else { + return [2 /*return*/, "/"]; + } + }); + }); }; + postSuperTokensInitCallbacks.PostSuperTokensInitCallbacks.addPostInitCallback(function () { + var defaultFactorsValidator = MultiFactorAuth.MultiFactorAuthClaim.validators.hasCompletedMFARequirementsForAuth(); + sessionClaimValidatorStore.SessionClaimValidatorStore.addClaimValidatorFromOtherRecipe(defaultFactorsValidator); + types.Session.getInstanceOrThrow().addEventListener(function () { + // We clear the cache if the session updated, since that may mean that the MFA info has changed + var stWindow = windowHandler.WindowHandlerReference.getReferenceOrThrow(); + stWindow.windowHandler.sessionStorage.removeItemSync(MFA_INFO_CACHE_KEY); + }); + }); + return _this; + } + MultiFactorAuth.init = function (config) { + var normalisedConfig = normaliseMultiFactorAuthFeature(config); + return { + recipeID: MultiFactorAuth.RECIPE_ID, + authReact: function (appInfo) { + MultiFactorAuth.instance = new MultiFactorAuth(utils.__assign(utils.__assign({}, normalisedConfig), { appInfo: appInfo, recipeId: MultiFactorAuth.RECIPE_ID })); + return MultiFactorAuth.instance; + }, + webJS: MultiFactorAuthWebJS__default.default.init(utils.__assign(utils.__assign({}, normalisedConfig), { override: { + functions: function (originalImpl, builder) { + var functions = getFunctionOverrides(normalisedConfig.onHandleEvent); + builder.override(functions); + builder.override(normalisedConfig.override.functions); + return originalImpl; + }, + } })), + }; + }; + MultiFactorAuth.getInstance = function () { + return MultiFactorAuth.instance; + }; + MultiFactorAuth.getInstanceOrThrow = function () { + if (MultiFactorAuth.instance === undefined) { + var error = "No instance of MultiFactorAuth found. Make sure to call the MultiFactorAuth.init method."; + // eslint-disable-next-line supertokens-auth-react/no-direct-window-object + if (typeof window === "undefined") { + error = error + utils.SSR_ERROR; + } + throw Error(error); + } + return MultiFactorAuth.instance; + }; + MultiFactorAuth.prototype.addMFAFactors = function (secondaryFactors) { + this.secondaryFactors = utils.__spreadArray(utils.__spreadArray([], this.secondaryFactors.filter(function (factor) { + return secondaryFactors.every(function (newFactor) { return factor.id !== newFactor.id; }); + }), true), secondaryFactors, true); + }; + MultiFactorAuth.prototype.isFirstFactorEnabledOnClient = function (factorId) { + return this.config.firstFactors === undefined || this.config.firstFactors.includes(factorId); + }; + MultiFactorAuth.prototype.getSecondaryFactors = function (userContext) { + return this.config.getSecondaryFactorInfo(this.secondaryFactors, userContext); + }; + MultiFactorAuth.prototype.redirectToFactor = function (_b) { + var factorId = _b.factorId, forceSetup = _b.forceSetup, stepUp = _b.stepUp, redirectBack = _b.redirectBack, navigate = _b.navigate, userContext = _b.userContext; + return utils.__awaiter(this, void 0, void 0, function () { + var url, redirectUrl, redirectUrl; + return utils.__generator(this, function (_c) { + switch (_c.label) { + case 0: return [4 /*yield*/, this.getRedirectUrl({ + action: "GO_TO_FACTOR", + forceSetup: forceSetup, + stepUp: stepUp, + factorId: factorId, + tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), + }, utils$1.getNormalisedUserContext(userContext))]; + case 1: + url = _c.sent(); + if (url === null) { + return [2 /*return*/]; + } + // If redirectBack was set to true we always set redirectToPath to that value + // otherwise we try and get it from the query params, finally falling back to not setting it. + // Example: + // 1. If the app calls this on pathX and with redirectBack=false, we redirect to /auth/mfa/factor-id + // 2. If the app calls this on pathX and with redirectBack=true, we redirect to /auth/mfa/factor-id?redirectToPath=pathX + // 3. If: + // - the app redirects to the factor chooser with redirectBack=true from path=X, they end up on /auth/mfa?redirectToPath=pathX + // - the factor chooser screen then calls this with redirectBack=false, then they end up on /auth/mfa/factor-id?redirectToPath=pathX + // 4. In the unlikely case that the app itself uses a `redirectToPath` query param internally + // and is on a custom path that has a redirectToPath set to pathX when calling this function, + // then we keep that in the query params if redirectBack is set to false. + if (redirectBack) { + redirectUrl = utils.getCurrentNormalisedUrlPathWithQueryParamsAndFragments(); + url = utils.appendQueryParamsToURL(url, { redirectToPath: redirectUrl }); + } + else { + redirectUrl = utils.getRedirectToPathFromURL(); + if (redirectUrl) { + url = utils.appendQueryParamsToURL(url, { redirectToPath: redirectUrl }); + } + } + return [2 /*return*/, superTokens.SuperTokens.getInstanceOrThrow().redirectToUrl(url, navigate)]; + } + }); + }); + }; + MultiFactorAuth.prototype.redirectToFactorChooser = function (_b) { + var _c = _b.redirectBack, redirectBack = _c === void 0 ? false : _c, _d = _b.nextFactorOptions, nextFactorOptions = _d === void 0 ? [] : _d, stepUp = _b.stepUp, navigate = _b.navigate, userContext = _b.userContext; + return utils.__awaiter(this, void 0, void 0, function () { + var url, redirectUrl, redirectUrl; + return utils.__generator(this, function (_e) { + switch (_e.label) { + case 0: return [4 /*yield*/, this.getRedirectUrl({ + action: "FACTOR_CHOOSER", + nextFactorOptions: nextFactorOptions, + stepUp: stepUp, + tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), + }, utils$1.getNormalisedUserContext(userContext))]; + case 1: + url = _e.sent(); + if (url === null) { + return [2 /*return*/]; + } + if (redirectBack) { + redirectUrl = utils.getCurrentNormalisedUrlPathWithQueryParamsAndFragments(); + url = utils.appendQueryParamsToURL(url, { redirectToPath: redirectUrl }); + } + else { + redirectUrl = utils.getRedirectToPathFromURL(); + if (redirectUrl) { + url = utils.appendQueryParamsToURL(url, { redirectToPath: redirectUrl }); + } + } + return [2 /*return*/, superTokens.SuperTokens.getInstanceOrThrow().redirectToUrl(url, navigate)]; + } + }); + }); + }; + /* + * Tests methods. + */ + MultiFactorAuth.reset = function () { + if (!utils.isTest()) { + return; + } + MultiFactorAuth.instance = undefined; + return; + }; + var _a; + _a = MultiFactorAuth; + MultiFactorAuth.RECIPE_ID = "multifactorauth"; + MultiFactorAuth.MultiFactorAuthClaim = new MultiFactorAuthClaimClass(function () { return MultiFactorAuth.getInstanceOrThrow(); }, function (context, userContext) { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(_a, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, this.getInstanceOrThrow().getRedirectUrl(utils.__assign(utils.__assign({}, context), { tenantIdFromQueryParams: utils.getTenantIdFromQueryParams() }), userContext)]; + case 1: return [2 /*return*/, (_b.sent()) || undefined]; + } + }); + }); }); + return MultiFactorAuth; +}(index.RecipeModule)); exports.DEFAULT_FACTOR_CHOOSER_PATH = DEFAULT_FACTOR_CHOOSER_PATH; exports.MultiFactorAuth = MultiFactorAuth; diff --git a/lib/build/multifactorauth-shared3.js b/lib/build/multifactorauth-shared3.js index bd3b554b5..7d16271fd 100644 --- a/lib/build/multifactorauth-shared3.js +++ b/lib/build/multifactorauth-shared3.js @@ -1,10 +1,8 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); +var genericComponentOverrideContext = require('./genericComponentOverrideContext.js'); -var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), - useContext = _a[0], - Provider = _a[1]; +var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), useContext = _a[0], Provider = _a[1]; exports.Provider = Provider; exports.useContext = useContext; diff --git a/lib/build/multifactorauth.js b/lib/build/multifactorauth.js index f0fe2be1e..9eeb16d09 100644 --- a/lib/build/multifactorauth.js +++ b/lib/build/multifactorauth.js @@ -1,88 +1,86 @@ -"use strict"; +'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, '__esModule', { value: true }); -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var componentOverrideContext = require("./multifactorauth-shared3.js"); -var recipe = require("./multifactorauth-shared2.js"); -var types = require("./multifactorauth-shared.js"); -require("supertokens-web-js"); -require("supertokens-web-js/utils/cookieHandler"); -require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -require("supertokens-web-js/utils/windowHandler"); -require("supertokens-web-js/recipe/multitenancy"); -require("supertokens-web-js/utils"); -require("react"); -require("supertokens-web-js/lib/build/error"); -require("supertokens-web-js/utils/normalisedURLDomain"); -require("supertokens-web-js/utils/normalisedURLPath"); -require("react/jsx-runtime"); -require("supertokens-web-js/recipe/multifactorauth"); -require("supertokens-web-js/utils/sessionClaimValidatorStore"); -require("./recipeModule-shared.js"); -require("supertokens-web-js/recipe/session"); -require("./oauth2provider-shared.js"); -require("supertokens-web-js/recipe/oauth2provider"); +var utils = require('./utils.js'); +var componentOverrideContext = require('./multifactorauth-shared3.js'); +var recipe = require('./multifactorauth-shared2.js'); +var types = require('./multifactorauth-shared.js'); +require('react'); +require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('supertokens-web-js/utils/normalisedURLPath'); +require('supertokens-web-js/utils/windowHandler'); +require('crypto'); +require('./genericComponentOverrideContext.js'); +require('react/jsx-runtime'); +require('supertokens-web-js/recipe/multifactorauth'); +require('supertokens-web-js/utils'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('supertokens-web-js/utils/sessionClaimValidatorStore'); +require('./superTokens.js'); +require('supertokens-web-js'); +require('supertokens-web-js/recipe/multitenancy'); +require('./recipeModule-shared.js'); +require('supertokens-web-js/recipe/session'); +require('./oauth2provider-shared.js'); +require('supertokens-web-js/recipe/oauth2provider'); -/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var Wrapper = /** @class */ (function () { - function Wrapper() {} - Wrapper.init = function (config) { - return recipe.MultiFactorAuth.init(config); - }; - Wrapper.resyncSessionAndFetchMFAInfo = function (input) { - return recipe.MultiFactorAuth.getInstanceOrThrow().webJSRecipe.resyncSessionAndFetchMFAInfo( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ); - }; - Wrapper.redirectToFactor = function (input) { - var _a, _b, _c; - return recipe.MultiFactorAuth.getInstanceOrThrow().redirectToFactor({ - factorId: input.factorId, - forceSetup: (_a = input.forceSetup) !== null && _a !== void 0 ? _a : false, - redirectBack: (_b = input.redirectBack) !== null && _b !== void 0 ? _b : true, - stepUp: (_c = input.stepUp) !== null && _c !== void 0 ? _c : false, - navigate: input.navigate, - userContext: genericComponentOverrideContext.getNormalisedUserContext(input.userContext), - }); - }; - Wrapper.redirectToFactorChooser = function (input) { - var _a, _b, _c; - return recipe.MultiFactorAuth.getInstanceOrThrow().redirectToFactorChooser({ - nextFactorOptions: (_a = input.nextFactorOptions) !== null && _a !== void 0 ? _a : [], - redirectBack: (_b = input.redirectBack) !== null && _b !== void 0 ? _b : true, - stepUp: (_c = input.stepUp) !== null && _c !== void 0 ? _c : false, - navigate: input.navigate, - userContext: genericComponentOverrideContext.getNormalisedUserContext(input.userContext), - }); - }; - Wrapper.MultiFactorAuthClaim = recipe.MultiFactorAuth.MultiFactorAuthClaim; - Wrapper.FactorIds = types.FactorIds; - Wrapper.ComponentsOverrideProvider = componentOverrideContext.Provider; - return Wrapper; -})(); -var init = Wrapper.init; -var resyncSessionAndFetchMFAInfo = Wrapper.resyncSessionAndFetchMFAInfo; -var redirectToFactor = Wrapper.redirectToFactor; -var redirectToFactorChooser = Wrapper.redirectToFactorChooser; -var MultiFactorAuthComponentsOverrideProvider = Wrapper.ComponentsOverrideProvider; +/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var Wrapper = /** @class */ (function () { + function Wrapper() { + } + Wrapper.init = function (config) { + return recipe.MultiFactorAuth.init(config); + }; + Wrapper.resyncSessionAndFetchMFAInfo = function (input) { + return recipe.MultiFactorAuth.getInstanceOrThrow().webJSRecipe.resyncSessionAndFetchMFAInfo(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) })); + }; + Wrapper.redirectToFactor = function (input) { + var _a, _b, _c; + return recipe.MultiFactorAuth.getInstanceOrThrow().redirectToFactor({ + factorId: input.factorId, + forceSetup: (_a = input.forceSetup) !== null && _a !== void 0 ? _a : false, + redirectBack: (_b = input.redirectBack) !== null && _b !== void 0 ? _b : true, + stepUp: (_c = input.stepUp) !== null && _c !== void 0 ? _c : false, + navigate: input.navigate, + userContext: utils.getNormalisedUserContext(input.userContext), + }); + }; + Wrapper.redirectToFactorChooser = function (input) { + var _a, _b, _c; + return recipe.MultiFactorAuth.getInstanceOrThrow().redirectToFactorChooser({ + nextFactorOptions: (_a = input.nextFactorOptions) !== null && _a !== void 0 ? _a : [], + redirectBack: (_b = input.redirectBack) !== null && _b !== void 0 ? _b : true, + stepUp: (_c = input.stepUp) !== null && _c !== void 0 ? _c : false, + navigate: input.navigate, + userContext: utils.getNormalisedUserContext(input.userContext), + }); + }; + Wrapper.MultiFactorAuthClaim = recipe.MultiFactorAuth.MultiFactorAuthClaim; + Wrapper.FactorIds = types.FactorIds; + Wrapper.ComponentsOverrideProvider = componentOverrideContext.Provider; + return Wrapper; +}()); +var init = Wrapper.init; +var resyncSessionAndFetchMFAInfo = Wrapper.resyncSessionAndFetchMFAInfo; +var redirectToFactor = Wrapper.redirectToFactor; +var redirectToFactorChooser = Wrapper.redirectToFactorChooser; +var MultiFactorAuthComponentsOverrideProvider = Wrapper.ComponentsOverrideProvider; var MultiFactorAuthClaim = recipe.MultiFactorAuth.MultiFactorAuthClaim; exports.FactorIds = types.FactorIds; diff --git a/lib/build/multifactorauthprebuiltui.js b/lib/build/multifactorauthprebuiltui.js index f7a16c3ab..32a2f4ba0 100644 --- a/lib/build/multifactorauthprebuiltui.js +++ b/lib/build/multifactorauthprebuiltui.js @@ -1,60 +1,53 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var jsxRuntime = require("react/jsx-runtime"); -var NormalisedURLPath = require("supertokens-web-js/utils/normalisedURLPath"); -var uiEntry = require("./index2.js"); -var session = require("./session.js"); -var componentOverrideContext = require("./multifactorauth-shared3.js"); -var React = require("react"); -var windowHandler = require("supertokens-web-js/utils/windowHandler"); -var types = require("./multifactorauth-shared.js"); -var recipe = require("./multifactorauth-shared2.js"); -var translationContext = require("./translationContext.js"); -var sessionprebuiltui = require("./sessionprebuiltui.js"); -var arrowLeftIcon = require("./arrowLeftIcon.js"); -require("supertokens-web-js"); -require("supertokens-web-js/utils/cookieHandler"); -require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -require("supertokens-web-js/recipe/multitenancy"); -require("supertokens-web-js/utils"); -require("supertokens-web-js/lib/build/error"); -require("supertokens-web-js/utils/normalisedURLDomain"); -require("react-dom"); -require("./multitenancy-shared.js"); -require("./oauth2provider-shared.js"); -require("supertokens-web-js/recipe/oauth2provider"); -require("./recipeModule-shared.js"); -require("./authRecipe-shared.js"); -require("supertokens-web-js/lib/build/normalisedURLPath"); -require("supertokens-web-js/recipe/session"); -require("./session-shared.js"); -require("supertokens-web-js/recipe/multifactorauth"); -require("supertokens-web-js/utils/sessionClaimValidatorStore"); +var utils = require('./utils.js'); +var jsxRuntime = require('react/jsx-runtime'); +var NormalisedURLPath = require('supertokens-web-js/utils/normalisedURLPath'); +var uiEntry = require('./index2.js'); +var session = require('./session.js'); +var componentOverrideContext = require('./multifactorauth-shared3.js'); +var React = require('react'); +var windowHandler = require('supertokens-web-js/utils/windowHandler'); +var superTokens = require('./superTokens.js'); +var types = require('./multifactorauth-shared.js'); +var recipe = require('./multifactorauth-shared2.js'); +var translationContext = require('./translationContext.js'); +var sessionprebuiltui = require('./sessionprebuiltui.js'); +var arrowLeftIcon = require('./arrowLeftIcon.js'); +require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('crypto'); +require('react-dom'); +require('./multitenancy-shared.js'); +require('./genericComponentOverrideContext.js'); +require('./oauth2provider-shared.js'); +require('supertokens-web-js/recipe/oauth2provider'); +require('./recipeModule-shared.js'); +require('./authRecipe-shared.js'); +require('supertokens-web-js/lib/build/normalisedURLPath'); +require('supertokens-web-js/recipe/session'); +require('./session-shared.js'); +require('supertokens-web-js'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('supertokens-web-js/recipe/multitenancy'); +require('supertokens-web-js/utils'); +require('supertokens-web-js/recipe/multifactorauth'); +require('supertokens-web-js/utils/sessionClaimValidatorStore'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { - if (k !== "default") { + if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: function () { - return e[k]; - }, - } - ); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); } }); } @@ -62,557 +55,237 @@ function _interopNamespace(e) { return Object.freeze(n); } -var NormalisedURLPath__default = /*#__PURE__*/ _interopDefault(NormalisedURLPath); -var React__namespace = /*#__PURE__*/ _interopNamespace(React); +var NormalisedURLPath__default = /*#__PURE__*/_interopDefault(NormalisedURLPath); +var React__namespace = /*#__PURE__*/_interopNamespace(React); -var styles = - '[data-supertokens~="container"] {\n --palette-background: 255, 255, 255;\n --palette-inputBackground: 250, 250, 250;\n --palette-inputBorder: 224, 224, 224;\n --palette-primary: 28, 34, 42;\n --palette-primaryBorder: 45, 54, 68;\n --palette-success: 65, 167, 0;\n --palette-successBackground: 217, 255, 191;\n --palette-error: 255, 23, 23;\n --palette-errorBackground: 255, 241, 235;\n --palette-textTitle: 0, 0, 0;\n --palette-textLabel: 0, 0, 0;\n --palette-textInput: 0, 0, 0;\n --palette-textPrimary: 128, 128, 128;\n --palette-textLink: 0, 122, 255;\n --palette-buttonText: 255, 255, 255;\n --palette-textGray: 54, 54, 54;\n --palette-superTokensBrandingBackground: 242, 245, 246;\n --palette-superTokensBrandingText: 173, 189, 196;\n --palette-buttonGreyedOut: 221, 221, 221;\n --palette-caution: 124, 96, 62;\n --palette-errorDark: 207, 54, 68;\n\n --font-size-0: 12px;\n --font-size-1: 14px;\n --font-size-2: 16px;\n --font-size-3: 19px;\n --font-size-4: 24px;\n --font-size-5: 28px;\n}\n/*\n * Default styles.\n */\n@keyframes slideTop {\n 0% {\n transform: translateY(-5px);\n }\n 100% {\n transform: translateY(0px);\n }\n}\n@keyframes swing-in-top-fwd {\n 0% {\n transform: rotateX(-100deg);\n transform-origin: top;\n opacity: 0;\n }\n 100% {\n transform: rotateX(0deg);\n transform-origin: top;\n opacity: 1;\n }\n}\n[data-supertokens~="container"] {\n font-family: "Arial", sans-serif;\n margin: 12px auto;\n margin-top: 26px;\n margin-bottom: 26px;\n width: 420px;\n text-align: center;\n border-radius: 8px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.16);\n background-color: rgb(var(--palette-background));\n}\n@media (max-width: 440px) {\n [data-supertokens~="container"] {\n width: 95vw;\n }\n}\n[data-supertokens~="row"] {\n margin: 0 auto;\n width: 76%;\n padding-top: 30px;\n padding-bottom: 10px;\n}\n[data-supertokens~="superTokensBranding"] {\n display: block;\n margin: 10px auto 0;\n background: rgb(var(--palette-superTokensBrandingBackground));\n color: rgb(var(--palette-superTokensBrandingText));\n text-decoration: none;\n width: -webkit-fit-content;\n width: fit-content;\n border-radius: 6px 6px 0 0;\n padding: 4px 9px;\n font-weight: 400;\n font-size: var(--font-size-0);\n letter-spacing: 0.4px;\n}\n[data-supertokens~="generalError"] {\n background: rgb(var(--palette-errorBackground));\n padding-top: 10px;\n padding-bottom: 10px;\n margin-bottom: 10px;\n margin-top: 24px;\n padding-left: 18px;\n padding-right: 18px;\n letter-spacing: 0.2px;\n font-size: var(--font-size-1);\n border-radius: 8px;\n color: rgb(var(--palette-error));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n word-wrap: break-word;\n}\n[data-supertokens~="headerTitle"] {\n font-size: var(--font-size-4);\n line-height: 27.6px;\n letter-spacing: 0.58px;\n font-weight: 700;\n margin-bottom: 20px;\n color: rgb(var(--palette-textTitle));\n}\n[data-supertokens~="headerSubtitle"] {\n font-weight: 400;\n color: rgb(var(--palette-textGray));\n margin-bottom: 21px;\n}\n[data-supertokens~="headerSubtitle"][data-supertokens~="secondaryText"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n}\n[data-supertokens~="privacyPolicyAndTermsAndConditions"] {\n max-width: 300px;\n margin-top: 10px;\n}\n[data-supertokens~="privacyPolicyAndTermsAndConditions"] a {\n line-height: 21px;\n}\n/* TODO: split the link style into separate things*/\n/* We add this before primary and secondary text, because if they are applied to the same element the other ones take priority */\n[data-supertokens~="link"] {\n padding-left: 3px;\n padding-right: 3px;\n color: rgb(var(--palette-textLink));\n font-size: var(--font-size-1);\n cursor: pointer;\n letter-spacing: 0.16px;\n line-height: 26px;\n}\n[data-supertokens~="primaryText"] {\n font-size: var(--font-size-2);\n font-weight: 400;\n letter-spacing: 0.4px;\n line-height: 21px;\n color: rgb(var(--palette-textLabel));\n}\n[data-supertokens~="secondaryText"] {\n font-size: var(--font-size-1);\n font-weight: 400;\n letter-spacing: 0.4px;\n color: rgb(var(--palette-textPrimary));\n}\n[data-supertokens~="secondaryText"] strong {\n font-weight: 600;\n}\n[data-supertokens~="divider"] {\n margin-top: 1.5em;\n margin-bottom: 1.5em;\n border-bottom: 0.3px solid #dddddd;\n align-items: center;\n padding-bottom: 5px;\n flex: 3 3;\n}\n[data-supertokens~="headerTinyTitle"] {\n margin-top: 24px;\n font-size: var(--font-size-5);\n letter-spacing: 1.1px;\n font-weight: 700;\n line-height: 28px;\n}\n[data-supertokens~="secondaryLinkWithArrow"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n}\n[data-supertokens~="secondaryLinkWithArrow"]:hover {\n position: relative;\n left: 2px;\n word-spacing: 4px;\n}\n[data-supertokens~="generalSuccess"] {\n color: rgb(var(--palette-success));\n font-size: var(--font-size-1);\n background: rgb(var(--palette-successBackground));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n padding: 9px 15px 9px 15px;\n border-radius: 6px;\n display: inline-block;\n}\n[data-supertokens~="spinner"] {\n width: 80px;\n height: auto;\n padding-top: 20px;\n padding-bottom: 40px;\n margin: 0 auto;\n}\n[data-supertokens~="error"] {\n color: rgb(var(--palette-error));\n}\n[data-supertokens~="linkButton"] {\n font-family: "Arial", sans-serif;\n background-color: transparent;\n border: 0;\n}\n[data-supertokens~="secondaryLinkWithLeftArrow"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n margin-top: 10px;\n margin-bottom: 40px;\n cursor: pointer;\n}\n[data-supertokens~="secondaryLinkWithLeftArrow"] svg {\n margin-right: 0.3em;\n}\n[data-supertokens~="secondaryLinkWithLeftArrow"]:hover svg {\n position: relative;\n left: -4px;\n}\n[data-supertokens~="button"] {\n font-family: "Arial", sans-serif;\n background-color: rgb(var(--palette-primary));\n color: rgb(var(--palette-buttonText));\n width: 100%;\n height: 34px;\n font-weight: 600;\n border-width: 1px;\n border-style: solid;\n border-radius: 6px;\n border-color: rgb(var(--palette-primaryBorder));\n background-position: center;\n transition: all 0.4s;\n background-size: 12000%;\n cursor: pointer;\n}\n[data-supertokens~="buttonGreyedOut"] {\n background-color: rgb(var(--palette-buttonGreyedOut));\n border-color: rgb(var(--palette-buttonGreyedOut));\n}\n[data-supertokens~="buttonWithIcon"] {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n}\n[data-supertokens~="button"]:disabled {\n border: none;\n cursor: no-drop;\n}\n[data-supertokens~="button"]:active {\n outline: none;\n transition: all 0s;\n background-size: 100%;\n filter: brightness(0.85);\n}\n[data-supertokens~="button"]:focus {\n outline: none;\n}\n[data-supertokens~="backButtonCommon"] {\n width: 16px;\n height: 13px;\n}\n[data-supertokens~="backButton"] {\n cursor: pointer;\n border: none;\n background-color: transparent;\n padding: 0px;\n}\n[data-supertokens~="backButtonPlaceholder"] {\n display: block;\n}\n[data-supertokens~="delayedRender"] {\n animation-duration: 0.1s;\n animation-name: animate-fade;\n animation-delay: 0.2s;\n animation-fill-mode: backwards;\n}\n@keyframes animate-fade {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n[data-supertokens~="footerLinkGroupVert"] {\n display: flex;\n flex-direction: column;\n margin-top: 10px;\n gap: 24px;\n}\n[data-supertokens~="footerLinkGroupVert"] > div {\n cursor: pointer;\n margin: 0;\n}\n[data-supertokens~="footerLinkGroupVert"] [data-supertokens~="secondaryText"] {\n font-weight: 400;\n}\n[data-supertokens~="footerLinkGroupVert"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n font-weight: 400;\n position: relative;\n left: -6px; /* half the width of the left arrow */\n}\n@media (max-width: 360px) {\n [data-supertokens~="footerLinkGroupVert"] {\n flex-direction: column;\n }\n [data-supertokens~="footerLinkGroupVert"] > div {\n margin: 0 auto;\n }\n}\n[data-supertokens~="footerLinkGroupVert"] div:only-child {\n margin-left: auto;\n margin-right: auto;\n margin-top: 14px;\n}\n[data-supertokens~="withBackButton"] {\n position: relative;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n[data-supertokens~="dividerWithOr"] {\n padding-top: 5px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n color: rgb(var(--palette-textPrimary));\n}\n[data-supertokens~="dividerText"] {\n flex: 1 1;\n font-weight: 400;\n font-size: var(--font-size-1);\n}\n[data-supertokens~="formLabelWithLinkWrapper"] {\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n[data-supertokens~="formLabelLinkBtn"] {\n width: auto;\n margin-top: 0;\n line-height: 24px;\n font-size: var(--font-size-0);\n}\n[data-supertokens~="formLabelLinkBtn"]:hover {\n text-decoration: underline;\n}\n[data-supertokens~="formLabelLinkBtn"]:disabled {\n color: rgb(var(--palette-textPrimary));\n cursor: default;\n text-decoration: none;\n}\n[data-supertokens~="authComponentList"] {\n padding-bottom: 20px;\n}\n[data-supertokens~="authPageTitleOAuthClient"] {\n color: rgb(var(--palette-textGray));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 10px 0 25px;\n}\n[data-supertokens~="authPageTitleOAuthClientUrl"] {\n text-decoration: none;\n}\n[data-supertokens~="authPageTitleOAuthClientLogo"] {\n width: 44px;\n height: 44px;\n margin-bottom: 10px;\n}\n[data-supertokens~="authPageTitleOAuthClient"] [data-supertokens~="authPageTitleOAuthClientName"] {\n color: rgb(var(--palette-textTitle));\n}\n[data-supertokens~="buttonWithArrow"] {\n border-radius: 6px;\n border: 1px solid #d0d5dd;\n width: 100%;\n color: rgb(var(--palette-textGray));\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n margin: 24px 0;\n min-height: 48px;\n cursor: pointer;\n}\n[data-supertokens~="buttonWithArrow"]:hover {\n background-color: rgb(var(--palette-inputBackground));\n}\n[data-supertokens~="buttonWithArrow"] [data-supertokens~="secondaryText"] {\n font-weight: 700;\n font-size: var(--font-size-2);\n color: rgb(var(--palette-textGray));\n margin: 0;\n}\n[data-supertokens~="buttonWithArrow"]:hover [data-supertokens~="secondaryLinkWithRightArrow"] ~ svg {\n position: relative;\n left: 2px;\n}\n[data-supertokens~="buttonWithArrow"]:hover [data-supertokens~="secondaryLinkWithLeftArrow"] svg {\n position: relative;\n left: -2px;\n}\n[data-supertokens~="buttonWithArrow"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n display: flex;\n align-items: center;\n}\n[data-supertokens~="mfa"][data-supertokens~="container"] {\n padding-top: 34px;\n}\n[data-supertokens~="mfa"] [data-supertokens~="row"] {\n padding-top: 6px;\n padding-bottom: 6px;\n}\n[data-supertokens~="mfa"] [data-supertokens~="headerTitle"] {\n font-size: var(--font-size-3);\n font-weight: 600;\n line-height: 30px;\n}\n[data-supertokens~="mfa"] [data-supertokens~="factorChooserList"] {\n margin-bottom: 12px;\n}\n[data-supertokens~="factorChooserOption"] {\n display: flex;\n flex-direction: row;\n border-radius: 6px;\n border: 1px solid rgb(var(--palette-inputBorder));\n padding: 20px 16px;\n cursor: pointer;\n margin-top: 12px;\n}\n[data-supertokens~="factorChooserOption"]:hover {\n border: 1px solid rgba(var(--palette-primary), 0.6);\n}\n[data-supertokens~="factorOptionText"] {\n flex-grow: 1;\n display: flex;\n flex-direction: column;\n align-items: start;\n text-align: left;\n}\n[data-supertokens~="factorLogo"] {\n flex-grow: 0;\n min-width: 30px;\n text-align: left;\n margin-top: 6px;\n}\n[data-supertokens~="totp"] [data-supertokens~="factorLogo"] {\n margin-top: 3px;\n margin-left: -1px;\n}\n[data-supertokens~="factorName"] {\n color: rgb(var(--palette-primary));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 4px;\n}\n[data-supertokens~="factorDescription"] {\n color: rgb(var(--palette-textPrimary));\n font-size: var(--font-size-0);\n margin: 4px;\n}\n[data-supertokens~="mfa"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n margin-bottom: 26px;\n text-align: right;\n}\n'; +var styles = "[data-supertokens~=\"container\"] {\n --palette-background: 255, 255, 255;\n --palette-inputBackground: 250, 250, 250;\n --palette-inputBorder: 224, 224, 224;\n --palette-primary: 28, 34, 42;\n --palette-primaryBorder: 45, 54, 68;\n --palette-success: 65, 167, 0;\n --palette-successBackground: 217, 255, 191;\n --palette-error: 255, 23, 23;\n --palette-errorBackground: 255, 241, 235;\n --palette-textTitle: 0, 0, 0;\n --palette-textLabel: 0, 0, 0;\n --palette-textInput: 0, 0, 0;\n --palette-textPrimary: 128, 128, 128;\n --palette-textLink: 0, 122, 255;\n --palette-buttonText: 255, 255, 255;\n --palette-textGray: 54, 54, 54;\n --palette-superTokensBrandingBackground: 242, 245, 246;\n --palette-superTokensBrandingText: 173, 189, 196;\n --palette-buttonGreyedOut: 221, 221, 221;\n --palette-caution: 124, 96, 62;\n --palette-errorDark: 207, 54, 68;\n\n --font-size-0: 12px;\n --font-size-1: 14px;\n --font-size-2: 16px;\n --font-size-3: 19px;\n --font-size-4: 24px;\n --font-size-5: 28px;\n}\n/*\n * Default styles.\n */\n@keyframes slideTop {\n 0% {\n transform: translateY(-5px);\n }\n 100% {\n transform: translateY(0px);\n }\n}\n@keyframes swing-in-top-fwd {\n 0% {\n transform: rotateX(-100deg);\n transform-origin: top;\n opacity: 0;\n }\n 100% {\n transform: rotateX(0deg);\n transform-origin: top;\n opacity: 1;\n }\n}\n[data-supertokens~=\"container\"] {\n font-family: \"Arial\", sans-serif;\n margin: 12px auto;\n margin-top: 26px;\n margin-bottom: 26px;\n width: 420px;\n text-align: center;\n border-radius: 8px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.16);\n background-color: rgb(var(--palette-background));\n}\n@media (max-width: 440px) {\n [data-supertokens~=\"container\"] {\n width: 95vw;\n }\n}\n[data-supertokens~=\"row\"] {\n margin: 0 auto;\n width: 76%;\n padding-top: 30px;\n padding-bottom: 10px;\n}\n[data-supertokens~=\"superTokensBranding\"] {\n display: block;\n margin: 10px auto 0;\n background: rgb(var(--palette-superTokensBrandingBackground));\n color: rgb(var(--palette-superTokensBrandingText));\n text-decoration: none;\n width: -webkit-fit-content;\n width: -moz-fit-content;\n width: fit-content;\n border-radius: 6px 6px 0 0;\n padding: 4px 9px;\n font-weight: 400;\n font-size: var(--font-size-0);\n letter-spacing: 0.4px;\n}\n[data-supertokens~=\"generalError\"] {\n background: rgb(var(--palette-errorBackground));\n padding-top: 10px;\n padding-bottom: 10px;\n margin-bottom: 10px;\n margin-top: 24px;\n padding-left: 18px;\n padding-right: 18px;\n letter-spacing: 0.2px;\n font-size: var(--font-size-1);\n border-radius: 8px;\n color: rgb(var(--palette-error));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n word-wrap: break-word;\n}\n[data-supertokens~=\"headerTitle\"] {\n font-size: var(--font-size-4);\n line-height: 27.6px;\n letter-spacing: 0.58px;\n font-weight: 700;\n margin-bottom: 20px;\n color: rgb(var(--palette-textTitle));\n}\n[data-supertokens~=\"headerSubtitle\"] {\n font-weight: 400;\n color: rgb(var(--palette-textGray));\n margin-bottom: 21px;\n}\n[data-supertokens~=\"headerSubtitle\"][data-supertokens~=\"secondaryText\"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n}\n[data-supertokens~=\"privacyPolicyAndTermsAndConditions\"] {\n max-width: 300px;\n margin-top: 10px;\n}\n[data-supertokens~=\"privacyPolicyAndTermsAndConditions\"] a {\n line-height: 21px;\n}\n/* TODO: split the link style into separate things*/\n/* We add this before primary and secondary text, because if they are applied to the same element the other ones take priority */\n[data-supertokens~=\"link\"] {\n padding-left: 3px;\n padding-right: 3px;\n color: rgb(var(--palette-textLink));\n font-size: var(--font-size-1);\n cursor: pointer;\n letter-spacing: 0.16px;\n line-height: 26px;\n}\n[data-supertokens~=\"primaryText\"] {\n font-size: var(--font-size-2);\n font-weight: 400;\n letter-spacing: 0.4px;\n line-height: 21px;\n color: rgb(var(--palette-textLabel));\n}\n[data-supertokens~=\"secondaryText\"] {\n font-size: var(--font-size-1);\n font-weight: 400;\n letter-spacing: 0.4px;\n color: rgb(var(--palette-textPrimary));\n}\n[data-supertokens~=\"secondaryText\"] strong {\n font-weight: 600;\n}\n[data-supertokens~=\"divider\"] {\n margin-top: 1.5em;\n margin-bottom: 1.5em;\n border-bottom: 0.3px solid #dddddd;\n align-items: center;\n padding-bottom: 5px;\n flex: 3 3;\n}\n[data-supertokens~=\"headerTinyTitle\"] {\n margin-top: 24px;\n font-size: var(--font-size-5);\n letter-spacing: 1.1px;\n font-weight: 700;\n line-height: 28px;\n}\n[data-supertokens~=\"secondaryLinkWithArrow\"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n}\n[data-supertokens~=\"secondaryLinkWithArrow\"]:hover {\n position: relative;\n left: 2px;\n word-spacing: 4px;\n}\n[data-supertokens~=\"generalSuccess\"] {\n color: rgb(var(--palette-success));\n font-size: var(--font-size-1);\n background: rgb(var(--palette-successBackground));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n padding: 9px 15px 9px 15px;\n border-radius: 6px;\n display: inline-block;\n}\n[data-supertokens~=\"spinner\"] {\n width: 80px;\n height: auto;\n padding-top: 20px;\n padding-bottom: 40px;\n margin: 0 auto;\n}\n[data-supertokens~=\"error\"] {\n color: rgb(var(--palette-error));\n}\n[data-supertokens~=\"linkButton\"] {\n font-family: \"Arial\", sans-serif;\n background-color: transparent;\n border: 0;\n}\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n margin-top: 10px;\n margin-bottom: 40px;\n cursor: pointer;\n}\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"] svg {\n margin-right: 0.3em;\n}\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"]:hover svg {\n position: relative;\n left: -4px;\n}\n[data-supertokens~=\"button\"] {\n font-family: \"Arial\", sans-serif;\n background-color: rgb(var(--palette-primary));\n color: rgb(var(--palette-buttonText));\n width: 100%;\n height: 34px;\n font-weight: 600;\n border-width: 1px;\n border-style: solid;\n border-radius: 6px;\n border-color: rgb(var(--palette-primaryBorder));\n background-position: center;\n transition: all 0.4s;\n background-size: 12000%;\n cursor: pointer;\n}\n[data-supertokens~=\"buttonGreyedOut\"] {\n background-color: rgb(var(--palette-buttonGreyedOut));\n border-color: rgb(var(--palette-buttonGreyedOut));\n}\n[data-supertokens~=\"buttonWithIcon\"] {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n}\n[data-supertokens~=\"button\"]:disabled {\n border: none;\n cursor: no-drop;\n}\n[data-supertokens~=\"button\"]:active {\n outline: none;\n transition: all 0s;\n background-size: 100%;\n filter: brightness(0.85);\n}\n[data-supertokens~=\"button\"]:focus {\n outline: none;\n}\n[data-supertokens~=\"backButtonCommon\"] {\n width: 16px;\n height: 13px;\n}\n[data-supertokens~=\"backButton\"] {\n cursor: pointer;\n border: none;\n background-color: transparent;\n padding: 0px;\n}\n[data-supertokens~=\"backButtonPlaceholder\"] {\n display: block;\n}\n[data-supertokens~=\"delayedRender\"] {\n animation-duration: 0.1s;\n animation-name: animate-fade;\n animation-delay: 0.2s;\n animation-fill-mode: backwards;\n}\n@keyframes animate-fade {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n[data-supertokens~=\"footerLinkGroupVert\"] {\n display: flex;\n flex-direction: column;\n margin-top: 10px;\n gap: 24px;\n}\n[data-supertokens~=\"footerLinkGroupVert\"] > div {\n cursor: pointer;\n margin: 0;\n}\n[data-supertokens~=\"footerLinkGroupVert\"] [data-supertokens~=\"secondaryText\"] {\n font-weight: 400;\n}\n[data-supertokens~=\"footerLinkGroupVert\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n font-weight: 400;\n position: relative;\n left: -6px; /* half the width of the left arrow */\n}\n@media (max-width: 360px) {\n [data-supertokens~=\"footerLinkGroupVert\"] {\n flex-direction: column;\n }\n [data-supertokens~=\"footerLinkGroupVert\"] > div {\n margin: 0 auto;\n }\n}\n[data-supertokens~=\"footerLinkGroupVert\"] div:only-child {\n margin-left: auto;\n margin-right: auto;\n margin-top: 14px;\n}\n[data-supertokens~=\"withBackButton\"] {\n position: relative;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n[data-supertokens~=\"dividerWithOr\"] {\n padding-top: 5px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n color: rgb(var(--palette-textPrimary));\n}\n[data-supertokens~=\"dividerText\"] {\n flex: 1 1;\n font-weight: 400;\n font-size: var(--font-size-1);\n}\n[data-supertokens~=\"formLabelWithLinkWrapper\"] {\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n[data-supertokens~=\"formLabelLinkBtn\"] {\n width: auto;\n margin-top: 0;\n line-height: 24px;\n font-size: var(--font-size-0);\n}\n[data-supertokens~=\"formLabelLinkBtn\"]:hover {\n text-decoration: underline;\n}\n[data-supertokens~=\"formLabelLinkBtn\"]:disabled {\n color: rgb(var(--palette-textPrimary));\n cursor: default;\n text-decoration: none;\n}\n[data-supertokens~=\"authComponentList\"] {\n padding-bottom: 20px;\n}\n[data-supertokens~=\"authPageTitleOAuthClient\"] {\n color: rgb(var(--palette-textGray));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 10px 0 25px;\n}\n[data-supertokens~=\"authPageTitleOAuthClientUrl\"] {\n text-decoration: none;\n}\n[data-supertokens~=\"authPageTitleOAuthClientLogo\"] {\n width: 44px;\n height: 44px;\n margin-bottom: 10px;\n}\n[data-supertokens~=\"authPageTitleOAuthClient\"] [data-supertokens~=\"authPageTitleOAuthClientName\"] {\n color: rgb(var(--palette-textTitle));\n}\n[data-supertokens~=\"buttonWithArrow\"] {\n border-radius: 6px;\n border: 1px solid #d0d5dd;\n width: 100%;\n color: rgb(var(--palette-textGray));\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n margin: 24px 0;\n min-height: 48px;\n cursor: pointer;\n}\n[data-supertokens~=\"buttonWithArrow\"]:hover {\n background-color: rgb(var(--palette-inputBackground));\n}\n[data-supertokens~=\"buttonWithArrow\"] [data-supertokens~=\"secondaryText\"] {\n font-weight: 700;\n font-size: var(--font-size-2);\n color: rgb(var(--palette-textGray));\n margin: 0;\n}\n[data-supertokens~=\"buttonWithArrow\"]:hover [data-supertokens~=\"secondaryLinkWithRightArrow\"] ~ svg {\n position: relative;\n left: 2px;\n}\n[data-supertokens~=\"buttonWithArrow\"]:hover [data-supertokens~=\"secondaryLinkWithLeftArrow\"] svg {\n position: relative;\n left: -2px;\n}\n[data-supertokens~=\"buttonWithArrow\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n display: flex;\n align-items: center;\n}\n[data-supertokens~=\"mfa\"][data-supertokens~=\"container\"] {\n padding-top: 34px;\n}\n[data-supertokens~=\"mfa\"] [data-supertokens~=\"row\"] {\n padding-top: 6px;\n padding-bottom: 6px;\n}\n[data-supertokens~=\"mfa\"] [data-supertokens~=\"headerTitle\"] {\n font-size: var(--font-size-3);\n font-weight: 600;\n line-height: 30px;\n}\n[data-supertokens~=\"mfa\"] [data-supertokens~=\"factorChooserList\"] {\n margin-bottom: 12px;\n}\n[data-supertokens~=\"factorChooserOption\"] {\n display: flex;\n flex-direction: row;\n border-radius: 6px;\n border: 1px solid rgb(var(--palette-inputBorder));\n padding: 20px 16px;\n cursor: pointer;\n margin-top: 12px;\n}\n[data-supertokens~=\"factorChooserOption\"]:hover {\n border: 1px solid rgba(var(--palette-primary), 0.6);\n}\n[data-supertokens~=\"factorOptionText\"] {\n flex-grow: 1;\n display: flex;\n flex-direction: column;\n align-items: start;\n text-align: left;\n}\n[data-supertokens~=\"factorLogo\"] {\n flex-grow: 0;\n min-width: 30px;\n text-align: left;\n margin-top: 6px;\n}\n[data-supertokens~=\"totp\"] [data-supertokens~=\"factorLogo\"] {\n margin-top: 3px;\n margin-left: -1px;\n}\n[data-supertokens~=\"factorName\"] {\n color: rgb(var(--palette-primary));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 4px;\n}\n[data-supertokens~=\"factorDescription\"] {\n color: rgb(var(--palette-textPrimary));\n font-size: var(--font-size-0);\n margin: 4px;\n}\n[data-supertokens~=\"mfa\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n margin-bottom: 26px;\n text-align: right;\n}\n"; -var ThemeBase = function (_a) { - var children = _a.children, - userStyles = _a.userStyles; - return jsxRuntime.jsxs(React.Fragment, { - children: [children, jsxRuntime.jsxs("style", { children: [styles, userStyles.join("\n")] })], - }); +var ThemeBase = function (_a) { + var children = _a.children, userStyles = _a.userStyles; + return (jsxRuntime.jsxs(React.Fragment, { children: [children, jsxRuntime.jsxs("style", { children: [styles, userStyles.join("\n")] })] })); }; -var FactorChooserFooter = uiEntry.withOverride("MFAFactorChooserFooter", function MFAChooserFooter(_a) { - var logout = _a.logout; - var t = translationContext.useTranslation(); - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row factorChooserFooter" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "secondaryText secondaryLinkWithLeftArrow", onClick: logout }, - { - children: [ - jsxRuntime.jsx(arrowLeftIcon.ArrowLeftIcon, { - color: "rgb(var(--palette-textPrimary))", - }), - t("MULTI_FACTOR_AUTH_LOGOUT"), - ], - } - ) - ), - } - ) - ); +var FactorChooserFooter = uiEntry.withOverride("MFAFactorChooserFooter", function MFAChooserFooter(_a) { + var logout = _a.logout; + var t = translationContext.useTranslation(); + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "row factorChooserFooter" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "secondaryText secondaryLinkWithLeftArrow", onClick: logout }, { children: [jsxRuntime.jsx(arrowLeftIcon.ArrowLeftIcon, { color: "rgb(var(--palette-textPrimary))" }), t("MULTI_FACTOR_AUTH_LOGOUT")] })) }))); }); -var FactorChooserHeader = uiEntry.withOverride("MFAFactorChooserHeader", function MFAFactorChooserHeader(props) { - var t = translationContext.useTranslation(); - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row factorChooserHeader" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle withBackButton" }, - { - children: [ - props.showBackButton - ? jsxRuntime.jsx(uiEntry.BackButton, { onClick: props.onBackButtonClicked }) - : jsxRuntime.jsx("span", { - "data-supertokens": "backButtonPlaceholder backButtonCommon", - }), - t("MULTI_FACTOR_CHOOSER_HEADER_TITLE"), - jsxRuntime.jsx("span", { - "data-supertokens": "backButtonPlaceholder backButtonCommon", - }), - ], - } - ) - ), - } - ) - ); +var FactorChooserHeader = uiEntry.withOverride("MFAFactorChooserHeader", function MFAFactorChooserHeader(props) { + var t = translationContext.useTranslation(); + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "row factorChooserHeader" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "headerTitle withBackButton" }, { children: [props.showBackButton ? (jsxRuntime.jsx(uiEntry.BackButton, { onClick: props.onBackButtonClicked })) : (jsxRuntime.jsx("span", { "data-supertokens": "backButtonPlaceholder backButtonCommon" })), t("MULTI_FACTOR_CHOOSER_HEADER_TITLE"), jsxRuntime.jsx("span", { "data-supertokens": "backButtonPlaceholder backButtonCommon" })] })) }))); }); -var FactorOption = uiEntry.withOverride("MFAFactorOption", function MFAFactorOption(_a) { - var onClick = _a.onClick, - id = _a.id, - name = _a.name, - description = _a.description, - logo = _a.logo; - var t = translationContext.useTranslation(); - return jsxRuntime.jsxs( - "a", - genericComponentOverrideContext.__assign( - { "data-supertokens": "factorChooserOption ".concat(id), onClick: onClick }, - { - children: [ - jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "factorLogo" }, - { children: [" ", logo({})] } - ) - ), - jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "factorOptionText" }, - { - children: [ - jsxRuntime.jsx( - "h6", - genericComponentOverrideContext.__assign( - { "data-supertokens": "factorName" }, - { children: t(name) } - ) - ), - jsxRuntime.jsx( - "p", - genericComponentOverrideContext.__assign( - { "data-supertokens": "factorDescription" }, - { children: t(description) } - ) - ), - ], - } - ) - ), - ], - } - ) - ); +var FactorOption = uiEntry.withOverride("MFAFactorOption", function MFAFactorOption(_a) { + var onClick = _a.onClick, id = _a.id, name = _a.name, description = _a.description, logo = _a.logo; + var t = translationContext.useTranslation(); + return (jsxRuntime.jsxs("a", utils.__assign({ "data-supertokens": "factorChooserOption ".concat(id), onClick: onClick }, { children: [jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "factorLogo" }, { children: [" ", logo({})] })), jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "factorOptionText" }, { children: [jsxRuntime.jsx("h6", utils.__assign({ "data-supertokens": "factorName" }, { children: t(name) })), jsxRuntime.jsx("p", utils.__assign({ "data-supertokens": "factorDescription" }, { children: t(description) }))] }))] }))); }); -var FactorList = uiEntry.withOverride("MFAFactorList", function MFAFactorList(_a) { - var availableFactors = _a.availableFactors, - navigateToFactor = _a.navigateToFactor; - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row factorChooserList" }, - { - children: availableFactors.map(function (factor) { - return jsxRuntime.jsx( - FactorOption, - { - id: factor.id, - name: factor.name, - description: factor.description, - logo: factor.logo, - onClick: function () { - return navigateToFactor(factor.id); - }, - }, - factor.id - ); - }), - } - ) - ); +var FactorList = uiEntry.withOverride("MFAFactorList", function MFAFactorList(_a) { + var availableFactors = _a.availableFactors, navigateToFactor = _a.navigateToFactor; + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "row factorChooserList" }, { children: availableFactors.map(function (factor) { return (jsxRuntime.jsx(FactorOption, { id: factor.id, name: factor.name, description: factor.description, logo: factor.logo, onClick: function () { return navigateToFactor(factor.id); } }, factor.id)); }) }))); }); -function FactorChooserTheme(props) { - var t = translationContext.useTranslation(); - if (props.availableFactors.length === 0) { - return jsxRuntime.jsx(sessionprebuiltui.AccessDeniedScreen, { - useShadowDom: false /* We set this to false, because we are already inside a shadowDom (if required) */, - error: props.showBackButton ? t("MFA_NO_AVAILABLE_OPTIONS") : t("MFA_NO_AVAILABLE_OPTIONS_LOGIN"), - }); - } - return jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container mfa" }, - { - children: [ - jsxRuntime.jsx(FactorChooserHeader, { - onBackButtonClicked: props.onBackButtonClicked, - showBackButton: props.showBackButton, - }), - jsxRuntime.jsx(FactorList, { - availableFactors: props.availableFactors, - navigateToFactor: props.navigateToFactor, - }), - jsxRuntime.jsx(FactorChooserFooter, { logout: props.onLogoutClicked }), - jsxRuntime.jsx(uiEntry.SuperTokensBranding, {}), - ], - } - ) - ); -} -function FactorChooserThemeWrapper(props) { - var rootStyle = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().rootStyle; - return jsxRuntime.jsx( - uiEntry.UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - ThemeBase, - genericComponentOverrideContext.__assign( - { - userStyles: [ - rootStyle, - props.config.recipeRootStyle, - props.config.factorChooserScreen.style, - ], - }, - { - children: jsxRuntime.jsx( - FactorChooserTheme, - genericComponentOverrideContext.__assign({}, props) - ), - } - ) - ), - } - ) - ); +function FactorChooserTheme(props) { + var t = translationContext.useTranslation(); + if (props.availableFactors.length === 0) { + return (jsxRuntime.jsx(sessionprebuiltui.AccessDeniedScreen, { useShadowDom: false /* We set this to false, because we are already inside a shadowDom (if required) */, error: props.showBackButton ? t("MFA_NO_AVAILABLE_OPTIONS") : t("MFA_NO_AVAILABLE_OPTIONS_LOGIN") })); + } + return (jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "container mfa" }, { children: [jsxRuntime.jsx(FactorChooserHeader, { onBackButtonClicked: props.onBackButtonClicked, showBackButton: props.showBackButton }), jsxRuntime.jsx(FactorList, { availableFactors: props.availableFactors, navigateToFactor: props.navigateToFactor }), jsxRuntime.jsx(FactorChooserFooter, { logout: props.onLogoutClicked }), jsxRuntime.jsx(uiEntry.SuperTokensBranding, {})] }))); +} +function FactorChooserThemeWrapper(props) { + var rootStyle = superTokens.SuperTokens.getInstanceOrThrow().rootStyle; + return (jsxRuntime.jsx(uiEntry.UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(ThemeBase, utils.__assign({ userStyles: [rootStyle, props.config.recipeRootStyle, props.config.factorChooserScreen.style] }, { children: jsxRuntime.jsx(FactorChooserTheme, utils.__assign({}, props)) })) }))); } -var defaultTranslationsMultiFactorAuth = { - en: genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, uiEntry.defaultTranslationsCommon.en), - { - MULTI_FACTOR_CHOOSER_HEADER_TITLE: "Please select a factor", - MULTI_FACTOR_AUTH_LOGOUT: "Log out", - PWLESS_MFA_OTP_PHONE_NAME: "SMS based OTP", - PWLESS_MFA_OTP_PHONE_DESCRIPTION: "Get an OTP code on your phone to complete the authentication request", - PWLESS_MFA_OTP_EMAIL_NAME: "Email based OTP", - PWLESS_MFA_OTP_EMAIL_DESCRIPTION: - "Get an OTP code on your email address to complete the authentication request", - TOTP_MFA_NAME: "TOTP", - TOTP_MFA_DESCRIPTION: "Use an authenticator app to complete the authentication request", - MFA_NO_AVAILABLE_OPTIONS: "You have no available secondary factors.", - MFA_NO_AVAILABLE_OPTIONS_LOGIN: - "You have no available secondary factors and cannot complete the sign-in process. Please contact support.", - } - ), +var defaultTranslationsMultiFactorAuth = { + en: utils.__assign(utils.__assign({}, uiEntry.defaultTranslationsCommon.en), { MULTI_FACTOR_CHOOSER_HEADER_TITLE: "Please select a factor", MULTI_FACTOR_AUTH_LOGOUT: "Log out", PWLESS_MFA_OTP_PHONE_NAME: "SMS based OTP", PWLESS_MFA_OTP_PHONE_DESCRIPTION: "Get an OTP code on your phone to complete the authentication request", PWLESS_MFA_OTP_EMAIL_NAME: "Email based OTP", PWLESS_MFA_OTP_EMAIL_DESCRIPTION: "Get an OTP code on your email address to complete the authentication request", TOTP_MFA_NAME: "TOTP", TOTP_MFA_DESCRIPTION: "Use an authenticator app to complete the authentication request", MFA_NO_AVAILABLE_OPTIONS: "You have no available secondary factors.", MFA_NO_AVAILABLE_OPTIONS_LOGIN: "You have no available secondary factors and cannot complete the sign-in process. Please contact support." }), }; -var FactorChooser$1 = function (props) { - var _a; - var sessionContext = React.useContext(uiEntry.SessionContext); - var rethrowInRender = genericComponentOverrideContext.useRethrowInRender(); - var _b = React.useState(undefined), - mfaInfo = _b[0], - setMFAInfo = _b[1]; - var userContext = uiEntry.useUserContext(); - if (props.userContext !== undefined) { - userContext = props.userContext; - } - var recipeComponentOverrides = props.useComponentOverrides(); - var nextQueryParam = - (_a = genericComponentOverrideContext.getQueryParams("n")) !== null && _a !== void 0 ? _a : undefined; - var stepUpQueryParam = genericComponentOverrideContext.getQueryParams("stepUp"); - var redirectToAuthWithHistory = React.useCallback( - function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - uiEntry.redirectToAuth({ redirectBack: false, navigate: props.navigate }), - ]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); - }, - [props.navigate] - ); - var fetchMFAInfo = React.useCallback( - function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - props.recipe.webJSRecipe.resyncSessionAndFetchMFAInfo({ userContext: userContext }), - ]; - }); - }); - }, - [props.recipe, userContext] - ); - var checkMFAInfo = React.useCallback( - function (mfaInfo) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - if (mfaInfo.factors.next.length === 0 && stepUpQueryParam !== "true") { - void types.Session.getInstanceOrThrow() - .validateGlobalClaimsAndHandleSuccessRedirection( - undefined, - recipe.MultiFactorAuth.RECIPE_ID, - genericComponentOverrideContext.getRedirectToPathFromURL(), - userContext, - props.navigate - ) - .catch(rethrowInRender); - } else { - setMFAInfo({ - factors: mfaInfo.factors, - phoneNumbers: mfaInfo.phoneNumbers, - emails: mfaInfo.emails, - }); - } - return [2 /*return*/]; - }); - }); - }, - [setMFAInfo, nextQueryParam, userContext] - ); - var handleError = React.useCallback( - function (err) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().doesSessionExist({ userContext: userContext }), - ]; - case 1: - if (!_a.sent()) return [3 /*break*/, 2]; - throw err; - case 2: - return [4 /*yield*/, redirectToAuthWithHistory()]; - case 3: - _a.sent(); - _a.label = 4; - case 4: - return [2 /*return*/]; - } - }); - }); - }, - [redirectToAuthWithHistory] - ); - genericComponentOverrideContext.useOnMountAPICall( - fetchMFAInfo, - checkMFAInfo, - handleError, - sessionContext.loading === false - ); - var navigateToFactor = React.useCallback( - function (factorId) { - props.recipe.config.onHandleEvent({ - action: "FACTOR_CHOOSEN", - factorId: factorId, - }); - return props.recipe.redirectToFactor({ - factorId: factorId, - forceSetup: false, - stepUp: stepUpQueryParam === "true", - redirectBack: false, - navigate: props.navigate, - userContext: props.userContext, - }); - }, - [props.recipe] - ); - var signOut = React.useCallback( - function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var session; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - session = types.Session.getInstanceOrThrow(); - return [4 /*yield*/, session.signOut({ userContext: userContext })]; - case 1: - _a.sent(); - return [2 /*return*/, redirectToAuthWithHistory()]; - } - }); - }); - }, - [props.recipe, redirectToAuthWithHistory] - ); - var onBackButtonClicked = React.useCallback( - function () { - // If we don't have navigate available this would mean we are not using react-router-dom, so we use window's history - if (props.navigate === undefined) { - return windowHandler.WindowHandlerReference.getReferenceOrThrow() - .windowHandler.getWindowUnsafe() - .history.back(); - } - // If we do have navigate and goBack function on it this means we are using react-router-dom v5 or lower - if ("goBack" in props.navigate) { - return props.navigate.goBack(); - } - // If we reach this code this means we are using react-router-dom v6 - return props.navigate(-1); - }, - [props.navigate] - ); - if (mfaInfo === undefined) { - return null; - } - var availableFactors = recipe.getAvailableFactors(mfaInfo.factors, nextQueryParam, props.recipe, userContext); - var childProps = { - config: props.recipe.config, - onBackButtonClicked: onBackButtonClicked, - // if the next array is empty, it means the user has logged in fully and has come here (from a settings page for example). - // So we show the back button. In case the next array is not empty, it means we are still signing in, and - // there is no where to go back to, other than logout, which is a different button in the UI. - showBackButton: mfaInfo.factors.next.length === 0, - mfaInfo: mfaInfo, - availableFactors: availableFactors, - onLogoutClicked: signOut, - navigateToFactor: navigateToFactor, - }; - return jsxRuntime.jsx( - uiEntry.ComponentOverrideContext.Provider, - genericComponentOverrideContext.__assign( - { value: recipeComponentOverrides }, - { - children: jsxRuntime.jsx( - uiEntry.FeatureWrapper, - genericComponentOverrideContext.__assign( - { - useShadowDom: genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().useShadowDom, - defaultStore: defaultTranslationsMultiFactorAuth, - }, - { - children: jsxRuntime.jsxs(React.Fragment, { - children: [ - props.children === undefined && - jsxRuntime.jsx( - FactorChooserThemeWrapper, - genericComponentOverrideContext.__assign({}, childProps) - ), - props.children && - React__namespace.Children.map(props.children, function (child) { - if (React__namespace.isValidElement(child)) { - return React__namespace.cloneElement(child, childProps); - } - return child; - }), - ], - }), - } - ) - ), - } - ) - ); +var FactorChooser$1 = function (props) { + var _a; + var sessionContext = React.useContext(uiEntry.SessionContext); + var rethrowInRender = utils.useRethrowInRender(); + var _b = React.useState(undefined), mfaInfo = _b[0], setMFAInfo = _b[1]; + var userContext = uiEntry.useUserContext(); + if (props.userContext !== undefined) { + userContext = props.userContext; + } + var recipeComponentOverrides = props.useComponentOverrides(); + var nextQueryParam = (_a = utils.getQueryParams("n")) !== null && _a !== void 0 ? _a : undefined; + var stepUpQueryParam = utils.getQueryParams("stepUp"); + var redirectToAuthWithHistory = React.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, uiEntry.redirectToAuth({ redirectBack: false, navigate: props.navigate })]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); + }); }, [props.navigate]); + var fetchMFAInfo = React.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { return utils.__generator(this, function (_a) { + return [2 /*return*/, props.recipe.webJSRecipe.resyncSessionAndFetchMFAInfo({ userContext: userContext })]; + }); }); }, [props.recipe, userContext]); + var checkMFAInfo = React.useCallback(function (mfaInfo) { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + if (mfaInfo.factors.next.length === 0 && stepUpQueryParam !== "true") { + void types.Session.getInstanceOrThrow() + .validateGlobalClaimsAndHandleSuccessRedirection(undefined, recipe.MultiFactorAuth.RECIPE_ID, utils.getRedirectToPathFromURL(), userContext, props.navigate) + .catch(rethrowInRender); + } + else { + setMFAInfo({ + factors: mfaInfo.factors, + phoneNumbers: mfaInfo.phoneNumbers, + emails: mfaInfo.emails, + }); + } + return [2 /*return*/]; + }); + }); }, [setMFAInfo, nextQueryParam, userContext]); + var handleError = React.useCallback(function (err) { return utils.__awaiter(void 0, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, types.Session.getInstanceOrThrow().doesSessionExist({ userContext: userContext })]; + case 1: + if (!_a.sent()) return [3 /*break*/, 2]; + throw err; + case 2: return [4 /*yield*/, redirectToAuthWithHistory()]; + case 3: + _a.sent(); + _a.label = 4; + case 4: return [2 /*return*/]; + } + }); + }); }, [redirectToAuthWithHistory]); + utils.useOnMountAPICall(fetchMFAInfo, checkMFAInfo, handleError, sessionContext.loading === false); + var navigateToFactor = React.useCallback(function (factorId) { + props.recipe.config.onHandleEvent({ + action: "FACTOR_CHOOSEN", + factorId: factorId, + }); + return props.recipe.redirectToFactor({ + factorId: factorId, + forceSetup: false, + stepUp: stepUpQueryParam === "true", + redirectBack: false, + navigate: props.navigate, + userContext: props.userContext, + }); + }, [props.recipe]); + var signOut = React.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + var session; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + session = types.Session.getInstanceOrThrow(); + return [4 /*yield*/, session.signOut({ userContext: userContext })]; + case 1: + _a.sent(); + return [2 /*return*/, redirectToAuthWithHistory()]; + } + }); + }); }, [props.recipe, redirectToAuthWithHistory]); + var onBackButtonClicked = React.useCallback(function () { + // If we don't have navigate available this would mean we are not using react-router-dom, so we use window's history + if (props.navigate === undefined) { + return windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.getWindowUnsafe().history.back(); + } + // If we do have navigate and goBack function on it this means we are using react-router-dom v5 or lower + if ("goBack" in props.navigate) { + return props.navigate.goBack(); + } + // If we reach this code this means we are using react-router-dom v6 + return props.navigate(-1); + }, [props.navigate]); + if (mfaInfo === undefined) { + return null; + } + var availableFactors = recipe.getAvailableFactors(mfaInfo.factors, nextQueryParam, props.recipe, userContext); + var childProps = { + config: props.recipe.config, + onBackButtonClicked: onBackButtonClicked, + // if the next array is empty, it means the user has logged in fully and has come here (from a settings page for example). + // So we show the back button. In case the next array is not empty, it means we are still signing in, and + // there is no where to go back to, other than logout, which is a different button in the UI. + showBackButton: mfaInfo.factors.next.length === 0, + mfaInfo: mfaInfo, + availableFactors: availableFactors, + onLogoutClicked: signOut, + navigateToFactor: navigateToFactor, + }; + return (jsxRuntime.jsx(uiEntry.ComponentOverrideContext.Provider, utils.__assign({ value: recipeComponentOverrides }, { children: jsxRuntime.jsx(uiEntry.FeatureWrapper, utils.__assign({ useShadowDom: superTokens.SuperTokens.getInstanceOrThrow().useShadowDom, defaultStore: defaultTranslationsMultiFactorAuth }, { children: jsxRuntime.jsxs(React.Fragment, { children: [props.children === undefined && jsxRuntime.jsx(FactorChooserThemeWrapper, utils.__assign({}, childProps)), props.children && + React__namespace.Children.map(props.children, function (child) { + if (React__namespace.isValidElement(child)) { + return React__namespace.cloneElement(child, childProps); + } + return child; + })] }) })) }))); }; -var MultiFactorAuthPreBuiltUI = /** @class */ (function (_super) { - genericComponentOverrideContext.__extends(MultiFactorAuthPreBuiltUI, _super); - function MultiFactorAuthPreBuiltUI(recipeInstance) { - var _this = _super.call(this) || this; - _this.recipeInstance = recipeInstance; - _this.languageTranslations = defaultTranslationsMultiFactorAuth; - // Instance methods - _this.getFeatures = function (useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = componentOverrideContext.useContext; - } - var features = {}; - if (_this.recipeInstance.config.disableDefaultUI !== true) { - var normalisedFullPath = _this.recipeInstance.config.appInfo.websiteBasePath.appendPath( - new NormalisedURLPath__default.default(recipe.DEFAULT_FACTOR_CHOOSER_PATH) - ); - features[normalisedFullPath.getAsStringDangerous()] = { - matches: genericComponentOverrideContext.matchRecipeIdUsingQueryParams( - _this.recipeInstance.config.recipeId - ), - component: function (props) { - return _this.getFeatureComponent("factorchooser", props, useComponentOverrides); - }, - recipeID: recipe.MultiFactorAuth.RECIPE_ID, - }; - } - return features; - }; - _this.getFeatureComponent = function ( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _, - props, - useComponentOverrides - ) { - if (useComponentOverrides === void 0) { - useComponentOverrides = componentOverrideContext.useContext; - } - return jsxRuntime.jsx( - uiEntry.UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - session.SessionAuth, - genericComponentOverrideContext.__assign( - { - overrideGlobalClaimValidators: function () { - return []; - }, - }, - { - children: jsxRuntime.jsx( - FactorChooser$1, - genericComponentOverrideContext.__assign( - { - recipe: _this.recipeInstance, - useComponentOverrides: useComponentOverrides, - }, - props - ) - ), - } - ) - ), - } - ) - ); - }; - return _this; - } - // Static methods - MultiFactorAuthPreBuiltUI.getInstanceOrInitAndGetInstance = function () { - if (MultiFactorAuthPreBuiltUI.instance === undefined) { - var recipeInstance = recipe.MultiFactorAuth.getInstanceOrThrow(); - MultiFactorAuthPreBuiltUI.instance = new MultiFactorAuthPreBuiltUI(recipeInstance); - } - return MultiFactorAuthPreBuiltUI.instance; - }; - MultiFactorAuthPreBuiltUI.getFeatures = function (useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = componentOverrideContext.useContext; - } - return MultiFactorAuthPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatures(useComponentOverrides); - }; - MultiFactorAuthPreBuiltUI.getFeatureComponent = function (componentName, props, useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = componentOverrideContext.useContext; - } - return MultiFactorAuthPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent( - componentName, - props, - useComponentOverrides - ); - }; - MultiFactorAuthPreBuiltUI.prototype.getAuthComponents = function () { - return []; - }; - // For tests - MultiFactorAuthPreBuiltUI.reset = function () { - if (!genericComponentOverrideContext.isTest()) { - return; - } - MultiFactorAuthPreBuiltUI.instance = undefined; - return; - }; - MultiFactorAuthPreBuiltUI.FactorChooser = function (props) { - return MultiFactorAuthPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent("factorchooser", props); - }; - MultiFactorAuthPreBuiltUI.FactorChooserTheme = FactorChooserThemeWrapper; - return MultiFactorAuthPreBuiltUI; -})(uiEntry.RecipeRouter); +var MultiFactorAuthPreBuiltUI = /** @class */ (function (_super) { + utils.__extends(MultiFactorAuthPreBuiltUI, _super); + function MultiFactorAuthPreBuiltUI(recipeInstance) { + var _this = _super.call(this) || this; + _this.recipeInstance = recipeInstance; + _this.languageTranslations = defaultTranslationsMultiFactorAuth; + // Instance methods + _this.getFeatures = function (useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = componentOverrideContext.useContext; } + var features = {}; + if (_this.recipeInstance.config.disableDefaultUI !== true) { + var normalisedFullPath = _this.recipeInstance.config.appInfo.websiteBasePath.appendPath(new NormalisedURLPath__default.default(recipe.DEFAULT_FACTOR_CHOOSER_PATH)); + features[normalisedFullPath.getAsStringDangerous()] = { + matches: utils.matchRecipeIdUsingQueryParams(_this.recipeInstance.config.recipeId), + component: function (props) { return _this.getFeatureComponent("factorchooser", props, useComponentOverrides); }, + recipeID: recipe.MultiFactorAuth.RECIPE_ID, + }; + } + return features; + }; + _this.getFeatureComponent = function ( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _, props, useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = componentOverrideContext.useContext; } + return (jsxRuntime.jsx(uiEntry.UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(session.SessionAuth, utils.__assign({ overrideGlobalClaimValidators: function () { return []; } }, { children: jsxRuntime.jsx(FactorChooser$1, utils.__assign({ recipe: _this.recipeInstance, useComponentOverrides: useComponentOverrides }, props)) })) }))); + }; + return _this; + } + // Static methods + MultiFactorAuthPreBuiltUI.getInstanceOrInitAndGetInstance = function () { + if (MultiFactorAuthPreBuiltUI.instance === undefined) { + var recipeInstance = recipe.MultiFactorAuth.getInstanceOrThrow(); + MultiFactorAuthPreBuiltUI.instance = new MultiFactorAuthPreBuiltUI(recipeInstance); + } + return MultiFactorAuthPreBuiltUI.instance; + }; + MultiFactorAuthPreBuiltUI.getFeatures = function (useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = componentOverrideContext.useContext; } + return MultiFactorAuthPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatures(useComponentOverrides); + }; + MultiFactorAuthPreBuiltUI.getFeatureComponent = function (componentName, props, useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = componentOverrideContext.useContext; } + return MultiFactorAuthPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent(componentName, props, useComponentOverrides); + }; + MultiFactorAuthPreBuiltUI.prototype.getAuthComponents = function () { + return []; + }; + // For tests + MultiFactorAuthPreBuiltUI.reset = function () { + if (!utils.isTest()) { + return; + } + MultiFactorAuthPreBuiltUI.instance = undefined; + return; + }; + MultiFactorAuthPreBuiltUI.FactorChooser = function (props) { + return MultiFactorAuthPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent("factorchooser", props); + }; + MultiFactorAuthPreBuiltUI.FactorChooserTheme = FactorChooserThemeWrapper; + return MultiFactorAuthPreBuiltUI; +}(uiEntry.RecipeRouter)); var FactorChooser = MultiFactorAuthPreBuiltUI.FactorChooser; exports.FactorChooser = FactorChooser; diff --git a/lib/build/multitenancy-shared.js b/lib/build/multitenancy-shared.js index bd3b554b5..7d16271fd 100644 --- a/lib/build/multitenancy-shared.js +++ b/lib/build/multitenancy-shared.js @@ -1,10 +1,8 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); +var genericComponentOverrideContext = require('./genericComponentOverrideContext.js'); -var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), - useContext = _a[0], - Provider = _a[1]; +var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), useContext = _a[0], Provider = _a[1]; exports.Provider = Provider; exports.useContext = useContext; diff --git a/lib/build/multitenancy.js b/lib/build/multitenancy.js index 222b442d8..c9f6d4e8f 100644 --- a/lib/build/multitenancy.js +++ b/lib/build/multitenancy.js @@ -1,52 +1,54 @@ -"use strict"; +'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, '__esModule', { value: true }); -var MultitenancyWebJS = require("supertokens-web-js/recipe/multitenancy"); -var componentOverrideContext = require("./multitenancy-shared.js"); -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -require("supertokens-web-js"); -require("supertokens-web-js/utils/cookieHandler"); -require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -require("supertokens-web-js/utils/windowHandler"); -require("supertokens-web-js/utils"); -require("react"); -require("supertokens-web-js/lib/build/error"); -require("supertokens-web-js/utils/normalisedURLDomain"); -require("supertokens-web-js/utils/normalisedURLPath"); -require("react/jsx-runtime"); +var MultitenancyWebJS = require('supertokens-web-js/recipe/multitenancy'); +var componentOverrideContext = require('./multitenancy-shared.js'); +var superTokens = require('./superTokens.js'); +require('./genericComponentOverrideContext.js'); +require('./utils.js'); +require('react'); +require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('supertokens-web-js/utils/normalisedURLPath'); +require('supertokens-web-js/utils/windowHandler'); +require('crypto'); +require('react/jsx-runtime'); +require('supertokens-web-js'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('supertokens-web-js/utils'); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var Wrapper = /** @class */ (function () { - function Wrapper() {} - Wrapper.init = function (config) { - return genericComponentOverrideContext.Multitenancy.init(config); - }; - Wrapper.AllowedDomainsClaim = MultitenancyWebJS.AllowedDomainsClaim; - Wrapper.ComponentsOverrideProvider = componentOverrideContext.Provider; - return Wrapper; -})(); -var init = Wrapper.init; +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var Wrapper = /** @class */ (function () { + function Wrapper() { + } + Wrapper.init = function (config) { + return superTokens.Multitenancy.init(config); + }; + Wrapper.AllowedDomainsClaim = MultitenancyWebJS.AllowedDomainsClaim; + Wrapper.ComponentsOverrideProvider = componentOverrideContext.Provider; + return Wrapper; +}()); +var init = Wrapper.init; var MultitenancyComponentsOverrideProvider = Wrapper.ComponentsOverrideProvider; -Object.defineProperty(exports, "AllowedDomainsClaim", { +Object.defineProperty(exports, 'AllowedDomainsClaim', { enumerable: true, - get: function () { - return MultitenancyWebJS.AllowedDomainsClaim; - }, + get: function () { return MultitenancyWebJS.AllowedDomainsClaim; } }); exports.MultitenancyComponentsOverrideProvider = MultitenancyComponentsOverrideProvider; exports.default = Wrapper; diff --git a/lib/build/nextjs/constants.d.ts b/lib/build/nextjs/constants.d.ts new file mode 100644 index 000000000..39e1df7af --- /dev/null +++ b/lib/build/nextjs/constants.d.ts @@ -0,0 +1,14 @@ +export declare const ACCESS_TOKEN_COOKIE_NAME = "sAccessToken"; +export declare const ACCESS_TOKEN_HEADER_NAME = "st-access-token"; +export declare const FRONT_TOKEN_COOKIE_NAME = "sFrontToken"; +export declare const FRONT_TOKEN_HEADER_NAME = "front-token"; +export declare const REFRESH_TOKEN_COOKIE_NAME = "sRefreshToken"; +export declare const REFRESH_TOKEN_HEADER_NAME = "st-refresh-token"; +export declare const ANTI_CSRF_TOKEN_COOKIE_NAME = "sAntiCsrf"; +export declare const ANTI_CSRF_TOKEN_HEADER_NAME = "anti-csrf"; +export declare const REDIRECT_ATTEMPT_MAX_COUNT = 5; +export declare const REDIRECT_ATTEMPT_COUNT_COOKIE_NAME = "stSsrSessionRefreshAttempt"; +export declare const CURRENT_PATH_COOKIE_NAME = "sCurrentPath"; +export declare const FORCE_LOGOUT_PATH_PARAM_NAME = "forceLogout"; +export declare const REDIRECT_PATH_PARAM_NAME = "stRedirectTo"; +export declare const DEFAULT_API_PATH = "/api/auth"; diff --git a/lib/build/nextjs/middleware.d.ts b/lib/build/nextjs/middleware.d.ts new file mode 100644 index 000000000..57025468f --- /dev/null +++ b/lib/build/nextjs/middleware.d.ts @@ -0,0 +1,9 @@ +import type { ApiRequestMiddleware, SuperTokensNextjsConfig } from "./types"; +declare type SuperTokensNextjsMiddlewareConfig = SuperTokensNextjsConfig & { + apiRequestMiddleware?: ApiRequestMiddleware; + isApiRequest?: (request: Request) => boolean; +}; +export declare function superTokensMiddleware(config: SuperTokensNextjsMiddlewareConfig): (request: Request) => Promise; +export declare function refreshSession(request: Request): Promise; +export declare function revokeSession(request: Request): Promise; +export {}; diff --git a/lib/build/nextjs/ssr.d.ts b/lib/build/nextjs/ssr.d.ts new file mode 100644 index 000000000..598414a60 --- /dev/null +++ b/lib/build/nextjs/ssr.d.ts @@ -0,0 +1,51 @@ +import type { CookiesObject, CookiesStore, GetServerSidePropsReturnValue, SuperTokensNextjsConfig } from "./types"; +import type { LoadedSessionContext } from "../recipe/session/types"; +export default class SuperTokensNextjsSSRAPIWrapper { + static config: SuperTokensNextjsConfig; + static init(config: SuperTokensNextjsConfig): void; + static getConfigOrThrow(): SuperTokensNextjsConfig; + static getJWKSUrl(): string; + /** + * Get the session state inside a server componet or redirect + * The function is meant to be used inside Next.js server components + * @param cookies - The cookies store exposed by next/headers (await cookies()) + * @returns The session context value or directly redirects the user to either the login page or the refresh API + **/ + static getServerComponentSession(cookies: CookiesStore): Promise; + /** + * Get the session state inside a server action + * The function is meant to be used inside Next.js server actions + * @param cookies - The cookies store exposed by next/headers (await cookies()) + * @returns An object that includes session context value and the status of the session ('valid' | 'expired' | 'invalid') + * If the status is 'invalid' or 'expired' then the users should be considered as unauthenticated + **/ + static getServerActionSession(cookies: CookiesStore): Promise<{ + session: LoadedSessionContext; + status: "valid"; + } | { + status: "expired" | "invalid"; + session: undefined; + }>; + /** + * Ensures that a server action is called by an authenticated user + * If the session does not exist/user is not authenticated, it will automatically redirect to the login page + * The function is meant to run on the client, before calling the actual server action + * @param action - A server action that will get called after the authentication state is confirmed + * @returns The server action return value + **/ + static confirmAuthenticationAndCallServerAction Promise, K>(action: T): Promise; + /** + * Get the session state or redirect + * The function is meant to be used inside getServerSideProps. + * @param request - The request object available inside getServerSideProps ctx (ctx.req) + * @returns The session context value or a redirects path to send the user to the refresh API or the login page + **/ + static getServerSidePropsSession(request: Request & { + cookies: CookiesObject; + }): Promise; +} +export declare const init: typeof SuperTokensNextjsSSRAPIWrapper.init; +export declare const getServerComponentSession: typeof SuperTokensNextjsSSRAPIWrapper.getServerComponentSession; +export declare const getServerActionSession: typeof SuperTokensNextjsSSRAPIWrapper.getServerActionSession; +export declare const getServerSidePropsSession: typeof SuperTokensNextjsSSRAPIWrapper.getServerSidePropsSession; +export declare const confirmAuthenticationAndCallServerAction: typeof SuperTokensNextjsSSRAPIWrapper.confirmAuthenticationAndCallServerAction; diff --git a/lib/build/nextjs/types.d.ts b/lib/build/nextjs/types.d.ts new file mode 100644 index 000000000..4351adedb --- /dev/null +++ b/lib/build/nextjs/types.d.ts @@ -0,0 +1,67 @@ +import type { LoadedSessionContext } from "../recipe/session/types"; +import type { AppInfoUserInput } from "../types"; +export declare type CookiesStore = { + get: (name: string) => { + value: string; + }; + set: (name: string, value: string) => void; +}; +export declare type HeadersStore = { + get: (name: string) => string | null; + set: (name: string, value: string) => void; + getSetCookie: () => string[]; +}; +export declare type CookiesObject = Record; +export declare type HeadersObject = Record; +export declare type GetServerSidePropsRedirect = { + redirect: { + destination: string; + permanent: boolean; + }; +}; +export declare type GetServerSidePropsReturnValue = { + props: { + session: LoadedSessionContext; + }; +} | GetServerSidePropsRedirect; +export declare function isCookiesStore(obj: unknown): obj is CookiesStore; +export declare type SuperTokensNextjsConfig = { + appInfo: AppInfoUserInput; + enableDebugLogs?: boolean; +}; +export declare type SuperTokensRequestToken = { + header: string | null; + cookie: string | null; +}; +export declare type FrontTokenPayload = { + uid: string; + ate: number; + up: { + iat: number; + exp: number; + sub: string; + tId: string; + rsub: string; + sessionHandle: string; + refrehTokenHash1: string; + parentRefereshTokenHash1: string | null; + antiCsrfToken: string | null; + iss: string; + "st-role": { + v: string; + t: number[]; + }; + "st-perm": { + v: string[]; + t: number; + }; + }; +}; +export interface ParsableRequest { + url: string; + method: string; + headers: Headers; + formData: () => Promise; + json: () => Promise; +} +export declare type ApiRequestMiddleware = (req: Req) => Promise; diff --git a/lib/build/nextjsmiddleware.js b/lib/build/nextjsmiddleware.js new file mode 100644 index 000000000..8025428c9 --- /dev/null +++ b/lib/build/nextjsmiddleware.js @@ -0,0 +1,308 @@ +'use strict'; + +var utils = require('./utils.js'); +var constants = require('./constants.js'); +require('react'); +require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('supertokens-web-js/utils/normalisedURLPath'); +require('supertokens-web-js/utils/windowHandler'); +require('crypto'); + +var AppInfo; +function superTokensMiddleware(config) { + var _this = this; + var apiRequestMiddleware = config.apiRequestMiddleware, _isApiRequest = config.isApiRequest; + var isApiRequest = _isApiRequest !== null && _isApiRequest !== void 0 ? _isApiRequest : defaultIsApiRequest; + var usesTheNextjsApiAsTheAuthenticationServer = compareUrlHost(config.appInfo.apiDomain, config.appInfo.websiteDomain); + if (config.enableDebugLogs) { + utils.enableLogging(); + } + AppInfo = utils.normaliseInputAppInfoOrThrowError(config.appInfo); + return function (request) { return utils.__awaiter(_this, void 0, void 0, function () { + var requestUrl, refreshPath, response; + return utils.__generator(this, function (_a) { + requestUrl = new URL(request.url); + refreshPath = getRefreshAPIPath(); + if (requestUrl.pathname.startsWith(refreshPath) && request.method === "GET") { + return [2 /*return*/, refreshSession(request)]; + } + if (isApiRequest(request) && usesTheNextjsApiAsTheAuthenticationServer) { + if (requestUrl.pathname.startsWith(AppInfo.apiBasePath.getAsStringDangerous())) { + // this hits our pages/api/auth/* endpoints + return [2 /*return*/, next()]; + } + if (apiRequestMiddleware) { + return [2 /*return*/, apiRequestMiddleware(request)]; + } + } + if (requestUrl.pathname.startsWith(AppInfo.websiteBasePath.getAsStringDangerous()) && + requestUrl.searchParams.get(constants.FORCE_LOGOUT_PATH_PARAM_NAME) === "true") { + return [2 /*return*/, revokeSession(request)]; + } + response = next(); + response.headers.append("set-cookie", "".concat(constants.CURRENT_PATH_COOKIE_NAME, "=").concat(requestUrl.pathname, "; Path=/; HttpOnly; SameSite=Strict")); + return [2 /*return*/, response]; + }); + }); }; +} +function refreshSession(request) { + return utils.__awaiter(this, void 0, void 0, function () { + var redirectAttemptNumber, requestUrl, urlParamRedirectPath, redirectTo, tokens, hasRequiredCookies, redirectUrl, finalResponse, err_1; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + redirectAttemptNumber = getRedirectAttemptNumber(request); + if (redirectAttemptNumber > constants.REDIRECT_ATTEMPT_MAX_COUNT) { + return [2 /*return*/, redirectToAuthPage(request)]; + } + if (!getCookie(request, constants.REFRESH_TOKEN_COOKIE_NAME) && !extractTokenFromTheAuthorizationHeader(request)) { + utils.logDebugMessage("Refresh token not found"); + return [2 /*return*/, redirectToAuthPage(request)]; + } + requestUrl = new URL(request.url); + urlParamRedirectPath = requestUrl.searchParams.get(constants.REDIRECT_PATH_PARAM_NAME); + redirectTo = urlParamRedirectPath && isValidUrlPath(urlParamRedirectPath) ? urlParamRedirectPath : "/"; + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, fetchNewTokens(request)]; + case 2: + tokens = _a.sent(); + hasRequiredCookies = tokens.accessToken && tokens.refreshToken && tokens.frontToken; + if (!hasRequiredCookies) { + utils.logDebugMessage("Missing tokens from refresh response"); + return [2 /*return*/, redirectToAuthPage(request)]; + } + redirectUrl = new URL(redirectTo, request.url); + finalResponse = redirect(redirectUrl.toString()); + finalResponse.headers.append("set-cookie", tokens.accessToken); + finalResponse.headers.append("set-cookie", tokens.refreshToken); + finalResponse.headers.append("set-cookie", tokens.frontToken); + if (tokens.antiCsrfToken) { + finalResponse.headers.append("set-cookie", tokens.antiCsrfToken); + } + finalResponse.headers.append("set-cookie", "".concat(constants.REDIRECT_ATTEMPT_COUNT_COOKIE_NAME, "=").concat(redirectAttemptNumber + 1, "; Path=/; Max-Age=10; HttpOnly; SameSite=Strict")); + utils.logDebugMessage("Attached new tokens to response"); + return [2 /*return*/, finalResponse]; + case 3: + err_1 = _a.sent(); + utils.logDebugMessage("Error refreshing session"); + utils.logDebugMessage(err_1); + return [2 /*return*/, redirectToAuthPage(request)]; + case 4: return [2 /*return*/]; + } + }); + }); +} +function revokeSession(request) { + return utils.__awaiter(this, void 0, void 0, function () { + var response, accessToken, signOutURL, err_2, refreshPath; + var _a; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + response = new Response(null, {}); + _b.label = 1; + case 1: + _b.trys.push([1, 3, , 4]); + accessToken = getCookie(request, constants.ACCESS_TOKEN_COOKIE_NAME) || extractTokenFromTheAuthorizationHeader(request); + if (!accessToken) { + throw new Error("No access token found in the request"); + } + signOutURL = new URL("".concat(AppInfo.apiBasePath.getAsStringDangerous(), "/signout"), AppInfo.apiDomain.getAsStringDangerous()); + return [4 /*yield*/, fetch(signOutURL, { + method: "POST", + headers: (_a = { + "Content-Type": "application/json" + }, + _a[constants.ACCESS_TOKEN_HEADER_NAME] = accessToken, + _a.Cookie = "".concat(constants.ACCESS_TOKEN_COOKIE_NAME, "=").concat(accessToken), + _a), + credentials: "include", + })]; + case 2: + _b.sent(); + return [3 /*break*/, 4]; + case 3: + err_2 = _b.sent(); + utils.logDebugMessage("Error during the sign out attempt"); + utils.logDebugMessage(err_2); + return [3 /*break*/, 4]; + case 4: + response.headers.set("x-middleware-next", "1"); + response.headers.append("set-cookie", "".concat(constants.ACCESS_TOKEN_COOKIE_NAME, "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Lax")); + response.headers.append("set-cookie", "".concat(constants.FRONT_TOKEN_COOKIE_NAME, "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Lax")); + response.headers.append("set-cookie", "".concat(constants.ANTI_CSRF_TOKEN_COOKIE_NAME, "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Lax")); + refreshPath = getRefreshAPIPath(); + response.headers.append("set-cookie", "".concat(constants.REFRESH_TOKEN_COOKIE_NAME, "=; Path=").concat(refreshPath, "; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Lax")); + response.headers.delete(constants.ACCESS_TOKEN_HEADER_NAME); + response.headers.delete(constants.REFRESH_TOKEN_HEADER_NAME); + response.headers.delete(constants.FRONT_TOKEN_HEADER_NAME); + response.headers.delete(constants.ANTI_CSRF_TOKEN_HEADER_NAME); + return [2 /*return*/, response]; + } + }); + }); +} +function redirectToAuthPage(request) { + var redirectUrl = new URL(AppInfo.websiteBasePath.getAsStringDangerous(), request.url); + redirectUrl.searchParams.set(constants.FORCE_LOGOUT_PATH_PARAM_NAME, "true"); + return redirect(redirectUrl.toString()); +} +function redirect(location) { + utils.logDebugMessage("Redirecting to: ".concat(location)); + return new Response(null, { + status: 302, + headers: { + Location: location, + }, + }); +} +function next() { + var response = new Response(null, {}); + response.headers.set("x-middleware-next", "1"); + return response; +} +function fetchNewTokens(request) { + return utils.__awaiter(this, void 0, void 0, function () { + var refreshApiURL, cookieRefreshToken, headerRefreshToken, refreshRequestHeaders, refreshResponse, frontTokenHeaderValue, cookieTokens, setCookieHeaders, _i, setCookieHeaders_1, header, accessTokenHeaderValue, refreshTokenHeaderValue, antiCsrfTokenHeaderValue; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + refreshApiURL = new URL("".concat(AppInfo.apiBasePath.getAsStringDangerous(), "/session/refresh"), AppInfo.apiDomain.getAsStringDangerous()); + cookieRefreshToken = getCookie(request, constants.REFRESH_TOKEN_COOKIE_NAME); + headerRefreshToken = extractTokenFromTheAuthorizationHeader(request); + refreshRequestHeaders = { + "Content-Type": "application/json", + }; + if (cookieRefreshToken) { + refreshRequestHeaders.Cookie = "".concat(constants.REFRESH_TOKEN_COOKIE_NAME, "=").concat(cookieRefreshToken); + } + else if (headerRefreshToken) { + refreshRequestHeaders.Authorization = "Bearer ".concat(headerRefreshToken); + } + return [4 /*yield*/, fetch(refreshApiURL, { + method: "POST", + headers: refreshRequestHeaders, + credentials: "include", + })]; + case 1: + refreshResponse = _a.sent(); + if (!refreshResponse.ok) { + utils.logDebugMessage("Refresh request returned an invalid status code: ".concat(refreshResponse.status)); + return [2 /*return*/, { accessToken: "", refreshToken: "", frontToken: "", antiCsrfToken: "" }]; + } + utils.logDebugMessage("Session refresh request completed"); + frontTokenHeaderValue = refreshResponse.headers.get(constants.FRONT_TOKEN_HEADER_NAME); + cookieTokens = { + accessToken: "", + refreshToken: "", + frontToken: "".concat(constants.FRONT_TOKEN_COOKIE_NAME, "=").concat(frontTokenHeaderValue, "; Path=/"), + antiCsrfToken: "", + }; + setCookieHeaders = refreshResponse.headers.getSetCookie(); + for (_i = 0, setCookieHeaders_1 = setCookieHeaders; _i < setCookieHeaders_1.length; _i++) { + header = setCookieHeaders_1[_i]; + if (header.includes(constants.ACCESS_TOKEN_COOKIE_NAME)) { + cookieTokens.accessToken = header; + } + if (header.includes(constants.REFRESH_TOKEN_COOKIE_NAME)) { + cookieTokens.refreshToken = header; + } + if (header.includes(constants.ANTI_CSRF_TOKEN_COOKIE_NAME)) { + cookieTokens.antiCsrfToken = header; + } + } + accessTokenHeaderValue = refreshResponse.headers.get(constants.ACCESS_TOKEN_HEADER_NAME); + refreshTokenHeaderValue = refreshResponse.headers.get(constants.REFRESH_TOKEN_HEADER_NAME); + antiCsrfTokenHeaderValue = refreshResponse.headers.get(constants.ANTI_CSRF_TOKEN_HEADER_NAME); + if (!cookieTokens.accessToken) { + cookieTokens.accessToken = "".concat(constants.ACCESS_TOKEN_COOKIE_NAME, "=").concat(accessTokenHeaderValue, "; Path=/; HttpOnly; SameSite=Lax"); + } + if (!cookieTokens.refreshToken) { + cookieTokens.refreshToken = "".concat(constants.REFRESH_TOKEN_COOKIE_NAME, "=").concat(refreshTokenHeaderValue, "; Path=/api/auth/session/refresh; HttpOnly; SameSite=Lax"); + } + if (!cookieTokens.antiCsrfToken && antiCsrfTokenHeaderValue) { + cookieTokens.antiCsrfToken = "".concat(constants.ANTI_CSRF_TOKEN_COOKIE_NAME, "=").concat(antiCsrfTokenHeaderValue, "; Path=/; HttpOnly; SameSite=Lax"); + } + return [2 /*return*/, cookieTokens]; + } + }); + }); +} +function getCookie(request, name) { + var _a, _b; + return (_b = (_a = request.headers + .get("cookie")) === null || _a === void 0 ? void 0 : _a.split("; ").find(function (row) { return row.startsWith("".concat(name, "=")); })) === null || _b === void 0 ? void 0 : _b.split("=")[1]; +} +function getRedirectAttemptNumber(request) { + var cookieValue = getCookie(request, constants.REDIRECT_ATTEMPT_COUNT_COOKIE_NAME) || "1"; + try { + return parseInt(cookieValue); + } + catch (err) { + return 1; + } +} +function isValidUrlPath(path) { + try { + if (typeof path !== "string" || path.trim() === "") { + return false; + } + if (!path.startsWith("/")) { + return false; + } + var normalizedPath = normalizeUrlPath(path); + var invalidChars = /[<>:"|?*\0]/; + return (!invalidChars.test(normalizedPath) && + normalizedPath.startsWith("/") && + !normalizedPath.includes("//") && + normalizedPath.length <= 2048); + } + catch (_a) { + return false; + } +} +function normalizeUrlPath(path) { + if (!path) + return "/"; + var normalizedPath = path.split("?")[0].split("#")[0]; + // remove trailing slash + normalizedPath = path.replace(/\/$/, ""); + normalizedPath = !normalizedPath.startsWith("/") ? "/".concat(path) : path; + return normalizedPath; +} +function compareUrlHost(firstUrl, secondUrl) { + try { + var firstUrlObject = new URL(firstUrl); + var secondUrlObject = new URL(secondUrl); + return firstUrlObject.host === secondUrlObject.host; + } + catch (err) { + utils.logDebugMessage("Error comparing URL host"); + utils.logDebugMessage(err); + return false; + } +} +function extractTokenFromTheAuthorizationHeader(request) { + var headerValue = request.headers.get("authorization") || request.headers.get("Authorization"); + if (!headerValue) + return null; + var token = headerValue.split(" ")[1]; + return token || null; +} +function getRefreshAPIPath() { + var apiPath = AppInfo.apiBasePath.getAsStringDangerous(); + return "".concat(apiPath, "/session/refresh"); +} +function defaultIsApiRequest(request) { + var requestUrl = new URL(request.url); + var refreshPath = getRefreshAPIPath(); + return requestUrl.pathname.startsWith(refreshPath); +} + +exports.refreshSession = refreshSession; +exports.revokeSession = revokeSession; +exports.superTokensMiddleware = superTokensMiddleware; diff --git a/lib/build/nextjsssr.js b/lib/build/nextjsssr.js new file mode 100644 index 000000000..36b1b8b86 --- /dev/null +++ b/lib/build/nextjsssr.js @@ -0,0 +1,338 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var utils = require('./utils.js'); +var WebJSSessionRecipe = require('supertokens-web-js/recipe/session'); +var constants = require('./constants.js'); +var utils$1 = require('supertokens-web-js/utils'); +var superTokens = require('./superTokens.js'); +require('react'); +require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('supertokens-web-js/utils/normalisedURLPath'); +require('supertokens-web-js/utils/windowHandler'); +require('crypto'); +require('supertokens-web-js'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('supertokens-web-js/recipe/multitenancy'); + +function isCookiesStore(obj) { + return typeof obj === "object" && obj !== null && "get" in obj && typeof obj.get === "function"; +} + +var SuperTokensNextjsSSRAPIWrapper = /** @class */ (function () { + function SuperTokensNextjsSSRAPIWrapper() { + } + SuperTokensNextjsSSRAPIWrapper.init = function (config) { + if (config.enableDebugLogs) { + utils.enableLogging(); + } + SuperTokensNextjsSSRAPIWrapper.config = config; + }; + SuperTokensNextjsSSRAPIWrapper.getConfigOrThrow = function () { + if (!SuperTokensNextjsSSRAPIWrapper.config) { + throw new Error("SuperTokens must be initialized before calling this method."); + } + return SuperTokensNextjsSSRAPIWrapper.config; + }; + SuperTokensNextjsSSRAPIWrapper.getJWKSUrl = function () { + var appInfo = SuperTokensNextjsSSRAPIWrapper.getConfigOrThrow().appInfo; + var jwksPath = "".concat(appInfo.apiBasePath, "/jwt/jwks.json"); + if (!jwksPath.startsWith("/")) { + jwksPath = "/".concat(jwksPath); + } + jwksPath = jwksPath.replace("//", "/"); + var jwksUrl = new URL(jwksPath, appInfo.apiDomain); + return jwksUrl.toString(); + }; + /** + * Get the session state inside a server componet or redirect + * The function is meant to be used inside Next.js server components + * @param cookies - The cookies store exposed by next/headers (await cookies()) + * @returns The session context value or directly redirects the user to either the login page or the refresh API + **/ + SuperTokensNextjsSSRAPIWrapper.getServerComponentSession = function (cookies) { + var _a; + return utils.__awaiter(this, void 0, void 0, function () { + var redirectPath, authPagePath, refreshLocation, _b, state, session; + return utils.__generator(this, function (_c) { + switch (_c.label) { + case 0: + redirectPath = ((_a = cookies.get(constants.CURRENT_PATH_COOKIE_NAME)) === null || _a === void 0 ? void 0 : _a.value) || "/"; + authPagePath = getAuthPagePath(redirectPath); + refreshLocation = getRefreshLocation(redirectPath); + return [4 /*yield*/, getSSRSessionState(cookies)]; + case 1: + _b = _c.sent(), state = _b.state, session = _b.session; + utils.logDebugMessage("SSR Session State: ".concat(state)); + switch (state) { + case "front-token-not-found": + case "front-token-invalid": + case "access-token-invalid": + utils.logDebugMessage("Redirecting to Auth Page: ".concat(authPagePath)); + return [2 /*return*/, redirect(authPagePath)]; + case "front-token-expired": + case "access-token-not-found": + case "tokens-do-not-match": + utils.logDebugMessage("Redirecting to refresh API: ".concat(refreshLocation)); + return [2 /*return*/, redirect(refreshLocation)]; + case "tokens-match": + utils.logDebugMessage("Returning session object"); + return [2 /*return*/, session]; + default: + // This is here just to prevent typescript from complaining + // about the function not returning a value + throw new Error("Unknown state: ".concat(state)); + } + return [2 /*return*/]; + } + }); + }); + }; + /** + * Get the session state inside a server action + * The function is meant to be used inside Next.js server actions + * @param cookies - The cookies store exposed by next/headers (await cookies()) + * @returns An object that includes session context value and the status of the session ('valid' | 'expired' | 'invalid') + * If the status is 'invalid' or 'expired' then the users should be considered as unauthenticated + **/ + SuperTokensNextjsSSRAPIWrapper.getServerActionSession = function (cookies) { + return utils.__awaiter(this, void 0, void 0, function () { + var _a, state, session; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, getSSRSessionState(cookies)]; + case 1: + _a = _b.sent(), state = _a.state, session = _a.session; + utils.logDebugMessage("SSR Session State: ".concat(state)); + if (state === "tokens-match") { + return [2 /*return*/, { session: session, status: "valid" }]; + } + else if (["tokens-do-not-match", "front-token-expired", "access-token-not-found", "access-token-invalid"].includes(state)) { + return [2 /*return*/, { status: "expired", session: undefined }]; + } + return [2 /*return*/, { status: "invalid", session: undefined }]; + } + }); + }); + }; + /** + * Ensures that a server action is called by an authenticated user + * If the session does not exist/user is not authenticated, it will automatically redirect to the login page + * The function is meant to run on the client, before calling the actual server action + * @param action - A server action that will get called after the authentication state is confirmed + * @returns The server action return value + **/ + SuperTokensNextjsSSRAPIWrapper.confirmAuthenticationAndCallServerAction = function (action) { + return utils.__awaiter(this, void 0, void 0, function () { + var sessionExists; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 3, , 4]); + return [4 /*yield*/, WebJSSessionRecipe.doesSessionExist()]; + case 1: + sessionExists = _a.sent(); + utils.logDebugMessage("Session exists: ".concat(sessionExists)); + if (!sessionExists) { + return [2 /*return*/, superTokens.SuperTokens.getInstanceOrThrow().redirectToAuth({ + show: "signin", + redirectBack: true, + userContext: utils$1.getNormalisedUserContext({}), + })]; + } + utils.logDebugMessage("Retrieved access token payload"); + return [4 /*yield*/, WebJSSessionRecipe.getAccessTokenPayloadSecurely()]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + _a.sent(); + utils.logDebugMessage("Error while authenticating server action"); + return [2 /*return*/, superTokens.SuperTokens.getInstanceOrThrow().redirectToAuth({ + show: "signin", + redirectBack: true, + userContext: utils$1.getNormalisedUserContext({}), + })]; + case 4: + utils.logDebugMessage("Calling server action"); + return [2 /*return*/, action()]; + } + }); + }); + }; + /** + * Get the session state or redirect + * The function is meant to be used inside getServerSideProps. + * @param request - The request object available inside getServerSideProps ctx (ctx.req) + * @returns The session context value or a redirects path to send the user to the refresh API or the login page + **/ + SuperTokensNextjsSSRAPIWrapper.getServerSidePropsSession = function (request) { + return utils.__awaiter(this, void 0, void 0, function () { + var appInfo, requestUrl, redirectPath, authPagePath, refreshLocation, _a, state, session; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + appInfo = SuperTokensNextjsSSRAPIWrapper.getConfigOrThrow().appInfo; + requestUrl = new URL(request.url, appInfo.websiteDomain); + redirectPath = requestUrl.pathname; + authPagePath = getAuthPagePath(redirectPath); + refreshLocation = getRefreshLocation(redirectPath); + return [4 /*yield*/, getSSRSessionState(request.cookies)]; + case 1: + _a = _b.sent(), state = _a.state, session = _a.session; + utils.logDebugMessage("SSR Session State: ".concat(state)); + switch (state) { + case "front-token-not-found": + case "front-token-invalid": + case "access-token-invalid": + utils.logDebugMessage("Redirecting to Auth Page: ".concat(authPagePath)); + return [2 /*return*/, { redirect: { destination: authPagePath, permanent: false } }]; + case "front-token-expired": + case "access-token-not-found": + case "tokens-do-not-match": + utils.logDebugMessage("Redirecting to refresh API: ".concat(refreshLocation)); + return [2 /*return*/, { redirect: { destination: refreshLocation, permanent: false } }]; + case "tokens-match": + utils.logDebugMessage("Returning session object"); + return [2 /*return*/, { props: { session: session } }]; + default: + // This is here just to prevent typescript from complaining + // about the function not returning a value + throw new Error("Unknown state: ".concat(state)); + } + return [2 /*return*/]; + } + }); + }); + }; + return SuperTokensNextjsSSRAPIWrapper; +}()); +var init = SuperTokensNextjsSSRAPIWrapper.init; +var getServerComponentSession = SuperTokensNextjsSSRAPIWrapper.getServerComponentSession; +var getServerActionSession = SuperTokensNextjsSSRAPIWrapper.getServerActionSession; +var getServerSidePropsSession = SuperTokensNextjsSSRAPIWrapper.getServerSidePropsSession; +var confirmAuthenticationAndCallServerAction = SuperTokensNextjsSSRAPIWrapper.confirmAuthenticationAndCallServerAction; +function getAuthPagePath(redirectPath) { + var authPagePath = SuperTokensNextjsSSRAPIWrapper.getConfigOrThrow().appInfo.websiteBasePath || "/auth"; + return "".concat(authPagePath, "?").concat(constants.FORCE_LOGOUT_PATH_PARAM_NAME, "=true&").concat(constants.REDIRECT_PATH_PARAM_NAME, "=").concat(redirectPath); +} +function getRefreshAPIPath() { + var apiPath = SuperTokensNextjsSSRAPIWrapper.getConfigOrThrow().appInfo.apiBasePath || constants.DEFAULT_API_PATH; + return "".concat(apiPath, "/session/refresh"); +} +function getRefreshLocation(redirectPath) { + var refreshAPIPath = getRefreshAPIPath(); + return "".concat(refreshAPIPath, "?").concat(constants.REDIRECT_PATH_PARAM_NAME, "=").concat(redirectPath); +} +function getSSRSessionState(cookies) { + return utils.__awaiter(this, void 0, void 0, function () { + var frontToken, parsedFrontToken, accessToken, parsedAccessToken; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + frontToken = getCookieValue(cookies, constants.FRONT_TOKEN_COOKIE_NAME) || getCookieValue(cookies, constants.FRONT_TOKEN_HEADER_NAME); + if (!frontToken) { + return [2 /*return*/, { state: "front-token-not-found" }]; + } + parsedFrontToken = parseFrontToken(frontToken); + if (!parsedFrontToken.isValid) { + return [2 /*return*/, { state: "front-token-invalid" }]; + } + utils.logDebugMessage("Front token expires at: ".concat(new Date(parsedFrontToken.ate))); + if (parsedFrontToken.ate < Date.now()) { + return [2 /*return*/, { state: "front-token-expired" }]; + } + accessToken = getCookieValue(cookies, constants.ACCESS_TOKEN_COOKIE_NAME) || getCookieValue(cookies, constants.ACCESS_TOKEN_HEADER_NAME); + if (!accessToken) { + return [2 /*return*/, { state: "access-token-not-found" }]; + } + return [4 /*yield*/, parseAccessToken(accessToken)]; + case 1: + parsedAccessToken = _a.sent(); + if (!parsedAccessToken.isValid) { + return [2 /*return*/, { state: "access-token-invalid" }]; + } + if (!compareTokenPayloads(parsedFrontToken.payload, parsedAccessToken.payload)) { + return [2 /*return*/, { state: "tokens-do-not-match" }]; + } + return [2 /*return*/, { + state: "tokens-match", + session: buildLoadedSessionContext(parsedAccessToken.payload), + }]; + } + }); + }); +} +function buildLoadedSessionContext(accessTokenPayload) { + return { + userId: accessTokenPayload.sub, + accessTokenPayload: accessTokenPayload, + doesSessionExist: true, + loading: false, + invalidClaims: [], + }; +} +function parseFrontToken(frontToken) { + try { + var parsedToken = JSON.parse(decodeURIComponent(escape(atob(frontToken)))); + if (!parsedToken.uid || !parsedToken.ate || !parsedToken.up) { + return { isValid: false }; + } + return { payload: parsedToken.up, ate: parsedToken.ate, isValid: true }; + } + catch (err) { + utils.logDebugMessage("Error while parsing front token: ".concat(err)); + return { isValid: false }; + } +} +function parseAccessToken(token) { + return utils.__awaiter(this, void 0, void 0, function () { + var payload, err_2; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + return [4 /*yield*/, utils.jwtVerify(token, SuperTokensNextjsSSRAPIWrapper.getJWKSUrl())]; + case 1: + payload = _a.sent(); + if (!payload.sub || !payload.exp) { + return [2 /*return*/, { isValid: false }]; + } + return [2 /*return*/, { isValid: true, payload: payload }]; + case 2: + err_2 = _a.sent(); + utils.logDebugMessage("Error while parsing access token: ".concat(err_2)); + return [2 /*return*/, { isValid: false }]; + case 3: return [2 /*return*/]; + } + }); + }); +} +function compareTokenPayloads(payload1, payload2) { + return JSON.stringify(payload1) === JSON.stringify(payload2); +} +function getCookieValue(cookie, name) { + var _a; + if (isCookiesStore(cookie)) { + return (_a = cookie.get(name)) === null || _a === void 0 ? void 0 : _a.value; + } + return cookie[name]; +} +var REDIRECT_ERROR_CODE = "NEXT_REDIRECT"; +function redirect(path) { + var type = "push"; + var statusCode = 307; + var error = new Error(REDIRECT_ERROR_CODE); + error.digest = "".concat(REDIRECT_ERROR_CODE, ";").concat(type, ";").concat(path, ";").concat(statusCode, ";"); + throw error; +} + +exports.confirmAuthenticationAndCallServerAction = confirmAuthenticationAndCallServerAction; +exports.default = SuperTokensNextjsSSRAPIWrapper; +exports.getServerActionSession = getServerActionSession; +exports.getServerComponentSession = getServerComponentSession; +exports.getServerSidePropsSession = getServerSidePropsSession; +exports.init = init; diff --git a/lib/build/oauth2provider-shared.js b/lib/build/oauth2provider-shared.js index 27f1e02ea..cec8b61c4 100644 --- a/lib/build/oauth2provider-shared.js +++ b/lib/build/oauth2provider-shared.js @@ -1,197 +1,144 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var OAuth2WebJS = require("supertokens-web-js/recipe/oauth2provider"); -var index = require("./recipeModule-shared.js"); +var utils = require('./utils.js'); +var OAuth2WebJS = require('supertokens-web-js/recipe/oauth2provider'); +var index = require('./recipeModule-shared.js'); +var superTokens = require('./superTokens.js'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } -var OAuth2WebJS__default = /*#__PURE__*/ _interopDefault(OAuth2WebJS); +var OAuth2WebJS__default = /*#__PURE__*/_interopDefault(OAuth2WebJS); -var getFunctionOverrides = function (onHandleEvent) { - return function (originalImp) { - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, originalImp), { - getLoginChallengeInfo: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, originalImp.getLoginChallengeInfo(input)]; - case 1: - response = _a.sent(); - onHandleEvent({ - action: "LOADED_LOGIN_CHALLENGE", - loginChallenge: input.loginChallenge, - loginInfo: response.info, - userContext: input.userContext, - }); - return [2 /*return*/, response]; - } - }); - }); - }, - logOut: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, originalImp.logOut(input)]; - case 1: - response = _a.sent(); - onHandleEvent({ - action: "OAUTH2_LOGOUT_SUCCESS", - frontendRedirectTo: response.frontendRedirectTo, - userContext: input.userContext, - }); - return [2 /*return*/, response]; - } - }); - }); - }, - }); - }; +var getFunctionOverrides = function (onHandleEvent) { + return function (originalImp) { return (utils.__assign(utils.__assign({}, originalImp), { getLoginChallengeInfo: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, originalImp.getLoginChallengeInfo(input)]; + case 1: + response = _a.sent(); + onHandleEvent({ + action: "LOADED_LOGIN_CHALLENGE", + loginChallenge: input.loginChallenge, + loginInfo: response.info, + userContext: input.userContext, + }); + return [2 /*return*/, response]; + } + }); + }); + }, logOut: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, originalImp.logOut(input)]; + case 1: + response = _a.sent(); + onHandleEvent({ + action: "OAUTH2_LOGOUT_SUCCESS", + frontendRedirectTo: response.frontendRedirectTo, + userContext: input.userContext, + }); + return [2 /*return*/, response]; + } + }); + }); + } })); }; }; -function normaliseOAuth2Config(config) { - var _a; - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign( - {}, - genericComponentOverrideContext.normaliseRecipeModuleConfig(config) - ), - { - disableDefaultUI: - (_a = config === null || config === void 0 ? void 0 : config.disableDefaultUI) !== null && _a !== void 0 - ? _a - : false, - tryRefreshPage: genericComponentOverrideContext.__assign( - { disableDefaultUI: false }, - config === null || config === void 0 ? void 0 : config.tryRefreshPage - ), - oauth2LogoutScreen: genericComponentOverrideContext.__assign( - { disableDefaultUI: false, style: "" }, - config === null || config === void 0 ? void 0 : config.oauth2LogoutScreen - ), - override: genericComponentOverrideContext.__assign( - { - functions: function (originalImplementation) { - return originalImplementation; - }, - }, - config === null || config === void 0 ? void 0 : config.override - ), - } - ); +function normaliseOAuth2Config(config) { + var _a; + return utils.__assign(utils.__assign({}, superTokens.normaliseRecipeModuleConfig(config)), { disableDefaultUI: (_a = config === null || config === void 0 ? void 0 : config.disableDefaultUI) !== null && _a !== void 0 ? _a : false, tryRefreshPage: utils.__assign({ disableDefaultUI: false }, config === null || config === void 0 ? void 0 : config.tryRefreshPage), oauth2LogoutScreen: utils.__assign({ disableDefaultUI: false, style: "" }, config === null || config === void 0 ? void 0 : config.oauth2LogoutScreen), override: utils.__assign({ functions: function (originalImplementation) { return originalImplementation; } }, config === null || config === void 0 ? void 0 : config.override) }); } -/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Class. - */ -var OAuth2Provider = /** @class */ (function (_super) { - genericComponentOverrideContext.__extends(OAuth2Provider, _super); - function OAuth2Provider(config, webJSRecipe) { - if (webJSRecipe === void 0) { - webJSRecipe = OAuth2WebJS__default.default; - } - var _this = _super.call(this, config) || this; - _this.webJSRecipe = webJSRecipe; - _this.recipeID = OAuth2Provider.RECIPE_ID; - return _this; - } - OAuth2Provider.init = function (config) { - var normalisedConfig = normaliseOAuth2Config(config); - return { - recipeID: OAuth2Provider.RECIPE_ID, - authReact: function (appInfo) { - OAuth2Provider.instance = new OAuth2Provider( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, normalisedConfig), - { appInfo: appInfo, recipeId: OAuth2Provider.RECIPE_ID } - ) - ); - return OAuth2Provider.instance; - }, - webJS: OAuth2WebJS__default.default.init( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, normalisedConfig), - { - override: { - functions: function (originalImpl, builder) { - var functions = getFunctionOverrides(normalisedConfig.onHandleEvent); - builder.override(functions); - builder.override(normalisedConfig.override.functions); - return originalImpl; - }, - }, - } - ) - ), - }; - }; - OAuth2Provider.getInstanceOrThrow = function () { - if (OAuth2Provider.instance === undefined) { - var error = - "No instance of OAuth2Provider found. Make sure to call the OAuth2Provider.init method." + - "See https://supertokens.io/docs/oauth2/quick-setup/frontend"; - // eslint-disable-next-line supertokens-auth-react/no-direct-window-object - if (typeof window === "undefined") { - error = error + genericComponentOverrideContext.SSR_ERROR; - } - throw Error(error); - } - return OAuth2Provider.instance; - }; - OAuth2Provider.getInstance = function () { - return OAuth2Provider.instance; - }; - OAuth2Provider.prototype.getDefaultRedirectionURL = function (ctx) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - // We do not use the util here, because we are likely redirecting across domains here. - if ( - ctx.action === "SUCCESS_OAUTH2" || - ctx.action === "CONTINUE_OAUTH2_AFTER_REFRESH" || - ctx.action === "POST_OAUTH2_LOGOUT_REDIRECT" - ) { - return [2 /*return*/, ctx.frontendRedirectTo]; - } else { - throw new Error( - "Should never come here: unknown action in OAuth2Provider.getDefaultRedirectionURL" - ); - } - }); - }); - }; - /* - * Tests methods. - */ - OAuth2Provider.reset = function () { - if (!genericComponentOverrideContext.isTest()) { - return; - } - OAuth2Provider.instance = undefined; - return; - }; - OAuth2Provider.RECIPE_ID = "oauth2provider"; - return OAuth2Provider; -})(index.RecipeModule); +/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Class. + */ +var OAuth2Provider = /** @class */ (function (_super) { + utils.__extends(OAuth2Provider, _super); + function OAuth2Provider(config, webJSRecipe) { + if (webJSRecipe === void 0) { webJSRecipe = OAuth2WebJS__default.default; } + var _this = _super.call(this, config) || this; + _this.webJSRecipe = webJSRecipe; + _this.recipeID = OAuth2Provider.RECIPE_ID; + return _this; + } + OAuth2Provider.init = function (config) { + var normalisedConfig = normaliseOAuth2Config(config); + return { + recipeID: OAuth2Provider.RECIPE_ID, + authReact: function (appInfo) { + OAuth2Provider.instance = new OAuth2Provider(utils.__assign(utils.__assign({}, normalisedConfig), { appInfo: appInfo, recipeId: OAuth2Provider.RECIPE_ID })); + return OAuth2Provider.instance; + }, + webJS: OAuth2WebJS__default.default.init(utils.__assign(utils.__assign({}, normalisedConfig), { override: { + functions: function (originalImpl, builder) { + var functions = getFunctionOverrides(normalisedConfig.onHandleEvent); + builder.override(functions); + builder.override(normalisedConfig.override.functions); + return originalImpl; + }, + } })), + }; + }; + OAuth2Provider.getInstanceOrThrow = function () { + if (OAuth2Provider.instance === undefined) { + var error = "No instance of OAuth2Provider found. Make sure to call the OAuth2Provider.init method." + + "See https://supertokens.io/docs/oauth2/quick-setup/frontend"; + // eslint-disable-next-line supertokens-auth-react/no-direct-window-object + if (typeof window === "undefined") { + error = error + utils.SSR_ERROR; + } + throw Error(error); + } + return OAuth2Provider.instance; + }; + OAuth2Provider.getInstance = function () { + return OAuth2Provider.instance; + }; + OAuth2Provider.prototype.getDefaultRedirectionURL = function (ctx) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + // We do not use the util here, because we are likely redirecting across domains here. + if (ctx.action === "SUCCESS_OAUTH2" || + ctx.action === "CONTINUE_OAUTH2_AFTER_REFRESH" || + ctx.action === "POST_OAUTH2_LOGOUT_REDIRECT") { + return [2 /*return*/, ctx.frontendRedirectTo]; + } + else { + throw new Error("Should never come here: unknown action in OAuth2Provider.getDefaultRedirectionURL"); + } + }); + }); + }; + /* + * Tests methods. + */ + OAuth2Provider.reset = function () { + if (!utils.isTest()) { + return; + } + OAuth2Provider.instance = undefined; + return; + }; + OAuth2Provider.RECIPE_ID = "oauth2provider"; + return OAuth2Provider; +}(index.RecipeModule)); exports.OAuth2Provider = OAuth2Provider; diff --git a/lib/build/oauth2provider-shared2.js b/lib/build/oauth2provider-shared2.js index bd3b554b5..7d16271fd 100644 --- a/lib/build/oauth2provider-shared2.js +++ b/lib/build/oauth2provider-shared2.js @@ -1,10 +1,8 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); +var genericComponentOverrideContext = require('./genericComponentOverrideContext.js'); -var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), - useContext = _a[0], - Provider = _a[1]; +var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), useContext = _a[0], Provider = _a[1]; exports.Provider = Provider; exports.useContext = useContext; diff --git a/lib/build/oauth2provider.js b/lib/build/oauth2provider.js index f987e40a7..0098d5dc3 100644 --- a/lib/build/oauth2provider.js +++ b/lib/build/oauth2provider.js @@ -1,96 +1,100 @@ -"use strict"; +'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, '__esModule', { value: true }); -var componentOverrideContext = require("./oauth2provider-shared2.js"); -var recipe = require("./oauth2provider-shared.js"); -require("./genericComponentOverrideContext.js"); -require("supertokens-web-js"); -require("supertokens-web-js/utils/cookieHandler"); -require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -require("supertokens-web-js/utils/windowHandler"); -require("supertokens-web-js/recipe/multitenancy"); -require("supertokens-web-js/utils"); -require("react"); -require("supertokens-web-js/lib/build/error"); -require("supertokens-web-js/utils/normalisedURLDomain"); -require("supertokens-web-js/utils/normalisedURLPath"); -require("react/jsx-runtime"); -require("supertokens-web-js/recipe/oauth2provider"); -require("./recipeModule-shared.js"); +var componentOverrideContext = require('./oauth2provider-shared2.js'); +var recipe = require('./oauth2provider-shared.js'); +require('./genericComponentOverrideContext.js'); +require('./utils.js'); +require('react'); +require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('supertokens-web-js/utils/normalisedURLPath'); +require('supertokens-web-js/utils/windowHandler'); +require('crypto'); +require('react/jsx-runtime'); +require('supertokens-web-js/recipe/oauth2provider'); +require('./recipeModule-shared.js'); +require('./superTokens.js'); +require('supertokens-web-js'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('supertokens-web-js/recipe/multitenancy'); +require('supertokens-web-js/utils'); -/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var Wrapper = /** @class */ (function () { - function Wrapper() {} - Wrapper.init = function (config) { - return recipe.OAuth2Provider.init(config); - }; - /** - * Returns information about an OAuth login in progress - * - * @param loginChallenge The login challenge from the url - * - * @param userContext (OPTIONAL) Refer to {@link https://supertokens.com/docs/emailpassword/advanced-customizations/user-context the documentation} - * - * @param options (OPTIONAL) Use this to configure additional properties (for example pre api hooks) - * - * @returns `{status: "OK", info: LoginInfo}` - * - * @throws STGeneralError if the API exposed by the backend SDKs returns `status: "GENERAL_ERROR"` - */ - Wrapper.getLoginChallengeInfo = function (input) { - return recipe.OAuth2Provider.getInstanceOrThrow().webJSRecipe.getLoginChallengeInfo(input); - }; - /** - * Accepts the OAuth2 Login request and returns the redirect URL to continue the OAuth flow. - * - * @param loginChallenge The login challenge from the url - * - * @param userContext (OPTIONAL) Refer to {@link https://supertokens.com/docs/emailpassword/advanced-customizations/user-context the documentation} - * - * @param options (OPTIONAL) Use this to configure additional properties (for example pre api hooks) - * - * @returns `{status: "OK", frontendRedirectTo: string}` - * - * @throws STGeneralError if the API exposed by the backend SDKs returns `status: "GENERAL_ERROR"` - */ - Wrapper.getRedirectURLToContinueOAuthFlow = function (input) { - return recipe.OAuth2Provider.getInstanceOrThrow().webJSRecipe.getRedirectURLToContinueOAuthFlow(input); - }; - /** - * Accepts the OAuth2 Logout request, clears the SuperTokens session and returns post logout redirect URL. - * - * @param logoutChallenge The logout challenge from the url - * - * @param userContext (OPTIONAL) Refer to {@link https://supertokens.com/docs/emailpassword/advanced-customizations/user-context the documentation} - * - * @param options (OPTIONAL) Use this to configure additional properties (for example pre api hooks) - * - * @returns `{status: "OK", frontendRedirectTo: string}` - * - * @throws STGeneralError if the API exposed by the backend SDKs returns `status: "GENERAL_ERROR"` - */ - Wrapper.logOut = function (input) { - return recipe.OAuth2Provider.getInstanceOrThrow().webJSRecipe.logOut(input); - }; - Wrapper.ComponentsOverrideProvider = componentOverrideContext.Provider; - return Wrapper; -})(); -var init = Wrapper.init; -var getLoginChallengeInfo = Wrapper.getLoginChallengeInfo; +/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var Wrapper = /** @class */ (function () { + function Wrapper() { + } + Wrapper.init = function (config) { + return recipe.OAuth2Provider.init(config); + }; + /** + * Returns information about an OAuth login in progress + * + * @param loginChallenge The login challenge from the url + * + * @param userContext (OPTIONAL) Refer to {@link https://supertokens.com/docs/emailpassword/advanced-customizations/user-context the documentation} + * + * @param options (OPTIONAL) Use this to configure additional properties (for example pre api hooks) + * + * @returns `{status: "OK", info: LoginInfo}` + * + * @throws STGeneralError if the API exposed by the backend SDKs returns `status: "GENERAL_ERROR"` + */ + Wrapper.getLoginChallengeInfo = function (input) { + return recipe.OAuth2Provider.getInstanceOrThrow().webJSRecipe.getLoginChallengeInfo(input); + }; + /** + * Accepts the OAuth2 Login request and returns the redirect URL to continue the OAuth flow. + * + * @param loginChallenge The login challenge from the url + * + * @param userContext (OPTIONAL) Refer to {@link https://supertokens.com/docs/emailpassword/advanced-customizations/user-context the documentation} + * + * @param options (OPTIONAL) Use this to configure additional properties (for example pre api hooks) + * + * @returns `{status: "OK", frontendRedirectTo: string}` + * + * @throws STGeneralError if the API exposed by the backend SDKs returns `status: "GENERAL_ERROR"` + */ + Wrapper.getRedirectURLToContinueOAuthFlow = function (input) { + return recipe.OAuth2Provider.getInstanceOrThrow().webJSRecipe.getRedirectURLToContinueOAuthFlow(input); + }; + /** + * Accepts the OAuth2 Logout request, clears the SuperTokens session and returns post logout redirect URL. + * + * @param logoutChallenge The logout challenge from the url + * + * @param userContext (OPTIONAL) Refer to {@link https://supertokens.com/docs/emailpassword/advanced-customizations/user-context the documentation} + * + * @param options (OPTIONAL) Use this to configure additional properties (for example pre api hooks) + * + * @returns `{status: "OK", frontendRedirectTo: string}` + * + * @throws STGeneralError if the API exposed by the backend SDKs returns `status: "GENERAL_ERROR"` + */ + Wrapper.logOut = function (input) { + return recipe.OAuth2Provider.getInstanceOrThrow().webJSRecipe.logOut(input); + }; + Wrapper.ComponentsOverrideProvider = componentOverrideContext.Provider; + return Wrapper; +}()); +var init = Wrapper.init; +var getLoginChallengeInfo = Wrapper.getLoginChallengeInfo; var logOut = Wrapper.logOut; exports.RecipeComponentsOverrideContextProvider = componentOverrideContext.Provider; diff --git a/lib/build/oauth2providerprebuiltui.js b/lib/build/oauth2providerprebuiltui.js index 93b384ce7..c9ad60840 100644 --- a/lib/build/oauth2providerprebuiltui.js +++ b/lib/build/oauth2providerprebuiltui.js @@ -1,59 +1,52 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var jsxRuntime = require("react/jsx-runtime"); -var NormalisedURLPath = require("supertokens-web-js/utils/normalisedURLPath"); -var uiEntry = require("./index2.js"); -var session = require("./session.js"); -var componentOverrideContext = require("./oauth2provider-shared2.js"); -var React = require("react"); -var recipe = require("./oauth2provider-shared.js"); -var translationContext = require("./translationContext.js"); -var button = require("./emailpassword-shared.js"); -require("supertokens-web-js"); -require("supertokens-web-js/utils/cookieHandler"); -require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -require("supertokens-web-js/utils/windowHandler"); -require("supertokens-web-js/recipe/multitenancy"); -require("supertokens-web-js/utils"); -require("supertokens-web-js/lib/build/error"); -require("supertokens-web-js/utils/normalisedURLDomain"); -require("react-dom"); -require("./multitenancy-shared.js"); -require("./multifactorauth-shared2.js"); -require("supertokens-web-js/recipe/multifactorauth"); -require("supertokens-web-js/utils/sessionClaimValidatorStore"); -require("./recipeModule-shared.js"); -require("./multifactorauth-shared.js"); -require("supertokens-web-js/recipe/session"); -require("./authRecipe-shared.js"); -require("supertokens-web-js/lib/build/normalisedURLPath"); -require("./session-shared.js"); -require("supertokens-web-js/recipe/oauth2provider"); +var utils = require('./utils.js'); +var jsxRuntime = require('react/jsx-runtime'); +var NormalisedURLPath = require('supertokens-web-js/utils/normalisedURLPath'); +var uiEntry = require('./index2.js'); +var session = require('./session.js'); +var componentOverrideContext = require('./oauth2provider-shared2.js'); +var React = require('react'); +var superTokens = require('./superTokens.js'); +var recipe = require('./oauth2provider-shared.js'); +var translationContext = require('./translationContext.js'); +var button = require('./emailpassword-shared.js'); +require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('supertokens-web-js/utils/windowHandler'); +require('crypto'); +require('react-dom'); +require('./multitenancy-shared.js'); +require('./genericComponentOverrideContext.js'); +require('./multifactorauth-shared2.js'); +require('supertokens-web-js/recipe/multifactorauth'); +require('supertokens-web-js/utils'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('supertokens-web-js/utils/sessionClaimValidatorStore'); +require('./recipeModule-shared.js'); +require('./multifactorauth-shared.js'); +require('supertokens-web-js/recipe/session'); +require('./authRecipe-shared.js'); +require('supertokens-web-js/lib/build/normalisedURLPath'); +require('./session-shared.js'); +require('supertokens-web-js'); +require('supertokens-web-js/recipe/multitenancy'); +require('supertokens-web-js/recipe/oauth2provider'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { - if (k !== "default") { + if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: function () { - return e[k]; - }, - } - ); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); } }); } @@ -61,567 +54,306 @@ function _interopNamespace(e) { return Object.freeze(n); } -var NormalisedURLPath__default = /*#__PURE__*/ _interopDefault(NormalisedURLPath); -var React__namespace = /*#__PURE__*/ _interopNamespace(React); +var NormalisedURLPath__default = /*#__PURE__*/_interopDefault(NormalisedURLPath); +var React__namespace = /*#__PURE__*/_interopNamespace(React); -var styles = - '/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved.\n *\n * This software is licensed under the Apache License, Version 2.0 (the\n * "License") as published by the Apache Software Foundation.\n *\n * You may not use this file except in compliance with the License. You may\n * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n[data-supertokens~="container"] {\n --palette-background: 255, 255, 255;\n --palette-inputBackground: 250, 250, 250;\n --palette-inputBorder: 224, 224, 224;\n --palette-primary: 28, 34, 42;\n --palette-primaryBorder: 45, 54, 68;\n --palette-success: 65, 167, 0;\n --palette-successBackground: 217, 255, 191;\n --palette-error: 255, 23, 23;\n --palette-errorBackground: 255, 241, 235;\n --palette-textTitle: 0, 0, 0;\n --palette-textLabel: 0, 0, 0;\n --palette-textInput: 0, 0, 0;\n --palette-textPrimary: 128, 128, 128;\n --palette-textLink: 0, 122, 255;\n --palette-buttonText: 255, 255, 255;\n --palette-textGray: 54, 54, 54;\n --palette-superTokensBrandingBackground: 242, 245, 246;\n --palette-superTokensBrandingText: 173, 189, 196;\n --palette-buttonGreyedOut: 221, 221, 221;\n --palette-caution: 124, 96, 62;\n --palette-errorDark: 207, 54, 68;\n\n --font-size-0: 12px;\n --font-size-1: 14px;\n --font-size-2: 16px;\n --font-size-3: 19px;\n --font-size-4: 24px;\n --font-size-5: 28px;\n}\n\n/*\n * Default styles.\n */\n\n@keyframes slideTop {\n 0% {\n transform: translateY(-5px);\n }\n 100% {\n transform: translateY(0px);\n }\n}\n\n@keyframes swing-in-top-fwd {\n 0% {\n transform: rotateX(-100deg);\n transform-origin: top;\n opacity: 0;\n }\n 100% {\n transform: rotateX(0deg);\n transform-origin: top;\n opacity: 1;\n }\n}\n\n[data-supertokens~="container"] {\n font-family: "Arial", sans-serif;\n margin: 12px auto;\n margin-top: 26px;\n margin-bottom: 26px;\n width: 420px;\n text-align: center;\n border-radius: 8px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.16);\n background-color: rgb(var(--palette-background));\n}\n\n@media (max-width: 440px) {\n [data-supertokens~="container"] {\n width: 95vw;\n }\n}\n\n[data-supertokens~="row"] {\n margin: 0 auto;\n width: 76%;\n padding-top: 30px;\n padding-bottom: 10px;\n}\n\n[data-supertokens~="superTokensBranding"] {\n display: block;\n margin: 10px auto 0;\n background: rgb(var(--palette-superTokensBrandingBackground));\n color: rgb(var(--palette-superTokensBrandingText));\n text-decoration: none;\n width: -webkit-fit-content;\n width: fit-content;\n border-radius: 6px 6px 0 0;\n padding: 4px 9px;\n font-weight: 400;\n font-size: var(--font-size-0);\n letter-spacing: 0.4px;\n}\n\n[data-supertokens~="generalError"] {\n background: rgb(var(--palette-errorBackground));\n padding-top: 10px;\n padding-bottom: 10px;\n margin-bottom: 10px;\n margin-top: 24px;\n padding-left: 18px;\n padding-right: 18px;\n letter-spacing: 0.2px;\n font-size: var(--font-size-1);\n border-radius: 8px;\n color: rgb(var(--palette-error));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n word-wrap: break-word;\n}\n\n[data-supertokens~="headerTitle"] {\n font-size: var(--font-size-4);\n line-height: 27.6px;\n letter-spacing: 0.58px;\n font-weight: 700;\n margin-bottom: 20px;\n color: rgb(var(--palette-textTitle));\n}\n\n[data-supertokens~="headerSubtitle"] {\n font-weight: 400;\n color: rgb(var(--palette-textGray));\n margin-bottom: 21px;\n}\n\n[data-supertokens~="headerSubtitle"][data-supertokens~="secondaryText"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n}\n\n[data-supertokens~="privacyPolicyAndTermsAndConditions"] {\n max-width: 300px;\n margin-top: 10px;\n}\n\n[data-supertokens~="privacyPolicyAndTermsAndConditions"] a {\n line-height: 21px;\n}\n\n/* TODO: split the link style into separate things*/\n\n/* We add this before primary and secondary text, because if they are applied to the same element the other ones take priority */\n\n[data-supertokens~="link"] {\n padding-left: 3px;\n padding-right: 3px;\n color: rgb(var(--palette-textLink));\n font-size: var(--font-size-1);\n cursor: pointer;\n letter-spacing: 0.16px;\n line-height: 26px;\n}\n\n[data-supertokens~="primaryText"] {\n font-size: var(--font-size-2);\n font-weight: 400;\n letter-spacing: 0.4px;\n line-height: 21px;\n color: rgb(var(--palette-textLabel));\n}\n\n[data-supertokens~="secondaryText"] {\n font-size: var(--font-size-1);\n font-weight: 400;\n letter-spacing: 0.4px;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~="secondaryText"] strong {\n font-weight: 600;\n}\n\n[data-supertokens~="divider"] {\n margin-top: 1.5em;\n margin-bottom: 1.5em;\n border-bottom: 0.3px solid #dddddd;\n align-items: center;\n padding-bottom: 5px;\n flex: 3 3;\n}\n\n[data-supertokens~="headerTinyTitle"] {\n margin-top: 24px;\n font-size: var(--font-size-5);\n letter-spacing: 1.1px;\n font-weight: 700;\n line-height: 28px;\n}\n\n[data-supertokens~="secondaryLinkWithArrow"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n}\n\n[data-supertokens~="secondaryLinkWithArrow"]:hover {\n position: relative;\n left: 2px;\n word-spacing: 4px;\n}\n\n[data-supertokens~="generalSuccess"] {\n color: rgb(var(--palette-success));\n font-size: var(--font-size-1);\n background: rgb(var(--palette-successBackground));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n padding: 9px 15px 9px 15px;\n border-radius: 6px;\n display: inline-block;\n}\n\n[data-supertokens~="spinner"] {\n width: 80px;\n height: auto;\n padding-top: 20px;\n padding-bottom: 40px;\n margin: 0 auto;\n}\n\n[data-supertokens~="error"] {\n color: rgb(var(--palette-error));\n}\n\n[data-supertokens~="linkButton"] {\n font-family: "Arial", sans-serif;\n background-color: transparent;\n border: 0;\n}\n\n[data-supertokens~="secondaryLinkWithLeftArrow"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n margin-top: 10px;\n margin-bottom: 40px;\n cursor: pointer;\n}\n\n[data-supertokens~="secondaryLinkWithLeftArrow"] svg {\n margin-right: 0.3em;\n}\n\n[data-supertokens~="secondaryLinkWithLeftArrow"]:hover svg {\n position: relative;\n left: -4px;\n}\n\n[data-supertokens~="button"] {\n font-family: "Arial", sans-serif;\n background-color: rgb(var(--palette-primary));\n color: rgb(var(--palette-buttonText));\n width: 100%;\n height: 34px;\n font-weight: 600;\n border-width: 1px;\n border-style: solid;\n border-radius: 6px;\n border-color: rgb(var(--palette-primaryBorder));\n background-position: center;\n transition: all 0.4s;\n background-size: 12000%;\n cursor: pointer;\n}\n\n[data-supertokens~="buttonGreyedOut"] {\n background-color: rgb(var(--palette-buttonGreyedOut));\n border-color: rgb(var(--palette-buttonGreyedOut));\n}\n\n[data-supertokens~="buttonWithIcon"] {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n}\n\n[data-supertokens~="button"]:disabled {\n border: none;\n cursor: no-drop;\n}\n\n[data-supertokens~="button"]:active {\n outline: none;\n transition: all 0s;\n background-size: 100%;\n filter: brightness(0.85);\n}\n\n[data-supertokens~="button"]:focus {\n outline: none;\n}\n\n[data-supertokens~="backButtonCommon"] {\n width: 16px;\n height: 13px;\n}\n\n[data-supertokens~="backButton"] {\n cursor: pointer;\n border: none;\n background-color: transparent;\n padding: 0px;\n}\n\n[data-supertokens~="backButtonPlaceholder"] {\n display: block;\n}\n\n[data-supertokens~="delayedRender"] {\n animation-duration: 0.1s;\n animation-name: animate-fade;\n animation-delay: 0.2s;\n animation-fill-mode: backwards;\n}\n\n@keyframes animate-fade {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n\n[data-supertokens~="footerLinkGroupVert"] {\n display: flex;\n flex-direction: column;\n margin-top: 10px;\n gap: 24px;\n}\n\n[data-supertokens~="footerLinkGroupVert"] > div {\n cursor: pointer;\n margin: 0;\n}\n\n[data-supertokens~="footerLinkGroupVert"] [data-supertokens~="secondaryText"] {\n font-weight: 400;\n}\n\n[data-supertokens~="footerLinkGroupVert"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n font-weight: 400;\n position: relative;\n left: -6px; /* half the width of the left arrow */\n}\n\n@media (max-width: 360px) {\n [data-supertokens~="footerLinkGroupVert"] {\n flex-direction: column;\n }\n [data-supertokens~="footerLinkGroupVert"] > div {\n margin: 0 auto;\n }\n}\n\n[data-supertokens~="footerLinkGroupVert"] div:only-child {\n margin-left: auto;\n margin-right: auto;\n margin-top: 14px;\n}\n\n[data-supertokens~="withBackButton"] {\n position: relative;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n[data-supertokens~="dividerWithOr"] {\n padding-top: 5px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~="dividerText"] {\n flex: 1 1;\n font-weight: 400;\n font-size: var(--font-size-1);\n}\n\n[data-supertokens~="formLabelWithLinkWrapper"] {\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n[data-supertokens~="formLabelLinkBtn"] {\n width: auto;\n margin-top: 0;\n line-height: 24px;\n font-size: var(--font-size-0);\n}\n\n[data-supertokens~="formLabelLinkBtn"]:hover {\n text-decoration: underline;\n}\n\n[data-supertokens~="formLabelLinkBtn"]:disabled {\n color: rgb(var(--palette-textPrimary));\n cursor: default;\n text-decoration: none;\n}\n\n[data-supertokens~="authComponentList"] {\n padding-bottom: 20px;\n}\n\n[data-supertokens~="authPageTitleOAuthClient"] {\n color: rgb(var(--palette-textGray));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 10px 0 25px;\n}\n\n[data-supertokens~="authPageTitleOAuthClientUrl"] {\n text-decoration: none;\n}\n\n[data-supertokens~="authPageTitleOAuthClientLogo"] {\n width: 44px;\n height: 44px;\n margin-bottom: 10px;\n}\n\n[data-supertokens~="authPageTitleOAuthClient"] [data-supertokens~="authPageTitleOAuthClientName"] {\n color: rgb(var(--palette-textTitle));\n}\n\n[data-supertokens~="buttonWithArrow"] {\n border-radius: 6px;\n border: 1px solid #d0d5dd;\n width: 100%;\n color: rgb(var(--palette-textGray));\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n margin: 24px 0;\n min-height: 48px;\n cursor: pointer;\n}\n\n[data-supertokens~="buttonWithArrow"]:hover {\n background-color: rgb(var(--palette-inputBackground));\n}\n\n[data-supertokens~="buttonWithArrow"] [data-supertokens~="secondaryText"] {\n font-weight: 700;\n font-size: var(--font-size-2);\n color: rgb(var(--palette-textGray));\n margin: 0;\n}\n\n[data-supertokens~="buttonWithArrow"]:hover [data-supertokens~="secondaryLinkWithRightArrow"] ~ svg {\n position: relative;\n left: 2px;\n}\n\n[data-supertokens~="buttonWithArrow"]:hover [data-supertokens~="secondaryLinkWithLeftArrow"] svg {\n position: relative;\n left: -2px;\n}\n\n[data-supertokens~="buttonWithArrow"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n display: flex;\n align-items: center;\n}\n\n[data-supertokens~="logoutIcon"] {\n padding: 18px 20px 18px 24px;\n background-color: rgba(var(--palette-textGray), 0.1);\n border-radius: 12px;\n}\n\n[data-supertokens~="oauth2Logout"] [data-supertokens~="headerTitle"] {\n margin-top: 24px;\n margin-bottom: 24px;\n}\n\n[data-supertokens~="oauth2Logout"] [data-supertokens~="button"] {\n margin-bottom: 24px;\n}\n'; +var styles = "/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved.\n *\n * This software is licensed under the Apache License, Version 2.0 (the\n * \"License\") as published by the Apache Software Foundation.\n *\n * You may not use this file except in compliance with the License. You may\n * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n[data-supertokens~=\"container\"] {\n --palette-background: 255, 255, 255;\n --palette-inputBackground: 250, 250, 250;\n --palette-inputBorder: 224, 224, 224;\n --palette-primary: 28, 34, 42;\n --palette-primaryBorder: 45, 54, 68;\n --palette-success: 65, 167, 0;\n --palette-successBackground: 217, 255, 191;\n --palette-error: 255, 23, 23;\n --palette-errorBackground: 255, 241, 235;\n --palette-textTitle: 0, 0, 0;\n --palette-textLabel: 0, 0, 0;\n --palette-textInput: 0, 0, 0;\n --palette-textPrimary: 128, 128, 128;\n --palette-textLink: 0, 122, 255;\n --palette-buttonText: 255, 255, 255;\n --palette-textGray: 54, 54, 54;\n --palette-superTokensBrandingBackground: 242, 245, 246;\n --palette-superTokensBrandingText: 173, 189, 196;\n --palette-buttonGreyedOut: 221, 221, 221;\n --palette-caution: 124, 96, 62;\n --palette-errorDark: 207, 54, 68;\n\n --font-size-0: 12px;\n --font-size-1: 14px;\n --font-size-2: 16px;\n --font-size-3: 19px;\n --font-size-4: 24px;\n --font-size-5: 28px;\n}\n\n/*\n * Default styles.\n */\n\n@keyframes slideTop {\n 0% {\n transform: translateY(-5px);\n }\n 100% {\n transform: translateY(0px);\n }\n}\n\n@keyframes swing-in-top-fwd {\n 0% {\n transform: rotateX(-100deg);\n transform-origin: top;\n opacity: 0;\n }\n 100% {\n transform: rotateX(0deg);\n transform-origin: top;\n opacity: 1;\n }\n}\n\n[data-supertokens~=\"container\"] {\n font-family: \"Arial\", sans-serif;\n margin: 12px auto;\n margin-top: 26px;\n margin-bottom: 26px;\n width: 420px;\n text-align: center;\n border-radius: 8px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.16);\n background-color: rgb(var(--palette-background));\n}\n\n@media (max-width: 440px) {\n [data-supertokens~=\"container\"] {\n width: 95vw;\n }\n}\n\n[data-supertokens~=\"row\"] {\n margin: 0 auto;\n width: 76%;\n padding-top: 30px;\n padding-bottom: 10px;\n}\n\n[data-supertokens~=\"superTokensBranding\"] {\n display: block;\n margin: 10px auto 0;\n background: rgb(var(--palette-superTokensBrandingBackground));\n color: rgb(var(--palette-superTokensBrandingText));\n text-decoration: none;\n width: -webkit-fit-content;\n width: -moz-fit-content;\n width: fit-content;\n border-radius: 6px 6px 0 0;\n padding: 4px 9px;\n font-weight: 400;\n font-size: var(--font-size-0);\n letter-spacing: 0.4px;\n}\n\n[data-supertokens~=\"generalError\"] {\n background: rgb(var(--palette-errorBackground));\n padding-top: 10px;\n padding-bottom: 10px;\n margin-bottom: 10px;\n margin-top: 24px;\n padding-left: 18px;\n padding-right: 18px;\n letter-spacing: 0.2px;\n font-size: var(--font-size-1);\n border-radius: 8px;\n color: rgb(var(--palette-error));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n word-wrap: break-word;\n}\n\n[data-supertokens~=\"headerTitle\"] {\n font-size: var(--font-size-4);\n line-height: 27.6px;\n letter-spacing: 0.58px;\n font-weight: 700;\n margin-bottom: 20px;\n color: rgb(var(--palette-textTitle));\n}\n\n[data-supertokens~=\"headerSubtitle\"] {\n font-weight: 400;\n color: rgb(var(--palette-textGray));\n margin-bottom: 21px;\n}\n\n[data-supertokens~=\"headerSubtitle\"][data-supertokens~=\"secondaryText\"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n}\n\n[data-supertokens~=\"privacyPolicyAndTermsAndConditions\"] {\n max-width: 300px;\n margin-top: 10px;\n}\n\n[data-supertokens~=\"privacyPolicyAndTermsAndConditions\"] a {\n line-height: 21px;\n}\n\n/* TODO: split the link style into separate things*/\n\n/* We add this before primary and secondary text, because if they are applied to the same element the other ones take priority */\n\n[data-supertokens~=\"link\"] {\n padding-left: 3px;\n padding-right: 3px;\n color: rgb(var(--palette-textLink));\n font-size: var(--font-size-1);\n cursor: pointer;\n letter-spacing: 0.16px;\n line-height: 26px;\n}\n\n[data-supertokens~=\"primaryText\"] {\n font-size: var(--font-size-2);\n font-weight: 400;\n letter-spacing: 0.4px;\n line-height: 21px;\n color: rgb(var(--palette-textLabel));\n}\n\n[data-supertokens~=\"secondaryText\"] {\n font-size: var(--font-size-1);\n font-weight: 400;\n letter-spacing: 0.4px;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~=\"secondaryText\"] strong {\n font-weight: 600;\n}\n\n[data-supertokens~=\"divider\"] {\n margin-top: 1.5em;\n margin-bottom: 1.5em;\n border-bottom: 0.3px solid #dddddd;\n align-items: center;\n padding-bottom: 5px;\n flex: 3 3;\n}\n\n[data-supertokens~=\"headerTinyTitle\"] {\n margin-top: 24px;\n font-size: var(--font-size-5);\n letter-spacing: 1.1px;\n font-weight: 700;\n line-height: 28px;\n}\n\n[data-supertokens~=\"secondaryLinkWithArrow\"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n}\n\n[data-supertokens~=\"secondaryLinkWithArrow\"]:hover {\n position: relative;\n left: 2px;\n word-spacing: 4px;\n}\n\n[data-supertokens~=\"generalSuccess\"] {\n color: rgb(var(--palette-success));\n font-size: var(--font-size-1);\n background: rgb(var(--palette-successBackground));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n padding: 9px 15px 9px 15px;\n border-radius: 6px;\n display: inline-block;\n}\n\n[data-supertokens~=\"spinner\"] {\n width: 80px;\n height: auto;\n padding-top: 20px;\n padding-bottom: 40px;\n margin: 0 auto;\n}\n\n[data-supertokens~=\"error\"] {\n color: rgb(var(--palette-error));\n}\n\n[data-supertokens~=\"linkButton\"] {\n font-family: \"Arial\", sans-serif;\n background-color: transparent;\n border: 0;\n}\n\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n margin-top: 10px;\n margin-bottom: 40px;\n cursor: pointer;\n}\n\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"] svg {\n margin-right: 0.3em;\n}\n\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"]:hover svg {\n position: relative;\n left: -4px;\n}\n\n[data-supertokens~=\"button\"] {\n font-family: \"Arial\", sans-serif;\n background-color: rgb(var(--palette-primary));\n color: rgb(var(--palette-buttonText));\n width: 100%;\n height: 34px;\n font-weight: 600;\n border-width: 1px;\n border-style: solid;\n border-radius: 6px;\n border-color: rgb(var(--palette-primaryBorder));\n background-position: center;\n transition: all 0.4s;\n background-size: 12000%;\n cursor: pointer;\n}\n\n[data-supertokens~=\"buttonGreyedOut\"] {\n background-color: rgb(var(--palette-buttonGreyedOut));\n border-color: rgb(var(--palette-buttonGreyedOut));\n}\n\n[data-supertokens~=\"buttonWithIcon\"] {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n}\n\n[data-supertokens~=\"button\"]:disabled {\n border: none;\n cursor: no-drop;\n}\n\n[data-supertokens~=\"button\"]:active {\n outline: none;\n transition: all 0s;\n background-size: 100%;\n filter: brightness(0.85);\n}\n\n[data-supertokens~=\"button\"]:focus {\n outline: none;\n}\n\n[data-supertokens~=\"backButtonCommon\"] {\n width: 16px;\n height: 13px;\n}\n\n[data-supertokens~=\"backButton\"] {\n cursor: pointer;\n border: none;\n background-color: transparent;\n padding: 0px;\n}\n\n[data-supertokens~=\"backButtonPlaceholder\"] {\n display: block;\n}\n\n[data-supertokens~=\"delayedRender\"] {\n animation-duration: 0.1s;\n animation-name: animate-fade;\n animation-delay: 0.2s;\n animation-fill-mode: backwards;\n}\n\n@keyframes animate-fade {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] {\n display: flex;\n flex-direction: column;\n margin-top: 10px;\n gap: 24px;\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] > div {\n cursor: pointer;\n margin: 0;\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] [data-supertokens~=\"secondaryText\"] {\n font-weight: 400;\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n font-weight: 400;\n position: relative;\n left: -6px; /* half the width of the left arrow */\n}\n\n@media (max-width: 360px) {\n [data-supertokens~=\"footerLinkGroupVert\"] {\n flex-direction: column;\n }\n [data-supertokens~=\"footerLinkGroupVert\"] > div {\n margin: 0 auto;\n }\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] div:only-child {\n margin-left: auto;\n margin-right: auto;\n margin-top: 14px;\n}\n\n[data-supertokens~=\"withBackButton\"] {\n position: relative;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n[data-supertokens~=\"dividerWithOr\"] {\n padding-top: 5px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~=\"dividerText\"] {\n flex: 1 1;\n font-weight: 400;\n font-size: var(--font-size-1);\n}\n\n[data-supertokens~=\"formLabelWithLinkWrapper\"] {\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n[data-supertokens~=\"formLabelLinkBtn\"] {\n width: auto;\n margin-top: 0;\n line-height: 24px;\n font-size: var(--font-size-0);\n}\n\n[data-supertokens~=\"formLabelLinkBtn\"]:hover {\n text-decoration: underline;\n}\n\n[data-supertokens~=\"formLabelLinkBtn\"]:disabled {\n color: rgb(var(--palette-textPrimary));\n cursor: default;\n text-decoration: none;\n}\n\n[data-supertokens~=\"authComponentList\"] {\n padding-bottom: 20px;\n}\n\n[data-supertokens~=\"authPageTitleOAuthClient\"] {\n color: rgb(var(--palette-textGray));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 10px 0 25px;\n}\n\n[data-supertokens~=\"authPageTitleOAuthClientUrl\"] {\n text-decoration: none;\n}\n\n[data-supertokens~=\"authPageTitleOAuthClientLogo\"] {\n width: 44px;\n height: 44px;\n margin-bottom: 10px;\n}\n\n[data-supertokens~=\"authPageTitleOAuthClient\"] [data-supertokens~=\"authPageTitleOAuthClientName\"] {\n color: rgb(var(--palette-textTitle));\n}\n\n[data-supertokens~=\"buttonWithArrow\"] {\n border-radius: 6px;\n border: 1px solid #d0d5dd;\n width: 100%;\n color: rgb(var(--palette-textGray));\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n margin: 24px 0;\n min-height: 48px;\n cursor: pointer;\n}\n\n[data-supertokens~=\"buttonWithArrow\"]:hover {\n background-color: rgb(var(--palette-inputBackground));\n}\n\n[data-supertokens~=\"buttonWithArrow\"] [data-supertokens~=\"secondaryText\"] {\n font-weight: 700;\n font-size: var(--font-size-2);\n color: rgb(var(--palette-textGray));\n margin: 0;\n}\n\n[data-supertokens~=\"buttonWithArrow\"]:hover [data-supertokens~=\"secondaryLinkWithRightArrow\"] ~ svg {\n position: relative;\n left: 2px;\n}\n\n[data-supertokens~=\"buttonWithArrow\"]:hover [data-supertokens~=\"secondaryLinkWithLeftArrow\"] svg {\n position: relative;\n left: -2px;\n}\n\n[data-supertokens~=\"buttonWithArrow\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n display: flex;\n align-items: center;\n}\n\n[data-supertokens~=\"logoutIcon\"] {\n padding: 18px 20px 18px 24px;\n background-color: rgba(var(--palette-textGray), 0.1);\n border-radius: 12px;\n}\n\n[data-supertokens~=\"oauth2Logout\"] [data-supertokens~=\"headerTitle\"] {\n margin-top: 24px;\n margin-bottom: 24px;\n}\n\n[data-supertokens~=\"oauth2Logout\"] [data-supertokens~=\"button\"] {\n margin-bottom: 24px;\n}\n"; -var ThemeBase = function (_a) { - var children = _a.children, - userStyles = _a.userStyles; - return jsxRuntime.jsxs(React.Fragment, { - children: [children, jsxRuntime.jsxs("style", { children: [styles, userStyles.join("\n")] })], - }); +var ThemeBase = function (_a) { + var children = _a.children, userStyles = _a.userStyles; + return (jsxRuntime.jsxs(React.Fragment, { children: [children, jsxRuntime.jsxs("style", { children: [styles, userStyles.join("\n")] })] })); }; -/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -function LogoutIcon() { - return jsxRuntime.jsx( - "svg", - genericComponentOverrideContext.__assign( - { - "data-supertokens": "logoutIcon", - xmlns: "http://www.w3.org/2000/svg", - width: "40", - height: "38", - fill: "none", - }, - { - children: jsxRuntime.jsx("path", { - fill: "rgb(var(--palette-textGray))", - fillRule: "evenodd", - d: "M2.972.022a.874.874 0 0 1-.23.062c-.234.042-.926.362-1.148.53a4.638 4.638 0 0 0-.656.63c-.178.228-.415.681-.495.948l-.116.378C.272 2.742.27 32.075.326 32.251l.111.37c.165.559.636 1.207 1.133 1.558a3.9 3.9 0 0 1 .195.145c.048.046.368.206.588.292l.196.08c.036.016.183.063.326.105.144.042.295.093.337.113.041.02.11.037.154.037s.098.015.12.034c.023.019.218.087.434.15.215.065.43.133.478.153.048.019.254.085.457.146.204.06.404.128.446.148.041.021.11.038.154.038s.098.015.12.034c.023.02.16.069.303.11.144.041.295.092.337.112.041.02.11.037.154.037s.098.015.12.034c.023.018.218.086.434.15.215.065.43.133.478.152.048.02.254.086.457.148.204.062.404.129.446.148a.45.45 0 0 0 .163.037c.048 0 .088.018.088.041 0 .023.034.043.076.043.042 0 .213.048.38.104.168.057.34.104.381.104.042 0 .076.02.076.042 0 .023.04.042.088.042.048 0 .122.017.163.038.042.02.193.07.337.11.274.076.366.106.544.176.06.024.285.096.5.16.216.064.41.132.433.15a.224.224 0 0 0 .12.035.4.4 0 0 1 .155.04c.042.02.193.07.337.108.144.038.3.084.348.103.178.07.613.125.954.122.365-.004.908-.078.965-.133a.16.16 0 0 1 .096-.031c.08 0 .707-.291.784-.364.032-.03.073-.054.09-.054.053 0 .632-.55.748-.71.195-.27.432-.71.432-.803 0-.04.02-.083.044-.097.024-.014.043-.077.043-.14 0-.063.023-.137.05-.163.034-.033.059-.404.077-1.148l.026-1.1 2.894-.023c2.31-.02 2.939-.037 3.119-.084.123-.033.24-.074.257-.091.018-.017.077-.031.132-.031.054 0 .11-.02.125-.042.015-.023.055-.042.089-.042.19 0 1.14-.54 1.493-.849.456-.398.898-.926 1.095-1.304a.916.916 0 0 1 .088-.147c.02-.018.06-.104.219-.48.02-.047.059-.16.088-.252.029-.091.069-.214.09-.271.125-.356.146-.97.146-4.265 0-3.563-.003-3.626-.205-3.987-.204-.364-.756-.78-1.036-.78-.045 0-.093-.019-.108-.042-.035-.054-.661-.054-.696 0-.015.023-.066.042-.113.042-.256 0-.85.449-1.002.757-.253.514-.256.568-.256 4.24v3.287l-.11.222c-.06.123-.186.306-.28.408-.171.188-.551.41-.7.41-.044 0-.092.02-.107.042-.018.027-.943.042-2.635.042h-2.608l-.011-12.165c-.01-9.665-.023-12.176-.066-12.218a.236.236 0 0 1-.055-.149.426.426 0 0 0-.039-.169 4.357 4.357 0 0 1-.118-.26c-.201-.477-.692-1.057-1.127-1.332a2.216 2.216 0 0 1-.196-.134c-.054-.058-.664-.307-.848-.346-.048-.01 1.66-.021 3.795-.024 2.546-.003 3.89.01 3.908.037.015.023.064.042.11.042.19 0 .646.313.82.561.274.39.267.31.267 3.032 0 2.402.02 2.851.14 3.139.245.59.71.966 1.318 1.068.33.055.642.012.979-.134.242-.105.696-.489.696-.588 0-.03.015-.054.033-.054.042 0 .166-.305.213-.522.058-.272.046-5.251-.015-5.666a4.778 4.778 0 0 0-.27-1.066 9.014 9.014 0 0 0-.397-.773 2.902 2.902 0 0 1-.161-.23 3.223 3.223 0 0 0-.298-.377 7.831 7.831 0 0 1-.23-.25c-.149-.175-.564-.502-.91-.717a5.197 5.197 0 0 0-.38-.224c-.011 0-.133-.05-.271-.11a4.346 4.346 0 0 0-.98-.319C22.442.018 3.025-.029 2.973.022Zm28.17 7.903c-.364.092-.514.172-.764.407-.225.21-.38.445-.487.737-.04.11-.054.77-.055 2.645v2.498h-3.457c-2.258 0-3.467.015-3.485.042-.014.023-.063.042-.107.042-.138 0-.449.18-.655.379-.194.187-.38.497-.474.794-.06.187-.062.653-.004.687.024.015.044.06.044.102 0 .17.198.495.443.724.141.132.285.24.32.24.035 0 .063.02.063.042 0 .023.036.042.08.042.044 0 .094.014.111.03.125.12.504.134 3.78.136l3.34.001.014 2.52c.015 2.39.032 2.79.122 2.79.021 0 .039.038.039.084 0 .046.02.084.043.084.024 0 .044.026.044.058 0 .073.476.527.552.527.032 0 .057.016.057.036 0 .02.108.069.24.109.35.106 1.009.076 1.305-.059.175-.08.895-.75 3.656-3.406 1.89-1.82 3.487-3.373 3.548-3.454.278-.37.388-.944.256-1.342-.15-.456-.165-.47-3.737-3.915-1.915-1.846-3.511-3.356-3.547-3.356-.037 0-.067-.014-.067-.031 0-.074-.636-.261-.87-.256-.06.001-.217.03-.349.063Z", - clipRule: "evenodd", - }), - } - ) - ); +/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +function LogoutIcon() { + return (jsxRuntime.jsx("svg", utils.__assign({ "data-supertokens": "logoutIcon", xmlns: "http://www.w3.org/2000/svg", width: "40", height: "38", fill: "none" }, { children: jsxRuntime.jsx("path", { fill: "rgb(var(--palette-textGray))", fillRule: "evenodd", d: "M2.972.022a.874.874 0 0 1-.23.062c-.234.042-.926.362-1.148.53a4.638 4.638 0 0 0-.656.63c-.178.228-.415.681-.495.948l-.116.378C.272 2.742.27 32.075.326 32.251l.111.37c.165.559.636 1.207 1.133 1.558a3.9 3.9 0 0 1 .195.145c.048.046.368.206.588.292l.196.08c.036.016.183.063.326.105.144.042.295.093.337.113.041.02.11.037.154.037s.098.015.12.034c.023.019.218.087.434.15.215.065.43.133.478.153.048.019.254.085.457.146.204.06.404.128.446.148.041.021.11.038.154.038s.098.015.12.034c.023.02.16.069.303.11.144.041.295.092.337.112.041.02.11.037.154.037s.098.015.12.034c.023.018.218.086.434.15.215.065.43.133.478.152.048.02.254.086.457.148.204.062.404.129.446.148a.45.45 0 0 0 .163.037c.048 0 .088.018.088.041 0 .023.034.043.076.043.042 0 .213.048.38.104.168.057.34.104.381.104.042 0 .076.02.076.042 0 .023.04.042.088.042.048 0 .122.017.163.038.042.02.193.07.337.11.274.076.366.106.544.176.06.024.285.096.5.16.216.064.41.132.433.15a.224.224 0 0 0 .12.035.4.4 0 0 1 .155.04c.042.02.193.07.337.108.144.038.3.084.348.103.178.07.613.125.954.122.365-.004.908-.078.965-.133a.16.16 0 0 1 .096-.031c.08 0 .707-.291.784-.364.032-.03.073-.054.09-.054.053 0 .632-.55.748-.71.195-.27.432-.71.432-.803 0-.04.02-.083.044-.097.024-.014.043-.077.043-.14 0-.063.023-.137.05-.163.034-.033.059-.404.077-1.148l.026-1.1 2.894-.023c2.31-.02 2.939-.037 3.119-.084.123-.033.24-.074.257-.091.018-.017.077-.031.132-.031.054 0 .11-.02.125-.042.015-.023.055-.042.089-.042.19 0 1.14-.54 1.493-.849.456-.398.898-.926 1.095-1.304a.916.916 0 0 1 .088-.147c.02-.018.06-.104.219-.48.02-.047.059-.16.088-.252.029-.091.069-.214.09-.271.125-.356.146-.97.146-4.265 0-3.563-.003-3.626-.205-3.987-.204-.364-.756-.78-1.036-.78-.045 0-.093-.019-.108-.042-.035-.054-.661-.054-.696 0-.015.023-.066.042-.113.042-.256 0-.85.449-1.002.757-.253.514-.256.568-.256 4.24v3.287l-.11.222c-.06.123-.186.306-.28.408-.171.188-.551.41-.7.41-.044 0-.092.02-.107.042-.018.027-.943.042-2.635.042h-2.608l-.011-12.165c-.01-9.665-.023-12.176-.066-12.218a.236.236 0 0 1-.055-.149.426.426 0 0 0-.039-.169 4.357 4.357 0 0 1-.118-.26c-.201-.477-.692-1.057-1.127-1.332a2.216 2.216 0 0 1-.196-.134c-.054-.058-.664-.307-.848-.346-.048-.01 1.66-.021 3.795-.024 2.546-.003 3.89.01 3.908.037.015.023.064.042.11.042.19 0 .646.313.82.561.274.39.267.31.267 3.032 0 2.402.02 2.851.14 3.139.245.59.71.966 1.318 1.068.33.055.642.012.979-.134.242-.105.696-.489.696-.588 0-.03.015-.054.033-.054.042 0 .166-.305.213-.522.058-.272.046-5.251-.015-5.666a4.778 4.778 0 0 0-.27-1.066 9.014 9.014 0 0 0-.397-.773 2.902 2.902 0 0 1-.161-.23 3.223 3.223 0 0 0-.298-.377 7.831 7.831 0 0 1-.23-.25c-.149-.175-.564-.502-.91-.717a5.197 5.197 0 0 0-.38-.224c-.011 0-.133-.05-.271-.11a4.346 4.346 0 0 0-.98-.319C22.442.018 3.025-.029 2.973.022Zm28.17 7.903c-.364.092-.514.172-.764.407-.225.21-.38.445-.487.737-.04.11-.054.77-.055 2.645v2.498h-3.457c-2.258 0-3.467.015-3.485.042-.014.023-.063.042-.107.042-.138 0-.449.18-.655.379-.194.187-.38.497-.474.794-.06.187-.062.653-.004.687.024.015.044.06.044.102 0 .17.198.495.443.724.141.132.285.24.32.24.035 0 .063.02.063.042 0 .023.036.042.08.042.044 0 .094.014.111.03.125.12.504.134 3.78.136l3.34.001.014 2.52c.015 2.39.032 2.79.122 2.79.021 0 .039.038.039.084 0 .046.02.084.043.084.024 0 .044.026.044.058 0 .073.476.527.552.527.032 0 .057.016.057.036 0 .02.108.069.24.109.35.106 1.009.076 1.305-.059.175-.08.895-.75 3.656-3.406 1.89-1.82 3.487-3.373 3.548-3.454.278-.37.388-.944.256-1.342-.15-.456-.165-.47-3.737-3.915-1.915-1.846-3.511-3.356-3.547-3.356-.037 0-.067-.014-.067-.031 0-.074-.636-.261-.87-.256-.06.001-.217.03-.349.063Z", clipRule: "evenodd" }) }))); } -var OAuth2LogoutScreenInner = uiEntry.withOverride("OAuth2LogoutScreenInner", function OAuth2LogoutScreenInner(props) { - var t = translationContext.useTranslation(); - return jsxRuntime.jsxs(jsxRuntime.Fragment, { - children: [ - jsxRuntime.jsx(LogoutIcon, {}), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle" }, - { children: t("LOGGING_OUT") } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerSubtitle" }, - { children: t("LOGOUT_CONFIRMATION") } - ) - ), - jsxRuntime.jsx("div", { "data-supertokens": "divider" }), - jsxRuntime.jsx(button.Button, { - disabled: props.isLoggingOut, - isLoading: props.isLoggingOut, - type: "button", - label: t("LOGOUT"), - onClick: props.onLogoutClicked, - }), - ], - }); +var OAuth2LogoutScreenInner = uiEntry.withOverride("OAuth2LogoutScreenInner", function OAuth2LogoutScreenInner(props) { + var t = translationContext.useTranslation(); + return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx(LogoutIcon, {}), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerTitle" }, { children: t("LOGGING_OUT") })), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerSubtitle" }, { children: t("LOGOUT_CONFIRMATION") })), jsxRuntime.jsx("div", { "data-supertokens": "divider" }), jsxRuntime.jsx(button.Button, { disabled: props.isLoggingOut, isLoading: props.isLoggingOut, type: "button", label: t("LOGOUT"), onClick: props.onLogoutClicked })] })); }); -var OAuth2LogoutScreen$1 = function (props) { - if (props.showSpinner) { - return jsxRuntime.jsx(uiEntry.DynamicLoginMethodsSpinner, {}); - } - return jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "oauth2Logout container" }, - { - children: [ - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row" }, - { - children: jsxRuntime.jsx(OAuth2LogoutScreenInner, { - isLoggingOut: props.isLoggingOut, - onLogoutClicked: props.onLogoutClicked, - }), - } - ) - ), - jsxRuntime.jsx(uiEntry.SuperTokensBranding, {}), - ], - } - ) - ); -}; -var OAuth2LogoutScreenTheme = function (props) { - var rootStyle = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().rootStyle; - return jsxRuntime.jsx( - ThemeBase, - genericComponentOverrideContext.__assign( - { userStyles: [rootStyle, props.config.recipeRootStyle, props.config.oauth2LogoutScreen.style] }, - { children: jsxRuntime.jsx(OAuth2LogoutScreen$1, genericComponentOverrideContext.__assign({}, props)) } - ) - ); +var OAuth2LogoutScreen$1 = function (props) { + if (props.showSpinner) { + return jsxRuntime.jsx(uiEntry.DynamicLoginMethodsSpinner, {}); + } + return (jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "oauth2Logout container" }, { children: [jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "row" }, { children: jsxRuntime.jsx(OAuth2LogoutScreenInner, { isLoggingOut: props.isLoggingOut, onLogoutClicked: props.onLogoutClicked }) })), jsxRuntime.jsx(uiEntry.SuperTokensBranding, {})] }))); +}; +var OAuth2LogoutScreenTheme = function (props) { + var rootStyle = superTokens.SuperTokens.getInstanceOrThrow().rootStyle; + return (jsxRuntime.jsx(ThemeBase, utils.__assign({ userStyles: [rootStyle, props.config.recipeRootStyle, props.config.oauth2LogoutScreen.style] }, { children: jsxRuntime.jsx(OAuth2LogoutScreen$1, utils.__assign({}, props)) }))); }; -var defaultTranslationsOAuth2Provider = { - en: genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, uiEntry.defaultTranslationsCommon.en), - { LOGGING_OUT: "Logging Out", LOGOUT_CONFIRMATION: "Are you sure you want to log out?", LOGOUT: "LOG OUT" } - ), +var defaultTranslationsOAuth2Provider = { + en: utils.__assign(utils.__assign({}, uiEntry.defaultTranslationsCommon.en), { LOGGING_OUT: "Logging Out", LOGOUT_CONFIRMATION: "Are you sure you want to log out?", LOGOUT: "LOG OUT" }), }; -var OAuth2LogoutScreen = function (props) { - var _a, _b, _c; - var rethrowInRender = genericComponentOverrideContext.useRethrowInRender(); - var sessionContext = React__namespace.useContext(uiEntry.SessionContext); - var _d = React__namespace.useState(false), - isLoggingOut = _d[0], - setIsLoggingOut = _d[1]; - var recipeComponentOverrides = props.useComponentOverrides(); - var userContext = uiEntry.useUserContext(); - if (props.userContext !== undefined) { - userContext = props.userContext; - } - var logoutChallenge = - (_a = genericComponentOverrideContext.getQueryParams("logoutChallenge")) !== null && _a !== void 0 - ? _a - : undefined; - var navigate = - (_b = props.navigate) !== null && _b !== void 0 - ? _b - : (_c = uiEntry.UI.getReactRouterDomWithCustomHistory()) === null || _c === void 0 - ? void 0 - : _c.useHistoryCustom(); - var onLogout = React__namespace.useCallback( - function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var frontendRedirectTo, err_1; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (logoutChallenge === undefined) { - return [2 /*return*/]; - } - setIsLoggingOut(true); - _a.label = 1; - case 1: - _a.trys.push([1, 4, , 6]); - return [ - 4 /*yield*/, - recipe.OAuth2Provider.getInstanceOrThrow().webJSRecipe.logOut({ - logoutChallenge: logoutChallenge, - userContext: userContext, - }), - ]; - case 2: - frontendRedirectTo = _a.sent().frontendRedirectTo; - return [ - 4 /*yield*/, - props.recipe.redirect( - { - recipeId: "oauth2provider", - action: "POST_OAUTH2_LOGOUT_REDIRECT", - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - frontendRedirectTo: frontendRedirectTo, - }, - navigate, - {}, - userContext - ), - ]; - case 3: - _a.sent(); - return [3 /*break*/, 6]; - case 4: - err_1 = _a.sent(); - return [4 /*yield*/, session.doesSessionExist(userContext)]; - case 5: - if (!_a.sent()) { - void genericComponentOverrideContext.SuperTokens.getInstanceOrThrow() - .redirectToAuth({ - userContext: userContext, - redirectBack: false, - }) - .catch(rethrowInRender); - } else { - rethrowInRender(err_1); - } - return [3 /*break*/, 6]; - case 6: - return [2 /*return*/]; - } - }); - }); - }, - [logoutChallenge, navigate, props.recipe, userContext, rethrowInRender] - ); - React__namespace.useEffect( - function () { - // We wait for session loading to finish - if (sessionContext.loading === false) { - // Redirect to the auth page if there is no logoutChallenge - if (logoutChallenge === undefined) { - void genericComponentOverrideContext.SuperTokens.getInstanceOrThrow() - .redirectToAuth({ - userContext: userContext, - redirectBack: false, - }) - .catch(rethrowInRender); - } else { - // Call logOut directly if there is no session - if (sessionContext.doesSessionExist === false) { - void onLogout(); - } - } - } - }, - [userContext, logoutChallenge, sessionContext, onLogout] - ); - var childProps = { - config: props.recipe.config, - showSpinner: sessionContext.loading || sessionContext.doesSessionExist === false, - onLogoutClicked: onLogout, - isLoggingOut: isLoggingOut, - }; - if (logoutChallenge === undefined) { - return null; - } - return jsxRuntime.jsx( - uiEntry.ComponentOverrideContext.Provider, - genericComponentOverrideContext.__assign( - { value: recipeComponentOverrides }, - { - children: jsxRuntime.jsx( - uiEntry.FeatureWrapper, - genericComponentOverrideContext.__assign( - { - useShadowDom: genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().useShadowDom, - defaultStore: defaultTranslationsOAuth2Provider, - }, - { - children: jsxRuntime.jsxs(React.Fragment, { - children: [ - props.children === undefined && - jsxRuntime.jsx( - OAuth2LogoutScreenTheme, - genericComponentOverrideContext.__assign({}, childProps) - ), - props.children && - React__namespace.Children.map(props.children, function (child) { - if (React__namespace.isValidElement(child)) { - return React__namespace.cloneElement(child, childProps); - } - return child; - }), - ], - }), - } - ) - ), - } - ) - ); +var OAuth2LogoutScreen = function (props) { + var _a, _b, _c; + var rethrowInRender = utils.useRethrowInRender(); + var sessionContext = React__namespace.useContext(uiEntry.SessionContext); + var _d = React__namespace.useState(false), isLoggingOut = _d[0], setIsLoggingOut = _d[1]; + var recipeComponentOverrides = props.useComponentOverrides(); + var userContext = uiEntry.useUserContext(); + if (props.userContext !== undefined) { + userContext = props.userContext; + } + var logoutChallenge = (_a = utils.getQueryParams("logoutChallenge")) !== null && _a !== void 0 ? _a : undefined; + var navigate = (_b = props.navigate) !== null && _b !== void 0 ? _b : (_c = uiEntry.UI.getReactRouterDomWithCustomHistory()) === null || _c === void 0 ? void 0 : _c.useHistoryCustom(); + var onLogout = React__namespace.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + var frontendRedirectTo, err_1; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (logoutChallenge === undefined) { + return [2 /*return*/]; + } + setIsLoggingOut(true); + _a.label = 1; + case 1: + _a.trys.push([1, 4, , 6]); + return [4 /*yield*/, recipe.OAuth2Provider.getInstanceOrThrow().webJSRecipe.logOut({ + logoutChallenge: logoutChallenge, + userContext: userContext, + })]; + case 2: + frontendRedirectTo = (_a.sent()).frontendRedirectTo; + return [4 /*yield*/, props.recipe.redirect({ + recipeId: "oauth2provider", + action: "POST_OAUTH2_LOGOUT_REDIRECT", + tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), + frontendRedirectTo: frontendRedirectTo, + }, navigate, {}, userContext)]; + case 3: + _a.sent(); + return [3 /*break*/, 6]; + case 4: + err_1 = _a.sent(); + return [4 /*yield*/, session.doesSessionExist(userContext)]; + case 5: + if (!(_a.sent())) { + void superTokens.SuperTokens.getInstanceOrThrow() + .redirectToAuth({ + userContext: userContext, + redirectBack: false, + }) + .catch(rethrowInRender); + } + else { + rethrowInRender(err_1); + } + return [3 /*break*/, 6]; + case 6: return [2 /*return*/]; + } + }); + }); }, [logoutChallenge, navigate, props.recipe, userContext, rethrowInRender]); + React__namespace.useEffect(function () { + // We wait for session loading to finish + if (sessionContext.loading === false) { + // Redirect to the auth page if there is no logoutChallenge + if (logoutChallenge === undefined) { + void superTokens.SuperTokens.getInstanceOrThrow() + .redirectToAuth({ + userContext: userContext, + redirectBack: false, + }) + .catch(rethrowInRender); + } + else { + // Call logOut directly if there is no session + if (sessionContext.doesSessionExist === false) { + void onLogout(); + } + } + } + }, [userContext, logoutChallenge, sessionContext, onLogout]); + var childProps = { + config: props.recipe.config, + showSpinner: sessionContext.loading || sessionContext.doesSessionExist === false, + onLogoutClicked: onLogout, + isLoggingOut: isLoggingOut, + }; + if (logoutChallenge === undefined) { + return null; + } + return (jsxRuntime.jsx(uiEntry.ComponentOverrideContext.Provider, utils.__assign({ value: recipeComponentOverrides }, { children: jsxRuntime.jsx(uiEntry.FeatureWrapper, utils.__assign({ useShadowDom: superTokens.SuperTokens.getInstanceOrThrow().useShadowDom, defaultStore: defaultTranslationsOAuth2Provider }, { children: jsxRuntime.jsxs(React.Fragment, { children: [props.children === undefined && jsxRuntime.jsx(OAuth2LogoutScreenTheme, utils.__assign({}, childProps)), props.children && + React__namespace.Children.map(props.children, function (child) { + if (React__namespace.isValidElement(child)) { + return React__namespace.cloneElement(child, childProps); + } + return child; + })] }) })) }))); }; -var TryRefreshPage$1 = function (props) { - var _a; - var rethrowInRender = genericComponentOverrideContext.useRethrowInRender(); - var sessionContext = React.useContext(uiEntry.SessionContext); - var loginChallenge = - (_a = genericComponentOverrideContext.getQueryParams("loginChallenge")) !== null && _a !== void 0 - ? _a - : undefined; - var userContext = uiEntry.useUserContext(); - if (props.userContext !== undefined) { - userContext = props.userContext; - } - React__namespace.useEffect( - function () { - if (sessionContext.loading === false) { - if (loginChallenge) { - (function () { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var frontendRedirectTo; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - props.recipe.webJSRecipe.getRedirectURLToContinueOAuthFlow({ - loginChallenge: loginChallenge, - userContext: userContext, - }), - ]; - case 1: - frontendRedirectTo = _a.sent().frontendRedirectTo; - return [ - 2 /*return*/, - props.recipe.redirect( - { - action: "CONTINUE_OAUTH2_AFTER_REFRESH", - frontendRedirectTo: frontendRedirectTo, - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - recipeId: "oauth2provider", - }, - props.navigate, - {}, - userContext - ), - ]; - } - }); - }); - })().catch(rethrowInRender); - } else { - void genericComponentOverrideContext.SuperTokens.getInstanceOrThrow() - .redirectToAuth({ - userContext: userContext, - redirectBack: false, - }) - .catch(rethrowInRender); - } - } - }, - [loginChallenge, props.recipe, props.navigate, userContext, sessionContext] - ); - var childProps = { - config: props.recipe.config, - }; - return jsxRuntime.jsx( - uiEntry.FeatureWrapper, - genericComponentOverrideContext.__assign( - { - useShadowDom: genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().useShadowDom, - defaultStore: defaultTranslationsOAuth2Provider, - }, - { - children: jsxRuntime.jsxs(React.Fragment, { - children: [ - props.children === undefined && jsxRuntime.jsx(uiEntry.DynamicLoginMethodsSpinner, {}), - props.children && - React__namespace.Children.map(props.children, function (child) { - if (React__namespace.isValidElement(child)) { - return React__namespace.cloneElement(child, childProps); - } - return child; - }), - ], - }), - } - ) - ); +var TryRefreshPage$1 = function (props) { + var _a; + var rethrowInRender = utils.useRethrowInRender(); + var sessionContext = React.useContext(uiEntry.SessionContext); + var loginChallenge = (_a = utils.getQueryParams("loginChallenge")) !== null && _a !== void 0 ? _a : undefined; + var userContext = uiEntry.useUserContext(); + if (props.userContext !== undefined) { + userContext = props.userContext; + } + React__namespace.useEffect(function () { + if (sessionContext.loading === false) { + if (loginChallenge) { + (function () { + return utils.__awaiter(this, void 0, void 0, function () { + var frontendRedirectTo; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, props.recipe.webJSRecipe.getRedirectURLToContinueOAuthFlow({ + loginChallenge: loginChallenge, + userContext: userContext, + })]; + case 1: + frontendRedirectTo = (_a.sent()).frontendRedirectTo; + return [2 /*return*/, props.recipe.redirect({ + action: "CONTINUE_OAUTH2_AFTER_REFRESH", + frontendRedirectTo: frontendRedirectTo, + tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), + recipeId: "oauth2provider", + }, props.navigate, {}, userContext)]; + } + }); + }); + })().catch(rethrowInRender); + } + else { + void superTokens.SuperTokens.getInstanceOrThrow() + .redirectToAuth({ + userContext: userContext, + redirectBack: false, + }) + .catch(rethrowInRender); + } + } + }, [loginChallenge, props.recipe, props.navigate, userContext, sessionContext]); + var childProps = { + config: props.recipe.config, + }; + return (jsxRuntime.jsx(uiEntry.FeatureWrapper, utils.__assign({ useShadowDom: superTokens.SuperTokens.getInstanceOrThrow().useShadowDom, defaultStore: defaultTranslationsOAuth2Provider }, { children: jsxRuntime.jsxs(React.Fragment, { children: [props.children === undefined && jsxRuntime.jsx(uiEntry.DynamicLoginMethodsSpinner, {}), props.children && + React__namespace.Children.map(props.children, function (child) { + if (React__namespace.isValidElement(child)) { + return React__namespace.cloneElement(child, childProps); + } + return child; + })] }) }))); }; -/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var DEFAULT_TRY_REFRESH_PATH = "/try-refresh"; +/* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var DEFAULT_TRY_REFRESH_PATH = "/try-refresh"; var DEFAULT_OAUTH2_LOGOUT_PATH = "/oauth/logout"; -var OAuth2ProviderPreBuiltUI = /** @class */ (function (_super) { - genericComponentOverrideContext.__extends(OAuth2ProviderPreBuiltUI, _super); - function OAuth2ProviderPreBuiltUI(recipeInstance) { - var _this = _super.call(this) || this; - _this.recipeInstance = recipeInstance; - _this.languageTranslations = defaultTranslationsOAuth2Provider; - // Instance methods - _this.getFeatures = function (useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = componentOverrideContext.useContext; - } - if (_this.recipeInstance.config.disableDefaultUI) { - return {}; - } - var features = {}; - if (_this.recipeInstance.config.tryRefreshPage.disableDefaultUI !== true) { - var normalisedFullPath = _this.recipeInstance.config.appInfo.websiteBasePath.appendPath( - new NormalisedURLPath__default.default(DEFAULT_TRY_REFRESH_PATH) - ); - features[normalisedFullPath.getAsStringDangerous()] = { - matches: genericComponentOverrideContext.matchRecipeIdUsingQueryParams( - _this.recipeInstance.config.recipeId - ), - component: function (props) { - return _this.getFeatureComponent("try-refresh-page", props, useComponentOverrides); - }, - recipeID: recipe.OAuth2Provider.RECIPE_ID, - }; - } - if (_this.recipeInstance.config.oauth2LogoutScreen.disableDefaultUI !== true) { - var normalisedFullPath = _this.recipeInstance.config.appInfo.websiteBasePath.appendPath( - new NormalisedURLPath__default.default(DEFAULT_OAUTH2_LOGOUT_PATH) - ); - features[normalisedFullPath.getAsStringDangerous()] = { - matches: genericComponentOverrideContext.matchRecipeIdUsingQueryParams( - _this.recipeInstance.config.recipeId - ), - component: function (props) { - return _this.getFeatureComponent("oauth2-logout-screen", props, useComponentOverrides); - }, - recipeID: recipe.OAuth2Provider.RECIPE_ID, - }; - } - return features; - }; - _this.getFeatureComponent = function ( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - componentName, - props, - useComponentOverrides - ) { - if (useComponentOverrides === void 0) { - useComponentOverrides = componentOverrideContext.useContext; - } - if (componentName === "try-refresh-page") { - return jsxRuntime.jsx( - uiEntry.UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - session.SessionAuth, - genericComponentOverrideContext.__assign( - { - requireAuth: false, - overrideGlobalClaimValidators: function () { - return []; - }, - }, - { - children: jsxRuntime.jsx( - TryRefreshPage$1, - genericComponentOverrideContext.__assign( - { - recipe: _this.recipeInstance, - useComponentOverrides: useComponentOverrides, - }, - props - ) - ), - } - ) - ), - } - ) - ); - } else if (componentName === "oauth2-logout-screen") { - return jsxRuntime.jsx( - uiEntry.UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - session.SessionAuth, - genericComponentOverrideContext.__assign( - { - requireAuth: false, - overrideGlobalClaimValidators: function () { - return []; - }, - }, - { - children: jsxRuntime.jsx( - OAuth2LogoutScreen, - genericComponentOverrideContext.__assign( - { - recipe: _this.recipeInstance, - useComponentOverrides: useComponentOverrides, - }, - props - ) - ), - } - ) - ), - } - ) - ); - } - throw new Error("Should never come here."); - }; - return _this; - } - // Static methods - OAuth2ProviderPreBuiltUI.getInstanceOrInitAndGetInstance = function () { - if (OAuth2ProviderPreBuiltUI.instance === undefined) { - var recipeInstance = recipe.OAuth2Provider.getInstanceOrThrow(); - OAuth2ProviderPreBuiltUI.instance = new OAuth2ProviderPreBuiltUI(recipeInstance); - } - return OAuth2ProviderPreBuiltUI.instance; - }; - OAuth2ProviderPreBuiltUI.getFeatures = function (useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = componentOverrideContext.useContext; - } - return OAuth2ProviderPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatures(useComponentOverrides); - }; - OAuth2ProviderPreBuiltUI.getFeatureComponent = function (componentName, props, useComponentOverrides) { - if (useComponentOverrides === void 0) { - useComponentOverrides = componentOverrideContext.useContext; - } - return OAuth2ProviderPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent( - componentName, - props, - useComponentOverrides - ); - }; - OAuth2ProviderPreBuiltUI.prototype.getAuthComponents = function () { - return []; - }; - // For tests - OAuth2ProviderPreBuiltUI.reset = function () { - if (!genericComponentOverrideContext.isTest()) { - return; - } - OAuth2ProviderPreBuiltUI.instance = undefined; - return; - }; - OAuth2ProviderPreBuiltUI.TryRefreshPage = function (props) { - return OAuth2ProviderPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent( - "try-refresh-page", - props - ); - }; - OAuth2ProviderPreBuiltUI.OAuth2LogoutScreen = function (props) { - return OAuth2ProviderPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent( - "oauth2-logout-screen", - props - ); - }; - return OAuth2ProviderPreBuiltUI; -})(uiEntry.RecipeRouter); +var OAuth2ProviderPreBuiltUI = /** @class */ (function (_super) { + utils.__extends(OAuth2ProviderPreBuiltUI, _super); + function OAuth2ProviderPreBuiltUI(recipeInstance) { + var _this = _super.call(this) || this; + _this.recipeInstance = recipeInstance; + _this.languageTranslations = defaultTranslationsOAuth2Provider; + // Instance methods + _this.getFeatures = function (useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = componentOverrideContext.useContext; } + if (_this.recipeInstance.config.disableDefaultUI) { + return {}; + } + var features = {}; + if (_this.recipeInstance.config.tryRefreshPage.disableDefaultUI !== true) { + var normalisedFullPath = _this.recipeInstance.config.appInfo.websiteBasePath.appendPath(new NormalisedURLPath__default.default(DEFAULT_TRY_REFRESH_PATH)); + features[normalisedFullPath.getAsStringDangerous()] = { + matches: utils.matchRecipeIdUsingQueryParams(_this.recipeInstance.config.recipeId), + component: function (props) { return _this.getFeatureComponent("try-refresh-page", props, useComponentOverrides); }, + recipeID: recipe.OAuth2Provider.RECIPE_ID, + }; + } + if (_this.recipeInstance.config.oauth2LogoutScreen.disableDefaultUI !== true) { + var normalisedFullPath = _this.recipeInstance.config.appInfo.websiteBasePath.appendPath(new NormalisedURLPath__default.default(DEFAULT_OAUTH2_LOGOUT_PATH)); + features[normalisedFullPath.getAsStringDangerous()] = { + matches: utils.matchRecipeIdUsingQueryParams(_this.recipeInstance.config.recipeId), + component: function (props) { + return _this.getFeatureComponent("oauth2-logout-screen", props, useComponentOverrides); + }, + recipeID: recipe.OAuth2Provider.RECIPE_ID, + }; + } + return features; + }; + _this.getFeatureComponent = function ( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + componentName, props, useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = componentOverrideContext.useContext; } + if (componentName === "try-refresh-page") { + return (jsxRuntime.jsx(uiEntry.UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(session.SessionAuth, utils.__assign({ requireAuth: false, overrideGlobalClaimValidators: function () { return []; } }, { children: jsxRuntime.jsx(TryRefreshPage$1, utils.__assign({ recipe: _this.recipeInstance, useComponentOverrides: useComponentOverrides }, props)) })) }))); + } + else if (componentName === "oauth2-logout-screen") { + return (jsxRuntime.jsx(uiEntry.UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(session.SessionAuth, utils.__assign({ requireAuth: false, overrideGlobalClaimValidators: function () { return []; } }, { children: jsxRuntime.jsx(OAuth2LogoutScreen, utils.__assign({ recipe: _this.recipeInstance, useComponentOverrides: useComponentOverrides }, props)) })) }))); + } + throw new Error("Should never come here."); + }; + return _this; + } + // Static methods + OAuth2ProviderPreBuiltUI.getInstanceOrInitAndGetInstance = function () { + if (OAuth2ProviderPreBuiltUI.instance === undefined) { + var recipeInstance = recipe.OAuth2Provider.getInstanceOrThrow(); + OAuth2ProviderPreBuiltUI.instance = new OAuth2ProviderPreBuiltUI(recipeInstance); + } + return OAuth2ProviderPreBuiltUI.instance; + }; + OAuth2ProviderPreBuiltUI.getFeatures = function (useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = componentOverrideContext.useContext; } + return OAuth2ProviderPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatures(useComponentOverrides); + }; + OAuth2ProviderPreBuiltUI.getFeatureComponent = function (componentName, props, useComponentOverrides) { + if (useComponentOverrides === void 0) { useComponentOverrides = componentOverrideContext.useContext; } + return OAuth2ProviderPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent(componentName, props, useComponentOverrides); + }; + OAuth2ProviderPreBuiltUI.prototype.getAuthComponents = function () { + return []; + }; + // For tests + OAuth2ProviderPreBuiltUI.reset = function () { + if (!utils.isTest()) { + return; + } + OAuth2ProviderPreBuiltUI.instance = undefined; + return; + }; + OAuth2ProviderPreBuiltUI.TryRefreshPage = function (props) { + return OAuth2ProviderPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent("try-refresh-page", props); + }; + OAuth2ProviderPreBuiltUI.OAuth2LogoutScreen = function (props) { + return OAuth2ProviderPreBuiltUI.getInstanceOrInitAndGetInstance().getFeatureComponent("oauth2-logout-screen", props); + }; + return OAuth2ProviderPreBuiltUI; +}(uiEntry.RecipeRouter)); var TryRefreshPage = OAuth2ProviderPreBuiltUI.TryRefreshPage; exports.OAuth2ProviderPreBuiltUI = OAuth2ProviderPreBuiltUI; diff --git a/lib/build/passwordless-shared.js b/lib/build/passwordless-shared.js index 099cb859c..919b23174 100644 --- a/lib/build/passwordless-shared.js +++ b/lib/build/passwordless-shared.js @@ -1,544 +1,355 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var PasswordlessWebJS = require("supertokens-web-js/recipe/passwordless"); -var postSuperTokensInitCallbacks = require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -var jsxRuntime = require("react/jsx-runtime"); -var index = require("./authRecipe-shared2.js"); -var recipe = require("./multifactorauth-shared2.js"); -var types = require("./multifactorauth-shared.js"); -var utils = require("./authRecipe-shared.js"); +var genericComponentOverrideContext = require('./genericComponentOverrideContext.js'); +var utils = require('./utils.js'); +var PasswordlessWebJS = require('supertokens-web-js/recipe/passwordless'); +var postSuperTokensInitCallbacks = require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +var jsxRuntime = require('react/jsx-runtime'); +var index = require('./authRecipe-shared2.js'); +var recipe = require('./multifactorauth-shared2.js'); +var types = require('./multifactorauth-shared.js'); +var utils$1 = require('./authRecipe-shared.js'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } -var PasswordlessWebJS__default = /*#__PURE__*/ _interopDefault(PasswordlessWebJS); +var PasswordlessWebJS__default = /*#__PURE__*/_interopDefault(PasswordlessWebJS); -var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), - useContext = _a[0], - Provider = _a[1]; +var _a = genericComponentOverrideContext.createGenericComponentsOverrideContext(), useContext = _a[0], Provider = _a[1]; -var OTPEmailIcon = function () { - return jsxRuntime.jsxs( - "svg", - genericComponentOverrideContext.__assign( - { width: "17", height: "15", viewBox: "0 0 17 15", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, - { - children: [ - jsxRuntime.jsx("path", { - id: "image 414 (Traced)", - fillRule: "evenodd", - clipRule: "evenodd", - d: "M2.01513 0.0546421C1.19571 0.195435 0.393224 0.877322 0.143564 1.64496C0.0564841 1.9127 -0.00197242 1.84636 0.659082 2.22993C0.91105 2.37612 1.64082 2.80042 2.28084 3.17276C2.92086 3.54514 3.96809 4.1544 4.60811 4.52674C5.24813 4.89905 6.37321 5.55428 7.10833 5.98278C7.84346 6.41131 8.46401 6.7689 8.48736 6.77743C8.52111 6.78982 10.4367 5.69077 12.6253 4.40341C12.7865 4.30852 13.8173 3.70613 14.9159 3.06475L16.9133 1.89856L16.903 1.78079C16.8974 1.71603 16.8178 1.51568 16.7262 1.3356C16.3776 0.650318 15.6775 0.156143 14.8905 0.039982C14.4716 -0.0218423 2.38016 -0.00809191 2.01513 0.0546421ZM6.60933e-06 6.62054C0.000739608 10.251 -0.00834948 10.1158 0.27063 10.655C0.659815 11.4073 1.39721 11.8833 2.30408 11.9675C2.77169 12.0109 14.2345 12.0108 14.7024 11.9673C15.3604 11.9062 15.8152 11.7008 16.2911 11.2498C16.5236 11.0295 16.619 10.9066 16.7395 10.6725C17.0173 10.133 17.0065 10.3025 16.996 6.65494L16.9866 3.40211L15.8322 4.07294C15.1972 4.44186 13.9767 5.15156 13.1201 5.65004C11.2459 6.74049 10.2603 7.31342 9.46206 7.77628C8.76656 8.17962 8.59368 8.23389 8.2745 8.14908C8.14446 8.11454 7.64668 7.84559 6.81451 7.36034C4.15032 5.80665 0.097862 3.44588 0.0268711 3.40617C0.0117346 3.39774 -0.00032324 4.84419 6.60933e-06 6.62054Z", - fill: "url(#paint0_linear_4445_310)", - }), - jsxRuntime.jsx("defs", { - children: jsxRuntime.jsxs( - "linearGradient", - genericComponentOverrideContext.__assign( - { - id: "paint0_linear_4445_310", - x1: "8.5", - y1: "0", - x2: "8.5", - y2: "12", - gradientUnits: "userSpaceOnUse", - }, - { - children: [ - jsxRuntime.jsx("stop", { stopColor: "#1C222A" }), - jsxRuntime.jsx("stop", { offset: "1", stopColor: "#1C222A" }), - ], - } - ) - ), - }), - ], - } - ) - ); -}; +var OTPEmailIcon = function () { return (jsxRuntime.jsxs("svg", utils.__assign({ width: "17", height: "15", viewBox: "0 0 17 15", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, { children: [jsxRuntime.jsx("path", { id: "image 414 (Traced)", fillRule: "evenodd", clipRule: "evenodd", d: "M2.01513 0.0546421C1.19571 0.195435 0.393224 0.877322 0.143564 1.64496C0.0564841 1.9127 -0.00197242 1.84636 0.659082 2.22993C0.91105 2.37612 1.64082 2.80042 2.28084 3.17276C2.92086 3.54514 3.96809 4.1544 4.60811 4.52674C5.24813 4.89905 6.37321 5.55428 7.10833 5.98278C7.84346 6.41131 8.46401 6.7689 8.48736 6.77743C8.52111 6.78982 10.4367 5.69077 12.6253 4.40341C12.7865 4.30852 13.8173 3.70613 14.9159 3.06475L16.9133 1.89856L16.903 1.78079C16.8974 1.71603 16.8178 1.51568 16.7262 1.3356C16.3776 0.650318 15.6775 0.156143 14.8905 0.039982C14.4716 -0.0218423 2.38016 -0.00809191 2.01513 0.0546421ZM6.60933e-06 6.62054C0.000739608 10.251 -0.00834948 10.1158 0.27063 10.655C0.659815 11.4073 1.39721 11.8833 2.30408 11.9675C2.77169 12.0109 14.2345 12.0108 14.7024 11.9673C15.3604 11.9062 15.8152 11.7008 16.2911 11.2498C16.5236 11.0295 16.619 10.9066 16.7395 10.6725C17.0173 10.133 17.0065 10.3025 16.996 6.65494L16.9866 3.40211L15.8322 4.07294C15.1972 4.44186 13.9767 5.15156 13.1201 5.65004C11.2459 6.74049 10.2603 7.31342 9.46206 7.77628C8.76656 8.17962 8.59368 8.23389 8.2745 8.14908C8.14446 8.11454 7.64668 7.84559 6.81451 7.36034C4.15032 5.80665 0.097862 3.44588 0.0268711 3.40617C0.0117346 3.39774 -0.00032324 4.84419 6.60933e-06 6.62054Z", fill: "url(#paint0_linear_4445_310)" }), jsxRuntime.jsx("defs", { children: jsxRuntime.jsxs("linearGradient", utils.__assign({ id: "paint0_linear_4445_310", x1: "8.5", y1: "0", x2: "8.5", y2: "12", gradientUnits: "userSpaceOnUse" }, { children: [jsxRuntime.jsx("stop", { stopColor: "#1C222A" }), jsxRuntime.jsx("stop", { offset: "1", stopColor: "#1C222A" })] })) })] }))); }; -var OTPSMSIcon = function () { - return jsxRuntime.jsxs( - "svg", - genericComponentOverrideContext.__assign( - { width: "17", height: "15", viewBox: "0 0 17 15", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, - { - children: [ - jsxRuntime.jsx("path", { - id: "image 412 (Traced)", - fillRule: "evenodd", - clipRule: "evenodd", - d: "M2.23143 0.0484105C1.11677 0.26606 0.230705 1.14148 0.0548812 2.19882C0.0207171 2.40417 -0.000319148 3.89779 3.66265e-06 6.09367C0.000595481 10.0175 0.00446909 10.0713 0.330507 10.706C0.544477 11.1223 1.03692 11.597 1.49058 11.8243C1.9253 12.042 2.4213 12.1389 3.10571 12.14L3.65718 12.1409L3.65739 13.3581C3.65755 14.4585 3.66729 14.5903 3.75859 14.733C3.88347 14.9281 4.1338 15.0332 4.37209 14.9906C4.50192 14.9674 5.03536 14.5737 6.32332 13.5507L8.09582 12.1427L11.2701 12.1409C14.8062 12.1389 14.8922 12.1322 15.5441 11.8059C15.9514 11.602 16.4058 11.1868 16.6406 10.8041C16.7198 10.6748 16.8331 10.3886 16.8923 10.1681C16.9951 9.78536 17 9.6 17 6.0949C17 3.67866 16.98 2.31864 16.9417 2.11857C16.7993 1.37604 16.1965 0.620747 15.4792 0.286303C15.2652 0.186472 14.9464 0.0801328 14.7708 0.049999C14.3886 -0.0156495 2.5671 -0.0171356 2.23143 0.0484105ZM5.24433 4.97226C5.37743 5.00736 5.55471 5.1197 5.70901 5.26668C6.20818 5.74216 6.20834 6.40218 5.70933 6.86336C5.19445 7.3393 4.53167 7.33945 4.03228 6.86382C3.54451 6.3992 3.53069 5.75907 3.99822 5.28943C4.33561 4.95053 4.75602 4.84352 5.24433 4.97226ZM8.87594 4.96544C9.55686 5.14589 9.9071 5.95945 9.57246 6.58313C9.13161 7.40469 7.91806 7.41591 7.45342 6.60271C7.32215 6.37302 7.3066 6.29861 7.32494 5.98907C7.34211 5.69977 7.37455 5.59794 7.50653 5.41904C7.804 5.01592 8.36509 4.83005 8.87594 4.96544ZM12.7023 5.05815C13.4409 5.4257 13.5612 6.36097 12.94 6.90635C12.6706 7.14291 12.3468 7.24567 12.0095 7.20164C11.0115 7.07132 10.59 5.99614 11.2623 5.29563C11.6485 4.89313 12.1909 4.80365 12.7023 5.05815Z", - fill: "url(#paint0_linear_4445_316)", - }), - jsxRuntime.jsx("defs", { - children: jsxRuntime.jsxs( - "linearGradient", - genericComponentOverrideContext.__assign( - { - id: "paint0_linear_4445_316", - x1: "8.5", - y1: "0", - x2: "8.5", - y2: "15", - gradientUnits: "userSpaceOnUse", - }, - { - children: [ - jsxRuntime.jsx("stop", { stopColor: "#1C222A" }), - jsxRuntime.jsx("stop", { offset: "1", stopColor: "#1C222A" }), - ], - } - ) - ), - }), - ], - } - ) - ); -}; +var OTPSMSIcon = function () { return (jsxRuntime.jsxs("svg", utils.__assign({ width: "17", height: "15", viewBox: "0 0 17 15", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, { children: [jsxRuntime.jsx("path", { id: "image 412 (Traced)", fillRule: "evenodd", clipRule: "evenodd", d: "M2.23143 0.0484105C1.11677 0.26606 0.230705 1.14148 0.0548812 2.19882C0.0207171 2.40417 -0.000319148 3.89779 3.66265e-06 6.09367C0.000595481 10.0175 0.00446909 10.0713 0.330507 10.706C0.544477 11.1223 1.03692 11.597 1.49058 11.8243C1.9253 12.042 2.4213 12.1389 3.10571 12.14L3.65718 12.1409L3.65739 13.3581C3.65755 14.4585 3.66729 14.5903 3.75859 14.733C3.88347 14.9281 4.1338 15.0332 4.37209 14.9906C4.50192 14.9674 5.03536 14.5737 6.32332 13.5507L8.09582 12.1427L11.2701 12.1409C14.8062 12.1389 14.8922 12.1322 15.5441 11.8059C15.9514 11.602 16.4058 11.1868 16.6406 10.8041C16.7198 10.6748 16.8331 10.3886 16.8923 10.1681C16.9951 9.78536 17 9.6 17 6.0949C17 3.67866 16.98 2.31864 16.9417 2.11857C16.7993 1.37604 16.1965 0.620747 15.4792 0.286303C15.2652 0.186472 14.9464 0.0801328 14.7708 0.049999C14.3886 -0.0156495 2.5671 -0.0171356 2.23143 0.0484105ZM5.24433 4.97226C5.37743 5.00736 5.55471 5.1197 5.70901 5.26668C6.20818 5.74216 6.20834 6.40218 5.70933 6.86336C5.19445 7.3393 4.53167 7.33945 4.03228 6.86382C3.54451 6.3992 3.53069 5.75907 3.99822 5.28943C4.33561 4.95053 4.75602 4.84352 5.24433 4.97226ZM8.87594 4.96544C9.55686 5.14589 9.9071 5.95945 9.57246 6.58313C9.13161 7.40469 7.91806 7.41591 7.45342 6.60271C7.32215 6.37302 7.3066 6.29861 7.32494 5.98907C7.34211 5.69977 7.37455 5.59794 7.50653 5.41904C7.804 5.01592 8.36509 4.83005 8.87594 4.96544ZM12.7023 5.05815C13.4409 5.4257 13.5612 6.36097 12.94 6.90635C12.6706 7.14291 12.3468 7.24567 12.0095 7.20164C11.0115 7.07132 10.59 5.99614 11.2623 5.29563C11.6485 4.89313 12.1909 4.80365 12.7023 5.05815Z", fill: "url(#paint0_linear_4445_316)" }), jsxRuntime.jsx("defs", { children: jsxRuntime.jsxs("linearGradient", utils.__assign({ id: "paint0_linear_4445_316", x1: "8.5", y1: "0", x2: "8.5", y2: "15", gradientUnits: "userSpaceOnUse" }, { children: [jsxRuntime.jsx("stop", { stopColor: "#1C222A" }), jsxRuntime.jsx("stop", { offset: "1", stopColor: "#1C222A" })] })) })] }))); }; -var getFunctionOverrides = function (onHandleEvent) { - return function (originalImp) { - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, originalImp), { - createCode: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, originalImp.createCode(input)]; - case 1: - response = _a.sent(); - if (response.status === "OK") { - onHandleEvent({ - action: "PASSWORDLESS_CODE_SENT", - isResend: false, - }); - } - return [2 /*return*/, response]; - } - }); - }); - }, - resendCode: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var response; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, originalImp.resendCode(input)]; - case 1: - response = _a.sent(); - if (response.status === "RESTART_FLOW_ERROR") { - onHandleEvent({ - action: "PASSWORDLESS_RESTART_FLOW", - }); - } else if (response.status === "OK") { - onHandleEvent({ - action: "PASSWORDLESS_CODE_SENT", - isResend: true, - }); - } - return [2 /*return*/, response]; - } - }); - }); - }, - consumeCode: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var payloadBeforeCall, response, payloadAfterCall; - return genericComponentOverrideContext.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _c.trys.push([0, 2, , 3]); - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ - userContext: input.userContext, - }), - ]; - case 1: - payloadBeforeCall = _c.sent(); - return [3 /*break*/, 3]; - case 2: - _c.sent(); - // If getAccessTokenPayloadSecurely threw, that generally means we have no active session - payloadBeforeCall = undefined; - return [3 /*break*/, 3]; - case 3: - return [4 /*yield*/, originalImp.consumeCode(input)]; - case 4: - response = _c.sent(); - if (!(response.status === "RESTART_FLOW_ERROR")) return [3 /*break*/, 5]; - onHandleEvent({ - action: "PASSWORDLESS_RESTART_FLOW", - }); - return [3 /*break*/, 10]; - case 5: - if (!(response.status === "OK")) return [3 /*break*/, 10]; - payloadAfterCall = void 0; - _c.label = 6; - case 6: - _c.trys.push([6, 8, , 9]); - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ - userContext: input.userContext, - }), - ]; - case 7: - payloadAfterCall = _c.sent(); - return [3 /*break*/, 9]; - case 8: - _c.sent(); - // If getAccessTokenPayloadSecurely threw, that generally means we have no active session - payloadAfterCall = undefined; - return [3 /*break*/, 9]; - case 9: - onHandleEvent({ - action: "SUCCESS", - isNewRecipeUser: response.createdNewRecipeUser, - user: response.user, - createdNewSession: - payloadAfterCall !== undefined && - (payloadBeforeCall === undefined || - payloadBeforeCall.sessionHandle !== payloadAfterCall.sessionHandle), - }); - _c.label = 10; - case 10: - return [2 /*return*/, response]; - } - }); - }); - }, - setLoginAttemptInfo: function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - originalImp.setLoginAttemptInfo( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, input), - { - attemptInfo: genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, input.attemptInfo), - input.userContext.additionalAttemptInfo - ), - } - ) - ), - ]; - }); - }); - }, - }); - }; +var getFunctionOverrides = function (onHandleEvent) { + return function (originalImp) { return (utils.__assign(utils.__assign({}, originalImp), { createCode: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, originalImp.createCode(input)]; + case 1: + response = _a.sent(); + if (response.status === "OK") { + onHandleEvent({ + action: "PASSWORDLESS_CODE_SENT", + isResend: false, + }); + } + return [2 /*return*/, response]; + } + }); + }); + }, resendCode: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var response; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, originalImp.resendCode(input)]; + case 1: + response = _a.sent(); + if (response.status === "RESTART_FLOW_ERROR") { + onHandleEvent({ + action: "PASSWORDLESS_RESTART_FLOW", + }); + } + else if (response.status === "OK") { + onHandleEvent({ + action: "PASSWORDLESS_CODE_SENT", + isResend: true, + }); + } + return [2 /*return*/, response]; + } + }); + }); + }, consumeCode: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + var payloadBeforeCall, response, payloadAfterCall; + return utils.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _c.trys.push([0, 2, , 3]); + return [4 /*yield*/, types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ + userContext: input.userContext, + })]; + case 1: + payloadBeforeCall = _c.sent(); + return [3 /*break*/, 3]; + case 2: + _c.sent(); + // If getAccessTokenPayloadSecurely threw, that generally means we have no active session + payloadBeforeCall = undefined; + return [3 /*break*/, 3]; + case 3: return [4 /*yield*/, originalImp.consumeCode(input)]; + case 4: + response = _c.sent(); + if (!(response.status === "RESTART_FLOW_ERROR")) return [3 /*break*/, 5]; + onHandleEvent({ + action: "PASSWORDLESS_RESTART_FLOW", + }); + return [3 /*break*/, 10]; + case 5: + if (!(response.status === "OK")) return [3 /*break*/, 10]; + payloadAfterCall = void 0; + _c.label = 6; + case 6: + _c.trys.push([6, 8, , 9]); + return [4 /*yield*/, types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ + userContext: input.userContext, + })]; + case 7: + payloadAfterCall = _c.sent(); + return [3 /*break*/, 9]; + case 8: + _c.sent(); + // If getAccessTokenPayloadSecurely threw, that generally means we have no active session + payloadAfterCall = undefined; + return [3 /*break*/, 9]; + case 9: + onHandleEvent({ + action: "SUCCESS", + isNewRecipeUser: response.createdNewRecipeUser, + user: response.user, + createdNewSession: payloadAfterCall !== undefined && + (payloadBeforeCall === undefined || + payloadBeforeCall.sessionHandle !== payloadAfterCall.sessionHandle), + }); + _c.label = 10; + case 10: return [2 /*return*/, response]; + } + }); + }); + }, setLoginAttemptInfo: function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, originalImp.setLoginAttemptInfo(utils.__assign(utils.__assign({}, input), { attemptInfo: utils.__assign(utils.__assign({}, input.attemptInfo), input.userContext.additionalAttemptInfo) }))]; + }); + }); + } })); }; }; -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -function defaultEmailValidator(value) { - if (typeof value !== "string") { - return "GENERAL_ERROR_EMAIL_NON_STRING"; - } - value = value.trim(); - var defaultEmailValidatorRegexp = - // eslint-disable-next-line no-useless-escape - /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - // We check if the email syntax is correct - // As per https://github.com/supertokens/supertokens-auth-react/issues/5#issuecomment-709512438 - // Regex from https://stackoverflow.com/a/46181/3867175 - if (value.match(defaultEmailValidatorRegexp) === null) { - return "GENERAL_ERROR_EMAIL_INVALID"; - } - return undefined; -} -function userInputCodeValidate(value) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - if (typeof value !== "string") { - return [2 /*return*/, "GENERAL_ERROR_OTP_NON_STRING"]; - } - if (value.length === 0) { - return [2 /*return*/, "GENERAL_ERROR_OTP_EMPTY"]; - } - return [2 /*return*/, undefined]; - }); - }); -} -/* - * defaultValidate - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -function defaultValidate(_) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [2 /*return*/, undefined]; - }); - }); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +function defaultEmailValidator(value) { + if (typeof value !== "string") { + return "GENERAL_ERROR_EMAIL_NON_STRING"; + } + value = value.trim(); + var defaultEmailValidatorRegexp = + // eslint-disable-next-line no-useless-escape + /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + // We check if the email syntax is correct + // As per https://github.com/supertokens/supertokens-auth-react/issues/5#issuecomment-709512438 + // Regex from https://stackoverflow.com/a/46181/3867175 + if (value.match(defaultEmailValidatorRegexp) === null) { + return "GENERAL_ERROR_EMAIL_INVALID"; + } + return undefined; +} +function userInputCodeValidate(value) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + if (typeof value !== "string") { + return [2 /*return*/, "GENERAL_ERROR_OTP_NON_STRING"]; + } + if (value.length === 0) { + return [2 /*return*/, "GENERAL_ERROR_OTP_EMPTY"]; + } + return [2 /*return*/, undefined]; + }); + }); +} +/* + * defaultValidate + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function defaultValidate(_) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, undefined]; + }); + }); } -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -function normalisePasswordlessConfig(config) { - if (config === undefined) { - throw new Error("Passwordless config should not be empty"); - } - if (!["EMAIL", "PHONE", "EMAIL_OR_PHONE"].includes(config.contactMethod)) { - throw new Error("Please pass one of 'PHONE', 'EMAIL' or 'EMAIL_OR_PHONE' as the contactMethod"); - } - var signInUpFeature = normalizeSignInUpFeatureConfig(config.signInUpFeature, config); - var override = genericComponentOverrideContext.__assign( - { - functions: function (originalImplementation) { - return originalImplementation; - }, - }, - config.override - ); - var validateEmailAddress = defaultEmailValidator; - if ( - (config.contactMethod === "EMAIL" || config.contactMethod === "EMAIL_OR_PHONE") && - config.validateEmailAddress !== undefined - ) { - validateEmailAddress = config.validateEmailAddress; - } - var validatePhoneNumber = undefined; - if ( - (config.contactMethod === "PHONE" || config.contactMethod === "EMAIL_OR_PHONE") && - config.validatePhoneNumber !== undefined - ) { - validatePhoneNumber = config.validatePhoneNumber; - } - return genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, utils.normaliseAuthRecipe(config)), - { - validateEmailAddress: validateEmailAddress, - validatePhoneNumber: validatePhoneNumber, - signInUpFeature: signInUpFeature, - linkClickedScreenFeature: normalisePasswordlessBaseConfig(config.linkClickedScreenFeature), - mfaFeature: normalisePasswordlessBaseConfig(config.mfaFeature), - contactMethod: config.contactMethod, - override: override, - } - ); -} -function normalizeSignInUpFeatureConfig(signInUpInput, config) { - if ( - (signInUpInput === null || signInUpInput === void 0 ? void 0 : signInUpInput.resendEmailOrSMSGapInSeconds) !== - undefined && - signInUpInput.resendEmailOrSMSGapInSeconds <= 0 - ) { - throw new Error("Please pass a positive number as resendEmailOrSMSGapInSeconds"); - } - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, signInUpInput), { - resendEmailOrSMSGapInSeconds: - (signInUpInput === null || signInUpInput === void 0 - ? void 0 - : signInUpInput.resendEmailOrSMSGapInSeconds) === undefined - ? 15 - : signInUpInput.resendEmailOrSMSGapInSeconds, - emailOrPhoneFormStyle: - (signInUpInput === null || signInUpInput === void 0 ? void 0 : signInUpInput.emailOrPhoneFormStyle) !== - undefined - ? signInUpInput.emailOrPhoneFormStyle - : "", - linkSentScreenStyle: - (signInUpInput === null || signInUpInput === void 0 ? void 0 : signInUpInput.linkSentScreenStyle) !== - undefined - ? signInUpInput.linkSentScreenStyle - : "", - userInputCodeFormStyle: - (signInUpInput === null || signInUpInput === void 0 ? void 0 : signInUpInput.userInputCodeFormStyle) !== - undefined - ? signInUpInput.userInputCodeFormStyle - : "", - defaultCountry: - ["PHONE", "EMAIL_OR_PHONE"].includes(config.contactMethod) && - signInUpInput !== undefined && - "defaultCountry" in signInUpInput - ? signInUpInput.defaultCountry - : undefined, - defaultToEmail: - signInUpInput !== undefined && - "defaultToEmail" in signInUpInput && - signInUpInput.defaultToEmail !== undefined - ? signInUpInput.defaultToEmail - : true, - }); -} -function normalisePasswordlessBaseConfig(config) { - var style = config && config.style !== undefined ? config.style : ""; - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, config), { - style: style, - }); -} -function checkAdditionalLoginAttemptInfoProperties(loginAttemptInfo) { - if ( - loginAttemptInfo.contactInfo === undefined || - loginAttemptInfo.contactMethod === undefined || - loginAttemptInfo.lastResend === undefined - ) { - return false; - } - return true; +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +function normalisePasswordlessConfig(config) { + if (config === undefined) { + throw new Error("Passwordless config should not be empty"); + } + if (!["EMAIL", "PHONE", "EMAIL_OR_PHONE"].includes(config.contactMethod)) { + throw new Error("Please pass one of 'PHONE', 'EMAIL' or 'EMAIL_OR_PHONE' as the contactMethod"); + } + var signInUpFeature = normalizeSignInUpFeatureConfig(config.signInUpFeature, config); + var override = utils.__assign({ functions: function (originalImplementation) { return originalImplementation; } }, config.override); + var validateEmailAddress = defaultEmailValidator; + if ((config.contactMethod === "EMAIL" || config.contactMethod === "EMAIL_OR_PHONE") && + config.validateEmailAddress !== undefined) { + validateEmailAddress = config.validateEmailAddress; + } + var validatePhoneNumber = undefined; + if ((config.contactMethod === "PHONE" || config.contactMethod === "EMAIL_OR_PHONE") && + config.validatePhoneNumber !== undefined) { + validatePhoneNumber = config.validatePhoneNumber; + } + return utils.__assign(utils.__assign({}, utils$1.normaliseAuthRecipe(config)), { validateEmailAddress: validateEmailAddress, validatePhoneNumber: validatePhoneNumber, signInUpFeature: signInUpFeature, linkClickedScreenFeature: normalisePasswordlessBaseConfig(config.linkClickedScreenFeature), mfaFeature: normalisePasswordlessBaseConfig(config.mfaFeature), contactMethod: config.contactMethod, override: override }); +} +function normalizeSignInUpFeatureConfig(signInUpInput, config) { + if ((signInUpInput === null || signInUpInput === void 0 ? void 0 : signInUpInput.resendEmailOrSMSGapInSeconds) !== undefined && signInUpInput.resendEmailOrSMSGapInSeconds <= 0) { + throw new Error("Please pass a positive number as resendEmailOrSMSGapInSeconds"); + } + return utils.__assign(utils.__assign({}, signInUpInput), { resendEmailOrSMSGapInSeconds: (signInUpInput === null || signInUpInput === void 0 ? void 0 : signInUpInput.resendEmailOrSMSGapInSeconds) === undefined ? 15 : signInUpInput.resendEmailOrSMSGapInSeconds, emailOrPhoneFormStyle: (signInUpInput === null || signInUpInput === void 0 ? void 0 : signInUpInput.emailOrPhoneFormStyle) !== undefined ? signInUpInput.emailOrPhoneFormStyle : "", linkSentScreenStyle: (signInUpInput === null || signInUpInput === void 0 ? void 0 : signInUpInput.linkSentScreenStyle) !== undefined ? signInUpInput.linkSentScreenStyle : "", userInputCodeFormStyle: (signInUpInput === null || signInUpInput === void 0 ? void 0 : signInUpInput.userInputCodeFormStyle) !== undefined ? signInUpInput.userInputCodeFormStyle : "", defaultCountry: ["PHONE", "EMAIL_OR_PHONE"].includes(config.contactMethod) && + signInUpInput !== undefined && + "defaultCountry" in signInUpInput + ? signInUpInput.defaultCountry + : undefined, defaultToEmail: signInUpInput !== undefined && + "defaultToEmail" in signInUpInput && + signInUpInput.defaultToEmail !== undefined + ? signInUpInput.defaultToEmail + : true }); +} +function normalisePasswordlessBaseConfig(config) { + var style = config && config.style !== undefined ? config.style : ""; + return utils.__assign(utils.__assign({}, config), { style: style }); +} +function checkAdditionalLoginAttemptInfoProperties(loginAttemptInfo) { + if (loginAttemptInfo.contactInfo === undefined || + loginAttemptInfo.contactMethod === undefined || + loginAttemptInfo.lastResend === undefined) { + return false; + } + return true; } -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var otpPhoneFactor = { - id: types.FactorIds.OTP_PHONE, - name: "PWLESS_MFA_OTP_PHONE_NAME", - description: "PWLESS_MFA_OTP_PHONE_DESCRIPTION", - path: "/mfa/otp-phone", - logo: OTPSMSIcon, -}; -var otpEmailFactor = { - id: types.FactorIds.OTP_EMAIL, - name: "PWLESS_MFA_OTP_EMAIL_NAME", - description: "PWLESS_MFA_OTP_EMAIL_DESCRIPTION", - path: "/mfa/otp-email", - logo: OTPEmailIcon, -}; -/* - * Class. - */ -var Passwordless = /** @class */ (function (_super) { - genericComponentOverrideContext.__extends(Passwordless, _super); - function Passwordless(config, webJSRecipe) { - if (webJSRecipe === void 0) { - webJSRecipe = PasswordlessWebJS__default.default; - } - var _this = _super.call(this, config) || this; - _this.webJSRecipe = webJSRecipe; - _this.recipeID = Passwordless.RECIPE_ID; - _this.firstFactorIds = [ - types.FactorIds.OTP_EMAIL, - types.FactorIds.OTP_PHONE, - types.FactorIds.LINK_EMAIL, - types.FactorIds.LINK_PHONE, - ]; - _this.getDefaultRedirectionURL = function (context) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [2 /*return*/, this.getAuthRecipeDefaultRedirectionURL(context)]; - }); - }); - }; - _this.recipeID = config.recipeId; - postSuperTokensInitCallbacks.PostSuperTokensInitCallbacks.addPostInitCallback(function () { - var mfa = recipe.MultiFactorAuth.getInstance(); - if (mfa !== undefined) { - mfa.addMFAFactors([otpPhoneFactor, otpEmailFactor]); - } - }); - return _this; - } - Passwordless.prototype.getFirstFactorsForAuthPage = function () { - if (this.config.contactMethod === "EMAIL") { - return [types.FactorIds.OTP_EMAIL, types.FactorIds.LINK_EMAIL]; - } - if (this.config.contactMethod === "PHONE") { - return [types.FactorIds.OTP_PHONE, types.FactorIds.LINK_PHONE]; - } - return this.firstFactorIds; - }; - Passwordless.init = function (config) { - var normalisedConfig = normalisePasswordlessConfig(config); - return { - recipeID: Passwordless.RECIPE_ID, - authReact: function (appInfo) { - Passwordless.instance = new Passwordless( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, normalisedConfig), - { appInfo: appInfo, recipeId: Passwordless.RECIPE_ID } - ) - ); - return Passwordless.instance; - }, - webJS: PasswordlessWebJS__default.default.init( - genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, normalisedConfig), - { - override: { - functions: function (originalImpl, builder) { - var functions = getFunctionOverrides(normalisedConfig.onHandleEvent); - builder.override(functions); - builder.override(normalisedConfig.override.functions); - return originalImpl; - }, - }, - } - ) - ), - }; - }; - Passwordless.getInstanceOrThrow = function () { - if (Passwordless.instance === undefined) { - var error = - "No instance of Passwordless found. Make sure to call the Passwordless.init method." + - "See https://supertokens.io/docs/passwordless/quick-setup/frontend"; - // eslint-disable-next-line supertokens-auth-react/no-direct-window-object - if (typeof window === "undefined") { - error = error + genericComponentOverrideContext.SSR_ERROR; - } - throw Error(error); - } - return Passwordless.instance; - }; - /* - * Tests methods. - */ - Passwordless.reset = function () { - if (!genericComponentOverrideContext.isTest()) { - return; - } - Passwordless.instance = undefined; - return; - }; - Passwordless.RECIPE_ID = "passwordless"; - return Passwordless; -})(index.AuthRecipe); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var otpPhoneFactor = { + id: types.FactorIds.OTP_PHONE, + name: "PWLESS_MFA_OTP_PHONE_NAME", + description: "PWLESS_MFA_OTP_PHONE_DESCRIPTION", + path: "/mfa/otp-phone", + logo: OTPSMSIcon, +}; +var otpEmailFactor = { + id: types.FactorIds.OTP_EMAIL, + name: "PWLESS_MFA_OTP_EMAIL_NAME", + description: "PWLESS_MFA_OTP_EMAIL_DESCRIPTION", + path: "/mfa/otp-email", + logo: OTPEmailIcon, +}; +/* + * Class. + */ +var Passwordless = /** @class */ (function (_super) { + utils.__extends(Passwordless, _super); + function Passwordless(config, webJSRecipe) { + if (webJSRecipe === void 0) { webJSRecipe = PasswordlessWebJS__default.default; } + var _this = _super.call(this, config) || this; + _this.webJSRecipe = webJSRecipe; + _this.recipeID = Passwordless.RECIPE_ID; + _this.firstFactorIds = [types.FactorIds.OTP_EMAIL, types.FactorIds.OTP_PHONE, types.FactorIds.LINK_EMAIL, types.FactorIds.LINK_PHONE]; + _this.getDefaultRedirectionURL = function (context) { return utils.__awaiter(_this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, this.getAuthRecipeDefaultRedirectionURL(context)]; + }); + }); }; + _this.recipeID = config.recipeId; + postSuperTokensInitCallbacks.PostSuperTokensInitCallbacks.addPostInitCallback(function () { + var mfa = recipe.MultiFactorAuth.getInstance(); + if (mfa !== undefined) { + mfa.addMFAFactors([otpPhoneFactor, otpEmailFactor]); + } + }); + return _this; + } + Passwordless.prototype.getFirstFactorsForAuthPage = function () { + if (this.config.contactMethod === "EMAIL") { + return [types.FactorIds.OTP_EMAIL, types.FactorIds.LINK_EMAIL]; + } + if (this.config.contactMethod === "PHONE") { + return [types.FactorIds.OTP_PHONE, types.FactorIds.LINK_PHONE]; + } + return this.firstFactorIds; + }; + Passwordless.init = function (config) { + var normalisedConfig = normalisePasswordlessConfig(config); + return { + recipeID: Passwordless.RECIPE_ID, + authReact: function (appInfo) { + Passwordless.instance = new Passwordless(utils.__assign(utils.__assign({}, normalisedConfig), { appInfo: appInfo, recipeId: Passwordless.RECIPE_ID })); + return Passwordless.instance; + }, + webJS: PasswordlessWebJS__default.default.init(utils.__assign(utils.__assign({}, normalisedConfig), { override: { + functions: function (originalImpl, builder) { + var functions = getFunctionOverrides(normalisedConfig.onHandleEvent); + builder.override(functions); + builder.override(normalisedConfig.override.functions); + return originalImpl; + }, + } })), + }; + }; + Passwordless.getInstanceOrThrow = function () { + if (Passwordless.instance === undefined) { + var error = "No instance of Passwordless found. Make sure to call the Passwordless.init method." + + "See https://supertokens.io/docs/passwordless/quick-setup/frontend"; + // eslint-disable-next-line supertokens-auth-react/no-direct-window-object + if (typeof window === "undefined") { + error = error + utils.SSR_ERROR; + } + throw Error(error); + } + return Passwordless.instance; + }; + /* + * Tests methods. + */ + Passwordless.reset = function () { + if (!utils.isTest()) { + return; + } + Passwordless.instance = undefined; + return; + }; + Passwordless.RECIPE_ID = "passwordless"; + return Passwordless; +}(index.AuthRecipe)); exports.Passwordless = Passwordless; exports.Provider = Provider; diff --git a/lib/build/passwordless.js b/lib/build/passwordless.js index 64c29e4ba..aad475f7e 100644 --- a/lib/build/passwordless.js +++ b/lib/build/passwordless.js @@ -1,220 +1,141 @@ -"use strict"; +'use strict'; -Object.defineProperty(exports, "__esModule", { value: true }); +Object.defineProperty(exports, '__esModule', { value: true }); -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var recipe = require("./passwordless-shared.js"); -require("supertokens-web-js"); -require("supertokens-web-js/utils/cookieHandler"); -require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -require("supertokens-web-js/utils/windowHandler"); -require("supertokens-web-js/recipe/multitenancy"); -require("supertokens-web-js/utils"); -require("react"); -require("supertokens-web-js/lib/build/error"); -require("supertokens-web-js/utils/normalisedURLDomain"); -require("supertokens-web-js/utils/normalisedURLPath"); -require("react/jsx-runtime"); -require("supertokens-web-js/recipe/passwordless"); -require("./authRecipe-shared2.js"); -require("./recipeModule-shared.js"); -require("./multifactorauth-shared.js"); -require("supertokens-web-js/recipe/session"); -require("./oauth2provider-shared.js"); -require("supertokens-web-js/recipe/oauth2provider"); -require("./multifactorauth-shared2.js"); -require("supertokens-web-js/recipe/multifactorauth"); -require("supertokens-web-js/utils/sessionClaimValidatorStore"); -require("./authRecipe-shared.js"); +var utils = require('./utils.js'); +var recipe = require('./passwordless-shared.js'); +require('react'); +require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('supertokens-web-js/utils/normalisedURLPath'); +require('supertokens-web-js/utils/windowHandler'); +require('crypto'); +require('./genericComponentOverrideContext.js'); +require('react/jsx-runtime'); +require('supertokens-web-js/recipe/passwordless'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('./authRecipe-shared2.js'); +require('./recipeModule-shared.js'); +require('./superTokens.js'); +require('supertokens-web-js'); +require('supertokens-web-js/recipe/multitenancy'); +require('supertokens-web-js/utils'); +require('./multifactorauth-shared.js'); +require('supertokens-web-js/recipe/session'); +require('./oauth2provider-shared.js'); +require('supertokens-web-js/recipe/oauth2provider'); +require('./multifactorauth-shared2.js'); +require('supertokens-web-js/recipe/multifactorauth'); +require('supertokens-web-js/utils/sessionClaimValidatorStore'); +require('./authRecipe-shared.js'); -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -var Wrapper = /** @class */ (function () { - function Wrapper() {} - Wrapper.init = function (config) { - return recipe.Passwordless.init(config); - }; - Wrapper.signOut = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.Passwordless.getInstanceOrThrow().signOut({ - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }), - ]; - }); - }); - }; - Wrapper.createCode = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.Passwordless.getInstanceOrThrow().webJSRecipe.createCode( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ), - ]; - }); - }); - }; - Wrapper.resendCode = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.Passwordless.getInstanceOrThrow().webJSRecipe.resendCode( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ), - ]; - }); - }); - }; - Wrapper.consumeCode = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.Passwordless.getInstanceOrThrow().webJSRecipe.consumeCode( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ), - ]; - }); - }); - }; - Wrapper.getLinkCodeFromURL = function (input) { - return recipe.Passwordless.getInstanceOrThrow().webJSRecipe.getLinkCodeFromURL( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ); - }; - Wrapper.getPreAuthSessionIdFromURL = function (input) { - return recipe.Passwordless.getInstanceOrThrow().webJSRecipe.getPreAuthSessionIdFromURL( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ); - }; - Wrapper.doesEmailExist = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.Passwordless.getInstanceOrThrow().webJSRecipe.doesEmailExist( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext(input.userContext), - }) - ), - ]; - }); - }); - }; - Wrapper.doesPhoneNumberExist = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.Passwordless.getInstanceOrThrow().webJSRecipe.doesPhoneNumberExist( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext(input.userContext), - }) - ), - ]; - }); - }); - }; - Wrapper.getLoginAttemptInfo = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.Passwordless.getInstanceOrThrow().webJSRecipe.getLoginAttemptInfo( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ), - ]; - }); - }); - }; - Wrapper.setLoginAttemptInfo = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.Passwordless.getInstanceOrThrow().webJSRecipe.setLoginAttemptInfo( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext(input.userContext), - }) - ), - ]; - }); - }); - }; - Wrapper.clearLoginAttemptInfo = function (input) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - return [ - 2 /*return*/, - recipe.Passwordless.getInstanceOrThrow().webJSRecipe.clearLoginAttemptInfo( - genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, input), { - userContext: genericComponentOverrideContext.getNormalisedUserContext( - input === null || input === void 0 ? void 0 : input.userContext - ), - }) - ), - ]; - }); - }); - }; - Wrapper.ComponentsOverrideProvider = recipe.Provider; - return Wrapper; -})(); -var init = Wrapper.init; -var createCode = Wrapper.createCode; -var resendCode = Wrapper.resendCode; -var consumeCode = Wrapper.consumeCode; -var getLinkCodeFromURL = Wrapper.getLinkCodeFromURL; -var getPreAuthSessionIdFromURL = Wrapper.getPreAuthSessionIdFromURL; -var doesEmailExist = Wrapper.doesEmailExist; -var doesPhoneNumberExist = Wrapper.doesPhoneNumberExist; -var getLoginAttemptInfo = Wrapper.getLoginAttemptInfo; -var setLoginAttemptInfo = Wrapper.setLoginAttemptInfo; -var clearLoginAttemptInfo = Wrapper.clearLoginAttemptInfo; -var signOut = Wrapper.signOut; +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +var Wrapper = /** @class */ (function () { + function Wrapper() { + } + Wrapper.init = function (config) { + return recipe.Passwordless.init(config); + }; + Wrapper.signOut = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.Passwordless.getInstanceOrThrow().signOut({ + userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext), + })]; + }); + }); + }; + Wrapper.createCode = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.Passwordless.getInstanceOrThrow().webJSRecipe.createCode(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) }))]; + }); + }); + }; + Wrapper.resendCode = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.Passwordless.getInstanceOrThrow().webJSRecipe.resendCode(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) }))]; + }); + }); + }; + Wrapper.consumeCode = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.Passwordless.getInstanceOrThrow().webJSRecipe.consumeCode(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) }))]; + }); + }); + }; + Wrapper.getLinkCodeFromURL = function (input) { + return recipe.Passwordless.getInstanceOrThrow().webJSRecipe.getLinkCodeFromURL(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) })); + }; + Wrapper.getPreAuthSessionIdFromURL = function (input) { + return recipe.Passwordless.getInstanceOrThrow().webJSRecipe.getPreAuthSessionIdFromURL(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) })); + }; + Wrapper.doesEmailExist = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.Passwordless.getInstanceOrThrow().webJSRecipe.doesEmailExist(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input.userContext) }))]; + }); + }); + }; + Wrapper.doesPhoneNumberExist = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.Passwordless.getInstanceOrThrow().webJSRecipe.doesPhoneNumberExist(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input.userContext) }))]; + }); + }); + }; + Wrapper.getLoginAttemptInfo = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.Passwordless.getInstanceOrThrow().webJSRecipe.getLoginAttemptInfo(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) }))]; + }); + }); + }; + Wrapper.setLoginAttemptInfo = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.Passwordless.getInstanceOrThrow().webJSRecipe.setLoginAttemptInfo(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input.userContext) }))]; + }); + }); + }; + Wrapper.clearLoginAttemptInfo = function (input) { + return utils.__awaiter(this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + return [2 /*return*/, recipe.Passwordless.getInstanceOrThrow().webJSRecipe.clearLoginAttemptInfo(utils.__assign(utils.__assign({}, input), { userContext: utils.getNormalisedUserContext(input === null || input === void 0 ? void 0 : input.userContext) }))]; + }); + }); + }; + Wrapper.ComponentsOverrideProvider = recipe.Provider; + return Wrapper; +}()); +var init = Wrapper.init; +var createCode = Wrapper.createCode; +var resendCode = Wrapper.resendCode; +var consumeCode = Wrapper.consumeCode; +var getLinkCodeFromURL = Wrapper.getLinkCodeFromURL; +var getPreAuthSessionIdFromURL = Wrapper.getPreAuthSessionIdFromURL; +var doesEmailExist = Wrapper.doesEmailExist; +var doesPhoneNumberExist = Wrapper.doesPhoneNumberExist; +var getLoginAttemptInfo = Wrapper.getLoginAttemptInfo; +var setLoginAttemptInfo = Wrapper.setLoginAttemptInfo; +var clearLoginAttemptInfo = Wrapper.clearLoginAttemptInfo; +var signOut = Wrapper.signOut; var PasswordlessComponentsOverrideProvider = Wrapper.ComponentsOverrideProvider; exports.PasswordlessComponentsOverrideProvider = PasswordlessComponentsOverrideProvider; diff --git a/lib/build/passwordlessprebuiltui.js b/lib/build/passwordlessprebuiltui.js index cc9c4bf3b..47b765384 100644 --- a/lib/build/passwordlessprebuiltui.js +++ b/lib/build/passwordlessprebuiltui.js @@ -1,76 +1,69 @@ -"use strict"; +'use strict'; -var genericComponentOverrideContext = require("./genericComponentOverrideContext.js"); -var React = require("react"); -var jsxRuntime = require("react/jsx-runtime"); -var NormalisedURLPath = require("supertokens-web-js/utils/normalisedURLPath"); -var uiEntry = require("./index2.js"); -var recipe$3 = require("./emailpassword-shared3.js"); -require("./multifactorauth.js"); -var session = require("./session.js"); -var recipe$1 = require("./passwordless-shared.js"); -var authCompWrapper = require("./authCompWrapper.js"); -var button = require("./emailpassword-shared.js"); -var translationContext = require("./translationContext.js"); -var STGeneralError = require("supertokens-web-js/utils/error"); -var types = require("./multifactorauth-shared.js"); -var emailverification = require("./emailverification.js"); -var recipe = require("./emailverification-shared.js"); -var arrowLeftIcon = require("./arrowLeftIcon.js"); -var emailLargeIcon = require("./emailLargeIcon.js"); -var windowHandler = require("supertokens-web-js/utils/windowHandler"); -var recipe$2 = require("./multifactorauth-shared2.js"); -var sessionprebuiltui = require("./sessionprebuiltui.js"); -var formBase = require("./emailpassword-shared6.js"); -var validators = require("./emailpassword-shared5.js"); -var STGeneralError$1 = require("supertokens-web-js/lib/build/error"); -require("supertokens-web-js"); -require("supertokens-web-js/utils/cookieHandler"); -require("supertokens-web-js/utils/postSuperTokensInitCallbacks"); -require("supertokens-web-js/recipe/multitenancy"); -require("supertokens-web-js/utils"); -require("supertokens-web-js/utils/normalisedURLDomain"); -require("react-dom"); -require("./multitenancy-shared.js"); -require("./oauth2provider-shared.js"); -require("supertokens-web-js/recipe/oauth2provider"); -require("./recipeModule-shared.js"); -require("./authRecipe-shared.js"); -require("supertokens-web-js/lib/build/normalisedURLPath"); -require("supertokens-web-js/recipe/emailpassword"); -require("./authRecipe-shared2.js"); -require("./emailpassword-shared4.js"); -require("./multifactorauth-shared3.js"); -require("supertokens-web-js/recipe/session"); -require("./session-shared.js"); -require("supertokens-web-js/recipe/passwordless"); -require("supertokens-web-js/recipe/emailverification"); -require("supertokens-web-js/utils/sessionClaimValidatorStore"); -require("supertokens-web-js/recipe/multifactorauth"); +var utils = require('./utils.js'); +var React = require('react'); +var jsxRuntime = require('react/jsx-runtime'); +var NormalisedURLPath = require('supertokens-web-js/utils/normalisedURLPath'); +var uiEntry = require('./index2.js'); +var recipe$3 = require('./emailpassword-shared3.js'); +require('./multifactorauth.js'); +var session = require('./session.js'); +var recipe$1 = require('./passwordless-shared.js'); +var authCompWrapper = require('./authCompWrapper.js'); +var superTokens = require('./superTokens.js'); +var button = require('./emailpassword-shared.js'); +var translationContext = require('./translationContext.js'); +var STGeneralError = require('supertokens-web-js/utils/error'); +var types = require('./multifactorauth-shared.js'); +var emailverification = require('./emailverification.js'); +var recipe = require('./emailverification-shared.js'); +var arrowLeftIcon = require('./arrowLeftIcon.js'); +var emailLargeIcon = require('./emailLargeIcon.js'); +var windowHandler = require('supertokens-web-js/utils/windowHandler'); +var recipe$2 = require('./multifactorauth-shared2.js'); +var sessionprebuiltui = require('./sessionprebuiltui.js'); +var formBase = require('./emailpassword-shared6.js'); +var validators = require('./emailpassword-shared5.js'); +var STGeneralError$1 = require('supertokens-web-js/lib/build/error'); +require('supertokens-web-js/utils/cookieHandler'); +require('supertokens-web-js/utils/normalisedURLDomain'); +require('crypto'); +require('react-dom'); +require('./multitenancy-shared.js'); +require('./genericComponentOverrideContext.js'); +require('./oauth2provider-shared.js'); +require('supertokens-web-js/recipe/oauth2provider'); +require('./recipeModule-shared.js'); +require('./authRecipe-shared.js'); +require('supertokens-web-js/lib/build/normalisedURLPath'); +require('supertokens-web-js/recipe/emailpassword'); +require('./authRecipe-shared2.js'); +require('./emailpassword-shared4.js'); +require('./multifactorauth-shared3.js'); +require('supertokens-web-js/recipe/session'); +require('./session-shared.js'); +require('supertokens-web-js/recipe/passwordless'); +require('supertokens-web-js/utils/postSuperTokensInitCallbacks'); +require('supertokens-web-js'); +require('supertokens-web-js/recipe/multitenancy'); +require('supertokens-web-js/utils'); +require('supertokens-web-js/recipe/emailverification'); +require('supertokens-web-js/utils/sessionClaimValidatorStore'); +require('supertokens-web-js/recipe/multifactorauth'); -function _interopDefault(e) { - return e && e.__esModule ? e : { default: e }; -} +function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { - if (k !== "default") { + if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty( - n, - k, - d.get - ? d - : { - enumerable: true, - get: function () { - return e[k]; - }, - } - ); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); } }); } @@ -78,1342 +71,698 @@ function _interopNamespace(e) { return Object.freeze(n); } -var React__namespace = /*#__PURE__*/ _interopNamespace(React); -var NormalisedURLPath__default = /*#__PURE__*/ _interopDefault(NormalisedURLPath); -var STGeneralError__default = /*#__PURE__*/ _interopDefault(STGeneralError); -var STGeneralError__default$1 = /*#__PURE__*/ _interopDefault(STGeneralError$1); +var React__namespace = /*#__PURE__*/_interopNamespace(React); +var NormalisedURLPath__default = /*#__PURE__*/_interopDefault(NormalisedURLPath); +var STGeneralError__default = /*#__PURE__*/_interopDefault(STGeneralError); +var STGeneralError__default$1 = /*#__PURE__*/_interopDefault(STGeneralError$1); -var styles = - '/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.\n *\n * This software is licensed under the Apache License, Version 2.0 (the\n * "License") as published by the Apache Software Foundation.\n *\n * You may not use this file except in compliance with the License. You may\n * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n[data-supertokens~="container"] {\n --palette-background: 255, 255, 255;\n --palette-inputBackground: 250, 250, 250;\n --palette-inputBorder: 224, 224, 224;\n --palette-primary: 28, 34, 42;\n --palette-primaryBorder: 45, 54, 68;\n --palette-success: 65, 167, 0;\n --palette-successBackground: 217, 255, 191;\n --palette-error: 255, 23, 23;\n --palette-errorBackground: 255, 241, 235;\n --palette-textTitle: 0, 0, 0;\n --palette-textLabel: 0, 0, 0;\n --palette-textInput: 0, 0, 0;\n --palette-textPrimary: 128, 128, 128;\n --palette-textLink: 0, 122, 255;\n --palette-buttonText: 255, 255, 255;\n --palette-textGray: 54, 54, 54;\n --palette-superTokensBrandingBackground: 242, 245, 246;\n --palette-superTokensBrandingText: 173, 189, 196;\n --palette-buttonGreyedOut: 221, 221, 221;\n --palette-caution: 124, 96, 62;\n --palette-errorDark: 207, 54, 68;\n\n --font-size-0: 12px;\n --font-size-1: 14px;\n --font-size-2: 16px;\n --font-size-3: 19px;\n --font-size-4: 24px;\n --font-size-5: 28px;\n}\n\n/*\n * Default styles.\n */\n\n@keyframes slideTop {\n 0% {\n transform: translateY(-5px);\n }\n 100% {\n transform: translateY(0px);\n }\n}\n\n@keyframes swing-in-top-fwd {\n 0% {\n transform: rotateX(-100deg);\n transform-origin: top;\n opacity: 0;\n }\n 100% {\n transform: rotateX(0deg);\n transform-origin: top;\n opacity: 1;\n }\n}\n\n[data-supertokens~="container"] {\n font-family: "Arial", sans-serif;\n margin: 12px auto;\n margin-top: 26px;\n margin-bottom: 26px;\n width: 420px;\n text-align: center;\n border-radius: 8px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.16);\n background-color: rgb(var(--palette-background));\n}\n\n@media (max-width: 440px) {\n [data-supertokens~="container"] {\n width: 95vw;\n }\n}\n\n[data-supertokens~="row"] {\n margin: 0 auto;\n width: 76%;\n padding-top: 30px;\n padding-bottom: 10px;\n}\n\n[data-supertokens~="superTokensBranding"] {\n display: block;\n margin: 10px auto 0;\n background: rgb(var(--palette-superTokensBrandingBackground));\n color: rgb(var(--palette-superTokensBrandingText));\n text-decoration: none;\n width: -webkit-fit-content;\n width: fit-content;\n border-radius: 6px 6px 0 0;\n padding: 4px 9px;\n font-weight: 400;\n font-size: var(--font-size-0);\n letter-spacing: 0.4px;\n}\n\n[data-supertokens~="generalError"] {\n background: rgb(var(--palette-errorBackground));\n padding-top: 10px;\n padding-bottom: 10px;\n margin-bottom: 10px;\n margin-top: 24px;\n padding-left: 18px;\n padding-right: 18px;\n letter-spacing: 0.2px;\n font-size: var(--font-size-1);\n border-radius: 8px;\n color: rgb(var(--palette-error));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n word-wrap: break-word;\n}\n\n[data-supertokens~="headerTitle"] {\n font-size: var(--font-size-4);\n line-height: 27.6px;\n letter-spacing: 0.58px;\n font-weight: 700;\n margin-bottom: 20px;\n color: rgb(var(--palette-textTitle));\n}\n\n[data-supertokens~="headerSubtitle"] {\n font-weight: 400;\n color: rgb(var(--palette-textGray));\n margin-bottom: 21px;\n}\n\n[data-supertokens~="headerSubtitle"][data-supertokens~="secondaryText"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n}\n\n[data-supertokens~="privacyPolicyAndTermsAndConditions"] {\n max-width: 300px;\n margin-top: 10px;\n}\n\n[data-supertokens~="privacyPolicyAndTermsAndConditions"] a {\n line-height: 21px;\n}\n\n/* TODO: split the link style into separate things*/\n\n/* We add this before primary and secondary text, because if they are applied to the same element the other ones take priority */\n\n[data-supertokens~="link"] {\n padding-left: 3px;\n padding-right: 3px;\n color: rgb(var(--palette-textLink));\n font-size: var(--font-size-1);\n cursor: pointer;\n letter-spacing: 0.16px;\n line-height: 26px;\n}\n\n[data-supertokens~="primaryText"] {\n font-size: var(--font-size-2);\n font-weight: 400;\n letter-spacing: 0.4px;\n line-height: 21px;\n color: rgb(var(--palette-textLabel));\n}\n\n[data-supertokens~="secondaryText"] {\n font-size: var(--font-size-1);\n font-weight: 400;\n letter-spacing: 0.4px;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~="secondaryText"] strong {\n font-weight: 600;\n}\n\n[data-supertokens~="divider"] {\n margin-top: 1.5em;\n margin-bottom: 1.5em;\n border-bottom: 0.3px solid #dddddd;\n align-items: center;\n padding-bottom: 5px;\n flex: 3 3;\n}\n\n[data-supertokens~="headerTinyTitle"] {\n margin-top: 24px;\n font-size: var(--font-size-5);\n letter-spacing: 1.1px;\n font-weight: 700;\n line-height: 28px;\n}\n\n[data-supertokens~="secondaryLinkWithArrow"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n}\n\n[data-supertokens~="secondaryLinkWithArrow"]:hover {\n position: relative;\n left: 2px;\n word-spacing: 4px;\n}\n\n[data-supertokens~="generalSuccess"] {\n color: rgb(var(--palette-success));\n font-size: var(--font-size-1);\n background: rgb(var(--palette-successBackground));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n padding: 9px 15px 9px 15px;\n border-radius: 6px;\n display: inline-block;\n}\n\n[data-supertokens~="spinner"] {\n width: 80px;\n height: auto;\n padding-top: 20px;\n padding-bottom: 40px;\n margin: 0 auto;\n}\n\n[data-supertokens~="error"] {\n color: rgb(var(--palette-error));\n}\n\n[data-supertokens~="linkButton"] {\n font-family: "Arial", sans-serif;\n background-color: transparent;\n border: 0;\n}\n\n[data-supertokens~="secondaryLinkWithLeftArrow"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n margin-top: 10px;\n margin-bottom: 40px;\n cursor: pointer;\n}\n\n[data-supertokens~="secondaryLinkWithLeftArrow"] svg {\n margin-right: 0.3em;\n}\n\n[data-supertokens~="secondaryLinkWithLeftArrow"]:hover svg {\n position: relative;\n left: -4px;\n}\n\n[data-supertokens~="button"] {\n font-family: "Arial", sans-serif;\n background-color: rgb(var(--palette-primary));\n color: rgb(var(--palette-buttonText));\n width: 100%;\n height: 34px;\n font-weight: 600;\n border-width: 1px;\n border-style: solid;\n border-radius: 6px;\n border-color: rgb(var(--palette-primaryBorder));\n background-position: center;\n transition: all 0.4s;\n background-size: 12000%;\n cursor: pointer;\n}\n\n[data-supertokens~="buttonGreyedOut"] {\n background-color: rgb(var(--palette-buttonGreyedOut));\n border-color: rgb(var(--palette-buttonGreyedOut));\n}\n\n[data-supertokens~="buttonWithIcon"] {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n}\n\n[data-supertokens~="button"]:disabled {\n border: none;\n cursor: no-drop;\n}\n\n[data-supertokens~="button"]:active {\n outline: none;\n transition: all 0s;\n background-size: 100%;\n filter: brightness(0.85);\n}\n\n[data-supertokens~="button"]:focus {\n outline: none;\n}\n\n[data-supertokens~="backButtonCommon"] {\n width: 16px;\n height: 13px;\n}\n\n[data-supertokens~="backButton"] {\n cursor: pointer;\n border: none;\n background-color: transparent;\n padding: 0px;\n}\n\n[data-supertokens~="backButtonPlaceholder"] {\n display: block;\n}\n\n[data-supertokens~="delayedRender"] {\n animation-duration: 0.1s;\n animation-name: animate-fade;\n animation-delay: 0.2s;\n animation-fill-mode: backwards;\n}\n\n@keyframes animate-fade {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n\n[data-supertokens~="footerLinkGroupVert"] {\n display: flex;\n flex-direction: column;\n margin-top: 10px;\n gap: 24px;\n}\n\n[data-supertokens~="footerLinkGroupVert"] > div {\n cursor: pointer;\n margin: 0;\n}\n\n[data-supertokens~="footerLinkGroupVert"] [data-supertokens~="secondaryText"] {\n font-weight: 400;\n}\n\n[data-supertokens~="footerLinkGroupVert"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n font-weight: 400;\n position: relative;\n left: -6px; /* half the width of the left arrow */\n}\n\n@media (max-width: 360px) {\n [data-supertokens~="footerLinkGroupVert"] {\n flex-direction: column;\n }\n [data-supertokens~="footerLinkGroupVert"] > div {\n margin: 0 auto;\n }\n}\n\n[data-supertokens~="footerLinkGroupVert"] div:only-child {\n margin-left: auto;\n margin-right: auto;\n margin-top: 14px;\n}\n\n[data-supertokens~="withBackButton"] {\n position: relative;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n[data-supertokens~="dividerWithOr"] {\n padding-top: 5px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~="dividerText"] {\n flex: 1 1;\n font-weight: 400;\n font-size: var(--font-size-1);\n}\n\n[data-supertokens~="formLabelWithLinkWrapper"] {\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n[data-supertokens~="formLabelLinkBtn"] {\n width: auto;\n margin-top: 0;\n line-height: 24px;\n font-size: var(--font-size-0);\n}\n\n[data-supertokens~="formLabelLinkBtn"]:hover {\n text-decoration: underline;\n}\n\n[data-supertokens~="formLabelLinkBtn"]:disabled {\n color: rgb(var(--palette-textPrimary));\n cursor: default;\n text-decoration: none;\n}\n\n[data-supertokens~="authComponentList"] {\n padding-bottom: 20px;\n}\n\n[data-supertokens~="authPageTitleOAuthClient"] {\n color: rgb(var(--palette-textGray));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 10px 0 25px;\n}\n\n[data-supertokens~="authPageTitleOAuthClientUrl"] {\n text-decoration: none;\n}\n\n[data-supertokens~="authPageTitleOAuthClientLogo"] {\n width: 44px;\n height: 44px;\n margin-bottom: 10px;\n}\n\n[data-supertokens~="authPageTitleOAuthClient"] [data-supertokens~="authPageTitleOAuthClientName"] {\n color: rgb(var(--palette-textTitle));\n}\n\n[data-supertokens~="buttonWithArrow"] {\n border-radius: 6px;\n border: 1px solid #d0d5dd;\n width: 100%;\n color: rgb(var(--palette-textGray));\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n margin: 24px 0;\n min-height: 48px;\n cursor: pointer;\n}\n\n[data-supertokens~="buttonWithArrow"]:hover {\n background-color: rgb(var(--palette-inputBackground));\n}\n\n[data-supertokens~="buttonWithArrow"] [data-supertokens~="secondaryText"] {\n font-weight: 700;\n font-size: var(--font-size-2);\n color: rgb(var(--palette-textGray));\n margin: 0;\n}\n\n[data-supertokens~="buttonWithArrow"]:hover [data-supertokens~="secondaryLinkWithRightArrow"] ~ svg {\n position: relative;\n left: 2px;\n}\n\n[data-supertokens~="buttonWithArrow"]:hover [data-supertokens~="secondaryLinkWithLeftArrow"] svg {\n position: relative;\n left: -2px;\n}\n\n[data-supertokens~="buttonWithArrow"] [data-supertokens~="secondaryLinkWithLeftArrow"] {\n display: flex;\n align-items: center;\n}\n\n/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.\n *\n * This software is licensed under the Apache License, Version 2.0 (the\n * "License") as published by the Apache Software Foundation.\n *\n * You may not use this file except in compliance with the License. You may\n * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n[data-supertokens~="inputContainer"] {\n margin-top: 6px;\n}\n\n[data-supertokens~="inputWrapper"] {\n box-sizing: border-box;\n width: 100%;\n display: flex;\n align-items: center;\n background-color: rgb(var(--palette-inputBackground));\n height: 34px;\n border-radius: 6px;\n border: 1px solid rgb(var(--palette-inputBorder));\n}\n\n[data-supertokens~="inputWrapper"][focus-within] {\n background-color: rgba(var(--palette-inputBackground), 0.25);\n border: 1px solid rgb(var(--palette-primary));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-primary), 0.25);\n outline: none;\n}\n\n[data-supertokens~="inputWrapper"]:focus-within {\n background-color: rgba(var(--palette-inputBackground), 0.25);\n border: 1px solid rgb(var(--palette-primary));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-primary), 0.25);\n outline: none;\n}\n\n[data-supertokens~="inputError"] {\n border: 1px solid rgb(var(--palette-error));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-error), 0.25);\n outline: none;\n}\n\n[data-supertokens~="inputError"][focus-within] {\n border: 1px solid rgb(var(--palette-error));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-error), 0.25);\n outline: none;\n}\n\n[data-supertokens~="inputError"]:focus-within {\n border: 1px solid rgb(var(--palette-error));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-error), 0.25);\n outline: none;\n}\n\n[data-supertokens~="input"] {\n box-sizing: border-box;\n padding-left: 15px;\n filter: none;\n color: rgb(var(--palette-textInput));\n background-color: transparent;\n border-radius: 6px;\n font-size: var(--font-size-1);\n border: none;\n padding-right: 25px;\n letter-spacing: 1.2px;\n flex: 9 1 75%;\n width: 75%;\n height: 32px;\n}\n\n[data-supertokens~="input"]:focus {\n border: none;\n outline: none;\n}\n\n[data-supertokens~="input"]:-webkit-autofill,\n[data-supertokens~="input"]:-webkit-autofill:hover,\n[data-supertokens~="input"]:-webkit-autofill:focus,\n[data-supertokens~="input"]:-webkit-autofill:active {\n -webkit-text-fill-color: rgb(var(--palette-textInput));\n box-shadow: 0 0 0 30px rgb(var(--palette-inputBackground)) inset;\n}\n\n[data-supertokens~="inputAdornment"] {\n justify-content: center;\n margin-right: 5px;\n}\n\n[data-supertokens~="showPassword"] {\n cursor: pointer;\n}\n\n[data-supertokens~="enterEmailSuccessMessage"] {\n margin-top: 15px;\n margin-bottom: 15px;\n word-break: break-word;\n}\n\n[data-supertokens~="submitNewPasswordSuccessMessage"] {\n margin-top: 15px;\n margin-bottom: 15px;\n}\n\n[data-supertokens~="inputErrorMessage"] {\n padding-top: 5px;\n padding-bottom: 5px;\n color: rgb(var(--palette-error));\n line-height: 24px;\n font-weight: 400;\n font-size: var(--font-size-1);\n text-align: left;\n animation: slideTop 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;\n max-width: 330px;\n}\n\n@media (max-width: 440px) {\n [data-supertokens~="inputErrorMessage"] {\n max-width: 250px;\n }\n}\n\n[data-supertokens~="inputErrorSymbol"] {\n margin-right: 5px;\n top: 1px;\n position: relative;\n left: 2px;\n}\n\n[data-supertokens~="label"] {\n text-align: left;\n font-weight: 700;\n font-size: var(--font-size-0);\n line-height: 24px;\n color: rgb(var(--palette-textLabel));\n}\n\n[data-supertokens~="formRow"] {\n display: flex;\n flex-direction: column;\n padding-top: 0px;\n padding-bottom: 20px;\n}\n\n[data-supertokens~="formRow"][data-supertokens~="hasError"] {\n padding-bottom: 0;\n}\n\n[data-supertokens~="formRow"]:last-child {\n padding-bottom: 0;\n}\n\n[data-supertokens~="sendVerifyEmailIcon"] {\n margin-top: 11px;\n}\n\n[data-supertokens~="primaryText"][data-supertokens~="sendVerifyEmailText"] {\n text-align: center;\n letter-spacing: 0.8px;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~="secondaryLinkWithArrow"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n font-weight: 700;\n}\n\n[data-supertokens~="sendVerifyEmailResend"] {\n margin-top: 13px;\n font-weight: 400;\n}\n\n[data-supertokens~="sendVerifyEmailResend"]:hover {\n text-decoration: underline;\n}\n\n[data-supertokens~="noFormRow"] {\n padding-bottom: 25px;\n}\n\n[data-supertokens~="emailVerificationButtonWrapper"] {\n padding-top: 25px;\n max-width: 96px;\n margin: 0 auto;\n}\n\n[data-supertokens~="resendEmailLink"] {\n display: inline-block;\n}\n\n[data-supertokens~="resetPasswordEmailForm"] {\n padding-bottom: 20px;\n}\n\n[data-supertokens~="resetPasswordPasswordForm"] {\n padding-bottom: 20px;\n}\n\n[data-supertokens~="generalSuccess"] {\n margin-bottom: 20px;\n animation: swingIn 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) alternate 2 both;\n}\n\n[data-supertokens~="headerSubtitle"] strong {\n max-width: 100%;\n display: inline-block;\n vertical-align: bottom;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n[data-supertokens~="primaryText"][data-supertokens~="sendCodeText"] {\n margin-top: 15px;\n margin-bottom: 20px;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~="sendCodeText"] strong {\n max-width: 100%;\n display: inline-block;\n vertical-align: bottom;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n[data-supertokens~="phoneInputLibRoot"] {\n display: flex;\n align-items: center;\n}\n\n[data-supertokens~="phoneInputWrapper"] {\n display: flex;\n align-items: center;\n}\n\ninput[type="tel"][data-supertokens~="input-phoneNumber"] {\n padding-left: 15px;\n}\n\n[data-supertokens~="phoneInputWrapper"] .iti {\n flex: 1 1;\n min-width: 0;\n width: 100%;\n background: transparent;\n border: none;\n color: inherit;\n outline: none;\n}\n\n[data-supertokens~="continueButtonWrapper"] {\n margin-top: 10px;\n margin-bottom: 30px;\n}\n\n.iti__country-list {\n border: 0;\n top: 40px;\n width: min(72.2vw, 320px);\n border-radius: 6;\n box-shadow: 0px 0px 3px 0px rgba(0, 0, 0, 0.16);\n}\n\n.iti__country {\n display: flex;\n align-items: center;\n height: 34px;\n cursor: pointer;\n\n padding: 0 8px;\n}\n\n.iti__country-name {\n color: var(--palette-textLabel);\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n margin: "0 16px";\n}\n\n[data-supertokens~="continueWithPasswordlessButtonWrapper"] {\n margin: 9px 0;\n}\n\n[data-supertokens~="continueWithPasswordlessLink"] {\n margin-top: 9px;\n}\n'; +var styles = "/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.\n *\n * This software is licensed under the Apache License, Version 2.0 (the\n * \"License\") as published by the Apache Software Foundation.\n *\n * You may not use this file except in compliance with the License. You may\n * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n[data-supertokens~=\"container\"] {\n --palette-background: 255, 255, 255;\n --palette-inputBackground: 250, 250, 250;\n --palette-inputBorder: 224, 224, 224;\n --palette-primary: 28, 34, 42;\n --palette-primaryBorder: 45, 54, 68;\n --palette-success: 65, 167, 0;\n --palette-successBackground: 217, 255, 191;\n --palette-error: 255, 23, 23;\n --palette-errorBackground: 255, 241, 235;\n --palette-textTitle: 0, 0, 0;\n --palette-textLabel: 0, 0, 0;\n --palette-textInput: 0, 0, 0;\n --palette-textPrimary: 128, 128, 128;\n --palette-textLink: 0, 122, 255;\n --palette-buttonText: 255, 255, 255;\n --palette-textGray: 54, 54, 54;\n --palette-superTokensBrandingBackground: 242, 245, 246;\n --palette-superTokensBrandingText: 173, 189, 196;\n --palette-buttonGreyedOut: 221, 221, 221;\n --palette-caution: 124, 96, 62;\n --palette-errorDark: 207, 54, 68;\n\n --font-size-0: 12px;\n --font-size-1: 14px;\n --font-size-2: 16px;\n --font-size-3: 19px;\n --font-size-4: 24px;\n --font-size-5: 28px;\n}\n\n/*\n * Default styles.\n */\n\n@keyframes slideTop {\n 0% {\n transform: translateY(-5px);\n }\n 100% {\n transform: translateY(0px);\n }\n}\n\n@keyframes swing-in-top-fwd {\n 0% {\n transform: rotateX(-100deg);\n transform-origin: top;\n opacity: 0;\n }\n 100% {\n transform: rotateX(0deg);\n transform-origin: top;\n opacity: 1;\n }\n}\n\n[data-supertokens~=\"container\"] {\n font-family: \"Arial\", sans-serif;\n margin: 12px auto;\n margin-top: 26px;\n margin-bottom: 26px;\n width: 420px;\n text-align: center;\n border-radius: 8px;\n box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.16);\n background-color: rgb(var(--palette-background));\n}\n\n@media (max-width: 440px) {\n [data-supertokens~=\"container\"] {\n width: 95vw;\n }\n}\n\n[data-supertokens~=\"row\"] {\n margin: 0 auto;\n width: 76%;\n padding-top: 30px;\n padding-bottom: 10px;\n}\n\n[data-supertokens~=\"superTokensBranding\"] {\n display: block;\n margin: 10px auto 0;\n background: rgb(var(--palette-superTokensBrandingBackground));\n color: rgb(var(--palette-superTokensBrandingText));\n text-decoration: none;\n width: -webkit-fit-content;\n width: -moz-fit-content;\n width: fit-content;\n border-radius: 6px 6px 0 0;\n padding: 4px 9px;\n font-weight: 400;\n font-size: var(--font-size-0);\n letter-spacing: 0.4px;\n}\n\n[data-supertokens~=\"generalError\"] {\n background: rgb(var(--palette-errorBackground));\n padding-top: 10px;\n padding-bottom: 10px;\n margin-bottom: 10px;\n margin-top: 24px;\n padding-left: 18px;\n padding-right: 18px;\n letter-spacing: 0.2px;\n font-size: var(--font-size-1);\n border-radius: 8px;\n color: rgb(var(--palette-error));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n word-wrap: break-word;\n}\n\n[data-supertokens~=\"headerTitle\"] {\n font-size: var(--font-size-4);\n line-height: 27.6px;\n letter-spacing: 0.58px;\n font-weight: 700;\n margin-bottom: 20px;\n color: rgb(var(--palette-textTitle));\n}\n\n[data-supertokens~=\"headerSubtitle\"] {\n font-weight: 400;\n color: rgb(var(--palette-textGray));\n margin-bottom: 21px;\n}\n\n[data-supertokens~=\"headerSubtitle\"][data-supertokens~=\"secondaryText\"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n}\n\n[data-supertokens~=\"privacyPolicyAndTermsAndConditions\"] {\n max-width: 300px;\n margin-top: 10px;\n}\n\n[data-supertokens~=\"privacyPolicyAndTermsAndConditions\"] a {\n line-height: 21px;\n}\n\n/* TODO: split the link style into separate things*/\n\n/* We add this before primary and secondary text, because if they are applied to the same element the other ones take priority */\n\n[data-supertokens~=\"link\"] {\n padding-left: 3px;\n padding-right: 3px;\n color: rgb(var(--palette-textLink));\n font-size: var(--font-size-1);\n cursor: pointer;\n letter-spacing: 0.16px;\n line-height: 26px;\n}\n\n[data-supertokens~=\"primaryText\"] {\n font-size: var(--font-size-2);\n font-weight: 400;\n letter-spacing: 0.4px;\n line-height: 21px;\n color: rgb(var(--palette-textLabel));\n}\n\n[data-supertokens~=\"secondaryText\"] {\n font-size: var(--font-size-1);\n font-weight: 400;\n letter-spacing: 0.4px;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~=\"secondaryText\"] strong {\n font-weight: 600;\n}\n\n[data-supertokens~=\"divider\"] {\n margin-top: 1.5em;\n margin-bottom: 1.5em;\n border-bottom: 0.3px solid #dddddd;\n align-items: center;\n padding-bottom: 5px;\n flex: 3 3;\n}\n\n[data-supertokens~=\"headerTinyTitle\"] {\n margin-top: 24px;\n font-size: var(--font-size-5);\n letter-spacing: 1.1px;\n font-weight: 700;\n line-height: 28px;\n}\n\n[data-supertokens~=\"secondaryLinkWithArrow\"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n}\n\n[data-supertokens~=\"secondaryLinkWithArrow\"]:hover {\n position: relative;\n left: 2px;\n word-spacing: 4px;\n}\n\n[data-supertokens~=\"generalSuccess\"] {\n color: rgb(var(--palette-success));\n font-size: var(--font-size-1);\n background: rgb(var(--palette-successBackground));\n animation: swing-in-top-fwd 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) both;\n padding: 9px 15px 9px 15px;\n border-radius: 6px;\n display: inline-block;\n}\n\n[data-supertokens~=\"spinner\"] {\n width: 80px;\n height: auto;\n padding-top: 20px;\n padding-bottom: 40px;\n margin: 0 auto;\n}\n\n[data-supertokens~=\"error\"] {\n color: rgb(var(--palette-error));\n}\n\n[data-supertokens~=\"linkButton\"] {\n font-family: \"Arial\", sans-serif;\n background-color: transparent;\n border: 0;\n}\n\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n color: rgb(var(--palette-textGray));\n font-weight: 400;\n margin-top: 10px;\n margin-bottom: 40px;\n cursor: pointer;\n}\n\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"] svg {\n margin-right: 0.3em;\n}\n\n[data-supertokens~=\"secondaryLinkWithLeftArrow\"]:hover svg {\n position: relative;\n left: -4px;\n}\n\n[data-supertokens~=\"button\"] {\n font-family: \"Arial\", sans-serif;\n background-color: rgb(var(--palette-primary));\n color: rgb(var(--palette-buttonText));\n width: 100%;\n height: 34px;\n font-weight: 600;\n border-width: 1px;\n border-style: solid;\n border-radius: 6px;\n border-color: rgb(var(--palette-primaryBorder));\n background-position: center;\n transition: all 0.4s;\n background-size: 12000%;\n cursor: pointer;\n}\n\n[data-supertokens~=\"buttonGreyedOut\"] {\n background-color: rgb(var(--palette-buttonGreyedOut));\n border-color: rgb(var(--palette-buttonGreyedOut));\n}\n\n[data-supertokens~=\"buttonWithIcon\"] {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n}\n\n[data-supertokens~=\"button\"]:disabled {\n border: none;\n cursor: no-drop;\n}\n\n[data-supertokens~=\"button\"]:active {\n outline: none;\n transition: all 0s;\n background-size: 100%;\n filter: brightness(0.85);\n}\n\n[data-supertokens~=\"button\"]:focus {\n outline: none;\n}\n\n[data-supertokens~=\"backButtonCommon\"] {\n width: 16px;\n height: 13px;\n}\n\n[data-supertokens~=\"backButton\"] {\n cursor: pointer;\n border: none;\n background-color: transparent;\n padding: 0px;\n}\n\n[data-supertokens~=\"backButtonPlaceholder\"] {\n display: block;\n}\n\n[data-supertokens~=\"delayedRender\"] {\n animation-duration: 0.1s;\n animation-name: animate-fade;\n animation-delay: 0.2s;\n animation-fill-mode: backwards;\n}\n\n@keyframes animate-fade {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] {\n display: flex;\n flex-direction: column;\n margin-top: 10px;\n gap: 24px;\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] > div {\n cursor: pointer;\n margin: 0;\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] [data-supertokens~=\"secondaryText\"] {\n font-weight: 400;\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n font-weight: 400;\n position: relative;\n left: -6px; /* half the width of the left arrow */\n}\n\n@media (max-width: 360px) {\n [data-supertokens~=\"footerLinkGroupVert\"] {\n flex-direction: column;\n }\n [data-supertokens~=\"footerLinkGroupVert\"] > div {\n margin: 0 auto;\n }\n}\n\n[data-supertokens~=\"footerLinkGroupVert\"] div:only-child {\n margin-left: auto;\n margin-right: auto;\n margin-top: 14px;\n}\n\n[data-supertokens~=\"withBackButton\"] {\n position: relative;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n[data-supertokens~=\"dividerWithOr\"] {\n padding-top: 5px;\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~=\"dividerText\"] {\n flex: 1 1;\n font-weight: 400;\n font-size: var(--font-size-1);\n}\n\n[data-supertokens~=\"formLabelWithLinkWrapper\"] {\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n\n[data-supertokens~=\"formLabelLinkBtn\"] {\n width: auto;\n margin-top: 0;\n line-height: 24px;\n font-size: var(--font-size-0);\n}\n\n[data-supertokens~=\"formLabelLinkBtn\"]:hover {\n text-decoration: underline;\n}\n\n[data-supertokens~=\"formLabelLinkBtn\"]:disabled {\n color: rgb(var(--palette-textPrimary));\n cursor: default;\n text-decoration: none;\n}\n\n[data-supertokens~=\"authComponentList\"] {\n padding-bottom: 20px;\n}\n\n[data-supertokens~=\"authPageTitleOAuthClient\"] {\n color: rgb(var(--palette-textGray));\n font-size: var(--font-size-1);\n font-weight: 400;\n margin: 10px 0 25px;\n}\n\n[data-supertokens~=\"authPageTitleOAuthClientUrl\"] {\n text-decoration: none;\n}\n\n[data-supertokens~=\"authPageTitleOAuthClientLogo\"] {\n width: 44px;\n height: 44px;\n margin-bottom: 10px;\n}\n\n[data-supertokens~=\"authPageTitleOAuthClient\"] [data-supertokens~=\"authPageTitleOAuthClientName\"] {\n color: rgb(var(--palette-textTitle));\n}\n\n[data-supertokens~=\"buttonWithArrow\"] {\n border-radius: 6px;\n border: 1px solid #d0d5dd;\n width: 100%;\n color: rgb(var(--palette-textGray));\n display: flex;\n justify-content: center;\n align-items: center;\n gap: 5px;\n margin: 24px 0;\n min-height: 48px;\n cursor: pointer;\n}\n\n[data-supertokens~=\"buttonWithArrow\"]:hover {\n background-color: rgb(var(--palette-inputBackground));\n}\n\n[data-supertokens~=\"buttonWithArrow\"] [data-supertokens~=\"secondaryText\"] {\n font-weight: 700;\n font-size: var(--font-size-2);\n color: rgb(var(--palette-textGray));\n margin: 0;\n}\n\n[data-supertokens~=\"buttonWithArrow\"]:hover [data-supertokens~=\"secondaryLinkWithRightArrow\"] ~ svg {\n position: relative;\n left: 2px;\n}\n\n[data-supertokens~=\"buttonWithArrow\"]:hover [data-supertokens~=\"secondaryLinkWithLeftArrow\"] svg {\n position: relative;\n left: -2px;\n}\n\n[data-supertokens~=\"buttonWithArrow\"] [data-supertokens~=\"secondaryLinkWithLeftArrow\"] {\n display: flex;\n align-items: center;\n}\n\n/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved.\n *\n * This software is licensed under the Apache License, Version 2.0 (the\n * \"License\") as published by the Apache Software Foundation.\n *\n * You may not use this file except in compliance with the License. You may\n * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n[data-supertokens~=\"inputContainer\"] {\n margin-top: 6px;\n}\n\n[data-supertokens~=\"inputWrapper\"] {\n box-sizing: border-box;\n width: 100%;\n display: flex;\n align-items: center;\n background-color: rgb(var(--palette-inputBackground));\n height: 34px;\n border-radius: 6px;\n border: 1px solid rgb(var(--palette-inputBorder));\n}\n\n[data-supertokens~=\"inputWrapper\"][focus-within] {\n background-color: rgba(var(--palette-inputBackground), 0.25);\n border: 1px solid rgb(var(--palette-primary));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-primary), 0.25);\n outline: none;\n}\n\n[data-supertokens~=\"inputWrapper\"]:focus-within {\n background-color: rgba(var(--palette-inputBackground), 0.25);\n border: 1px solid rgb(var(--palette-primary));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-primary), 0.25);\n outline: none;\n}\n\n[data-supertokens~=\"inputError\"] {\n border: 1px solid rgb(var(--palette-error));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-error), 0.25);\n outline: none;\n}\n\n[data-supertokens~=\"inputError\"][focus-within] {\n border: 1px solid rgb(var(--palette-error));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-error), 0.25);\n outline: none;\n}\n\n[data-supertokens~=\"inputError\"]:focus-within {\n border: 1px solid rgb(var(--palette-error));\n box-shadow: 0 0 0 0.2rem rgba(var(--palette-error), 0.25);\n outline: none;\n}\n\n[data-supertokens~=\"input\"] {\n box-sizing: border-box;\n padding-left: 15px;\n filter: none;\n color: rgb(var(--palette-textInput));\n background-color: transparent;\n border-radius: 6px;\n font-size: var(--font-size-1);\n border: none;\n padding-right: 25px;\n letter-spacing: 1.2px;\n flex: 9 1 75%;\n width: 75%;\n height: 32px;\n}\n\n[data-supertokens~=\"input\"]:focus {\n border: none;\n outline: none;\n}\n\n[data-supertokens~=\"input\"]:-webkit-autofill,\n[data-supertokens~=\"input\"]:-webkit-autofill:hover,\n[data-supertokens~=\"input\"]:-webkit-autofill:focus,\n[data-supertokens~=\"input\"]:-webkit-autofill:active {\n -webkit-text-fill-color: rgb(var(--palette-textInput));\n box-shadow: 0 0 0 30px rgb(var(--palette-inputBackground)) inset;\n}\n\n[data-supertokens~=\"inputAdornment\"] {\n justify-content: center;\n margin-right: 5px;\n}\n\n[data-supertokens~=\"showPassword\"] {\n cursor: pointer;\n}\n\n[data-supertokens~=\"enterEmailSuccessMessage\"] {\n margin-top: 15px;\n margin-bottom: 15px;\n word-break: break-word;\n}\n\n[data-supertokens~=\"submitNewPasswordSuccessMessage\"] {\n margin-top: 15px;\n margin-bottom: 15px;\n}\n\n[data-supertokens~=\"inputErrorMessage\"] {\n padding-top: 5px;\n padding-bottom: 5px;\n color: rgb(var(--palette-error));\n line-height: 24px;\n font-weight: 400;\n font-size: var(--font-size-1);\n text-align: left;\n animation: slideTop 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) both;\n max-width: 330px;\n}\n\n@media (max-width: 440px) {\n [data-supertokens~=\"inputErrorMessage\"] {\n max-width: 250px;\n }\n}\n\n[data-supertokens~=\"inputErrorSymbol\"] {\n margin-right: 5px;\n top: 1px;\n position: relative;\n left: 2px;\n}\n\n[data-supertokens~=\"label\"] {\n text-align: left;\n font-weight: 700;\n font-size: var(--font-size-0);\n line-height: 24px;\n color: rgb(var(--palette-textLabel));\n}\n\n[data-supertokens~=\"formRow\"] {\n display: flex;\n flex-direction: column;\n padding-top: 0px;\n padding-bottom: 20px;\n}\n\n[data-supertokens~=\"formRow\"][data-supertokens~=\"hasError\"] {\n padding-bottom: 0;\n}\n\n[data-supertokens~=\"formRow\"]:last-child {\n padding-bottom: 0;\n}\n\n[data-supertokens~=\"sendVerifyEmailIcon\"] {\n margin-top: 11px;\n}\n\n[data-supertokens~=\"primaryText\"][data-supertokens~=\"sendVerifyEmailText\"] {\n text-align: center;\n letter-spacing: 0.8px;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~=\"secondaryLinkWithArrow\"] {\n margin-top: 10px;\n margin-bottom: 30px;\n cursor: pointer;\n font-weight: 700;\n}\n\n[data-supertokens~=\"sendVerifyEmailResend\"] {\n margin-top: 13px;\n font-weight: 400;\n}\n\n[data-supertokens~=\"sendVerifyEmailResend\"]:hover {\n text-decoration: underline;\n}\n\n[data-supertokens~=\"noFormRow\"] {\n padding-bottom: 25px;\n}\n\n[data-supertokens~=\"emailVerificationButtonWrapper\"] {\n padding-top: 25px;\n max-width: 96px;\n margin: 0 auto;\n}\n\n[data-supertokens~=\"resendEmailLink\"] {\n display: inline-block;\n}\n\n[data-supertokens~=\"resetPasswordEmailForm\"] {\n padding-bottom: 20px;\n}\n\n[data-supertokens~=\"resetPasswordPasswordForm\"] {\n padding-bottom: 20px;\n}\n\n[data-supertokens~=\"generalSuccess\"] {\n margin-bottom: 20px;\n animation: swingIn 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) alternate 2 both;\n}\n\n[data-supertokens~=\"headerSubtitle\"] strong {\n max-width: 100%;\n display: inline-block;\n vertical-align: bottom;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n[data-supertokens~=\"primaryText\"][data-supertokens~=\"sendCodeText\"] {\n margin-top: 15px;\n margin-bottom: 20px;\n color: rgb(var(--palette-textPrimary));\n}\n\n[data-supertokens~=\"sendCodeText\"] strong {\n max-width: 100%;\n display: inline-block;\n vertical-align: bottom;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n[data-supertokens~=\"phoneInputLibRoot\"] {\n display: flex;\n align-items: center;\n}\n\n[data-supertokens~=\"phoneInputWrapper\"] {\n display: flex;\n align-items: center;\n}\n\ninput[type=\"tel\"][data-supertokens~=\"input-phoneNumber\"] {\n padding-left: 15px;\n}\n\n[data-supertokens~=\"phoneInputWrapper\"] .iti {\n flex: 1 1;\n min-width: 0;\n width: 100%;\n background: transparent;\n border: none;\n color: inherit;\n outline: none;\n}\n\n[data-supertokens~=\"continueButtonWrapper\"] {\n margin-top: 10px;\n margin-bottom: 30px;\n}\n\n.iti__country-list {\n border: 0;\n top: 40px;\n width: min(72.2vw, 320px);\n border-radius: 6;\n box-shadow: 0px 0px 3px 0px rgba(0, 0, 0, 0.16);\n}\n\n.iti__country {\n display: flex;\n align-items: center;\n height: 34px;\n cursor: pointer;\n\n padding: 0 8px;\n}\n\n.iti__country-name {\n color: var(--palette-textLabel);\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n margin: \"0 16px\";\n}\n\n[data-supertokens~=\"continueWithPasswordlessButtonWrapper\"] {\n margin: 9px 0;\n}\n\n[data-supertokens~=\"continueWithPasswordlessLink\"] {\n margin-top: 9px;\n}\n"; -var ThemeBase = function (_a) { - var children = _a.children, - userStyles = _a.userStyles; - return jsxRuntime.jsxs(React.Fragment, { - children: [children, jsxRuntime.jsxs("style", { children: [styles, userStyles.join("\n")] })], - }); +var ThemeBase = function (_a) { + var children = _a.children, userStyles = _a.userStyles; + return (jsxRuntime.jsxs(React.Fragment, { children: [children, jsxRuntime.jsxs("style", { children: [styles, userStyles.join("\n")] })] })); }; -var ContinueWithPasswordless = function (props) { - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "continueWithPasswordlessButtonWrapper" }, - { - children: jsxRuntime.jsx(button.Button, { - isLoading: false, - onClick: function () { - props.continueWithPasswordlessClicked(); - }, - type: "button", - label: "PWLESS_COMBO_CONTINUE_WITH_PASSWORDLESS_BUTTON", - }), - } - ) - ); -}; -var ContinueWithPasswordlessWithOverride = uiEntry.withOverride( - "PasswordlessContinueWithPasswordless", - ContinueWithPasswordless -); -var ContinueWithPasswordlessTheme = function (props) { - var rootStyle = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().rootStyle; - return jsxRuntime.jsx( - ThemeBase, - genericComponentOverrideContext.__assign( - { userStyles: [rootStyle, props.config.recipeRootStyle] }, - { - children: jsxRuntime.jsx( - ContinueWithPasswordlessWithOverride, - genericComponentOverrideContext.__assign({}, props) - ), - } - ) - ); +var ContinueWithPasswordless = function (props) { + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "continueWithPasswordlessButtonWrapper" }, { children: jsxRuntime.jsx(button.Button, { isLoading: false, onClick: function () { + props.continueWithPasswordlessClicked(); + }, type: "button", label: "PWLESS_COMBO_CONTINUE_WITH_PASSWORDLESS_BUTTON" }) }))); +}; +var ContinueWithPasswordlessWithOverride = uiEntry.withOverride("PasswordlessContinueWithPasswordless", ContinueWithPasswordless); +var ContinueWithPasswordlessTheme = function (props) { + var rootStyle = superTokens.SuperTokens.getInstanceOrThrow().rootStyle; + return (jsxRuntime.jsx(ThemeBase, utils.__assign({ userStyles: [rootStyle, props.config.recipeRootStyle] }, { children: jsxRuntime.jsx(ContinueWithPasswordlessWithOverride, utils.__assign({}, props)) }))); }; -var ContinueWithPasswordlessFeature = function (props) { - var recipeComponentOverrides = props.useComponentOverrides(); - return jsxRuntime.jsx( - authCompWrapper.AuthComponentWrapper, - genericComponentOverrideContext.__assign( - { recipeComponentOverrides: recipeComponentOverrides }, - { - children: jsxRuntime.jsx( - ContinueWithPasswordlessTheme, - genericComponentOverrideContext.__assign({}, props, { - continueWithPasswordlessClicked: function () { - return props.setFactorList(props.factorIds); - }, - config: props.recipe.config, - }) - ), - } - ) - ); +var ContinueWithPasswordlessFeature = function (props) { + var recipeComponentOverrides = props.useComponentOverrides(); + return (jsxRuntime.jsx(authCompWrapper.AuthComponentWrapper, utils.__assign({ recipeComponentOverrides: recipeComponentOverrides }, { children: jsxRuntime.jsx(ContinueWithPasswordlessTheme, utils.__assign({}, props, { continueWithPasswordlessClicked: function () { return props.setFactorList(props.factorIds); }, config: props.recipe.config })) }))); }; -var PasswordlessLinkClickedScreen = function (props) { - var t = translationContext.useTranslation(); - var _a = React.useState(false), - loading = _a[0], - setLoading = _a[1]; - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container" }, - { - children: jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row" }, - { - children: - props.requireUserInteraction === true - ? jsxRuntime.jsxs(React__namespace.default.Fragment, { - children: [ - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle" }, - { children: t("PWLESS_LINK_CLICKED_CONTINUE_HEADER") } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerSubtitle secondaryText" }, - { children: t("PWLESS_LINK_CLICKED_CONTINUE_DESC") } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "continueButtonWrapper" }, - { - children: jsxRuntime.jsx(button.Button, { - isLoading: loading, - onClick: function () { - setLoading(true); - props.consumeCode(); - }, - type: "button", - label: "PWLESS_LINK_CLICKED_CONTINUE_BUTTON", - }), - } - ) - ), - ], - }) - : jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "spinner" }, - { children: jsxRuntime.jsx(uiEntry.SpinnerIcon, {}) } - ) - ), - } - ) - ), - } - ) - ); -}; -var LinkClickedScreenWithOverride = uiEntry.withOverride( - "PasswordlessLinkClickedScreen", - PasswordlessLinkClickedScreen -); -var LinkClickedScreen$1 = function (props) { - var rootStyle = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().rootStyle; - return jsxRuntime.jsx( - ThemeBase, - genericComponentOverrideContext.__assign( - { userStyles: [rootStyle, props.config.recipeRootStyle, props.config.linkClickedScreenFeature.style] }, - { - children: jsxRuntime.jsx( - LinkClickedScreenWithOverride, - genericComponentOverrideContext.__assign({}, props) - ), - } - ) - ); +var PasswordlessLinkClickedScreen = function (props) { + var t = translationContext.useTranslation(); + var _a = React.useState(false), loading = _a[0], setLoading = _a[1]; + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container" }, { children: jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "row" }, { children: props.requireUserInteraction === true ? (jsxRuntime.jsxs(React__namespace.default.Fragment, { children: [jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerTitle" }, { children: t("PWLESS_LINK_CLICKED_CONTINUE_HEADER") })), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerSubtitle secondaryText" }, { children: t("PWLESS_LINK_CLICKED_CONTINUE_DESC") })), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "continueButtonWrapper" }, { children: jsxRuntime.jsx(button.Button, { isLoading: loading, onClick: function () { + setLoading(true); + props.consumeCode(); + }, type: "button", label: "PWLESS_LINK_CLICKED_CONTINUE_BUTTON" }) }))] })) : (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "spinner" }, { children: jsxRuntime.jsx(uiEntry.SpinnerIcon, {}) }))) })) }))); +}; +var LinkClickedScreenWithOverride = uiEntry.withOverride("PasswordlessLinkClickedScreen", PasswordlessLinkClickedScreen); +var LinkClickedScreen$1 = function (props) { + var rootStyle = superTokens.SuperTokens.getInstanceOrThrow().rootStyle; + return (jsxRuntime.jsx(ThemeBase, utils.__assign({ userStyles: [rootStyle, props.config.recipeRootStyle, props.config.linkClickedScreenFeature.style] }, { children: jsxRuntime.jsx(LinkClickedScreenWithOverride, utils.__assign({}, props)) }))); }; -var defaultTranslationsPasswordless = { - en: genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, uiEntry.defaultTranslationsCommon.en), - { - GENERAL_ERROR_EMAIL_UNDEFINED: "Please set your email", - GENERAL_ERROR_EMAIL_NON_STRING: "Email must be of type string", - GENERAL_ERROR_EMAIL_INVALID: "Email is invalid", - GENERAL_ERROR_PHONE_UNDEFINED: "Please set your phone number", - GENERAL_ERROR_PHONE_NON_STRING: "Phone number must be of type string", - GENERAL_ERROR_PHONE_INVALID: "Phone number is invalid", - GENERAL_ERROR_OTP_UNDEFINED: "Please fill your OTP", - GENERAL_ERROR_OTP_INVALID: "Invalid OTP", - GENERAL_ERROR_OTP_EXPIRED: "Expired OTP.", - GENERAL_ERROR_OTP_NON_STRING: "OTP must be of type string", - GENERAL_ERROR_OTP_EMPTY: "OTP cannot be empty", - ERROR_SIGN_IN_UP_LINK: "Invalid magic link. Please try again.", - ERROR_SIGN_IN_UP_RESEND_RESTART_FLOW: "Login timed out. Please try again.", - ERROR_SIGN_IN_UP_CODE_CONSUME_RESTART_FLOW: "Login unsuccessful. Please try again.", - PWLESS_SIGN_IN_UP_EMAIL_LABEL: "Email", - PWLESS_SIGN_IN_UP_PHONE_LABEL: "Phone Number", - PWLESS_SIGN_IN_UP_SWITCH_TO_PHONE: "Use a Phone number", - PWLESS_SIGN_IN_UP_SWITCH_TO_EMAIL: "Use an Email", - PWLESS_SIGN_IN_UP_CONTINUE_BUTTON: "CONTINUE", - PWLESS_COMBO_CONTINUE_WITH_PASSWORDLESS_LINK: "Continue with passwordless", - PWLESS_COMBO_CONTINUE_WITH_PASSWORDLESS_BUTTON: "CONTINUE WITH PASSWORDLESS", - PWLESS_COMBO_PASSWORD_LABEL: "Password", - PWLESS_COMBO_FORGOT_PW_LINK: "Forgot password?", - PWLESS_LINK_SENT_RESEND_SUCCESS: "Link resent", - PWLESS_LINK_SENT_RESEND_TITLE: "Link sent!", - PWLESS_LINK_SENT_RESEND_DESC_START_EMAIL: "We sent a link to ", - PWLESS_LINK_SENT_RESEND_DESC_START_PHONE: "We sent a link to your phone number ", - PWLESS_LINK_SENT_RESEND_DESC_END_EMAIL: ". Click the link to login or sign up", - PWLESS_LINK_SENT_RESEND_DESC_END_PHONE: "", - PWLESS_SIGN_IN_UP_CHANGE_CONTACT_INFO_EMAIL: "Change email", - PWLESS_SIGN_IN_UP_CHANGE_CONTACT_INFO_PHONE: "Change phone number", - PWLESS_LINK_CLICKED_CONTINUE_HEADER: "Sign Up or Log In", - PWLESS_LINK_CLICKED_CONTINUE_DESC: "Click the button below to log in on this device", - PWLESS_LINK_CLICKED_CONTINUE_BUTTON: "CONTINUE", - PWLESS_RESEND_SUCCESS_EMAIL: "Email resent", - PWLESS_RESEND_SUCCESS_PHONE: "SMS resent", - PWLESS_RESEND_BTN_DISABLED_START: "Resend in ", - PWLESS_RESEND_BTN_DISABLED_END: "", - PWLESS_RESEND_BTN_EMAIL: "Resend Email", - PWLESS_RESEND_BTN_PHONE: "Resend SMS", - PWLESS_USER_INPUT_CODE_HEADER_TITLE: "Enter OTP", - PWLESS_USER_INPUT_CODE_HEADER_SUBTITLE: "An OTP was sent to you at", - PWLESS_USER_INPUT_CODE_HEADER_SUBTITLE_LINK: "An OTP and a magic link was sent to you at", - PWLESS_USER_INPUT_CODE_INPUT_LABEL: "OTP", - PWLESS_MFA_HEADER_TITLE_PHONE: "SMS based OTP", - PWLESS_MFA_HEADER_TITLE_EMAIL: "Email based OTP", - PWLESS_MFA_FOOTER_LOGOUT: "Logout", - /* - * The following are error messages from our backend SDK. - * These are returned as full messages to preserver compatibilty, but they work just like the keys above. - * They are shown as is by default (setting the value to undefined will display the raw translation key) - */ - "Failed to generate a one time code. Please try again": undefined, - "Phone number is invalid": undefined, - "Email is invalid": undefined, - "Cannot sign in / up due to security reasons. Please try a different login method or contact support. (ERR_CODE_002)": - undefined, - "Cannot sign in / up due to security reasons. Please try a different login method or contact support. (ERR_CODE_003)": - undefined, - "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_017)": undefined, - "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_018)": undefined, - "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_019)": undefined, - } - ), +var defaultTranslationsPasswordless = { + en: utils.__assign(utils.__assign({}, uiEntry.defaultTranslationsCommon.en), { GENERAL_ERROR_EMAIL_UNDEFINED: "Please set your email", GENERAL_ERROR_EMAIL_NON_STRING: "Email must be of type string", GENERAL_ERROR_EMAIL_INVALID: "Email is invalid", GENERAL_ERROR_PHONE_UNDEFINED: "Please set your phone number", GENERAL_ERROR_PHONE_NON_STRING: "Phone number must be of type string", GENERAL_ERROR_PHONE_INVALID: "Phone number is invalid", GENERAL_ERROR_OTP_UNDEFINED: "Please fill your OTP", GENERAL_ERROR_OTP_INVALID: "Invalid OTP", GENERAL_ERROR_OTP_EXPIRED: "Expired OTP.", GENERAL_ERROR_OTP_NON_STRING: "OTP must be of type string", GENERAL_ERROR_OTP_EMPTY: "OTP cannot be empty", ERROR_SIGN_IN_UP_LINK: "Invalid magic link. Please try again.", ERROR_SIGN_IN_UP_RESEND_RESTART_FLOW: "Login timed out. Please try again.", ERROR_SIGN_IN_UP_CODE_CONSUME_RESTART_FLOW: "Login unsuccessful. Please try again.", PWLESS_SIGN_IN_UP_EMAIL_LABEL: "Email", PWLESS_SIGN_IN_UP_PHONE_LABEL: "Phone Number", PWLESS_SIGN_IN_UP_SWITCH_TO_PHONE: "Use a Phone number", PWLESS_SIGN_IN_UP_SWITCH_TO_EMAIL: "Use an Email", PWLESS_SIGN_IN_UP_CONTINUE_BUTTON: "CONTINUE", PWLESS_COMBO_CONTINUE_WITH_PASSWORDLESS_LINK: "Continue with passwordless", PWLESS_COMBO_CONTINUE_WITH_PASSWORDLESS_BUTTON: "CONTINUE WITH PASSWORDLESS", PWLESS_COMBO_PASSWORD_LABEL: "Password", PWLESS_COMBO_FORGOT_PW_LINK: "Forgot password?", PWLESS_LINK_SENT_RESEND_SUCCESS: "Link resent", PWLESS_LINK_SENT_RESEND_TITLE: "Link sent!", PWLESS_LINK_SENT_RESEND_DESC_START_EMAIL: "We sent a link to ", PWLESS_LINK_SENT_RESEND_DESC_START_PHONE: "We sent a link to your phone number ", PWLESS_LINK_SENT_RESEND_DESC_END_EMAIL: ". Click the link to login or sign up", PWLESS_LINK_SENT_RESEND_DESC_END_PHONE: "", PWLESS_SIGN_IN_UP_CHANGE_CONTACT_INFO_EMAIL: "Change email", PWLESS_SIGN_IN_UP_CHANGE_CONTACT_INFO_PHONE: "Change phone number", PWLESS_LINK_CLICKED_CONTINUE_HEADER: "Sign Up or Log In", PWLESS_LINK_CLICKED_CONTINUE_DESC: "Click the button below to log in on this device", PWLESS_LINK_CLICKED_CONTINUE_BUTTON: "CONTINUE", PWLESS_RESEND_SUCCESS_EMAIL: "Email resent", PWLESS_RESEND_SUCCESS_PHONE: "SMS resent", PWLESS_RESEND_BTN_DISABLED_START: "Resend in ", PWLESS_RESEND_BTN_DISABLED_END: "", PWLESS_RESEND_BTN_EMAIL: "Resend Email", PWLESS_RESEND_BTN_PHONE: "Resend SMS", PWLESS_USER_INPUT_CODE_HEADER_TITLE: "Enter OTP", PWLESS_USER_INPUT_CODE_HEADER_SUBTITLE: "An OTP was sent to you at", PWLESS_USER_INPUT_CODE_HEADER_SUBTITLE_LINK: "An OTP and a magic link was sent to you at", PWLESS_USER_INPUT_CODE_INPUT_LABEL: "OTP", PWLESS_MFA_HEADER_TITLE_PHONE: "SMS based OTP", PWLESS_MFA_HEADER_TITLE_EMAIL: "Email based OTP", PWLESS_MFA_FOOTER_LOGOUT: "Logout", + /* + * The following are error messages from our backend SDK. + * These are returned as full messages to preserver compatibilty, but they work just like the keys above. + * They are shown as is by default (setting the value to undefined will display the raw translation key) + */ + "Failed to generate a one time code. Please try again": undefined, "Phone number is invalid": undefined, "Email is invalid": undefined, "Cannot sign in / up due to security reasons. Please try a different login method or contact support. (ERR_CODE_002)": undefined, "Cannot sign in / up due to security reasons. Please try a different login method or contact support. (ERR_CODE_003)": undefined, "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_017)": undefined, "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_018)": undefined, "Cannot sign in / up due to security reasons. Please contact support. (ERR_CODE_019)": undefined }), }; -var LinkClickedScreen = function (props) { - var rethrowInRender = genericComponentOverrideContext.useRethrowInRender(); - var userContext = uiEntry.useUserContext(); - if (props.userContext !== undefined) { - userContext = props.userContext; - } - var _a = React.useState(false), - requireUserInteraction = _a[0], - setRequireUserInteraction = _a[1]; - var consumeCodeAtMount = React.useCallback( - function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var preAuthSessionId, linkCode, loginAttemptInfo, payloadBeforeCall; - var _b; - return genericComponentOverrideContext.__generator(this, function (_c) { - switch (_c.label) { - case 0: - preAuthSessionId = genericComponentOverrideContext.getQueryParams("preAuthSessionId"); - linkCode = genericComponentOverrideContext.getURLHash(); - if (!(preAuthSessionId === null || preAuthSessionId.length === 0 || linkCode.length === 0)) - return [3 /*break*/, 2]; - return [ - 4 /*yield*/, - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToAuth({ - navigate: props.navigate, - queryParams: { - error: "signin", - }, - redirectBack: false, - userContext: userContext, - }), - ]; - case 1: - _c.sent(); - return [2 /*return*/, "REDIRECTING"]; - case 2: - return [ - 4 /*yield*/, - props.recipe.webJSRecipe.getLoginAttemptInfo({ userContext: userContext }), - ]; - case 3: - loginAttemptInfo = _c.sent(); - if ( - (loginAttemptInfo === null || loginAttemptInfo === void 0 - ? void 0 - : loginAttemptInfo.preAuthSessionId) !== preAuthSessionId - ) { - return [2 /*return*/, "REQUIRES_INTERACTION"]; - } - _c.label = 4; - case 4: - _c.trys.push([4, 6, , 7]); - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ - userContext: userContext, - }), - ]; - case 5: - payloadBeforeCall = _c.sent(); - return [3 /*break*/, 7]; - case 6: - _c.sent(); - // If getAccessTokenPayloadSecurely threw, that generally means we have no active session - payloadBeforeCall = undefined; - return [3 /*break*/, 7]; - case 7: - _b = { - payloadBeforeCall: payloadBeforeCall, - }; - return [ - 4 /*yield*/, - props.recipe.webJSRecipe.consumeCode({ - userContext: userContext, - }), - ]; - case 8: - return [2 /*return*/, ((_b.response = _c.sent()), _b)]; - } - }); - }); - }, - [props.recipe, props.navigate, userContext] - ); - var handleConsumeResp = React.useCallback( - function (consumeRes) { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var response, payloadBeforeCall, payloadAfterCall, loginAttemptInfo; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (consumeRes === "REQUIRES_INTERACTION") { - // We set this here, to make sure it's set after a possible remount - setRequireUserInteraction(true); - } - if (typeof consumeRes === "string") { - // In this case we are already redirecting or showing the continue button - return [2 /*return*/]; - } - (response = consumeRes.response), (payloadBeforeCall = consumeRes.payloadBeforeCall); - if (response.status === "RESTART_FLOW_ERROR") { - return [ - 2 /*return*/, - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToAuth({ - navigate: props.navigate, - queryParams: { - error: "restart_link", - }, - redirectBack: false, - userContext: userContext, - }), - ]; - } - if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { - return [ - 2 /*return*/, - genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToAuth({ - navigate: props.navigate, - queryParams: { - error: response.reason, - }, - redirectBack: false, - userContext: userContext, - }), - ]; - } - if (!(response.status === "OK")) return [3 /*break*/, 7]; - payloadAfterCall = void 0; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ - userContext: userContext, - }), - ]; - case 2: - payloadAfterCall = _b.sent(); - return [3 /*break*/, 4]; - case 3: - _b.sent(); - payloadAfterCall = undefined; - return [3 /*break*/, 4]; - case 4: - return [ - 4 /*yield*/, - props.recipe.webJSRecipe.getLoginAttemptInfo({ - userContext: userContext, - }), - ]; - case 5: - loginAttemptInfo = _b.sent(); - return [ - 4 /*yield*/, - props.recipe.webJSRecipe.clearLoginAttemptInfo({ - userContext: userContext, - }), - ]; - case 6: - _b.sent(); - return [ - 2 /*return*/, - types.Session.getInstanceOrThrow() - .validateGlobalClaimsAndHandleSuccessRedirection( - { - action: "SUCCESS", - createdNewUser: - response.createdNewRecipeUser && - response.user.loginMethods.length === 1, - isNewRecipeUser: response.createdNewRecipeUser, - newSessionCreated: - payloadAfterCall !== undefined && - (payloadBeforeCall === undefined || - payloadBeforeCall.sessionHandle !== payloadAfterCall.sessionHandle), - recipeId: props.recipe.recipeID, - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - }, - props.recipe.recipeID, - loginAttemptInfo === null || loginAttemptInfo === void 0 - ? void 0 - : loginAttemptInfo.redirectToPath, - userContext, - props.navigate - ) - .catch(rethrowInRender), - ]; - case 7: - return [2 /*return*/]; - } - }); - }); - }, - [props.navigate, props.recipe, userContext] - ); - var handleConsumeError = React.useCallback( - function (err) { - if (STGeneralError__default.default.isThisError(err)) { - return genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToAuth({ - navigate: props.navigate, - queryParams: { - error: "custom", - message: err.message, - }, - redirectBack: false, - userContext: userContext, - }); - } else { - return genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().redirectToAuth({ - navigate: props.navigate, - queryParams: { - error: "signin", - }, - redirectBack: false, - userContext: userContext, - }); - } - }, - [props.navigate, userContext] - ); - genericComponentOverrideContext.useOnMountAPICall(consumeCodeAtMount, handleConsumeResp, handleConsumeError); - var recipeComponentOverrides = props.useComponentOverrides(); - var childProps = { - recipeImplementation: props.recipe.webJSRecipe, - config: props.recipe.config, - requireUserInteraction: requireUserInteraction, - consumeCode: function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var payloadBeforeCall, consumeResp, err_1; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 7, , 8]); - payloadBeforeCall = void 0; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ - userContext: userContext, - }), - ]; - case 2: - payloadBeforeCall = _b.sent(); - return [3 /*break*/, 4]; - case 3: - _b.sent(); - // If getAccessTokenPayloadSecurely threw, that generally means we have no active session - payloadBeforeCall = undefined; - return [3 /*break*/, 4]; - case 4: - return [ - 4 /*yield*/, - props.recipe.webJSRecipe.consumeCode({ - userContext: userContext, - }), - ]; - case 5: - consumeResp = _b.sent(); - return [ - 4 /*yield*/, - handleConsumeResp({ response: consumeResp, payloadBeforeCall: payloadBeforeCall }), - ]; - case 6: - _b.sent(); - return [3 /*break*/, 8]; - case 7: - err_1 = _b.sent(); - void handleConsumeError(err_1); - return [3 /*break*/, 8]; - case 8: - return [2 /*return*/]; - } - }); - }); - }, - }; - return jsxRuntime.jsx( - uiEntry.ComponentOverrideContext.Provider, - genericComponentOverrideContext.__assign( - { value: recipeComponentOverrides }, - { - children: jsxRuntime.jsx( - uiEntry.FeatureWrapper, - genericComponentOverrideContext.__assign( - { - useShadowDom: genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().useShadowDom, - defaultStore: defaultTranslationsPasswordless, - }, - { - children: jsxRuntime.jsxs(React.Fragment, { - children: [ - props.children === undefined && - jsxRuntime.jsx( - LinkClickedScreen$1, - genericComponentOverrideContext.__assign({}, childProps) - ), - props.children && - React__namespace.default.Children.map(props.children, function (child) { - if (React__namespace.default.isValidElement(child)) { - return React__namespace.default.cloneElement(child, childProps); - } - return child; - }), - ], - }), - } - ) - ), - } - ) - ); +var LinkClickedScreen = function (props) { + var rethrowInRender = utils.useRethrowInRender(); + var userContext = uiEntry.useUserContext(); + if (props.userContext !== undefined) { + userContext = props.userContext; + } + var _a = React.useState(false), requireUserInteraction = _a[0], setRequireUserInteraction = _a[1]; + var consumeCodeAtMount = React.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + var preAuthSessionId, linkCode, loginAttemptInfo, payloadBeforeCall; + var _b; + return utils.__generator(this, function (_c) { + switch (_c.label) { + case 0: + preAuthSessionId = utils.getQueryParams("preAuthSessionId"); + linkCode = utils.getURLHash(); + if (!(preAuthSessionId === null || preAuthSessionId.length === 0 || linkCode.length === 0)) return [3 /*break*/, 2]; + return [4 /*yield*/, superTokens.SuperTokens.getInstanceOrThrow().redirectToAuth({ + navigate: props.navigate, + queryParams: { + error: "signin", + }, + redirectBack: false, + userContext: userContext, + })]; + case 1: + _c.sent(); + return [2 /*return*/, "REDIRECTING"]; + case 2: return [4 /*yield*/, props.recipe.webJSRecipe.getLoginAttemptInfo({ userContext: userContext })]; + case 3: + loginAttemptInfo = _c.sent(); + if ((loginAttemptInfo === null || loginAttemptInfo === void 0 ? void 0 : loginAttemptInfo.preAuthSessionId) !== preAuthSessionId) { + return [2 /*return*/, "REQUIRES_INTERACTION"]; + } + _c.label = 4; + case 4: + _c.trys.push([4, 6, , 7]); + return [4 /*yield*/, types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ + userContext: userContext, + })]; + case 5: + payloadBeforeCall = _c.sent(); + return [3 /*break*/, 7]; + case 6: + _c.sent(); + // If getAccessTokenPayloadSecurely threw, that generally means we have no active session + payloadBeforeCall = undefined; + return [3 /*break*/, 7]; + case 7: + _b = { + payloadBeforeCall: payloadBeforeCall + }; + return [4 /*yield*/, props.recipe.webJSRecipe.consumeCode({ + userContext: userContext, + })]; + case 8: return [2 /*return*/, (_b.response = _c.sent(), + _b)]; + } + }); + }); }, [props.recipe, props.navigate, userContext]); + var handleConsumeResp = React.useCallback(function (consumeRes) { return utils.__awaiter(void 0, void 0, void 0, function () { + var response, payloadBeforeCall, payloadAfterCall, loginAttemptInfo; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (consumeRes === "REQUIRES_INTERACTION") { + // We set this here, to make sure it's set after a possible remount + setRequireUserInteraction(true); + } + if (typeof consumeRes === "string") { + // In this case we are already redirecting or showing the continue button + return [2 /*return*/]; + } + response = consumeRes.response, payloadBeforeCall = consumeRes.payloadBeforeCall; + if (response.status === "RESTART_FLOW_ERROR") { + return [2 /*return*/, superTokens.SuperTokens.getInstanceOrThrow().redirectToAuth({ + navigate: props.navigate, + queryParams: { + error: "restart_link", + }, + redirectBack: false, + userContext: userContext, + })]; + } + if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { + return [2 /*return*/, superTokens.SuperTokens.getInstanceOrThrow().redirectToAuth({ + navigate: props.navigate, + queryParams: { + error: response.reason, + }, + redirectBack: false, + userContext: userContext, + })]; + } + if (!(response.status === "OK")) return [3 /*break*/, 7]; + payloadAfterCall = void 0; + _b.label = 1; + case 1: + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ + userContext: userContext, + })]; + case 2: + payloadAfterCall = _b.sent(); + return [3 /*break*/, 4]; + case 3: + _b.sent(); + payloadAfterCall = undefined; + return [3 /*break*/, 4]; + case 4: return [4 /*yield*/, props.recipe.webJSRecipe.getLoginAttemptInfo({ + userContext: userContext, + })]; + case 5: + loginAttemptInfo = _b.sent(); + return [4 /*yield*/, props.recipe.webJSRecipe.clearLoginAttemptInfo({ + userContext: userContext, + })]; + case 6: + _b.sent(); + return [2 /*return*/, types.Session.getInstanceOrThrow() + .validateGlobalClaimsAndHandleSuccessRedirection({ + action: "SUCCESS", + createdNewUser: response.createdNewRecipeUser && response.user.loginMethods.length === 1, + isNewRecipeUser: response.createdNewRecipeUser, + newSessionCreated: payloadAfterCall !== undefined && + (payloadBeforeCall === undefined || + payloadBeforeCall.sessionHandle !== payloadAfterCall.sessionHandle), + recipeId: props.recipe.recipeID, + tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), + }, props.recipe.recipeID, loginAttemptInfo === null || loginAttemptInfo === void 0 ? void 0 : loginAttemptInfo.redirectToPath, userContext, props.navigate) + .catch(rethrowInRender)]; + case 7: return [2 /*return*/]; + } + }); + }); }, [props.navigate, props.recipe, userContext]); + var handleConsumeError = React.useCallback(function (err) { + if (STGeneralError__default.default.isThisError(err)) { + return superTokens.SuperTokens.getInstanceOrThrow().redirectToAuth({ + navigate: props.navigate, + queryParams: { + error: "custom", + message: err.message, + }, + redirectBack: false, + userContext: userContext, + }); + } + else { + return superTokens.SuperTokens.getInstanceOrThrow().redirectToAuth({ + navigate: props.navigate, + queryParams: { + error: "signin", + }, + redirectBack: false, + userContext: userContext, + }); + } + }, [props.navigate, userContext]); + utils.useOnMountAPICall(consumeCodeAtMount, handleConsumeResp, handleConsumeError); + var recipeComponentOverrides = props.useComponentOverrides(); + var childProps = { + recipeImplementation: props.recipe.webJSRecipe, + config: props.recipe.config, + requireUserInteraction: requireUserInteraction, + consumeCode: function () { return utils.__awaiter(void 0, void 0, void 0, function () { + var payloadBeforeCall, consumeResp, err_1; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _b.trys.push([0, 7, , 8]); + payloadBeforeCall = void 0; + _b.label = 1; + case 1: + _b.trys.push([1, 3, , 4]); + return [4 /*yield*/, types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ + userContext: userContext, + })]; + case 2: + payloadBeforeCall = _b.sent(); + return [3 /*break*/, 4]; + case 3: + _b.sent(); + // If getAccessTokenPayloadSecurely threw, that generally means we have no active session + payloadBeforeCall = undefined; + return [3 /*break*/, 4]; + case 4: return [4 /*yield*/, props.recipe.webJSRecipe.consumeCode({ + userContext: userContext, + })]; + case 5: + consumeResp = _b.sent(); + return [4 /*yield*/, handleConsumeResp({ response: consumeResp, payloadBeforeCall: payloadBeforeCall })]; + case 6: + _b.sent(); + return [3 /*break*/, 8]; + case 7: + err_1 = _b.sent(); + void handleConsumeError(err_1); + return [3 /*break*/, 8]; + case 8: return [2 /*return*/]; + } + }); + }); }, + }; + return (jsxRuntime.jsx(uiEntry.ComponentOverrideContext.Provider, utils.__assign({ value: recipeComponentOverrides }, { children: jsxRuntime.jsx(uiEntry.FeatureWrapper, utils.__assign({ useShadowDom: superTokens.SuperTokens.getInstanceOrThrow().useShadowDom, defaultStore: defaultTranslationsPasswordless }, { children: jsxRuntime.jsxs(React.Fragment, { children: [props.children === undefined && jsxRuntime.jsx(LinkClickedScreen$1, utils.__assign({}, childProps)), props.children && + React__namespace.default.Children.map(props.children, function (child) { + if (React__namespace.default.isValidElement(child)) { + return React__namespace.default.cloneElement(child, childProps); + } + return child; + })] }) })) }))); }; -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http="//www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ -/* - * Imports. - */ -/* - * Component. - */ -function SMSLargeIcon() { - return jsxRuntime.jsxs( - "svg", - genericComponentOverrideContext.__assign( - { width: "81", height: "74", viewBox: "0 0 81 74", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, - { - children: [ - jsxRuntime.jsx("rect", { - width: "81", - height: "74", - rx: "12", - fill: "#2D3644", - "fill-opacity": "0.1", - }), - jsxRuntime.jsx("path", { - fillRule: "evenodd", - clipRule: "evenodd", - d: "M24.2791 18.0721C23.4556 18.2346 22.8383 18.5501 22.2521 19.1081C21.8207 19.5187 21.386 20.2086 21.202 20.7749C20.9933 21.4174 21 21.014 21 32.9399C21 44.8055 20.9953 44.5105 21.1962 45.0802C21.6287 46.3063 22.5027 47.2275 23.6138 47.6284C24.2239 47.8485 24.5957 47.8781 26.7622 47.879L28.7938 47.8799L28.7945 51.3361C28.7953 54.928 28.797 54.9609 28.9957 55.3449C29.2026 55.7447 29.7368 56.0357 30.1914 55.9964C30.557 55.9648 30.7792 55.8285 31.6485 55.1029C32.0817 54.7413 32.5179 54.3786 32.6179 54.2969C32.718 54.2151 32.8782 54.0813 32.9739 53.9995C33.0696 53.9178 33.2293 53.784 33.3288 53.7022C33.6246 53.4593 35.3203 52.0426 35.4235 51.9522C35.476 51.9063 35.6683 51.7462 35.851 51.5963C36.0337 51.4464 36.2261 51.2867 36.2785 51.2414C36.3609 51.1702 37.0269 50.6141 38.5123 49.3762C38.7214 49.2019 38.9673 48.9969 39.0588 48.9205C39.1503 48.8442 39.4689 48.5788 39.7668 48.3308L40.3085 47.8799H48.2834C53.8058 47.8799 56.3722 47.8632 56.6286 47.8256C58.2358 47.59 59.5022 46.4036 59.9294 44.7333C60.0239 44.364 60.0233 21.5127 59.9288 21.1466C59.5021 19.493 58.3008 18.3427 56.7137 18.0678C56.1756 17.9746 24.7519 17.9788 24.2791 18.0721ZM51.4173 28.981C52.2557 29.3855 52.4751 30.4017 51.8772 31.1101C51.7556 31.254 51.5818 31.3895 51.4269 31.4609L51.1745 31.5773H40.5392C28.8194 31.5773 29.681 31.6007 29.2987 31.2721C28.9166 30.9437 28.7361 30.438 28.8355 29.9747C28.9464 29.458 29.3009 29.0629 29.7764 28.9262C29.9644 28.8722 31.912 28.8618 40.6033 28.8685L51.201 28.8767L51.4173 28.981ZM41.0193 34.419C41.3249 34.5599 41.6353 34.9094 41.7403 35.2309C41.9512 35.8762 41.6712 36.5538 41.0654 36.8639L40.7934 37.0032L35.4708 37.0186C31.645 37.0297 30.0783 37.0183 29.8996 36.9781C29.5714 36.9043 29.4061 36.814 29.1927 36.5921C28.6448 36.0224 28.6929 35.1284 29.2996 34.607C29.6628 34.2948 29.3424 34.3108 35.315 34.3065L40.767 34.3026L41.0193 34.419Z", - fill: "#2D3644", - }), - ], - } - ) - ); +/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http="//www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/* + * Imports. + */ +/* + * Component. + */ +function SMSLargeIcon() { + return (jsxRuntime.jsxs("svg", utils.__assign({ width: "81", height: "74", viewBox: "0 0 81 74", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, { children: [jsxRuntime.jsx("rect", { width: "81", height: "74", rx: "12", fill: "#2D3644", "fill-opacity": "0.1" }), jsxRuntime.jsx("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M24.2791 18.0721C23.4556 18.2346 22.8383 18.5501 22.2521 19.1081C21.8207 19.5187 21.386 20.2086 21.202 20.7749C20.9933 21.4174 21 21.014 21 32.9399C21 44.8055 20.9953 44.5105 21.1962 45.0802C21.6287 46.3063 22.5027 47.2275 23.6138 47.6284C24.2239 47.8485 24.5957 47.8781 26.7622 47.879L28.7938 47.8799L28.7945 51.3361C28.7953 54.928 28.797 54.9609 28.9957 55.3449C29.2026 55.7447 29.7368 56.0357 30.1914 55.9964C30.557 55.9648 30.7792 55.8285 31.6485 55.1029C32.0817 54.7413 32.5179 54.3786 32.6179 54.2969C32.718 54.2151 32.8782 54.0813 32.9739 53.9995C33.0696 53.9178 33.2293 53.784 33.3288 53.7022C33.6246 53.4593 35.3203 52.0426 35.4235 51.9522C35.476 51.9063 35.6683 51.7462 35.851 51.5963C36.0337 51.4464 36.2261 51.2867 36.2785 51.2414C36.3609 51.1702 37.0269 50.6141 38.5123 49.3762C38.7214 49.2019 38.9673 48.9969 39.0588 48.9205C39.1503 48.8442 39.4689 48.5788 39.7668 48.3308L40.3085 47.8799H48.2834C53.8058 47.8799 56.3722 47.8632 56.6286 47.8256C58.2358 47.59 59.5022 46.4036 59.9294 44.7333C60.0239 44.364 60.0233 21.5127 59.9288 21.1466C59.5021 19.493 58.3008 18.3427 56.7137 18.0678C56.1756 17.9746 24.7519 17.9788 24.2791 18.0721ZM51.4173 28.981C52.2557 29.3855 52.4751 30.4017 51.8772 31.1101C51.7556 31.254 51.5818 31.3895 51.4269 31.4609L51.1745 31.5773H40.5392C28.8194 31.5773 29.681 31.6007 29.2987 31.2721C28.9166 30.9437 28.7361 30.438 28.8355 29.9747C28.9464 29.458 29.3009 29.0629 29.7764 28.9262C29.9644 28.8722 31.912 28.8618 40.6033 28.8685L51.201 28.8767L51.4173 28.981ZM41.0193 34.419C41.3249 34.5599 41.6353 34.9094 41.7403 35.2309C41.9512 35.8762 41.6712 36.5538 41.0654 36.8639L40.7934 37.0032L35.4708 37.0186C31.645 37.0297 30.0783 37.0183 29.8996 36.9781C29.5714 36.9043 29.4061 36.814 29.1927 36.5921C28.6448 36.0224 28.6929 35.1284 29.2996 34.607C29.6628 34.2948 29.3424 34.3108 35.315 34.3065L40.767 34.3026L41.0193 34.419Z", fill: "#2D3644" })] }))); } -var ResendButton = uiEntry.withOverride("PasswordlessResendButton", function PasswordlessResendButton(_a) { - var loginAttemptInfo = _a.loginAttemptInfo, - resendEmailOrSMSGapInSeconds = _a.resendEmailOrSMSGapInSeconds, - onClick = _a.onClick; - var t = translationContext.useTranslation(); - var getTimeLeft = React.useCallback( - function () { - var timeLeft = loginAttemptInfo.lastResend + resendEmailOrSMSGapInSeconds * 1000 - Date.now(); - return timeLeft < 0 ? undefined : Math.ceil(timeLeft / 1000); - }, - [loginAttemptInfo, resendEmailOrSMSGapInSeconds] - ); - var _b = React.useState(getTimeLeft()), - secsUntilResend = _b[0], - setSecsUntilResend = _b[1]; - React.useEffect( - function () { - // This runs every time the loginAttemptInfo updates, so after every resend - var interval = setInterval(function () { - var timeLeft = getTimeLeft(); - if (timeLeft === undefined) { - clearInterval(interval); - } - setSecsUntilResend(timeLeft); - }, 500); - return function () { - // This can safely run twice - clearInterval(interval); - }; - }, - [getTimeLeft, setSecsUntilResend] - ); - return jsxRuntime.jsx( - "button", - genericComponentOverrideContext.__assign( - { - type: "button", - disabled: secsUntilResend !== undefined, - onClick: onClick, - "data-supertokens": "link linkButton formLabelLinkBtn resendCodeBtn", - }, - { - children: - secsUntilResend !== undefined - ? jsxRuntime.jsxs(React__namespace.default.Fragment, { - children: [ - t("PWLESS_RESEND_BTN_DISABLED_START"), - jsxRuntime.jsxs("strong", { - children: [ - Math.floor(secsUntilResend / 60) - .toString() - .padStart(2, "0"), - ":", - (secsUntilResend % 60).toString().padStart(2, "0"), - ], - }), - t("PWLESS_RESEND_BTN_DISABLED_END"), - ], - }) - : loginAttemptInfo.contactMethod === "EMAIL" - ? t("PWLESS_RESEND_BTN_EMAIL") - : t("PWLESS_RESEND_BTN_PHONE"), - } - ) - ); +var ResendButton = uiEntry.withOverride("PasswordlessResendButton", function PasswordlessResendButton(_a) { + var loginAttemptInfo = _a.loginAttemptInfo, resendEmailOrSMSGapInSeconds = _a.resendEmailOrSMSGapInSeconds, onClick = _a.onClick; + var t = translationContext.useTranslation(); + var getTimeLeft = React.useCallback(function () { + var timeLeft = loginAttemptInfo.lastResend + resendEmailOrSMSGapInSeconds * 1000 - Date.now(); + return timeLeft < 0 ? undefined : Math.ceil(timeLeft / 1000); + }, [loginAttemptInfo, resendEmailOrSMSGapInSeconds]); + var _b = React.useState(getTimeLeft()), secsUntilResend = _b[0], setSecsUntilResend = _b[1]; + React.useEffect(function () { + // This runs every time the loginAttemptInfo updates, so after every resend + var interval = setInterval(function () { + var timeLeft = getTimeLeft(); + if (timeLeft === undefined) { + clearInterval(interval); + } + setSecsUntilResend(timeLeft); + }, 500); + return function () { + // This can safely run twice + clearInterval(interval); + }; + }, [getTimeLeft, setSecsUntilResend]); + return (jsxRuntime.jsx("button", utils.__assign({ type: "button", disabled: secsUntilResend !== undefined, onClick: onClick, "data-supertokens": "link linkButton formLabelLinkBtn resendCodeBtn" }, { children: secsUntilResend !== undefined ? (jsxRuntime.jsxs(React__namespace.default.Fragment, { children: [t("PWLESS_RESEND_BTN_DISABLED_START"), jsxRuntime.jsxs("strong", { children: [Math.floor(secsUntilResend / 60) + .toString() + .padStart(2, "0"), ":", (secsUntilResend % 60).toString().padStart(2, "0")] }), t("PWLESS_RESEND_BTN_DISABLED_END")] })) : loginAttemptInfo.contactMethod === "EMAIL" ? (t("PWLESS_RESEND_BTN_EMAIL")) : (t("PWLESS_RESEND_BTN_PHONE")) }))); }); -var PasswordlessLinkSent = function (props) { - var t = translationContext.useTranslation(); - var userContext = uiEntry.useUserContext(); - var _a = React.useState(props.error !== undefined ? "ERROR" : "READY"), - status = _a[0], - setStatus = _a[1]; - // Any because node types are included here, messing with return type of setTimeout - var resendNotifTimeout = React.useRef(); - React.useEffect(function () { - return function () { - // This can safely run even if it was cleared before - if (resendNotifTimeout.current) { - clearTimeout(resendNotifTimeout.current); - } - }; - }, []); - var resendEmail = React.useCallback( - function () { - return genericComponentOverrideContext.__awaiter(void 0, void 0, void 0, function () { - var response, generalError, e_1; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 5, , 6]); - props.clearError(); - response = void 0; - generalError = void 0; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [ - 4 /*yield*/, - props.recipeImplementation.resendCode({ - userContext: userContext, - }), - ]; - case 2: - response = _a.sent(); - return [3 /*break*/, 4]; - case 3: - e_1 = _a.sent(); - if (STGeneralError__default.default.isThisError(e_1)) { - generalError = e_1; - } else { - throw e_1; - } - return [3 /*break*/, 4]; - case 4: - if (response !== undefined && response.status === "OK") { - setStatus("LINK_RESENT"); - resendNotifTimeout.current = setTimeout(function () { - setStatus(function (status) { - return status === "LINK_RESENT" ? "READY" : status; - }); - resendNotifTimeout.current = undefined; - }, 2000); - } else { - setStatus("ERROR"); - if (generalError !== undefined) { - props.onError(generalError.message); - } - } - return [3 /*break*/, 6]; - case 5: - _a.sent(); - setStatus("ERROR"); - return [3 /*break*/, 6]; - case 6: - return [2 /*return*/]; - } - }); - }); - }, - [props.recipeImplementation, props.loginAttemptInfo, props.config, setStatus] - ); - var resendActive = status === "LINK_RESENT"; - return jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "container" }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "row" }, - { - children: [ - status === "ERROR" && - jsxRuntime.jsx(uiEntry.GeneralError, { - error: props.error === undefined ? "SOMETHING_WENT_WRONG_ERROR" : props.error, - }), - resendActive && - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "generalSuccess" }, - { children: t("PWLESS_LINK_SENT_RESEND_SUCCESS") } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "sendCodeIcon" }, - { - children: - props.loginAttemptInfo.contactMethod === "EMAIL" - ? jsxRuntime.jsx(emailLargeIcon.EmailLargeIcon, {}) - : jsxRuntime.jsx(SMSLargeIcon, {}), - } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "headerTitle headerTinyTitle" }, - { children: t("PWLESS_LINK_SENT_RESEND_TITLE") } - ) - ), - jsxRuntime.jsx("div", { "data-supertokens": "divider" }), - jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "primaryText sendCodeText" }, - { - children: [ - props.loginAttemptInfo.contactMethod === "EMAIL" - ? t("PWLESS_LINK_SENT_RESEND_DESC_START_EMAIL") - : t("PWLESS_LINK_SENT_RESEND_DESC_START_PHONE"), - jsxRuntime.jsx("strong", { - children: props.loginAttemptInfo.contactInfo, - }), - props.loginAttemptInfo.contactMethod === "EMAIL" - ? t("PWLESS_LINK_SENT_RESEND_DESC_END_EMAIL") - : t("PWLESS_LINK_SENT_RESEND_DESC_END_PHONE"), - ], - } - ) - ), - jsxRuntime.jsx( - "div", - genericComponentOverrideContext.__assign( - { - "data-supertokens": "buttonWithArrow", - onClick: function () { - return props.recipeImplementation.clearLoginAttemptInfo({ - userContext: userContext, - }); - }, - }, - { - children: jsxRuntime.jsxs( - "div", - genericComponentOverrideContext.__assign( - { "data-supertokens": "secondaryText secondaryLinkWithLeftArrow" }, - { - children: [ - jsxRuntime.jsx(arrowLeftIcon.ArrowLeftIcon, { - color: "rgb(var(--palette-textGray))", - }), - jsxRuntime.jsx("span", { - children: - props.loginAttemptInfo.contactMethod === "EMAIL" - ? t( - "PWLESS_SIGN_IN_UP_CHANGE_CONTACT_INFO_EMAIL" - ) - : t( - "PWLESS_SIGN_IN_UP_CHANGE_CONTACT_INFO_PHONE" - ), - }), - ], - } - ) - ), - } - ) - ), - jsxRuntime.jsx(ResendButton, { - loginAttemptInfo: props.loginAttemptInfo, - resendEmailOrSMSGapInSeconds: - props.config.signInUpFeature.resendEmailOrSMSGapInSeconds, - onClick: resendEmail, - }), - ], - } - ) - ), - } - ) - ); -}; -var LinkSent = uiEntry.withOverride("PasswordlessLinkSent", PasswordlessLinkSent); -function LinkSentWrapper(props) { - var rootStyle = genericComponentOverrideContext.SuperTokens.getInstanceOrThrow().rootStyle; - var activeStyle = props.config.signInUpFeature.linkSentScreenStyle; - return jsxRuntime.jsx( - uiEntry.UserContextWrapper, - genericComponentOverrideContext.__assign( - { userContext: props.userContext }, - { - children: jsxRuntime.jsx( - ThemeBase, - genericComponentOverrideContext.__assign( - { userStyles: [rootStyle, props.config.recipeRootStyle, activeStyle] }, - { children: jsxRuntime.jsx(LinkSent, genericComponentOverrideContext.__assign({}, props)) } - ) - ), - } - ) - ); +var PasswordlessLinkSent = function (props) { + var t = translationContext.useTranslation(); + var userContext = uiEntry.useUserContext(); + var _a = React.useState(props.error !== undefined ? "ERROR" : "READY"), status = _a[0], setStatus = _a[1]; + // Any because node types are included here, messing with return type of setTimeout + var resendNotifTimeout = React.useRef(); + React.useEffect(function () { + return function () { + // This can safely run even if it was cleared before + if (resendNotifTimeout.current) { + clearTimeout(resendNotifTimeout.current); + } + }; + }, []); + var resendEmail = React.useCallback(function () { return utils.__awaiter(void 0, void 0, void 0, function () { + var response, generalError, e_1; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 5, , 6]); + props.clearError(); + response = void 0; + generalError = void 0; + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, props.recipeImplementation.resendCode({ + userContext: userContext, + })]; + case 2: + response = _a.sent(); + return [3 /*break*/, 4]; + case 3: + e_1 = _a.sent(); + if (STGeneralError__default.default.isThisError(e_1)) { + generalError = e_1; + } + else { + throw e_1; + } + return [3 /*break*/, 4]; + case 4: + if (response !== undefined && response.status === "OK") { + setStatus("LINK_RESENT"); + resendNotifTimeout.current = setTimeout(function () { + setStatus(function (status) { return (status === "LINK_RESENT" ? "READY" : status); }); + resendNotifTimeout.current = undefined; + }, 2000); + } + else { + setStatus("ERROR"); + if (generalError !== undefined) { + props.onError(generalError.message); + } + } + return [3 /*break*/, 6]; + case 5: + _a.sent(); + setStatus("ERROR"); + return [3 /*break*/, 6]; + case 6: return [2 /*return*/]; + } + }); + }); }, [props.recipeImplementation, props.loginAttemptInfo, props.config, setStatus]); + var resendActive = status === "LINK_RESENT"; + return (jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "container" }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "row" }, { children: [status === "ERROR" && (jsxRuntime.jsx(uiEntry.GeneralError, { error: props.error === undefined ? "SOMETHING_WENT_WRONG_ERROR" : props.error })), resendActive && jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "generalSuccess" }, { children: t("PWLESS_LINK_SENT_RESEND_SUCCESS") })), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "sendCodeIcon" }, { children: props.loginAttemptInfo.contactMethod === "EMAIL" ? jsxRuntime.jsx(emailLargeIcon.EmailLargeIcon, {}) : jsxRuntime.jsx(SMSLargeIcon, {}) })), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "headerTitle headerTinyTitle" }, { children: t("PWLESS_LINK_SENT_RESEND_TITLE") })), jsxRuntime.jsx("div", { "data-supertokens": "divider" }), jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "primaryText sendCodeText" }, { children: [props.loginAttemptInfo.contactMethod === "EMAIL" + ? t("PWLESS_LINK_SENT_RESEND_DESC_START_EMAIL") + : t("PWLESS_LINK_SENT_RESEND_DESC_START_PHONE"), jsxRuntime.jsx("strong", { children: props.loginAttemptInfo.contactInfo }), props.loginAttemptInfo.contactMethod === "EMAIL" + ? t("PWLESS_LINK_SENT_RESEND_DESC_END_EMAIL") + : t("PWLESS_LINK_SENT_RESEND_DESC_END_PHONE")] })), jsxRuntime.jsx("div", utils.__assign({ "data-supertokens": "buttonWithArrow", onClick: function () { + return props.recipeImplementation.clearLoginAttemptInfo({ + userContext: userContext, + }); + } }, { children: jsxRuntime.jsxs("div", utils.__assign({ "data-supertokens": "secondaryText secondaryLinkWithLeftArrow" }, { children: [jsxRuntime.jsx(arrowLeftIcon.ArrowLeftIcon, { color: "rgb(var(--palette-textGray))" }), jsxRuntime.jsx("span", { children: props.loginAttemptInfo.contactMethod === "EMAIL" + ? t("PWLESS_SIGN_IN_UP_CHANGE_CONTACT_INFO_EMAIL") + : t("PWLESS_SIGN_IN_UP_CHANGE_CONTACT_INFO_PHONE") })] })) })), jsxRuntime.jsx(ResendButton, { loginAttemptInfo: props.loginAttemptInfo, resendEmailOrSMSGapInSeconds: props.config.signInUpFeature.resendEmailOrSMSGapInSeconds, onClick: resendEmail })] })) }))); +}; +var LinkSent = uiEntry.withOverride("PasswordlessLinkSent", PasswordlessLinkSent); +function LinkSentWrapper(props) { + var rootStyle = superTokens.SuperTokens.getInstanceOrThrow().rootStyle; + var activeStyle = props.config.signInUpFeature.linkSentScreenStyle; + return (jsxRuntime.jsx(uiEntry.UserContextWrapper, utils.__assign({ userContext: props.userContext }, { children: jsxRuntime.jsx(ThemeBase, utils.__assign({ userStyles: [rootStyle, props.config.recipeRootStyle, activeStyle] }, { children: jsxRuntime.jsx(LinkSent, utils.__assign({}, props)) })) }))); } -function useChildProps$4( - recipe$1, - loginAttemptInfo, - error, - onError, - clearError, - rebuildAuthPage, - userContext, - navigate -) { - var _this = this; - var session$1 = uiEntry.useSessionContext(); - var recipeImplementation = React__namespace.useMemo( - function () { - return getModifiedRecipeImplementation$4(recipe$1.webJSRecipe, onError, rebuildAuthPage); - }, - [recipe$1, onError, rebuildAuthPage] - ); - var rethrowInRender = genericComponentOverrideContext.useRethrowInRender(); - return React.useMemo( - function () { - return { - userContext: userContext, - onSuccess: function (result) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var payloadAfterCall; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 2, , 3]); - return [ - 4 /*yield*/, - types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ - userContext: userContext, - }), - ]; - case 1: - payloadAfterCall = _b.sent(); - return [3 /*break*/, 3]; - case 2: - _b.sent(); - payloadAfterCall = undefined; - return [3 /*break*/, 3]; - case 3: - return [ - 2 /*return*/, - types.Session.getInstanceOrThrow() - .validateGlobalClaimsAndHandleSuccessRedirection( - { - action: "SUCCESS", - createdNewUser: - result.createdNewRecipeUser && - result.user.loginMethods.length === 1, - isNewRecipeUser: result.createdNewRecipeUser, - newSessionCreated: - session$1.loading || - !session$1.doesSessionExist || - (payloadAfterCall !== undefined && - session$1.accessTokenPayload.sessionHandle !== - payloadAfterCall.sessionHandle), - recipeId: recipe$1.recipeID, - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - }, - recipe$1.recipeID, - genericComponentOverrideContext.getRedirectToPathFromURL(), - userContext, - navigate - ) - .catch(rethrowInRender), - ]; - } - }); - }); - }, - onFetchError: function (err) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var invalidClaims, evInstance; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if ( - !( - err.status === - types.Session.getInstanceOrThrow().config.invalidClaimStatusCode - ) - ) - return [3 /*break*/, 5]; - return [ - 4 /*yield*/, - session.getInvalidClaimsFromResponse({ - response: err, - userContext: userContext, - }), - ]; - case 1: - invalidClaims = _b.sent(); - if ( - !invalidClaims.some(function (i) { - return i.id === emailverification.EmailVerificationClaim.id; - }) - ) - return [3 /*break*/, 5]; - _b.label = 2; - case 2: - _b.trys.push([2, 4, , 5]); - evInstance = recipe.EmailVerification.getInstanceOrThrow(); - return [ - 4 /*yield*/, - evInstance.redirect( - { - tenantIdFromQueryParams: - genericComponentOverrideContext.getTenantIdFromQueryParams(), - action: "VERIFY_EMAIL", - }, - navigate, - undefined, - userContext - ), - ]; - case 3: - _b.sent(); - return [2 /*return*/]; - case 4: - _b.sent(); - return [3 /*break*/, 5]; - case 5: - onError("SOMETHING_WENT_WRONG_ERROR"); - return [2 /*return*/]; - } - }); - }); - }, - loginAttemptInfo: loginAttemptInfo, - error: error, - onError: onError, - clearError: clearError, - recipeImplementation: recipeImplementation, - config: recipe$1.config, - }; - }, - [error, recipeImplementation] - ); -} -var LinkSentFeatureInner = function (props) { - var childProps = useChildProps$4( - props.recipe, - props.loginAttemptInfo, - props.error, - props.onError, - props.clearError, - props.rebuildAuthPage, - props.userContext, - props.navigate - ); - return jsxRuntime.jsxs(React.Fragment, { - children: [ - props.children === undefined && - jsxRuntime.jsx( - LinkSentWrapper, - genericComponentOverrideContext.__assign({}, childProps, { userContext: props.userContext }) - ), - props.children && - React__namespace.Children.map(props.children, function (child) { - if (React__namespace.isValidElement(child)) { - return React__namespace.cloneElement( - child, - genericComponentOverrideContext.__assign({}, childProps) - ); - } - return child; - }), - ], - }); -}; -var LinkSentFeature = function (props) { - var recipeComponentOverrides = props.useComponentOverrides(); - return jsxRuntime.jsx( - authCompWrapper.AuthComponentWrapper, - genericComponentOverrideContext.__assign( - { recipeComponentOverrides: recipeComponentOverrides }, - { children: jsxRuntime.jsx(LinkSentFeatureInner, genericComponentOverrideContext.__assign({}, props)) } - ) - ); -}; -function getModifiedRecipeImplementation$4(originalImpl, setError, rebuildAuthPage) { - var _this = this; - return genericComponentOverrideContext.__assign(genericComponentOverrideContext.__assign({}, originalImpl), { - resendCode: function (input) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var res, loginAttemptInfo, timestamp; - var _a; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - return [4 /*yield*/, originalImpl.resendCode(input)]; - case 1: - res = _b.sent(); - if (!(res.status === "OK")) return [3 /*break*/, 5]; - return [ - 4 /*yield*/, - originalImpl.getLoginAttemptInfo({ - userContext: input.userContext, - }), - ]; - case 2: - loginAttemptInfo = _b.sent(); - if (!(loginAttemptInfo !== undefined)) return [3 /*break*/, 4]; - timestamp = Date.now(); - return [ - 4 /*yield*/, - originalImpl.setLoginAttemptInfo({ - userContext: input.userContext, - attemptInfo: genericComponentOverrideContext.__assign( - genericComponentOverrideContext.__assign({}, loginAttemptInfo), - { - shouldTryLinkingWithSessionUser: - (_a = loginAttemptInfo.shouldTryLinkingWithSessionUser) !== null && - _a !== void 0 - ? _a - : false, - lastResend: timestamp, - } - ), - }), - ]; - case 3: - _b.sent(); - _b.label = 4; - case 4: - return [3 /*break*/, 7]; - case 5: - if (!(res.status === "RESTART_FLOW_ERROR")) return [3 /*break*/, 7]; - return [ - 4 /*yield*/, - originalImpl.clearLoginAttemptInfo({ - userContext: input.userContext, - }), - ]; - case 6: - _b.sent(); - setError("ERROR_SIGN_IN_UP_RESEND_RESTART_FLOW"); - rebuildAuthPage(); - _b.label = 7; - case 7: - return [2 /*return*/, res]; - } - }); - }); - }, - consumeCode: function (input) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var res; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, originalImpl.consumeCode(input)]; - case 1: - res = _a.sent(); - if (!(res.status === "RESTART_FLOW_ERROR")) return [3 /*break*/, 3]; - return [ - 4 /*yield*/, - originalImpl.clearLoginAttemptInfo({ - userContext: input.userContext, - }), - ]; - case 2: - _a.sent(); - setError("ERROR_SIGN_IN_UP_CODE_CONSUME_RESTART_FLOW"); - rebuildAuthPage(); - return [3 /*break*/, 7]; - case 3: - if (!(res.status === "SIGN_IN_UP_NOT_ALLOWED")) return [3 /*break*/, 5]; - return [ - 4 /*yield*/, - originalImpl.clearLoginAttemptInfo({ - userContext: input.userContext, - }), - ]; - case 4: - _a.sent(); - setError(res.reason); - rebuildAuthPage(); - return [3 /*break*/, 7]; - case 5: - if (!(res.status === "OK")) return [3 /*break*/, 7]; - return [ - 4 /*yield*/, - originalImpl.clearLoginAttemptInfo({ - userContext: input.userContext, - }), - ]; - case 6: - _a.sent(); - _a.label = 7; - case 7: - return [2 /*return*/, res]; - } - }); - }); - }, - clearLoginAttemptInfo: function (input) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [ - 4 /*yield*/, - originalImpl.clearLoginAttemptInfo({ - userContext: input.userContext, - }), - ]; - case 1: - _a.sent(); - genericComponentOverrideContext.clearErrorQueryParam(); - rebuildAuthPage(); - return [2 /*return*/]; - } - }); - }); - }, - }); +function useChildProps$4(recipe$1, loginAttemptInfo, error, onError, clearError, rebuildAuthPage, userContext, navigate) { + var _this = this; + var session$1 = uiEntry.useSessionContext(); + var recipeImplementation = React__namespace.useMemo(function () { return getModifiedRecipeImplementation$4(recipe$1.webJSRecipe, onError, rebuildAuthPage); }, [recipe$1, onError, rebuildAuthPage]); + var rethrowInRender = utils.useRethrowInRender(); + return React.useMemo(function () { + return { + userContext: userContext, + onSuccess: function (result) { return utils.__awaiter(_this, void 0, void 0, function () { + var payloadAfterCall; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _b.trys.push([0, 2, , 3]); + return [4 /*yield*/, types.Session.getInstanceOrThrow().getAccessTokenPayloadSecurely({ + userContext: userContext, + })]; + case 1: + payloadAfterCall = _b.sent(); + return [3 /*break*/, 3]; + case 2: + _b.sent(); + payloadAfterCall = undefined; + return [3 /*break*/, 3]; + case 3: return [2 /*return*/, types.Session.getInstanceOrThrow() + .validateGlobalClaimsAndHandleSuccessRedirection({ + action: "SUCCESS", + createdNewUser: result.createdNewRecipeUser && result.user.loginMethods.length === 1, + isNewRecipeUser: result.createdNewRecipeUser, + newSessionCreated: session$1.loading || + !session$1.doesSessionExist || + (payloadAfterCall !== undefined && + session$1.accessTokenPayload.sessionHandle !== payloadAfterCall.sessionHandle), + recipeId: recipe$1.recipeID, + tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), + }, recipe$1.recipeID, utils.getRedirectToPathFromURL(), userContext, navigate) + .catch(rethrowInRender)]; + } + }); + }); }, + onFetchError: function (err) { return utils.__awaiter(_this, void 0, void 0, function () { + var invalidClaims, evInstance; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!(err.status === types.Session.getInstanceOrThrow().config.invalidClaimStatusCode)) return [3 /*break*/, 5]; + return [4 /*yield*/, session.getInvalidClaimsFromResponse({ response: err, userContext: userContext })]; + case 1: + invalidClaims = _b.sent(); + if (!invalidClaims.some(function (i) { return i.id === emailverification.EmailVerificationClaim.id; })) return [3 /*break*/, 5]; + _b.label = 2; + case 2: + _b.trys.push([2, 4, , 5]); + evInstance = recipe.EmailVerification.getInstanceOrThrow(); + return [4 /*yield*/, evInstance.redirect({ + tenantIdFromQueryParams: utils.getTenantIdFromQueryParams(), + action: "VERIFY_EMAIL", + }, navigate, undefined, userContext)]; + case 3: + _b.sent(); + return [2 /*return*/]; + case 4: + _b.sent(); + return [3 /*break*/, 5]; + case 5: + onError("SOMETHING_WENT_WRONG_ERROR"); + return [2 /*return*/]; + } + }); + }); }, + loginAttemptInfo: loginAttemptInfo, + error: error, + onError: onError, + clearError: clearError, + recipeImplementation: recipeImplementation, + config: recipe$1.config, + }; + }, [error, recipeImplementation]); +} +var LinkSentFeatureInner = function (props) { + var childProps = useChildProps$4(props.recipe, props.loginAttemptInfo, props.error, props.onError, props.clearError, props.rebuildAuthPage, props.userContext, props.navigate); + return (jsxRuntime.jsxs(React.Fragment, { children: [props.children === undefined && jsxRuntime.jsx(LinkSentWrapper, utils.__assign({}, childProps, { userContext: props.userContext })), props.children && + React__namespace.Children.map(props.children, function (child) { + if (React__namespace.isValidElement(child)) { + return React__namespace.cloneElement(child, utils.__assign({}, childProps)); + } + return child; + })] })); +}; +var LinkSentFeature = function (props) { + var recipeComponentOverrides = props.useComponentOverrides(); + return (jsxRuntime.jsx(authCompWrapper.AuthComponentWrapper, utils.__assign({ recipeComponentOverrides: recipeComponentOverrides }, { children: jsxRuntime.jsx(LinkSentFeatureInner, utils.__assign({}, props)) }))); +}; +function getModifiedRecipeImplementation$4(originalImpl, setError, rebuildAuthPage) { + var _this = this; + return utils.__assign(utils.__assign({}, originalImpl), { resendCode: function (input) { return utils.__awaiter(_this, void 0, void 0, function () { + var res, loginAttemptInfo, timestamp; + var _a; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, originalImpl.resendCode(input)]; + case 1: + res = _b.sent(); + if (!(res.status === "OK")) return [3 /*break*/, 5]; + return [4 /*yield*/, originalImpl.getLoginAttemptInfo({ + userContext: input.userContext, + })]; + case 2: + loginAttemptInfo = _b.sent(); + if (!(loginAttemptInfo !== undefined)) return [3 /*break*/, 4]; + timestamp = Date.now(); + return [4 /*yield*/, originalImpl.setLoginAttemptInfo({ + userContext: input.userContext, + attemptInfo: utils.__assign(utils.__assign({}, loginAttemptInfo), { shouldTryLinkingWithSessionUser: (_a = loginAttemptInfo.shouldTryLinkingWithSessionUser) !== null && _a !== void 0 ? _a : false, lastResend: timestamp }), + })]; + case 3: + _b.sent(); + _b.label = 4; + case 4: return [3 /*break*/, 7]; + case 5: + if (!(res.status === "RESTART_FLOW_ERROR")) return [3 /*break*/, 7]; + return [4 /*yield*/, originalImpl.clearLoginAttemptInfo({ + userContext: input.userContext, + })]; + case 6: + _b.sent(); + setError("ERROR_SIGN_IN_UP_RESEND_RESTART_FLOW"); + rebuildAuthPage(); + _b.label = 7; + case 7: return [2 /*return*/, res]; + } + }); + }); }, consumeCode: function (input) { return utils.__awaiter(_this, void 0, void 0, function () { + var res; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, originalImpl.consumeCode(input)]; + case 1: + res = _a.sent(); + if (!(res.status === "RESTART_FLOW_ERROR")) return [3 /*break*/, 3]; + return [4 /*yield*/, originalImpl.clearLoginAttemptInfo({ + userContext: input.userContext, + })]; + case 2: + _a.sent(); + setError("ERROR_SIGN_IN_UP_CODE_CONSUME_RESTART_FLOW"); + rebuildAuthPage(); + return [3 /*break*/, 7]; + case 3: + if (!(res.status === "SIGN_IN_UP_NOT_ALLOWED")) return [3 /*break*/, 5]; + return [4 /*yield*/, originalImpl.clearLoginAttemptInfo({ + userContext: input.userContext, + })]; + case 4: + _a.sent(); + setError(res.reason); + rebuildAuthPage(); + return [3 /*break*/, 7]; + case 5: + if (!(res.status === "OK")) return [3 /*break*/, 7]; + return [4 /*yield*/, originalImpl.clearLoginAttemptInfo({ + userContext: input.userContext, + })]; + case 6: + _a.sent(); + _a.label = 7; + case 7: return [2 /*return*/, res]; + } + }); + }); }, clearLoginAttemptInfo: function (input) { return utils.__awaiter(_this, void 0, void 0, function () { + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, originalImpl.clearLoginAttemptInfo({ + userContext: input.userContext, + })]; + case 1: + _a.sent(); + utils.clearErrorQueryParam(); + rebuildAuthPage(); + return [2 /*return*/]; + } + }); + }); } }); } -var phoneNumberUtilsImport; -function getPhoneNumberUtils() { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var global; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 /*yield*/, preloadPhoneNumberUtils()]; - case 1: - _a.sent(); - global = windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.getWindowUnsafe(); - return [2 /*return*/, global.intlTelInputUtils]; - } - }); - }); -} -function preloadPhoneNumberUtils() { - if (phoneNumberUtilsImport === undefined) { - /* eslint-disable @typescript-eslint/ban-ts-comment */ - // @ts-ignore: We need to disable no implicit any here, otherwise we'd need to add types for this module - phoneNumberUtilsImport = Promise.resolve().then(function () { - return require("./utils.js"); - }); - /* eslint-enable @typescript-eslint/ban-ts-comment */ - } - return phoneNumberUtilsImport; +var phoneNumberUtilsImport; +function getPhoneNumberUtils() { + return utils.__awaiter(this, void 0, void 0, function () { + var global; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, preloadPhoneNumberUtils()]; + case 1: + _a.sent(); + global = windowHandler.WindowHandlerReference.getReferenceOrThrow().windowHandler.getWindowUnsafe(); + return [2 /*return*/, global.intlTelInputUtils]; + } + }); + }); +} +function preloadPhoneNumberUtils() { + if (phoneNumberUtilsImport === undefined) { + /* eslint-disable @typescript-eslint/ban-ts-comment */ + // @ts-ignore: We need to disable no implicit any here, otherwise we'd need to add types for this module + phoneNumberUtilsImport = Promise.resolve().then(function () { return require('./utils2.js'); }); + /* eslint-enable @typescript-eslint/ban-ts-comment */ + } + return phoneNumberUtilsImport; } -// This was moved to a separate file to make tree-shaking more effective, since we do not want to include the phoneNumberUtils -// in the base pwless recipe because it increases the bundle size by a lot -function defaultPhoneNumberValidator(value) { - return genericComponentOverrideContext.__awaiter(this, void 0, void 0, function () { - var intlTelInputUtils; - return genericComponentOverrideContext.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (typeof value !== "string") { - return [2 /*return*/, "GENERAL_ERROR_PHONE_NON_STRING"]; - } - value = value.trim(); - return [4 /*yield*/, getPhoneNumberUtils()]; - case 1: - intlTelInputUtils = _a.sent(); - if (!intlTelInputUtils.isValidNumber(value, undefined)) { - return [2 /*return*/, "GENERAL_ERROR_PHONE_INVALID"]; - } - return [2 /*return*/, undefined]; - } - }); - }); +// This was moved to a separate file to make tree-shaking more effective, since we do not want to include the phoneNumberUtils +// in the base pwless recipe because it increases the bundle size by a lot +function defaultPhoneNumberValidator(value) { + return utils.__awaiter(this, void 0, void 0, function () { + var intlTelInputUtils; + return utils.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (typeof value !== "string") { + return [2 /*return*/, "GENERAL_ERROR_PHONE_NON_STRING"]; + } + value = value.trim(); + return [4 /*yield*/, getPhoneNumberUtils()]; + case 1: + intlTelInputUtils = _a.sent(); + if (!intlTelInputUtils.isValidNumber(value, undefined)) { + return [2 /*return*/, "GENERAL_ERROR_PHONE_INVALID"]; + } + return [2 /*return*/, undefined]; + } + }); + }); } -var EmailForm = uiEntry.withOverride("PasswordlessEmailForm", function PasswordlessEmailForm(props) { - var _this = this; - var userContext = uiEntry.useUserContext(); - return jsxRuntime.jsx(formBase.FormBase, { - clearError: props.clearError, - onFetchError: props.onFetchError, - onError: props.onError, - formFields: [ - { - id: "email", - label: "PWLESS_SIGN_IN_UP_EMAIL_LABEL", - optional: false, - autofocus: true, - placeholder: "", - autoComplete: "email", - // We are using the default validator that allows any string - validate: validators.defaultValidate, - }, - ], - buttonLabel: "PWLESS_SIGN_IN_UP_CONTINUE_BUTTON", - onSuccess: props.onSuccess, - callAPI: function (formFields) { - return genericComponentOverrideContext.__awaiter(_this, void 0, void 0, function () { - var email, validationRes, response; - var _a; - return genericComponentOverrideContext.__generator(this, function (_b) { - switch (_b.label) { - case 0: - email = - (_a = formFields.find(function (field) { - return field.id === "email"; - })) === null || _a === void 0 - ? void 0 - : _a.value; - if (email === undefined) { - throw new STGeneralError__default.default("GENERAL_ERROR_EMAIL_UNDEFINED"); - } - return [4 /*yield*/, props.config.validateEmailAddress(email)]; - case 1: - validationRes = _b.sent(); - if (validationRes !== undefined) { - throw new STGeneralError__default.default(validationRes); - } - return [ - 4 /*yield*/, - props.recipeImplementation.createCode({ - email: email, - // shouldTryLinkingWithSessionUser is set by the fn override - userContext: userContext, - }), - ]; - case 2: - response = _b.sent(); - if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { - throw new STGeneralError__default.default(response.reason); - } - return [2 /*return*/, response]; - } - }); - }); - }, - validateOnBlur: false, - showLabels: true, - footer: props.footer, - }); +var EmailForm = uiEntry.withOverride("PasswordlessEmailForm", function PasswordlessEmailForm(props) { + var _this = this; + var userContext = uiEntry.useUserContext(); + return (jsxRuntime.jsx(formBase.FormBase, { clearError: props.clearError, onFetchError: props.onFetchError, onError: props.onError, formFields: [ + { + id: "email", + label: "PWLESS_SIGN_IN_UP_EMAIL_LABEL", + optional: false, + autofocus: true, + placeholder: "", + autoComplete: "email", + // We are using the default validator that allows any string + validate: validators.defaultValidate, + }, + ], buttonLabel: "PWLESS_SIGN_IN_UP_CONTINUE_BUTTON", onSuccess: props.onSuccess, callAPI: function (formFields) { return utils.__awaiter(_this, void 0, void 0, function () { + var email, validationRes, response; + var _a; + return utils.__generator(this, function (_b) { + switch (_b.label) { + case 0: + email = (_a = formFields.find(function (field) { return field.id === "email"; })) === null || _a === void 0 ? void 0 : _a.value; + if (email === undefined) { + throw new STGeneralError__default.default("GENERAL_ERROR_EMAIL_UNDEFINED"); + } + return [4 /*yield*/, props.config.validateEmailAddress(email)]; + case 1: + validationRes = _b.sent(); + if (validationRes !== undefined) { + throw new STGeneralError__default.default(validationRes); + } + return [4 /*yield*/, props.recipeImplementation.createCode({ + email: email, + // shouldTryLinkingWithSessionUser is set by the fn override + userContext: userContext, + })]; + case 2: + response = _b.sent(); + if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { + throw new STGeneralError__default.default(response.reason); + } + return [2 /*return*/, response]; + } + }); + }); }, validateOnBlur: false, showLabels: true, footer: props.footer })); }); -function getDefaultExportFromCjs(x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var intlTelInputExports$1 = {}; var intlTelInput$2 = { - get exports() { - return intlTelInputExports$1; - }, - set exports(v) { - intlTelInputExports$1 = v; - }, + get exports(){ return intlTelInputExports$1; }, + set exports(v){ intlTelInputExports$1 = v; }, }; var intlTelInputExports = {}; var intlTelInput$1 = { - get exports() { - return intlTelInputExports; - }, - set exports(v) { - intlTelInputExports = v; - }, + get exports(){ return intlTelInputExports; }, + set exports(v){ intlTelInputExports = v; }, }; /* @@ -1423,5830 +772,3398 @@ var intlTelInput$1 = { */ (function (module) { - // wrap in UMD - (function (factory) { - if (module.exports) module.exports = factory(); - else window.intlTelInput = factory(); - })(function (undefined$1) { - return (function () { - // Array of country objects for the flag dropdown. - // Here is the criteria for the plugin to support a given country/territory - // - It has an iso2 code: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 - // - It has it's own country calling code (it is not a sub-region of another country): https://en.wikipedia.org/wiki/List_of_country_calling_codes - // - It has a flag in the region-flags project: https://github.com/behdad/region-flags/tree/gh-pages/png - // - It is supported by libphonenumber (it must be listed on this page): https://github.com/googlei18n/libphonenumber/blob/master/resources/ShortNumberMetadata.xml - // Each country array has the following information: - // [ - // Country name, - // iso2 code, - // International dial code, - // Order (if >1 country with same dial code), - // Area codes - // ] - var allCountries = [ - ["Afghanistan (‫افغانستان‬‎)", "af", "93"], - ["Albania (Shqipëri)", "al", "355"], - ["Algeria (‫الجزائر‬‎)", "dz", "213"], - ["American Samoa", "as", "1", 5, ["684"]], - ["Andorra", "ad", "376"], - ["Angola", "ao", "244"], - ["Anguilla", "ai", "1", 6, ["264"]], - ["Antigua and Barbuda", "ag", "1", 7, ["268"]], - ["Argentina", "ar", "54"], - ["Armenia (Հայաստան)", "am", "374"], - ["Aruba", "aw", "297"], - ["Ascension Island", "ac", "247"], - ["Australia", "au", "61", 0], - ["Austria (Österreich)", "at", "43"], - ["Azerbaijan (Azərbaycan)", "az", "994"], - ["Bahamas", "bs", "1", 8, ["242"]], - ["Bahrain (‫البحرين‬‎)", "bh", "973"], - ["Bangladesh (বাংলাদেশ)", "bd", "880"], - ["Barbados", "bb", "1", 9, ["246"]], - ["Belarus (Беларусь)", "by", "375"], - ["Belgium (België)", "be", "32"], - ["Belize", "bz", "501"], - ["Benin (Bénin)", "bj", "229"], - ["Bermuda", "bm", "1", 10, ["441"]], - ["Bhutan (འབྲུག)", "bt", "975"], - ["Bolivia", "bo", "591"], - ["Bosnia and Herzegovina (Босна и Херцеговина)", "ba", "387"], - ["Botswana", "bw", "267"], - ["Brazil (Brasil)", "br", "55"], - ["British Indian Ocean Territory", "io", "246"], - ["British Virgin Islands", "vg", "1", 11, ["284"]], - ["Brunei", "bn", "673"], - ["Bulgaria (България)", "bg", "359"], - ["Burkina Faso", "bf", "226"], - ["Burundi (Uburundi)", "bi", "257"], - ["Cambodia (កម្ពុជា)", "kh", "855"], - ["Cameroon (Cameroun)", "cm", "237"], - [ - "Canada", - "ca", - "1", - 1, - [ - "204", - "226", - "236", - "249", - "250", - "289", - "306", - "343", - "365", - "387", - "403", - "416", - "418", - "431", - "437", - "438", - "450", - "506", - "514", - "519", - "548", - "579", - "581", - "587", - "604", - "613", - "639", - "647", - "672", - "705", - "709", - "742", - "778", - "780", - "782", - "807", - "819", - "825", - "867", - "873", - "902", - "905", - ], - ], - ["Cape Verde (Kabu Verdi)", "cv", "238"], - ["Caribbean Netherlands", "bq", "599", 1, ["3", "4", "7"]], - ["Cayman Islands", "ky", "1", 12, ["345"]], - ["Central African Republic (République centrafricaine)", "cf", "236"], - ["Chad (Tchad)", "td", "235"], - ["Chile", "cl", "56"], - ["China (中国)", "cn", "86"], - ["Christmas Island", "cx", "61", 2, ["89164"]], - ["Cocos (Keeling) Islands", "cc", "61", 1, ["89162"]], - ["Colombia", "co", "57"], - ["Comoros (‫جزر القمر‬‎)", "km", "269"], - ["Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)", "cd", "243"], - ["Congo (Republic) (Congo-Brazzaville)", "cg", "242"], - ["Cook Islands", "ck", "682"], - ["Costa Rica", "cr", "506"], - ["Côte d’Ivoire", "ci", "225"], - ["Croatia (Hrvatska)", "hr", "385"], - ["Cuba", "cu", "53"], - ["Curaçao", "cw", "599", 0], - ["Cyprus (Κύπρος)", "cy", "357"], - ["Czech Republic (Česká republika)", "cz", "420"], - ["Denmark (Danmark)", "dk", "45"], - ["Djibouti", "dj", "253"], - ["Dominica", "dm", "1", 13, ["767"]], - ["Dominican Republic (República Dominicana)", "do", "1", 2, ["809", "829", "849"]], - ["Ecuador", "ec", "593"], - ["Egypt (‫مصر‬‎)", "eg", "20"], - ["El Salvador", "sv", "503"], - ["Equatorial Guinea (Guinea Ecuatorial)", "gq", "240"], - ["Eritrea", "er", "291"], - ["Estonia (Eesti)", "ee", "372"], - ["Eswatini", "sz", "268"], - ["Ethiopia", "et", "251"], - ["Falkland Islands (Islas Malvinas)", "fk", "500"], - ["Faroe Islands (Føroyar)", "fo", "298"], - ["Fiji", "fj", "679"], - ["Finland (Suomi)", "fi", "358", 0], - ["France", "fr", "33"], - ["French Guiana (Guyane française)", "gf", "594"], - ["French Polynesia (Polynésie française)", "pf", "689"], - ["Gabon", "ga", "241"], - ["Gambia", "gm", "220"], - ["Georgia (საქართველო)", "ge", "995"], - ["Germany (Deutschland)", "de", "49"], - ["Ghana (Gaana)", "gh", "233"], - ["Gibraltar", "gi", "350"], - ["Greece (Ελλάδα)", "gr", "30"], - ["Greenland (Kalaallit Nunaat)", "gl", "299"], - ["Grenada", "gd", "1", 14, ["473"]], - ["Guadeloupe", "gp", "590", 0], - ["Guam", "gu", "1", 15, ["671"]], - ["Guatemala", "gt", "502"], - ["Guernsey", "gg", "44", 1, ["1481", "7781", "7839", "7911"]], - ["Guinea (Guinée)", "gn", "224"], - ["Guinea-Bissau (Guiné Bissau)", "gw", "245"], - ["Guyana", "gy", "592"], - ["Haiti", "ht", "509"], - ["Honduras", "hn", "504"], - ["Hong Kong (香港)", "hk", "852"], - ["Hungary (Magyarország)", "hu", "36"], - ["Iceland (Ísland)", "is", "354"], - ["India (भारत)", "in", "91"], - ["Indonesia", "id", "62"], - ["Iran (‫ایران‬‎)", "ir", "98"], - ["Iraq (‫العراق‬‎)", "iq", "964"], - ["Ireland", "ie", "353"], - ["Isle of Man", "im", "44", 2, ["1624", "74576", "7524", "7924", "7624"]], - ["Israel (‫ישראל‬‎)", "il", "972"], - ["Italy (Italia)", "it", "39", 0], - ["Jamaica", "jm", "1", 4, ["876", "658"]], - ["Japan (日本)", "jp", "81"], - ["Jersey", "je", "44", 3, ["1534", "7509", "7700", "7797", "7829", "7937"]], - ["Jordan (‫الأردن‬‎)", "jo", "962"], - ["Kazakhstan (Казахстан)", "kz", "7", 1, ["33", "7"]], - ["Kenya", "ke", "254"], - ["Kiribati", "ki", "686"], - ["Kosovo", "xk", "383"], - ["Kuwait (‫الكويت‬‎)", "kw", "965"], - ["Kyrgyzstan (Кыргызстан)", "kg", "996"], - ["Laos (ລາວ)", "la", "856"], - ["Latvia (Latvija)", "lv", "371"], - ["Lebanon (‫لبنان‬‎)", "lb", "961"], - ["Lesotho", "ls", "266"], - ["Liberia", "lr", "231"], - ["Libya (‫ليبيا‬‎)", "ly", "218"], - ["Liechtenstein", "li", "423"], - ["Lithuania (Lietuva)", "lt", "370"], - ["Luxembourg", "lu", "352"], - ["Macau (澳門)", "mo", "853"], - ["Madagascar (Madagasikara)", "mg", "261"], - ["Malawi", "mw", "265"], - ["Malaysia", "my", "60"], - ["Maldives", "mv", "960"], - ["Mali", "ml", "223"], - ["Malta", "mt", "356"], - ["Marshall Islands", "mh", "692"], - ["Martinique", "mq", "596"], - ["Mauritania (‫موريتانيا‬‎)", "mr", "222"], - ["Mauritius (Moris)", "mu", "230"], - ["Mayotte", "yt", "262", 1, ["269", "639"]], - ["Mexico (México)", "mx", "52"], - ["Micronesia", "fm", "691"], - ["Moldova (Republica Moldova)", "md", "373"], - ["Monaco", "mc", "377"], - ["Mongolia (Монгол)", "mn", "976"], - ["Montenegro (Crna Gora)", "me", "382"], - ["Montserrat", "ms", "1", 16, ["664"]], - ["Morocco (‫المغرب‬‎)", "ma", "212", 0], - ["Mozambique (Moçambique)", "mz", "258"], - ["Myanmar (Burma) (မြန်မာ)", "mm", "95"], - ["Namibia (Namibië)", "na", "264"], - ["Nauru", "nr", "674"], - ["Nepal (नेपाल)", "np", "977"], - ["Netherlands (Nederland)", "nl", "31"], - ["New Caledonia (Nouvelle-Calédonie)", "nc", "687"], - ["New Zealand", "nz", "64"], - ["Nicaragua", "ni", "505"], - ["Niger (Nijar)", "ne", "227"], - ["Nigeria", "ng", "234"], - ["Niue", "nu", "683"], - ["Norfolk Island", "nf", "672"], - ["North Korea (조선 민주주의 인민 공화국)", "kp", "850"], - ["North Macedonia (Северна Македонија)", "mk", "389"], - ["Northern Mariana Islands", "mp", "1", 17, ["670"]], - ["Norway (Norge)", "no", "47", 0], - ["Oman (‫عُمان‬‎)", "om", "968"], - ["Pakistan (‫پاکستان‬‎)", "pk", "92"], - ["Palau", "pw", "680"], - ["Palestine (‫فلسطين‬‎)", "ps", "970"], - ["Panama (Panamá)", "pa", "507"], - ["Papua New Guinea", "pg", "675"], - ["Paraguay", "py", "595"], - ["Peru (Perú)", "pe", "51"], - ["Philippines", "ph", "63"], - ["Poland (Polska)", "pl", "48"], - ["Portugal", "pt", "351"], - ["Puerto Rico", "pr", "1", 3, ["787", "939"]], - ["Qatar (‫قطر‬‎)", "qa", "974"], - ["Réunion (La Réunion)", "re", "262", 0], - ["Romania (România)", "ro", "40"], - ["Russia (Россия)", "ru", "7", 0], - ["Rwanda", "rw", "250"], - ["Saint Barthélemy", "bl", "590", 1], - ["Saint Helena", "sh", "290"], - ["Saint Kitts and Nevis", "kn", "1", 18, ["869"]], - ["Saint Lucia", "lc", "1", 19, ["758"]], - ["Saint Martin (Saint-Martin (partie française))", "mf", "590", 2], - ["Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)", "pm", "508"], - ["Saint Vincent and the Grenadines", "vc", "1", 20, ["784"]], - ["Samoa", "ws", "685"], - ["San Marino", "sm", "378"], - ["São Tomé and Príncipe (São Tomé e Príncipe)", "st", "239"], - ["Saudi Arabia (‫المملكة العربية السعودية‬‎)", "sa", "966"], - ["Senegal (Sénégal)", "sn", "221"], - ["Serbia (Србија)", "rs", "381"], - ["Seychelles", "sc", "248"], - ["Sierra Leone", "sl", "232"], - ["Singapore", "sg", "65"], - ["Sint Maarten", "sx", "1", 21, ["721"]], - ["Slovakia (Slovensko)", "sk", "421"], - ["Slovenia (Slovenija)", "si", "386"], - ["Solomon Islands", "sb", "677"], - ["Somalia (Soomaaliya)", "so", "252"], - ["South Africa", "za", "27"], - ["South Korea (대한민국)", "kr", "82"], - ["South Sudan (‫جنوب السودان‬‎)", "ss", "211"], - ["Spain (España)", "es", "34"], - ["Sri Lanka (ශ්‍රී ලංකාව)", "lk", "94"], - ["Sudan (‫السودان‬‎)", "sd", "249"], - ["Suriname", "sr", "597"], - ["Svalbard and Jan Mayen", "sj", "47", 1, ["79"]], - ["Sweden (Sverige)", "se", "46"], - ["Switzerland (Schweiz)", "ch", "41"], - ["Syria (‫سوريا‬‎)", "sy", "963"], - ["Taiwan (台灣)", "tw", "886"], - ["Tajikistan", "tj", "992"], - ["Tanzania", "tz", "255"], - ["Thailand (ไทย)", "th", "66"], - ["Timor-Leste", "tl", "670"], - ["Togo", "tg", "228"], - ["Tokelau", "tk", "690"], - ["Tonga", "to", "676"], - ["Trinidad and Tobago", "tt", "1", 22, ["868"]], - ["Tunisia (‫تونس‬‎)", "tn", "216"], - ["Turkey (Türkiye)", "tr", "90"], - ["Turkmenistan", "tm", "993"], - ["Turks and Caicos Islands", "tc", "1", 23, ["649"]], - ["Tuvalu", "tv", "688"], - ["U.S. Virgin Islands", "vi", "1", 24, ["340"]], - ["Uganda", "ug", "256"], - ["Ukraine (Україна)", "ua", "380"], - ["United Arab Emirates (‫الإمارات العربية المتحدة‬‎)", "ae", "971"], - ["United Kingdom", "gb", "44", 0], - ["United States", "us", "1", 0], - ["Uruguay", "uy", "598"], - ["Uzbekistan (Oʻzbekiston)", "uz", "998"], - ["Vanuatu", "vu", "678"], - ["Vatican City (Città del Vaticano)", "va", "39", 1, ["06698"]], - ["Venezuela", "ve", "58"], - ["Vietnam (Việt Nam)", "vn", "84"], - ["Wallis and Futuna (Wallis-et-Futuna)", "wf", "681"], - ["Western Sahara (‫الصحراء الغربية‬‎)", "eh", "212", 1, ["5288", "5289"]], - ["Yemen (‫اليمن‬‎)", "ye", "967"], - ["Zambia", "zm", "260"], - ["Zimbabwe", "zw", "263"], - ["Åland Islands", "ax", "358", 1, ["18"]], - ]; - // loop over all of the countries above, restructuring the data to be objects with named keys - for (var i = 0; i < allCountries.length; i++) { - var c = allCountries[i]; - allCountries[i] = { - name: c[0], - iso2: c[1], - dialCode: c[2], - priority: c[3] || 0, - areaCodes: c[4] || null, - }; - } - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - var intlTelInputGlobals = { - getInstance: function getInstance(input) { - var id = input.getAttribute("data-intl-tel-input-id"); - return window.intlTelInputGlobals.instances[id]; - }, - instances: {}, - // using a global like this allows us to mock it in the tests - documentReady: function documentReady() { - return document.readyState === "complete"; - }, - }; - if (typeof window === "object") window.intlTelInputGlobals = intlTelInputGlobals; - // these vars persist through all instances of the plugin - var id = 0; - var defaults = { - // whether or not to allow the dropdown - allowDropdown: true, - // if there is just a dial code in the input: remove it on blur - autoHideDialCode: true, - // add a placeholder in the input with an example number for the selected country - autoPlaceholder: "polite", - // modify the parentClass - customContainer: "", - // modify the auto placeholder - customPlaceholder: null, - // append menu to specified element - dropdownContainer: null, - // don't display these countries - excludeCountries: [], - // format the input value during initialisation and on setNumber - formatOnDisplay: true, - // geoIp lookup function - geoIpLookup: null, - // inject a hidden input with this name, and on submit, populate it with the result of getNumber - hiddenInput: "", - // initial country - initialCountry: "", - // localized country names e.g. { 'de': 'Deutschland' } - localizedCountries: null, - // don't insert international dial codes - nationalMode: true, - // display only these countries - onlyCountries: [], - // number type to use for placeholders - placeholderNumberType: "MOBILE", - // the countries at the top of the list. defaults to united states and united kingdom - preferredCountries: ["us", "gb"], - // display the country dial code next to the selected flag so it's not part of the typed number - separateDialCode: false, - // specify the path to the libphonenumber script to enable validation/formatting - utilsScript: "", - }; - // https://en.wikipedia.org/wiki/List_of_North_American_Numbering_Plan_area_codes#Non-geographic_area_codes - var regionlessNanpNumbers = [ - "800", - "822", - "833", - "844", - "855", - "866", - "877", - "880", - "881", - "882", - "883", - "884", - "885", - "886", - "887", - "888", - "889", - ]; - // utility function to iterate over an object. can't use Object.entries or native forEach because - // of IE11 - var forEachProp = function forEachProp(obj, callback) { - var keys = Object.keys(obj); - for (var i = 0; i < keys.length; i++) { - callback(keys[i], obj[keys[i]]); - } - }; - // run a method on each instance of the plugin - var forEachInstance = function forEachInstance(method) { - forEachProp(window.intlTelInputGlobals.instances, function (key) { - window.intlTelInputGlobals.instances[key][method](); - }); - }; - // this is our plugin class that we will create an instance of - // eslint-disable-next-line no-unused-vars - var Iti = - /*#__PURE__*/ - (function () { - function Iti(input, options) { - var _this = this; - _classCallCheck(this, Iti); - this.id = id++; - this.telInput = input; - this.activeItem = null; - this.highlightedItem = null; - // process specified options / defaults - // alternative to Object.assign, which isn't supported by IE11 - var customOptions = options || {}; - this.options = {}; - forEachProp(defaults, function (key, value) { - _this.options[key] = customOptions.hasOwnProperty(key) ? customOptions[key] : value; - }); - this.hadInitialPlaceholder = Boolean(input.getAttribute("placeholder")); - } - _createClass(Iti, [ - { - key: "_init", - value: function _init() { - var _this2 = this; - // if in nationalMode, disable options relating to dial codes - if (this.options.nationalMode) this.options.autoHideDialCode = false; - // if separateDialCode then doesn't make sense to A) insert dial code into input - // (autoHideDialCode), and B) display national numbers (because we're displaying the country - // dial code next to them) - if (this.options.separateDialCode) { - this.options.autoHideDialCode = this.options.nationalMode = false; - } - // we cannot just test screen size as some smartphones/website meta tags will report desktop - // resolutions - // Note: for some reason jasmine breaks if you put this in the main Plugin function with the - // rest of these declarations - // Note: to target Android Mobiles (and not Tablets), we must find 'Android' and 'Mobile' - this.isMobile = - /Android.+Mobile|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test( - navigator.userAgent - ); - if (this.isMobile) { - // trigger the mobile dropdown css - document.body.classList.add("iti-mobile"); - // on mobile, we want a full screen dropdown, so we must append it to the body - if (!this.options.dropdownContainer) this.options.dropdownContainer = document.body; - } - // these promises get resolved when their individual requests complete - // this way the dev can do something like iti.promise.then(...) to know when all requests are - // complete - if (typeof Promise !== "undefined") { - var autoCountryPromise = new Promise(function (resolve, reject) { - _this2.resolveAutoCountryPromise = resolve; - _this2.rejectAutoCountryPromise = reject; - }); - var utilsScriptPromise = new Promise(function (resolve, reject) { - _this2.resolveUtilsScriptPromise = resolve; - _this2.rejectUtilsScriptPromise = reject; - }); - this.promise = Promise.all([autoCountryPromise, utilsScriptPromise]); - } else { - // prevent errors when Promise doesn't exist - this.resolveAutoCountryPromise = this.rejectAutoCountryPromise = function () {}; - this.resolveUtilsScriptPromise = this.rejectUtilsScriptPromise = function () {}; - } - // in various situations there could be no country selected initially, but we need to be able - // to assume this variable exists - this.selectedCountryData = {}; - // process all the data: onlyCountries, excludeCountries, preferredCountries etc - this._processCountryData(); - // generate the markup - this._generateMarkup(); - // set the initial state of the input value and the selected flag - this._setInitialState(); - // start all of the event listeners: autoHideDialCode, input keydown, selectedFlag click - this._initListeners(); - // utils script, and auto country - this._initRequests(); - }, - }, - { - key: "_processCountryData", - value: function _processCountryData() { - // process onlyCountries or excludeCountries array if present - this._processAllCountries(); - // process the countryCodes map - this._processCountryCodes(); - // process the preferredCountries - this._processPreferredCountries(); - // translate countries according to localizedCountries option - if (this.options.localizedCountries) this._translateCountriesByLocale(); - // sort countries by name - if (this.options.onlyCountries.length || this.options.localizedCountries) { - this.countries.sort(this._countryNameSort); - } - }, - }, - { - key: "_addCountryCode", - value: function _addCountryCode(iso2, countryCode, priority) { - if (countryCode.length > this.countryCodeMaxLen) { - this.countryCodeMaxLen = countryCode.length; - } - if (!this.countryCodes.hasOwnProperty(countryCode)) { - this.countryCodes[countryCode] = []; - } - // bail if we already have this country for this countryCode - for (var i = 0; i < this.countryCodes[countryCode].length; i++) { - if (this.countryCodes[countryCode][i] === iso2) return; - } - // check for undefined as 0 is falsy - var index = priority !== undefined$1 ? priority : this.countryCodes[countryCode].length; - this.countryCodes[countryCode][index] = iso2; - }, - }, - { - key: "_processAllCountries", - value: function _processAllCountries() { - if (this.options.onlyCountries.length) { - var lowerCaseOnlyCountries = this.options.onlyCountries.map(function (country) { - return country.toLowerCase(); - }); - this.countries = allCountries.filter(function (country) { - return lowerCaseOnlyCountries.indexOf(country.iso2) > -1; - }); - } else if (this.options.excludeCountries.length) { - var lowerCaseExcludeCountries = this.options.excludeCountries.map(function ( - country - ) { - return country.toLowerCase(); - }); - this.countries = allCountries.filter(function (country) { - return lowerCaseExcludeCountries.indexOf(country.iso2) === -1; - }); - } else { - this.countries = allCountries; - } - }, - }, - { - key: "_translateCountriesByLocale", - value: function _translateCountriesByLocale() { - for (var i = 0; i < this.countries.length; i++) { - var iso = this.countries[i].iso2.toLowerCase(); - if (this.options.localizedCountries.hasOwnProperty(iso)) { - this.countries[i].name = this.options.localizedCountries[iso]; - } - } - }, - }, - { - key: "_countryNameSort", - value: function _countryNameSort(a, b) { - return a.name.localeCompare(b.name); - }, - }, - { - key: "_processCountryCodes", - value: function _processCountryCodes() { - this.countryCodeMaxLen = 0; - // here we store just dial codes - this.dialCodes = {}; - // here we store "country codes" (both dial codes and their area codes) - this.countryCodes = {}; - // first: add dial codes - for (var i = 0; i < this.countries.length; i++) { - var c = this.countries[i]; - if (!this.dialCodes[c.dialCode]) this.dialCodes[c.dialCode] = true; - this._addCountryCode(c.iso2, c.dialCode, c.priority); - } - // next: add area codes - // this is a second loop over countries, to make sure we have all of the "root" countries - // already in the map, so that we can access them, as each time we add an area code substring - // to the map, we also need to include the "root" country's code, as that also matches - for (var _i = 0; _i < this.countries.length; _i++) { - var _c = this.countries[_i]; - // area codes - if (_c.areaCodes) { - var rootCountryCode = this.countryCodes[_c.dialCode][0]; - // for each area code - for (var j = 0; j < _c.areaCodes.length; j++) { - var areaCode = _c.areaCodes[j]; - // for each digit in the area code to add all partial matches as well - for (var k = 1; k < areaCode.length; k++) { - var partialDialCode = _c.dialCode + areaCode.substr(0, k); - // start with the root country, as that also matches this dial code - this._addCountryCode(rootCountryCode, partialDialCode); - this._addCountryCode(_c.iso2, partialDialCode); - } - // add the full area code - this._addCountryCode(_c.iso2, _c.dialCode + areaCode); - } - } - } - }, - }, - { - key: "_processPreferredCountries", - value: function _processPreferredCountries() { - this.preferredCountries = []; - for (var i = 0; i < this.options.preferredCountries.length; i++) { - var countryCode = this.options.preferredCountries[i].toLowerCase(); - var countryData = this._getCountryData(countryCode, false, true); - if (countryData) this.preferredCountries.push(countryData); - } - }, - }, - { - key: "_createEl", - value: function _createEl(name, attrs, container) { - var el = document.createElement(name); - if (attrs) - forEachProp(attrs, function (key, value) { - return el.setAttribute(key, value); - }); - if (container) container.appendChild(el); - return el; - }, - }, - { - key: "_generateMarkup", - value: function _generateMarkup() { - // if autocomplete does not exist on the element and its form, then - // prevent autocomplete as there's no safe, cross-browser event we can react to, so it can - // easily put the plugin in an inconsistent state e.g. the wrong flag selected for the - // autocompleted number, which on submit could mean wrong number is saved (esp in nationalMode) - if ( - !this.telInput.hasAttribute("autocomplete") && - !(this.telInput.form && this.telInput.form.hasAttribute("autocomplete")) - ) { - this.telInput.setAttribute("autocomplete", "off"); - } - // containers (mostly for positioning) - var parentClass = "iti"; - if (this.options.allowDropdown) parentClass += " iti--allow-dropdown"; - if (this.options.separateDialCode) parentClass += " iti--separate-dial-code"; - if (this.options.customContainer) { - parentClass += " "; - parentClass += this.options.customContainer; - } - var wrapper = this._createEl("div", { - class: parentClass, - }); - this.telInput.parentNode.insertBefore(wrapper, this.telInput); - this.flagsContainer = this._createEl( - "div", - { - class: "iti__flag-container", - }, - wrapper - ); - wrapper.appendChild(this.telInput); - // selected flag (displayed to left of input) - this.selectedFlag = this._createEl( - "div", - { - class: "iti__selected-flag", - role: "combobox", - "aria-controls": "iti-".concat(this.id, "__country-listbox"), - "aria-owns": "iti-".concat(this.id, "__country-listbox"), - "aria-expanded": "false", - }, - this.flagsContainer - ); - this.selectedFlagInner = this._createEl( - "div", - { - class: "iti__flag", - }, - this.selectedFlag - ); - if (this.options.separateDialCode) { - this.selectedDialCode = this._createEl( - "div", - { - class: "iti__selected-dial-code", - }, - this.selectedFlag - ); - } - if (this.options.allowDropdown) { - // make element focusable and tab navigable - this.selectedFlag.setAttribute("tabindex", "0"); - this.dropdownArrow = this._createEl( - "div", - { - class: "iti__arrow", - }, - this.selectedFlag - ); - // country dropdown: preferred countries, then divider, then all countries - this.countryList = this._createEl("ul", { - class: "iti__country-list iti__hide", - id: "iti-".concat(this.id, "__country-listbox"), - role: "listbox", - "aria-label": "List of countries", - }); - if (this.preferredCountries.length) { - this._appendListItems(this.preferredCountries, "iti__preferred", true); - this._createEl( - "li", - { - class: "iti__divider", - role: "separator", - "aria-disabled": "true", - }, - this.countryList - ); - } - this._appendListItems(this.countries, "iti__standard"); - // create dropdownContainer markup - if (this.options.dropdownContainer) { - this.dropdown = this._createEl("div", { - class: "iti iti--container", - }); - this.dropdown.appendChild(this.countryList); - } else { - this.flagsContainer.appendChild(this.countryList); - } - } - if (this.options.hiddenInput) { - var hiddenInputName = this.options.hiddenInput; - var name = this.telInput.getAttribute("name"); - if (name) { - var i = name.lastIndexOf("["); - // if input name contains square brackets, then give the hidden input the same name, - // replacing the contents of the last set of brackets with the given hiddenInput name - if (i !== -1) - hiddenInputName = "" - .concat(name.substr(0, i), "[") - .concat(hiddenInputName, "]"); - } - this.hiddenInput = this._createEl("input", { - type: "hidden", - name: hiddenInputName, - }); - wrapper.appendChild(this.hiddenInput); - } - }, - }, - { - key: "_appendListItems", - value: function _appendListItems(countries, className, preferred) { - // we create so many DOM elements, it is faster to build a temp string - // and then add everything to the DOM in one go at the end - var tmp = ""; - // for each country - for (var i = 0; i < countries.length; i++) { - var c = countries[i]; - var idSuffix = preferred ? "-preferred" : ""; - // open the list item - tmp += "
  • "); - // add the flag - tmp += "
    " - ); - // and the country name and dial code - tmp += "".concat(c.name, ""); - tmp += "+".concat(c.dialCode, ""); - // close the list item - tmp += "
  • "; - } - this.countryList.insertAdjacentHTML("beforeend", tmp); - }, - }, - { - key: "_setInitialState", - value: function _setInitialState() { - // fix firefox bug: when first load page (with input with value set to number with intl dial - // code) and initialising plugin removes the dial code from the input, then refresh page, - // and we try to init plugin again but this time on number without dial code so get grey flag - var attributeValue = this.telInput.getAttribute("value"); - var inputValue = this.telInput.value; - var useAttribute = - attributeValue && - attributeValue.charAt(0) === "+" && - (!inputValue || inputValue.charAt(0) !== "+"); - var val = useAttribute ? attributeValue : inputValue; - var dialCode = this._getDialCode(val); - var isRegionlessNanp = this._isRegionlessNanp(val); - var _this$options = this.options, - initialCountry = _this$options.initialCountry, - nationalMode = _this$options.nationalMode, - autoHideDialCode = _this$options.autoHideDialCode, - separateDialCode = _this$options.separateDialCode; - // if we already have a dial code, and it's not a regionlessNanp, we can go ahead and set the - // flag, else fall back to the default country - if (dialCode && !isRegionlessNanp) { - this._updateFlagFromNumber(val); - } else if (initialCountry !== "auto") { - // see if we should select a flag - if (initialCountry) { - this._setFlag(initialCountry.toLowerCase()); - } else { - if (dialCode && isRegionlessNanp) { - // has intl dial code, is regionless nanp, and no initialCountry, so default to US - this._setFlag("us"); - } else { - // no dial code and no initialCountry, so default to first in list - this.defaultCountry = this.preferredCountries.length - ? this.preferredCountries[0].iso2 - : this.countries[0].iso2; - if (!val) { - this._setFlag(this.defaultCountry); - } - } - } - // if empty and no nationalMode and no autoHideDialCode then insert the default dial code - if (!val && !nationalMode && !autoHideDialCode && !separateDialCode) { - this.telInput.value = "+".concat(this.selectedCountryData.dialCode); - } - } - // NOTE: if initialCountry is set to auto, that will be handled separately - // format - note this wont be run after _updateDialCode as that's only called if no val - if (val) this._updateValFromNumber(val); - }, - }, - { - key: "_initListeners", - value: function _initListeners() { - this._initKeyListeners(); - if (this.options.autoHideDialCode) this._initBlurListeners(); - if (this.options.allowDropdown) this._initDropdownListeners(); - if (this.hiddenInput) this._initHiddenInputListener(); - }, - }, - { - key: "_initHiddenInputListener", - value: function _initHiddenInputListener() { - var _this3 = this; - this._handleHiddenInputSubmit = function () { - _this3.hiddenInput.value = _this3.getNumber(); - }; - if (this.telInput.form) - this.telInput.form.addEventListener("submit", this._handleHiddenInputSubmit); - }, - }, - { - key: "_getClosestLabel", - value: function _getClosestLabel() { - var el = this.telInput; - while (el && el.tagName !== "LABEL") { - el = el.parentNode; - } - return el; - }, - }, - { - key: "_initDropdownListeners", - value: function _initDropdownListeners() { - var _this4 = this; - // hack for input nested inside label (which is valid markup): clicking the selected-flag to - // open the dropdown would then automatically trigger a 2nd click on the input which would - // close it again - this._handleLabelClick = function (e) { - // if the dropdown is closed, then focus the input, else ignore the click - if (_this4.countryList.classList.contains("iti__hide")) _this4.telInput.focus(); - else e.preventDefault(); - }; - var label = this._getClosestLabel(); - if (label) label.addEventListener("click", this._handleLabelClick); - // toggle country dropdown on click - this._handleClickSelectedFlag = function () { - // only intercept this event if we're opening the dropdown - // else let it bubble up to the top ("click-off-to-close" listener) - // we cannot just stopPropagation as it may be needed to close another instance - if ( - _this4.countryList.classList.contains("iti__hide") && - !_this4.telInput.disabled && - !_this4.telInput.readOnly - ) { - _this4._showDropdown(); - } - }; - this.selectedFlag.addEventListener("click", this._handleClickSelectedFlag); - // open dropdown list if currently focused - this._handleFlagsContainerKeydown = function (e) { - var isDropdownHidden = _this4.countryList.classList.contains("iti__hide"); - if ( - isDropdownHidden && - ["ArrowUp", "Up", "ArrowDown", "Down", " ", "Enter"].indexOf(e.key) !== -1 - ) { - // prevent form from being submitted if "ENTER" was pressed - e.preventDefault(); - // prevent event from being handled again by document - e.stopPropagation(); - _this4._showDropdown(); - } - // allow navigation from dropdown to input on TAB - if (e.key === "Tab") _this4._closeDropdown(); - }; - this.flagsContainer.addEventListener("keydown", this._handleFlagsContainerKeydown); - }, - }, - { - key: "_initRequests", - value: function _initRequests() { - var _this5 = this; - // if the user has specified the path to the utils script, fetch it on window.load, else resolve - if (this.options.utilsScript && !window.intlTelInputUtils) { - // if the plugin is being initialised after the window.load event has already been fired - if (window.intlTelInputGlobals.documentReady()) { - window.intlTelInputGlobals.loadUtils(this.options.utilsScript); - } else { - // wait until the load event so we don't block any other requests e.g. the flags image - window.addEventListener("load", function () { - window.intlTelInputGlobals.loadUtils(_this5.options.utilsScript); - }); - } - } else this.resolveUtilsScriptPromise(); - if (this.options.initialCountry === "auto") this._loadAutoCountry(); - else this.resolveAutoCountryPromise(); - }, - }, - { - key: "_loadAutoCountry", - value: function _loadAutoCountry() { - // 3 options: - // 1) already loaded (we're done) - // 2) not already started loading (start) - // 3) already started loading (do nothing - just wait for loading callback to fire) - if (window.intlTelInputGlobals.autoCountry) { - this.handleAutoCountry(); - } else if (!window.intlTelInputGlobals.startedLoadingAutoCountry) { - // don't do this twice! - window.intlTelInputGlobals.startedLoadingAutoCountry = true; - if (typeof this.options.geoIpLookup === "function") { - this.options.geoIpLookup( - function (countryCode) { - window.intlTelInputGlobals.autoCountry = countryCode.toLowerCase(); - // tell all instances the auto country is ready - // TODO: this should just be the current instances - // UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight - // away (e.g. if they have already done the geo ip lookup somewhere else). Using - // setTimeout means that the current thread of execution will finish before executing - // this, which allows the plugin to finish initialising. - setTimeout(function () { - return forEachInstance("handleAutoCountry"); - }); - }, - function () { - return forEachInstance("rejectAutoCountryPromise"); - } - ); - } - } - }, - }, - { - key: "_initKeyListeners", - value: function _initKeyListeners() { - var _this6 = this; - // update flag on keyup - this._handleKeyupEvent = function () { - if (_this6._updateFlagFromNumber(_this6.telInput.value)) { - _this6._triggerCountryChange(); - } - }; - this.telInput.addEventListener("keyup", this._handleKeyupEvent); - // update flag on cut/paste events (now supported in all major browsers) - this._handleClipboardEvent = function () { - // hack because "paste" event is fired before input is updated - setTimeout(_this6._handleKeyupEvent); - }; - this.telInput.addEventListener("cut", this._handleClipboardEvent); - this.telInput.addEventListener("paste", this._handleClipboardEvent); - }, - }, - { - key: "_cap", - value: function _cap(number) { - var max = this.telInput.getAttribute("maxlength"); - return max && number.length > max ? number.substr(0, max) : number; - }, - }, - { - key: "_initBlurListeners", - value: function _initBlurListeners() { - var _this7 = this; - // on blur or form submit: if just a dial code then remove it - this._handleSubmitOrBlurEvent = function () { - _this7._removeEmptyDialCode(); - }; - if (this.telInput.form) - this.telInput.form.addEventListener("submit", this._handleSubmitOrBlurEvent); - this.telInput.addEventListener("blur", this._handleSubmitOrBlurEvent); - }, - }, - { - key: "_removeEmptyDialCode", - value: function _removeEmptyDialCode() { - if (this.telInput.value.charAt(0) === "+") { - var numeric = this._getNumeric(this.telInput.value); - // if just a plus, or if just a dial code - if (!numeric || this.selectedCountryData.dialCode === numeric) { - this.telInput.value = ""; - } - } - }, - }, - { - key: "_getNumeric", - value: function _getNumeric(s) { - return s.replace(/\D/g, ""); - }, - }, - { - key: "_trigger", - value: function _trigger(name) { - // have to use old school document.createEvent as IE11 doesn't support `new Event()` syntax - var e = document.createEvent("Event"); - e.initEvent(name, true, true); - // can bubble, and is cancellable - this.telInput.dispatchEvent(e); - }, - }, - { - key: "_showDropdown", - value: function _showDropdown() { - this.countryList.classList.remove("iti__hide"); - this.selectedFlag.setAttribute("aria-expanded", "true"); - this._setDropdownPosition(); - // update highlighting and scroll to active list item - if (this.activeItem) { - this._highlightListItem(this.activeItem, false); - this._scrollTo(this.activeItem, true); - } - // bind all the dropdown-related listeners: mouseover, click, click-off, keydown - this._bindDropdownListeners(); - // update the arrow - this.dropdownArrow.classList.add("iti__arrow--up"); - this._trigger("open:countrydropdown"); - }, - }, - { - key: "_toggleClass", - value: function _toggleClass(el, className, shouldHaveClass) { - if (shouldHaveClass && !el.classList.contains(className)) el.classList.add(className); - else if (!shouldHaveClass && el.classList.contains(className)) - el.classList.remove(className); - }, - }, - { - key: "_setDropdownPosition", - value: function _setDropdownPosition() { - var _this8 = this; - if (this.options.dropdownContainer) { - this.options.dropdownContainer.appendChild(this.dropdown); - } - if (!this.isMobile) { - var pos = this.telInput.getBoundingClientRect(); - // windowTop from https://stackoverflow.com/a/14384091/217866 - var windowTop = window.pageYOffset || document.documentElement.scrollTop; - var inputTop = pos.top + windowTop; - var dropdownHeight = this.countryList.offsetHeight; - // dropdownFitsBelow = (dropdownBottom < windowBottom) - var dropdownFitsBelow = - inputTop + this.telInput.offsetHeight + dropdownHeight < - windowTop + window.innerHeight; - var dropdownFitsAbove = inputTop - dropdownHeight > windowTop; - // by default, the dropdown will be below the input. If we want to position it above the - // input, we add the dropup class. - this._toggleClass( - this.countryList, - "iti__country-list--dropup", - !dropdownFitsBelow && dropdownFitsAbove - ); - // if dropdownContainer is enabled, calculate postion - if (this.options.dropdownContainer) { - // by default the dropdown will be directly over the input because it's not in the flow. - // If we want to position it below, we need to add some extra top value. - var extraTop = - !dropdownFitsBelow && dropdownFitsAbove ? 0 : this.telInput.offsetHeight; - // calculate placement - this.dropdown.style.top = "".concat(inputTop + extraTop, "px"); - this.dropdown.style.left = "".concat(pos.left + document.body.scrollLeft, "px"); - // close menu on window scroll - this._handleWindowScroll = function () { - return _this8._closeDropdown(); - }; - window.addEventListener("scroll", this._handleWindowScroll); - } - } - }, - }, - { - key: "_getClosestListItem", - value: function _getClosestListItem(target) { - var el = target; - while (el && el !== this.countryList && !el.classList.contains("iti__country")) { - el = el.parentNode; - } - // if we reached the countryList element, then return null - return el === this.countryList ? null : el; - }, - }, - { - key: "_bindDropdownListeners", - value: function _bindDropdownListeners() { - var _this9 = this; - // when mouse over a list item, just highlight that one - // we add the class "highlight", so if they hit "enter" we know which one to select - this._handleMouseoverCountryList = function (e) { - // handle event delegation, as we're listening for this event on the countryList - var listItem = _this9._getClosestListItem(e.target); - if (listItem) _this9._highlightListItem(listItem, false); - }; - this.countryList.addEventListener("mouseover", this._handleMouseoverCountryList); - // listen for country selection - this._handleClickCountryList = function (e) { - var listItem = _this9._getClosestListItem(e.target); - if (listItem) _this9._selectListItem(listItem); - }; - this.countryList.addEventListener("click", this._handleClickCountryList); - // click off to close - // (except when this initial opening click is bubbling up) - // we cannot just stopPropagation as it may be needed to close another instance - var isOpening = true; - this._handleClickOffToClose = function () { - if (!isOpening) _this9._closeDropdown(); - isOpening = false; - }; - document.documentElement.addEventListener("click", this._handleClickOffToClose); - // listen for up/down scrolling, enter to select, or letters to jump to country name. - // use keydown as keypress doesn't fire for non-char keys and we want to catch if they - // just hit down and hold it to scroll down (no keyup event). - // listen on the document because that's where key events are triggered if no input has focus - var query = ""; - var queryTimer = null; - this._handleKeydownOnDropdown = function (e) { - // prevent down key from scrolling the whole page, - // and enter key from submitting a form etc - e.preventDefault(); - // up and down to navigate - if ( - e.key === "ArrowUp" || - e.key === "Up" || - e.key === "ArrowDown" || - e.key === "Down" - ) - _this9._handleUpDownKey(e.key); - else if (e.key === "Enter") _this9._handleEnterKey(); - else if (e.key === "Escape") _this9._closeDropdown(); - else if (/^[a-zA-ZÀ-ÿа-яА-Я ]$/.test(e.key)) { - // jump to countries that start with the query string - if (queryTimer) clearTimeout(queryTimer); - query += e.key.toLowerCase(); - _this9._searchForCountry(query); - // if the timer hits 1 second, reset the query - queryTimer = setTimeout(function () { - query = ""; - }, 1e3); - } - }; - document.addEventListener("keydown", this._handleKeydownOnDropdown); - }, - }, - { - key: "_handleUpDownKey", - value: function _handleUpDownKey(key) { - var next = - key === "ArrowUp" || key === "Up" - ? this.highlightedItem.previousElementSibling - : this.highlightedItem.nextElementSibling; - if (next) { - // skip the divider - if (next.classList.contains("iti__divider")) { - next = - key === "ArrowUp" || key === "Up" - ? next.previousElementSibling - : next.nextElementSibling; - } - this._highlightListItem(next, true); - } - }, - }, - { - key: "_handleEnterKey", - value: function _handleEnterKey() { - if (this.highlightedItem) this._selectListItem(this.highlightedItem); - }, - }, - { - key: "_searchForCountry", - value: function _searchForCountry(query) { - for (var i = 0; i < this.countries.length; i++) { - if (this._startsWith(this.countries[i].name, query)) { - var listItem = this.countryList.querySelector( - "#iti-".concat(this.id, "__item-").concat(this.countries[i].iso2) - ); - // update highlighting and scroll - this._highlightListItem(listItem, false); - this._scrollTo(listItem, true); - break; - } - } - }, - }, - { - key: "_startsWith", - value: function _startsWith(a, b) { - return a.substr(0, b.length).toLowerCase() === b; - }, - }, - { - key: "_updateValFromNumber", - value: function _updateValFromNumber(originalNumber) { - var number = originalNumber; - if ( - this.options.formatOnDisplay && - window.intlTelInputUtils && - this.selectedCountryData - ) { - var useNational = - !this.options.separateDialCode && - (this.options.nationalMode || number.charAt(0) !== "+"); - var _intlTelInputUtils$nu = intlTelInputUtils.numberFormat, - NATIONAL = _intlTelInputUtils$nu.NATIONAL, - INTERNATIONAL = _intlTelInputUtils$nu.INTERNATIONAL; - var format = useNational ? NATIONAL : INTERNATIONAL; - number = intlTelInputUtils.formatNumber( - number, - this.selectedCountryData.iso2, - format - ); - } - number = this._beforeSetNumber(number); - this.telInput.value = number; - }, - }, - { - key: "_updateFlagFromNumber", - value: function _updateFlagFromNumber(originalNumber) { - // if we're in nationalMode and we already have US/Canada selected, make sure the number starts - // with a +1 so _getDialCode will be able to extract the area code - // update: if we dont yet have selectedCountryData, but we're here (trying to update the flag - // from the number), that means we're initialising the plugin with a number that already has a - // dial code, so fine to ignore this bit - var number = originalNumber; - var selectedDialCode = this.selectedCountryData.dialCode; - var isNanp = selectedDialCode === "1"; - if (number && this.options.nationalMode && isNanp && number.charAt(0) !== "+") { - if (number.charAt(0) !== "1") number = "1".concat(number); - number = "+".concat(number); - } - // update flag if user types area code for another country - if (this.options.separateDialCode && selectedDialCode && number.charAt(0) !== "+") { - number = "+".concat(selectedDialCode).concat(number); - } - // try and extract valid dial code from input - var dialCode = this._getDialCode(number, true); - var numeric = this._getNumeric(number); - var countryCode = null; - if (dialCode) { - var countryCodes = this.countryCodes[this._getNumeric(dialCode)]; - // check if the right country is already selected. this should be false if the number is - // longer than the matched dial code because in this case we need to make sure that if - // there are multiple country matches, that the first one is selected (note: we could - // just check that here, but it requires the same loop that we already have later) - var alreadySelected = - countryCodes.indexOf(this.selectedCountryData.iso2) !== -1 && - numeric.length <= dialCode.length - 1; - var isRegionlessNanpNumber = - selectedDialCode === "1" && this._isRegionlessNanp(numeric); - // only update the flag if: - // A) NOT (we currently have a NANP flag selected, and the number is a regionlessNanp) - // AND - // B) the right country is not already selected - if (!isRegionlessNanpNumber && !alreadySelected) { - // if using onlyCountries option, countryCodes[0] may be empty, so we must find the first - // non-empty index - for (var j = 0; j < countryCodes.length; j++) { - if (countryCodes[j]) { - countryCode = countryCodes[j]; - break; - } - } - } - } else if (number.charAt(0) === "+" && numeric.length) { - // invalid dial code, so empty - // Note: use getNumeric here because the number has not been formatted yet, so could contain - // bad chars - countryCode = ""; - } else if (!number || number === "+") { - // empty, or just a plus, so default - countryCode = this.defaultCountry; - } - if (countryCode !== null) { - return this._setFlag(countryCode); - } - return false; - }, - }, - { - key: "_isRegionlessNanp", - value: function _isRegionlessNanp(number) { - var numeric = this._getNumeric(number); - if (numeric.charAt(0) === "1") { - var areaCode = numeric.substr(1, 3); - return regionlessNanpNumbers.indexOf(areaCode) !== -1; - } - return false; - }, - }, - { - key: "_highlightListItem", - value: function _highlightListItem(listItem, shouldFocus) { - var prevItem = this.highlightedItem; - if (prevItem) prevItem.classList.remove("iti__highlight"); - this.highlightedItem = listItem; - this.highlightedItem.classList.add("iti__highlight"); - if (shouldFocus) this.highlightedItem.focus(); - }, - }, - { - key: "_getCountryData", - value: function _getCountryData(countryCode, ignoreOnlyCountriesOption, allowFail) { - var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries; - for (var i = 0; i < countryList.length; i++) { - if (countryList[i].iso2 === countryCode) { - return countryList[i]; - } - } - if (allowFail) { - return null; - } - throw new Error("No country data for '".concat(countryCode, "'")); - }, - }, - { - key: "_setFlag", - value: function _setFlag(countryCode) { - var prevCountry = this.selectedCountryData.iso2 ? this.selectedCountryData : {}; - // do this first as it will throw an error and stop if countryCode is invalid - this.selectedCountryData = countryCode - ? this._getCountryData(countryCode, false, false) - : {}; - // update the defaultCountry - we only need the iso2 from now on, so just store that - if (this.selectedCountryData.iso2) { - this.defaultCountry = this.selectedCountryData.iso2; - } - this.selectedFlagInner.setAttribute("class", "iti__flag iti__".concat(countryCode)); - // update the selected country's title attribute - var title = countryCode - ? "" - .concat(this.selectedCountryData.name, ": +") - .concat(this.selectedCountryData.dialCode) - : "Unknown"; - this.selectedFlag.setAttribute("title", title); - if (this.options.separateDialCode) { - var dialCode = this.selectedCountryData.dialCode - ? "+".concat(this.selectedCountryData.dialCode) - : ""; - this.selectedDialCode.innerHTML = dialCode; - // offsetWidth is zero if input is in a hidden container during initialisation - var selectedFlagWidth = - this.selectedFlag.offsetWidth || this._getHiddenSelectedFlagWidth(); - // add 6px of padding after the grey selected-dial-code box, as this is what we use in the css - this.telInput.style.paddingLeft = "".concat(selectedFlagWidth + 6, "px"); - } - // and the input's placeholder - this._updatePlaceholder(); - // update the active list item - if (this.options.allowDropdown) { - var prevItem = this.activeItem; - if (prevItem) { - prevItem.classList.remove("iti__active"); - prevItem.setAttribute("aria-selected", "false"); - } - if (countryCode) { - // check if there is a preferred item first, else fall back to standard - var nextItem = - this.countryList.querySelector( - "#iti-".concat(this.id, "__item-").concat(countryCode, "-preferred") - ) || - this.countryList.querySelector( - "#iti-".concat(this.id, "__item-").concat(countryCode) - ); - nextItem.setAttribute("aria-selected", "true"); - nextItem.classList.add("iti__active"); - this.activeItem = nextItem; - this.selectedFlag.setAttribute( - "aria-activedescendant", - nextItem.getAttribute("id") - ); - } - } - // return if the flag has changed or not - return prevCountry.iso2 !== countryCode; - }, - }, - { - key: "_getHiddenSelectedFlagWidth", - value: function _getHiddenSelectedFlagWidth() { - // to get the right styling to apply, all we need is a shallow clone of the container, - // and then to inject a deep clone of the selectedFlag element - var containerClone = this.telInput.parentNode.cloneNode(); - containerClone.style.visibility = "hidden"; - document.body.appendChild(containerClone); - var flagsContainerClone = this.flagsContainer.cloneNode(); - containerClone.appendChild(flagsContainerClone); - var selectedFlagClone = this.selectedFlag.cloneNode(true); - flagsContainerClone.appendChild(selectedFlagClone); - var width = selectedFlagClone.offsetWidth; - containerClone.parentNode.removeChild(containerClone); - return width; - }, - }, - { - key: "_updatePlaceholder", - value: function _updatePlaceholder() { - var shouldSetPlaceholder = - this.options.autoPlaceholder === "aggressive" || - (!this.hadInitialPlaceholder && this.options.autoPlaceholder === "polite"); - if (window.intlTelInputUtils && shouldSetPlaceholder) { - var numberType = intlTelInputUtils.numberType[this.options.placeholderNumberType]; - var placeholder = this.selectedCountryData.iso2 - ? intlTelInputUtils.getExampleNumber( - this.selectedCountryData.iso2, - this.options.nationalMode, - numberType - ) - : ""; - placeholder = this._beforeSetNumber(placeholder); - if (typeof this.options.customPlaceholder === "function") { - placeholder = this.options.customPlaceholder( - placeholder, - this.selectedCountryData - ); - } - this.telInput.setAttribute("placeholder", placeholder); - } - }, - }, - { - key: "_selectListItem", - value: function _selectListItem(listItem) { - // update selected flag and active list item - var flagChanged = this._setFlag(listItem.getAttribute("data-country-code")); - this._closeDropdown(); - this._updateDialCode(listItem.getAttribute("data-dial-code"), true); - // focus the input - this.telInput.focus(); - // put cursor at end - this fix is required for FF and IE11 (with nationalMode=false i.e. auto - // inserting dial code), who try to put the cursor at the beginning the first time - var len = this.telInput.value.length; - this.telInput.setSelectionRange(len, len); - if (flagChanged) { - this._triggerCountryChange(); - } - }, - }, - { - key: "_closeDropdown", - value: function _closeDropdown() { - this.countryList.classList.add("iti__hide"); - this.selectedFlag.setAttribute("aria-expanded", "false"); - // update the arrow - this.dropdownArrow.classList.remove("iti__arrow--up"); - // unbind key events - document.removeEventListener("keydown", this._handleKeydownOnDropdown); - document.documentElement.removeEventListener("click", this._handleClickOffToClose); - this.countryList.removeEventListener("mouseover", this._handleMouseoverCountryList); - this.countryList.removeEventListener("click", this._handleClickCountryList); - // remove menu from container - if (this.options.dropdownContainer) { - if (!this.isMobile) window.removeEventListener("scroll", this._handleWindowScroll); - if (this.dropdown.parentNode) this.dropdown.parentNode.removeChild(this.dropdown); - } - this._trigger("close:countrydropdown"); - }, - }, - { - key: "_scrollTo", - value: function _scrollTo(element, middle) { - var container = this.countryList; - // windowTop from https://stackoverflow.com/a/14384091/217866 - var windowTop = window.pageYOffset || document.documentElement.scrollTop; - var containerHeight = container.offsetHeight; - var containerTop = container.getBoundingClientRect().top + windowTop; - var containerBottom = containerTop + containerHeight; - var elementHeight = element.offsetHeight; - var elementTop = element.getBoundingClientRect().top + windowTop; - var elementBottom = elementTop + elementHeight; - var newScrollTop = elementTop - containerTop + container.scrollTop; - var middleOffset = containerHeight / 2 - elementHeight / 2; - if (elementTop < containerTop) { - // scroll up - if (middle) newScrollTop -= middleOffset; - container.scrollTop = newScrollTop; - } else if (elementBottom > containerBottom) { - // scroll down - if (middle) newScrollTop += middleOffset; - var heightDifference = containerHeight - elementHeight; - container.scrollTop = newScrollTop - heightDifference; - } - }, - }, - { - key: "_updateDialCode", - value: function _updateDialCode(newDialCodeBare, hasSelectedListItem) { - var inputVal = this.telInput.value; - // save having to pass this every time - var newDialCode = "+".concat(newDialCodeBare); - var newNumber; - if (inputVal.charAt(0) === "+") { - // there's a plus so we're dealing with a replacement (doesn't matter if nationalMode or not) - var prevDialCode = this._getDialCode(inputVal); - if (prevDialCode) { - // current number contains a valid dial code, so replace it - newNumber = inputVal.replace(prevDialCode, newDialCode); - } else { - // current number contains an invalid dial code, so ditch it - // (no way to determine where the invalid dial code ends and the rest of the number begins) - newNumber = newDialCode; - } - } else if (this.options.nationalMode || this.options.separateDialCode) { - // don't do anything - return; - } else { - // nationalMode is disabled - if (inputVal) { - // there is an existing value with no dial code: prefix the new dial code - newNumber = newDialCode + inputVal; - } else if (hasSelectedListItem || !this.options.autoHideDialCode) { - // no existing value and either they've just selected a list item, or autoHideDialCode is - // disabled: insert new dial code - newNumber = newDialCode; - } else { - return; - } - } - this.telInput.value = newNumber; - }, - }, - { - key: "_getDialCode", - value: function _getDialCode(number, includeAreaCode) { - var dialCode = ""; - // only interested in international numbers (starting with a plus) - if (number.charAt(0) === "+") { - var numericChars = ""; - // iterate over chars - for (var i = 0; i < number.length; i++) { - var c = number.charAt(i); - // if char is number (https://stackoverflow.com/a/8935649/217866) - if (!isNaN(parseInt(c, 10))) { - numericChars += c; - // if current numericChars make a valid dial code - if (includeAreaCode) { - if (this.countryCodes[numericChars]) { - // store the actual raw string (useful for matching later) - dialCode = number.substr(0, i + 1); - } - } else { - if (this.dialCodes[numericChars]) { - dialCode = number.substr(0, i + 1); - // if we're just looking for a dial code, we can break as soon as we find one - break; - } - } - // stop searching as soon as we can - in this case when we hit max len - if (numericChars.length === this.countryCodeMaxLen) { - break; - } - } - } - } - return dialCode; - }, - }, - { - key: "_getFullNumber", - value: function _getFullNumber() { - var val = this.telInput.value.trim(); - var dialCode = this.selectedCountryData.dialCode; - var prefix; - var numericVal = this._getNumeric(val); - if (this.options.separateDialCode && val.charAt(0) !== "+" && dialCode && numericVal) { - // when using separateDialCode, it is visible so is effectively part of the typed number - prefix = "+".concat(dialCode); - } else { - prefix = ""; - } - return prefix + val; - }, - }, - { - key: "_beforeSetNumber", - value: function _beforeSetNumber(originalNumber) { - var number = originalNumber; - if (this.options.separateDialCode) { - var dialCode = this._getDialCode(number); - // if there is a valid dial code - if (dialCode) { - // in case _getDialCode returned an area code as well - dialCode = "+".concat(this.selectedCountryData.dialCode); - // a lot of numbers will have a space separating the dial code and the main number, and - // some NANP numbers will have a hyphen e.g. +1 684-733-1234 - in both cases we want to get - // rid of it - // NOTE: don't just trim all non-numerics as may want to preserve an open parenthesis etc - var start = - number[dialCode.length] === " " || number[dialCode.length] === "-" - ? dialCode.length + 1 - : dialCode.length; - number = number.substr(start); - } - } - return this._cap(number); - }, - }, - { - key: "_triggerCountryChange", - value: function _triggerCountryChange() { - this._trigger("countrychange"); - }, - }, - { - key: "handleAutoCountry", - value: function handleAutoCountry() { - if (this.options.initialCountry === "auto") { - // we must set this even if there is an initial val in the input: in case the initial val is - // invalid and they delete it - they should see their auto country - this.defaultCountry = window.intlTelInputGlobals.autoCountry; - // if there's no initial value in the input, then update the flag - if (!this.telInput.value) { - this.setCountry(this.defaultCountry); - } - this.resolveAutoCountryPromise(); - } - }, - }, - { - key: "handleUtils", - value: function handleUtils() { - // if the request was successful - if (window.intlTelInputUtils) { - // if there's an initial value in the input, then format it - if (this.telInput.value) { - this._updateValFromNumber(this.telInput.value); - } - this._updatePlaceholder(); - } - this.resolveUtilsScriptPromise(); - }, - }, - { - key: "destroy", - value: function destroy() { - var form = this.telInput.form; - if (this.options.allowDropdown) { - // make sure the dropdown is closed (and unbind listeners) - this._closeDropdown(); - this.selectedFlag.removeEventListener("click", this._handleClickSelectedFlag); - this.flagsContainer.removeEventListener( - "keydown", - this._handleFlagsContainerKeydown - ); - // label click hack - var label = this._getClosestLabel(); - if (label) label.removeEventListener("click", this._handleLabelClick); - } - // unbind hiddenInput listeners - if (this.hiddenInput && form) - form.removeEventListener("submit", this._handleHiddenInputSubmit); - // unbind autoHideDialCode listeners - if (this.options.autoHideDialCode) { - if (form) form.removeEventListener("submit", this._handleSubmitOrBlurEvent); - this.telInput.removeEventListener("blur", this._handleSubmitOrBlurEvent); - } - // unbind key events, and cut/paste events - this.telInput.removeEventListener("keyup", this._handleKeyupEvent); - this.telInput.removeEventListener("cut", this._handleClipboardEvent); - this.telInput.removeEventListener("paste", this._handleClipboardEvent); - // remove attribute of id instance: data-intl-tel-input-id - this.telInput.removeAttribute("data-intl-tel-input-id"); - // remove markup (but leave the original input) - var wrapper = this.telInput.parentNode; - wrapper.parentNode.insertBefore(this.telInput, wrapper); - wrapper.parentNode.removeChild(wrapper); - delete window.intlTelInputGlobals.instances[this.id]; - }, - }, - { - key: "getExtension", - value: function getExtension() { - if (window.intlTelInputUtils) { - return intlTelInputUtils.getExtension( - this._getFullNumber(), - this.selectedCountryData.iso2 - ); - } - return ""; - }, - }, - { - key: "getNumber", - value: function getNumber(format) { - if (window.intlTelInputUtils) { - var iso2 = this.selectedCountryData.iso2; - return intlTelInputUtils.formatNumber(this._getFullNumber(), iso2, format); - } - return ""; - }, - }, - { - key: "getNumberType", - value: function getNumberType() { - if (window.intlTelInputUtils) { - return intlTelInputUtils.getNumberType( - this._getFullNumber(), - this.selectedCountryData.iso2 - ); - } - return -99; - }, - }, - { - key: "getSelectedCountryData", - value: function getSelectedCountryData() { - return this.selectedCountryData; - }, - }, - { - key: "getValidationError", - value: function getValidationError() { - if (window.intlTelInputUtils) { - var iso2 = this.selectedCountryData.iso2; - return intlTelInputUtils.getValidationError(this._getFullNumber(), iso2); - } - return -99; - }, - }, - { - key: "isValidNumber", - value: function isValidNumber() { - var val = this._getFullNumber().trim(); - var countryCode = this.options.nationalMode ? this.selectedCountryData.iso2 : ""; - return window.intlTelInputUtils - ? intlTelInputUtils.isValidNumber(val, countryCode) - : null; - }, - }, - { - key: "setCountry", - value: function setCountry(originalCountryCode) { - var countryCode = originalCountryCode.toLowerCase(); - // check if already selected - if (!this.selectedFlagInner.classList.contains("iti__".concat(countryCode))) { - this._setFlag(countryCode); - this._updateDialCode(this.selectedCountryData.dialCode, false); - this._triggerCountryChange(); - } - }, - }, - { - key: "setNumber", - value: function setNumber(number) { - // we must update the flag first, which updates this.selectedCountryData, which is used for - // formatting the number before displaying it - var flagChanged = this._updateFlagFromNumber(number); - this._updateValFromNumber(number); - if (flagChanged) { - this._triggerCountryChange(); - } - }, - }, - { - key: "setPlaceholderNumberType", - value: function setPlaceholderNumberType(type) { - this.options.placeholderNumberType = type; - this._updatePlaceholder(); - }, - }, - ]); - return Iti; - })(); - /******************** - * STATIC METHODS - ********************/ - // get the country data object - intlTelInputGlobals.getCountryData = function () { - return allCountries; - }; - // inject a