Skip to content

Conversation

panteliselef
Copy link
Member

@panteliselef panteliselef commented Sep 26, 2025

Description

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features

    • Payment method management added: initialize, add, and list payment methods; checkout displays payment method details.
  • Refactor

    • Global terminology change from “payment source” → “payment method” across public types, resources, UI, hooks, and org/user APIs.
    • Field/payload and form input names updated to payment_method / payment_method_id.
  • Chores

    • Bumped Clerk dependencies and added a changeset noting the Billing Beta terminology update.
  • Tests

    • Updated tests and type tests to reflect paymentMethod renames.

Copy link

changeset-bot bot commented Sep 26, 2025

🦋 Changeset detected

Latest commit: 8ed4a25

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 22 packages
Name Type
@clerk/clerk-js Minor
@clerk/shared Patch
@clerk/types Minor
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/vue Patch
@clerk/localizations Patch
@clerk/themes Patch

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

Copy link

vercel bot commented Sep 26, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Oct 3, 2025 8:34pm

Copy link
Contributor

coderabbitai bot commented Sep 26, 2025

Walkthrough

Renames "payment source" to "payment method" across types, resources, modules, hooks, UI, and tests; adds Billing.path to build /commerce API paths with optional org scope; updates initialize/add/list billing flows, JSON mappings, and public interfaces to use payment method naming.

Changes

Cohort / File(s) Change summary
Changeset
./.changeset/rich-breads-move.md
Adds changeset recording dependency bumps and a Billing Beta note renaming "payment source" → "payment method".
Billing namespace
packages/clerk-js/src/core/modules/billing/namespace.ts
Adds Billing.path(subPath, { orgId? }) to build /commerce paths scoped to user (/me) or organization (/organizations/{orgId}).
Billing methods (module)
packages/clerk-js/src/core/modules/billing/payment-source-methods.ts
Replaces payment source APIs with payment method equivalents (initializePaymentMethod, addPaymentMethod, getPaymentMethods); uses Billing.path and swaps JSON/model types to payment method variants.
Core models (rename)
packages/clerk-js/src/core/resources/BillingPaymentSource.ts
Renames BillingPaymentSourceBillingPaymentMethod and BillingInitializedPaymentSourceBillingInitializedPaymentMethod; updates types, status enums, constructors, and JSON mappings to payment method shapes.
Core resources — usages
packages/clerk-js/src/core/resources/BillingCheckout.ts, packages/clerk-js/src/core/resources/BillingPayment.ts, packages/clerk-js/src/core/resources/BillingSubscription.ts
Replace paymentSource fields with paymentMethod; update JSON-to-model mapping and payment_source_idpayment_method_id.
Resource APIs (User / Organization)
packages/clerk-js/src/core/resources/Organization.ts, packages/clerk-js/src/core/resources/User.ts
Rename instance methods: initialize/add/getPaymentSourceinitialize/add/getPaymentMethod; update imports to billing module's new method APIs.
UI — Checkout components & form
packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx, .../CheckoutForm.tsx
Switch checkout usage to paymentMethod; change types to BillingPaymentMethodResource; replace form field names (payment_source_idpayment_method_id) and hidden input handling; add HIDDEN_INPUT_NAME constant.
UI — PaymentSources screens & rows
packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx, packages/clerk-js/src/ui/components/PaymentSources.tsx
Component prop types updated to BillingPaymentMethodResource; display logic uses paymentType (and card fields) and Add flow calls addPaymentMethod.
Shared React logic & hooks
packages/shared/src/react/commerce.tsx, packages/shared/src/react/hooks/usePaymentMethods.tsx
Rename initialize flow and SWR keys to payment method variants; hooks return BillingPaymentMethodResource and call getPaymentMethods; update usage of initializePaymentMethod.
Types — billing & json
packages/types/src/billing.ts, packages/types/src/json.ts
Public types renamed from PaymentSourcePaymentMethod (resources, params, statuses, JSON shapes); introduce BillingPayerMethods replacing BillingPaymentSourceMethods; rename JSON fields (payment_sourcepayment_method, _id fields).
Types — resource extensions
packages/types/src/organization.ts, packages/types/src/user.ts
OrganizationResource and UserResource now extend BillingPayerMethods (replacing BillingPaymentSourceMethods).
Tests — types & UI
packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts, packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
Updated tests and mocks to use payment method naming: paymentSourcepaymentMethod, API mocks getPaymentSourcesgetPaymentMethods, data shape paymentMethodpaymentType, and selector input[name="payment_source_id"]input[name="payment_method_id"].

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant User as User Resource
  participant Org as Organization Resource
  participant Billing as Billing.path
  participant API as /commerce API

  rect rgba(200,220,255,0.12)
    note right of Client: Initialize payment method (user)
    Client->>User: initializePaymentMethod(params)
    User->>Billing: path('/payment_methods/initialize')
    Billing-->>User: /commerce/me/payment_methods/initialize
    User->>API: POST /commerce/me/payment_methods/initialize
    API-->>User: BillingInitializedPaymentMethod JSON
    User-->>Client: BillingInitializedPaymentMethod
  end

  rect rgba(200,255,200,0.12)
    note right of Client: Add payment method (org-scoped)
    Client->>Org: addPaymentMethod({ orgId, ... })
    Org->>Billing: path('/payment_methods', { orgId })
    Billing-->>Org: /commerce/organizations/{orgId}/payment_methods
    Org->>API: POST /commerce/organizations/{orgId}/payment_methods
    API-->>Org: BillingPaymentMethod JSON
    Org-->>Client: BillingPaymentMethod
  end

  rect rgba(255,230,200,0.12)
    note right of Client: List payment methods
    Client->>User: getPaymentMethods(query)
    User->>Billing: path('/payment_methods')
    Billing-->>User: /commerce/me/payment_methods
    User->>API: GET /commerce/me/payment_methods
    API-->>User: Paginated BillingPaymentMethod JSON
    User-->>Client: Page<BillingPaymentMethod>
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

A hop, a bop—goodbye old source,
Hello method—same swift course.
Paths now route through /commerce lanes,
Orgs and users, tidy chains.
I thump with glee — new names, neat carrots! 🥕🐇

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly describes the primary change—aligning payment methods terminology across the clerk-js and types packages—using a conventional commit prefix and scope, making it clear, concise, and directly related to the extensive renaming in the changeset.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch elef/bill-1264-rename-payment_sources-payment_methods

📜 Recent 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 2ae5a17 and 8ed4a25.

📒 Files selected for processing (1)
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (11 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/ui/components/Checkout/tests/Checkout.test.tsx
⏰ 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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

pkg-pr-new bot commented Sep 26, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6865

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6865

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6865

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6865

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6865

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6865

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6865

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6865

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6865

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6865

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6865

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6865

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6865

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6865

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6865

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6865

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6865

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6865

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6865

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6865

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6865

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6865

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6865

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6865

commit: 8ed4a25

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx (1)

115-118: Avoid in-place mutation and potential undefined crash in sort

  • paymentMethods may be undefined initially (SWR), causing .sort to throw.
  • .sort mutates the array; prefer sorting a copy.

Apply:

-  const sortedPaymentSources = useMemo(
-    () => paymentMethods.sort((a, b) => (a.isDefault && !b.isDefault ? -1 : 1)),
-    [paymentMethods],
-  );
+  const sortedPaymentSources = useMemo(() => {
+    const items = (paymentMethods || []).slice();
+    return items.sort((a, b) => (a.isDefault === b.isDefault ? 0 : a.isDefault ? -1 : 1));
+  }, [paymentMethods]);
🧹 Nitpick comments (20)
packages/shared/src/react/hooks/usePaymentMethods.tsx (1)

16-20: Bind instance methods returned by the fetcher to preserve this context.

Passing unbound instance methods can lose this (especially for organization-scoped methods that may rely on this.id). Bind them when returning.

Apply this diff:

     if (resource === 'organization') {
-      return organization?.getPaymentMethods;
+      return organization ? organization.getPaymentMethods.bind(organization) : undefined;
     }
-    return user?.getPaymentMethods;
+    return user ? user.getPaymentMethods.bind(user) : undefined;

Please confirm whether these methods rely on instance context; if not, this change is harmless; if they do, it prevents subtle runtime errors.

packages/types/src/user.ts (1)

2-2: Add deprecated alias and update legacy payment-source references

  • In packages/types/src/billing.ts, add:
    /** @deprecated Use BillingPayerMethods */
    export type BillingPaymentSourceMethods = BillingPayerMethods;
  • Update or alias legacy methods/exports for getPaymentSources/addPaymentSource/initializePaymentSource in changelogs, tests (packages/clerk-js/src/ui/components/Checkout/tests/Checkout.test.tsx) and internal exports (packages/clerk-js/src/core/resources/internal.ts) to preserve backward compatibility.
  • Re-run:
    rg -nP -C2 '\b(getPaymentSources|addPaymentSource|initializePaymentSource)\b|BillingPaymentSource(Method|Methods|Resource|JSON)?\b'
packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx (2)

32-33: Remove redundant Promise.resolve in async handler

Unnecessary in an async function.

Apply:

-    return Promise.resolve();

149-168: Minor naming consistency (optional)

Props/vars still named paymentSource while types are PaymentMethod. Consider renaming for consistency in a follow-up to reduce cognitive overhead.

packages/shared/src/react/commerce.tsx (2)

85-93: Add initializePaymentMethod to effect deps

Avoid stale closure and satisfy exhaustive-deps ESLint.

Apply:

-  }, [resource?.id]);
+  }, [resource?.id, initializePaymentMethod]);

As per coding guidelines (ESLint).


65-71: Optional: rename usePaymentSourceUtils to usePaymentMethodUtils

Pure naming cleanup to reduce confusion post-rename. Low priority.

packages/types/src/billing.ts (5)

261-270: Add method-param aliases for consistency

Types still use PaymentSource in Remove/MakeDefault param names. Add aliases to reduce cognitive overhead without breaking changes.

Apply:

 export type RemovePaymentSourceParams = WithOptionalOrgType<unknown>;
 
 export type MakeDefaultPaymentSourceParams = WithOptionalOrgType<unknown>;
+
+// Aliases for terminology alignment (non-breaking)
+export type RemovePaymentMethodParams = RemovePaymentSourceParams;
+export type MakeDefaultPaymentMethodParams = MakeDefaultPaymentSourceParams;

271-331: Docs still say “payment source” on PaymentMethod resource

Update JSDoc to “payment method” to match the rename.

Apply (docs only):

- * A function that removes this payment source from the account. Accepts the following parameters:
+ * A function that removes this payment method from the account. Accepts the following parameters:
@@
- * A function that sets this payment source as the default for the account. Accepts the following parameters:
+ * A function that sets this payment method as the default for the account. Accepts the following parameters:

392-395: Doc: rename “payment source” to “payment method”

Property name is updated; fix the comment for clarity.

Apply:

-  /**
-   * The payment source being used for the payment, such as credit card or bank account.
-   */
+  /**
+   * The payment method used for the payment, such as a credit card or bank account.
+   */

496-499: Doc: rename “payment source” to “payment method”

Comment should match paymentMethodId.

Apply:

-  /**
-   * The unique identifier for the payment source being used for the subscription item.
-   */
+  /**
+   * The unique identifier for the payment method used for the subscription item.
+   */

704-731: Add paymentMethodId and deprecate paymentSourceId
Update the first union branch in ConfirmCheckoutParams to introduce paymentMethodId and mark paymentSourceId as deprecated. Existing calls remain valid.

 export type ConfirmCheckoutParams =
   | {
-      /**
-       * The ID of a saved payment source to use for this checkout.
-       */
-      paymentSourceId?: string;
+      /**
+       * The ID of a saved payment method to use for this checkout.
+       */
+      paymentMethodId?: string;
+      /** @deprecated Use `paymentMethodId` instead. */
+      paymentSourceId?: string;
     }
packages/clerk-js/src/core/resources/Organization.ts (1)

265-270: LGTM on org-scoped wrappers; add JSDoc and explicit public for clarity

The wrappers correctly inject orgId. Consider adding JSDoc and public for these public APIs. As per coding guidelines.

Also applies to: 272-277, 279-284

packages/clerk-js/src/core/resources/BillingPaymentSource.ts (2)

46-46: Add explicit return types for public methods

Annotate return types to satisfy public API guidelines. As per coding guidelines.

Apply:

-  public async remove(params?: RemovePaymentSourceParams) {
+  public async remove(params?: RemovePaymentSourceParams): Promise<DeletedObject> {
@@
-  public async makeDefault(params?: MakeDefaultPaymentSourceParams) {
+  public async makeDefault(params?: MakeDefaultPaymentSourceParams): Promise<null> {

Also applies to: 60-60


46-58: Align BillingPaymentSource to payment_methods & Billing.path

  • Import Billing and PAYMENT_METHODS_PATH from core/modules/billing/payment-source-methods and replace the hard-coded /commerce/payment_sources/${this.id} in remove() with
    Billing.path(${PAYMENT_METHODS_PATH}/${this.id}, { orgId })
  • Change the default-setter path to use /payers/default_payment_method via Billing.path and update its body to { payment_method_id: this.id }
  • Update the hidden input in CheckoutForm and its tests from payment_source_idpayment_method_id
  • If your API still only supports payment_sources, leave the existing implementation for compatibility
packages/clerk-js/src/core/modules/billing/payment-source-methods.ts (6)

1-8: Import resource interface types for accurate return typings

Use the resource interfaces in return types for public APIs.

As per coding guidelines

 import type {
   AddPaymentMethodParams,
   BillingInitializedPaymentMethodJSON,
   BillingPaymentMethodJSON,
   ClerkPaginatedResponse,
   GetPaymentMethodsParams,
   InitializePaymentMethodParams,
+  BillingInitializedPaymentMethodResource,
+  BillingPaymentMethodResource,
 } from '@clerk/types';

14-14: Consider centralizing PAYMENT_METHODS_PATH

Expose this via Billing (e.g., Billing.paths.paymentMethods) to avoid duplication across modules/resources.


16-26: Add explicit return type and avoid any in initializePaymentMethod

Return the resource interface and tighten the body type.

As per coding guidelines

-export const initializePaymentMethod = async (params: InitializePaymentMethodParams) => {
+export const initializePaymentMethod = async (
+  params: InitializePaymentMethodParams,
+): Promise<BillingInitializedPaymentMethodResource> => {
   const { orgId, ...rest } = params;

   const json = (
     await BaseResource._fetch({
       path: Billing.path(`${PAYMENT_METHODS_PATH}/initialize`, { orgId }),
       method: 'POST',
-      body: rest as any,
+      body: rest as Omit<InitializePaymentMethodParams, "orgId">,
     })
   )?.response as unknown as BillingInitializedPaymentMethodJSON;
   return new BillingInitializedPaymentMethod(json);
 }

29-39: Add explicit return type and avoid any in addPaymentMethod

Return the resource interface and tighten the body type.

As per coding guidelines

-export const addPaymentMethod = async (params: AddPaymentMethodParams) => {
+export const addPaymentMethod = async (
+  params: AddPaymentMethodParams,
+): Promise<BillingPaymentMethodResource> => {
   const { orgId, ...rest } = params;

   const json = (
     await BaseResource._fetch({
       path: Billing.path(PAYMENT_METHODS_PATH, { orgId }),
       method: 'POST',
-      body: rest as any,
+      body: rest as Omit<AddPaymentMethodParams, "orgId">,
     })
   )?.response as unknown as BillingPaymentMethodJSON;
   return new BillingPaymentMethod(json);
 }

42-56: Type the return, drop redundant await, and fix naming

  • Explicit return type with Resource interface
  • Remove redundant await before .then
  • Rename paymentSources -> paymentMethods

As per coding guidelines

-export const getPaymentMethods = async (params: GetPaymentMethodsParams) => {
+export const getPaymentMethods = async (
+  params: GetPaymentMethodsParams,
+): Promise<ClerkPaginatedResponse<BillingPaymentMethodResource>> => {
   const { orgId, ...rest } = params;

-  return await BaseResource._fetch({
+  return BaseResource._fetch({
     path: Billing.path(PAYMENT_METHODS_PATH, { orgId }),
     method: 'GET',
     search: convertPageToOffsetSearchParams(rest),
   }).then(res => {
-    const { data: paymentSources, total_count } =
+    const { data: paymentMethods, total_count } =
       res?.response as unknown as ClerkPaginatedResponse<BillingPaymentMethodJSON>;
     return {
       total_count,
-      data: paymentSources.map(paymentMethod => new BillingPaymentMethod(paymentMethod)),
+      data: paymentMethods.map(pm => new BillingPaymentMethod(pm)),
     };
   });
 }

1-1: Rename file and update import

Rename
packages/clerk-js/src/core/modules/billing/payment-source-methods.tspayment-methods.ts
and in
packages/clerk-js/src/core/modules/billing/index.ts
change

-export * from './payment-source-methods';
+export * from './payment-methods';
📜 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 5546352 and cb47eea.

📒 Files selected for processing (19)
  • .changeset/rich-breads-move.md (1 hunks)
  • packages/clerk-js/src/core/modules/billing/namespace.ts (1 hunks)
  • packages/clerk-js/src/core/modules/billing/payment-source-methods.ts (1 hunks)
  • packages/clerk-js/src/core/resources/BillingCheckout.ts (3 hunks)
  • packages/clerk-js/src/core/resources/BillingPayment.ts (2 hunks)
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts (2 hunks)
  • packages/clerk-js/src/core/resources/BillingSubscription.ts (2 hunks)
  • packages/clerk-js/src/core/resources/Organization.ts (2 hunks)
  • packages/clerk-js/src/core/resources/User.ts (2 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (2 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (2 hunks)
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx (1 hunks)
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx (4 hunks)
  • packages/shared/src/react/commerce.tsx (5 hunks)
  • packages/shared/src/react/hooks/usePaymentMethods.tsx (1 hunks)
  • packages/types/src/billing.ts (11 hunks)
  • packages/types/src/json.ts (5 hunks)
  • packages/types/src/organization.ts (2 hunks)
  • packages/types/src/user.ts (2 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/types/src/organization.ts
  • packages/types/src/user.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/clerk-js/src/core/modules/billing/namespace.ts
  • packages/clerk-js/src/core/resources/BillingSubscription.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/User.ts
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx
  • packages/types/src/billing.ts
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/commerce.tsx
  • packages/clerk-js/src/core/resources/BillingPayment.ts
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/core/modules/billing/payment-source-methods.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/organization.ts
  • packages/types/src/user.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/clerk-js/src/core/modules/billing/namespace.ts
  • packages/clerk-js/src/core/resources/BillingSubscription.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/User.ts
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx
  • packages/types/src/billing.ts
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/commerce.tsx
  • packages/clerk-js/src/core/resources/BillingPayment.ts
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/core/modules/billing/payment-source-methods.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/types/src/organization.ts
  • packages/types/src/user.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/clerk-js/src/core/modules/billing/namespace.ts
  • packages/clerk-js/src/core/resources/BillingSubscription.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/User.ts
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx
  • packages/types/src/billing.ts
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/commerce.tsx
  • packages/clerk-js/src/core/resources/BillingPayment.ts
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/core/modules/billing/payment-source-methods.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/organization.ts
  • packages/types/src/user.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/clerk-js/src/core/modules/billing/namespace.ts
  • packages/clerk-js/src/core/resources/BillingSubscription.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/User.ts
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx
  • packages/types/src/billing.ts
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/commerce.tsx
  • packages/clerk-js/src/core/resources/BillingPayment.ts
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/core/modules/billing/payment-source-methods.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
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly 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
Use const assertions for literal types: as const
Use satisfies 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 ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly 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/organization.ts
  • packages/types/src/user.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/clerk-js/src/core/modules/billing/namespace.ts
  • packages/clerk-js/src/core/resources/BillingSubscription.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/User.ts
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx
  • packages/types/src/billing.ts
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/commerce.tsx
  • packages/clerk-js/src/core/resources/BillingPayment.ts
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/core/modules/billing/payment-source-methods.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/organization.ts
  • packages/types/src/user.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/clerk-js/src/core/modules/billing/namespace.ts
  • packages/clerk-js/src/core/resources/BillingSubscription.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/User.ts
  • packages/clerk-js/src/core/resources/Organization.ts
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx
  • packages/types/src/billing.ts
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/commerce.tsx
  • packages/clerk-js/src/core/resources/BillingPayment.ts
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/core/modules/billing/payment-source-methods.ts
.changeset/**

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/rich-breads-move.md
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/components/PaymentSources/PaymentSources.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/components/PaymentSources/PaymentSources.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/commerce.tsx
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/components/PaymentSources/PaymentSources.tsx
  • packages/shared/src/react/hooks/usePaymentMethods.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/commerce.tsx
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
🧬 Code graph analysis (15)
packages/types/src/organization.ts (2)
packages/types/src/resource.ts (1)
  • ClerkResource (8-21)
packages/types/src/billing.ts (1)
  • BillingPayerMethods (88-105)
packages/types/src/user.ts (1)
packages/types/src/billing.ts (1)
  • BillingPayerMethods (88-105)
packages/clerk-js/src/core/resources/BillingCheckout.ts (2)
packages/types/src/billing.ts (2)
  • BillingCheckoutResource (737-790)
  • BillingPaymentMethodResource (276-331)
packages/clerk-js/src/core/resources/BillingPaymentSource.ts (1)
  • BillingPaymentMethod (14-72)
packages/types/src/json.ts (2)
packages/backend/src/api/resources/JSON.ts (1)
  • ClerkResourceJSON (78-87)
packages/types/src/billing.ts (1)
  • BillingPaymentMethodStatus (223-223)
packages/clerk-js/src/core/resources/User.ts (1)
packages/clerk-js/src/core/modules/billing/payment-source-methods.ts (3)
  • initializePaymentMethod (16-26)
  • addPaymentMethod (28-39)
  • getPaymentMethods (41-56)
packages/clerk-js/src/core/resources/Organization.ts (1)
packages/clerk-js/src/core/modules/billing/payment-source-methods.ts (3)
  • initializePaymentMethod (16-26)
  • addPaymentMethod (28-39)
  • getPaymentMethods (41-56)
packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx (1)
packages/types/src/billing.ts (1)
  • BillingPaymentMethodResource (276-331)
packages/types/src/billing.ts (2)
packages/types/src/pagination.ts (2)
  • ClerkPaginatedResponse (22-31)
  • ClerkPaginationParams (36-47)
packages/types/src/resource.ts (1)
  • ClerkResource (8-21)
packages/clerk-js/src/core/resources/BillingPaymentSource.ts (2)
packages/types/src/billing.ts (3)
  • BillingPaymentMethodResource (276-331)
  • BillingPaymentMethodStatus (223-223)
  • BillingInitializedPaymentMethodResource (336-349)
packages/types/src/json.ts (2)
  • BillingPaymentMethodJSON (674-684)
  • BillingInitializedPaymentMethodJSON (689-694)
packages/shared/src/react/hooks/usePaymentMethods.tsx (4)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • usePaymentMethods (32-40)
packages/shared/src/react/hooks/index.ts (1)
  • usePaymentMethods (13-13)
packages/shared/src/react/hooks/createBillingPaginatedHook.tsx (1)
  • createBillingPaginatedHook (41-112)
packages/types/src/billing.ts (2)
  • BillingPaymentMethodResource (276-331)
  • GetPaymentMethodsParams (228-228)
packages/shared/src/react/commerce.tsx (1)
packages/clerk-js/src/core/modules/billing/payment-source-methods.ts (1)
  • initializePaymentMethod (16-26)
packages/clerk-js/src/core/resources/BillingPayment.ts (2)
packages/types/src/billing.ts (3)
  • BillingPaymentResource (370-407)
  • BillingMoneyAmount (621-638)
  • BillingPaymentMethodResource (276-331)
packages/clerk-js/src/core/resources/BillingPaymentSource.ts (1)
  • BillingPaymentMethod (14-72)
packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx (1)
packages/types/src/billing.ts (1)
  • BillingPaymentMethodResource (276-331)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (2)
packages/types/src/billing.ts (1)
  • BillingPaymentMethodResource (276-331)
packages/shared/src/react/hooks/useCheckout.ts (1)
  • useCheckout (70-147)
packages/clerk-js/src/core/modules/billing/payment-source-methods.ts (5)
packages/types/src/billing.ts (3)
  • InitializePaymentMethodParams (240-245)
  • AddPaymentMethodParams (250-259)
  • GetPaymentMethodsParams (228-228)
packages/clerk-js/src/core/modules/billing/namespace.ts (1)
  • Billing (30-142)
packages/types/src/json.ts (2)
  • BillingInitializedPaymentMethodJSON (689-694)
  • BillingPaymentMethodJSON (674-684)
packages/clerk-js/src/core/resources/BillingPaymentSource.ts (2)
  • BillingInitializedPaymentMethod (74-94)
  • BillingPaymentMethod (14-72)
packages/types/src/pagination.ts (1)
  • ClerkPaginatedResponse (22-31)
⏰ 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 (28)
packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx (1)

6-6: LGTM: Prop type updated to BillingPaymentMethodResource.

The runtime logic remains compatible and continues to use stable element descriptors for theming.

packages/clerk-js/src/core/resources/BillingCheckout.ts (1)

23-24: LGTM: paymentMethod field and JSON mapping updated correctly.

The resource now aligns with types (BillingCheckoutResource.paymentMethod?) and correctly maps data.payment_method via BillingPaymentMethod.

Also applies to: 46-46

packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx (4)

27-33: LGTM: switched to addPaymentMethod

The add flow correctly calls the new addPaymentMethod API.


57-59: LGTM: prop type updated to BillingPaymentMethodResource

Matches the new public type.


170-181: Localization keys still reference paymentSourcesSection

If terminology is being aligned everywhere, confirm whether localization keys will remain as-is for backward compatibility or need aliases/new keys.


196-198: LGTM: menu prop type updated to BillingPaymentMethodResource

Consistent with the rename.

packages/clerk-js/src/core/resources/User.ts (2)

39-39: LGTM: imports switched to payment method APIs

Imports align with the new billing module exports.


294-304: LGTM: user forwards to initialize/add/get payment methods

Signatures delegate correctly.

Confirm deprecation strategy for old method names (initializePaymentSource/addPaymentSource/getPaymentSources) to avoid breaking third-party consumers. If kept, mark deprecated and forward to the new calls.

packages/clerk-js/src/core/resources/BillingPayment.ts (3)

5-9: LGTM: type import updated to BillingPaymentMethodResource

Matches the types package changes.


21-22: LGTM: field renamed to paymentMethod

Public shape matches updated BillingPaymentResource.


41-43: LGTM: fromJSON maps payment_method to BillingPaymentMethod

Deserializer aligned with JSON changes.

packages/shared/src/react/commerce.tsx (4)

71-81: LGTM: initialize flow renamed to payment method

SWR mutation, key, and resource call updated consistently.


94-97: LGTM: derived fields renamed

externalGatewayId/externalClientSecret/paymentMethodOrder usage is consistent.


115-121: LGTM

Provider returns renamed initializer and fields.


326-368: LGTM: reset now re-initializes payment method

Stripe flow remains unchanged; rename applied correctly.

packages/types/src/billing.ts (5)

88-105: LGTM: BillingPayerMethods moved to payment method APIs

Public surface matches the rename.


223-229: LGTM: BillingPaymentMethodStatus defined

Matches resource usage.


228-259: LGTM: Initialize/Add/Get PaymentMethod param types

Consistent with backend expectations.


336-349: LGTM: InitializedPaymentMethodResource shape

Matches shared/react usage (externalClientSecret, externalGatewayId, paymentMethodOrder).


751-754: LGTM: BillingCheckout.paymentMethod switched to PaymentMethodResource

Public surface aligns with rename.

packages/types/src/json.ts (3)

9-9: LGTM: status type rename import is consistent


674-684: LGTM: type and field renames from payment_source → payment_method

Interfaces and JSON field names align with the new terminology.

Also applies to: 720-733, 737-759, 816-832


689-694: Confirm object discriminator matches API spec
In packages/types/src/json.ts at line 690, the object field is set to 'commerce_payment_source_initialize'; verify against the backend/API docs and update to the correct discriminator (e.g. 'commerce_payment_method_initialize') if needed.

packages/clerk-js/src/core/resources/BillingPaymentSource.ts (2)

2-10: LGTM: class/type renames and JSON mapping

Renames to PaymentMethod types and status look consistent. Mapping from JSON fields to resource props is correct.

Also applies to: 14-22, 24-45


74-95: LGTM: InitializedPaymentMethod resource

Fields map correctly; sensible default for paymentMethodOrder.

packages/clerk-js/src/core/resources/Organization.ts (1)

31-31: Barrel exports confirmed
../modules/billing/index.ts re-exports initializePaymentMethod, addPaymentMethod, and getPaymentMethods; imports are valid.

packages/clerk-js/src/core/modules/billing/payment-source-methods.ts (2)

20-21: Nice: centralized path construction

Using Billing.path improves consistency and reduces duplication of org/me path logic.


41-56: Verify billing endpoint consistency
getPaymentMethods uses /commerce/payment_methods, but BillingPaymentSource.remove and .makeDefault still hit /commerce/payment_sources (and use payment_source_id). Confirm the backend supports both or update these methods (and related types/params) to use the payment_methods endpoints and naming.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/clerk-js/src/core/resources/BillingPaymentSource.ts (1)

46-71: Update the REST endpoints to payment_methods.

Everything else in the PR (types, JSON DTOs, UI) now speaks in terms of “payment methods”, but these calls still hit /payment_sources and send payment_source_id. Once the backend ships the new naming (see BillingPaymentMethodJSON.object = 'commerce_payment_method'), these requests will 404 or be rejected, so removing or making a payment method default will break. Please switch the paths/body payload over to the new payment_methods naming.

Apply this diff:

-        path: orgId
-          ? `/organizations/${orgId}/commerce/payment_sources/${this.id}`
-          : `/me/commerce/payment_sources/${this.id}`,
+        path: orgId
+          ? `/organizations/${orgId}/commerce/payment_methods/${this.id}`
+          : `/me/commerce/payment_methods/${this.id}`,
@@
-      path: orgId
-        ? `/organizations/${orgId}/commerce/payers/default_payment_source`
-        : `/me/commerce/payers/default_payment_source`,
+      path: orgId
+        ? `/organizations/${orgId}/commerce/payers/default_payment_method`
+        : `/me/commerce/payers/default_payment_method`,
@@
-      body: { payment_source_id: this.id } as any,
+      body: { payment_method_id: this.id } as any,
📜 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.

📥 Commits

Reviewing files that changed from the base of the PR and between cb47eea and 4dc4c44.

📒 Files selected for processing (8)
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts (2 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (2 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (6 hunks)
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx (3 hunks)
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx (5 hunks)
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts (3 hunks)
  • packages/types/src/billing.ts (14 hunks)
  • packages/types/src/json.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSourceRow.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
🧰 Additional context used
📓 Path-based instructions (11)
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/components/PaymentSources/PaymentSources.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/components/PaymentSources/PaymentSources.tsx
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/types/src/json.ts
  • packages/types/src/billing.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/components/PaymentSources/PaymentSources.tsx
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/types/src/json.ts
  • packages/types/src/billing.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/types/src/json.ts
  • packages/types/src/billing.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/components/PaymentSources/PaymentSources.tsx
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/types/src/json.ts
  • packages/types/src/billing.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
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly 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
Use const assertions for literal types: as const
Use satisfies 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 ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly 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/components/PaymentSources/PaymentSources.tsx
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/types/src/json.ts
  • packages/types/src/billing.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/components/PaymentSources/PaymentSources.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/components/PaymentSources/PaymentSources.tsx
  • packages/clerk-js/src/core/resources/BillingPaymentSource.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/types/src/json.ts
  • packages/types/src/billing.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/components/PaymentSources/PaymentSources.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/shared/src/react/hooks/__tests__/useCheckout.type.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/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
🧬 Code graph analysis (5)
packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx (1)
packages/types/src/billing.ts (1)
  • BillingPaymentMethodResource (277-332)
packages/clerk-js/src/core/resources/BillingPaymentSource.ts (2)
packages/types/src/billing.ts (3)
  • BillingPaymentMethodResource (277-332)
  • BillingPaymentMethodStatus (223-223)
  • BillingInitializedPaymentMethodResource (337-350)
packages/types/src/json.ts (2)
  • BillingPaymentMethodJSON (674-684)
  • BillingInitializedPaymentMethodJSON (689-694)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (2)
packages/types/src/billing.ts (1)
  • BillingPaymentMethodResource (277-332)
packages/shared/src/react/hooks/useCheckout.ts (1)
  • useCheckout (70-147)
packages/types/src/json.ts (2)
packages/backend/src/api/resources/JSON.ts (1)
  • ClerkResourceJSON (78-87)
packages/types/src/billing.ts (1)
  • BillingPaymentMethodStatus (223-223)
packages/types/src/billing.ts (2)
packages/types/src/pagination.ts (2)
  • ClerkPaginatedResponse (22-31)
  • ClerkPaginationParams (36-47)
packages/types/src/resource.ts (1)
  • ClerkResource (8-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). (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

Comment on lines +380 to 382
const [selectedPaymentSource, setSelectedPaymentSource] = useState<BillingPaymentMethodResource | undefined>(
paymentMethod || paymentSources.find(p => p.isDefault),
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Restore fallback when preselecting payment method

With the new initialization, selectedPaymentSource stays undefined whenever the checkout payload doesn’t include paymentMethod and none of the entries are flagged isDefault. In that case the hidden input posts an empty string, so confirmCheckout sends { paymentMethodId: '' } and the backend rejects the confirmation. Reintroduce the fallback to the first available method so we always submit a valid id.

-    const [selectedPaymentSource, setSelectedPaymentSource] = useState<BillingPaymentMethodResource | undefined>(
-      paymentMethod || paymentSources.find(p => p.isDefault),
-    );
+    const defaultPaymentMethod =
+      paymentMethod ?? paymentSources.find(p => p.isDefault) ?? paymentSources[0];
+
+    const [selectedPaymentSource, setSelectedPaymentSource] = useState<BillingPaymentMethodResource | undefined>(
+      defaultPaymentMethod,
+    );
📝 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.

Suggested change
const [selectedPaymentSource, setSelectedPaymentSource] = useState<BillingPaymentMethodResource | undefined>(
paymentMethod || paymentSources.find(p => p.isDefault),
);
const defaultPaymentMethod =
paymentMethod ?? paymentSources.find(p => p.isDefault) ?? paymentSources[0];
const [selectedPaymentSource, setSelectedPaymentSource] = useState<BillingPaymentMethodResource | undefined>(
defaultPaymentMethod,
);
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx around lines
380 to 382, the state initialization for selectedPaymentSource can end up
undefined when paymentMethod is not provided and no paymentSource has isDefault;
restore a fallback to the first available payment source so we always have a
valid id. Change the initializer to pick paymentMethod || paymentSources.find(p
=> p.isDefault) || paymentSources[0] (and guard for an empty array if needed) so
the hidden input always posts a valid paymentMethodId.

Comment on lines +88 to 105
export interface BillingPayerMethods {
/**
* @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.
*/
initializePaymentSource: (
params: Exclude<InitializePaymentSourceParams, 'orgId'>,
) => Promise<BillingInitializedPaymentSourceResource>;
initializePaymentMethod: (
params: Exclude<InitializePaymentMethodParams, 'orgId'>,
) => Promise<BillingInitializedPaymentMethodResource>;
/**
* @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.
*/
addPaymentSource: (params: Exclude<AddPaymentSourceParams, 'orgId'>) => Promise<BillingPaymentSourceResource>;
addPaymentMethod: (params: Exclude<AddPaymentMethodParams, 'orgId'>) => Promise<BillingPaymentMethodResource>;
/**
* @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.
*/
getPaymentSources: (
params: Exclude<GetPaymentSourcesParams, 'orgId'>,
) => Promise<ClerkPaginatedResponse<BillingPaymentSourceResource>>;
getPaymentMethods: (
params: Exclude<GetPaymentMethodsParams, 'orgId'>,
) => Promise<ClerkPaginatedResponse<BillingPaymentMethodResource>>;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Drop orgId with Omit, not Exclude.

Exclude<…,'orgId'> is a no-op here because the source type is an object; callers can still pass orgId, defeating the whole point of the payer-scoped helpers. Please switch these three helpers over to Omit so the user/org-specific APIs can’t accidentally leak the org parameter.

Apply this diff:

-  initializePaymentMethod: (
-    params: Exclude<InitializePaymentMethodParams, 'orgId'>,
-  ) => Promise<BillingInitializedPaymentMethodResource>;
+  initializePaymentMethod: (
+    params: Omit<InitializePaymentMethodParams, 'orgId'>,
+  ) => Promise<BillingInitializedPaymentMethodResource>;
@@
-  addPaymentMethod: (params: Exclude<AddPaymentMethodParams, 'orgId'>) => Promise<BillingPaymentMethodResource>;
+  addPaymentMethod: (params: Omit<AddPaymentMethodParams, 'orgId'>) => Promise<BillingPaymentMethodResource>;
@@
-  getPaymentMethods: (
-    params: Exclude<GetPaymentMethodsParams, 'orgId'>,
-  ) => Promise<ClerkPaginatedResponse<BillingPaymentMethodResource>>;
+  getPaymentMethods: (
+    params: Omit<GetPaymentMethodsParams, 'orgId'>,
+  ) => Promise<ClerkPaginatedResponse<BillingPaymentMethodResource>>;
📝 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.

Suggested change
export interface BillingPayerMethods {
/**
* @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.
*/
initializePaymentSource: (
params: Exclude<InitializePaymentSourceParams, 'orgId'>,
) => Promise<BillingInitializedPaymentSourceResource>;
initializePaymentMethod: (
params: Exclude<InitializePaymentMethodParams, 'orgId'>,
) => Promise<BillingInitializedPaymentMethodResource>;
/**
* @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.
*/
addPaymentSource: (params: Exclude<AddPaymentSourceParams, 'orgId'>) => Promise<BillingPaymentSourceResource>;
addPaymentMethod: (params: Exclude<AddPaymentMethodParams, 'orgId'>) => Promise<BillingPaymentMethodResource>;
/**
* @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.
*/
getPaymentSources: (
params: Exclude<GetPaymentSourcesParams, 'orgId'>,
) => Promise<ClerkPaginatedResponse<BillingPaymentSourceResource>>;
getPaymentMethods: (
params: Exclude<GetPaymentMethodsParams, 'orgId'>,
) => Promise<ClerkPaginatedResponse<BillingPaymentMethodResource>>;
}
export interface BillingPayerMethods {
/**
* @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.
*/
initializePaymentMethod: (
params: Omit<InitializePaymentMethodParams, 'orgId'>,
) => Promise<BillingInitializedPaymentMethodResource>;
/**
* @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.
*/
addPaymentMethod: (params: Omit<AddPaymentMethodParams, 'orgId'>) => Promise<BillingPaymentMethodResource>;
/**
* @experimental This is an experimental API for the Billing feature that is available under a public beta, and the API is subject to change. It is advised to [pin](https://clerk.com/docs/pinning) the SDK version and the clerk-js version to avoid breaking changes.
*/
getPaymentMethods: (
params: Omit<GetPaymentMethodsParams, 'orgId'>,
) => Promise<ClerkPaginatedResponse<BillingPaymentMethodResource>>;
}
🤖 Prompt for AI Agents
In packages/types/src/billing.ts around lines 88 to 105, the methods currently
use Exclude<..., 'orgId'> which is ineffective for object types; replace Exclude
with Omit for initializePaymentMethod, addPaymentMethod and getPaymentMethods so
the returned param types cannot include orgId (i.e., change each Exclude<...,
'orgId'> to Omit<..., 'orgId'>) and ensure any affected type references still
resolve after the swap.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants