Skip to content

feat(backend): Add cancelSubscriptionItem to BillingApi #6611

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

panteliselef
Copy link
Member

@panteliselef panteliselef commented Aug 22, 2025

Description

While implementing this addition I discovered that our BAPI endpoints return different payloads than the ones consumed by our webhook events. Thus I had to I renamed the existing ones by adding *WebhookEvent* in their names.

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
    • Add ability to cancel a subscription item in Billing (optional immediate cancellation).
    • Introduce a CommerceSubscriptionItem resource.
  • Webhooks
    • Commerce webhook events now use richer, dedicated payloads; subscription events include detailed subscription item data.
  • Improvements
    • CommerceMoneyAmount type is now publicly available for reuse.
  • Breaking Changes
    • Older JSON-based commerce types removed from public exports; use the new webhook event types instead.
  • Chores
    • Minor version bump for @clerk/backend.

@panteliselef panteliselef requested review from mauricioabreu and a team August 22, 2025 18:13
@panteliselef panteliselef self-assigned this Aug 22, 2025
Copy link

changeset-bot bot commented Aug 22, 2025

🦋 Changeset detected

Latest commit: 5115fe6

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

This PR includes changesets to release 11 packages
Name Type
@clerk/backend Minor
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing 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 22, 2025

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

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Aug 22, 2025 7:33pm

Copy link
Contributor

coderabbitai bot commented Aug 22, 2025

📝 Walkthrough

Walkthrough

Adds a new BillingApi method cancelSubscriptionItem with optional endNow param, issuing DELETE to /commerce/subscription_items/{id} and returning CommerceSubscriptionItem. Introduces CommerceSubscriptionItem resource with fromJSON mapper, exports it, and wires it into Deserializer. Expands and revises commerce JSON types: adds CommerceSubscriptionItemJSON fields; introduces webhook-specific JSON types for subscription, payment attempt, and subscription item; updates Webhooks type aliases to use these. Exports updated webhook event types and removes prior JSON exports from the public index. Exports CommerceMoneyAmount and CommerceSubscriptionItem from resources. Adds a changeset for a minor version bump.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 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

pkg-pr-new bot commented Aug 22, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 5115fe6

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

🧹 Nitpick comments (9)
packages/backend/src/api/resources/CommercePlan.ts (1)

4-9: Avoid duplicating CommerceMoneyAmount; alias the source type and add JSDoc.

This locally redefined type can drift from @clerk/types. Prefer a single source of truth by aliasing the upstream interface and documenting the public export.

Apply this diff:

-export type CommerceMoneyAmount = {
-  amount: number;
-  amountFormatted: string;
-  currency: string;
-  currencySymbol: 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 to avoid breaking changes.
+ */
+export type CommerceMoneyAmount = import('@clerk/types').CommerceMoneyAmount;
packages/backend/src/api/resources/Deserializer.ts (1)

187-188: Add deserialization case — consider adding unit tests to lock behavior.

The new case correctly maps ObjectType.CommerceSubscriptionItem to CommerceSubscriptionItem.fromJSON. Please add tests that:

  • Verify single-item deserialization.
  • Verify list/paginated payloads with mixed object types still work.

I can draft Jest tests for jsonToObject and deserialize covering subscription item payloads if helpful.

packages/backend/src/api/endpoints/BillingApi.ts (1)

15-21: Update JSDoc and Confirm Query Param Casing

  • Added a JSDoc on the CancelSubscriptionItemParams type to mirror other endpoint-level typedefs.
  • No manual snake_case mapping is required: the HTTP layer uses snakecase-keys to convert all queryParams keys (e.g. endNowend_now) before appending them to the URL.
--- a/packages/backend/src/api/endpoints/BillingApi.ts
+++ b/packages/backend/src/api/endpoints/BillingApi.ts
@@ -12,6 +12,11 @@
 type CancelSubscriptionItemParams = {
   /**
    * If true, the subscription item will be canceled immediately. If false or undefined, the subscription item will be canceled at the end of the current billing period.
    * @default undefined
    */
   endNow?: boolean;
 };

+/**
+ * Parameters for canceling a subscription item.
+ *
+ * The `endNow` field is automatically converted to `end_now` at the HTTP layer.
+ */
 type CancelSubscriptionItemParams = {
   /**
    * If true, the subscription item will be canceled immediately. If false or undefined, the subscription item will be canceled at the end of the current billing period.
    * @default undefined
    */
   endNow?: boolean;
 };
packages/backend/src/api/resources/CommerceSubscriptionItem.ts (2)

25-28: Clarify timestamp units in JSDoc (seconds vs. milliseconds)

periodStart, periodEnd, canceledAt, pastDueAt are numbers; the unit isn’t stated. Elsewhere we use Unix epoch seconds. Add “Unix epoch seconds” to avoid ambiguity for integrators.

Also applies to: 48-55, 58-58


1-4: Optional: avoid coupling to @clerk/types for JSON money shape

CommercePlan.ts derives the money shape from CommercePlanJSON['fee'] and avoids direct imports from @clerk/types. For consistency and to reduce cross-package coupling, consider using CommerceSubscriptionItemJSON['amount']/['lifetime_paid'] in the formatter signature rather than importing CommerceMoneyAmountJSON.

If you take this path:

-import type { CommerceMoneyAmountJSON } from '@clerk/types';
+// Rely on local JSON shape to avoid external type coupling
+// (no extra import needed)

And change the function signature to:

function formatAmountJSON(
  amount: NonNullable<CommerceSubscriptionItemJSON['amount']> | null,
): CommerceMoneyAmount | null { ... }
packages/backend/src/api/resources/Webhooks.ts (1)

78-89: SubscriptionItem webhook events: confirm full event taxonomy

We include created/updated/active/canceled/upcoming/ended/abandoned/incomplete/past_due. If 'expired' is a possible event (status exists), confirm whether it should be included or is intentionally omitted.

If needed:

   | 'subscriptionItem.past_due',
+  | 'subscriptionItem.expired',

Also consider adding a short JSDoc note above each new type to help SDK consumers discover the new shapes.

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

846-855: Centralize and export CommerceSubscriptionItemStatus if referenced externally

The status union looks right. If SDK consumers need to narrow against these statuses, consider re-exporting this type from the package’s public surface (or document the intended import path). Otherwise, keep it internal.


881-919: Webhook item plan shape diverges from CommercePlanJSON by design — consider a named alias

Embedding a bespoke plan object is fine (webhook vs. BAPI shapes differ), but consider introducing a named alias (e.g., CommerceWebhookPlanJSON) and reusing it across webhook types to avoid duplication and ease future changes.


920-954: CommercePaymentAttemptWebhookEventJSON: webhook item collection rename

subscription_items: CommerceSubscriptionItemWebhookEventJSON[] is clear. If older consumers used items, a migration note in the changelog would help. Otherwise, LGTM.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 44a191f and 67f538a.

📒 Files selected for processing (9)
  • .changeset/eight-sheep-matter.md (1 hunks)
  • packages/backend/src/api/endpoints/BillingApi.ts (3 hunks)
  • packages/backend/src/api/resources/CommercePlan.ts (1 hunks)
  • packages/backend/src/api/resources/CommerceSubscriptionItem.ts (1 hunks)
  • packages/backend/src/api/resources/Deserializer.ts (2 hunks)
  • packages/backend/src/api/resources/JSON.ts (4 hunks)
  • packages/backend/src/api/resources/Webhooks.ts (3 hunks)
  • packages/backend/src/api/resources/index.ts (1 hunks)
  • packages/backend/src/index.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/backend/src/api/resources/index.ts
  • packages/backend/src/api/resources/Deserializer.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/backend/src/api/endpoints/BillingApi.ts
  • packages/backend/src/index.ts
  • packages/backend/src/api/resources/CommerceSubscriptionItem.ts
  • packages/backend/src/api/resources/Webhooks.ts
  • packages/backend/src/api/resources/JSON.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/index.ts
  • packages/backend/src/api/resources/Deserializer.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/backend/src/api/endpoints/BillingApi.ts
  • packages/backend/src/index.ts
  • packages/backend/src/api/resources/CommerceSubscriptionItem.ts
  • packages/backend/src/api/resources/Webhooks.ts
  • packages/backend/src/api/resources/JSON.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/backend/src/api/resources/index.ts
  • packages/backend/src/api/resources/Deserializer.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/backend/src/api/endpoints/BillingApi.ts
  • packages/backend/src/index.ts
  • packages/backend/src/api/resources/CommerceSubscriptionItem.ts
  • packages/backend/src/api/resources/Webhooks.ts
  • packages/backend/src/api/resources/JSON.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/index.ts
  • packages/backend/src/api/resources/Deserializer.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/backend/src/api/endpoints/BillingApi.ts
  • packages/backend/src/index.ts
  • packages/backend/src/api/resources/CommerceSubscriptionItem.ts
  • packages/backend/src/api/resources/Webhooks.ts
  • packages/backend/src/api/resources/JSON.ts
packages/**/index.{js,ts}

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

Use tree-shaking friendly exports

Files:

  • packages/backend/src/api/resources/index.ts
  • packages/backend/src/index.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/index.ts
  • packages/backend/src/api/resources/Deserializer.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/backend/src/api/endpoints/BillingApi.ts
  • packages/backend/src/index.ts
  • packages/backend/src/api/resources/CommerceSubscriptionItem.ts
  • packages/backend/src/api/resources/Webhooks.ts
  • packages/backend/src/api/resources/JSON.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/index.ts
  • packages/backend/src/api/resources/Deserializer.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/backend/src/api/endpoints/BillingApi.ts
  • packages/backend/src/index.ts
  • packages/backend/src/api/resources/CommerceSubscriptionItem.ts
  • packages/backend/src/api/resources/Webhooks.ts
  • packages/backend/src/api/resources/JSON.ts
**/index.ts

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

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

  • packages/backend/src/api/resources/index.ts
  • packages/backend/src/index.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/index.ts
  • packages/backend/src/api/resources/Deserializer.ts
  • packages/backend/src/api/resources/CommercePlan.ts
  • packages/backend/src/api/endpoints/BillingApi.ts
  • packages/backend/src/index.ts
  • packages/backend/src/api/resources/CommerceSubscriptionItem.ts
  • packages/backend/src/api/resources/Webhooks.ts
  • packages/backend/src/api/resources/JSON.ts
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/eight-sheep-matter.md
🧬 Code graph analysis (6)
packages/backend/src/api/resources/Deserializer.ts (3)
packages/backend/src/api/resources/JSON.ts (2)
  • ObjectType (19-74)
  • ObjectType (76-76)
packages/backend/src/api/resources/CommerceSubscriptionItem.ts (1)
  • CommerceSubscriptionItem (10-99)
packages/backend/src/index.ts (1)
  • CommerceSubscriptionItem (147-147)
packages/backend/src/api/resources/CommercePlan.ts (1)
packages/types/src/commerce.ts (1)
  • CommerceMoneyAmount (1207-1244)
packages/backend/src/api/endpoints/BillingApi.ts (2)
packages/backend/src/api/resources/CommerceSubscriptionItem.ts (1)
  • CommerceSubscriptionItem (10-99)
packages/backend/src/index.ts (1)
  • CommerceSubscriptionItem (147-147)
packages/backend/src/api/resources/CommerceSubscriptionItem.ts (3)
packages/backend/src/api/resources/JSON.ts (1)
  • CommerceSubscriptionItemJSON (860-876)
packages/backend/src/api/resources/CommercePlan.ts (2)
  • CommerceMoneyAmount (4-9)
  • CommercePlan (15-101)
packages/types/src/json.ts (1)
  • CommerceMoneyAmountJSON (834-839)
packages/backend/src/api/resources/Webhooks.ts (1)
packages/backend/src/api/resources/JSON.ts (3)
  • CommercePaymentAttemptWebhookEventJSON (923-954)
  • CommerceSubscriptionWebhookEventJSON (959-973)
  • CommerceSubscriptionItemWebhookEventJSON (881-918)
packages/backend/src/api/resources/JSON.ts (1)
packages/types/src/json.ts (4)
  • CommerceSubscriptionItemJSON (773-794)
  • ClerkResourceJSON (36-40)
  • CommerceMoneyAmountJSON (834-839)
  • CommercePlanJSON (632-658)
⏰ 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). (23)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Static analysis
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (10)
.changeset/eight-sheep-matter.md (1)

1-6: No webhook JSON type exports changed—minor bump is correct

I’ve verified that there are no added or removed *JSON type exports in packages/backend/src/api/resources/Webhooks.ts or JSON.ts compared to main. There are no webhook JSON type renames or removals, so this change is non-breaking and the minor version bump remains appropriate.

packages/backend/src/api/resources/index.ts (1)

61-61: LGTM: public export for CommerceSubscriptionItem.

Re-export aligns with the rest of the resources barrel and keeps import ergonomics consistent. Watch for circulars, but importing the class directly in Deserializer avoids that.

packages/backend/src/api/resources/Deserializer.ts (1)

41-41: Correct choice: direct class import avoids barrel cycles.

Importing CommerceSubscriptionItem from its module (not the barrel) prevents potential circular deps during deserialization.

packages/backend/src/api/endpoints/BillingApi.ts (1)

5-5: Type-only import is correct.

Using a type-only import for the return model avoids accidental runtime dependencies.

packages/backend/src/index.ts (1)

147-148: Exporting CommerceSubscriptionItem from resources looks good

Publicly surfacing the runtime class aligns with the new cancelSubscriptionItem response shape and keeps parity with CommercePlan.

packages/backend/src/api/resources/CommerceSubscriptionItem.ts (1)

84-97: Deserializer mapping LGTM with the tightened types

The field mapping matches the new JSON contract and uses CommercePlan.fromJSON correctly. After applying the type fixes above, this constructor stays valid.

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

68-71: PaymentAttempt webhook now references webhook-specific JSON — good

The generic event wrapper remains unchanged; switching to CommercePaymentAttemptWebhookEventJSON aligns types with the new payload.


73-76: Subscription webhook JSON type switch looks correct

Using CommerceSubscriptionWebhookEventJSON for subscription.* events matches the revised payload shape.

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

860-876: CommerceSubscriptionItemJSON shape: confirm lifetime_paid non-nullability across BAPI

This defines lifetime_paid as a required money object (non-null). That’s preferable; just ensure all BAPI responses indeed include it (including free plans). If not, either make it nullable or guarantee a zero-amount money value.


959-973: CommerceSubscriptionWebhookEventJSON: items now typed to webhook item JSON — good

This aligns the nested shape with the new webhook-specific item contract.

Comment on lines +36 to +47
/**
* @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 to avoid breaking changes.
*/
public async cancelSubscriptionItem(subscriptionItemId: string, params?: CancelSubscriptionItemParams) {
this.requireId(subscriptionItemId);
return this.request<CommerceSubscriptionItem>({
method: 'DELETE',
path: joinPaths(basePath, 'subscription_items', subscriptionItemId),
queryParams: params,
});
}
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

Explicit return type required for public API; also ensure endNow is serialized as end_now.

  • Per guidelines, public APIs must have explicit return types.
  • Unless the transport transforms query params, end_now is likely the server-expected shape. Pass a mapped object.

Apply this diff:

   /**
    * @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 to avoid breaking changes.
    */
-  public async cancelSubscriptionItem(subscriptionItemId: string, params?: CancelSubscriptionItemParams) {
+  public async cancelSubscriptionItem(
+    subscriptionItemId: string,
+    params?: CancelSubscriptionItemParams,
+  ): Promise<CommerceSubscriptionItem> {
     this.requireId(subscriptionItemId);
-    return this.request<CommerceSubscriptionItem>({
+    const queryParams =
+      params && typeof params.endNow !== 'undefined'
+        ? { end_now: params.endNow }
+        : undefined;
+    return this.request<CommerceSubscriptionItem>({
       method: 'DELETE',
       path: joinPaths(basePath, 'subscription_items', subscriptionItemId),
-      queryParams: params,
+      queryParams,
     });
   }

Optional: enrich JSDoc with param details and an example:

/**
 * Cancels a subscription item.
 * @param subscriptionItemId The subscription item id.
 * @param params Optional cancellation options. When `endNow` is true, cancellation is immediate; otherwise effective at period end.
 * @returns The updated CommerceSubscriptionItem.
 */

Also, please add tests that assert:

  • Path: /commerce/subscription_items/{id}
  • Query serialization: end_now=true|false
  • Response mapped to CommerceSubscriptionItem via Deserializer

I can provide a test stub using the existing request mock harness.

🤖 Prompt for AI Agents
In packages/backend/src/api/endpoints/BillingApi.ts around lines 36 to 47, the
public method cancelSubscriptionItem lacks an explicit return type and does not
serialize the params.endNow to the server-expected end_now query param; update
the method signature to declare an explicit return type
Promise<CommerceSubscriptionItem>, map params (e.g. const queryParams = params ?
{ end_now: params.endNow } : undefined) and pass that to request, and add the
suggested JSDoc block above the method; also add tests that assert the request
path is /commerce/subscription_items/{id}, that query serialization produces
end_now=true|false, and that the response is deserialized to
CommerceSubscriptionItem using the existing request mock harness.

Comment on lines +36 to +39
* The current amount for the subscription item.
*/
readonly amount: CommerceMoneyAmount | null | undefined,
/**
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

Narrow the amount type to match JSON (avoid undefined)

JSON shape defines amount: CommerceMoneyAmountJSON | null, not undefined. Allowing undefined here expands the public API unnecessarily and mismatches the deserializer contract.

Apply:

-    readonly amount: CommerceMoneyAmount | null | undefined,
+    readonly amount: CommerceMoneyAmount | 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
* The current amount for the subscription item.
*/
readonly amount: CommerceMoneyAmount | null | undefined,
/**
* The current amount for the subscription item.
*/
readonly amount: CommerceMoneyAmount | null,
/**
🤖 Prompt for AI Agents
In packages/backend/src/api/resources/CommerceSubscriptionItem.ts around lines
36–39, the `amount` field is typed as `CommerceMoneyAmount | null | undefined`,
which permits `undefined` but the JSON contract is `CommerceMoneyAmountJSON |
null`; remove `undefined` and narrow the type to match the JSON contract (i.e.,
use `CommerceMoneyAmountJSON | null`), and update any related
serializer/deserializer or callers to treat absent values as `null` per the JSON
shape.

Comment on lines +60 to +63
* The lifetime amount paid for this subscription item.
*/
readonly lifetimePaid?: CommerceMoneyAmount | null,
) {}
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

lifetimePaid should be required and non-null to match JSON

CommerceSubscriptionItemJSON.lifetime_paid is required and non-null. Making lifetimePaid optional (and nullable) diverges and forces extra undefined/null checks downstream.

Apply:

-    readonly lifetimePaid?: CommerceMoneyAmount | null,
+    readonly lifetimePaid: CommerceMoneyAmount,
📝 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
* The lifetime amount paid for this subscription item.
*/
readonly lifetimePaid?: CommerceMoneyAmount | null,
) {}
/**
* The lifetime amount paid for this subscription item.
*/
readonly lifetimePaid: CommerceMoneyAmount,
🤖 Prompt for AI Agents
In packages/backend/src/api/resources/CommerceSubscriptionItem.ts around lines
60 to 63, the lifetimePaid property is declared as optional and nullable but the
JSON model (CommerceSubscriptionItemJSON.lifetime_paid) is required and
non-null; change the class/property signature to make lifetimePaid required and
non-null (remove the "?" and "| null"), update any constructor parameters and
assignments to expect a non-null CommerceMoneyAmount, and adjust
parsing/serialization code to validate and map
CommerceSubscriptionItemJSON.lifetime_paid into this required property (throw or
surface an error if the JSON field is missing/null).

Comment on lines +66 to +83
function formatAmountJSON(
amount: CommerceMoneyAmountJSON | null | undefined,
): CommerceMoneyAmount | null | undefined;
function formatAmountJSON(
amount: CommerceMoneyAmountJSON | null | undefined,
): CommerceMoneyAmount | null | undefined {
if (!amount) {
return amount;
}

return {
amount: amount.amount,
amountFormatted: amount.amount_formatted,
currency: amount.currency,
currencySymbol: amount.currency_symbol,
};
}

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

Simplify and type the amount formatter overloads precisely

  • The current overload is redundant and permits undefined which the JSON never returns.
  • Tighten types and keep one public overload for nullability plus a concrete implementation.

Apply:

-    function formatAmountJSON(
-      amount: CommerceMoneyAmountJSON | null | undefined,
-    ): CommerceMoneyAmount | null | undefined;
-    function formatAmountJSON(
-      amount: CommerceMoneyAmountJSON | null | undefined,
-    ): CommerceMoneyAmount | null | undefined {
-      if (!amount) {
-        return amount;
-      }
-
-      return {
-        amount: amount.amount,
-        amountFormatted: amount.amount_formatted,
-        currency: amount.currency,
-        currencySymbol: amount.currency_symbol,
-      };
-    }
+    function formatAmountJSON(amount: CommerceMoneyAmountJSON): CommerceMoneyAmount;
+    function formatAmountJSON(amount: CommerceMoneyAmountJSON | null): CommerceMoneyAmount | null;
+    function formatAmountJSON(amount: CommerceMoneyAmountJSON | null): CommerceMoneyAmount | null {
+      if (amount === null) {
+        return null;
+      }
+      return {
+        amount: amount.amount,
+        amountFormatted: amount.amount_formatted,
+        currency: amount.currency,
+        currencySymbol: amount.currency_symbol,
+      };
+    }

And adjust the constructor call sites accordingly (type inference will keep lifetimePaid non-null while allowing amount to be 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
function formatAmountJSON(
amount: CommerceMoneyAmountJSON | null | undefined,
): CommerceMoneyAmount | null | undefined;
function formatAmountJSON(
amount: CommerceMoneyAmountJSON | null | undefined,
): CommerceMoneyAmount | null | undefined {
if (!amount) {
return amount;
}
return {
amount: amount.amount,
amountFormatted: amount.amount_formatted,
currency: amount.currency,
currencySymbol: amount.currency_symbol,
};
}
function formatAmountJSON(amount: CommerceMoneyAmountJSON): CommerceMoneyAmount;
function formatAmountJSON(amount: CommerceMoneyAmountJSON | null): CommerceMoneyAmount | null;
function formatAmountJSON(amount: CommerceMoneyAmountJSON | null): CommerceMoneyAmount | null {
if (amount === null) {
return null;
}
return {
amount: amount.amount,
amountFormatted: amount.amount_formatted,
currency: amount.currency,
currencySymbol: amount.currency_symbol,
};
}
🤖 Prompt for AI Agents
In packages/backend/src/api/resources/CommerceSubscriptionItem.ts around lines
66 to 83, the amount formatter currently has a redundant overload that allows
undefined (which the JSON never returns) and duplicates the signature; replace
both overloads with a single exported function signature that accepts
CommerceMoneyAmountJSON | null (no undefined) and returns CommerceMoneyAmount |
null, keep a single concrete implementation that handles null and maps amount,
amount_formatted, currency, currency_symbol to the camelCased fields, and then
update all constructor/call sites to pass non-undefined JSON (or null) so type
inference keeps fields like lifetimePaid non-null while still allowing amount to
be null.

Comment on lines +167 to 170
CommercePaymentAttemptWebhookEvent,
CommerceSubscriptionWebhookEvent,
CommerceSubscriptionItemWebhookEvent,
} from './api/resources/Webhooks';
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

Webhook event type re-exports: verify event set coverage and SemVer impact

  • Coverage: Do we intentionally omit a 'subscriptionItem.expired' event even though 'expired' exists in CommerceSubscriptionItemStatus? If 'expired' is a real webhook type, consider adding it to the union for completeness; if it’s not emitted, we’re good. Please confirm with BAPI/webhook docs.
  • SemVer: This PR also removes previously exported JSON types (e.g., CommerceSubscriptionJSON, CommercePaymentAttemptJSON, CommercePayerJSON) from the public surface. If those were published before, that’s a breaking change. Consider shipping deprecation aliases for one release cycle or bumping major.

Proposed non-breaking aliases (deprecate old names, point to new webhook-specific JSONs):

+/**
+ * @deprecated Use CommerceSubscriptionWebhookEventJSON instead. Will be removed in the next major.
+ */
+export type {
+  CommerceSubscriptionWebhookEventJSON as CommerceSubscriptionJSON,
+  CommercePaymentAttemptWebhookEventJSON as CommercePaymentAttemptJSON,
+} from './api/resources/JSON';
+
+/**
+ * @deprecated This type is still referenced by webhook JSON payloads, but we no longer recommend importing it from the backend package.
+ * Consider removing in the next major.
+ */
+export type { CommercePayerJSON } from './api/resources/JSON';

To check for potential breakages in consumers inside this repo:


🏁 Script executed:

#!/bin/bash
# Find usages of removed type names across the monorepo
rg -nP -C2 '\b(CommerceSubscriptionJSON|CommercePaymentAttemptJSON|CommercePayerJSON)\b'

Length of output: 5038


SemVer-breaking removal of JSON types – deprecate or bump major

Confirmed that the following JSON interfaces are still referenced across the monorepo (in packages/types, packages/backend, and packages/clerk-js), so removing their re-exports from the public surface will be a breaking change:

  • CommerceSubscriptionJSON (used to describe top-level subscriptions)
  • CommercePaymentAttemptJSON
  • CommercePayerJSON

Please address this before merging by either:

  • Shipping one release with deprecation aliases, pointing the old names to the new JSON types, then removing them in the next major; or
  • Bumping the major version immediately to acknowledge the breaking change.

Locations to update (in packages/backend/src/index.ts):

  • After the existing export { … } from './api/resources/Webhooks'; block

Suggested deprecation alias diff:

 // keep existing webhook re-exports
 export {
   CommercePaymentAttemptWebhookEvent,
   CommerceSubscriptionWebhookEvent,
   CommerceSubscriptionItemWebhookEvent,
 } from './api/resources/Webhooks';

+/**
+ * @deprecated Use CommerceSubscriptionWebhookEventJSON instead. Will be removed in the next major.
+ */
+export type {
+  CommerceSubscriptionWebhookEventJSON as CommerceSubscriptionJSON,
+  CommercePaymentAttemptWebhookEventJSON as CommercePaymentAttemptJSON,
+} from './api/resources/JSON';
+
+/**
+ * @deprecated Use CommercePayerWebhookEventJSON instead. Will be removed in the next major.
+ */
+export type { CommercePayerJSON } from './api/resources/JSON';

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

🤖 Prompt for AI Agents
In packages/backend/src/index.ts around lines 167 to 170, the public re-exports
removed the CommerceSubscriptionJSON, CommercePaymentAttemptJSON, and
CommercePayerJSON types which are still referenced elsewhere; restore
compatibility by adding deprecation aliases that re-export the old names
pointing to the new JSON types (add export statements for
CommerceSubscriptionJSON, CommercePaymentAttemptJSON, CommercePayerJSON that
forward to the current types and mark them with a deprecated JSDoc comment),
commit that change for a deprecation release, or alternatively, if you intend to
remove them now, bump the package major version to reflect the breaking change.

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

Successfully merging this pull request may close these issues.

4 participants