-
Notifications
You must be signed in to change notification settings - Fork 391
chore(clerk-js,types): Align payment methods terminology #6865
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?
chore(clerk-js,types): Align payment methods terminology #6865
Conversation
🦋 Changeset detectedLatest commit: 8ed4a25 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 |
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughRenames "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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Disabled knowledge base sources:
📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ 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)
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: 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 preservethis
context.Passing unbound instance methods can lose
this
(especially for organization-scoped methods that may rely onthis.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 handlerUnnecessary 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 depsAvoid stale closure and satisfy exhaustive-deps ESLint.
Apply:
- }, [resource?.id]); + }, [resource?.id, initializePaymentMethod]);As per coding guidelines (ESLint).
65-71
: Optional: rename usePaymentSourceUtils to usePaymentMethodUtilsPure naming cleanup to reduce confusion post-rename. Low priority.
packages/types/src/billing.ts (5)
261-270
: Add method-param aliases for consistencyTypes 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 resourceUpdate 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
: AddpaymentMethodId
and deprecatepaymentSourceId
Update the first union branch inConfirmCheckoutParams
to introducepaymentMethodId
and markpaymentSourceId
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 clarityThe wrappers correctly inject
orgId
. Consider adding JSDoc andpublic
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 methodsAnnotate 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
andPAYMENT_METHODS_PATH
fromcore/modules/billing/payment-source-methods
and replace the hard-coded/commerce/payment_sources/${this.id}
inremove()
with
Billing.path(
${PAYMENT_METHODS_PATH}/${this.id}, { orgId })
- Change the default-setter path to use
/payers/default_payment_method
viaBilling.path
and update its body to{ payment_method_id: this.id }
- Update the hidden input in
CheckoutForm
and its tests frompayment_source_id
→payment_method_id
- If your API still only supports
payment_sources
, leave the existing implementation for compatibilitypackages/clerk-js/src/core/modules/billing/payment-source-methods.ts (6)
1-8
: Import resource interface types for accurate return typingsUse 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_PATHExpose this via Billing (e.g., Billing.paths.paymentMethods) to avoid duplication across modules/resources.
16-26
: Add explicit return type and avoid any in initializePaymentMethodReturn 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 addPaymentMethodReturn 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 importRename
packages/clerk-js/src/core/modules/billing/payment-source-methods.ts
→payment-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.
📒 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
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/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 mapsdata.payment_method
viaBillingPaymentMethod
.Also applies to: 46-46
packages/clerk-js/src/ui/components/PaymentSources/PaymentSources.tsx (4)
27-33
: LGTM: switched to addPaymentMethodThe add flow correctly calls the new addPaymentMethod API.
57-59
: LGTM: prop type updated to BillingPaymentMethodResourceMatches the new public type.
170-181
: Localization keys still reference paymentSourcesSectionIf 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 BillingPaymentMethodResourceConsistent with the rename.
packages/clerk-js/src/core/resources/User.ts (2)
39-39
: LGTM: imports switched to payment method APIsImports align with the new billing module exports.
294-304
: LGTM: user forwards to initialize/add/get payment methodsSignatures 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 BillingPaymentMethodResourceMatches the types package changes.
21-22
: LGTM: field renamed to paymentMethodPublic shape matches updated BillingPaymentResource.
41-43
: LGTM: fromJSON maps payment_method to BillingPaymentMethodDeserializer aligned with JSON changes.
packages/shared/src/react/commerce.tsx (4)
71-81
: LGTM: initialize flow renamed to payment methodSWR mutation, key, and resource call updated consistently.
94-97
: LGTM: derived fields renamedexternalGatewayId/externalClientSecret/paymentMethodOrder usage is consistent.
115-121
: LGTMProvider returns renamed initializer and fields.
326-368
: LGTM: reset now re-initializes payment methodStripe flow remains unchanged; rename applied correctly.
packages/types/src/billing.ts (5)
88-105
: LGTM: BillingPayerMethods moved to payment method APIsPublic surface matches the rename.
223-229
: LGTM: BillingPaymentMethodStatus definedMatches resource usage.
228-259
: LGTM: Initialize/Add/Get PaymentMethod param typesConsistent with backend expectations.
336-349
: LGTM: InitializedPaymentMethodResource shapeMatches shared/react usage (externalClientSecret, externalGatewayId, paymentMethodOrder).
751-754
: LGTM: BillingCheckout.paymentMethod switched to PaymentMethodResourcePublic 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_methodInterfaces 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, theobject
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 mappingRenames 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 resourceFields 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-exportsinitializePaymentMethod
,addPaymentMethod
, andgetPaymentMethods
; imports are valid.packages/clerk-js/src/core/modules/billing/payment-source-methods.ts (2)
20-21
: Nice: centralized path constructionUsing 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 usepayment_source_id
). Confirm the backend supports both or update these methods (and related types/params) to use thepayment_methods
endpoints and naming.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
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 topayment_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 sendpayment_source_id
. Once the backend ships the new naming (seeBillingPaymentMethodJSON.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 newpayment_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.
📒 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
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/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
const [selectedPaymentSource, setSelectedPaymentSource] = useState<BillingPaymentMethodResource | undefined>( | ||
paymentMethod || paymentSources.find(p => p.isDefault), | ||
); |
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.
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.
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.
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>>; | ||
} |
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.
🛠️ 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.
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.
Description
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Refactor
Chores
Tests