-
Couldn't load subscription status.
- Fork 402
feat(clerk-js,types,shared): Infer resource in checkout.confirm()
#6642
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
feat(clerk-js,types,shared): Infer resource in checkout.confirm()
#6642
Conversation
🦋 Changeset detectedLatest commit: 716c373 The changes in this PR will be included in the next version bump. This PR includes changesets to release 22 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughThis PR removes the orgId parameter from checkout.confirm(), infers organization from a new CommercePayer on the checkout, adds CommercePayer resources and types, updates CommerceCheckout construction and confirm path resolution, and adjusts billing module, hook defaults, and UI to call confirm() without orgId. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor App
participant Billing as Billing Module
participant Checkout as CommerceCheckout
participant API as Clerk API
App->>Billing: startCheckout({ orgId })
Billing-->>App: CommerceCheckout (contains payer with organizationId)
note right of App: orgId captured in payer, not passed to confirm
App->>Checkout: confirm(params)
alt payer.organizationId present
Checkout->>API: POST /organizations/{orgId}/billing/checkouts/{id}/confirm
else no organizationId
Checkout->>API: POST /me/billing/checkouts/{id}/confirm
end
API-->>Checkout: 200/response
Checkout-->>App: Promise<void>
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. 📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
✨ Finishing Touches🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (13)
.changeset/proud-walls-travel.md (3)
2-5: Sanity-check semver level vs. API surface changeIf existing apps commonly call
checkout.confirm({ orgId }), removing that parameter from the public TS type would be a source-incompatible change and should be a major bump. If the old shape is still accepted (ignored/deprecated) and the new zero-arg call is additive, a minor bump is fine. Please confirm which of the two applies and adjust the bump notes accordingly (and consider adding a brief deprecation note if backward-compatible).
9-19: Make the examples consistent and more precise
- Use consistent casing for the root object (
Clerkvsclerk) across “Before/After”. Pick the one that matches your docs (globalClerkor instanceclerk) and stick to it.- Add colons after “After”/“Before”.
- Clarify the comment to say that
orgIdis inferred (from payer), not just “implied”.Proposed edits (assuming the global
Clerkform is correct—adjust toclerkif that’s your canonical usage):-After +After: ```tsx -const checkout = Clerk.billing.startCheckout({orgId}) -checkout.confirm() // orgId is always implied +const checkout = Clerk.billing.startCheckout({ orgId }); +checkout.confirm(); // orgId is inferred from the checkout’s payer-Before
+Before:-const checkout = clerk.billing.startCheckout({orgId}) -checkout.confirm({orgId}) +const checkout = Clerk.billing.startCheckout({ orgId }); +checkout.confirm({ orgId });If the instance form (`clerk`) is the canonical usage in your SDK docs, swap `Clerk` → `clerk` in both snippets. --- `9-19`: **Add a short migration note to reduce churn** Consider appending a “Migration” section to the changeset with one-liners for users skimming release notes. Suggested addition: ```diff +Migration: +- Replace `checkout.confirm({ orgId })` with `checkout.confirm()`. +- Ensure the `orgId` you pass to `startCheckout({ orgId })` matches the payer’s organization; `confirm()` now derives the resource from `checkout.payer`. +- If you still call `confirm({ orgId })`, it will ${kept ? 'continue to work but is deprecated' : 'no longer type-check'}.Please tune the last bullet to reflect the actual backward-compat story.
packages/types/src/json.ts (1)
901-917: Align CommercePayerJSON with backend DTO or annotate divergenceThere are notable differences vs backend JSON (see packages/backend/src/api/resources/JSON.ts):
instance_idexists and is required in backend but is missing here.image_urlis non-nullable in backend but nullable here.If the runtime layer doesn’t rely on these fields, this is harmless; otherwise it risks drift. Prefer matching the backend DTO and relaxing at the resource layer if needed.
Apply this minimal, non-breaking alignment (keep looser nullability to avoid forced changes, but surface the field to avoid silent drift):
export interface CommercePayerJSON extends ClerkResourceJSON { object: 'commerce_payer'; id: string; created_at: number; updated_at: number; image_url: string | null; // User attributes user_id?: string; - email?: string; + email?: string; first_name?: string; last_name?: string; // Organization attributes organization_id?: string; organization_name?: string; + /** + * Backend emits instance_id; exposed for completeness, not used in clients. + */ + instance_id?: string; }If this divergence is intentional (public/SDK JSON vs backend-internal JSON), please add a short comment noting the contract.
packages/types/src/commerce.ts (2)
1359-1410: ConfirmCheckoutParams is too permissive; enforce mutually exclusive modesEach union member’s properties are optional, so
{}is currently valid, and callers can accidentally mix modes (e.g.,paymentToken+useTestCard). This weakens type-safety on a public API. Recommend an XOR style with required keys per mode.Proposed stricter, backwards-compatible typing (disallows empty/mixed payloads):
-export type ConfirmCheckoutParams = - | { - /** - * @experimental ... - */ - paymentSourceId?: string; - } - | { - /** - * @experimental ... - */ - paymentToken?: string; - /** - * @experimental ... - */ - gateway?: PaymentGateway; - } - | { - /** - * @experimental ... - */ - gateway?: PaymentGateway; - /** - * @experimental ... - */ - useTestCard?: boolean; - }; +export type ConfirmCheckoutParams = + | { + /** + * Use an existing payment source by id. + */ + paymentSourceId: string; + paymentToken?: never; + gateway?: never; + useTestCard?: never; + } + | { + /** + * Use a new payment method via token from the specified gateway. + */ + paymentToken: string; + gateway: PaymentGateway; + paymentSourceId?: never; + useTestCard?: never; + } + | { + /** + * Use a test card via the specified gateway. + */ + gateway: PaymentGateway; + useTestCard: true; + paymentSourceId?: never; + paymentToken?: never; + };If tightening types right now is risky for downstreams, at minimum add JSDoc warnings that exactly one mode must be provided.
1532-1631: CommercePayerResource shape looks good; confirm parity with JSON and consider future-proofingThe resource fields mirror
CommercePayerJSONand useDatewhere appropriate. Two follow-ups:
- Confirm the mapper handles optional
imageUrlconsistently and thatorganizationId/organizationNameare only present for org payers.- Consider adding a small
typediscriminator (e.g.,payerType: 'org' | 'user') at the resource level for ergonomics, derived from plan or presence oforganizationId. This can be deferred.packages/clerk-js/src/core/resources/CommerceCheckout.ts (4)
29-29: Clarify payer nullability and make confirm path resolution resilientThere’s an implicit assumption that
payeris always present and non-null. However, related changes (e.g., UI hook defaultingpayerto null) suggestpayermay be absent at certain stages. Accessingthis.payer.organizationIdwould then throw.Two safe paths—pick one and align types across packages:
- Option A (enforce invariant): Fail fast if
data.payeris missing. Keeps current public shape intact.- Option B (nullable): Allow
payerto be null and guard inconfirm.If you choose Option B, apply this localized refactor:
- payer!: CommercePayerResource; + payer!: CommercePayerResource | null;- this.payer = new CommercePayer(data.payer); + this.payer = data.payer ? new CommercePayer(data.payer) : null;- path: this.payer.organizationId + path: this.payer?.organizationId ? `/organizations/${this.payer.organizationId}/commerce/checkouts/${this.id}/confirm` : `/me/commerce/checkouts/${this.id}/confirm`,If you prefer Option A, add:
+ if (!data.payer) { + throw new Error('Checkout payload missing payer; cannot infer resource for confirmation.'); + } + this.payer = new CommercePayer(data.payer);I can follow up with a types audit to ensure
CommerceCheckoutJSON['payer']andCommerceCheckoutResource['payer']match the chosen invariant.Also applies to: 52-53, 63-65
63-66: Replaceas anywith precise typing and extract path builder for testability
- Casting
paramstoanyweakens type safety againstConfirmCheckoutParams.- Building the confirm path inline makes it harder to unit-test and reuse.
Apply:
- body: params as any, + body: params as ConfirmCheckoutParams,Optionally extract a helper for path construction:
+ private getConfirmPath(): string { + const orgId = this.payer?.organizationId; + return orgId + ? `/organizations/${orgId}/commerce/checkouts/${this.id}/confirm` + : `/me/commerce/checkouts/${this.id}/confirm`; + }- path: this.payer?.organizationId - ? `/organizations/${this.payer.organizationId}/commerce/checkouts/${this.id}/confirm` - : `/me/commerce/checkouts/${this.id}/confirm`, + path: this.getConfirmPath(),Bonus: consider retrying on 429 with respect to
Retry-Afterwhen available.
57-60: Sync retry comments with implementation and consider 429The comment says “retry up to 3 times” and lists 2s, 4s, 6s, 8s, which is 4 retries. The guard
iterations >= 4suggests 4 retries. Please reconcile the comment with behavior. Also consider including 429 handling with backoff since confirmation can be rate-limited.Also applies to: 74-85
31-34: No outdated CommerceCheckout usages found; please add constructor JSDocI’ve verified that all existing call sites use the new single‐argument constructor and that there are no lingering
orgIdparameters:
- Only usage of
new CommerceCheckout(json)is in
packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts:157- No occurrences of
checkout.confirm({... orgId ...})in.ts/.tsxfilesNext, let’s document the constructor’s behavior. Here’s a suggested JSDoc snippet to add immediately above the constructor in
packages/clerk-js/src/core/resources/CommerceCheckout.ts:/** + * Instantiate a CommerceCheckout resource from its JSON representation. + * + * @param data - Raw `CommerceCheckoutJSON` payload. + * + * @remarks + * The organization ID is automatically inferred from `payer.organizationId`. + * If no organization is found on the payer, the resource will default to `/me`. + */ constructor(data: CommerceCheckoutJSON) { super(); this.fromJSON(data); }Let me know if you’d like any tweaks to the wording or additional examples.
packages/clerk-js/src/core/resources/CommercePayer.ts (3)
19-22: Constructor should accept nullable JSON to match fromJSON and callers
fromJSONalready handlesnull, but the constructor enforces a non-null JSON. Allownullfor symmetry and safer calls from resources that may receive incomplete payloads.Apply:
- constructor(data: CommercePayerJSON) { + constructor(data: CommercePayerJSON | null) { super(); this.fromJSON(data); }If the API guarantees
payeris always present, alternatively keep as-is and add a runtime assert in callers. Otherwise, prefer this change.
24-40: Defensive parsing for timestamps and JSDoc for public fields
- If
created_at/updated_atcan ever be absent,unixEpochToDate(undefined)may yield an invalidDate. Either assert presence or make these fields nullable and guard.- Add JSDoc on the class and fields—this is a public API surface and guidelines require JSDoc.
Apply defensiveness if needed:
- this.createdAt = unixEpochToDate(data.created_at); - this.updatedAt = unixEpochToDate(data.updated_at); + this.createdAt = data.created_at ? unixEpochToDate(data.created_at) : new Date(0); + this.updatedAt = data.updated_at ? unixEpochToDate(data.updated_at) : new Date(0);I can also draft JSDoc (purpose, fields, and examples) if helpful.
7-17: Consider marking immutable identity fields as readonly (if objects aren’t rehydrated)If instances aren’t re-used via
fromJSONafter construction,id,createdAt, andupdatedAtcan bereadonlyto reflect immutability. If rehydration is common in your resource layer, skip this.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (8)
.changeset/proud-walls-travel.md(1 hunks)packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts(1 hunks)packages/clerk-js/src/core/resources/CommerceCheckout.ts(3 hunks)packages/clerk-js/src/core/resources/CommercePayer.ts(1 hunks)packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx(2 hunks)packages/shared/src/react/hooks/useCheckout.ts(1 hunks)packages/types/src/commerce.ts(3 hunks)packages/types/src/json.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/types/src/json.tspackages/clerk-js/src/core/modules/commerce/CommerceBilling.tspackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/core/resources/CommercePayer.tspackages/shared/src/react/hooks/useCheckout.tspackages/clerk-js/src/core/resources/CommerceCheckout.tspackages/types/src/commerce.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/types/src/json.tspackages/clerk-js/src/core/modules/commerce/CommerceBilling.tspackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/core/resources/CommercePayer.tspackages/shared/src/react/hooks/useCheckout.tspackages/clerk-js/src/core/resources/CommerceCheckout.tspackages/types/src/commerce.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/types/src/json.tspackages/clerk-js/src/core/modules/commerce/CommerceBilling.tspackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/core/resources/CommercePayer.tspackages/shared/src/react/hooks/useCheckout.tspackages/clerk-js/src/core/resources/CommerceCheckout.tspackages/types/src/commerce.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/types/src/json.tspackages/clerk-js/src/core/modules/commerce/CommerceBilling.tspackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/core/resources/CommercePayer.tspackages/shared/src/react/hooks/useCheckout.tspackages/clerk-js/src/core/resources/CommerceCheckout.tspackages/types/src/commerce.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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/types/src/json.tspackages/clerk-js/src/core/modules/commerce/CommerceBilling.tspackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/core/resources/CommercePayer.tspackages/shared/src/react/hooks/useCheckout.tspackages/clerk-js/src/core/resources/CommerceCheckout.tspackages/types/src/commerce.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/types/src/json.tspackages/clerk-js/src/core/modules/commerce/CommerceBilling.tspackages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsxpackages/clerk-js/src/core/resources/CommercePayer.tspackages/shared/src/react/hooks/useCheckout.tspackages/clerk-js/src/core/resources/CommerceCheckout.tspackages/types/src/commerce.ts
.changeset/**
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/proud-walls-travel.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/Checkout/CheckoutForm.tsx
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
🧬 Code graph analysis (2)
packages/types/src/json.ts (1)
packages/backend/src/api/resources/JSON.ts (2)
CommercePayerJSON(787-799)ClerkResourceJSON(78-87)
packages/types/src/commerce.ts (1)
packages/types/src/resource.ts (1)
ClerkResource(8-21)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: pr-title-lint
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (8)
packages/types/src/json.ts (1)
890-891: CommerceCheckout.payer Mapping Verified; Please Confirm API CoverageI’ve validated that the client-side handling of the new required
payerfield is wired up correctly, but the backend API still needs a manual check:• In packages/clerk-js/src/core/resources/CommerceCheckout.ts, the constructor calls
this.payer = new CommercePayer(data.payer);ensuring
data.payeris consumed with a non-null assertion.
• All instantiations ofnew CommerceCheckout(json)in packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts pass aCommerceCheckoutJSONpayload that must includepayer.
• The JSON type definition in packages/types/src/json.ts declaresexport interface CommerceCheckoutJSON { … payer: CommercePayerJSON; }making the property required in the shared types.
Action required: the repo does not contain the backend serializers, so please manually verify that both the start and confirm
commerce_checkoutendpoints always include a non-nullpayerfield in their responses. If any rollout window might omitpayer, consider reverting to an optional property or gating the change via versioned DTOs to avoid breaking consumers.packages/types/src/commerce.ts (1)
1521-1530: Adding payer to CommerceCheckoutResource: LGTMNon-null
payer: CommercePayerResourcehere keeps runtime shape consistent with the JSON change. Ensure the constructor/resource mapper always instantiatespayer.packages/shared/src/react/hooks/useCheckout.ts (1)
116-116: Expose payer in the no-checkout fallback: LGTMIncluding
payer: nullkeeps the public shape stable. MatchesCheckoutPropertiesafter addingpayerto the resource.packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (2)
1-1: Import path change: OKSwitching to
@clerk/shared/reactforuseCheckoutis consistent with shared hook exposure. No issues spotted.
152-152: Confirm now omits orgId: ensure return type alignment and path resolutionCalling
confirm(params)without augmentingorgIdlooks correct with payer-based inference. However, the call expects{ data, error }whileCommerceCheckoutResource.confirm’s type isPromise<CommerceCheckoutResource>. IfuseCheckoutoverrides this to return a result envelope, ensure the public typing in__experimental_UseCheckoutReturnreflects that to avoid confusion for integrators. Also, confirm that the underlying resource resolves the correct confirm path fromcheckout.payer.packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts (1)
157-157: CommerceCheckout confirm path derivation is correctI’ve verified that:
- The
CommercePayerconstructor mapsdata.organization_idtothis.organizationId(see line 37 in CommercePayer.ts).- The
CommerceCheckoutconfirm()method checksthis.payer.organizationIdand uses
/organizations/${this.payer.organizationId}/…when present/me/…otherwise
(lines 63–65 in CommerceCheckout.ts).No changes are needed here.
packages/clerk-js/src/core/resources/CommerceCheckout.ts (1)
6-6: LGTM: Type-only import and concrete resource importThe
import type { CommercePayerResource }and concreteCommercePayerimport cleanly separate types vs values and align with the new inference model.Also applies to: 14-14
packages/clerk-js/src/core/resources/CommercePayer.ts (1)
1-6: Imports and base class usage look correctType-only import for shapes and
BaseResourceextension align with package conventions.
.changeset/proud-walls-travel.md
Outdated
| '@clerk/types': minor | ||
| --- | ||
|
|
||
| [Billing Beta] `checkout.confirm()` now infers the resource id resulting an less repetition and improved DX. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix grammar and clarify what is inferred
Minor copy edit and clarity: “resulting an less repetition” → “resulting in less repetition”; explicitly say “resource ID (orgId)” and “from the checkout’s payer”.
Apply:
-[Billing Beta] `checkout.confirm()` now infers the resource id resulting an less repetition and improved DX.
+[Billing Beta] `checkout.confirm()` now infers the resource ID (orgId) from the checkout’s payer, resulting in less repetition and improved DX.📝 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.
| [Billing Beta] `checkout.confirm()` now infers the resource id resulting an less repetition and improved DX. | |
| [Billing Beta] `checkout.confirm()` now infers the resource ID (orgId) from the checkout’s payer, resulting in less repetition and improved DX. |
🤖 Prompt for AI Agents
In .changeset/proud-walls-travel.md around line 7, fix the grammar and clarify
the inference description: change “resulting an less repetition” to “resulting
in less repetition” and rephrase to explicitly state “resource ID (orgId)
inferred from the checkout’s payer” so the sentence reads clearly that
checkout.confirm() now infers the resource ID (orgId) from the checkout’s payer,
resulting in less repetition and improved DX.
Co-authored-by: Robert Soriano <sorianorobertc@gmail.com>
Description
Since FAPI now returns the payer information, we can infer the organization id during confirmation and stop requiring as a parameter. This results to improved DX and also eliminates the possibility of a wrong organization id being passed.
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
New Features
Chores