@fantastic.dev/better-stripe 0.37.1 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/MIGRATION.md +9 -0
  3. package/README.md +25 -1
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +506 -2
  5. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +253 -1
  7. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +506 -2
  9. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts +253 -1
  11. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  12. package/dist/client/core/accountCapabilities.d.ts +20 -0
  13. package/dist/client/core/accountCapabilities.d.ts.map +1 -0
  14. package/dist/client/core/accountCapabilities.js +7 -0
  15. package/dist/client/core/accountCapabilities.js.map +1 -0
  16. package/dist/client/core/accountConfigurations.d.ts +46 -0
  17. package/dist/client/core/accountConfigurations.d.ts.map +1 -0
  18. package/dist/client/core/accountConfigurations.js +99 -0
  19. package/dist/client/core/accountConfigurations.js.map +1 -0
  20. package/dist/client/core/accountLinks.d.ts +29 -2
  21. package/dist/client/core/accountLinks.d.ts.map +1 -1
  22. package/dist/client/core/accountLinks.js +56 -4
  23. package/dist/client/core/accountLinks.js.map +1 -1
  24. package/dist/client/core/accounts.d.ts +2 -36
  25. package/dist/client/core/accounts.d.ts.map +1 -1
  26. package/dist/client/core/accounts.js +3 -73
  27. package/dist/client/core/accounts.js.map +1 -1
  28. package/dist/client/core/billingPortalClient.d.ts +14 -0
  29. package/dist/client/core/billingPortalClient.d.ts.map +1 -0
  30. package/dist/client/core/billingPortalClient.js +18 -0
  31. package/dist/client/core/billingPortalClient.js.map +1 -0
  32. package/dist/client/costRecovery-invoices.d.ts +4 -4
  33. package/dist/client/costRecovery.d.ts +19 -1
  34. package/dist/client/costRecovery.d.ts.map +1 -1
  35. package/dist/client/costRecovery.js +4 -0
  36. package/dist/client/costRecovery.js.map +1 -1
  37. package/dist/client/financialOutcomes/adapters.d.ts +18 -0
  38. package/dist/client/financialOutcomes/adapters.d.ts.map +1 -0
  39. package/dist/client/financialOutcomes/adapters.js +60 -0
  40. package/dist/client/financialOutcomes/adapters.js.map +1 -0
  41. package/dist/client/financialOutcomes/contracts.d.ts +42 -0
  42. package/dist/client/financialOutcomes/contracts.d.ts.map +1 -0
  43. package/dist/client/financialOutcomes/contracts.js +39 -0
  44. package/dist/client/financialOutcomes/contracts.js.map +1 -0
  45. package/dist/client/financialOutcomes/errors.d.ts +6 -0
  46. package/dist/client/financialOutcomes/errors.d.ts.map +1 -0
  47. package/dist/client/financialOutcomes/errors.js +22 -0
  48. package/dist/client/financialOutcomes/errors.js.map +1 -0
  49. package/dist/client/financialOutcomes/index.d.ts +6 -0
  50. package/dist/client/financialOutcomes/index.d.ts.map +1 -0
  51. package/dist/client/financialOutcomes/index.js +4 -0
  52. package/dist/client/financialOutcomes/index.js.map +1 -0
  53. package/dist/client/financialOutcomes/retry.d.ts +24 -0
  54. package/dist/client/financialOutcomes/retry.d.ts.map +1 -0
  55. package/dist/client/financialOutcomes/retry.js +31 -0
  56. package/dist/client/financialOutcomes/retry.js.map +1 -0
  57. package/dist/client/index.d.ts +21 -111
  58. package/dist/client/index.d.ts.map +1 -1
  59. package/dist/client/index.js +11 -85
  60. package/dist/client/index.js.map +1 -1
  61. package/dist/client/processingCostDeficit/index.d.ts +27 -0
  62. package/dist/client/processingCostDeficit/index.d.ts.map +1 -0
  63. package/dist/client/processingCostDeficit/index.js +54 -0
  64. package/dist/client/processingCostDeficit/index.js.map +1 -0
  65. package/dist/client/products/catalog.d.ts +26 -0
  66. package/dist/client/products/catalog.d.ts.map +1 -0
  67. package/dist/client/products/catalog.js +140 -0
  68. package/dist/client/products/catalog.js.map +1 -0
  69. package/dist/client/products/catalogClient.d.ts +109 -0
  70. package/dist/client/products/catalogClient.d.ts.map +1 -0
  71. package/dist/client/products/catalogClient.js +84 -0
  72. package/dist/client/products/catalogClient.js.map +1 -0
  73. package/dist/client/products/prices.d.ts +1 -0
  74. package/dist/client/products/prices.d.ts.map +1 -1
  75. package/dist/client/products/prices.js +1 -0
  76. package/dist/client/products/prices.js.map +1 -1
  77. package/dist/client/publicTypes.d.ts +2 -0
  78. package/dist/client/publicTypes.d.ts.map +1 -1
  79. package/dist/component/_generated/api.d.ts +284 -0
  80. package/dist/component/_generated/api.d.ts.map +1 -0
  81. package/dist/component/_generated/api.js +31 -0
  82. package/dist/component/_generated/api.js.map +1 -0
  83. package/dist/component/_generated/component.d.ts +535 -0
  84. package/dist/component/_generated/component.d.ts.map +1 -1
  85. package/dist/component/balanceFunding/helpers.d.ts +86 -0
  86. package/dist/component/balanceFunding/helpers.d.ts.map +1 -0
  87. package/dist/component/balanceFunding/helpers.js +68 -0
  88. package/dist/component/balanceFunding/helpers.js.map +1 -0
  89. package/dist/component/balanceFunding/importHandler.d.ts +13 -0
  90. package/dist/component/balanceFunding/importHandler.d.ts.map +1 -0
  91. package/dist/component/balanceFunding/importHandler.js +130 -0
  92. package/dist/component/balanceFunding/importHandler.js.map +1 -0
  93. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +85 -0
  94. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -0
  95. package/dist/component/balanceFunding/lifecycleHandlers.js +60 -0
  96. package/dist/component/balanceFunding/lifecycleHandlers.js.map +1 -0
  97. package/dist/component/balanceFunding/mutationValidators.d.ts +238 -0
  98. package/dist/component/balanceFunding/mutationValidators.d.ts.map +1 -0
  99. package/dist/component/balanceFunding/mutationValidators.js +55 -0
  100. package/dist/component/balanceFunding/mutationValidators.js.map +1 -0
  101. package/dist/component/balanceFunding/mutations.d.ts +335 -0
  102. package/dist/component/balanceFunding/mutations.d.ts.map +1 -0
  103. package/dist/component/balanceFunding/mutations.js +106 -0
  104. package/dist/component/balanceFunding/mutations.js.map +1 -0
  105. package/dist/component/balanceFunding/preparationHandlers.d.ts +55 -0
  106. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -0
  107. package/dist/component/balanceFunding/preparationHandlers.js +165 -0
  108. package/dist/component/balanceFunding/preparationHandlers.js.map +1 -0
  109. package/dist/component/balanceFunding/queries.d.ts +151 -0
  110. package/dist/component/balanceFunding/queries.d.ts.map +1 -0
  111. package/dist/component/balanceFunding/queries.js +180 -0
  112. package/dist/component/balanceFunding/queries.js.map +1 -0
  113. package/dist/component/balanceFunding/schema.d.ts +748 -0
  114. package/dist/component/balanceFunding/schema.d.ts.map +1 -0
  115. package/dist/component/balanceFunding/schema.js +124 -0
  116. package/dist/component/balanceFunding/schema.js.map +1 -0
  117. package/dist/component/balanceFunding/stateHandlers.d.ts +58 -0
  118. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -0
  119. package/dist/component/balanceFunding/stateHandlers.js +160 -0
  120. package/dist/component/balanceFunding/stateHandlers.js.map +1 -0
  121. package/dist/component/convex.config.d.ts.map +1 -1
  122. package/dist/component/convex.config.js +2 -0
  123. package/dist/component/convex.config.js.map +1 -1
  124. package/dist/component/costRecovery/completion.d.ts +1 -0
  125. package/dist/component/costRecovery/completion.d.ts.map +1 -1
  126. package/dist/component/costRecovery/helpers.d.ts +1 -0
  127. package/dist/component/costRecovery/helpers.d.ts.map +1 -1
  128. package/dist/component/costRecovery/mutations.d.ts +5 -0
  129. package/dist/component/costRecovery/mutations.d.ts.map +1 -1
  130. package/dist/component/costRecovery/preparation.d.ts +50 -0
  131. package/dist/component/costRecovery/preparation.d.ts.map +1 -0
  132. package/dist/component/costRecovery/preparation.js +108 -0
  133. package/dist/component/costRecovery/preparation.js.map +1 -0
  134. package/dist/component/costRecovery/queries.d.ts +1 -0
  135. package/dist/component/costRecovery/queries.d.ts.map +1 -1
  136. package/dist/component/costRecovery/reservations.d.ts +2 -0
  137. package/dist/component/costRecovery/reservations.d.ts.map +1 -1
  138. package/dist/component/costRecovery/schema.d.ts +7 -2
  139. package/dist/component/costRecovery/schema.d.ts.map +1 -1
  140. package/dist/component/costRecovery/schema.js +1 -0
  141. package/dist/component/costRecovery/schema.js.map +1 -1
  142. package/dist/component/durableExecution/runtime.d.ts +3 -0
  143. package/dist/component/durableExecution/runtime.d.ts.map +1 -0
  144. package/dist/component/durableExecution/runtime.js +12 -0
  145. package/dist/component/durableExecution/runtime.js.map +1 -0
  146. package/dist/component/earnings/triggers.d.ts +242 -2
  147. package/dist/component/earnings/triggers.d.ts.map +1 -1
  148. package/dist/component/products/mutations.d.ts +9 -0
  149. package/dist/component/products/mutations.d.ts.map +1 -1
  150. package/dist/component/products/mutations.js +31 -2
  151. package/dist/component/products/mutations.js.map +1 -1
  152. package/dist/component/schema.d.ts +253 -1
  153. package/dist/component/schema.js +4 -0
  154. package/dist/component/schema.js.map +1 -1
  155. package/docs/read-contracts.md +33 -0
  156. package/package.json +4 -2
  157. package/src/client/core/account-session-client.test.ts +74 -0
  158. package/src/client/core/accountCapabilities.ts +22 -0
  159. package/src/client/core/accountConfigurations.test.ts +183 -0
  160. package/src/client/core/accountConfigurations.ts +161 -0
  161. package/src/client/core/accountLinks.test.ts +6 -2
  162. package/src/client/core/accountLinks.ts +122 -5
  163. package/src/client/core/accounts.ts +8 -115
  164. package/src/client/core/billingPortal.test.ts +247 -0
  165. package/src/client/core/billingPortalClient.ts +35 -0
  166. package/src/client/costRecovery.test.ts +34 -0
  167. package/src/client/costRecovery.ts +21 -0
  168. package/src/client/financialOutcomes/adapters.ts +88 -0
  169. package/src/client/financialOutcomes/contracts.ts +43 -0
  170. package/src/client/financialOutcomes/errors.ts +29 -0
  171. package/src/client/financialOutcomes/index.ts +5 -0
  172. package/src/client/financialOutcomes/outcomes.test.ts +254 -0
  173. package/src/client/financialOutcomes/retry.ts +52 -0
  174. package/src/client/index.test.ts +0 -64
  175. package/src/client/index.ts +35 -185
  176. package/src/client/processingCostDeficit/README.md +35 -0
  177. package/src/client/processingCostDeficit/calculator.test.ts +176 -0
  178. package/src/client/processingCostDeficit/index.ts +91 -0
  179. package/src/client/products/catalog.test.ts +389 -0
  180. package/src/client/products/catalog.ts +225 -0
  181. package/src/client/products/catalogClient.ts +172 -0
  182. package/src/client/products/prices.test.ts +24 -0
  183. package/src/client/products/prices.ts +2 -0
  184. package/src/client/publicTypes.ts +13 -0
  185. package/src/component/_generated/api.ts +27 -1
  186. package/src/component/_generated/component.ts +707 -0
  187. package/src/component/balanceFunding/failure.test.ts +116 -0
  188. package/src/component/balanceFunding/helpers.ts +102 -0
  189. package/src/component/balanceFunding/import.test.ts +221 -0
  190. package/src/component/balanceFunding/importHandler.ts +146 -0
  191. package/src/component/balanceFunding/lifecycleHandlers.ts +90 -0
  192. package/src/component/balanceFunding/lookup.test.ts +113 -0
  193. package/src/component/balanceFunding/mutationValidators.ts +63 -0
  194. package/src/component/balanceFunding/mutations.ts +136 -0
  195. package/src/component/balanceFunding/preparation.test.ts +146 -0
  196. package/src/component/balanceFunding/preparationHandlers.ts +204 -0
  197. package/src/component/balanceFunding/queries.ts +221 -0
  198. package/src/component/balanceFunding/requestLookup.test.ts +160 -0
  199. package/src/component/balanceFunding/schema.ts +169 -0
  200. package/src/component/balanceFunding/state.test.ts +352 -0
  201. package/src/component/balanceFunding/stateHandlers.ts +198 -0
  202. package/src/component/balanceFunding/validation.test.ts +100 -0
  203. package/src/component/convex.config.ts +2 -0
  204. package/src/component/costRecovery/preparation.test.ts +355 -0
  205. package/src/component/costRecovery/preparation.ts +124 -0
  206. package/src/component/costRecovery/schema.ts +1 -0
  207. package/src/component/durableExecution/composition.test.ts +568 -0
  208. package/src/component/durableExecution/runtime.ts +12 -0
  209. package/src/component/products/mutations.ts +39 -2
  210. package/src/component/schema.ts +8 -0
@@ -0,0 +1,183 @@
1
+ // @vitest-environment edge-runtime
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import type Stripe from "stripe";
4
+ import type { Component, RunCtx } from "../helpers.js";
5
+ import { components, initConvexTest } from "../setup.test.js";
6
+ import schema from "../../component/schema.js";
7
+ import * as accounts from "./accounts.js";
8
+
9
+ const modules = import.meta.glob("../../component/**/*.{ts,js,tsx,jsx}");
10
+ function setup() {
11
+ const t = initConvexTest();
12
+ t.registerComponent("betterStripe", schema, modules);
13
+ const component = components.betterStripe as unknown as Component;
14
+ const ctx = {
15
+ runQuery: (ref: any, args: any) => t.query(ref, args),
16
+ runMutation: (ref: any, args: any) => t.mutation(ref, args),
17
+ } as RunCtx;
18
+ const update = vi.fn().mockResolvedValue({});
19
+ const retrieve = vi.fn().mockResolvedValue({
20
+ id: "acct_merchant",
21
+ applied_configurations: ["recipient", "merchant"],
22
+ });
23
+ const stripe = {
24
+ v2: { core: { accounts: { update, retrieve } } },
25
+ } as unknown as Stripe;
26
+ return { t, component, ctx, stripe, update, retrieve };
27
+ }
28
+
29
+ describe("merchant configuration", () => {
30
+ it("requests card payments and persists only the target account without changing ownership", async () => {
31
+ const { t, component, ctx, stripe, update, retrieve } = setup();
32
+ for (const stripeAccountId of ["acct_merchant", "acct_other"]) {
33
+ await t.mutation(component.core.mutations.upsertAccount, {
34
+ stripeAccountId,
35
+ userId: "owner",
36
+ orgId: "org",
37
+ appliedConfigurations: ["recipient"],
38
+ });
39
+ }
40
+ expect(typeof accounts.addMerchantConfiguration).toBe("function");
41
+ const result = await accounts.addMerchantConfiguration(
42
+ stripe,
43
+ component,
44
+ ctx,
45
+ { stripeAccountId: "acct_merchant" },
46
+ );
47
+ expect(result).toEqual({
48
+ success: true,
49
+ appliedConfigurations: ["recipient", "merchant"],
50
+ });
51
+ expect(update).toHaveBeenCalledWith("acct_merchant", {
52
+ configuration: {
53
+ merchant: { capabilities: { card_payments: { requested: true } } },
54
+ },
55
+ });
56
+ expect(retrieve).toHaveBeenCalledWith("acct_merchant");
57
+ expect(
58
+ await t.query(component.core.queries.getAccountByStripeId, {
59
+ stripeAccountId: "acct_merchant",
60
+ }),
61
+ ).toMatchObject({
62
+ userId: "owner",
63
+ orgId: "org",
64
+ appliedConfigurations: ["recipient", "merchant"],
65
+ });
66
+ expect(
67
+ await t.query(component.core.queries.getAccountByStripeId, {
68
+ stripeAccountId: "acct_other",
69
+ }),
70
+ ).toMatchObject({ appliedConfigurations: ["recipient"] });
71
+ });
72
+
73
+ it.each([
74
+ "addMerchantConfiguration",
75
+ "addCustomerConfiguration",
76
+ "addRecipientConfiguration",
77
+ ] as const)(
78
+ "%s preserves organization ownership pinned by a pending closure",
79
+ async (method) => {
80
+ const { t, component, ctx, stripe } = setup();
81
+ await t.mutation(component.core.mutations.upsertAccount, {
82
+ stripeAccountId: "acct_merchant",
83
+ userId: "owner",
84
+ orgId: "org",
85
+ appliedConfigurations: ["recipient"],
86
+ });
87
+ await t.mutation(component.accountClosure.mutations.prepare, {
88
+ stripeAccountId: "acct_merchant",
89
+ });
90
+ await accounts[method](stripe, component, ctx, {
91
+ stripeAccountId: "acct_merchant",
92
+ });
93
+ expect(
94
+ await t.query(component.core.queries.getAccountByStripeId, {
95
+ stripeAccountId: "acct_merchant",
96
+ }),
97
+ ).toMatchObject({
98
+ userId: "owner",
99
+ orgId: "org",
100
+ appliedConfigurations: ["recipient", "merchant"],
101
+ });
102
+ },
103
+ );
104
+
105
+ it("rejects missing component ownership before provider mutation", async () => {
106
+ const { component, ctx, stripe, update } = setup();
107
+ expect(typeof accounts.addMerchantConfiguration).toBe("function");
108
+ await expect(
109
+ accounts.addMerchantConfiguration(stripe, component, ctx, {
110
+ stripeAccountId: "acct_missing",
111
+ }),
112
+ ).rejects.toMatchObject({ data: { code: "ACCOUNT_NOT_FOUND" } });
113
+ expect(update).not.toHaveBeenCalled();
114
+ });
115
+
116
+ it("propagates failed readback and recovers on retry with provider configurations", async () => {
117
+ const { t, component, ctx, stripe, retrieve } = setup();
118
+ await t.mutation(component.core.mutations.upsertAccount, {
119
+ stripeAccountId: "acct_merchant",
120
+ userId: "owner",
121
+ appliedConfigurations: ["recipient"],
122
+ });
123
+ retrieve.mockRejectedValueOnce(new Error("readback unavailable"));
124
+ expect(typeof accounts.addMerchantConfiguration).toBe("function");
125
+ await expect(
126
+ accounts.addMerchantConfiguration(stripe, component, ctx, {
127
+ stripeAccountId: "acct_merchant",
128
+ }),
129
+ ).rejects.toThrow("readback unavailable");
130
+ expect(
131
+ await t.query(component.core.queries.getAccountByStripeId, {
132
+ stripeAccountId: "acct_merchant",
133
+ }),
134
+ ).toMatchObject({ appliedConfigurations: ["recipient"] });
135
+ await accounts.addMerchantConfiguration(stripe, component, ctx, {
136
+ stripeAccountId: "acct_merchant",
137
+ });
138
+ expect(
139
+ await t.query(component.core.queries.getAccountByStripeId, {
140
+ stripeAccountId: "acct_merchant",
141
+ }),
142
+ ).toMatchObject({ appliedConfigurations: ["recipient", "merchant"] });
143
+ });
144
+ });
145
+
146
+ describe("transfer capability", () => {
147
+ it("accepts active V2 recipient transfers and V1 transfers", () => {
148
+ expect(typeof accounts.canReceiveTransfers).toBe("function");
149
+ expect(
150
+ accounts.canReceiveTransfers({
151
+ configuration: {
152
+ recipient: {
153
+ capabilities: {
154
+ stripe_balance: { stripe_transfers: { status: "active" } },
155
+ },
156
+ },
157
+ },
158
+ }),
159
+ ).toBe(true);
160
+ expect(
161
+ accounts.canReceiveTransfers({ capabilities: { transfers: "active" } }),
162
+ ).toBe(true);
163
+ });
164
+ it.each([
165
+ null,
166
+ undefined,
167
+ {},
168
+ { capabilities: { transfers: "pending" } },
169
+ { configuration: { recipient: null } },
170
+ {
171
+ configuration: {
172
+ recipient: {
173
+ capabilities: {
174
+ stripe_balance: { stripe_transfers: { status: "inactive" } },
175
+ },
176
+ },
177
+ },
178
+ },
179
+ ])("rejects absent or unready capability %#", (account) => {
180
+ expect(typeof accounts.canReceiveTransfers).toBe("function");
181
+ expect(accounts.canReceiveTransfers(account)).toBe(false);
182
+ });
183
+ });
@@ -0,0 +1,161 @@
1
+ import type Stripe from "stripe";
2
+ import type { Component, RunCtx } from "../helpers.js";
3
+ import { runMutationOrThrow } from "../helpers.js";
4
+ import { throwStripeError } from "../errors.js";
5
+ import type { V2AccountUpdateParams } from "../stripe-types.js";
6
+ import type { StripeComponentAccount } from "../types.js";
7
+ import { componentRef } from "../webhooks/helpers.js";
8
+ import { DEFAULT_ACCOUNT_CONFIGURATION } from "./accountDefaults.js";
9
+
10
+ /**
11
+ * Default V2 customer configuration. Applying the customer configuration is
12
+ * what makes a V2 Account billable — the customer-facing payment/billing flows
13
+ * (subscriptions, invoices, billing portal). In the V2 Accounts API a single
14
+ * Account with this configuration replaces the legacy V1 Customer object, so
15
+ * `customer_account: acct_…` is what you pass to subscriptions, setup intents,
16
+ * and billing-portal sessions. No capabilities are requested by default;
17
+ * request `customer.capabilities.automatic_indirect_tax` separately if you need
18
+ * automatic tax on this account's invoices/subscriptions.
19
+ */
20
+ export const DEFAULT_CUSTOMER_CONFIGURATION: Record<string, unknown> = {
21
+ customer: {},
22
+ };
23
+
24
+ /**
25
+ * Apply the customer configuration to an existing V2 Account, making it
26
+ * billable, and record the resulting applied configurations on the component
27
+ * account. The account must already exist in the component DB (e.g. created via
28
+ * `createAccount`); its owning `userId` is recovered from that record.
29
+ */
30
+ export async function addCustomerConfiguration(
31
+ stripe: Stripe,
32
+ component: Component,
33
+ ctx: RunCtx,
34
+ opts: { stripeAccountId: string },
35
+ ): Promise<{ success: true; appliedConfigurations: string[] }> {
36
+ const existing = (await ctx.runQuery(
37
+ componentRef(component, "core/queries/getAccountByStripeId"),
38
+ { stripeAccountId: opts.stripeAccountId },
39
+ )) as StripeComponentAccount | null;
40
+
41
+ if (!existing) {
42
+ throwStripeError(
43
+ "ACCOUNT_NOT_FOUND",
44
+ `No component account found for ${opts.stripeAccountId}; create it before applying the customer configuration`,
45
+ );
46
+ }
47
+
48
+ await stripe.v2.core.accounts.update(opts.stripeAccountId, {
49
+ configuration: DEFAULT_CUSTOMER_CONFIGURATION,
50
+ } as V2AccountUpdateParams);
51
+
52
+ // Re-fetch to record the configurations Stripe actually applied
53
+ const updated = await stripe.v2.core.accounts.retrieve(opts.stripeAccountId);
54
+ const appliedConfigurations = updated.applied_configurations ?? [];
55
+
56
+ await runMutationOrThrow(
57
+ ctx,
58
+ componentRef(component, "core/mutations/upsertAccount"),
59
+ {
60
+ stripeAccountId: opts.stripeAccountId,
61
+ userId: existing.userId,
62
+ ...(existing.orgId !== undefined ? { orgId: existing.orgId } : {}),
63
+ appliedConfigurations,
64
+ },
65
+ );
66
+
67
+ return { success: true, appliedConfigurations };
68
+ }
69
+
70
+ /**
71
+ * Apply the V2 recipient configuration to an existing account, and record the
72
+ * resulting applied configurations on the component account. The account must
73
+ * already exist in the component DB (e.g. from {@link createAccount}); its
74
+ * owning `userId` is recovered from that record, matching
75
+ * {@link addCustomerConfiguration}.
76
+ */
77
+ export async function addRecipientConfiguration(
78
+ stripe: Stripe,
79
+ component: Component,
80
+ ctx: RunCtx,
81
+ opts: { stripeAccountId: string },
82
+ ): Promise<{ success: true; appliedConfigurations: string[] }> {
83
+ const existing = (await ctx.runQuery(
84
+ componentRef(component, "core/queries/getAccountByStripeId"),
85
+ { stripeAccountId: opts.stripeAccountId },
86
+ )) as StripeComponentAccount | null;
87
+
88
+ if (!existing) {
89
+ throwStripeError(
90
+ "ACCOUNT_NOT_FOUND",
91
+ `No component account found for ${opts.stripeAccountId}; create it before applying the recipient configuration`,
92
+ );
93
+ }
94
+
95
+ await stripe.v2.core.accounts.update(opts.stripeAccountId, {
96
+ configuration: {
97
+ recipient: {
98
+ // V2 (API 2026-05-27.dahlia) requires the `capabilities` wrapper with an
99
+ // explicit `requested: true`. The bare `recipient.stripe_balance` shape
100
+ // is rejected with "Unknown field" (confirmed against the Stripe sandbox).
101
+ capabilities: {
102
+ stripe_balance: {
103
+ stripe_transfers: { requested: true },
104
+ },
105
+ },
106
+ },
107
+ },
108
+ } as V2AccountUpdateParams);
109
+
110
+ // Re-fetch to record the configurations Stripe actually applied
111
+ const updated = await stripe.v2.core.accounts.retrieve(opts.stripeAccountId);
112
+ const appliedConfigurations = updated.applied_configurations ?? [];
113
+
114
+ await runMutationOrThrow(
115
+ ctx,
116
+ componentRef(component, "core/mutations/upsertAccount"),
117
+ {
118
+ stripeAccountId: opts.stripeAccountId,
119
+ userId: existing.userId,
120
+ ...(existing.orgId !== undefined ? { orgId: existing.orgId } : {}),
121
+ appliedConfigurations,
122
+ },
123
+ );
124
+
125
+ return { success: true, appliedConfigurations };
126
+ }
127
+
128
+ /** Request merchant card payments and refresh only this account's applied configurations. */
129
+ export async function addMerchantConfiguration(
130
+ stripe: Stripe,
131
+ component: Component,
132
+ ctx: RunCtx,
133
+ opts: { stripeAccountId: string },
134
+ ): Promise<{ success: true; appliedConfigurations: string[] }> {
135
+ const existing = (await ctx.runQuery(
136
+ componentRef(component, "core/queries/getAccountByStripeId"),
137
+ { stripeAccountId: opts.stripeAccountId },
138
+ )) as StripeComponentAccount | null;
139
+ if (!existing) {
140
+ throwStripeError(
141
+ "ACCOUNT_NOT_FOUND",
142
+ `No component account found for ${opts.stripeAccountId}; create it before applying the merchant configuration`,
143
+ );
144
+ }
145
+ await stripe.v2.core.accounts.update(opts.stripeAccountId, {
146
+ configuration: DEFAULT_ACCOUNT_CONFIGURATION,
147
+ } as V2AccountUpdateParams);
148
+ const updated = await stripe.v2.core.accounts.retrieve(opts.stripeAccountId);
149
+ const appliedConfigurations = updated.applied_configurations ?? [];
150
+ await runMutationOrThrow(
151
+ ctx,
152
+ componentRef(component, "core/mutations/upsertAccount"),
153
+ {
154
+ stripeAccountId: opts.stripeAccountId,
155
+ userId: existing.userId,
156
+ ...(existing.orgId !== undefined ? { orgId: existing.orgId } : {}),
157
+ appliedConfigurations,
158
+ },
159
+ );
160
+ return { success: true, appliedConfigurations };
161
+ }
@@ -169,10 +169,11 @@ describe("createV2AccountLink", () => {
169
169
  });
170
170
 
171
171
  describe("createAccountSession", () => {
172
- it("returns the client secret on success", async () => {
172
+ it("returns the provider client secret and expiry on success", async () => {
173
173
  const stripe = makeStripe();
174
174
  stripe.accountSessions.create.mockResolvedValue({
175
175
  client_secret: "secret_123",
176
+ expires_at: 1234567890,
176
177
  });
177
178
 
178
179
  const result = await createAccountSession(asStripe(stripe), ctx, {
@@ -180,7 +181,10 @@ describe("createAccountSession", () => {
180
181
  components: { account_onboarding: { enabled: true } },
181
182
  });
182
183
 
183
- expect(result).toEqual({ clientSecret: "secret_123" });
184
+ expect(result).toEqual({
185
+ clientSecret: "secret_123",
186
+ expiresAt: 1234567890,
187
+ });
184
188
  expect(stripe.accountSessions.create).toHaveBeenCalledWith({
185
189
  account: "acct_5",
186
190
  components: { account_onboarding: { enabled: true } },
@@ -107,7 +107,10 @@ export async function createAccountSession(
107
107
  account: opts.stripeAccountId,
108
108
  components: opts.components,
109
109
  });
110
- return { clientSecret: session.client_secret };
110
+ return {
111
+ clientSecret: session.client_secret,
112
+ expiresAt: session.expires_at,
113
+ };
111
114
  } catch (error) {
112
115
  throwStripeError(
113
116
  "STRIPE_API_ERROR",
@@ -182,16 +185,130 @@ export async function getAccountLinkWithStatus(
182
185
  return getOnboardingLink();
183
186
  }
184
187
 
188
+ /** The connected account that owns the configuration and its customer data.
189
+ * Omit for platform scope. Hosts must authorize both this scope and the customer.
190
+ */
191
+ type BillingPortalScope = { connectedAccountId?: string };
192
+
193
+ export type CreateBillingPortalConfigurationOptions = BillingPortalScope & {
194
+ /** Host-owned allowlists, proration, cancellation, and branding policy. */
195
+ params: Stripe.BillingPortal.ConfigurationCreateParams;
196
+ };
197
+ export type RetrieveBillingPortalConfigurationOptions = BillingPortalScope & {
198
+ configurationId: string;
199
+ };
200
+ export type UpdateBillingPortalConfigurationOptions = BillingPortalScope & {
201
+ configurationId: string;
202
+ params: Stripe.BillingPortal.ConfigurationUpdateParams;
203
+ };
204
+ export type CreateBillingPortalSessionOptions = BillingPortalScope & {
205
+ /** Customer account opening the portal, distinct from connectedAccountId. */
206
+ stripeAccountId: string;
207
+ returnUrl: string;
208
+ /** Omit to use Stripe's default portal configuration. */
209
+ configurationId?: string;
210
+ };
211
+
212
+ export async function createBillingPortalConfiguration(
213
+ stripe: Stripe,
214
+ _ctx: RunCtx,
215
+ opts: CreateBillingPortalConfigurationOptions,
216
+ ): Promise<Stripe.BillingPortal.Configuration> {
217
+ try {
218
+ return opts.connectedAccountId !== undefined
219
+ ? await stripe.billingPortal.configurations.create(opts.params, {
220
+ stripeAccount: opts.connectedAccountId,
221
+ })
222
+ : await stripe.billingPortal.configurations.create(opts.params);
223
+ } catch (error) {
224
+ throwStripeError(
225
+ "STRIPE_API_ERROR",
226
+ "Failed to create Billing Portal configuration",
227
+ error,
228
+ );
229
+ }
230
+ }
231
+
232
+ export async function retrieveBillingPortalConfiguration(
233
+ stripe: Stripe,
234
+ _ctx: RunCtx,
235
+ opts: RetrieveBillingPortalConfigurationOptions,
236
+ ): Promise<Stripe.BillingPortal.Configuration> {
237
+ try {
238
+ return opts.connectedAccountId !== undefined
239
+ ? await stripe.billingPortal.configurations.retrieve(
240
+ opts.configurationId,
241
+ {},
242
+ {
243
+ stripeAccount: opts.connectedAccountId,
244
+ },
245
+ )
246
+ : await stripe.billingPortal.configurations.retrieve(
247
+ opts.configurationId,
248
+ );
249
+ } catch (error) {
250
+ throwStripeError(
251
+ "STRIPE_API_ERROR",
252
+ "Failed to retrieve Billing Portal configuration",
253
+ error,
254
+ );
255
+ }
256
+ }
257
+
258
+ export async function updateBillingPortalConfiguration(
259
+ stripe: Stripe,
260
+ _ctx: RunCtx,
261
+ opts: UpdateBillingPortalConfigurationOptions,
262
+ ): Promise<Stripe.BillingPortal.Configuration> {
263
+ try {
264
+ return opts.connectedAccountId !== undefined
265
+ ? await stripe.billingPortal.configurations.update(
266
+ opts.configurationId,
267
+ opts.params,
268
+ {
269
+ stripeAccount: opts.connectedAccountId,
270
+ },
271
+ )
272
+ : await stripe.billingPortal.configurations.update(
273
+ opts.configurationId,
274
+ opts.params,
275
+ );
276
+ } catch (error) {
277
+ throwStripeError(
278
+ "STRIPE_API_ERROR",
279
+ "Failed to update Billing Portal configuration",
280
+ error,
281
+ );
282
+ }
283
+ }
284
+
185
285
  export async function createBillingPortalSession(
186
286
  stripe: Stripe,
187
287
  _ctx: RunCtx,
188
- opts: { stripeAccountId: string; returnUrl: string },
288
+ opts: CreateBillingPortalSessionOptions,
189
289
  ) {
190
- const session = await stripe.billingPortal.sessions.create({
290
+ const params: Stripe.BillingPortal.SessionCreateParams = {
191
291
  customer_account: opts.stripeAccountId,
192
292
  return_url: opts.returnUrl,
193
- });
194
- return { url: session.url };
293
+ ...(opts.configurationId !== undefined
294
+ ? { configuration: opts.configurationId }
295
+ : {}),
296
+ };
297
+ try {
298
+ const session =
299
+ opts.connectedAccountId !== undefined
300
+ ? await stripe.billingPortal.sessions.create(params, {
301
+ stripeAccount: opts.connectedAccountId,
302
+ })
303
+ : await stripe.billingPortal.sessions.create(params);
304
+ return { url: session.url };
305
+ } catch (error) {
306
+ throwStripeError(
307
+ "STRIPE_API_ERROR",
308
+ "Failed to create Billing Portal session",
309
+ error,
310
+ );
311
+ }
195
312
  }
196
313
 
197
314
  export async function getCountrySpecs(
@@ -1,3 +1,4 @@
1
+ import { addCustomerConfiguration } from "./accountConfigurations.js";
1
2
  import { idempotencyOptions } from "./idempotency.js";
2
3
  export type CreateAccountOptions = {
3
4
  userId: string;
@@ -474,121 +475,13 @@ export async function restartAccountOnboarding(
474
475
  return closeAccount(stripe, component, ctx, opts);
475
476
  }
476
477
 
477
- /**
478
- * Default V2 customer configuration. Applying the customer configuration is
479
- * what makes a V2 Account billable — the customer-facing payment/billing flows
480
- * (subscriptions, invoices, billing portal). In the V2 Accounts API a single
481
- * Account with this configuration replaces the legacy V1 Customer object, so
482
- * `customer_account: acct_…` is what you pass to subscriptions, setup intents,
483
- * and billing-portal sessions. No capabilities are requested by default;
484
- * request `customer.capabilities.automatic_indirect_tax` separately if you need
485
- * automatic tax on this account's invoices/subscriptions.
486
- */
487
- export const DEFAULT_CUSTOMER_CONFIGURATION: Record<string, unknown> = {
488
- customer: {},
489
- };
490
-
491
- /**
492
- * Apply the customer configuration to an existing V2 Account, making it
493
- * billable, and record the resulting applied configurations on the component
494
- * account. The account must already exist in the component DB (e.g. created via
495
- * `createAccount`); its owning `userId` is recovered from that record.
496
- */
497
- export async function addCustomerConfiguration(
498
- stripe: Stripe,
499
- component: Component,
500
- ctx: RunCtx,
501
- opts: { stripeAccountId: string },
502
- ): Promise<{ success: true; appliedConfigurations: string[] }> {
503
- const existing = (await ctx.runQuery(
504
- componentRef(component, "core/queries/getAccountByStripeId"),
505
- { stripeAccountId: opts.stripeAccountId },
506
- )) as StripeComponentAccount | null;
507
-
508
- if (!existing) {
509
- throwStripeError(
510
- "ACCOUNT_NOT_FOUND",
511
- `No component account found for ${opts.stripeAccountId}; create it before applying the customer configuration`,
512
- );
513
- }
514
-
515
- await stripe.v2.core.accounts.update(opts.stripeAccountId, {
516
- configuration: DEFAULT_CUSTOMER_CONFIGURATION,
517
- } as V2AccountUpdateParams);
518
-
519
- // Re-fetch to record the configurations Stripe actually applied
520
- const updated = await stripe.v2.core.accounts.retrieve(opts.stripeAccountId);
521
- const appliedConfigurations = updated.applied_configurations ?? [];
522
-
523
- await runMutationOrThrow(
524
- ctx,
525
- componentRef(component, "core/mutations/upsertAccount"),
526
- {
527
- stripeAccountId: opts.stripeAccountId,
528
- userId: existing.userId,
529
- appliedConfigurations,
530
- },
531
- );
532
-
533
- return { success: true, appliedConfigurations };
534
- }
535
-
536
- /**
537
- * Apply the V2 recipient configuration to an existing account, and record the
538
- * resulting applied configurations on the component account. The account must
539
- * already exist in the component DB (e.g. from {@link createAccount}); its
540
- * owning `userId` is recovered from that record, matching
541
- * {@link addCustomerConfiguration}.
542
- */
543
- export async function addRecipientConfiguration(
544
- stripe: Stripe,
545
- component: Component,
546
- ctx: RunCtx,
547
- opts: { stripeAccountId: string },
548
- ): Promise<{ success: true; appliedConfigurations: string[] }> {
549
- const existing = (await ctx.runQuery(
550
- componentRef(component, "core/queries/getAccountByStripeId"),
551
- { stripeAccountId: opts.stripeAccountId },
552
- )) as StripeComponentAccount | null;
553
-
554
- if (!existing) {
555
- throwStripeError(
556
- "ACCOUNT_NOT_FOUND",
557
- `No component account found for ${opts.stripeAccountId}; create it before applying the recipient configuration`,
558
- );
559
- }
560
-
561
- await stripe.v2.core.accounts.update(opts.stripeAccountId, {
562
- configuration: {
563
- recipient: {
564
- // V2 (API 2026-05-27.dahlia) requires the `capabilities` wrapper with an
565
- // explicit `requested: true`. The bare `recipient.stripe_balance` shape
566
- // is rejected with "Unknown field" (confirmed against the Stripe sandbox).
567
- capabilities: {
568
- stripe_balance: {
569
- stripe_transfers: { requested: true },
570
- },
571
- },
572
- },
573
- },
574
- } as V2AccountUpdateParams);
575
-
576
- // Re-fetch to record the configurations Stripe actually applied
577
- const updated = await stripe.v2.core.accounts.retrieve(opts.stripeAccountId);
578
- const appliedConfigurations = updated.applied_configurations ?? [];
579
-
580
- await runMutationOrThrow(
581
- ctx,
582
- componentRef(component, "core/mutations/upsertAccount"),
583
- {
584
- stripeAccountId: opts.stripeAccountId,
585
- userId: existing.userId,
586
- appliedConfigurations,
587
- },
588
- );
589
-
590
- return { success: true, appliedConfigurations };
591
- }
478
+ export {
479
+ DEFAULT_CUSTOMER_CONFIGURATION,
480
+ addCustomerConfiguration,
481
+ addRecipientConfiguration,
482
+ addMerchantConfiguration,
483
+ } from "./accountConfigurations.js";
484
+ export { canReceiveTransfers } from "./accountCapabilities.js";
592
485
 
593
486
  // =============================================================================
594
487
  // Sync