-
Notifications
You must be signed in to change notification settings - Fork 408
feat(clerk-js,clerk-react,types): Signal transfer support #6614
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
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
🦋 Changeset detectedLatest commit: 7418bf2 The changes in this PR will be included in the next version bump. This PR includes changesets to release 22 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
WalkthroughAdds transfer and external-account SSO flows: SignIn/SignUp futures gain transferability and existingSession getters; create accepts a transfer flag; SignUp adds captcha-guarded create and sso flows and SignUp.sso; state now emits signUp error signals; react exports useSignUpSignal; types and a bundlewatch threshold updated. Changes
Sequence Diagram(s)sequenceDiagram
participant App
participant SignUpFuture
participant CaptchaSvc as CaptchaService
participant API
participant Browser
rect rgba(70,130,180,0.08)
Note over App,SignUpFuture: Sign-up (create) with optional transfer
App->>SignUpFuture: create({ transfer? })
SignUpFuture->>CaptchaSvc: fetch captchaToken
CaptchaSvc-->>SignUpFuture: captchaToken
SignUpFuture->>API: POST /sign-up { transfer, captchaToken, ... }
API-->>SignUpFuture: { externalAccount?.status, externalVerificationUrl?, error? }
alt status == "transferable"
SignUpFuture-->>App: isTransferable = true (return)
else status == "failed" or "unverified" && externalVerificationUrl
SignUpFuture->>Browser: navigate externalVerificationUrl
SignUpFuture-->>App: return
else
SignUpFuture-->>App: return { error }
end
end
sequenceDiagram
participant App
participant SignInFuture
participant API
Note over App,SignInFuture: Sign-in create with optional transfer flag
App->>SignInFuture: create({ identifier?, transfer? })
SignInFuture->>API: POST /sign-in { identifier, transfer? }
API-->>SignInFuture: { firstFactorVerification?.status, error?.meta?.sessionId }
alt status == "transferable"
SignInFuture-->>App: isTransferable = true
else error indicates already-signed-in
SignInFuture-->>App: existingSession = { sessionId }
else
SignInFuture-->>App: return { error }
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/types/src/signIn.ts (1)
222-264: Tighten the “transfer-only” variant to requiretransfer: trueThe standalone union arm is indeed needed to allow calls like
signIn.create({ transfer: true })(and similarly forsignUp), but it’s too permissive as written (it even allows{}and{ transfer: false }). Instead, change it to only permit the literaltruein that branch, while retaining the intersection for the other variants.• File:
packages/types/src/signIn.ts
Replace the last union arm so that it requirestransfer: truerather than an optional boolean.export type SignInCreateParams = ( | { strategy: OAuthStrategy | SamlStrategy | EnterpriseSSOStrategy; redirectUrl: string; actionCompleteRedirectUrl?: string; identifier?: string; oidcPrompt?: string; oidcLoginHint?: string; } | { strategy: TicketStrategy; ticket: string; } | { strategy: GoogleOneTapStrategy; token: string; } | { strategy: PasswordStrategy; password: string; identifier: string; } | { strategy: PasskeyStrategy } | { strategy: | PhoneCodeStrategy | EmailCodeStrategy | Web3Strategy | ResetPasswordEmailCodeStrategy | ResetPasswordPhoneCodeStrategy; identifier: string; } | { strategy: EmailLinkStrategy; identifier: string; redirectUrl?: string; } | { identifier: string; } - | { transfer?: boolean } ) & { transfer?: boolean }; + | { transfer: true } ) & { transfer?: boolean };This ensures:
signIn.create({ transfer: true })still types correctly.- You can’t pass an empty object or
{ transfer: false }alone.- All other variants retain an optional
transferflag via the intersection.
🧹 Nitpick comments (13)
.changeset/late-results-melt.md (1)
1-8: Expand the changeset note with concrete API surface and migration hints.Current note is too terse for a minor bump across three packages. Please list the experimental APIs and behavioral changes added in this PR so downstreams understand what shipped:
- SignInFuture: getters isTransferable, existingSession; create({ transfer? }).
- SignUp/SignUpFuture: analogous transfer support and SSO helpers.
- React experimental exports: useSignUpSignal.
- State: SignUp errors now emitted via signUpErrorSignal.
If this feature is gated/undocumented, add a one-liner stating it’s experimental and subject to change, and point to any internal docs or follow-up docs PR.
packages/clerk-js/src/core/state.ts (1)
39-47: Reset fetch status on error to avoid stuck “loading” UIsOn error, we currently only emit the error signal—so if your UI went into
fetching, it never returns toidle. To fix this, update theonResourceErrorhandler inpackages/clerk-js/src/core/state.tsto also reset the fetch status:• In
onResourceError, after signaling the error, emit the corresponding fetch-idle signal.
• For example:--- a/packages/clerk-js/src/core/state.ts +++ b/packages/clerk-js/src/core/state.ts @@ private onResourceError = (payload: { resource: BaseResource; error: unknown }) => { if (payload.resource instanceof SignIn) { - this.signInErrorSignal({ error: payload.error }); + this.signInErrorSignal({ error: payload.error }); + this.signInFetchSignal({ status: 'idle' }); } if (payload.resource instanceof SignUp) { - this.signUpErrorSignal({ error: payload.error }); + this.signUpErrorSignal({ error: payload.error }); + this.signUpFetchSignal({ status: 'idle' }); } };This ensures that any “loading” state is promptly cleared when an error occurs.
packages/types/src/signIn.ts (1)
132-134: Add JSDoc for new fields on SignInFutureResource.Document the semantics to keep the public API self-describing:
- isTransferable: true when the first factor supports transfer to an existing session.
- existingSession: present when sign-in failed due to identifier_already_signed_in and contains the sessionId to target for transfer.
This helps IDE hovers and downstream TS users.
packages/clerk-js/src/core/resources/SignIn.ts (3)
486-667: Add focused tests for the new Future surface (unit or integration).Please add tests covering:
- isTransferable toggling based on firstFactorVerification.status.
- existingSession extraction when error.code === 'identifier_already_signed_in'.
- create({ transfer: true }) passes through and results in expected server interaction.
- sso() + create path remains unaffected by transfer unless explicitly set.
Happy to scaffold test cases using your preferred test runner; say the word and I’ll draft them.
512-523: Add inline JSDoc to theexistingSessiongetterThe error code string
"identifier_already_signed_in"is used consistently across the codebase (in both UI and core logic, as well as tests), so documenting its meaning here will improve maintainability and help future refactors.• File:
packages/clerk-js/src/core/resources/SignIn.ts
Lines: 512–523Suggested diff:
/** - * Present when sign-in failed because the identifier is already signed in elsewhere. - * Contains the { sessionId } that may be targeted for transfer. + * Returns the session ID when sign-in failed with code + * `"identifier_already_signed_in"` and the payload includes a `sessionId`. + * This indicates the identifier is already signed in; the returned + * `{ sessionId }` may be used to transfer or resume that session. + * + * @returns {{ sessionId: string } | undefined} */ get existingSession() { if ( this.resource.firstFactorVerification.status === 'failed' && this.resource.firstFactorVerification.error?.code === 'identifier_already_signed_in' && this.resource.firstFactorVerification.error?.meta?.sessionId ) { return { sessionId: this.resource.firstFactorVerification.error.meta.sessionId }; } return undefined; }
508-511: Add JSDoc forisTransferable(status literal confirmed valid)I’ve confirmed that
"transferable"is a member ofVerificationStatus(seepackages/types/src/verification.ts:26) and is consistently used for first-factor flows throughout the codebase. Adding a short JSDoc here will clarify when this flag flips totrueand how callers (e.g., custom UIs) should handle it.• Location:
packages/clerk-js/src/core/resources/SignIn.tsaround line 508
• Status literal verified in:
packages/types/src/verification.ts:26- Multiple usage sites in hooks, machines, SignUp/SignIn resources, and tests
Suggested inline JSDoc:
/** + * Returns true when the user’s first-factor verification status is + * “transferable”, indicating the flow can be continued on an existing session. + * Callers can use this to prompt a “Continue on existing session” UI path. */ get isTransferable() { return this.resource.firstFactorVerification.status === 'transferable'; }packages/types/src/signUp.ts (2)
125-127: Document new fields and harden param typing (readonly) on create()Add concise JSDoc for the new Future fields and mark the
transferparam asreadonlyto signal immutability at the call site. This also satisfies the “All public APIs must be documented with JSDoc” guideline.export interface SignUpFutureResource { status: SignUpStatus | null; unverifiedFields: SignUpIdentificationField[]; - isTransferable: boolean; - existingSession?: { sessionId: string }; - create: (params: { transfer?: boolean }) => Promise<{ error: unknown }>; + /** + * True when the external account can be transferred into this sign-up flow. + * Derived from backend verification signals for external accounts. + */ + isTransferable: boolean; + /** + * Present when the identifier is already signed in elsewhere (e.g. SSO already used). + * Use to prompt "Continue with existing session". + */ + existingSession?: { readonly sessionId: string }; + /** + * Starts the sign-up. When `transfer` is true, the backend may attempt to transfer + * a matched external account into the new sign-up. + */ + create: (params: { readonly transfer?: boolean }) => Promise<{ error: unknown }>;
133-135: Narrow SSO strategy typing to known strategy unions
strategy: stringis too loose for a public API. Tightening to the existing strategy unions improves DX and catches mistakes at compile time.- sso: (params: { strategy: string; redirectUrl: string; redirectUrlComplete: string }) => Promise<{ error: unknown }>; + /** + * Initiate SSO during sign-up using OAuth/SAML/Enterprise strategies. + */ + sso: (params: { + strategy: OAuthStrategy | SamlStrategy | EnterpriseSSOStrategy; + redirectUrl: string; + redirectUrlComplete: string; + }) => Promise<{ error: unknown }>;packages/clerk-js/src/core/resources/SignUp.ts (5)
117-120: Guard access tofirstFactorVerification.strategyin transfer pathAvoid potential undefined access; only set
params.strategywhen available. Keeps this path resilient in atypical client states.- if (params.transfer && this.shouldBypassCaptchaForAttempt(params)) { - params.strategy = SignUp.clerk.client?.signIn.firstFactorVerification.strategy; - } + if (params.transfer && this.shouldBypassCaptchaForAttempt(params)) { + const strategy = SignUp.clerk.client?.signIn?.firstFactorVerification?.strategy; + if (strategy) { + params.strategy = strategy; + } + }
498-509: Return a typed session object only whensessionIdis a stringMinor robustness: ensure we never return
{ sessionId: undefined }if the meta shape changes.- get existingSession() { - if ( - (this.resource.verifications.externalAccount.status === 'failed' || - this.resource.verifications.externalAccount.status === 'unverified') && - this.resource.verifications.externalAccount.error?.code === 'identifier_already_signed_in' && - this.resource.verifications.externalAccount.error?.meta?.sessionId - ) { - return { sessionId: this.resource.verifications.externalAccount.error?.meta?.sessionId }; - } - - return undefined; - } + get existingSession() { + const v = this.resource.verifications.externalAccount; + const code = v.error?.code; + const sessionId = v.error?.meta?.sessionId; + if ((v.status === 'failed' || v.status === 'unverified') && code === 'identifier_already_signed_in') { + return typeof sessionId === 'string' ? { sessionId } : undefined; + } + return undefined; + }
526-534: Deduplicate captcha logic: delegate toSignUp.createand add captcha-retry fallback
SignUpFuture.createreimplements captcha handling that already exists inSignUp.createand misses the environment-reload retry used elsewhere. Delegate tocreatefor consistency and add the same retry. Fewer moving parts, less drift.- async create({ transfer }: { transfer?: boolean }): Promise<{ error: unknown }> { - return runAsyncResourceTask(this.resource, async () => { - const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken(); - await this.resource.__internal_basePost({ - path: this.resource.pathRoot, - body: { transfer, captchaToken, captchaWidgetType, captchaError }, - }); - }); - } + async create({ transfer }: { transfer?: boolean }): Promise<{ error: unknown }> { + return runAsyncResourceTask(this.resource, async () => { + try { + await this.resource.create({ transfer }); + } catch (e) { + if (isClerkAPIResponseError(e) && isCaptchaError(e)) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + await SignUp.clerk.__unstable__environment!.reload(); + await this.resource.create({ transfer }); + } else { + throw e; + } + } + }); + }
572-604: Reusecreate()and mirror captcha-retry behavior in SSO flowThis mirrors
authenticateWithRedirectOrPopup’s resilience (captcha environment reload) and avoids duplicating captcha plumbing by delegating tocreate. Also mapsredirectUrlCompletetoactionCompleteRedirectUrlwhichcreatealready understands.- async sso({ - strategy, - redirectUrl, - redirectUrlComplete, - }: { - strategy: string; - redirectUrl: string; - redirectUrlComplete: string; - }): Promise<{ error: unknown }> { - return runAsyncResourceTask(this.resource, async () => { - const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken(); - await this.resource.__internal_basePost({ - path: this.resource.pathRoot, - body: { - strategy, - redirectUrl: SignUp.clerk.buildUrlWithAuth(redirectUrl), - redirectUrlComplete, - captchaToken, - captchaWidgetType, - captchaError, - }, - }); - - const { status, externalVerificationRedirectURL } = this.resource.verifications.externalAccount; - - if (status === 'unverified' && !!externalVerificationRedirectURL) { - windowNavigate(externalVerificationRedirectURL); - } else { - clerkInvalidFAPIResponse(status, SignUp.fapiClient.buildEmailAddress('support')); - } - }); - } + async sso({ + strategy, + redirectUrl, + redirectUrlComplete, + }: { + strategy: string; + redirectUrl: string; + redirectUrlComplete: string; + }): Promise<{ error: unknown }> { + return runAsyncResourceTask(this.resource, async () => { + const redirectUrlWithAuth = SignUp.clerk.buildUrlWithAuth(redirectUrl); + const createWithSSO = () => + this.resource.create({ + strategy, + redirectUrl: redirectUrlWithAuth, + actionCompleteRedirectUrl: redirectUrlComplete, + }); + + try { + await createWithSSO(); + } catch (e) { + if (isClerkAPIResponseError(e) && isCaptchaError(e)) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + await SignUp.clerk.__unstable__environment!.reload(); + await createWithSSO(); + } else { + throw e; + } + } + + const { status, externalVerificationRedirectURL } = this.resource.verifications.externalAccount; + if (status === 'unverified' && !!externalVerificationRedirectURL) { + windowNavigate(externalVerificationRedirectURL); + } else { + clerkInvalidFAPIResponse(status, SignUp.fapiClient.buildEmailAddress('support')); + } + }); + }Happy to push a follow-up commit if you want this refactor applied across the analogous SignInFuture flow as well.
526-534: Add tests for transfer and SSO “Future” flowsNo tests are shown in this PR. Please add focused unit/integration coverage for:
- SignUpFuture.isTransferable: true only when externalAccount.status === 'transferable' and error.code === 'external_account_exists'.
- SignUpFuture.existingSession: returns sessionId when error.code === 'identifier_already_signed_in' and meta.sessionId present; otherwise undefined.
- SignUpFuture.create: calls SignUp.create with { transfer }, and retries after environment reload on captcha error.
- SignUpFuture.sso:
- Posts with buildUrlWithAuth(redirectUrl) and maps redirectUrlComplete -> actionCompleteRedirectUrl when delegating to create.
- Navigates to externalVerificationRedirectURL on 'unverified'; throws via clerkInvalidFAPIResponse otherwise.
- SignUp.create (transfer path): when bypass applies, sets strategy from client.signIn.firstFactorVerification if present.
I can draft the tests (Jest + msw) and a small helper to fabricate
SignUp.verifications.externalAccountsnapshots if you’d like.Also applies to: 572-604, 491-497, 498-509
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (7)
.changeset/late-results-melt.md(1 hunks)packages/clerk-js/src/core/resources/SignIn.ts(2 hunks)packages/clerk-js/src/core/resources/SignUp.ts(3 hunks)packages/clerk-js/src/core/state.ts(1 hunks)packages/react/src/experimental.ts(1 hunks)packages/types/src/signIn.ts(1 hunks)packages/types/src/signUp.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
.changeset/**
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/late-results-melt.md
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/src/core/state.tspackages/types/src/signUp.tspackages/clerk-js/src/core/resources/SignIn.tspackages/react/src/experimental.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignUp.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/src/core/state.tspackages/types/src/signUp.tspackages/clerk-js/src/core/resources/SignIn.tspackages/react/src/experimental.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignUp.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/state.tspackages/types/src/signUp.tspackages/clerk-js/src/core/resources/SignIn.tspackages/react/src/experimental.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignUp.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/core/state.tspackages/types/src/signUp.tspackages/clerk-js/src/core/resources/SignIn.tspackages/react/src/experimental.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignUp.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/clerk-js/src/core/state.tspackages/types/src/signUp.tspackages/clerk-js/src/core/resources/SignIn.tspackages/react/src/experimental.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignUp.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/core/state.tspackages/types/src/signUp.tspackages/clerk-js/src/core/resources/SignIn.tspackages/react/src/experimental.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignUp.ts
**/*
⚙️ CodeRabbit configuration file
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/clerk-js/src/core/state.tspackages/types/src/signUp.tspackages/clerk-js/src/core/resources/SignIn.tspackages/react/src/experimental.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignUp.ts
🧬 Code graph analysis (2)
packages/types/src/signIn.ts (1)
packages/types/src/strategies.ts (1)
OAuthStrategy(18-18)
packages/clerk-js/src/core/resources/SignUp.ts (3)
packages/clerk-js/src/utils/runAsyncResourceTask.ts (1)
runAsyncResourceTask(8-30)packages/clerk-js/src/utils/windowNavigate.ts (1)
windowNavigate(19-23)packages/clerk-js/src/core/errors.ts (1)
clerkInvalidFAPIResponse(79-83)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (5)
packages/clerk-js/src/core/state.ts (1)
45-45: Correct fix: route SignUp errors to the error signal.This aligns SignUp with SignIn and prevents polluting the resource signal with error payloads.
packages/types/src/signIn.ts (1)
139-140: LGTM: create accepts transfer?: boolean.Type surface matches the runtime support added in SignInFuture.create.
packages/clerk-js/src/core/resources/SignIn.ts (1)
570-576: LGTM: create now forwards transfer to the API.Matches the types and the feature intent.
packages/react/src/experimental.ts (1)
4-4: Good fix: export useSignUpSignal.Restores parity with useSignInSignal and makes the experimental API discoverable.
packages/clerk-js/src/core/resources/SignUp.ts (1)
491-497: Transferability check looks correctThe predicate matches the described backend states for transferability. Nice and explicit.
| export { PlanDetailsButton } from './components/PlanDetailsButton'; | ||
| export { SubscriptionDetailsButton } from './components/SubscriptionDetailsButton'; | ||
| export { useSignInSignal } from './hooks/useClerkSignal'; | ||
| export { useSignInSignal, useSignUpSignal } from './hooks/useClerkSignal'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Ensure the hook is actually exported from hooks/useClerkSignal and add JSDoc at the source.
Add or verify JSDoc on the hook definition so consumers see guidance in IDEs (experimental, subject to change).
🏁 Script executed:
#!/bin/bash
# Confirm the named export exists and is correctly spelled.
rg -n "^export\s+\{\s*useSignInSignal\s*,\s*useSignUpSignal\s*\}" packages/react/src/hooks/useClerkSignal.ts
rg -n "export function useSignUpSignal|export const useSignUpSignal" packages/react/src/hooks/useClerkSignal.tsLength of output: 263
🏁 Script executed:
#!/bin/bash
# Verify presence of useSignInSignal and its export
rg -n "useSignInSignal" packages/react/src/hooks/useClerkSignal.ts
rg -C3 -n "export function useSignInSignal" packages/react/src/hooks/useClerkSignal.ts
# Verify presence of useSignUpSignal export context and surrounding JSDoc
rg -C3 -n "export function useSignUpSignal" packages/react/src/hooks/useClerkSignal.ts
rg -C3 -n "/\*\*" packages/react/src/hooks/useClerkSignal.tsLength of output: 589
Add JSDoc to exported hooks in useClerkSignal.ts
Both useSignInSignal (line 58) and useSignUpSignal (line 62) are correctly exported, but neither has preceding JSDoc comments. Please add descriptive JSDoc blocks above each function so IDEs surface usage details and mark these as experimental. For example:
• File: packages/react/src/hooks/useClerkSignal.ts
– Line 57–58 (before export function useSignInSignal):
/**
* Returns a signal that tracks the sign-in process.
*
* @remarks
* Experimental: subject to change.
*
* @returns A signal object for sign-in state.
*/
export function useSignInSignal() { … }• File: packages/react/src/hooks/useClerkSignal.ts
– Line 61–62 (before export function useSignUpSignal):
/**
* Returns a signal that tracks the sign-up process.
*
* @remarks
* Experimental: subject to change.
*
* @returns A signal object for sign-up state.
*/
export function useSignUpSignal() { … }This ensures consumers see the experimental-status notice and return type guidance in their IDEs.
🤖 Prompt for AI Agents
In packages/react/src/hooks/useClerkSignal.ts around lines 57–62, the exported
functions useSignInSignal and useSignUpSignal lack JSDoc comments; add
descriptive JSDoc blocks immediately above each export that briefly describe
what the hook returns, include an "@remarks Experimental: subject to change."
line, and an "@returns" annotation describing the returned signal object so IDEs
surface usage and the experimental status.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
packages/clerk-js/bundlewatch.config.json (1)
1-35: Add tests for new Signal transfer and error-routing behavior introduced by this PR.This config change accompanies new runtime features (transfer flag, new getters, SignUp.sso, and error signal routing). Ensure unit/integration coverage exists for:
- SignInFuture/SignUpFuture isTransferable and existingSession getters.
- create({ transfer }) flows for both sign-in and sign-up, including captcha paths.
- SignUp.sso(...) external-account redirect and error propagation to the dedicated sign-up error signal.
- react: experimental re-export of useSignUpSignal.
I can help draft test cases if needed.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/clerk-js/bundlewatch.config.json(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/bundlewatch.config.json
**/*
⚙️ CodeRabbit configuration file
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/clerk-js/bundlewatch.config.json
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/clerk-js/bundlewatch.config.json (1)
5-5: Build artifact missing – please generate and measure gzip/brotli sizesIt looks like
packages/clerk-js/dist/clerk.legacy.browser.jsisn’t present in the repo, so we can’t verify the bundle size automatically. To tighten your bundle budget and avoid masking unintended growth:
- Run the project build (e.g.,
pnpm build) to emitdist/clerk.legacy.browser.js.- Execute the sizing script from your repo root to record raw, gzip, and brotli outputs.
- In
packages/clerk-js/bundlewatch.config.json, setmaxSizeto the measured gzip size plus ~0.5 KB headroom.- Investigate why the legacy bundle grew (likely new polyfills for transfer/SSO); consider deferring or lazy-loading these in the legacy build.
Once you’ve measured and updated the threshold, please confirm here.
| this.resource.verifications.externalAccount.status === 'transferable' && | ||
| this.resource.verifications.externalAccount.error?.code === 'external_account_exists' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would expect the transferable status is all we need to check for here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
happy to take your word for it, but this is a direct copy-paste of the existing logic https://github.com/clerk/javascript/blob/main/packages/clerk-js/src/core/clerk.ts#L1935-L1936
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
makes sense, just thinking from first principles here 😅 I'm not sure why the extra check exists
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'll add a TODO note to it that we can likely drop the extra check!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
♻️ Duplicate comments (1)
packages/clerk-js/src/core/resources/SignUp.ts (1)
491-497: Simplify transferable check and add explicit return typeThe extra error-code coupling is brittle. The server-reported status should be authoritative. Also add an explicit return type and JSDoc since this is part of the experimental API surface.
Apply this diff:
- get isTransferable() { - // TODO: we can likely remove the error code check as the status should be sufficient - return ( - this.resource.verifications.externalAccount.status === 'transferable' && - this.resource.verifications.externalAccount.error?.code === 'external_account_exists' - ); - } + /** + * @experimental True if the external account can be transferred to the current user (as reported by FAPI). + */ + get isTransferable(): boolean { + return this.resource.verifications.externalAccount.status === 'transferable'; + }
🧹 Nitpick comments (1)
packages/clerk-js/src/core/resources/SignUp.ts (1)
499-510: Add explicit return type and minor readability refactor for existingSessionMake the return type explicit and avoid repeating the long property chain. Keeps semantics identical.
- get existingSession() { - if ( - (this.resource.verifications.externalAccount.status === 'failed' || - this.resource.verifications.externalAccount.status === 'unverified') && - this.resource.verifications.externalAccount.error?.code === 'identifier_already_signed_in' && - this.resource.verifications.externalAccount.error?.meta?.sessionId - ) { - return { sessionId: this.resource.verifications.externalAccount.error?.meta?.sessionId }; - } - - return undefined; - } + get existingSession(): { sessionId: string } | undefined { + const ext = this.resource.verifications.externalAccount; + const sid = ext.error?.meta?.sessionId; + if ((ext.status === 'failed' || ext.status === 'unverified') && ext.error?.code === 'identifier_already_signed_in' && sid) { + return { sessionId: sid }; + } + return undefined; + }
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
packages/clerk-js/src/core/resources/SignIn.ts(2 hunks)packages/clerk-js/src/core/resources/SignUp.ts(3 hunks)packages/types/src/signIn.ts(1 hunks)packages/types/src/signUp.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/clerk-js/src/core/resources/SignIn.ts
- packages/types/src/signIn.ts
- packages/types/src/signUp.ts
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/src/core/resources/SignUp.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/src/core/resources/SignUp.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/resources/SignUp.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/core/resources/SignUp.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/clerk-js/src/core/resources/SignUp.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/core/resources/SignUp.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/resources/SignUp.ts (3)
packages/clerk-js/src/utils/runAsyncResourceTask.ts (1)
runAsyncResourceTask(8-30)packages/clerk-js/src/utils/windowNavigate.ts (1)
windowNavigate(19-23)packages/clerk-js/src/core/errors.ts (1)
clerkInvalidFAPIResponse(79-83)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep/ci
- GitHub Check: semgrep-cloud-platform/scan
| async create({ transfer }: { transfer?: boolean }): Promise<{ error: unknown }> { | ||
| return runAsyncResourceTask(this.resource, async () => { | ||
| const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken(); | ||
| await this.resource.__internal_basePost({ | ||
| path: this.resource.pathRoot, | ||
| body: { transfer, captchaToken, captchaWidgetType, captchaError }, | ||
| }); | ||
| }); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unconditional captcha breaks OAuth bypass for transfer flows; mirror SignUp.create semantics
This always triggers a captcha challenge, diverging from SignUp.create (Lines 108-120) which bypasses captcha for OAuth strategies and transfer flows. In environments relying on captchaOauthBypass, this can fail with “Captcha challenge failed” and/or add unnecessary friction. Also, when transfer is true we should inject the first-factor strategy to align with the bypass logic.
Apply this diff to:
- Respect captchaBypass and captchaOauthBypass
- Inject the first-factor strategy during transfer bypass
- Only fetch captcha when needed
async create({ transfer }: { transfer?: boolean }): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
- const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
- await this.resource.__internal_basePost({
- path: this.resource.pathRoot,
- body: { transfer, captchaToken, captchaWidgetType, captchaError },
- });
+ // Mirror SignUp.create captcha-bypass semantics for transfer flows
+ const captchaBypass = SignUp.clerk.client?.captchaBypass;
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ const captchaOauthBypass = SignUp.clerk.__unstable__environment!.displayConfig.captchaOauthBypass;
+ const firstFactorStrategy = SignUp.clerk.client?.signIn.firstFactorVerification.strategy;
+ const shouldBypassCaptcha = Boolean(
+ transfer && firstFactorStrategy && captchaOauthBypass.some(s => s === firstFactorStrategy),
+ );
+
+ const body: Record<string, unknown> = { transfer };
+ if (!__BUILD_DISABLE_RHC__ && !captchaBypass && !shouldBypassCaptcha) {
+ const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
+ Object.assign(body, { captchaToken, captchaWidgetType, captchaError });
+ } else if (transfer && firstFactorStrategy) {
+ Object.assign(body, { strategy: firstFactorStrategy });
+ }
+
+ await this.resource.__internal_basePost({
+ path: this.resource.pathRoot,
+ body,
+ });
});
}Optional follow-up: factor the bypass computation into a shared helper to keep SignUp and SignUpFuture in lockstep.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| async create({ transfer }: { transfer?: boolean }): Promise<{ error: unknown }> { | |
| return runAsyncResourceTask(this.resource, async () => { | |
| const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken(); | |
| await this.resource.__internal_basePost({ | |
| path: this.resource.pathRoot, | |
| body: { transfer, captchaToken, captchaWidgetType, captchaError }, | |
| }); | |
| }); | |
| } | |
| async create({ transfer }: { transfer?: boolean }): Promise<{ error: unknown }> { | |
| return runAsyncResourceTask(this.resource, async () => { | |
| // Mirror SignUp.create captcha-bypass semantics for transfer flows | |
| const captchaBypass = SignUp.clerk.client?.captchaBypass; | |
| // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
| const captchaOauthBypass = SignUp.clerk.__unstable__environment!.displayConfig.captchaOauthBypass; | |
| const firstFactorStrategy = SignUp.clerk.client?.signIn.firstFactorVerification.strategy; | |
| const shouldBypassCaptcha = Boolean( | |
| transfer && firstFactorStrategy && captchaOauthBypass.some(s => s === firstFactorStrategy), | |
| ); | |
| const body: Record<string, unknown> = { transfer }; | |
| if (!__BUILD_DISABLE_RHC__ && !captchaBypass && !shouldBypassCaptcha) { | |
| const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken(); | |
| Object.assign(body, { captchaToken, captchaWidgetType, captchaError }); | |
| } else if (transfer && firstFactorStrategy) { | |
| Object.assign(body, { strategy: firstFactorStrategy }); | |
| } | |
| await this.resource.__internal_basePost({ | |
| path: this.resource.pathRoot, | |
| body, | |
| }); | |
| }); | |
| } |
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignUp.ts around lines 527 to 535, the
create method always requests a captcha which breaks OAuth/transfer bypass
behavior; change it to mirror SignUp.create (lines 108-120) by computing captcha
bypass (respecting captchaBypass and captchaOauthBypass and bypassing when
strategy is OAuth or transfer flow), only call getCaptchaToken when captcha is
needed, and when transfer===true include the firstFactorStrategy in the request
body to enable transfer bypass; update the body passed to __internal_basePost to
conditionally include captchaToken/captchaWidgetType/captchaError and
firstFactorStrategy so transfer and OAuth flows skip the captcha challenge.
| async sso({ | ||
| strategy, | ||
| redirectUrl, | ||
| redirectUrlComplete, | ||
| }: { | ||
| strategy: string; | ||
| redirectUrl: string; | ||
| redirectUrlComplete: string; | ||
| }): Promise<{ error: unknown }> { | ||
| return runAsyncResourceTask(this.resource, async () => { | ||
| const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken(); | ||
| await this.resource.__internal_basePost({ | ||
| path: this.resource.pathRoot, | ||
| body: { | ||
| strategy, | ||
| redirectUrl: SignUp.clerk.buildUrlWithAuth(redirectUrl), | ||
| redirectUrlComplete, | ||
| captchaToken, | ||
| captchaWidgetType, | ||
| captchaError, | ||
| }, | ||
| }); | ||
|
|
||
| const { status, externalVerificationRedirectURL } = this.resource.verifications.externalAccount; | ||
|
|
||
| if (status === 'unverified' && !!externalVerificationRedirectURL) { | ||
| windowNavigate(externalVerificationRedirectURL); | ||
| } else { | ||
| clerkInvalidFAPIResponse(status, SignUp.fapiClient.buildEmailAddress('support')); | ||
| } | ||
| }); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix SSO body field name, use union type for strategy, and mirror captcha-bypass + one-retry-on-captcha-error semantics
- Server expects actionCompleteRedirectUrl (not redirectUrlComplete) when posting to FAPI (see authenticateWithRedirectOrPopup above).
- Use the union type for strategy instead of string.
- Respect captchaOauthBypass for SSO strategies and implement the environment-reload-on-captcha-error retry used elsewhere for resilience.
async sso({
strategy,
redirectUrl,
redirectUrlComplete,
}: {
- strategy: string;
+ strategy: SignUpCreateParams['strategy'];
redirectUrl: string;
redirectUrlComplete: string;
}): Promise<{ error: unknown }> {
return runAsyncResourceTask(this.resource, async () => {
- const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
- await this.resource.__internal_basePost({
- path: this.resource.pathRoot,
- body: {
- strategy,
- redirectUrl: SignUp.clerk.buildUrlWithAuth(redirectUrl),
- redirectUrlComplete,
- captchaToken,
- captchaWidgetType,
- captchaError,
- },
- });
+ const redirectUrlWithAuth = SignUp.clerk.buildUrlWithAuth(redirectUrl);
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ const captchaOauthBypass = SignUp.clerk.__unstable__environment!.displayConfig.captchaOauthBypass;
+ const shouldBypassCaptcha = captchaOauthBypass.some(s => s === strategy);
+
+ const postOnce = async () => {
+ const body: Record<string, unknown> = {
+ strategy,
+ redirectUrl: redirectUrlWithAuth,
+ actionCompleteRedirectUrl: redirectUrlComplete,
+ };
+ if (!shouldBypassCaptcha) {
+ const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken();
+ Object.assign(body, { captchaToken, captchaWidgetType, captchaError });
+ }
+ await this.resource.__internal_basePost({
+ path: this.resource.pathRoot,
+ body,
+ });
+ };
+
+ try {
+ await postOnce();
+ } catch (e) {
+ if (isClerkAPIResponseError(e) && isCaptchaError(e)) {
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ await SignUp.clerk.__unstable__environment!.reload();
+ await postOnce();
+ } else {
+ throw e;
+ }
+ }
const { status, externalVerificationRedirectURL } = this.resource.verifications.externalAccount;
if (status === 'unverified' && !!externalVerificationRedirectURL) {
windowNavigate(externalVerificationRedirectURL);
} else {
clerkInvalidFAPIResponse(status, SignUp.fapiClient.buildEmailAddress('support'));
}
});
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| async sso({ | |
| strategy, | |
| redirectUrl, | |
| redirectUrlComplete, | |
| }: { | |
| strategy: string; | |
| redirectUrl: string; | |
| redirectUrlComplete: string; | |
| }): Promise<{ error: unknown }> { | |
| return runAsyncResourceTask(this.resource, async () => { | |
| const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken(); | |
| await this.resource.__internal_basePost({ | |
| path: this.resource.pathRoot, | |
| body: { | |
| strategy, | |
| redirectUrl: SignUp.clerk.buildUrlWithAuth(redirectUrl), | |
| redirectUrlComplete, | |
| captchaToken, | |
| captchaWidgetType, | |
| captchaError, | |
| }, | |
| }); | |
| const { status, externalVerificationRedirectURL } = this.resource.verifications.externalAccount; | |
| if (status === 'unverified' && !!externalVerificationRedirectURL) { | |
| windowNavigate(externalVerificationRedirectURL); | |
| } else { | |
| clerkInvalidFAPIResponse(status, SignUp.fapiClient.buildEmailAddress('support')); | |
| } | |
| }); | |
| } | |
| async sso({ | |
| strategy, | |
| redirectUrl, | |
| redirectUrlComplete, | |
| }: { | |
| strategy: SignUpCreateParams['strategy']; | |
| redirectUrl: string; | |
| redirectUrlComplete: string; | |
| }): Promise<{ error: unknown }> { | |
| return runAsyncResourceTask(this.resource, async () => { | |
| const redirectUrlWithAuth = SignUp.clerk.buildUrlWithAuth(redirectUrl); | |
| // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
| const captchaOauthBypass = SignUp.clerk.__unstable__environment!.displayConfig.captchaOauthBypass; | |
| const shouldBypassCaptcha = captchaOauthBypass.some(s => s === strategy); | |
| const postOnce = async () => { | |
| const body: Record<string, unknown> = { | |
| strategy, | |
| redirectUrl: redirectUrlWithAuth, | |
| actionCompleteRedirectUrl: redirectUrlComplete, | |
| }; | |
| if (!shouldBypassCaptcha) { | |
| const { captchaToken, captchaWidgetType, captchaError } = await this.getCaptchaToken(); | |
| Object.assign(body, { captchaToken, captchaWidgetType, captchaError }); | |
| } | |
| await this.resource.__internal_basePost({ | |
| path: this.resource.pathRoot, | |
| body, | |
| }); | |
| }; | |
| try { | |
| await postOnce(); | |
| } catch (e) { | |
| if (isClerkAPIResponseError(e) && isCaptchaError(e)) { | |
| // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
| await SignUp.clerk.__unstable__environment!.reload(); | |
| await postOnce(); | |
| } else { | |
| throw e; | |
| } | |
| } | |
| const { status, externalVerificationRedirectURL } = this.resource.verifications.externalAccount; | |
| if (status === 'unverified' && !!externalVerificationRedirectURL) { | |
| windowNavigate(externalVerificationRedirectURL); | |
| } else { | |
| clerkInvalidFAPIResponse(status, SignUp.fapiClient.buildEmailAddress('support')); | |
| } | |
| }); | |
| } |
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignUp.ts around lines 573 to 604, the
SSO method needs three fixes: change the POST body field redirectUrlComplete to
actionCompleteRedirectUrl (server expects actionCompleteRedirectUrl), change the
strategy parameter type from string to the existing strategy union type used
elsewhere in the codebase, and implement captcha-bypass +
one-retry-on-captcha-error semantics for SSO: include the captchaOauthBypass
flag (read from the same config/source used elsewhere) in the POST body, and if
getCaptchaToken returns a captchaError, reload the environment/state and retry
the POST exactly once before failing. Ensure the rest of the flow (handling
externalVerificationRedirectURL and clerkInvalidFAPIResponse) remains unchanged.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
packages/react/src/stateProxy.ts (1)
70-76: SignUp proxy methods are correctly wired; optionalexistingSessionplaceholder for shape parityThe
createandssomethods on the SignUp proxy are already returning Promises in your types, so wrapping them withgateMethod(which itself isasync) preserves the expected return types:
- SignUpFutureResource defines
•create: (params: { transfer?: boolean }) => Promise<{ error: unknown }>
•sso: (params: { strategy: string; redirectUrl: string; redirectUrlComplete: string }) => Promise<{ error: unknown }>- Wrapping a Promise-returning function in an
asyncwrapper returns the samePromise<…>shape, not a nested Promise.As an optional refactoring to keep the pre-load object shape aligned with the future resource, you may add an explicit
existingSession: undefinedplaceholder. The SignUpFutureResource already exposesexistingSession?: { sessionId: string }, so this ensures parity with SignIn:unverifiedFields: [], isTransferable: false, + // Keep shape parity with SignUpFutureResource while Clerk loads + existingSession: undefined, create: this.gateMethod(target, 'create'), sso: this.gateMethod(target, 'sso'),No further verification is required—both methods return Promises as expected.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/react/src/stateProxy.ts(2 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/react/src/stateProxy.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/react/src/stateProxy.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/react/src/stateProxy.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/react/src/stateProxy.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/react/src/stateProxy.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/react/src/stateProxy.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/react/src/stateProxy.ts (1)
46-46: The helper script will print the relevant sections of the SignIn and SignUp future types and confirm whether React code already readsexistingSession. Once we have that, we can decide if adding the placeholder is safe.
Description
This PR implements sign-in/sign-up transfer support in our Signal implementation, which is not yet intended for public use. It also fixes two smaller issues, one where
useSignUpSignalwas not exported, and another where sign-up errors were sent to the incorrect Signal.Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
New Features
Bug Fixes
Chores