Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(clerk-js): Support loaded clerk without environment (experimental) #5288

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changeset/breezy-monkeys-compare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
56 changes: 36 additions & 20 deletions packages/clerk-js/src/core/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,10 @@ export class Clerk implements ClerkInterface {
return this.#loaded;
}

get __internal_resiliency(): boolean {
return this.#options.experimental?.resiliency ?? false;
}

get isSatellite(): boolean {
if (inBrowser()) {
return handleValueOrFn(this.#options.isSatellite, new URL(window.location.href), false);
Expand Down Expand Up @@ -1113,6 +1117,7 @@ export class Clerk implements ClerkInterface {
return this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl);
}

// TODO: Removed since Core 2
public buildHomeUrl(): string {
if (!this.environment || !this.environment.displayConfig) {
return '';
Expand All @@ -1137,10 +1142,10 @@ export class Clerk implements ClerkInterface {
}

public buildWaitlistUrl(options?: { initialValues?: Record<string, string> }): string {
if (!this.environment || !this.environment.displayConfig) {
if (!this.__internal_resiliency && (!this.environment || !this.environment.displayConfig)) {
return '';
}
const waitlistUrl = this.#options['waitlistUrl'] || this.environment.displayConfig.waitlistUrl;
const waitlistUrl = this.#options['waitlistUrl'] || this.environment?.displayConfig.waitlistUrl;
const initValues = new URLSearchParams(options?.initialValues || {});
return buildURL({ base: waitlistUrl, hashSearchParams: [initValues] }, { stringify: true });
}
Expand Down Expand Up @@ -1315,7 +1320,7 @@ export class Clerk implements ClerkInterface {
params: HandleOAuthCallbackParams,
customNavigate?: (to: string) => Promise<unknown>,
): Promise<unknown> => {
if (!this.loaded || !this.environment || !this.client) {
if (!this.loaded || !this.client) {
return;
}
const { signIn: _signIn, signUp: _signUp } = this.client;
Expand Down Expand Up @@ -1347,11 +1352,11 @@ export class Clerk implements ClerkInterface {
navigate: (to: string) => Promise<unknown>;
},
): Promise<unknown> => {
if (!this.loaded || !this.environment || !this.client) {
if (!this.loaded || (!this.environment && !this.__internal_resiliency) || !this.client) {
return;
}

const { displayConfig } = this.environment;
const displayConfig = this.environment?.displayConfig;
const { firstFactorVerification } = signIn;
const { externalAccount } = signUp.verifications;
const su = {
Expand All @@ -1373,23 +1378,22 @@ export class Clerk implements ClerkInterface {

const makeNavigate = (to: string) => () => navigate(to);

const navigateToSignIn = makeNavigate(params.signInUrl || displayConfig.signInUrl);

const navigateToSignUp = makeNavigate(params.signUpUrl || displayConfig.signUpUrl);
const navigateToSignIn = makeNavigate(params.signInUrl || displayConfig?.signInUrl || '');
const navigateToSignUp = makeNavigate(params.signUpUrl || displayConfig?.signUpUrl || '');

const navigateToFactorOne = makeNavigate(
params.firstFactorUrl ||
buildURL({ base: displayConfig.signInUrl, hashPath: '/factor-one' }, { stringify: true }),
buildURL({ base: displayConfig?.signInUrl, hashPath: '/factor-one' }, { stringify: true }),
);

const navigateToFactorTwo = makeNavigate(
params.secondFactorUrl ||
buildURL({ base: displayConfig.signInUrl, hashPath: '/factor-two' }, { stringify: true }),
buildURL({ base: displayConfig?.signInUrl, hashPath: '/factor-two' }, { stringify: true }),
);

const navigateToResetPassword = makeNavigate(
params.resetPasswordUrl ||
buildURL({ base: displayConfig.signInUrl, hashPath: '/reset-password' }, { stringify: true }),
buildURL({ base: displayConfig?.signInUrl, hashPath: '/reset-password' }, { stringify: true }),
);

const redirectUrls = new RedirectUrls(this.#options, params);
Expand All @@ -1398,7 +1402,7 @@ export class Clerk implements ClerkInterface {
params.continueSignUpUrl ||
buildURL(
{
base: displayConfig.signUpUrl,
base: displayConfig?.signUpUrl,
hashPath: '/continue',
},
{ stringify: true },
Expand All @@ -1416,14 +1420,14 @@ export class Clerk implements ClerkInterface {
params.verifyEmailAddressUrl ||
buildURL(
{
base: displayConfig.signUpUrl,
base: displayConfig?.signUpUrl,
hashPath: '/verify-email-address',
},
{ stringify: true },
),
verifyPhonePath:
params.verifyPhoneNumberUrl ||
buildURL({ base: displayConfig.signUpUrl, hashPath: '/verify-phone-number' }, { stringify: true }),
buildURL({ base: displayConfig?.signUpUrl, hashPath: '/verify-phone-number' }, { stringify: true }),
navigate,
});
};
Expand Down Expand Up @@ -1549,7 +1553,7 @@ export class Clerk implements ClerkInterface {
params: HandleOAuthCallbackParams = {},
customNavigate?: (to: string) => Promise<unknown>,
): Promise<unknown> => {
if (!this.loaded || !this.environment || !this.client) {
if (!this.loaded || (!this.environment && !this.__internal_resiliency) || !this.client) {
return;
}
const { signIn, signUp } = this.client;
Expand Down Expand Up @@ -1663,7 +1667,7 @@ export class Clerk implements ClerkInterface {
return;
}

if (!this.client || !this.environment) {
if (!this.client || !(this.__internal_resiliency ? this.loaded : this.environment)) {
return;
}
const provider = strategy.replace('web3_', '').replace('_signature', '') as Web3Provider;
Expand Down Expand Up @@ -1939,6 +1943,7 @@ export class Clerk implements ClerkInterface {

const isInAccountsHostedPages = isDevAccountPortalOrigin(window?.location.hostname);
const shouldTouchEnv = this.#instanceType === 'development' && !isInAccountsHostedPages;
let envFailed = false;

let retries = 0;
while (retries < 2) {
Expand All @@ -1949,6 +1954,10 @@ export class Clerk implements ClerkInterface {
.fetch({ touch: shouldTouchEnv })
.then(res => {
this.updateEnvironment(res);
})
.catch(e => {
envFailed = true;
throw e;
});

const initClient = () => {
Expand All @@ -1968,13 +1977,20 @@ export class Clerk implements ClerkInterface {
};

await Promise.all([initEnvironmentPromise, initClient()]).catch(async e => {
const rethrow = (e: any) => {
if (envFailed && this.__internal_resiliency) {
return;
}
throw e;
};

// limit the changes for this specific error for now
if (isClerkAPIResponseError(e) && e.errors[0].code === 'requires_captcha') {
await initEnvironmentPromise;
await initEnvironmentPromise.catch(rethrow);
initComponents();
await initClient();
} else {
throw e;
rethrow(e);
}
});

Expand Down Expand Up @@ -2190,11 +2206,11 @@ export class Clerk implements ClerkInterface {
options: RedirectOptions,
_initValues?: Record<string, string>,
): string => {
if (!key || !this.loaded || !this.environment || !this.environment.displayConfig) {
if (!key || !this.loaded) {
return '';
}

let signInOrUpUrl = this.#options[key] || this.environment.displayConfig[key];
let signInOrUpUrl = this.#options[key] || this.environment?.displayConfig[key] || '';
if (this.#isCombinedSignInOrUpFlow()) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- The isCombinedSignInOrUpFlow() function checks for the existence of signInUrl
signInOrUpUrl = this.#options.signInUrl!;
Expand Down
15 changes: 11 additions & 4 deletions packages/clerk-js/src/core/resources/SignUp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,15 @@ export class SignUp extends BaseResource implements SignUpResource {
// to reload the environment and try again one more time with the new environment.
// If this fails again, we will let the caller handle the error accordingly.
if (isClerkAPIResponseError(e) && isCaptchaError(e)) {
await SignUp.clerk.__unstable__environment!.reload();
return authenticateFn();
if (SignUp.clerk.__unstable__environment) {
try {
await SignUp.clerk.__unstable__environment.reload();
return authenticateFn();
} catch {
// If the environment reload fails, we will throw the original error
throw e;
}
}
}
throw e;
});
Expand Down Expand Up @@ -416,15 +423,15 @@ export class SignUp extends BaseResource implements SignUpResource {
return false;
}

const captchaOauthBypass = SignUp.clerk.__unstable__environment!.displayConfig.captchaOauthBypass;
const captchaOauthBypass = SignUp.clerk.__unstable__environment?.displayConfig.captchaOauthBypass || [];

if (captchaOauthBypass.some(strategy => strategy === params.strategy)) {
return true;
}

if (
params.transfer &&
captchaOauthBypass.some(strategy => strategy === SignUp.clerk.client!.signIn.firstFactorVerification.strategy)
captchaOauthBypass.some(strategy => strategy === SignUp.clerk.client?.signIn?.firstFactorVerification?.strategy)
) {
return true;
}
Expand Down
13 changes: 11 additions & 2 deletions packages/clerk-js/src/ui/Components.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useSafeLayoutEffect } from '@clerk/shared/react';
import { createDeferredPromise } from '@clerk/shared/utils';
import { createDeferredPromise, noop } from '@clerk/shared/utils';
import type {
__internal_UserVerificationProps,
Appearance,
Expand Down Expand Up @@ -143,7 +143,11 @@ function assertDOMElement(element: HTMLElement): asserts element {
}
}

export const mountComponentRenderer = (clerk: Clerk, environment: EnvironmentResource, options: ClerkOptions) => {
export const mountComponentRenderer = (
clerk: Clerk,
environment: EnvironmentResource | undefined,
options: ClerkOptions,
) => {
// TODO: Init of components should start
// before /env and /client requests
let clerkRoot = document.getElementById(ROOT_ELEMENT_ID);
Expand All @@ -158,6 +162,11 @@ export const mountComponentRenderer = (clerk: Clerk, environment: EnvironmentRes

return {
ensureMounted: async (opts?: { preloadHint: ClerkComponentName }) => {
if (!environment) {
return new Promise<ComponentControls>(res => {
res(new Proxy({}, { get: () => noop }) as ComponentControls);
});
}
const { preloadHint } = opts || {};
// This mechanism ensures that mountComponentControls will only be called once
// and any calls to .mount before mountComponentControls resolves will fire in order.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export function createClerkInstance(ClerkClass: typeof Clerk) {

__internal_clerk.addListener(({ client }) => {
// @ts-expect-error - This is an internal API
const environment = __internal_clerk?.__unstable__environment as EnvironmentResource;
const environment = __internal_clerk?.__unstable__environment;
if (environment) {
void EnvironmentResourceCache.save(environment.__internal_toSnapshot());
}
Expand Down
1 change: 1 addition & 0 deletions packages/types/src/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -773,6 +773,7 @@ export type ClerkOptions = ClerkOptionsNavigation &
persistClient: boolean;
rethrowOfflineNetworkErrors: boolean;
combinedFlow: boolean;
resiliency: boolean;
},
Record<string, any>
>;
Expand Down