-
Notifications
You must be signed in to change notification settings - Fork 382
fix(clerk-js): Send client_id in CHIPS build #6758
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
base: main
Are you sure you want to change the base?
Conversation
The latest updates on your projects. Learn more about Vercel for GitHub.
|
🦋 Changeset detectedLatest commit: e124825 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 |
WalkthroughAdds an optional Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant App
participant Runtime as inIframe()
participant Resource as SignIn/SignUp
participant Base as BaseResource.clerk
participant Backend as API
App->>Resource: create()/update()/authenticateWithRedirectOrPopup(params)
Resource->>Runtime: inIframe()
Runtime-->>Resource: true/false
alt __BUILD_VARIANT_CHIPS__ && inIframe() == true
rect #EBF8FF
Resource->>Base: read client?.id
Resource->>Resource: clone params -> createParams/finalParams
Resource->>Resource: set createParams.clientId = client.id
end
end
Resource->>Backend: POST/PATCH with body (maybe includes clientId)
Backend-->>Resource: response
Resource-->>App: result / redirect
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing touches
🧪 Generate unit tests
Comment |
@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: |
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 (4)
packages/types/src/signUpCommon.ts (1)
103-106
: Make the property optional for readability (already optional via Partial)The field is inside a Partial<…>, so it’s effectively optional. For consistency with SignIn types, consider adding ?.
Apply:
- iframeContext: boolean; + iframeContext?: boolean;packages/clerk-js/src/core/resources/SignUp.ts (2)
146-149
: Correctly signaling iframe context on createGated by BUILD_VARIANT_CHIPS and inIframe(), which matches the PR goal.
Avoid overriding a pre-set value (even if internal) by only setting when undefined:
- if (__BUILD_VARIANT_CHIPS__ && inIframe()) { - finalParams.iframeContext = true; - } + if (__BUILD_VARIANT_CHIPS__ && inIframe() && finalParams.iframeContext === undefined) { + finalParams.iframeContext = true; + }Please confirm normalizeUnsafeMetadata preserves unknown top-level keys like iframeContext.
434-442
: Propagating iframe context on update as well — good coverageMirrors create() behavior so both create/update payloads carry the signal.
Extract a small helper to DRY this logic across create/update:
+const withIframeContext = <T extends Record<string, unknown>>(params: T): T => + (__BUILD_VARIANT_CHIPS__ && inIframe() && params.iframeContext === undefined + ? ({ ...params, iframeContext: true } as T) + : params); ... - const finalParams = { ...params }; - if (__BUILD_VARIANT_CHIPS__ && inIframe()) { - finalParams.iframeContext = true; - } + const finalParams = withIframeContext({ ...params });Do we also need this flag when using the SignUpFuture API paths (create/sso) in CHIPS? If so, consider similar handling there.
packages/clerk-js/src/core/resources/SignIn.ts (1)
302-314
: Adds iframeContext during create for OAuth flows — correct, but consider centralizingThis fixes the affected flow. To prevent future misses, consider doing this in SignIn.create() with a safe guard.
Apply:
create = (params: SignInCreateParams): Promise<SignInResource> => { debugLogger.debug('SignIn.create', { id: this.id, strategy: 'strategy' in params ? params.strategy : undefined }); - return this._basePost({ - path: this.pathRoot, - body: params, - }); + const body = + __BUILD_VARIANT_CHIPS__ && + inIframe() && + 'strategy' in params && + (params.strategy === 'saml' || params.strategy === 'enterprise_sso' || typeof params.strategy === 'string') + ? ({ ...params, iframeContext: true } as SignInCreateParams) + : params; + return this._basePost({ path: this.pathRoot, body }); };This keeps the flag constrained to strategy-based creates and avoids touching identifier-only creates.
If you prefer not to centralize, audit other create paths (e.g., web3, email_code bootstrap) to ensure the flag isn’t required there.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (5)
packages/clerk-js/src/core/resources/SignIn.ts
(3 hunks)packages/clerk-js/src/core/resources/SignUp.ts
(3 hunks)packages/types/src/signInCommon.ts
(1 hunks)packages/types/src/signInFuture.ts
(1 hunks)packages/types/src/signUpCommon.ts
(1 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/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignUp.ts
packages/types/src/signUpCommon.ts
packages/types/src/signInCommon.ts
packages/clerk-js/src/core/resources/SignIn.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/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignUp.ts
packages/types/src/signUpCommon.ts
packages/types/src/signInCommon.ts
packages/clerk-js/src/core/resources/SignIn.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignUp.ts
packages/types/src/signUpCommon.ts
packages/types/src/signInCommon.ts
packages/clerk-js/src/core/resources/SignIn.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignUp.ts
packages/types/src/signUpCommon.ts
packages/types/src/signInCommon.ts
packages/clerk-js/src/core/resources/SignIn.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for 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 assertions
for literal types:as const
Usesatisfies
operator 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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for 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/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignUp.ts
packages/types/src/signUpCommon.ts
packages/types/src/signInCommon.ts
packages/clerk-js/src/core/resources/SignIn.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/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignUp.ts
packages/types/src/signUpCommon.ts
packages/types/src/signInCommon.ts
packages/clerk-js/src/core/resources/SignIn.ts
🧬 Code graph analysis (2)
packages/clerk-js/src/core/resources/SignUp.ts (1)
packages/clerk-js/src/utils/runtime.ts (1)
inIframe
(9-19)
packages/clerk-js/src/core/resources/SignIn.ts (3)
packages/types/src/signInCommon.ts (1)
SignInCreateParams
(123-168)packages/clerk-js/src/utils/runtime.ts (1)
inIframe
(9-19)packages/types/src/signInFuture.ts (1)
SignInFutureCreateParams
(6-16)
⏰ 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). (2)
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
packages/types/src/signInFuture.ts (1)
12-15
: iframeContext type surface addition looks goodOptional flag aligns with runtime usage in SignInFuture.create. Keep it marked @internal to avoid leaking in public docs.
If you generate API docs, ensure @internal is excluded by your Typedoc config so this field doesn’t appear publicly.
packages/clerk-js/src/core/resources/SignUp.ts (1)
56-56
: New inIframe import — OKImport location and usage are consistent with utils/runtime.
packages/types/src/signInCommon.ts (1)
131-135
: Targeted addition for OAuth/SAML/Enterprise SSO variant — OKField is scoped to the variant that’s relevant for OAuth/SSO flows. Looks correct.
Double-check all call sites that construct this variant (e.g., authenticateWithRedirect/Popup) so none miss the flag.
packages/clerk-js/src/core/resources/SignIn.ts (2)
57-57
: inIframe import — OKConsistent with utils usage elsewhere.
637-646
: SignInFuture.create includes iframeContext — goodCovers the programmatic future API. No further issues.
Ensure SignInFuture.sso indeed routes through this.create so the flag propagates (it does in the current code).
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: 3
🧹 Nitpick comments (9)
.changeset/violet-badgers-change.md (1)
1-6
: Tighten release note; call out CHIPS gating and linked issueClarify optionality and gating to reduce ambiguity in release notes and generated changelog.
Apply:
-Adding iframeContext to SignIn and SignUp params when a CHIPS build is running in an iframe context +CHIPS: Signal iframe context for OAuth flows. + +- Adds optional `iframeContext` to `SignInCreateParams` and `SignUpCreateParams`. +- Only sent when `__BUILD_VARIANT_CHIPS__` is true and `inIframe()` returns true. +- Backwards compatible (no-op for non-CHIPS builds). +- Fixes USER-3277.packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (4)
10-12
: Avoid module-scope mutation of global build flagSetting
global.__BUILD_VARIANT_CHIPS__
at import time can leak across suites. Prefer per-test or per-beforeEach
setup.Apply:
-const originalBuildVariant = global.__BUILD_VARIANT_CHIPS__; -global.__BUILD_VARIANT_CHIPS__ = true; +const originalBuildVariant = global.__BUILD_VARIANT_CHIPS__;And initialize a known default in
beforeEach
:beforeEach(() => { vi.clearAllMocks(); + global.__BUILD_VARIANT_CHIPS__ = false; });
Finally, make CHIPS-enabled tests explicit (example for the first test):
it('should set iframeContext to true when CHIPS build and in iframe', async () => { + global.__BUILD_VARIANT_CHIPS__ = true; vi.mocked(inIframe).mockReturnValue(true);
31-35
: Use a getter spy forfapiClient
to auto-restore
Object.defineProperty
won’t be reset byvi.clearAllMocks()
, risking leakage. Spy on the getter and restore inafterEach
.Apply:
- Object.defineProperty(SignIn, 'fapiClient', { - get: () => mockFapiClient, - configurable: true, - }); + vi.spyOn(SignIn as any, 'fapiClient', 'get').mockReturnValue(mockFapiClient);Also restore spies:
afterEach(() => { global.__BUILD_VARIANT_CHIPS__ = originalBuildVariant; + vi.restoreAllMocks(); });
21-24
: Remove redundant reassignment ofbuildUrlWithAuth
You already set
buildUrlWithAuth
onmockClerk
. Reassigning it again is unnecessary.Apply:
- mockBuildUrlWithAuth = vi.fn((url: string) => `https://clerk.example.com${url}`); - SignIn.clerk.buildUrlWithAuth = mockBuildUrlWithAuth; + mockBuildUrlWithAuth = mockClerk.buildUrlWithAuth;Also applies to: 48-50
78-85
: Avoid asserting undefined properties; use partial matchAsserting keys with
undefined
makes tests brittle if the implementation omits the key. Preferexpect.objectContaining
.Apply:
- expect(mockCreate).toHaveBeenCalledWith({ - strategy: 'oauth_google', - identifier: '[email protected]', - redirectUrl: 'https://clerk.example.com/callback', - actionCompleteRedirectUrl: undefined, - iframeContext: true, - }); + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ + strategy: 'oauth_google', + identifier: '[email protected]', + redirectUrl: 'https://clerk.example.com/callback', + iframeContext: true, + }), + );Replicate this pattern for similar assertions in this file.
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (4)
10-12
: Avoid module-scope mutation of global build flagMatch the SignIn.spec.ts pattern: don’t set CHIPS at import time; set a default in
beforeEach
, toggle per test.Apply:
-const originalBuildVariant = global.__BUILD_VARIANT_CHIPS__; -global.__BUILD_VARIANT_CHIPS__ = true; +const originalBuildVariant = global.__BUILD_VARIANT_CHIPS__;And in
beforeEach
:beforeEach(() => { vi.clearAllMocks(); + global.__BUILD_VARIANT_CHIPS__ = false; });
42-46
: Spy onfapiClient
getter instead of redefining propertyEnsures clean teardown with
vi.restoreAllMocks()
.Apply:
- Object.defineProperty(SignUp, 'fapiClient', { - get: () => mockFapiClient, - configurable: true, - }); + vi.spyOn(SignUp as any, 'fapiClient', 'get').mockReturnValue(mockFapiClient);Also restore spies and static replacements:
afterEach(() => { global.__BUILD_VARIANT_CHIPS__ = originalBuildVariant; + vi.restoreAllMocks(); });
40-41
: RestoreSignUp.clerk
after testsStatic assignment can leak across suites. Save original and restore in
afterEach
.Apply:
- SignUp.clerk = mockClerk as any; + const originalClerk = SignUp.clerk; + SignUp.clerk = mockClerk as any;And:
afterEach(() => { global.__BUILD_VARIANT_CHIPS__ = originalBuildVariant; + // Restore static + // @ts-expect-error test-only restoration + SignUp.clerk = originalClerk; + vi.restoreAllMocks(); });Also applies to: 81-83
238-250
: Avoid asserting undefined properties; use partial matchPrefer partial matches over explicit
undefined
keys to reduce brittleness.Apply:
- expect(mockCreate).toHaveBeenCalledWith({ - path: '/client/sign_ups', - body: { - strategy: 'oauth_google', - redirectUrl: 'https://clerk.example.com/callback', - actionCompleteRedirectUrl: undefined, - unsafeMetadata: undefined, - emailAddress: undefined, - legalAccepted: undefined, - oidcPrompt: undefined, - iframeContext: true, - }, - }); + expect(mockCreate).toHaveBeenCalledWith({ + path: '/client/sign_ups', + body: expect.objectContaining({ + strategy: 'oauth_google', + redirectUrl: 'https://clerk.example.com/callback', + iframeContext: true, + }), + });Replicate for the update flow below.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
.changeset/violet-badgers-change.md
(1 hunks)packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
(1 hunks)packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{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/__tests__/SignUp.spec.ts
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.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/__tests__/SignUp.spec.ts
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.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/__tests__/SignUp.spec.ts
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for 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 assertions
for literal types:as const
Usesatisfies
operator 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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for 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/__tests__/SignUp.spec.ts
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Visual regression testing should be performed for UI components.
Files:
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.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/__tests__/SignUp.spec.ts
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}
: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
.changeset/**
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/violet-badgers-change.md
🧬 Code graph analysis (2)
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (1)
packages/clerk-js/src/utils/runtime.ts (1)
inIframe
(9-19)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (1)
packages/clerk-js/src/utils/runtime.ts (1)
inIframe
(9-19)
⏰ 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). (25)
- GitHub Check: Integration Tests (nextjs, chrome, 15)
- GitHub Check: Integration Tests (nextjs, chrome, 14)
- GitHub Check: Integration Tests (react-router, chrome)
- GitHub Check: Integration Tests (sessions, chrome)
- GitHub Check: Integration Tests (custom, chrome)
- GitHub Check: Integration Tests (billing, chrome)
- GitHub Check: Integration Tests (machine, chrome)
- GitHub Check: Integration Tests (tanstack-react-router, chrome)
- GitHub Check: Integration Tests (vue, chrome)
- GitHub Check: Integration Tests (nuxt, chrome)
- GitHub Check: Integration Tests (tanstack-react-start, chrome)
- GitHub Check: Integration Tests (ap-flows, chrome)
- GitHub Check: Integration Tests (elements, chrome)
- GitHub Check: Integration Tests (expo-web, chrome)
- GitHub Check: Integration Tests (quickstart, chrome)
- GitHub Check: Integration Tests (express, chrome)
- GitHub Check: Integration Tests (localhost, chrome)
- GitHub Check: Integration Tests (astro, chrome)
- GitHub Check: Integration Tests (generic, chrome)
- GitHub Check: Publish with pkg-pr-new
- GitHub Check: Unit Tests (22, **)
- GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
- GitHub Check: Static analysis
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
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 (11)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (11)
10-12
: Avoid module-scoped mutation of BUILD_VARIANT_CHIPS (order-dependent tests).Setting the flag at module load makes test outcomes depend on execution order. Prefer per-test or per-suite setup.
Apply this diff to stop setting it at module scope:
- (globalThis as any).__BUILD_VARIANT_CHIPS__ = true; + // Set __BUILD_VARIANT_CHIPS__ explicitly in beforeEach or per test
18-20
: Set the CHIPS flag in beforeEach for deterministic defaults.Ensure every test starts from the same baseline; tests that need a different value can override locally.
beforeEach(() => { vi.clearAllMocks(); + (globalThis as any).__BUILD_VARIANT_CHIPS__ = true; });
14-17
: Prevent static leakage: capture originals to restore after the suite.Stubbing SignIn.clerk and the fapiClient getter without restoring can leak across suites.
let signIn: SignIn; let mockCreate: any; - let mockBuildUrlWithAuth: any; + let mockBuildUrlWithAuth: any; + + // Capture originals to restore after the suite + const originalClerk = SignIn.clerk; + const originalFapiDescriptor = Object.getOwnPropertyDescriptor(SignIn, 'fapiClient');
52-55
: Restore globals and statics after the suite.Complements the per-test setup and avoids cross-file interference.
afterEach(() => { (globalThis as any).__BUILD_VARIANT_CHIPS__ = originalBuildVariant; }); + + afterAll(() => { + // Restore SignIn statics + SignIn.clerk = originalClerk as any; + if (originalFapiDescriptor) { + Object.defineProperty(SignIn, 'fapiClient', originalFapiDescriptor); + } else { + // Ensure we don't leave a test-only getter behind + // eslint-disable-next-line @typescript-eslint/no-explicit-any + delete (SignIn as any).fapiClient; + } + });
21-35
: Minor: prefer vi.stubGlobal for globals, and vi.restoreAllMocks for spies.Not mandatory, but vi.stubGlobal/vi.unstubAllGlobals provide cleaner lifecycle for globals, and restoreAllMocks reverts spy replacements (beyond clearAllMocks).
48-50
: Drop redundant reassignment of buildUrlWithAuth.You already set SignIn.clerk in beforeEach; reassigning buildUrlWithAuth here is unnecessary and can trip ESLint (unused variable).
- mockBuildUrlWithAuth = vi.fn((url: string) => `https://clerk.example.com${url}`); - SignIn.clerk.buildUrlWithAuth = mockBuildUrlWithAuth; + // buildUrlWithAuth already mocked via mockClerk above
56-85
: Make the expectation resilient; avoid asserting undefined keys.Asserting actionCompleteRedirectUrl: undefined is brittle if the implementation omits undefined fields. Use objectContaining and assert iframeContext specifically.
- expect(mockCreate).toHaveBeenCalledWith({ - strategy: 'oauth_google', - identifier: '[email protected]', - redirectUrl: 'https://clerk.example.com/callback', - actionCompleteRedirectUrl: undefined, - iframeContext: true, - }); + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ + strategy: 'oauth_google', + identifier: '[email protected]', + redirectUrl: 'https://clerk.example.com/callback', + iframeContext: true, + }), + ); + // Optional: assert navigation target if applicable in this path + // expect(mockNavigate).toHaveBeenCalledWith('https://oauth.provider.com/auth');
87-116
: Clarify test intent and reduce false positives.Explicitly set CHIPS=true so this test validates the “not in iframe” condition rather than passing because CHIPS might be falsy from a prior test. Also avoid asserting undefined keys.
it('should not set iframeContext when not in iframe', async () => { - vi.mocked(inIframe).mockReturnValue(false); + vi.mocked(inIframe).mockReturnValue(false); + (globalThis as any).__BUILD_VARIANT_CHIPS__ = true; @@ - expect(mockCreate).toHaveBeenCalledWith({ - strategy: 'oauth_google', - identifier: '[email protected]', - redirectUrl: 'https://clerk.example.com/callback', - actionCompleteRedirectUrl: undefined, - }); + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ + strategy: 'oauth_google', + identifier: '[email protected]', + redirectUrl: 'https://clerk.example.com/callback', + }), + ); expect(mockCreate).toHaveBeenCalledWith(expect.not.objectContaining({ iframeContext: true }));
117-141
: Optional: also assert redirectUrl building under non-CHIPS.Verifies we still use Clerk’s URL builder regardless of CHIPS.
await signIn.authenticateWithRedirectOrPopup(params, mockNavigate); expect(mockCreate).toHaveBeenCalledWith(expect.not.objectContaining({ iframeContext: true })); + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ redirectUrl: 'https://clerk.example.com/callback' }), + );
143-167
: Strengthen “continueSignIn” behavior check.Also assert that navigation occurs to the provider URL, since create is skipped.
await signIn.authenticateWithRedirectOrPopup(params, mockNavigate); expect(mockCreate).not.toHaveBeenCalled(); + expect(mockNavigate).toHaveBeenCalledWith('https://oauth.provider.com/auth');
198-223
: Clarify test baseline for Future path (set CHIPS).Not required for correctness here, but setting CHIPS=true removes any ambiguity about why iframeContext is omitted.
it('should not set iframeContext when not in iframe', async () => { - vi.mocked(inIframe).mockReturnValue(false); + vi.mocked(inIframe).mockReturnValue(false); + (globalThis as any).__BUILD_VARIANT_CHIPS__ = true;
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
(1 hunks)packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/clerk-js/src/core/resources/tests/SignUp.spec.ts
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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/__tests__/SignIn.spec.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/__tests__/SignIn.spec.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.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/__tests__/SignIn.spec.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for 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 assertions
for literal types:as const
Usesatisfies
operator 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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for 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/__tests__/SignIn.spec.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Visual regression testing should be performed for UI components.
Files:
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.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/__tests__/SignIn.spec.ts
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}
: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (1)
packages/clerk-js/src/utils/runtime.ts (1)
inIframe
(9-19)
⏰ 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). (4)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (2)
6-8
: Mocking inIframe is clean and focused.Good isolation of the runtime check; keeps tests deterministic.
169-196
: LGTM: Future path sets iframeContext correctly under CHIPS+iframe.Good coverage of the internal basePost payload.
if (__BUILD_VARIANT_CHIPS__ && inIframe()) { | ||
createParams.iframeContext = true; |
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.
This is the core change. When in CHIPS build and running in an iframe we want to send extra params to FAPI that indicate we are using partitioned cookies in an iframe. FAPI will skip validating the client_id in this scenario
if (__BUILD_VARIANT_CHIPS__ && inIframe()) { | ||
createParams.iframeContext = true; |
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.
Same as above, this is the core logical change
if (__BUILD_VARIANT_CHIPS__ && inIframe()) { | ||
finalParams.iframeContext = true; |
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.
Same as the SignIn change
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 (2)
packages/types/src/signInCommon.ts (1)
131-134
: Confirm scope: sessionId only on SSO/OAuth branch by designIf backend needs iframe context only for OAuth/SAML/EnterpriseSSO, this is fine. If other strategies may also flow through the same validation, consider broadening. At minimum, make the intent explicit in docs.
Doc tweak (optional):
/** - * @internal Used to identify the session making the request in iframe context. + * @internal Used to identify the session making the request in iframe context. + * Set internally by the CHIPS build; intentionally exposed only on SSO/OAuth-like strategies. */ sessionId?: string;packages/types/src/signUpCommon.ts (1)
103-106
: Mirror internal-only wording; discourage manual settingAlign doc text with SignIn to reduce accidental external usage.
Apply:
/** - * @internal Used to identify the session making the request in iframe context. + * @internal Used to identify the session making the request in iframe context. + * Do not set manually—this is set by the CHIPS build when embedded in an iframe. */ sessionId?: string;
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (7)
packages/clerk-js/src/core/resources/SignIn.ts
(3 hunks)packages/clerk-js/src/core/resources/SignUp.ts
(3 hunks)packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
(1 hunks)packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
(1 hunks)packages/types/src/signInCommon.ts
(1 hunks)packages/types/src/signInFuture.ts
(1 hunks)packages/types/src/signUpCommon.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
- packages/clerk-js/src/core/resources/tests/SignIn.spec.ts
- packages/clerk-js/src/core/resources/SignUp.ts
- packages/clerk-js/src/core/resources/tests/SignUp.spec.ts
- packages/clerk-js/src/core/resources/SignIn.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/types/src/signUpCommon.ts
packages/types/src/signInCommon.ts
packages/types/src/signInFuture.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/types/src/signUpCommon.ts
packages/types/src/signInCommon.ts
packages/types/src/signInFuture.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/types/src/signUpCommon.ts
packages/types/src/signInCommon.ts
packages/types/src/signInFuture.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/types/src/signUpCommon.ts
packages/types/src/signInCommon.ts
packages/types/src/signInFuture.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for 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 assertions
for literal types:as const
Usesatisfies
operator 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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for 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/types/src/signUpCommon.ts
packages/types/src/signInCommon.ts
packages/types/src/signInFuture.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/types/src/signUpCommon.ts
packages/types/src/signInCommon.ts
packages/types/src/signInFuture.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). (4)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/types/src/signInFuture.ts (1)
12-15
: Make internal-only intent explicitDoc tweak below; runtime verified — sessionId is overridden from BaseResource.clerk.session?.id only when BUILD_VARIANT_CHIPS && inIframe(), and caller-provided values are ignored otherwise.
/** - * @internal Used to identify the session making the request in iframe context. + * @internal Used to identify the session making the request in iframe context. + * Do not set manually—this is set by the CHIPS build when embedded in an iframe. */ sessionId?: string;
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 (7)
packages/clerk-js/src/core/resources/SignIn.ts (1)
302-314
: Avoid scattering iframe clientId injection; centralize inSignIn.create
Right now, clientId is injected here and in
SignInFuture.create
, but not inSignIn.create
. A direct OAuth call tosignIn.create(...)
outside this path would miss the signal. Centralize the injection insideSignIn.create
to cover all paths and remove duplication.Apply:
create = (params: SignInCreateParams): Promise<SignInResource> => { debugLogger.debug('SignIn.create', { id: this.id, strategy: 'strategy' in params ? params.strategy : undefined }); - return this._basePost({ - path: this.pathRoot, - body: params, - }); + const finalParams = + __BUILD_VARIANT_CHIPS__ && inIframe() + ? { ...params, clientId: BaseResource.clerk.client?.id } + : params; + return this._basePost({ + path: this.pathRoot, + body: finalParams, + }); };Optionally, extract a tiny helper
withIframeClientId(params)
to DRY this and theSignInFuture.create
site.packages/clerk-js/src/core/resources/SignUp.ts (3)
146-149
: Only setclientId
when present to avoid sendingundefined
Minor: guard assignment to avoid
clientId: undefined
landing in the serialized body (even if JSON.stringify drops it, best to avoid).- if (__BUILD_VARIANT_CHIPS__ && inIframe()) { - finalParams.clientId = BaseResource.clerk.client?.id; - } + if (__BUILD_VARIANT_CHIPS__ && inIframe()) { + const cid = BaseResource.clerk.client?.id; + if (cid) finalParams.clientId = cid; + }
433-442
: Mirror the same guard inupdate
Apply the same defined‑value check when augmenting
finalParams
in update().- if (__BUILD_VARIANT_CHIPS__ && inIframe()) { - finalParams.clientId = BaseResource.clerk.client?.id; - } + if (__BUILD_VARIANT_CHIPS__ && inIframe()) { + const cid = BaseResource.clerk.client?.id; + if (cid) finalParams.clientId = cid; + }
684-697
: SignUpFuture.sso path also needs iframe client signalThe future SSO flow posts directly and currently omits
clientId
. Add it under CHIPS+iframe for parity with create/update and to cover OAuth in future flows.await this.resource.__internal_basePost({ path: this.resource.pathRoot, - body: { + body: { strategy, redirectUrl: SignUp.clerk.buildUrlWithAuth(redirectCallbackUrl), redirectUrlComplete: redirectUrl, captchaToken, captchaWidgetType, captchaError, - }, + ...( __BUILD_VARIANT_CHIPS__ && inIframe() + ? { clientId: BaseResource.clerk.client?.id } + : {} ), + }, });Add unit tests for this path mirroring the create/update expectations.
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (3)
222-304
: Add coverage forSignUpFuture.sso
Future SSO posts bypass
create/update
. Add tests to assertclientId
presence under CHIPS+iframe and absence otherwise.I can draft the vitest cases if helpful.
20-53
: Prevent global leakage of mocked staticsWe mutate
SignUp.clerk
andBaseResource.clerk
but don’t restore them. Capture previous values inbeforeEach
and restore inafterEach
to avoid cross‑test contamination.beforeEach(() => { vi.clearAllMocks(); + prevSignUpClerk = SignUp.clerk; + prevBaseClerk = BaseResource.clerk; @@ SignUp.clerk = mockClerk as any; // Mock BaseResource.clerk for client ID access BaseResource.clerk = mockClerk as any; }); afterEach(() => { global.__BUILD_VARIANT_CHIPS__ = originalBuildVariant; + SignUp.clerk = prevSignUpClerk as any; + BaseResource.clerk = prevBaseClerk as any; });Declare at top:
let prevSignUpClerk: unknown; let prevBaseClerk: unknown;
14-114
: Nit: test names say “set clientId to true”They actually assert specific id value. Consider renaming to “includes clientId when CHIPS build and in iframe”.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (9)
packages/clerk-js/src/core/resources/SignIn.ts
(3 hunks)packages/clerk-js/src/core/resources/SignUp.ts
(3 hunks)packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
(1 hunks)packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
(1 hunks)packages/clerk-js/src/ui/elements/Action/ActionTrigger.tsx
(1 hunks)packages/clerk-js/src/ui/router/BaseRouter.tsx
(1 hunks)packages/types/src/signInCommon.ts
(1 hunks)packages/types/src/signInFuture.ts
(1 hunks)packages/types/src/signUpCommon.ts
(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- packages/clerk-js/src/ui/elements/Action/ActionTrigger.tsx
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/types/src/signInCommon.ts
- packages/types/src/signUpCommon.ts
- packages/clerk-js/src/core/resources/tests/SignIn.spec.ts
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{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/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignUp.ts
packages/clerk-js/src/ui/router/BaseRouter.tsx
packages/clerk-js/src/core/resources/SignIn.ts
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.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/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignUp.ts
packages/clerk-js/src/ui/router/BaseRouter.tsx
packages/clerk-js/src/core/resources/SignIn.ts
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignUp.ts
packages/clerk-js/src/ui/router/BaseRouter.tsx
packages/clerk-js/src/core/resources/SignIn.ts
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignUp.ts
packages/clerk-js/src/ui/router/BaseRouter.tsx
packages/clerk-js/src/core/resources/SignIn.ts
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for 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 assertions
for literal types:as const
Usesatisfies
operator 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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for 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/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignUp.ts
packages/clerk-js/src/ui/router/BaseRouter.tsx
packages/clerk-js/src/core/resources/SignIn.ts
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.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/types/src/signInFuture.ts
packages/clerk-js/src/core/resources/SignUp.ts
packages/clerk-js/src/ui/router/BaseRouter.tsx
packages/clerk-js/src/core/resources/SignIn.ts
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
packages/clerk-js/src/ui/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)
packages/clerk-js/src/ui/**/*.{ts,tsx}
: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure
Files:
packages/clerk-js/src/ui/router/BaseRouter.tsx
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}
: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}
: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile
,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/clerk-js/src/ui/router/BaseRouter.tsx
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.tsx
: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/clerk-js/src/ui/router/BaseRouter.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Visual regression testing should be performed for UI components.
Files:
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}
: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
🧬 Code graph analysis (3)
packages/clerk-js/src/core/resources/SignUp.ts (1)
packages/clerk-js/src/utils/runtime.ts (1)
inIframe
(9-21)
packages/clerk-js/src/ui/router/BaseRouter.tsx (1)
packages/types/src/clerk.ts (1)
NavigateOptions
(1107-1110)
packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (2)
packages/clerk-js/src/core/resources/SignUp.ts (1)
SignUp
(72-541)packages/clerk-js/src/utils/runtime.ts (1)
inIframe
(9-21)
⏰ 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). (1)
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (8)
packages/clerk-js/src/ui/router/BaseRouter.tsx (2)
118-121
: Confirm RouterMetadata shapeWe pass
{ metadata: { navigationType: 'internal' } }
. EnsureRouterMetadata
allowsnavigationType
or adjust to the canonical keys.
17-17
: Type narrowing: ensure allinternalNavigate
providers are asyncBaseRouter.internalNavigate now returns a Promise (packages/clerk-js/src/ui/router/BaseRouter.tsx:17). Repository search for JSX props and object providers returned no hits — verify all BaseRouter instantiations, factories, adapters and platform-specific forks and update any sync providers to return a Promise (mark async or wrap with Promise.resolve()).
packages/types/src/signInFuture.ts (1)
12-16
: Addition ofclientId?: string
looks goodMatches the CHIPS+iframe requirement and is marked
@internal
. Keep docs consistent with corresponding SignIn/SignUp params.Confirm the same optional field exists on:
SignInCreateParams
SignUpCreateParams
packages/clerk-js/src/core/resources/SignIn.ts (2)
57-58
: Runtime guard import is appropriateUsing
inIframe()
gated by__BUILD_VARIANT_CHIPS__
is the right boundary for CHIPS behavior.
637-646
: LGTM onSignInFuture.create
augmentationCloning and conditionally attaching
clientId
is correct and side‑effect free.packages/clerk-js/src/core/resources/SignUp.ts (1)
39-40
: Import is correctUsing
inIframe
here aligns SignUp with SignIn behavior.packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts (2)
92-156
: Create-path tests: assertions look solidPositive and negative cases correctly check
body.clientId
. Good coverage for CHIPS/inIframe toggles.
158-220
: Update-path tests: assertions look solidMirrors create-path checks; nice.
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 (4)
packages/clerk-js/src/ui/router/PathRouter.tsx (2)
24-27
: Signature alignment looks good; prefer stable callback and a narrower return type if possible.
- Wrap with
useCallback
sointernalNavigate
identity is stable.- If
BaseRouter
accepts it, preferPromise<void>
overPromise<any>
to avoidany
.- const internalNavigate = async (toURL: URL, options?: NavigateOptions): Promise<any> => { - // Only send the path - return navigate(stripOrigin(toURL), options); - }; + const internalNavigate = React.useCallback( + async (toURL: URL, options?: NavigateOptions): Promise<any> => { + // Only send the path + return navigate(stripOrigin(toURL), options); + }, + [navigate], + );
37-46
: Avoidwindow.location.hash
in deps; either run once on mount or subscribe tohashchange
.Including
window.location.hash
in the deps array doesn’t react to hash changes (no render is triggered) and can upset SSR. Either:
- Minimal: run once on mount (matches current behavior) and silence the linter, or
- Robust: add a
hashchange
listener and callconvertHashToPath
on change.Minimal change:
- React.useEffect(() => { + React.useEffect(() => { const convertHashToPath = async () => { if (hasUrlInFragment(window.location.hash)) { const url = mergeFragmentIntoUrl(new URL(window.location.href)); await internalNavigate(url, { replace: true }); setStripped(true); } }; void convertHashToPath(); - }, [setStripped, navigate, window.location.hash]); + // We only need to strip once on mount + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []);Robust alternative (if you want to handle hash mutations after mount):
- React.useEffect(() => { - const convertHashToPath = async () => { - if (hasUrlInFragment(window.location.hash)) { - const url = mergeFragmentIntoUrl(new URL(window.location.href)); - await internalNavigate(url, { replace: true }); - setStripped(true); - } - }; - void convertHashToPath(); - }, [setStripped, navigate, window.location.hash]); + React.useEffect(() => { + const convertHashToPath = async () => { + if (hasUrlInFragment(window.location.hash)) { + const url = mergeFragmentIntoUrl(new URL(window.location.href)); + await internalNavigate(url, { replace: true }); + setStripped(true); + } + }; + const onHashChange = () => void convertHashToPath(); + window.addEventListener('hashchange', onHashChange); + void convertHashToPath(); + return () => window.removeEventListener('hashchange', onHashChange); + }, [internalNavigate, setStripped]);packages/clerk-js/src/core/resources/SignIn.ts (2)
680-689
: Mirror the clientId guard in Future.createSame concern: don’t include an undefined
clientId
; align onSignIn.clerk
accessor.Apply this diff:
- if (__BUILD_VARIANT_CHIPS__ && inIframe()) { - createParams.clientId = BaseResource.clerk.client?.id; - } + if (__BUILD_VARIANT_CHIPS__ && inIframe()) { + const clientId = SignIn.clerk.client?.id; + if (clientId) { + createParams.clientId = clientId; + } + }Optional follow‑up: extract a small helper (e.g.,
attachIframeClientId<T extends { clientId?: string }>(p: T): T
) and reuse in both sites (and SignUp) to avoid drift.
313-325
: Only attach clientId when defined; use SignIn.clerkAvoid sending clientId: undefined and prefer SignIn.clerk for consistency. Apply the same change at the other occurrence in SignIn.ts.
- if (__BUILD_VARIANT_CHIPS__ && inIframe()) { - createParams.clientId = BaseResource.clerk.client?.id; - } + if (__BUILD_VARIANT_CHIPS__ && inIframe()) { + const clientId = SignIn.clerk.client?.id; + if (clientId) { + createParams.clientId = clientId; + } + }Locations: packages/clerk-js/src/core/resources/SignIn.ts (around lines ~320 and ~683). Verified: BUILD_VARIANT_CHIPS declared in packages/clerk-js/global.d.ts and set in vitest.config.mts / rspack.config.js / jest.config.js (tests also toggle it).
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (5)
packages/clerk-js/src/core/resources/SignIn.ts
(3 hunks)packages/clerk-js/src/core/resources/SignUp.ts
(3 hunks)packages/clerk-js/src/ui/router/PathRouter.tsx
(2 hunks)packages/clerk-js/src/ui/router/VirtualRouter.tsx
(2 hunks)packages/types/src/signInFuture.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/clerk-js/src/core/resources/SignUp.ts
- packages/types/src/signInFuture.ts
🧰 Additional context used
📓 Path-based instructions (9)
packages/clerk-js/src/ui/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)
packages/clerk-js/src/ui/**/*.{ts,tsx}
: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure
Files:
packages/clerk-js/src/ui/router/VirtualRouter.tsx
packages/clerk-js/src/ui/router/PathRouter.tsx
**/*.{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/ui/router/VirtualRouter.tsx
packages/clerk-js/src/ui/router/PathRouter.tsx
packages/clerk-js/src/core/resources/SignIn.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/ui/router/VirtualRouter.tsx
packages/clerk-js/src/ui/router/PathRouter.tsx
packages/clerk-js/src/core/resources/SignIn.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/ui/router/VirtualRouter.tsx
packages/clerk-js/src/ui/router/PathRouter.tsx
packages/clerk-js/src/core/resources/SignIn.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/ui/router/VirtualRouter.tsx
packages/clerk-js/src/ui/router/PathRouter.tsx
packages/clerk-js/src/core/resources/SignIn.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for 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 assertions
for literal types:as const
Usesatisfies
operator 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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for 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/ui/router/VirtualRouter.tsx
packages/clerk-js/src/ui/router/PathRouter.tsx
packages/clerk-js/src/core/resources/SignIn.ts
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}
: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}
: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile
,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/clerk-js/src/ui/router/VirtualRouter.tsx
packages/clerk-js/src/ui/router/PathRouter.tsx
**/*.{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/ui/router/VirtualRouter.tsx
packages/clerk-js/src/ui/router/PathRouter.tsx
packages/clerk-js/src/core/resources/SignIn.ts
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.tsx
: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/clerk-js/src/ui/router/VirtualRouter.tsx
packages/clerk-js/src/ui/router/PathRouter.tsx
🧬 Code graph analysis (3)
packages/clerk-js/src/ui/router/VirtualRouter.tsx (1)
packages/types/src/clerk.ts (1)
NavigateOptions
(1107-1110)
packages/clerk-js/src/ui/router/PathRouter.tsx (1)
packages/types/src/clerk.ts (1)
NavigateOptions
(1107-1110)
packages/clerk-js/src/core/resources/SignIn.ts (3)
packages/types/src/signInCommon.ts (1)
SignInCreateParams
(123-168)packages/clerk-js/src/utils/runtime.ts (1)
inIframe
(9-21)packages/types/src/signInFuture.ts (1)
SignInFutureCreateParams
(7-17)
⏰ 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: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (3)
packages/clerk-js/src/ui/router/VirtualRouter.tsx (2)
2-2
: Type‑only import is correct and keeps bundles lean.Using
import type
avoids runtime code and aligns with TS best practices.
44-47
: Stabilize internalNavigate with useCallback and align its return type with BaseRouter
- Wrap the handler in React.useCallback and drop the redundant Promise.resolve(); keep the function body as a plain async (or return nothing) to avoid extra allocations.
- BaseRouter currently types internalNavigate as (toURL: URL, options?: NavigateOptions) => Promise — packages/clerk-js/src/ui/router/BaseRouter.tsx:17. Either keep Promise on VirtualRouter to match, or update BaseRouter (and any implementations) before changing the signature to Promise.
- If ESLint flags the unused _options, silence it with void _options; or rely on the leading underscore.
packages/clerk-js/src/core/resources/SignIn.ts (1)
59-59
: SSR‑safe iframe detection import — LGTMImporting
inIframe
from the runtime utilities is appropriate and remains SSR‑safe due to the internalinBrowser()
guard.
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 (9)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (9)
11-13
: Avoid module-scope mutation of the CHIPS flagSetting
__BUILD_VARIANT_CHIPS__
at import time can leak state across test files. Move this intobeforeEach
and restore it inafterEach
.-const originalBuildVariant = (globalThis as any).__BUILD_VARIANT_CHIPS__; -(globalThis as any).__BUILD_VARIANT_CHIPS__ = true; +let originalBuildVariant: unknown;And update lifecycle hooks:
beforeEach(() => { - vi.clearAllMocks(); + vi.clearAllMocks(); + originalBuildVariant = (globalThis as any).__BUILD_VARIANT_CHIPS__; + (globalThis as any).__BUILD_VARIANT_CHIPS__ = true; }); afterEach(() => { - (globalThis as any).__BUILD_VARIANT_CHIPS__ = originalBuildVariant; + (globalThis as any).__BUILD_VARIANT_CHIPS__ = originalBuildVariant; });
20-21
: Reset mocked implementation, not only calls
vi.clearAllMocks()
clears calls but preserves return values. Add a reset forinIframe
to prevent leakage between tests.beforeEach(() => { vi.clearAllMocks(); + vi.mocked(inIframe).mockReset(); });
33-41
: Restore patched statics to avoid cross-test pollutionYou patch
SignIn.clerk
,BaseResource.clerk
, and redefineSignIn.fapiClient
but never restore them. Capture originals and restore inafterEach
.+let originalSignInClerk: unknown; +let originalBaseResourceClerk: unknown; +const originalFapiDescriptor = Object.getOwnPropertyDescriptor(SignIn, 'fapiClient'); + beforeEach(() => { vi.clearAllMocks(); + originalSignInClerk = SignIn.clerk; + originalBaseResourceClerk = BaseResource.clerk; ... SignIn.clerk = mockClerk as any; // Mock BaseResource.clerk for client ID access BaseResource.clerk = mockClerk as any; Object.defineProperty(SignIn, 'fapiClient', { get: () => mockFapiClient, configurable: true, }); }); afterEach(() => { (globalThis as any).__BUILD_VARIANT_CHIPS__ = originalBuildVariant; + SignIn.clerk = originalSignInClerk as any; + BaseResource.clerk = originalBaseResourceClerk as any; + if (originalFapiDescriptor) { + Object.defineProperty(SignIn, 'fapiClient', originalFapiDescriptor); + } });Also applies to: 59-61
64-64
: Clarify test nameIt’s setting
clientId
to the Clerk client id, not “to true”.-it('should set clientId to true when CHIPS build and in iframe', async () => { +it('should include clientId when CHIPS build and in an iframe', async () => {
85-91
: Make expectation resilient to omitted undefined fieldsMatching
actionCompleteRedirectUrl: undefined
is brittle if the implementation omits the key. UseobjectContaining
and drop the undefined field.- expect(mockCreate).toHaveBeenCalledWith({ - strategy: 'oauth_google', - identifier: '[email protected]', - redirectUrl: 'https://clerk.example.com/callback', - actionCompleteRedirectUrl: undefined, - clientId: 'test-client-id', - }); + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ + strategy: 'oauth_google', + identifier: '[email protected]', + redirectUrl: 'https://clerk.example.com/callback', + clientId: 'test-client-id', + }), + );
83-84
: Also assert navigation to the provider URLVerifies the primary side effect when verification is unverified.
await signIn.authenticateWithRedirectOrPopup(params, mockNavigate); + expect(mockNavigate).toHaveBeenCalledWith('https://oauth.provider.com/auth');
115-121
: Same resilience for the non-iframe caseAvoid asserting on an explicitly undefined field.
- expect(mockCreate).toHaveBeenCalledWith({ - strategy: 'oauth_google', - identifier: '[email protected]', - redirectUrl: 'https://clerk.example.com/callback', - actionCompleteRedirectUrl: undefined, - }); + expect(mockCreate).toHaveBeenCalledWith( + expect.objectContaining({ + strategy: 'oauth_google', + identifier: '[email protected]', + redirectUrl: 'https://clerk.example.com/callback', + }), + );
177-177
: Clarify test nameSame wording nit as above.
-it('should set clientId to true when CHIPS build and in iframe', async () => { +it('should include clientId when CHIPS build and in an iframe', async () => {
52-57
: Prefer spying over method reassignment
vi.spyOn(signIn, 'create')
preserves prototype behavior and is easier to restore.- mockCreate = vi.fn().mockResolvedValue({}); - signIn.create = mockCreate; + mockCreate = vi.spyOn(signIn as any, 'create').mockResolvedValue({});
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
(1 hunks)packages/clerk-js/src/core/resources/__tests__/SignUp.spec.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/clerk-js/src/core/resources/tests/SignUp.spec.ts
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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/__tests__/SignIn.spec.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/__tests__/SignIn.spec.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.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/__tests__/SignIn.spec.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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for 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 assertions
for literal types:as const
Usesatisfies
operator 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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for 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/__tests__/SignIn.spec.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Visual regression testing should be performed for UI components.
Files:
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.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/__tests__/SignIn.spec.ts
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}
: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/resources/__tests__/SignIn.spec.ts (2)
packages/clerk-js/src/core/resources/SignIn.ts (1)
SignIn
(93-552)packages/clerk-js/src/utils/runtime.ts (1)
inIframe
(9-21)
⏰ 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). (4)
- 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/src/core/resources/__tests__/SignIn.spec.ts (1)
1-231
: Overall: solid coverage and correct assertions for CHIPS + iframe behaviorThe tests capture the clientId propagation paths for both
authenticateWithRedirectOrPopup
andSignInFuture.create
and validate redirect URL building. With the small robustness and hygiene tweaks above, this looks good.
Converted this back to draft as I don't think this can be securely implemented from the client-facing SDKs |
Description
When the CHIPS build of clerk-js runs inside an iframe, OAuth sign-in/sign-up flows fail because the backend attempts to validate the client_id against registered OAuth applications. The client_id differs between the iframe context and the parent window context, causing validation failures.
Fixes: USER-3277
Related: https://github.com/clerk/clerk_go/pull/13638
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Improvements
Types
Tests
Style