Skip to content

chore(clerk-js,types): Update PricingTable with trial info #6493

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from

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

    • Added support for displaying free trial information in pricing plans, including trial duration and eligibility.
    • Pricing tables now show when a free trial is active and display the trial end date.
    • Subscription details indicate free trial eligibility and end dates where applicable.
  • Localization

    • Introduced new localized strings for free trial messaging, including trial end dates and "Start free trial" prompts.

@panteliselef panteliselef requested review from aeliox and a team August 8, 2025 16:56
@panteliselef panteliselef self-assigned this Aug 8, 2025
Copy link

changeset-bot bot commented Aug 8, 2025

🦋 Changeset detected

Latest commit: b228074

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/localizations Minor
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/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 ↗︎

Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 8, 2025 4:57pm

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@6493

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: b228074

Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

📝 Walkthrough

Walkthrough

This change introduces support for free trial properties across multiple packages. It adds new fields such as freeTrialDays, freeTrialEnabled, eligibleForFreeTrial, and freeTrialEndsAt to commerce-related types, resources, and JSON interfaces. The UI components and context logic are updated to display free trial information, including new conditional rendering and localization strings for trial periods. Changesets are included to record minor version updates and describe the new trial-related features. Localization files and type declarations are updated to support the new trial messaging and logic.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


🪧 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
  • 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 src/utils.ts and explain its main purpose.
    • @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 comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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: 5

🔭 Outside diff range comments (2)
packages/types/src/localization.ts (1)

151-156: Add ‘date’ parameter to badge__endsAt

All locales that define badge__endsAt use a {{ date }} placeholder, so update its type:

• In packages/types/src/localization.ts (line 153):

-  badge__endsAt: LocalizationValue;
+  badge__endsAt: LocalizationValue<'date'>;
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (1)

144-153: Prioritize trial notice over plan-period mismatch to avoid suppressing it

With the current else-if ordering, when both a plan-period mismatch and an active trial are true, the mismatch branch executes first, setting shouldShowFooterNotice=false and suppressing the trial message. Trial notice should take precedence.

Apply this reordering so trial wins:

-    } else if (planPeriod !== subscription.planPeriod && plan.annualMonthlyAmount > 0) {
-      shouldShowFooter = true;
-      shouldShowFooterNotice = false;
-    } else if (plan.freeTrialEnabled && subscription.freeTrialEndsAt !== null) {
-      shouldShowFooter = true;
-      shouldShowFooterNotice = true;
+    } else if (plan.freeTrialEnabled && subscription.freeTrialEndsAt) {
+      shouldShowFooter = true;
+      shouldShowFooterNotice = true;
+    } else if (planPeriod !== subscription.planPeriod && plan.annualMonthlyAmount > 0) {
+      shouldShowFooter = true;
+      shouldShowFooterNotice = false;

This ensures the “trial ends at …” notice shows even when a mismatch exists.

🧹 Nitpick comments (8)
packages/localizations/src/en-US.ts (1)

144-144: New “Start free trial” label added – consider pluralization edge case

String is fine and param matches types. Minor nit: “{{days}}-day” reads a bit odd for 1 (e.g., “1-day”). If your i18n system supports it, consider singular/plural variants; otherwise this is acceptable.

Example alternatives (if desired):

  • “Start your {{days}}-day free trial”
  • Add plural forms: startFreeTrial_one / startFreeTrial_other
packages/clerk-js/src/core/resources/CommercePlan.ts (2)

68-91: Snapshot omits new fields—confirm intent, or include them

__internal_toSnapshot doesn’t include freeTrialDays/freeTrialEnabled. If snapshots are used for caching or devtools, consider adding them; if snapshots intentionally exclude experimental fields, ignore.

If inclusion is desired and CommercePlanJSONSnapshot supports them, update as:

       slug: this.slug,
       avatar_url: this.avatarUrl,
+      free_trial_days: this.freeTrialDays,
+      free_trial_enabled: this.freeTrialEnabled,
       features: this.features.map(feature => feature.__internal_toSnapshot()),

Also ensure @clerk/types CommercePlanJSONSnapshot includes these fields.


33-66: Add unit tests for deserialization defaults

No tests were added. Please add coverage for:

  • Missing trial fields → defaults (null/false)
  • Explicit values (e.g., 0 days, enabled true)

I can help scaffold tests if useful.

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

785-788: Document experimental fields; avoid commented-out properties

  • Keep free_trial_ends_at optional for beta, but add a JSDoc explaining semantics, units, and GA plan.
  • Remove the commented is_free_trial line or link to a tracking issue.

Example:

/**
 * UNIX epoch seconds when the free trial ends.
 * @experimental Optional until GA; may become required when backend guarantees presence.
 */
free_trial_ends_at?: number | null;
packages/types/src/commerce.ts (3)

440-457: Model the free-trial invariants more explicitly (or at least document them).

Right now freeTrialEnabled and freeTrialDays can drift (e.g., enabled with null or disabled with a number). Either:

  • Document the invariant in JSDoc: when freeTrialEnabled === true, freeTrialDays is a positive integer; when false, it must be null.
  • Or (preferred) encode it in the type system via a discriminated union.

Example approach (outside this range, shown for clarity):

type FreeTrialInfo =
  | { freeTrialEnabled: true; freeTrialDays: number }
  | { freeTrialEnabled: false; freeTrialDays: null };

// Then:
export interface CommercePlanResource extends ClerkResource, FreeTrialInfo {
  // ...
}

1126-1146: Remove commented-out code and rely on tracked TODOs.

The isFreeTrial block is commented out. Avoid commented code in types; it tends to rot and confuses consumers. Keep the TODO in an issue or a code comment without the dead code.

Also, freeTrialEndsAt: Date | null; looks good and consistent with other date fields.

-  // /**
-  //  * @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" />
-  //  * ```
-  //  */
-  // isFreeTrial: boolean;

1256-1265: Clarify semantics for eligibleForFreeTrial (and why it’s optional).

Add a short JSDoc note clarifying what “eligible” means (e.g., new subscriber with no prior trial? per-plan vs account-level?) and whether absence (undefined) should be interpreted as “unknown” vs “false”. This helps UI logic avoid misinterpretation.

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

271-272: Narrow the dependency to avoid unnecessary re-creations.

Depending on the entire topLevelSubscription object can cause needless callback invalidations. Depend only on the boolean you read.

-    [activeOrUpcomingSubscriptionWithPlanPeriod, canManageBilling, subscriptionItems, topLevelSubscription],
+    [activeOrUpcomingSubscriptionWithPlanPeriod, canManageBilling, subscriptionItems, topLevelSubscription?.eligibleForFreeTrial],
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cf284ee and b228074.

📒 Files selected for processing (10)
  • .changeset/sour-lemons-talk.md (1 hunks)
  • .changeset/tender-planets-win.md (1 hunks)
  • packages/clerk-js/src/core/resources/CommercePlan.ts (2 hunks)
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts (4 hunks)
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (2 hunks)
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx (4 hunks)
  • packages/localizations/src/en-US.ts (2 hunks)
  • packages/types/src/commerce.ts (3 hunks)
  • packages/types/src/json.ts (3 hunks)
  • packages/types/src/localization.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/tender-planets-win.md
  • .changeset/sour-lemons-talk.md
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/types/src/commerce.ts
  • packages/localizations/src/en-US.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/types/src/localization.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/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/types/src/commerce.ts
  • packages/localizations/src/en-US.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/types/src/localization.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/resources/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/types/src/commerce.ts
  • packages/localizations/src/en-US.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/types/src/localization.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/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/types/src/commerce.ts
  • packages/localizations/src/en-US.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/types/src/localization.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/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/types/src/commerce.ts
  • packages/localizations/src/en-US.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/types/src/localization.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/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/types/src/commerce.ts
  • packages/localizations/src/en-US.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/types/src/localization.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/CommercePlan.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/types/src/commerce.ts
  • packages/localizations/src/en-US.ts
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
  • packages/types/src/localization.ts
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.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/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.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/contexts/components/Plans.tsx
  • packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx
packages/localizations/**/*

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

Localization files must be placed in 'packages/localizations/'.

Files:

  • packages/localizations/src/en-US.ts
**/localizations/**/*.ts

⚙️ CodeRabbit Configuration File

**/localizations/**/*.ts: Review the changes to localization files with the following guidelines:

  • Ensure that no existing translations are accidentally removed unless they are being replaced or fixed. If a string is removed, verify that it is intentional and justified.
  • Check that all translations are friendly, formal, or semi-formal. Explicit, offensive, or inappropriate language is not allowed. If you find any potentially offensive language or are unsure, tag the @clerk/sdk-infra team in a separate comment. If you do not intend to tag the team, refer to it as "Clerk SDK Infra team" instead.
  • Use the most up-to-date base localization file (https://github.com/clerk/javascript/blob/main/packages/localizations/src/en-US.ts) to validate changes, ensuring consistency and completeness.
  • Confirm that new translations are accurate, contextually appropriate, and match the intent of the original English strings.
  • Check for formatting issues, such as missing placeholders, incorrect variable usage, or syntax errors.
  • Ensure that all keys are unique and that there are no duplicate or conflicting entries.
  • If you notice missing translations for new keys, flag them for completion.

Files:

  • packages/localizations/src/en-US.ts
🧠 Learnings (1)
📚 Learning: 2025-07-22T08:43:52.095Z
Learnt from: panteliselef
PR: clerk/javascript#6317
File: packages/clerk-js/src/ui/contexts/components/Plans.tsx:56-68
Timestamp: 2025-07-22T08:43:52.095Z
Learning: The `useSubscription` hook exported from `packages/clerk-js/src/ui/contexts/components/Plans.tsx` is only used internally within clerk-js UI components and is not exposed to external consumers, making renames and modifications to this hook non-breaking for end users.

Applied to files:

  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
🧬 Code Graph Analysis (1)
packages/clerk-js/src/ui/components/PricingTable/PricingTableDefault.tsx (1)
packages/clerk-js/src/ui/localization/localizationKeys.ts (1)
  • localizationKeys (72-77)
⏰ 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 (14)
packages/localizations/src/en-US.ts (1)

46-46: Add trial-end badge: placeholder and format look correct

Key and pipe formatting are consistent with existing date-based badges. No issues.

.changeset/tender-planets-win.md (1)

1-7: Changeset looks good for trial info in PricingTable

Packages and bump type are appropriate; concise description aligns with PR scope.

.changeset/sour-lemons-talk.md (1)

1-6: Second changeset OK; confirm intended duplication of bumped packages

Multiple changesets both bumping @clerk/clerk-js and @clerk/types will coalesce to a single minor bump per package, which is fine. Just confirm this duplication is intentional.

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

152-152: Type for new badge key is correct

badge__trialEndsAt: LocalizationValue<'date'>; matches its usage in en-US and other date badges.


178-179: Type for startFreeTrial is correct

Param name 'days' matches the en-US string. Good addition.

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

30-31: New free trial fields added to plan: good shape

Types and nullability look right: number | null for days, boolean for enabled.


61-63: Safe deserialization with sensible defaults

withDefault(null/false) guards absent fields and preserves 0 days when present. LGTM.

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

238-244: Confirmation: Localization keys and date param are valid

Both badge__trialEndsAt and badge__startsAt are defined in packages/types/src/localization.ts as LocalizationValue<'date'> and have corresponding entries in your locale files (e.g. en-US). The LocalizationValue<'date'> type allows a Date object for the date parameter, so your usage is correct.

Optional readability tweak:

  • In PricingTableDefault.tsx (lines 238–244), you could replace
    plan.freeTrialEnabled && subscription.freeTrialEndsAt !== null
    with
    plan.freeTrialEnabled && Boolean(subscription.freeTrialEndsAt)
    since freeTrialEndsAt is normalized to null when absent.
packages/clerk-js/src/core/resources/CommerceSubscription.ts (2)

30-31: LGTM: Adds eligibleForFreeTrial with backward-compatible optional typing

Property and typing align with the new JSON field and preserve BC.


79-79: LGTM: Adds freeTrialEndsAt on subscription items

The field is correctly modeled as Date | null and matches the UI usage.

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

652-654: LGTM: Adds plan-level free trial fields

Fields use snake_case, correct optionality, and appropriate nullability for days.


817-818: LGTM: Adds subscription-level trial eligibility (optional)

Optionality preserves BC. Consider adding a brief JSDoc for clarity similar to other experimental fields.

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

111-111: LGTM: exposing data as topLevelSubscription.

This improves readability when combined with subscriptionItems. No issues spotted.


258-261: Apply the free-trial override only on the subscribe path.

This is the right place to inject the trial CTA. Keep this, and remove the global override in the final return below.

Add tests to ensure:

  • With no active subscription and eligible trial: CTA is “Start free trial (X days)”.
  • With active subscription: CTA remains “Manage subscription”.
  • With canceled subscription (period mismatch): CTA is “Switch to …”, not trial.

I can help draft tests using @testing-library/react and mocked hooks.

Comment on lines +110 to 111
this.freeTrialEndsAt = data.free_trial_ends_at ? unixEpochToDate(data.free_trial_ends_at) : null;
return this;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid falsy checks on epoch timestamps

Using a truthy check can mis-handle 0 as a valid timestamp. Prefer an explicit type/nullish guard.

Use a robust check:

-    this.freeTrialEndsAt = data.free_trial_ends_at ? unixEpochToDate(data.free_trial_ends_at) : null;
+    this.freeTrialEndsAt =
+      typeof data.free_trial_ends_at === 'number' ? unixEpochToDate(data.free_trial_ends_at) : null;
📝 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
this.freeTrialEndsAt = data.free_trial_ends_at ? unixEpochToDate(data.free_trial_ends_at) : null;
return this;
this.freeTrialEndsAt =
typeof data.free_trial_ends_at === 'number' ? unixEpochToDate(data.free_trial_ends_at) : null;
return this;
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/CommerceSubscription.ts at lines
110-111, replace the current truthy check on data.free_trial_ends_at with an
explicit nullish check to correctly handle 0 as a valid timestamp. Change the
condition to explicitly check if data.free_trial_ends_at is not null or
undefined before converting it with unixEpochToDate; otherwise, assign null.

Comment on lines +190 to 191
// TODO(@COMMERCE): This needs to be removed.
subscription: sub,
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

Track the TODO for removing the subscription param.

Create an issue to remove this param and plan a small cleanup PR. I can scan for call sites to confirm it’s unused before removal.


🏁 Script executed:

#!/bin/bash
# Find direct and object-style usages of the `subscription` param passed to buttonPropsForPlan
rg -n --no-heading "buttonPropsForPlan\(" -A 5
rg -n --no-heading "subscription\s*:" -g "packages/clerk-js/**"

Length of output: 3060


Plan removal of unused subscription prop from Plans component
The subscription parameter in packages/clerk-js/src/ui/contexts/components/Plans.tsx isn’t consumed by any downstream code. Please create an issue to track this cleanup and open a small PR to:

  • Remove subscription from the component signature (around line 178).
  • Delete the subscription: sub, mapping (line 191).
-      // TODO(@COMMERCE): This needs to be removed.
-      subscription: sub,
📝 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
// TODO(@COMMERCE): This needs to be removed.
subscription: sub,
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/contexts/components/Plans.tsx around lines 178 to
191, the subscription prop is unused and should be removed. First, remove the
subscription parameter from the Plans component signature near line 178. Then,
delete the subscription: sub, mapping at line 191. Additionally, create an issue
to track this cleanup and open a small PR to implement these removals.

Comment on lines +215 to +221
const freeTrialOr = (localizationKey: LocalizationKey): LocalizationKey => {
if (plan?.freeTrialEnabled && topLevelSubscription?.eligibleForFreeTrial) {
return localizationKeys('commerce.startFreeTrial', { days: plan.freeTrialDays ?? 0 });
}
return localizationKey;
};

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

Don’t globally override CTAs with “Start free trial”.

As written, freeTrialOr is later applied to the final result, so “Start free trial” can incorrectly replace “Manage subscription”, “Switch to Annual/Monthly”, etc., whenever plan.freeTrialEnabled && topLevelSubscription?.eligibleForFreeTrial. Restrict the override only to the “subscribe” path.

Also consider guarding against 0/null trial days to avoid odd UI like “Start free trial (0 days)”.

-      const freeTrialOr = (localizationKey: LocalizationKey): LocalizationKey => {
-        if (plan?.freeTrialEnabled && topLevelSubscription?.eligibleForFreeTrial) {
-          return localizationKeys('commerce.startFreeTrial', { days: plan.freeTrialDays ?? 0 });
-        }
-        return localizationKey;
-      };
+      const freeTrialOr = (localizationKey: LocalizationKey): LocalizationKey => {
+        // Only used for initial subscribe CTA; final application must not override manage/switch CTAs.
+        if (plan?.freeTrialEnabled && topLevelSubscription?.eligibleForFreeTrial) {
+          const days = Math.max(plan.freeTrialDays ?? 0, 0);
+          return localizationKeys('commerce.startFreeTrial', { days });
+        }
+        return localizationKey;
+      };

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

🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/contexts/components/Plans.tsx around lines 215 to
221, the freeTrialOr function currently overrides all CTAs with "Start free
trial" when freeTrialEnabled and eligibleForFreeTrial are true, which
incorrectly replaces other CTAs like "Manage subscription" or "Switch to
Annual/Monthly". To fix this, restrict the override so it only applies on the
"subscribe" path by adding a condition to check the current CTA context before
returning the free trial localization key. Additionally, add a guard to ensure
plan.freeTrialDays is greater than zero before applying the free trial text to
avoid showing "Start free trial (0 days)" or similar UI issues.

Comment on lines 263 to 269
return {
localizationKey: getLocalizationKey(),
localizationKey: freeTrialOr(getLocalizationKey()),
variant: isCompact ? 'bordered' : 'solid',
colorScheme: isCompact ? 'secondary' : 'primary',
isDisabled: !canManageBilling,
disabled: !canManageBilling,
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Bug: final return still overrides everything with trial CTA.

Remove the outer freeTrialOr to avoid overriding non-subscription CTAs.

-      return {
-        localizationKey: freeTrialOr(getLocalizationKey()),
+      return {
+        localizationKey: getLocalizationKey(),
         variant: isCompact ? 'bordered' : 'solid',
         colorScheme: isCompact ? 'secondary' : 'primary',
         isDisabled: !canManageBilling,
         disabled: !canManageBilling,
       };
📝 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
return {
localizationKey: getLocalizationKey(),
localizationKey: freeTrialOr(getLocalizationKey()),
variant: isCompact ? 'bordered' : 'solid',
colorScheme: isCompact ? 'secondary' : 'primary',
isDisabled: !canManageBilling,
disabled: !canManageBilling,
};
return {
localizationKey: getLocalizationKey(),
variant: isCompact ? 'bordered' : 'solid',
colorScheme: isCompact ? 'secondary' : 'primary',
isDisabled: !canManageBilling,
disabled: !canManageBilling,
};
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/contexts/components/Plans.tsx around lines 263 to
269, the final return statement wraps the localizationKey with freeTrialOr,
which causes it to override all non-subscription CTAs incorrectly. To fix this,
remove the outer freeTrialOr call from the return statement so that only
appropriate CTAs use freeTrialOr and others remain unaffected.

@@ -43,6 +43,7 @@ export const enUS: LocalizationResource = {
badge__default: 'Default',
badge__endsAt: "Ends {{ date | shortDate('en-US') }}",
badge__expired: 'Expired',
badge__trialEndsAt: "Trial ends {{ date | shortDate('en-US') }}",
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

Ensure other locales add these new keys

Please verify all locale files define:

  • badge__trialEndsAt
  • commerce.startFreeTrial

Missing translations will fall back to English or cause gaps depending on runtime.

Run to audit locale coverage:

Also applies to: 144-144


🏁 Script executed:

#!/bin/bash
set -euo pipefail
# List all locale files missing either key
echo "Checking for missing 'badge__trialEndsAt'..."
rg -L --no-messages -n "badge__trialEndsAt" packages/localizations/src/*.ts | sed 's/:.*//' | sort -u > /tmp/has_trialEndsAt.txt || true
echo "Checking for missing 'startFreeTrial'..."
rg -L --no-messages -n "startFreeTrial" packages/localizations/src/*.ts | sed 's/:.*//' | sort -u > /tmp/has_startFreeTrial.txt || true

ls packages/localizations/src/*.ts | sort -u > /tmp/all_locales.txt

echo "Locales missing badge__trialEndsAt:"
comm -23 /tmp/all_locales.txt /tmp/has_trialEndsAt.txt || true
echo
echo "Locales missing commerce.startFreeTrial:"
comm -23 /tmp/all_locales.txt /tmp/has_startFreeTrial.txt || true

Length of output: 6275


To handle the missing comm utility in the sandbox, let’s directly list locales missing each key using rg -L:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Locales missing badge__trialEndsAt:"
rg -L "badge__trialEndsAt" packages/localizations/src/*.ts || true

echo
echo "Locales missing startFreeTrial:"
rg -L "startFreeTrial" packages/localizations/src/*.ts || true

Length of output: 4024


To get an accurate list of missing translations (excluding the index.ts file), let’s re-run the audit and filter out index.ts:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Locales missing 'badge__trialEndsAt' (excluding index.ts):"
rg -L "badge__trialEndsAt" packages/localizations/src/*.ts | grep -v "index.ts" || true

echo
echo "Locales missing 'startFreeTrial' (excluding index.ts):"
rg -L "startFreeTrial" packages/localizations/src/*.ts | grep -v "index.ts" || true

Length of output: 4166


Ensure new localization keys are added to every locale
en-US.ts already defines both entries. All other files in packages/localizations/src (excluding index.ts) are missing them—please add:

// At the top level (alongside other keys)
badge__trialEndsAt: "Trial ends {{ date | shortDate('en-US') }}",

// Under the commerce namespace
commerce: {,
  startFreeTrial: 'Start {{days}}-day free trial',
},

Apply this to every <locale>.ts file in packages/localizations/src except index.ts and en-US.ts so no locale falls back to English or has missing entries.

🤖 Prompt for AI Agents
In packages/localizations/src/en-US.ts at line 46, the localization keys
badge__trialEndsAt and commerce.startFreeTrial are defined, but these keys are
missing in all other locale files except index.ts and en-US.ts. To fix this, add
the badge__trialEndsAt key at the top level and the commerce.startFreeTrial key
inside the commerce namespace in every other locale file within
packages/localizations/src, ensuring no locale falls back to English or has
missing entries.

@panteliselef panteliselef marked this pull request as draft August 8, 2025 18:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants