Skip to content

chore(clerk-js,types): Switch to fees for plan prices #6490

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

Merged
merged 13 commits into from
Aug 12, 2025

Conversation

panteliselef
Copy link
Member

@panteliselef panteliselef commented Aug 8, 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

    • Pricing now uses structured fee objects (fee, annualFee, annualMonthlyFee) and a formatter to normalize displayed prices.
  • Refactor

    • Consolidated pricing fields and extracted subscription/payment UI pieces into dedicated components for clearer rendering.
  • Bug Fixes

    • More consistent billing-period toggles and price selection/display across checkout, plans, subscriptions, and payment attempts.
  • Tests

    • Updated test fixtures and expectations to match new fee structure and formatting.
  • Chores

    • Added a changeset documenting a minor version update.

@panteliselef panteliselef requested a review from a team August 8, 2025 10:17
@panteliselef panteliselef self-assigned this Aug 8, 2025
Copy link

changeset-bot bot commented Aug 8, 2025

🦋 Changeset detected

Latest commit: 5377039

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/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/localizations Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/shared Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/themes Patch
@clerk/vue 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 Aug 8, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Preview Comment Aug 12, 2025 8:05pm

Copy link

pkg-pr-new bot commented Aug 8, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 5377039

Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

📝 Walkthrough

Walkthrough

Renames and reshapes monetary types and plan pricing across the codebase: CommerceMoney → CommerceMoneyAmount and flat plan pricing fields (amount, amountFormatted, annualAmount*, annualMonthlyAmount*) → structured fee objects (fee, annualFee, annualMonthlyFee) of type CommerceMoneyAmount. Updates include JSON types, parsing helpers (commerceMoneyFromJSON → commerceMoneyAmountFromJSON), utils (commerceTotalsFromJSON), backend JSON shapes, TypeScript public interfaces, and many UI components/contexts to read fee objects and use a new normalizeFormatted helper. Tests and fixtures were updated to the new shape and expected formatted strings; some inline UI blocks were extracted into small components and plan snapshot code removed.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 9

🔭 Outside diff range comments (2)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)

193-200: Localize aria-label

Avoid hard-coded strings; use localization for accessibility labels.

-        <SegmentedControl.Root
-          aria-label='Payment method source'
+        <SegmentedControl.Root
+          aria-label={localizationKeys('commerce.checkout.paymentMethodSource')}
packages/types/src/json.ts (1)

635-645: Deprecate legacy flat amount fields in CommercePlanJSON

The CommercePlanJSON type now includes a structured fee: CommerceFeeJSON object while continuing to expose the old flat amount* properties. Maintaining both sets without marking the old fields as deprecated increases the risk of inconsistent client usage.

Suggested fixes:

  • In packages/types/src/json.ts (around lines 635–645), add @deprecated JSDoc to these legacy fields:
    • amount
    • amount_formatted
    • annual_amount
    • annual_amount_formatted
    • annual_monthly_amount
    • annual_monthly_amount_formatted
    • currency_symbol
    • currency
  • Update your release notes or a migration guide to:
    1. Inform clients about the preferred fee object.
    2. Provide a timeline for removing the deprecated fields.
🧹 Nitpick comments (17)
.changeset/rich-drinks-ring.md (1)

6-6: Clarify the migration note for easier changelog scanning

Consider mentioning key property renames in the message (e.g., “annualMonthlyAmount → annualMonthlyFee.amount”) to help downstream consumers.

packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)

154-163: Nit: typo in variable name

subscriptionBaseOnPanPeriodsubscriptionBasedOnPlanPeriod for clarity.

packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)

359-363: Avoid passing undefined to hidden input value

React can warn on undefined value. Default to empty string.

-              value={selectedPaymentSource?.id}
+              value={selectedPaymentSource?.id ?? ''}

Also applies to: 380-384

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

72-76: Clarify optional amount and credit semantics

There’s a TODO about amount possibly being undefined. Consider documenting cases when these fields are absent to guide consumers and prevent defensive checks proliferating in UI.

Also ensure data.credit shape is stable (i.e., data.credit?.amount) — your guard is correct.

Also applies to: 104-106

packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx (1)

240-242: Inconsistent price formatting – use the shared normalizeFormatted helper

Other components now strip trailing “.00” via normalizeFormatted; this one still renders the raw amountFormatted, so $10.00 shows up instead of $10.

Import the helper (or centralise it in utils/formatting.ts) and render:

{planFee.currencySymbol}
{normalizeFormatted(planFee.amountFormatted)}

to keep pricing display consistent across the UI.

packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx (1)

35-53: Heavy inline fee objects – consider a test builder

Every test now repeats the full { amount, amountFormatted, … } shape. A small helper like makeFee(1000, '$10.00') or a factory in createFixtures would slash ~100 LOC and keep future changes (e.g. new field) to one place.

packages/clerk-js/src/ui/components/Plans/PlanDetails.tsx (1)

221-226: Deduplicate normalizeFormatted

The same helper appears in multiple components. Move it to a shared utility (e.g. src/utils/formatting.ts) and re-use to avoid drift and ensure pricing is formatted uniformly.

packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx (1)

217-233: Use the shared normalizeFormatted helper for fee display

Other components (e.g. SubscriptionsList, PricingTableDefault) run fee strings through normalizeFormatted to strip trailing “.00”.
For UI consistency, apply the same helper here:

-            text={`${fee.currencySymbol}${fee.amountFormatted}`}
+            text={`${fee.currencySymbol}${normalizeFormatted(fee.amountFormatted)}`}

…and add the corresponding import.

packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx (1)

132-137: Deduplicate normalizeFormatted – extract to a shared util

The same helper exists here and in PricingTableDefault.tsx.
Move it to ui/utils/formatting.ts (or similar) and import where needed to keep DRY.

packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (1)

289-294: Helper duplication – reuse the shared normalizeFormatted

This is the second definition of the same helper. Centralize it once in a utility module and import it to avoid maintenance drift.

packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx (2)

327-333: Make price normalization locale-safe and reusable

The string check only handles ".00". If formatted values use commas (e.g., "10,00") you’ll miss normalization. Prefer a locale-agnostic approach or at least support both separators. Consider centralizing this helper to avoid duplication across UI.

-function normalizeFormatted(formatted: string) {
-  return formatted.endsWith('.00') ? formatted.slice(0, -3) : formatted;
-}
+function normalizeFormatted(formatted: string) {
+  // Strip trailing zero cents regardless of decimal separator
+  return /([.,]00)$/.test(formatted) ? formatted.slice(0, -3) : formatted;
+}

344-346: Switchability should be symmetric for annual→monthly

Current logic checks annualMonthlyFee > 0 only when on a monthly plan. Consider also requiring monthly fee > 0 when on an annual plan to avoid offering a switch to a zero-cost monthly tier unintentionally.

-  const isSwitchable =
-    ((subscription.planPeriod === 'month' && subscription.plan.annualMonthlyFee.amount > 0) ||
-      subscription.planPeriod === 'annual') &&
-    subscription.status !== 'past_due';
+  const isSwitchable =
+    ((subscription.planPeriod === 'month' && subscription.plan.annualMonthlyFee.amount > 0) ||
+      (subscription.planPeriod === 'annual' && subscription.plan.fee.amount > 0)) &&
+    subscription.status !== 'past_due';

If product intent is to allow switching even when the destination has no base fee (e.g., free→free), feel free to dismiss.

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

290-309: Clarify fee fields’ semantics (docs)

Document each fee field clearly:

  • fee: monthly price when billed monthly
  • annualFee: total annual price when billed annually
  • annualMonthlyFee: effective monthly price when billed annually

This avoids confusion and reduces misuse across UI/client code.


1034-1034: Document when subscription item amount is present

amount?: CommerceFee is optional. Add a brief JSDoc describing when it’s set (e.g., non-free items, proration scenarios).


1052-1052: Currency consistency between credit and plan

Consider asserting/documenting that credit.amount.currency matches the plan’s currency to prevent mixed-currency totals. Type-level enforcement may be heavy, but documentation helps.


1182-1219: Mark CommerceFee fields as readonly and specify units

These values are data snapshots and should be immutable. Also, clarify whether amount is in major currency units (e.g., 10.50 USD) vs minor units (e.g., 1050 cents).

-export interface CommerceFee {
+export interface CommerceFee {
-  amount: number;
-  amountFormatted: string;
-  currency: string;
-  currencySymbol: string;
+  readonly amount: number; // Clarify units (major vs minor) in JSDoc
+  readonly amountFormatted: string;
+  readonly currency: string; // ISO 4217 code
+  readonly currencySymbol: string; // Display symbol corresponding to currency
 }

1238-1284: Totals currency invariants (optional strong typing)

All totals should share the same currency. If you want type-level guarantees, consider parameterizing CommerceFee with a currency generic and threading it through CommerceCheckoutTotals. This is optional and can be deferred if it complicates usage.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6ff416f and d7daf96.

📒 Files selected for processing (17)
  • .changeset/rich-drinks-ring.md (1 hunks)
  • packages/clerk-js/src/core/resources/CommercePayment.ts (3 hunks)
  • packages/clerk-js/src/core/resources/CommercePlan.ts (2 hunks)
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts (6 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (4 hunks)
  • packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx (3 hunks)
  • packages/clerk-js/src/ui/components/Plans/PlanDetails.tsx (3 hunks)
  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx (8 hunks)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (4 hunks)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx (4 hunks)
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx (14 hunks)
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx (5 hunks)
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx (3 hunks)
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx (2 hunks)
  • packages/clerk-js/src/utils/commerce.ts (2 hunks)
  • packages/types/src/commerce.ts (15 hunks)
  • packages/types/src/json.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (15)
.changeset/**

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/rich-drinks-ring.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/Plans/PlanDetails.tsx
  • packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.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/Plans/PlanDetails.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/utils/commerce.ts
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
**/*.{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/Plans/PlanDetails.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/utils/commerce.ts
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/Plans/PlanDetails.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/utils/commerce.ts
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
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/Plans/PlanDetails.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/utils/commerce.ts
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
**/*.{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/Plans/PlanDetails.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/utils/commerce.ts
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.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/Plans/PlanDetails.tsx
  • packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.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/Plans/PlanDetails.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/utils/commerce.ts
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.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/Plans/PlanDetails.tsx
  • packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
**/*

⚙️ CodeRabbit Configuration File

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/clerk-js/src/ui/components/Plans/PlanDetails.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/ui/components/PaymentAttempts/PaymentAttemptPage.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
  • packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
  • packages/clerk-js/src/utils/commerce.ts
  • packages/types/src/commerce.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableMatrix.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
**/*.test.{jsx,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

**/*.test.{jsx,tsx}: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure

Files:

  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/clerk-js/src/ui/components/Plans/__tests__/PlanDetails.test.tsx
  • packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx
🧬 Code Graph Analysis (3)
packages/clerk-js/src/core/resources/CommerceSubscription.ts (2)
packages/types/src/commerce.ts (1)
  • CommerceFee (1182-1219)
packages/clerk-js/src/utils/commerce.ts (1)
  • commerceFeeFromJSON (10-17)
packages/clerk-js/src/core/resources/CommercePayment.ts (2)
packages/types/src/commerce.ts (2)
  • CommercePaymentResource (696-780)
  • CommerceFee (1182-1219)
packages/clerk-js/src/utils/commerce.ts (1)
  • commerceFeeFromJSON (10-17)
packages/clerk-js/src/utils/commerce.ts (2)
packages/types/src/json.ts (1)
  • CommerceFeeJSON (825-830)
packages/types/src/commerce.ts (3)
  • CommerceFee (1182-1219)
  • CommerceCheckoutTotals (1229-1284)
  • CommerceStatementTotals (1295-1295)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (15)
.changeset/rich-drinks-ring.md (1)

1-7: Changeset present and correct for automated release

Packages and version bumps look valid; message communicates the switch to fee objects.

packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)

302-306: Ignore annualMonthlyFee guard suggestion

The annualMonthlyFee property is defined as a required CommerceFee in both packages/types/src/commerce.ts and packages/clerk-js/src/core/resources/CommercePlan.ts, so it will always be present at runtime. No additional optional‐chaining or defaulting is needed here—keep the existing logic as is.

Likely an incorrect or invalid review comment.

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

2-9: Type migration to CommerceFee looks correct

Imports, property type, and JSON parsing updated to fees; aligns with @clerk/types and utils/commerce.

Also applies to: 11-11, 17-17, 41-41

packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (3)

2-2: Import/type update is consistent

Switch to CommerceFee is aligned with the refactor.


59-60: Price display now uses fee fields — LGTM

${fee.currencySymbol}${fee.amountFormatted} matches the new CommerceFee structure.


312-314: Prop type update to CommerceFee is correct

ExistingPaymentSourceForm.totalDueNow now matches totals.totalDueNow type.

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

3-11: Fee migration in subscription models is consistent

  • Replaced CommerceMoney with CommerceFee in nextPayment, amount, and credit.
  • Switched to commerceFeeFromJSON deserializer.

No logic changes — deserialization remains straightforward.

Also applies to: 15-16, 26-29, 49-51, 73-77, 104-106

packages/clerk-js/src/ui/components/SubscriptionDetails/__tests__/SubscriptionDetails.test.tsx (1)

58-75: Fixture realism – annualMonthlyFee.amount looks off

annualMonthlyFee.amount is set to 8333 ($83.33) while the corresponding annual fee is $100.
If the intent is “$8.33 / month when billed annually”, this should be 833, not 8333, or the assertions will silently rely on unrelated fields. Double-check the cents values in all test fixtures to prevent false positives.

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

825-830: 👍 New CommerceFeeJSON type looks solid

Clear, minimal shape; no issues spotted.

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

10-12: LGTM – fee properties correctly introduced

fee, annualFee, annualMonthlyFee are typed and populated via commerceFeeFromJSON.
No functional or typing issues detected.

packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (1)

147-150: Condition relies on annualMonthlyFee.amount; confirm zero-price annual plans

plan.annualMonthlyFee.amount > 0 guards the annual–toggle logic.
If an annual plan’s monthly-equivalent is zero (free annual plan), users will never see the annual switch even though annualFee.amount might be non-zero. Double-check the intended behaviour.

packages/clerk-js/src/ui/components/SubscriptionDetails/index.tsx (2)

379-385: Good: normalized amounts and fee object usage in switch labels

Using fee.amountFormatted via normalizeFormatted and fee.currencySymbol is consistent with the new CommerceFee model.


379-385: Ensure translation placeholders match expectations for currency/code

You pass currencySymbol as the “currency” placeholder. Verify your i18n messages expect a symbol vs a code. If they expect ISO code, pass amount.currency instead.

Also applies to: 511-514

packages/types/src/commerce.ts (2)

706-706: LGTM: unify payment.amount to CommerceFee

This enables consistent currency/symbol handling across UI.


1118-1118: LGTM: nextPayment.amount moved to CommerceFee

Matches UI consumption patterns.

Comment on lines 58 to 61
prefix={planPeriod === 'annual' ? 'x12' : undefined}
text={`${plan.currencySymbol}${planPeriod === 'month' ? plan.amountFormatted : plan.annualMonthlyAmountFormatted}`}
text={`${fee.currencySymbol}${fee.amountFormatted}`}
suffix={localizationKeys('commerce.checkout.perMonth')}
/>
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

Localize hard-coded 'x12' multiplier

All user-facing strings must be localized. Replace 'x12' with a localization key (e.g., commerce.checkout.x12) or a parameterized key.

-              prefix={planPeriod === 'annual' ? 'x12' : undefined}
+              prefix={planPeriod === 'annual' ? localizationKeys('commerce.checkout.x12') : undefined}
📝 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
prefix={planPeriod === 'annual' ? 'x12' : undefined}
text={`${plan.currencySymbol}${planPeriod === 'month' ? plan.amountFormatted : plan.annualMonthlyAmountFormatted}`}
text={`${fee.currencySymbol}${fee.amountFormatted}`}
suffix={localizationKeys('commerce.checkout.perMonth')}
/>
prefix={planPeriod === 'annual' ? localizationKeys('commerce.checkout.x12') : undefined}
text={`${fee.currencySymbol}${fee.amountFormatted}`}
suffix={localizationKeys('commerce.checkout.perMonth')}
/>
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx around lines 58
to 61, the hard-coded string 'x12' used as a prefix should be replaced with a
localized string. Update the code to use a localization key such as
'commerce.checkout.x12' or a parameterized localization key instead of the
literal 'x12' to ensure all user-facing strings are properly localized.

…-from-clerk-js

# Conflicts:
#	packages/clerk-js/src/core/resources/CommerceSubscription.ts
#	packages/clerk-js/src/ui/components/Subscriptions/SubscriptionsList.tsx
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: 1

🔭 Outside diff range comments (3)
packages/clerk-js/src/core/resources/CommercePlan.ts (1)

33-36: Avoid partially initialized instances: don’t silently accept null in fromJSON

fromJSON returns without initializing required fields when data is null. This can lead to instances with uninitialized non-optional properties and hard-to-debug runtime errors.

Apply this diff to fail fast and keep the contract strict:

-  protected fromJSON(data: CommercePlanJSON | null): this {
-    if (!data) {
-      return this;
-    }
+  protected fromJSON(data: CommercePlanJSON | null): this {
+    if (!data) {
+      throw new Error('CommercePlan.fromJSON: expected data, received null');
+    }
packages/types/src/commerce.ts (2)

1189-1226: Type rename is breaking — provide a deprecated alias for CommerceMoney

Renaming CommerceMoney to CommerceMoneyAmount will break downstream consumers of @clerk/types. Provide a backwards-compatible alias to avoid a breaking change under a “chore” PR.

Apply this addition after the CommerceMoneyAmount interface:

 export interface CommerceMoneyAmount {
   ...
 }
+
+/**
+ * @deprecated Use CommerceMoneyAmount instead. This alias will be removed in a future major release.
+ */
+export type CommerceMoney = CommerceMoneyAmount;

290-309: Remove all stale references to deprecated money and plan fields

The search uncovered numerous remaining usages of removed types and fields—these must be updated or removed to complete the Billing feature refactor.

• Type definitions

  • packages/types/src/snapshots.ts:192export type CommercePlanJSONSnapshot = CommercePlanJSON;
  • packages/types/src/commerce.ts:1225currencySymbol: string;

• Backend resource mappings

  • packages/backend/src/api/resources/CommercePlan.ts:8, 81currencySymbol property and JSON mapping

• JSON schema files

  • packages/backend/src/api/resources/JSON.ts:879annual_monthly_amount
  • packages/types/src/json.ts:357, 640–643 — snake_case and formatted fields
  • packages/types/src/api.ts:34 — formatted snake_case

• Core checkout tests

  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.spec.ts:30–31annualAmount, annualAmountFormatted
  • multiple assertions of currencySymbol in test fixtures

• Clerk-JS client code & tests

  • packages/clerk-js/src/utils/commerce.ts
  • packages/clerk-js/src/ui/components/** (SubscriptionsList, SubscriptionDetails, StatementsList, PricingTable, Plans, CheckoutForm, etc.)
  • numerous currencySymbol, amountFormatted, annual_monthly_amount_formatted usages in both implementation and tests

Please remove or rename each deprecated reference (fields, JSON keys, types, and snapshots) to align with the new CommerceMoneyAmount model.

♻️ Duplicate comments (1)
packages/types/src/commerce.ts (1)

290-309: Naming: “Fee” vs “Price/Rate” — revisit terminology for clarity

There’s prior concern that calling plan prices “fee” is confusing in product pricing contexts (fees are often additive charges). “price” or “rate” may be clearer.

If you stick with “fee”, ensure docs consistently use this term across SDK and API responses to avoid ambiguity.

🧹 Nitpick comments (15)
packages/backend/src/api/resources/CommercePlan.ts (2)

75-83: Type the helper’s return for stronger guarantees and future-proofing

Annotate formatAmountJSON’s return as CommerceMoneyAmount to lock the contract and catch drift if fields ever change.

Apply:

-  static fromJSON(data: CommercePlanJSON): CommercePlan {
-    const formatAmountJSON = (fee: CommercePlanJSON['fee']) => {
+  static fromJSON(data: CommercePlanJSON): CommercePlan {
+    const formatAmountJSON = (fee: CommercePlanJSON['fee']): CommerceMoneyAmount => {
       return {
         amount: fee.amount,
         amountFormatted: fee.amount_formatted,
         currency: fee.currency,
         currencySymbol: fee.currency_symbol,
       };
     };

4-9: Avoid duplicating shared Money type across packages (optional)

Re-defining CommerceMoneyAmount locally risks divergence from the canonical type in packages/types. If feasible (no cycle), import it as a type-only import from @clerk/types for consistency.

Example:

-import type { CommercePlanJSON } from './JSON';
-type CommerceMoneyAmount = {
-  amount: number;
-  amountFormatted: string;
-  currency: string;
-  currencySymbol: string;
-};
+import type { CommercePlanJSON } from './JSON';
+import type { CommerceMoneyAmount } from '@clerk/types';
packages/types/src/json.ts (4)

635-637: New fee fields are good; deprecate legacy amount fields to prevent ambiguity

You’ve introduced fee, annual_fee, annual_monthly_fee. The legacy fields (amount, amount_formatted, currency, currency_symbol, annual_* variants) remain below and can confuse consumers.

Add @deprecated JSDoc on the legacy fields to guide migrations:

// Outside this hunk — add JSDoc on lines 638-646 and 640-643
/**
 * @deprecated Use `fee.amountFormatted` instead.
 */
amount_formatted: string;
/**
 * @deprecated Use `fee.currency_symbol` instead.
 */
currency_symbol: string;
/**
 * @deprecated Use `fee.currency` instead.
 */
currency: string;

Optionally mark numeric amount/annual fields as deprecated as well with pointers to the new nested objects.


773-776: Document when amount and credit.amount may be absent

amount? suggests free-tier items or special cases. Add a brief JSDoc note to clarify when it’s undefined to help downstream handling.

Apply:

 export interface CommerceSubscriptionItemJSON extends ClerkResourceJSON {
@@
-  amount?: CommerceMoneyAmountJSON;
+  /**
+   * Present for paid items; absent for free-tier or zero-charge cycles.
+   */
+  amount?: CommerceMoneyAmountJSON;
   credit?: {
-    amount: CommerceMoneyAmountJSON;
+    /**
+     * Remaining credit applicable to the active cycle.
+     */
+    amount: CommerceMoneyAmountJSON;
   };

830-835: Add JSDoc for the new CommerceMoneyAmountJSON

Mirror the runtime type’s experimental notice and briefly describe each field for SDK users.

Apply:

-export interface CommerceMoneyAmountJSON {
+/**
+ * Monetary amount with currency metadata.
+ * @experimental Billing API is in public beta; shape may change.
+ */
+export interface CommerceMoneyAmountJSON {
   amount: number;
   amount_formatted: string;
   currency: string;
   currency_symbol: string;
 }

846-851: Clarify guarantees for credit and consider past_due coverage

  • credit is modeled as required here and in CommerceStatementTotalsJSON. If some responses omit it, the typing should reflect credit?. Otherwise, enforce presence in the builders.
  • Some code paths (utils) derive a past_due field when present. If the API guarantees it, consider adding past_due?: CommerceMoneyAmountJSON to the relevant totals JSON type for accuracy.

Would you like me to prepare changes to:

  • Make credit optional (JSON and runtime), or
  • Enforce credit unconditionally in parsers and update API docs to reflect it’s always present?
packages/clerk-js/src/core/resources/CommerceSubscription.ts (2)

71-75: Resolve TODO and document amount? semantics

The optional amount likely corresponds to free plans or zero-charge periods. Replace the TODO with a concise doc to avoid confusion.

Apply:

-  //TODO(@COMMERCE): Why can this be undefined ?
-  amount?: CommerceMoneyAmount;
+  /**
+   * Present for paid items; undefined for free-tier items or zero-charge cycles.
+   */
+  amount?: CommerceMoneyAmount;

109-121: Add explicit return type to public API method

Per guidelines, public APIs should have explicit return types. Add Promise to cancel.

Apply:

-  public async cancel(params: CancelSubscriptionParams) {
+  public async cancel(params: CancelSubscriptionParams): Promise<DeletedObject> {
     const { orgId } = params;
     const json = (
       await BaseResource._fetch({
         path: orgId
           ? `/organizations/${orgId}/commerce/subscription_items/${this.id}`
           : `/me/commerce/subscription_items/${this.id}`,
         method: 'DELETE',
       })
     )?.response as unknown as DeletedObjectJSON;

     return new DeletedObject(json);
   }
packages/backend/src/api/resources/JSON.ts (3)

803-808: Introduce brief JSDoc for CommerceMoneyAmountJSON

Add a one-liner description to improve discoverability in the backend JSON shapes.

Apply:

-interface CommerceMoneyAmountJSON {
+/**
+ * Monetary amount with formatted string and currency metadata.
+ */
+interface CommerceMoneyAmountJSON {
   amount: number;
   amount_formatted: string;
   currency: string;
   currency_symbol: string;
 }

846-865: Ensure consistency of nested plan shape in SubscriptionItem

CommerceSubscriptionItemJSON.plan still exposes legacy numeric fields (amount, annual_monthly_amount, currency) while CommercePlanJSON has switched to fee objects. If the API will standardize on fee objects, consider migrating this nested plan shape as well to avoid dual models in consumers.

Would you like a follow-up PR plan to migrate the nested plan object to use the fee fields?


856-864: Clarify timestamp units for period_*, next_payment_date, etc.

Add a note whether these are Unix seconds or milliseconds to avoid off-by-1000 errors on consumers.

Proposed doc additions:

/**
 * Start of the billing period as Unix epoch (seconds).
 */
period_start: number;
/**
 * End of the billing period as Unix epoch (seconds). Absent for free plans.
 */
period_end?: number;
/**
 * Next payment date as Unix epoch (seconds).
 */
next_payment_date: number;
packages/clerk-js/src/core/resources/CommercePlan.ts (1)

15-17: Plan monetary fields migrated to CommerceMoneyAmount

The fee, annualFee, and annualMonthlyFee fields align with the new structured money model. Consider documenting semantics in code comments (e.g., annualMonthlyFee = monthly unit price when billed annually).

Would you like me to add concise JSDoc comments mirroring the public types’ intent?

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

290-309: Fees API surface added on plans — confirm requiredness and clarify semantics

  • All three fields (fee, annualFee, annualMonthlyFee) are required. Confirm the backend always returns them for every plan (including free plans), otherwise make them optional or provide defaults.
  • Consider clarifying that annualMonthlyFee represents the monthly unit price when billed annually (often annualFee/12), to prevent misuse.

Proposed doc additions for clarity:

   /**
    * @experimental ...
    */
-  fee: CommerceMoneyAmount;
+  /**
+   * Base monthly fee, billed monthly.
+   */
+  fee: CommerceMoneyAmount;
   /**
    * @experimental ...
    */
-  annualFee: CommerceMoneyAmount;
+  /**
+   * Total annual fee when billed annually.
+   */
+  annualFee: CommerceMoneyAmount;
   /**
    * @experimental ...
    */
-  annualMonthlyFee: CommerceMoneyAmount;
+  /**
+   * Effective monthly fee when billed annually (typically annualFee / 12).
+   */
+  annualMonthlyFee: CommerceMoneyAmount;

1189-1226: Add JSON counterpart type to money amount if not already exported

Given commerceMoneyAmountFromJSON exists, consider exporting CommerceMoneyAmountJSON here to give SDK consumers a canonical JSON shape type.

I can scaffold the JSON type and helper signatures if helpful.


290-309: Add tests for the new plan fee surface

No tests are shown in this PR. Please add unit tests covering:

  • Parsing fee/annualFee/annualMonthlyFee from JSON (happy path and missing-field errors)
  • Formatting/consumption in UI helpers that previously used flat fields

I can provide test scaffolding for both runtime resource parsing and type-level checks.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0bb6872 and 6a0d739.

📒 Files selected for processing (9)
  • packages/backend/src/api/resources/CommercePlan.ts (2 hunks)
  • packages/backend/src/api/resources/JSON.ts (4 hunks)
  • packages/clerk-js/src/core/resources/CommercePayment.ts (3 hunks)
  • packages/clerk-js/src/core/resources/CommercePlan.ts (2 hunks)
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts (6 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (4 hunks)
  • packages/clerk-js/src/utils/commerce.ts (2 hunks)
  • packages/types/src/commerce.ts (15 hunks)
  • packages/types/src/json.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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/backend/src/api/resources/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.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/backend/src/api/resources/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.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/backend/src/api/resources/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.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/backend/src/api/resources/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
**/*

⚙️ CodeRabbit Configuration File

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/types/src/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
🧬 Code Graph Analysis (5)
packages/backend/src/api/resources/CommercePlan.ts (1)
packages/types/src/commerce.ts (1)
  • CommerceMoneyAmount (1189-1226)
packages/clerk-js/src/utils/commerce.ts (2)
packages/types/src/json.ts (3)
  • CommerceMoneyAmountJSON (830-835)
  • CommerceStatementTotalsJSON (862-862)
  • CommerceCheckoutTotalsJSON (845-851)
packages/types/src/commerce.ts (3)
  • CommerceMoneyAmount (1189-1226)
  • CommerceCheckoutTotals (1236-1291)
  • CommerceStatementTotals (1302-1302)
packages/backend/src/api/resources/JSON.ts (1)
packages/types/src/json.ts (1)
  • CommerceMoneyAmountJSON (830-835)
packages/clerk-js/src/core/resources/CommercePlan.ts (2)
packages/types/src/commerce.ts (1)
  • CommerceMoneyAmount (1189-1226)
packages/clerk-js/src/utils/commerce.ts (1)
  • commerceMoneyAmountFromJSON (10-17)
packages/clerk-js/src/core/resources/CommerceSubscription.ts (2)
packages/types/src/commerce.ts (1)
  • CommerceMoneyAmount (1189-1226)
packages/clerk-js/src/utils/commerce.ts (1)
  • commerceMoneyAmountFromJSON (10-17)
🔇 Additional comments (16)
packages/backend/src/api/resources/CommercePlan.ts (1)

56-64: Migration to fee/annualFee/annualMonthlyFee looks correct

Fields are readonly and typed consistently with the MoneyAmount shape. The constructor wiring matches JSON keys and the class API is clear.

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

751-751: Good: amount moved to structured CommerceMoneyAmountJSON

This aligns payments with the MoneyAmount model and carries currency metadata.


807-809: Good: next_payment.amount now carries currency metadata

Matches the broader MoneyAmount migration and simplifies client rendering.

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

25-28: LGTM: nextPayment typed with MoneyAmount and parsed correctly

The JSON-to-object mapping is correct and date conversions are consistent.

packages/clerk-js/src/utils/commerce.ts (2)

10-17: LGTM: MoneyAmount parser is correct and consistent

Mapping from JSON snake_case to runtime camelCase looks good.


19-21: Nice: precise type guard for past_due

Simple and safe runtime check without ts-ignore.

packages/backend/src/api/resources/JSON.ts (2)

810-814: Totals migration looks correct

subtotal, tax_total, grand_total now use CommerceMoneyAmountJSON consistently.


839-843: Plan money fields updated — good

fee, annual_fee, annual_monthly_fee types align with the new money shape.

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

2-2: Type-only import for money amount is correct

Good use of a type-only import for CommerceMoneyAmount to avoid bundling runtime artifacts.


8-8: Using centralized JSON → money mapper is the right call

Importing commerceMoneyAmountFromJSON promotes consistency across resources.


40-42: No runtime guards needed for required fee fields

The CommercePlanJSON interface (in packages/types/src/json.ts) declares fee, annual_fee and annual_monthly_fee as non-nullable CommerceMoneyAmountJSON properties. Since these fields are guaranteed by the JSON type—and commerceMoneyAmountFromJSON safely maps each required property—no additional defensive checks are necessary here. If the backend ever violates this contract, that should be caught at build time by TypeScript or by API-level validation, rather than in each resource’s fromJSON method.

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

4-4: Snapshot import cleanup looks correct

Keeping only CommerceFeatureJSONSnapshot after removing the plan snapshot aligns with the refactor.


706-706: Payment.amount migrated to CommerceMoneyAmount

This aligns with the new money model and improves consistency across resources.


1022-1041: Subscription item amount/credit migrated to CommerceMoneyAmount

Looks good. Optional amount and nested credit.amount are consistent with other money usages.


1115-1115: Subscription.nextPayment.amount migrated to CommerceMoneyAmount

Consistent with the rest of the money refactor.


1245-1291: Totals migrated to CommerceMoneyAmount — verify presence or mark optional where applicable

Ensure all fields (subtotal, grandTotal, taxTotal, totalDueNow, credit, pastDue) are always present in API responses. In many systems, credit and pastDue can be zero or omitted; if omitted, these should be optional to reflect reality and avoid forcing placeholders.

If they can be absent, change to optional:

-  credit: CommerceMoneyAmount;
+  credit?: CommerceMoneyAmount;
-  pastDue: CommerceMoneyAmount;
+  pastDue?: CommerceMoneyAmount;

Comment on lines +23 to 45
export const commerceTotalsFromJSON = <T extends CommerceStatementTotalsJSON | CommerceCheckoutTotalsJSON>(
data: T,
): T extends { total_due_now: CommerceMoneyAmountJSON } ? CommerceCheckoutTotals : CommerceStatementTotals => {
const totals: Partial<CommerceCheckoutTotals & CommerceStatementTotals> = {
grandTotal: commerceMoneyAmountFromJSON(data.grand_total),
subtotal: commerceMoneyAmountFromJSON(data.subtotal),
taxTotal: commerceMoneyAmountFromJSON(data.tax_total),
};

if ('total_due_now' in data) {
// @ts-ignore
totals['totalDueNow'] = commerceMoneyFromJSON(data.total_due_now);
totals.totalDueNow = commerceMoneyAmountFromJSON(data.total_due_now);
}
if ('credit' in data) {
// @ts-ignore
totals['credit'] = commerceMoneyFromJSON(data.credit);
totals.credit = commerceMoneyAmountFromJSON(data.credit);
}
if ('past_due' in data) {
// @ts-ignore
totals['pastDue'] = commerceMoneyFromJSON(data.past_due);
if (hasPastDue(data)) {
totals.pastDue = commerceMoneyAmountFromJSON(data.past_due);
}

return totals as T extends { total_due_now: CommerceMoneyJSON } ? CommerceCheckoutTotals : CommerceStatementTotals;
return totals as T extends { total_due_now: CommerceMoneyAmountJSON }
? CommerceCheckoutTotals
: CommerceStatementTotals;
};
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

⚠️ Potential issue

Potential contract mismatch: credit and pastDue may be missing while types require them

The function casts to CommerceCheckoutTotals/CommerceStatementTotals, where credit and pastDue are modeled as required (see packages/types/src/commerce.ts). However:

  • credit is only set if present in JSON.
  • pastDue is only set when hasPastDue(data) is true.
    This can return objects missing required properties, hidden by the final cast.

Two safe options:

  • If API guarantees presence, set unconditionally and fail early if missing.
  • If not guaranteed, make them optional in the runtime types.

If presence is guaranteed, apply:

 export const commerceTotalsFromJSON = <T extends CommerceStatementTotalsJSON | CommerceCheckoutTotalsJSON>(
   data: T,
 ): T extends { total_due_now: CommerceMoneyAmountJSON } ? CommerceCheckoutTotals : CommerceStatementTotals => {
   const totals: Partial<CommerceCheckoutTotals & CommerceStatementTotals> = {
     grandTotal: commerceMoneyAmountFromJSON(data.grand_total),
     subtotal: commerceMoneyAmountFromJSON(data.subtotal),
     taxTotal: commerceMoneyAmountFromJSON(data.tax_total),
   };

-  if ('total_due_now' in data) {
+  if ('total_due_now' in data) {
     totals.totalDueNow = commerceMoneyAmountFromJSON(data.total_due_now);
   }
-  if ('credit' in data) {
-    totals.credit = commerceMoneyAmountFromJSON(data.credit);
-  }
+  // enforce credit presence
+  totals.credit = commerceMoneyAmountFromJSON((data as CommerceCheckoutTotalsJSON).credit);
-  if (hasPastDue(data)) {
-    totals.pastDue = commerceMoneyAmountFromJSON(data.past_due);
-  }
+  // enforce past_due presence where applicable; if not guaranteed, discuss making it optional in types
+  if (hasPastDue(data)) {
+    totals.pastDue = commerceMoneyAmountFromJSON((data as any).past_due);
+  }
 
   return totals as T extends { total_due_now: CommerceMoneyAmountJSON }
     ? CommerceCheckoutTotals
     : CommerceStatementTotals;
 };

Alternatively, if these fields are not always present, I can prepare a types change to mark them optional and align parsers accordingly. Preference?

📝 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 const commerceTotalsFromJSON = <T extends CommerceStatementTotalsJSON | CommerceCheckoutTotalsJSON>(
data: T,
): T extends { total_due_now: CommerceMoneyAmountJSON } ? CommerceCheckoutTotals : CommerceStatementTotals => {
const totals: Partial<CommerceCheckoutTotals & CommerceStatementTotals> = {
grandTotal: commerceMoneyAmountFromJSON(data.grand_total),
subtotal: commerceMoneyAmountFromJSON(data.subtotal),
taxTotal: commerceMoneyAmountFromJSON(data.tax_total),
};
if ('total_due_now' in data) {
// @ts-ignore
totals['totalDueNow'] = commerceMoneyFromJSON(data.total_due_now);
totals.totalDueNow = commerceMoneyAmountFromJSON(data.total_due_now);
}
if ('credit' in data) {
// @ts-ignore
totals['credit'] = commerceMoneyFromJSON(data.credit);
totals.credit = commerceMoneyAmountFromJSON(data.credit);
}
if ('past_due' in data) {
// @ts-ignore
totals['pastDue'] = commerceMoneyFromJSON(data.past_due);
if (hasPastDue(data)) {
totals.pastDue = commerceMoneyAmountFromJSON(data.past_due);
}
return totals as T extends { total_due_now: CommerceMoneyJSON } ? CommerceCheckoutTotals : CommerceStatementTotals;
return totals as T extends { total_due_now: CommerceMoneyAmountJSON }
? CommerceCheckoutTotals
: CommerceStatementTotals;
};
export const commerceTotalsFromJSON = <T extends CommerceStatementTotalsJSON | CommerceCheckoutTotalsJSON>(
data: T,
): T extends { total_due_now: CommerceMoneyAmountJSON } ? CommerceCheckoutTotals : CommerceStatementTotals => {
const totals: Partial<CommerceCheckoutTotals & CommerceStatementTotals> = {
grandTotal: commerceMoneyAmountFromJSON(data.grand_total),
subtotal: commerceMoneyAmountFromJSON(data.subtotal),
taxTotal: commerceMoneyAmountFromJSON(data.tax_total),
};
if ('total_due_now' in data) {
totals.totalDueNow = commerceMoneyAmountFromJSON(data.total_due_now);
}
// enforce credit presence
totals.credit = commerceMoneyAmountFromJSON(
(data as CommerceCheckoutTotalsJSON).credit,
);
// enforce past_due presence where applicable; if not guaranteed, discuss making it optional in types
if (hasPastDue(data)) {
totals.pastDue = commerceMoneyAmountFromJSON(
(data as any).past_due,
);
}
return totals as T extends { total_due_now: CommerceMoneyAmountJSON }
? CommerceCheckoutTotals
: CommerceStatementTotals;
};
🤖 Prompt for AI Agents
In packages/clerk-js/src/utils/commerce.ts around lines 23-45, the function
builds a totals object but only assigns credit and pastDue conditionally while
the return type asserts CommerceCheckoutTotals/CommerceStatementTotals where
those fields are required; fix by either (A) enforcing the type contract at
runtime: check for the presence of data.credit and hasPastDue(data) and throw a
clear error if missing so you can safely set totals.credit and totals.pastDue
unconditionally before returning, or (B) change the types to make credit and
pastDue optional and update all callers/parsers to accept those fields being
undefined; pick one approach and implement the corresponding runtime checks or
type updates consistently across the codebase.

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

🔭 Outside diff range comments (2)
packages/clerk-js/src/core/resources/CommercePlan.ts (1)

33-37: Add JSDoc to fromJSON in CommercePlan.ts

The description and avatarUrl properties on CommercePlanJSON are defined as non-nullable strings, so no runtime null‐coercion or optional typing is needed. However, per public-resource guidelines, we should still add JSDoc above the initializer.

• File: packages/clerk-js/src/core/resources/CommercePlan.ts
• Location: just above protected fromJSON(data: CommercePlanJSON | null): this {

Suggested diff:

+/**
+ * Populate this CommercePlan resource from the API response.
+ * @experimental Billing API is in public beta and subject to change;
+ * pin SDK and clerk-js to a fixed version to avoid breaking changes.
+ */
 protected fromJSON(data: CommercePlanJSON | null): this {
   if (!data) {
     return this;
   }
packages/types/src/commerce.ts (1)

1245-1291: pastDue should be optional or always provided by JSON

Resource types require pastDue, but JSON types (CommerceCheckoutTotalsJSON/CommerceStatementTotalsJSON) don’t define past_due. The parser currently sets pastDue only conditionally, which can produce invalid objects at runtime.

Choose one:

  • Make pastDue optional in both totals types; or
  • Update JSON types to include past_due and set it unconditionally in the parser.

If we go with optional in resources:

 export interface CommerceCheckoutTotals {
@@
-  pastDue: CommerceMoneyAmount;
+  pastDue?: CommerceMoneyAmount;
 }
@@
-export interface CommerceStatementTotals extends Omit<CommerceCheckoutTotals, 'totalDueNow'> {}
+export interface CommerceStatementTotals extends Omit<CommerceCheckoutTotals, 'totalDueNow'> {}

If we go with required in JSON, please update packages/types/src/json.ts accordingly and adjust the parser to always set pastDue.

♻️ Duplicate comments (1)
packages/clerk-js/src/utils/commerce.ts (1)

26-31: Nice cleanup replacing ts-ignore mutation with a typed Partial build

This addresses the earlier comment to remove the suppressions and build a properly typed object before a single final cast.

🧹 Nitpick comments (8)
packages/types/src/json.ts (1)

830-835: Introduce CommerceMoneyAmountJSON – add JSDoc since this is a public type

Public JSON interfaces benefit from minimal field-level docs.

Apply this diff to add a short JSDoc:

-export interface CommerceMoneyAmountJSON {
+/**
+ * Monetary amount returned by the API, including formatted representation and currency metadata.
+ */
+export interface CommerceMoneyAmountJSON {
   amount: number;
   amount_formatted: string;
   currency: string;
   currency_symbol: string;
 }
packages/backend/src/api/resources/CommercePlan.ts (1)

76-83: Helper mapping from JSON → MoneyAmount is correct; consider reusing a shared helper

Mapping is straightforward. If this pattern recurs, consider a small shared backend util (e.g., commerceMoneyAmountFromJSON) to avoid duplication.

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

72-75: SubscriptionItem.amount and credit.amount migrated – clarify the TODO about undefined amount

The optional amount is expected (e.g., free plan). Replace the TODO with a clarifying note to reduce churn for future readers.

You can update the class field doc (outside this hunk) as:

/**
 * The billed amount for this subscription item. Undefined for free plans or when no charge is applicable.
 */
amount?: CommerceMoneyAmount;
packages/clerk-js/src/utils/commerce.ts (2)

10-17: Add JSDoc for public parsing helper

This is a public utility used across packages. Please add a brief JSDoc with parameter/return types and stability notes to align with guidelines for public APIs.

+/**
+ * Maps a CommerceMoneyAmountJSON into a CommerceMoneyAmount.
+ * @experimental Billing API subject to change; pin versions to avoid breaking changes.
+ */
 export const commerceMoneyAmountFromJSON = (data: CommerceMoneyAmountJSON): CommerceMoneyAmount => {
   return {
     amount: data.amount,
     amountFormatted: data.amount_formatted,
     currency: data.currency,
     currencySymbol: data.currency_symbol,
   };
 };

23-45: Prefer overloads for better inference and set credit unconditionally

  • Overloads improve call-site inference vs. a conditional return on a generic.
  • credit appears in both JSON shapes; set it unconditionally and avoid an unnecessary in check.
-export const commerceTotalsFromJSON = <T extends CommerceStatementTotalsJSON | CommerceCheckoutTotalsJSON>(
-  data: T,
-): T extends { total_due_now: CommerceMoneyAmountJSON } ? CommerceCheckoutTotals : CommerceStatementTotals => {
+export function commerceTotalsFromJSON(data: CommerceCheckoutTotalsJSON): CommerceCheckoutTotals;
+export function commerceTotalsFromJSON(data: CommerceStatementTotalsJSON): CommerceStatementTotals;
+export function commerceTotalsFromJSON<T extends CommerceStatementTotalsJSON | CommerceCheckoutTotalsJSON>(
+  data: T,
+):
+  | (T extends { total_due_now: CommerceMoneyAmountJSON } ? CommerceCheckoutTotals : never)
+  | (T extends { total_due_now: CommerceMoneyAmountJSON } ? never : CommerceStatementTotals) {
   const totals: Partial<CommerceCheckoutTotals & CommerceStatementTotals> = {
     grandTotal: commerceMoneyAmountFromJSON(data.grand_total),
     subtotal: commerceMoneyAmountFromJSON(data.subtotal),
     taxTotal: commerceMoneyAmountFromJSON(data.tax_total),
   };
 
   if ('total_due_now' in data) {
     totals.totalDueNow = commerceMoneyAmountFromJSON(data.total_due_now);
   }
-  if ('credit' in data) {
-    totals.credit = commerceMoneyAmountFromJSON(data.credit);
-  }
+  totals.credit = commerceMoneyAmountFromJSON(data.credit);
   if (hasPastDue(data)) {
     totals.pastDue = commerceMoneyAmountFromJSON(data.past_due);
   }
 
   return totals as T extends { total_due_now: CommerceMoneyAmountJSON }
     ? CommerceCheckoutTotals
     : CommerceStatementTotals;
 }

If we proceed with Option A in the previous comment (making pastDue optional), also consider defaulting to undefined rather than conditionally adding the key to keep shapes consistent.

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

15-17: Please add/update tests for fee fields and formatting

Given the public API change, add tests covering:

  • CommercePlan.fromJSON populating fee, annualFee, annualMonthlyFee correctly (amount, amountFormatted, currency, currencySymbol).
  • Backward-compat edge cases if any legacy fields might still appear in fixtures.

I can help scaffold these tests if useful.

packages/types/src/commerce.ts (2)

1189-1226: Make MoneyAmount properties readonly

MoneyAmount is a value object; mark fields readonly to prevent accidental mutation and to better communicate immutability.

-export interface CommerceMoneyAmount {
+export interface CommerceMoneyAmount {
   /**
    * @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 the SDK version and the clerk-js version to a specific version to avoid breaking changes.
    * @example
    * ```tsx
    * <ClerkProvider clerkJsVersion="x.x.x" />
    * ```
    */
-  amount: number;
+  readonly amount: number;
   /**
    * @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 the SDK version and the clerk-js version to a specific version to avoid breaking changes.
    * @example
    * ```tsx
    * <ClerkProvider clerkJsVersion="x.x.x" />
    * ```
    */
-  amountFormatted: string;
+  readonly amountFormatted: string;
   /**
    * @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 the SDK version and the clerk-js version to a specific version to avoid breaking changes.
    * @example
    * ```tsx
    * <ClerkProvider clerkJsVersion="x.x.x" />
    * ```
    */
-  currency: string;
+  readonly currency: string;
   /**
    * @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 the SDK version and the clerk-js version to a specific version to avoid breaking changes.
    * @example
    * ```tsx
    * <ClerkProvider clerkJsVersion="x.x.x" />
    * ```
    */
-  currencySymbol: string;
+  readonly currencySymbol: string;
 }

271-395: Tests are required for public API shape changes

Please add/update tests to cover:

  • Plan resource shape (fee/annualFee/annualMonthlyFee).
  • Totals objects including credit and pastDue semantics.
  • Rendering/formatting expectations if UI depends on amountFormatted/currencySymbol.

I can help draft these tests if you’d like.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0bb6872 and 6a0d739.

📒 Files selected for processing (9)
  • packages/backend/src/api/resources/CommercePlan.ts (2 hunks)
  • packages/backend/src/api/resources/JSON.ts (4 hunks)
  • packages/clerk-js/src/core/resources/CommercePayment.ts (3 hunks)
  • packages/clerk-js/src/core/resources/CommercePlan.ts (2 hunks)
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts (6 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (4 hunks)
  • packages/clerk-js/src/utils/commerce.ts (2 hunks)
  • packages/types/src/commerce.ts (15 hunks)
  • packages/types/src/json.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/json.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/commerce.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/json.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/commerce.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/json.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/commerce.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/json.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/commerce.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.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/core/resources/CommerceSubscription.ts
  • packages/types/src/json.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/commerce.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/json.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/commerce.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
**/*

⚙️ CodeRabbit Configuration File

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/json.ts
  • packages/backend/src/api/resources/JSON.ts
  • packages/clerk-js/src/core/resources/CommercePayment.ts
  • packages/types/src/commerce.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/clerk-js/src/utils/commerce.ts
  • packages/clerk-js/src/core/resources/CommercePlan.ts
🧬 Code Graph Analysis (6)
packages/clerk-js/src/core/resources/CommerceSubscription.ts (2)
packages/types/src/commerce.ts (1)
  • CommerceMoneyAmount (1189-1226)
packages/clerk-js/src/utils/commerce.ts (1)
  • commerceMoneyAmountFromJSON (10-17)
packages/backend/src/api/resources/JSON.ts (1)
packages/types/src/json.ts (1)
  • CommerceMoneyAmountJSON (830-835)
packages/clerk-js/src/core/resources/CommercePayment.ts (2)
packages/types/src/commerce.ts (2)
  • CommercePaymentResource (696-780)
  • CommerceMoneyAmount (1189-1226)
packages/clerk-js/src/utils/commerce.ts (1)
  • commerceMoneyAmountFromJSON (10-17)
packages/backend/src/api/resources/CommercePlan.ts (1)
packages/types/src/commerce.ts (1)
  • CommerceMoneyAmount (1189-1226)
packages/clerk-js/src/utils/commerce.ts (2)
packages/types/src/json.ts (3)
  • CommerceMoneyAmountJSON (830-835)
  • CommerceStatementTotalsJSON (862-862)
  • CommerceCheckoutTotalsJSON (845-851)
packages/types/src/commerce.ts (3)
  • CommerceMoneyAmount (1189-1226)
  • CommerceCheckoutTotals (1236-1291)
  • CommerceStatementTotals (1302-1302)
packages/clerk-js/src/core/resources/CommercePlan.ts (3)
packages/backend/src/api/resources/CommercePlan.ts (1)
  • CommercePlan (15-101)
packages/types/src/commerce.ts (2)
  • CommercePlanResource (271-395)
  • CommerceMoneyAmount (1189-1226)
packages/clerk-js/src/utils/commerce.ts (1)
  • commerceMoneyAmountFromJSON (10-17)
🔇 Additional comments (27)
packages/backend/src/api/resources/JSON.ts (5)

839-842: Plans now use MoneyAmount fields; nested plan snapshot in SubscriptionItem appears inconsistent

While CommercePlanJSON exposes fee, annual_fee, and annual_monthly_fee, the nested plan under CommerceSubscriptionItemJSON (Lines 866-881) still lists flat fields (amount, currency, annual_monthly_amount, etc.). If the API migrated fully, prefer reusing CommercePlanJSON to avoid duplication and drift.

If the nested plan is meant to be a snapshot with legacy fields, please confirm and consider documenting it. Otherwise, update to:

plan: CommercePlanJSON;

If you want, I can prepare the refactor touches across backend/types accordingly.


850-851: credit.amount migrated to MoneyAmount – LGTM

This aligns credit with the new monetary struct. No further issues spotted.


803-809: Add JSDoc to CommerceMoneyAmountJSON interface

No remaining references to legacy money JSON types in packages/backend (searched for CommerceFeeJSON, CommerceMoneyJSON, commerceMoneyFromJSON). Applying the proposed doc to clarify the shape:

- interface CommerceMoneyAmountJSON {
+ /**
+  * Money amount as returned by the backend, including formatted and currency metadata.
+  */
+ interface CommerceMoneyAmountJSON {
    amount: number;
    amount_formatted: string;
    currency: string;
    currency_symbol: string;
  }

811-814: No arithmetic on formatted values—change is safe
Search across packages/backend found only:

  • The type declaration in JSON.ts (amount_formatted: string)
  • A simple mapping in CommercePlan.ts (amountFormatted: fee.amount_formatted)

No consumers perform math on amount_formatted. All downstream code uses the numeric amount field where needed.


864-865: SubscriptionItem.amount migration verified

I searched the codebase for any direct .amount usages on subscription items (excluding formatted fields) and found none. All UI renderers and serializers continue to use amount_formatted (a string) or the new MoneyAmount JSON shape.

No further changes are required.

packages/clerk-js/src/core/resources/CommercePayment.ts (4)

2-2: Switch to CommerceMoneyAmount type import – LGTM

Type import is correct and follows type-only import convention.


11-11: Use commerceMoneyAmountFromJSON – LGTM

Utility switch is consistent with the MoneyAmount migration.


41-41: fromJSON mapping updated to MoneyAmount – LGTM

Mapping via commerceMoneyAmountFromJSON is correct and mirrors type expectations.


17-17: amount typed as CommerceMoneyAmount – verification complete

  • Ran ripgrep across packages/clerk-js and confirmed there are no raw CommerceMoney or commerceMoneyFromJSON references.
  • All remaining occurrences use the new CommerceMoneyAmount type and commerceMoneyAmountFromJSON utility.
  • Downstream UI can safely access amount.amount and amount.amountFormatted as intended.
packages/types/src/json.ts (4)

751-751: CommercePaymentJSON.amount → CommerceMoneyAmountJSON – LGTM

The JSON surface now reflects a structured money amount. No issues.


773-776: SubscriptionItem amounts migrated to MoneyAmount – LGTM; optionality is appropriate

amount is optional (free plan/snapshot cases) and credit.amount is structured. Looks consistent.


807-809: next_payment.amount migrated to MoneyAmount – LGTM

Migration aligns with the rest of the monetary surface.


846-851: No arithmetic on formatted money strings detected
I searched the codebase for any + - * / operations on .amountFormatted or .amount_formatted and found none. All calculations appear to use the numeric .amount field as intended—no changes required here.

packages/backend/src/api/resources/CommercePlan.ts (3)

4-9: Local CommerceMoneyAmount alias – LGTM

Local alias matches the cross-package shape. Keeping it local avoids coupling backend to frontend types.


56-65: fee/annualFee/annualMonthlyFee fields added – LGTM

Public API aligns with the new MoneyAmount model.


94-99: Mapping fee fields via helper – LGTM

Consistent use and clear readability.

packages/clerk-js/src/core/resources/CommerceSubscription.ts (5)

3-3: Import CommerceMoneyAmount – LGTM

Type import is correct and type-only.


15-15: Use commerceMoneyAmountFromJSON – LGTM

Consistent with other resources.


26-27: nextPayment.amount typed as CommerceMoneyAmount – LGTM

Shape change is reflected in both type and parser.


50-51: Parse nextPayment.amount using MoneyAmount – LGTM

Mapping is correct.


101-104: Mapping amount/credit amounts via MoneyAmount – LGTM

I ran a repository-wide search for any remaining uses of commerceMoneyFromJSON or CommerceMoney in packages/clerk-js and found none. Everything is up-to-date and no further changes are required.

packages/clerk-js/src/utils/commerce.ts (1)

4-5: Imports align with the MoneyAmount rename

The import switch to the MoneyAmount types is consistent with the PR’s intent.

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

8-9: Switching to commerceMoneyAmountFromJSON is correct

Importing and using the new helper is aligned with the MoneyAmount migration.


15-17: Plan price fields migrated to fee-based MoneyAmount objects

The new fields and types align with the types package and backend JSON. Good consolidation.


40-42: Mapping fee fields via helper keeps a single source of truth

Centralized mapping reduces duplication and keeps JSON-to-model conversion consistent.

packages/types/src/commerce.ts (2)

290-308: Plan resource: fee-based fields look consistent

Switching to fee, annualFee, and annualMonthlyFee as CommerceMoneyAmount is consistent with the rest of the refactor.


706-706: MoneyAmount migration across resources looks correct

  • Payment.amount (Line 706), SubscriptionItem.amount (Line 1022), SubscriptionItem.credit.amount (Line 1040), and Subscription.nextPayment.amount (Line 1115) now use CommerceMoneyAmount, consistent with the MoneyAmount model.

Also applies to: 1022-1022, 1040-1040, 1115-1115

Comment on lines +19 to +21
const hasPastDue = (data: unknown): data is { past_due: CommerceMoneyAmountJSON } => {
return typeof data === 'object' && data !== null && 'past_due' in data;
};
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Past-due presence/type mismatch: JSON vs resource type

The guard only checks for property existence. More importantly, types show no past_due in CommerceCheckoutTotalsJSON/CommerceStatementTotalsJSON, while CommerceCheckoutTotals/CommerceStatementTotals require pastDue. This can yield runtime objects missing required fields.

  • Option A (recommended): Make pastDue optional in both CommerceCheckoutTotals and CommerceStatementTotals.
  • Option B: Ensure backend JSON types include past_due (optional or required) and populate it unconditionally.

Run this script to check JSON type declarations and usages for past_due:


🏁 Script executed:

#!/bin/bash
# Verify whether past_due exists in JSON types and where it's used.
rg -n -A3 -B3 $'interface\\s+CommerceCheckoutTotalsJSON\\b|interface\\s+CommerceStatementTotalsJSON\\b|past_due' packages/types/src/json.ts

# Also check for consumers expecting pastDue as required
rg -n -A2 -B2 '\bpastDue\b' packages

Length of output: 20864


JSON interfaces missing past_due leading to mismatched pastDue in resources

Our type guard checks for data.past_due at runtime, but both CommerceCheckoutTotalsJSON and CommerceStatementTotalsJSON never declare a past_due field. Meanwhile the resource types in packages/types/src/commerce.ts require pastDue: CommerceMoneyAmount. This mismatch means consumers could see invalid or missing data at runtime.

Fix Required:

• In packages/types/src/json.ts

 export interface CommerceCheckoutTotalsJSON {
   grand_total: CommerceMoneyAmountJSON;
   subtotal: CommerceMoneyAmountJSON;
   tax_total: CommerceMoneyAmountJSON;
+  /** Optional past-due amount when returned by the API */
+  past_due?: CommerceMoneyAmountJSON;
 }

 // eslint-disable-next-line @typescript-eslint/no-empty-object-type
-export interface CommerceStatementTotalsJSON extends Omit<CommerceCheckoutTotalsJSON, 'total_due_now'> {}
+export interface CommerceStatementTotalsJSON extends Omit<CommerceCheckoutTotalsJSON, 'total_due_now'> {
+  past_due?: CommerceMoneyAmountJSON;
}

After adding past_due (mark as optional or required per your API contract), rerun your build/tests to ensure the guard and mapping logic in clerk-js/src/utils/commerce.ts align correctly with the JSON types.

📝 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 hasPastDue = (data: unknown): data is { past_due: CommerceMoneyAmountJSON } => {
return typeof data === 'object' && data !== null && 'past_due' in data;
};
// In packages/types/src/json.ts
export interface CommerceCheckoutTotalsJSON {
grand_total: CommerceMoneyAmountJSON;
subtotal: CommerceMoneyAmountJSON;
tax_total: CommerceMoneyAmountJSON;
/** Optional past-due amount when returned by the API */
past_due?: CommerceMoneyAmountJSON;
}
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface CommerceStatementTotalsJSON extends Omit<CommerceCheckoutTotalsJSON, 'total_due_now'> {
/** Optional past-due amount when returned by the API */
past_due?: CommerceMoneyAmountJSON;
}
🤖 Prompt for AI Agents
In packages/clerk-js/src/utils/commerce.ts around lines 19–21, the type guard
checks for a runtime field past_due but the JSON interfaces do not declare it;
update packages/types/src/json.ts to add past_due to the relevant interfaces
(CommerceCheckoutTotalsJSON and CommerceStatementTotalsJSON), marking it
optional or required according to the API contract, then update any mapping code
to convert past_due → pastDue consistently and rerun the build/tests to verify
the guard and resource types are aligned.

Comment on lines +635 to +637
fee: CommerceMoneyAmountJSON;
annual_fee: CommerceMoneyAmountJSON;
annual_monthly_fee: CommerceMoneyAmountJSON;
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Added fee/annual_fee/annual_monthly_fee – consider deprecating legacy flat fields to avoid ambiguity

The new fields are correct. However, CommercePlanJSON still includes amount, amount_formatted, annual_amount, etc. If those are kept for back-compat, mark them deprecated to steer consumers to fee/annual_fee/annual_monthly_fee.

Add JSDoc deprecation for legacy fields (outside this hunk), e.g.:

/**
 * @deprecated Use `fee.amount` (number) or `fee.amount_formatted` (string) instead.
 */
amount: number;
/**
 * @deprecated Use `fee.amount_formatted` instead.
 */
amount_formatted: string;
/**
 * @deprecated Use `annual_fee.amount` instead.
 */
annual_amount: number;
/**
 * @deprecated Use `annual_fee.amount_formatted` instead.
 */
annual_amount_formatted: string;
/**
 * @deprecated Use `annual_monthly_fee.amount` instead.
 */
annual_monthly_amount: number;
/**
 * @deprecated Use `annual_monthly_fee.amount_formatted` instead.
 */
annual_monthly_amount_formatted: string;
/**
 * @deprecated Use `fee.currency` instead.
 */
currency: string;
/**
 * @deprecated Use `fee.currency_symbol` instead.
 */
currency_symbol: string;

🏁 Script executed:

#!/bin/bash
# Find consumers still depending on legacy flat plan price fields
rg -n $'\\b(annual_)?(monthly_)?amount(_formatted)?\\b|\\bcurrency_symbol\\b' packages/

Length of output: 24142


Deprecate legacy flat fields in CommercePlanJSON
CommercePlanJSON still exposes flat price properties (amount, amount_formatted, annual_amount, etc.) alongside the new nested fee/annual_fee/annual_monthly_fee fields. Please add JSDoc @deprecated annotations to steer consumers toward the new structure.

Locations to update:

  • packages/types/src/json.ts (CommercePlanJSON, ~lines 638–644)
  • packages/types/src/api.ts (response schema, lines 33–35)

Suggested diffs:

packages/types/src/json.ts

-  amount: number;
+  /**
+   * @deprecated Use `fee.amount` instead.
+   */
+  amount: number;

-  amount_formatted: string;
+  /**
+   * @deprecated Use `fee.amount_formatted` instead.
+   */
+  amount_formatted: string;

-  annual_amount: number;
+  /**
+   * @deprecated Use `annual_fee.amount` instead.
+   */
+  annual_amount: number;

-  annual_amount_formatted: string;
+  /**
+   * @deprecated Use `annual_fee.amount_formatted` instead.
+   */
+  annual_amount_formatted: string;

-  annual_monthly_amount: number;
+  /**
+   * @deprecated Use `annual_monthly_fee.amount` instead.
+   */
+  annual_monthly_amount: number;

-  annual_monthly_amount_formatted: string;
+  /**
+   * @deprecated Use `annual_monthly_fee.amount_formatted` instead.
+   */
+  annual_monthly_amount_formatted: string;

-  currency: string;
+  /**
+   * @deprecated Use `fee.currency` instead.
+   */
+  currency: string;

-  currency_symbol: string;
+  /**
+   * @deprecated Use `fee.currency_symbol` instead.
+   */
+  currency_symbol: string;

packages/types/src/api.ts

-  amount_formatted: string;
+  /**
+   * @deprecated Use `fee.amount_formatted` instead.
+   */
+  amount_formatted: string;

-  annual_monthly_amount_formatted: string;
+  /**
+   * @deprecated Use `annual_monthly_fee.amount_formatted` instead.
+   */
+  annual_monthly_amount_formatted: string;

-  currency_symbol: string;
+  /**
+   * @deprecated Use `fee.currency_symbol` instead.
+   */
+  currency_symbol: string;

This will guide consumers toward the new nested CommerceMoneyAmountJSON fields and clarify the intended usage.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/types/src/json.ts around lines 635–644 and packages/types/src/api.ts
around lines 33–35, the legacy flat price fields on CommercePlanJSON are still
exposed; add JSDoc @deprecated annotations to each deprecated flat field (e.g.,
amount, amount_formatted, annual_amount, etc.) indicating consumers should use
the new nested fee / annual_fee / annual_monthly_fee CommerceMoneyAmountJSON
fields; update the comment blocks above each deprecated property to include
@deprecated and a short pointer to the replacement nested field, ensuring
TypeScript/JSDoc tools and IDEs surface the deprecation warnings.

# Conflicts:
#	packages/clerk-js/src/ui/contexts/components/Plans.tsx
#	packages/types/src/commerce.ts
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: 1

🔭 Outside diff range comments (1)
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (1)

1-85: Fix test fixtures to use nested pricing fields
The CommercePlanResource no longer exposes flat fields like amountFormatted, currencySymbol, annualAmount or annualMonthlyAmount at the top level—you must use the nested fee and annualFee properties instead.

Please update the PricingTable tests accordingly:

  • packages/clerk-js/src/ui/components/PricingTable/tests/PricingTable.test.tsx
    • Replace top-level properties in your mock plans:
      • amountFormattedfee.amountFormatted
      • currencySymbolfee.currencySymbol
      • annualAmountannualFee.amount
      • annualMonthlyAmountannualFee.amount / 12 (or annualFee.amountFormatted if you need the formatted string)

Remove any remaining direct references to those removed plan properties elsewhere to prevent type or runtime errors.

🧹 Nitpick comments (7)
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (3)

298-301: Annual support guard: consider optional chaining for resiliency

annualMonthlyFee is required per types, but if any upstream JSON deviates, this will throw. Optional chaining would be safer without changing behavior.

Apply:

-  const planSupportsAnnual = annualMonthlyFee.amount > 0;
+  const planSupportsAnnual = Boolean(annualMonthlyFee?.amount && annualMonthlyFee.amount > 0);

309-312: Formatting normalization is appropriate; minor dep tweak optional

Using normalizeFormatted ensures consistent display. Depending on fee.amountFormatted is fine; alternatively depend on fee to recompute if different aspects of fee change together.

Optional:

-  }, [fee.amountFormatted]);
+  }, [fee]);

394-406: Remove redundant truthiness check for setPlanPeriod

setPlanPeriod is non-optional in CardHeaderProps, so && setPlanPeriod is always true and can be removed for clarity.

Apply:

-      {planSupportsAnnual && setPlanPeriod ? (
+      {planSupportsAnnual ? (
packages/clerk-js/src/core/resources/CommercePlan.ts (4)

15-17: New MoneyAmount fields declared; consider documentation and immutability

Fields are correctly typed. Add JSDoc for public APIs and consider freezing or cloning the money objects to prevent accidental external mutations.

Example JSDoc:

/** Monthly fee of the plan. */
fee!: CommerceMoneyAmount;
/** Annual fee of the plan. */
annualFee!: CommerceMoneyAmount;
/** Annual fee expressed per month. */
annualMonthlyFee!: CommerceMoneyAmount;

Optional immutability guard inside fromJSON after assignment:

this.fee = Object.freeze({ ...this.fee });
this.annualFee = Object.freeze({ ...this.annualFee });
this.annualMonthlyFee = Object.freeze({ ...this.annualMonthlyFee });

35-58: Mark fromJSON as override if BaseResource defines it

If BaseResource declares fromJSON, use the override modifier to have the compiler verify parity with the base signature.

Proposed change (only if BaseResource has fromJSON):

-  protected fromJSON(data: CommercePlanJSON | null): this {
+  protected override fromJSON(data: CommercePlanJSON | null): this {

Please confirm BaseResource signature before applying to avoid TS errors.


42-45: JSON parsing of fees: consider minimal null-guards

If any of data.fee, data.annual_fee, or data.annual_monthly_fee are unexpectedly null/undefined, this will throw. If backend guarantees presence, fine; otherwise, add guards or safe defaults.

Guarded version:

-    this.fee = commerceMoneyAmountFromJSON(data.fee);
-    this.annualFee = commerceMoneyAmountFromJSON(data.annual_fee);
-    this.annualMonthlyFee = commerceMoneyAmountFromJSON(data.annual_monthly_fee);
+    if (data.fee) this.fee = commerceMoneyAmountFromJSON(data.fee);
+    if (data.annual_fee) this.annualFee = commerceMoneyAmountFromJSON(data.annual_fee);
+    if (data.annual_monthly_fee) this.annualMonthlyFee = commerceMoneyAmountFromJSON(data.annual_monthly_fee);

If these are required by API contract, keep as-is and document the invariant.


12-29: Public fields added: add JSDoc to satisfy public API guidelines

Per coding guidelines, public APIs should have JSDoc. Consider annotating new fields like hasBaseFee, forPayerType, publiclyVisible, slug, avatarUrl, freeTrialDays, freeTrialEnabled.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a0d739 and 22841e6.

⛔ Files ignored due to path filters (1)
  • .typedoc/__tests__/__snapshots__/file-structure.test.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (7)
  • packages/clerk-js/src/core/resources/CommercePlan.ts (2 hunks)
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts (6 hunks)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (5 hunks)
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx (3 hunks)
  • packages/react/src/components/__tests__/PlanDetailsButton.test.tsx (1 hunks)
  • packages/types/src/commerce.ts (15 hunks)
  • packages/types/src/json.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/types/src/json.ts
  • packages/types/src/commerce.ts
  • packages/react/src/components/tests/PlanDetailsButton.test.tsx
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
🧰 Additional context used
📓 Path-based instructions (10)
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/PricingTable/PricingTableDefault.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/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.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/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.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/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.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/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.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/PricingTable/PricingTableDefault.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/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.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/PricingTable/PricingTableDefault.tsx
**/*

⚙️ CodeRabbit Configuration File

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/clerk-js/src/core/resources/CommercePlan.ts
🧬 Code Graph Analysis (2)
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (1)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
  • normalizeFormatted (27-29)
packages/clerk-js/src/core/resources/CommercePlan.ts (3)
packages/backend/src/api/resources/CommercePlan.ts (1)
  • CommercePlan (15-101)
packages/types/src/commerce.ts (2)
  • CommercePlanResource (271-413)
  • CommerceMoneyAmount (1207-1244)
packages/clerk-js/src/utils/commerce.ts (1)
  • commerceMoneyAmountFromJSON (10-17)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (10)
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (7)

147-147: Condition update to annual pricing check looks correct

Switching to plan.annualMonthlyFee.amount > 0 aligns with the new MoneyAmount model and preserves prior semantics. If “annual support” can exist with a zero price (e.g., free annual plan), this check may hide the toggle; confirm backend invariants.


302-308: Fee selection logic: LGTM and matches new MoneyAmount fields

Memoized selection between plan.fee and plan.annualMonthlyFee based on planPeriod and planSupportsAnnual is clear and correct. Dependency array covers all inputs used in the memo.


374-376: Price rendering correctly uses nested money object

Using fee.currencySymbol and normalized formatted value is consistent with the new shape and avoids reliance on removed top-level fields.


239-244: Localization keys for footer notice: good coverage

Static strings use localizationKeys. Dates are passed as values. Looks consistent with localization guidelines.


255-263: Button props sourcing from Plans context is correct; ensure error/permission tooltips remain localized

organizationProfile.plansPage.alerts.noPermissionsToManageBilling is a localization key; good.


360-391: Always “per month” label: confirm intended behavior for annual period

The period label remains ‘month’ even when showing annualMonthlyFee (monthly equivalent). This matches the intent, but double-check UX copy requirements in case an explicit “/mo” vs “billed annually” combination needs alternate wording for accessibility.


1-85: General: theming & localization compliance

  • Element descriptors are camelCase and used consistently.
  • Static text uses localization keys.
  • Styled system sx is applied.
  • No hard-coded user-facing strings introduced.
packages/clerk-js/src/core/resources/CommercePlan.ts (3)

2-6: Type import of CommerceMoneyAmount: correct

Using import type avoids bundling types at runtime and aligns with TS best practices.


8-9: Use of shared JSON→model mapper is correct

commerceMoneyAmountFromJSON centralizes translation and keeps this resource lean.


1-60: No flat money fields remain on CommercePlan

Verified that there are no plan.amount, plan.currency, plan.amountFormatted or plan.currencySymbol references in packages/clerk-js/src/core/resources/CommercePlan.ts or anywhere in the UI. All monetary values are now consistently exposed via CommerceMoneyAmount on the fee, annualFee and annualMonthlyFee properties.

@@ -7,7 +7,7 @@ import { Tooltip } from '@/ui/elements/Tooltip';
import { getClosestProfileScrollBox } from '@/ui/utils/getClosestProfileScrollBox';

import { useProtect } from '../../common';
import { usePlansContext, usePricingTableContext, useSubscriberTypeContext } from '../../contexts';
import { normalizeFormatted, usePlansContext, usePricingTableContext, useSubscriberTypeContext } from '../../contexts';
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Confirm normalizeFormatted is re-exported from contexts

Import looks correct, assuming contexts’ index re-exports it. Please verify the re-export to avoid runtime import errors.

Run to confirm the re-export:


🏁 Script executed:

#!/bin/bash
rg -n -S "export .*normalizeFormatted" packages/clerk-js/src/ui/contexts

Length of output: 188


🏁 Script executed:

#!/bin/bash
# Locate the contexts index file
INDEX_FILE=$(fd -e ts -e tsx -t f index packages/clerk-js/src/ui/contexts | head -n 1)
echo "Index file: $INDEX_FILE"
sed -n '1,200p' "$INDEX_FILE"

Length of output: 921


🏁 Script executed:

#!/bin/bash
# List root-level TypeScript files in contexts directory
echo "Root-level TS/TSX files in contexts/:"
fd -e ts -e tsx -t f packages/clerk-js/src/ui/contexts -d 1

# Display contents of contexts/index.ts if it exists
if [ -f packages/clerk-js/src/ui/contexts/index.ts ]; then
  echo -e "\nFound contexts/index.ts:"
  sed -n '1,200p' packages/clerk-js/src/ui/contexts/index.ts
else
  echo -e "\nNo root-level index.ts in contexts/"
fi

Length of output: 1076


Import paths need adjustment for normalizeFormatted and related hooks
The root-level packages/clerk-js/src/ui/contexts/index.ts does not re-export normalizeFormatted, usePlansContext, usePricingTableContext, or useSubscriberTypeContext. Those are defined and re-exported in the components subfolder:

  • packages/clerk-js/src/ui/contexts/components/Plans.tsx defines normalizeFormatted
  • packages/clerk-js/src/ui/contexts/components/index.ts re-exports it (and the hooks)

To fix the runtime import error, update your import in PricingTableDefault.tsx:

- import { normalizeFormatted, usePlansContext, usePricingTableContext, useSubscriberTypeContext } from '../../contexts';
+ import { normalizeFormatted, usePlansContext, usePricingTableContext, useSubscriberTypeContext } from '../../contexts/components';

Alternatively, if you prefer to keep all exports on the root context, add these lines to packages/clerk-js/src/ui/contexts/index.ts:

export * from './components';
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
around line 10, the import is pulling normalizeFormatted and the hooks from the
root contexts index which does not re-export them; update the import to point to
the components subfolder that actually exports them (e.g., import from
'../../contexts/components' or '../../contexts/components/index') so the correct
symbols are resolved at runtime, or alternatively add "export * from
'./components';" to packages/clerk-js/src/ui/contexts/index.ts to re-export
those symbols from the root.

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: 0

🧹 Nitpick comments (6)
packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.tsx (6)

39-41: Remove legacy __internal_toSnapshot stub to match updated resource types

This field was removed in the refactor; keeping it in tests can cause type drift and confusion.

Apply this diff to remove it:

   freeTrialDays: 14,
-  __internal_toSnapshot: jest.fn(),
   pathRoot: '',

53-54: Avoid as any in fixtures; prefer typed builders or satisfies with partials

Using as any hides shape mismatches with the updated plan type and makes refactors riskier. Consider:

  • Creating a typed plan factory in test utils that returns a Partial with sensible defaults, or
  • Annotating the object with satisfies against a partial type to preserve literal types and catch drift early.

I can add a minimal builder (e.g., makePlan({ overrides })) across PricingTable tests to eliminate the as any casts. Want me to open a follow-up?


123-129: Prefer role-based query for CTA instead of raw text

Querying the button by role reduces brittleness and improves a11y alignment.

Apply this diff:

-    const { getByRole, getByText } = render(<PricingTable />, { wrapper });
+    const { getByRole } = render(<PricingTable />, { wrapper });
@@
-      // Button text from Plans.buttonPropsForPlan via freeTrialOr
-      expect(getByText('Start 14-day free trial')).toBeVisible();
+      // Button text from Plans.buttonPropsForPlan via freeTrialOr
+      expect(getByRole('button', { name: /Start 14-day free trial/i })).toBeVisible();

142-148: Prefer role-based query for CTA instead of raw text (signed-out case)

Same rationale as above; makes the test less fragile against text node structure changes.

Apply this diff:

-    const { getByRole, getByText } = render(<PricingTable />, { wrapper });
+    const { getByRole } = render(<PricingTable />, { wrapper });
@@
-      // Signed out users should see free trial CTA when plan has trial enabled
-      expect(getByText('Start 14-day free trial')).toBeVisible();
+      // Signed out users should see free trial CTA when plan has trial enabled
+      expect(getByRole('button', { name: /Start 14-day free trial/i })).toBeVisible();

169-175: Prefer role-based query for "Subscribe" CTA

Align with RTL best practices and reduce brittleness.

Apply this diff:

-    const { getByRole, getByText } = render(<PricingTable />, { wrapper });
+    const { getByRole } = render(<PricingTable />, { wrapper });
@@
-      // Signed out users should see regular "Subscribe" for non-trial plans
-      expect(getByText('Subscribe')).toBeVisible();
+      // Signed out users should see regular "Subscribe" for non-trial plans
+      expect(getByRole('button', { name: /Subscribe/i })).toBeVisible();

7-44: Consider a shared typed plan fixture to cover fees and edge cases

Now that fees are nested, it’s worth adding a small builder to exercise:

  • Plans without annual support (annualMonthlyFee.amount = 0)
  • Non-USD currencies and zero-decimal currencies
  • Whole-dollar vs fractional amounts (to validate normalizeFormatted behavior)
  • hasBaseFee = false plans (if applicable)

This improves coverage for the new model and prevents regressions in PricingTableDefault/Matrix and Plans context.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 22841e6 and 5377039.

📒 Files selected for processing (1)
  • packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (14)
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/PricingTable/__tests__/PricingTable.test.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/PricingTable/__tests__/PricingTable.test.tsx
**/*.{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/PricingTable/__tests__/PricingTable.test.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.tsx
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/PricingTable/__tests__/PricingTable.test.tsx
**/*.{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/PricingTable/__tests__/PricingTable.test.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/PricingTable/__tests__/PricingTable.test.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.tsx
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.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/PricingTable/__tests__/PricingTable.test.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/PricingTable/__tests__/PricingTable.test.tsx
**/*.test.{jsx,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

**/*.test.{jsx,tsx}: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure

Files:

  • packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.tsx
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.tsx
**/*

⚙️ CodeRabbit Configuration File

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

Files:

  • packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.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). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/clerk-js/src/ui/components/PricingTable/__tests__/PricingTable.test.tsx (2)

11-28: Fee fields correctly migrated to nested CommerceMoneyAmount structure

The switch to fee/annualFee/annualMonthlyFee with amount and amountFormatted looks consistent and aligns with the new model. Minor-unit amounts match formatted strings ($20.00, $200.00, $16.67). Currency fields are present where needed. LGTM.


95-95: Locale/timezone pinning confirmed; assertion is safe

The CI test setup already locks both locale and TZ to a constant value, so the hard-coded “Trial ends Jan 15, 2021” won’t flake:

• In jest.setup-after-env.ts, Date.prototype.toLocaleDateString is overridden to always use “en-US.”
• In jest.jsdom-with-timezone.ts, process.env.TZ is set (defaulting to UTC).

No change required here.

@panteliselef panteliselef merged commit 173837c into main Aug 12, 2025
63 of 64 checks passed
@panteliselef panteliselef deleted the elef/com-1139-remove-amount-usage-from-clerk-js branch August 12, 2025 20:35
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.

3 participants