@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,254 @@
1
+ import { ConvexError } from "convex/values";
2
+ import { describe, expect, it } from "vitest";
3
+ import type { ProcessingCostContext } from "../settlement/processingCosts.js";
4
+ import type { VerifiedSale } from "../settlement/verifiedSale.js";
5
+ import {
6
+ financialRetryDecision,
7
+ processingCostOutcome,
8
+ readFinancialOutcomeError,
9
+ throwFinancialOutcome,
10
+ verifiedSaleOutcome,
11
+ } from "./index.js";
12
+
13
+ const policy = { maxRetries: 10, initialDelayMs: 1000, maxDelayMs: 60000 };
14
+ const pending = {
15
+ status: "not_ready",
16
+ reason: "fee_pending",
17
+ retryable: true,
18
+ } as const;
19
+
20
+ describe("legacy readiness adapters", () => {
21
+ it.each([
22
+ ["payment_processing", "provider_pending"],
23
+ ["charge_unavailable", "provider_pending"],
24
+ ["processing_fee_unavailable", "fee_pending"],
25
+ ["invoice_not_paid", "provider_pending"],
26
+ ])(
27
+ "converts verified sale %s without using English messages",
28
+ (reason, mapped) => {
29
+ expect(
30
+ verifiedSaleOutcome({ status: "pending", reason, retryable: true }),
31
+ ).toEqual({
32
+ status: "not_ready",
33
+ reason: mapped,
34
+ retryable: true,
35
+ });
36
+ },
37
+ );
38
+ it.each(["payment_not_succeeded", "charge_refunded_or_disputed"])(
39
+ "rejects terminal sale reason %s even if a caller marks it retryable",
40
+ (reason) => {
41
+ expect(
42
+ verifiedSaleOutcome({ status: "not_payable", reason, retryable: true }),
43
+ ).toEqual({
44
+ status: "rejected",
45
+ reason: "payment_not_payable",
46
+ retryable: false,
47
+ });
48
+ },
49
+ );
50
+ it("fails closed for unrecognized sale reasons and disabled retry flags", () => {
51
+ for (const sale of [
52
+ {
53
+ status: "pending",
54
+ reason: "processing fees are not available yet",
55
+ retryable: true,
56
+ },
57
+ { status: "pending", reason: "payment_processing", retryable: false },
58
+ ] as VerifiedSale[]) {
59
+ expect(verifiedSaleOutcome(sale)).toEqual({
60
+ status: "rejected",
61
+ reason: "unsupported_source",
62
+ retryable: false,
63
+ });
64
+ }
65
+ });
66
+ it("retains the complete ready sale without changing the legacy object", () => {
67
+ const sale: VerifiedSale = {
68
+ status: "ready",
69
+ paymentIntentId: "pi_one",
70
+ chargeId: "ch_one",
71
+ gross: 100,
72
+ processingFee: 3,
73
+ currency: "usd",
74
+ metadata: {},
75
+ };
76
+ expect(verifiedSaleOutcome(sale)).toEqual({ status: "ready", value: sale });
77
+ });
78
+ it.each([
79
+ ["charge_unavailable", "provider_pending"],
80
+ ["refund_pending", "provider_pending"],
81
+ ["charge_transaction_unavailable", "fee_pending"],
82
+ ["refund_transaction_unavailable", "fee_pending"],
83
+ ["refund_failure_transaction_unavailable", "fee_pending"],
84
+ ["dispute_transactions_unavailable", "fee_pending"],
85
+ ["dispute_reinstatement_unavailable", "fee_pending"],
86
+ ] as const)("converts processing cost %s", (reason, mapped) => {
87
+ expect(
88
+ processingCostOutcome({
89
+ status: "not_ready",
90
+ paymentIntentId: "pi_one",
91
+ reason,
92
+ }),
93
+ ).toEqual({ status: "not_ready", reason: mapped, retryable: true });
94
+ });
95
+ it.each([
96
+ ["payment_not_succeeded", "payment_not_payable"],
97
+ ["currency_mismatch", "currency_mismatch"],
98
+ ] as const)(
99
+ "rejects cost %s without scheduling more financial actions",
100
+ (reason, mapped) => {
101
+ expect(
102
+ processingCostOutcome({
103
+ status: "not_ready",
104
+ paymentIntentId: "pi_one",
105
+ reason,
106
+ }),
107
+ ).toEqual({ status: "rejected", reason: mapped, retryable: false });
108
+ },
109
+ );
110
+ it("preserves ready processing cost evidence", () => {
111
+ const cost: ProcessingCostContext = {
112
+ status: "ready",
113
+ paymentIntentId: "pi_one",
114
+ chargeId: "ch_one",
115
+ currency: "usd",
116
+ gross: 100,
117
+ metadata: {},
118
+ processingFee: 3,
119
+ refundFeeAdjustment: 0,
120
+ disputeFeeAdjustment: 0,
121
+ netFees: 3,
122
+ refundedPrincipal: 0,
123
+ disputedPrincipal: 0,
124
+ principalReturned: 0,
125
+ refunds: [],
126
+ disputes: [],
127
+ transactions: [],
128
+ };
129
+ expect(processingCostOutcome(cost)).toEqual({
130
+ status: "ready",
131
+ value: cost,
132
+ });
133
+ });
134
+ });
135
+
136
+ describe("bounded financial retries", () => {
137
+ it("caps exponential delay and permits exactly the selected retry count", () => {
138
+ expect(
139
+ Array.from({ length: 10 }, (_, attempt) =>
140
+ financialRetryDecision(pending, attempt, policy),
141
+ ),
142
+ ).toEqual(
143
+ [1000, 2000, 4000, 8000, 16000, 32000, 60000, 60000, 60000, 60000].map(
144
+ (delayMs, attempt) => ({
145
+ status: "retry",
146
+ delayMs,
147
+ nextAttempt: attempt + 1,
148
+ }),
149
+ ),
150
+ );
151
+ expect(financialRetryDecision(pending, 10, policy)).toEqual({
152
+ status: "stop",
153
+ reason: "exhausted",
154
+ });
155
+ expect(financialRetryDecision(pending, 11, policy)).toEqual({
156
+ status: "stop",
157
+ reason: "exhausted",
158
+ });
159
+ });
160
+ it("allows zero retries", () => {
161
+ expect(
162
+ financialRetryDecision(pending, 0, { ...policy, maxRetries: 0 }),
163
+ ).toEqual({ status: "stop", reason: "exhausted" });
164
+ });
165
+ it.each([
166
+ { status: "conflict", reason: "scope_busy", retryable: false },
167
+ { status: "conflict", reason: "revision_changed", retryable: false },
168
+ { status: "conflict", reason: "identity_changed", retryable: false },
169
+ { status: "rejected", reason: "invalid_scope", retryable: false },
170
+ { status: "rejected", reason: "policy_invalid", retryable: false },
171
+ { status: "unknown", reason: "provider_outcome_unknown", retryable: false },
172
+ { status: "unknown", reason: "history_incomplete", retryable: false },
173
+ { status: "ready", value: {} },
174
+ ] as const)("never retries $status/$reason", (outcome) => {
175
+ expect(financialRetryDecision(outcome, 0, policy)).toEqual({
176
+ status: "stop",
177
+ reason: "not_retryable",
178
+ });
179
+ });
180
+ it.each([-1, 0.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1])(
181
+ "rejects invalid attempts %s",
182
+ (attempt) => {
183
+ expect(() => financialRetryDecision(pending, attempt, policy)).toThrow();
184
+ },
185
+ );
186
+ it.each([
187
+ { maxRetries: -1 },
188
+ { maxRetries: 21 },
189
+ { maxRetries: 0.5 },
190
+ { initialDelayMs: 0 },
191
+ { initialDelayMs: NaN },
192
+ { maxDelayMs: Infinity },
193
+ { maxDelayMs: 86400001 },
194
+ { initialDelayMs: 60001 },
195
+ ])("rejects invalid policy %j", (invalid) => {
196
+ expect(() =>
197
+ financialRetryDecision(pending, 0, { ...policy, ...invalid }),
198
+ ).toThrow();
199
+ });
200
+ });
201
+
202
+ describe("serializable financial errors", () => {
203
+ it("round trips only a validated nonsecret outcome through Convex data", () => {
204
+ let caught: unknown;
205
+ try {
206
+ throwFinancialOutcome(pending);
207
+ } catch (error) {
208
+ caught = error;
209
+ }
210
+ expect(caught).toBeInstanceOf(ConvexError);
211
+ expect(readFinancialOutcomeError(caught)).toEqual(pending);
212
+ const serialized = JSON.parse(
213
+ JSON.stringify((caught as { data: unknown }).data),
214
+ );
215
+ expect(readFinancialOutcomeError({ data: serialized })).toEqual(pending);
216
+ expect(serialized).toEqual({ code: "FINANCIAL_OUTCOME", outcome: pending });
217
+ });
218
+ it.each([
219
+ new Error(
220
+ "Stripe processing fees are not available yet; retry settlement.",
221
+ ),
222
+ {
223
+ data: {
224
+ code: "STRIPE_API_ERROR",
225
+ message: "processing fees are not available",
226
+ },
227
+ },
228
+ {
229
+ data: {
230
+ code: "FINANCIAL_OUTCOME",
231
+ outcome: { ...pending, retryable: false },
232
+ },
233
+ },
234
+ {
235
+ data: {
236
+ code: "FINANCIAL_OUTCOME",
237
+ outcome: { ...pending, reason: "arbitrary" },
238
+ },
239
+ },
240
+ {
241
+ data: {
242
+ code: "FINANCIAL_OUTCOME",
243
+ outcome: { ...pending, secret: "redacted" },
244
+ },
245
+ },
246
+ null,
247
+ "not_ready",
248
+ ])(
249
+ "does not infer retryability from unrelated or malformed errors",
250
+ (error) => {
251
+ expect(readFinancialOutcomeError(error)).toBeNull();
252
+ },
253
+ );
254
+ });
@@ -0,0 +1,52 @@
1
+ import {
2
+ financialUnavailableSchema,
3
+ type FinancialOutcome,
4
+ } from "./contracts.js";
5
+
6
+ export type FinancialRetryPolicy = {
7
+ /** Additional attempts after the initial call, from 0 to 20. */
8
+ maxRetries: number;
9
+ /** Positive integer milliseconds, no greater than maxDelayMs. */
10
+ initialDelayMs: number;
11
+ /** Positive integer milliseconds, at most one day. */
12
+ maxDelayMs: number;
13
+ };
14
+ export type FinancialRetryDecision =
15
+ | { status: "retry"; delayMs: number; nextAttempt: number }
16
+ | { status: "stop"; reason: "not_retryable" | "exhausted" };
17
+
18
+ /**
19
+ * Schedules nothing and retries no provider write. The caller schedules a new
20
+ * readiness observation only. attempt is the number of retries already made.
21
+ * Conflicts require fresh state/policy; unknown writes require reconciliation.
22
+ */
23
+ export function financialRetryDecision(
24
+ outcome: FinancialOutcome<unknown>,
25
+ attempt: number,
26
+ policy: FinancialRetryPolicy,
27
+ ): FinancialRetryDecision {
28
+ if (
29
+ !Number.isSafeInteger(attempt) ||
30
+ attempt < 0 ||
31
+ !Number.isSafeInteger(policy.maxRetries) ||
32
+ policy.maxRetries < 0 ||
33
+ policy.maxRetries > 20 ||
34
+ !Number.isSafeInteger(policy.initialDelayMs) ||
35
+ policy.initialDelayMs < 1 ||
36
+ !Number.isSafeInteger(policy.maxDelayMs) ||
37
+ policy.maxDelayMs < 1 ||
38
+ policy.maxDelayMs > 86400000 ||
39
+ policy.initialDelayMs > policy.maxDelayMs
40
+ )
41
+ throw new RangeError("Invalid financial retry attempt or policy.");
42
+ const parsed = financialUnavailableSchema.safeParse(outcome);
43
+ if (!parsed.success || parsed.data.status !== "not_ready")
44
+ return { status: "stop", reason: "not_retryable" };
45
+ if (attempt >= policy.maxRetries)
46
+ return { status: "stop", reason: "exhausted" };
47
+ return {
48
+ status: "retry",
49
+ delayMs: Math.min(policy.maxDelayMs, policy.initialDelayMs * 2 ** attempt),
50
+ nextAttempt: attempt + 1,
51
+ };
52
+ }
@@ -67,9 +67,6 @@ const mockStripeInstance = {
67
67
  accountLinks: {
68
68
  create: vi.fn(),
69
69
  },
70
- accountSessions: {
71
- create: vi.fn(),
72
- },
73
70
  accounts: {
74
71
  createLoginLink: vi.fn(),
75
72
  },
@@ -1444,67 +1441,6 @@ describe("BetterStripe", () => {
1444
1441
  });
1445
1442
  });
1446
1443
 
1447
- // =========================================================================
1448
- // Account link methods: createAccountSession
1449
- // =========================================================================
1450
-
1451
- describe("createAccountSession", () => {
1452
- it("calls Stripe accountSessions.create and returns the clientSecret", async () => {
1453
- const bs = new BetterStripe(components.betterStripe, {
1454
- STRIPE_SECRET_KEY: "sk_test_xxx",
1455
- });
1456
-
1457
- mockStripeInstance.accountSessions.create.mockResolvedValue({
1458
- client_secret: "as_secret_123",
1459
- });
1460
-
1461
- const result = await bs.createAccountSession(mockCtx, {
1462
- stripeAccountId: "acct_123",
1463
- components: {
1464
- account_management: { enabled: true },
1465
- },
1466
- });
1467
-
1468
- expect(mockStripeInstance.accountSessions.create).toHaveBeenCalledWith({
1469
- account: "acct_123",
1470
- components: {
1471
- account_management: { enabled: true },
1472
- },
1473
- });
1474
- expect(result).toEqual({ clientSecret: "as_secret_123" });
1475
- });
1476
-
1477
- it("wraps Stripe failures in a structured STRIPE_API_ERROR", async () => {
1478
- const bs = new BetterStripe(components.betterStripe, {
1479
- STRIPE_SECRET_KEY: "sk_test_xxx",
1480
- });
1481
-
1482
- mockStripeInstance.accountSessions.create.mockRejectedValue(
1483
- Object.assign(new Error("No such account: acct_missing"), {
1484
- type: "StripeInvalidRequestError",
1485
- code: "resource_missing",
1486
- }),
1487
- );
1488
-
1489
- const error = await bs
1490
- .createAccountSession(mockCtx, {
1491
- stripeAccountId: "acct_missing",
1492
- components: { account_onboarding: { enabled: true } },
1493
- })
1494
- .catch((e: unknown) => e);
1495
-
1496
- expect(error).toBeInstanceOf(ConvexError);
1497
- expect((error as { data: Record<string, unknown> }).data).toMatchObject({
1498
- code: "STRIPE_API_ERROR",
1499
- stripeError: {
1500
- type: "StripeInvalidRequestError",
1501
- code: "resource_missing",
1502
- message: "No such account: acct_missing",
1503
- },
1504
- });
1505
- });
1506
- });
1507
-
1508
1444
  // =========================================================================
1509
1445
  // syncAllProducts
1510
1446
  // =========================================================================
@@ -1,5 +1,7 @@
1
1
  import * as personalAccountMappingImpl from "./core/personalAccountMapping.js";
2
2
  export type * from "./publicTypes.js";
3
+ export * from "./financialOutcomes/index.js";
4
+ export * from "./processingCostDeficit/index.js";
3
5
  import * as accountClosuresImpl from "./core/accountClosures.js";
4
6
  import type { PaginationOptions } from "convex/server";
5
7
  import { reconcilePayoutAndTrigger } from "./webhooks/payoutReconciliation.js";
@@ -18,26 +20,25 @@ import type { CreateCheckoutSessionOptions } from "./billing/checkoutOptions.js"
18
20
  export type { CreateCheckoutSessionOptions } from "./billing/checkoutOptions.js";
19
21
  import * as intentsImpl from "./billing/intents.js";
20
22
  export type * from "./billing/intents.js";
21
- import { FinancialOwnershipHost } from "./financialOwnership.js";
23
+ import { CatalogClient } from "./products/catalogClient.js";
24
+ export type {
25
+ CreateBillingPortalConfigurationOptions,
26
+ RetrieveBillingPortalConfigurationOptions,
27
+ UpdateBillingPortalConfigurationOptions,
28
+ CreateBillingPortalSessionOptions,
29
+ } from "./core/accountLinks.js";
30
+ export type {
31
+ AdoptProductOptions,
32
+ EnsurePriceOptions,
33
+ } from "./products/catalog.js";
34
+ export type { CreatePriceOptions } from "./products/prices.js";
35
+ export type { CreateProductOptions } from "./products/products.js";
22
36
  import { CostRecoveryClient } from "./costRecovery.js";
23
37
  export * from "./charge-currency.js";
24
38
  export * from "./costRecovery.js";
25
39
  import type { SubscriptionStatus } from "../component/billing/validators.js";
26
40
  import * as processingCostsImpl from "./settlement/processingCosts.js";
27
- export type {
28
- ProcessingCostContext,
29
- ProcessingCostOptions,
30
- ProcessingCostTransaction,
31
- ProcessingCostRecord,
32
- ProcessingCostNotReadyReason,
33
- } from "./settlement/processingCosts.js";
34
41
  import * as balanceFundingImpl from "./billing/balanceFunding.js";
35
- export type {
36
- BalanceFundingCapability,
37
- BalanceFundingPreparation,
38
- PrepareBalanceFundingOptions,
39
- SetBalanceFundingOptions,
40
- } from "./billing/balanceFunding.js";
41
42
  import * as invoicePreviewImpl from "./billing/invoicePreview.js";
42
43
  export type {
43
44
  UpcomingInvoicePreview,
@@ -72,6 +73,10 @@ export type {
72
73
  ProviderCheckoutSessionPage,
73
74
  } from "./billing/checkoutPages.js";
74
75
  export type { CreateAccountOptions } from "./core/accounts.js";
76
+ export {
77
+ canReceiveTransfers,
78
+ type TransferCapabilityAccount,
79
+ } from "./core/accountCapabilities.js";
75
80
  import { buildAsyncHookRoutes } from "./webhooks/asyncHooks.js";
76
81
  import * as saleContextImpl from "./settlement/verifiedSale.js";
77
82
  import * as settlementImpl from "./settlement/settleSale.js";
@@ -144,8 +149,6 @@ import type {
144
149
  V2AccountUpdateParams,
145
150
  } from "./stripe-types.js";
146
151
  import { componentRef, DISPATCHER_UPSERT_PATHS } from "./webhooks/helpers.js";
147
- import * as pricesImpl from "./products/prices.js";
148
- import * as productsImpl from "./products/products.js";
149
152
  import type {
150
153
  AccountLinkWithStatus,
151
154
  AsyncHookCtx,
@@ -202,7 +205,7 @@ export type BetterStripeComponent = ComponentApi;
202
205
 
203
206
  // BETTER STRIPE CLIENT
204
207
 
205
- export class BetterStripe extends FinancialOwnershipHost {
208
+ export class BetterStripe extends CatalogClient {
206
209
  readonly stripeApiVersion: SupportedStripeApiVersion;
207
210
  private _apiKey?: string;
208
211
  private _triggers?: SyncTriggers;
@@ -464,11 +467,7 @@ export class BetterStripe extends FinancialOwnershipHost {
464
467
  );
465
468
  }
466
469
 
467
- /**
468
- * Apply the V2 recipient configuration to an existing account, and record
469
- * the applied configurations on the component account. The account must
470
- * already exist in the component DB (e.g. from {@link createAccount}).
471
- */
470
+ /** Request recipient transfers and persist the provider configurations for this account. */
472
471
  async addRecipientConfiguration(
473
472
  ctx: RunCtx,
474
473
  opts: { stripeAccountId: string },
@@ -481,12 +480,7 @@ export class BetterStripe extends FinancialOwnershipHost {
481
480
  );
482
481
  }
483
482
 
484
- /**
485
- * Apply the V2 customer configuration to an existing account, making it
486
- * billable (subscriptions, invoices, billing portal via `customer_account`),
487
- * and record the applied configurations on the component account. The account
488
- * must already exist in the component DB (e.g. from {@link createAccount}).
489
- */
483
+ /** Make an existing account billable and persist its provider configurations. */
490
484
  async addCustomerConfiguration(
491
485
  ctx: RunCtx,
492
486
  opts: { stripeAccountId: string },
@@ -499,6 +493,19 @@ export class BetterStripe extends FinancialOwnershipHost {
499
493
  );
500
494
  }
501
495
 
496
+ /** Request merchant card payments and persist only this account's provider configurations. */
497
+ async addMerchantConfiguration(
498
+ ctx: RunCtx,
499
+ opts: { stripeAccountId: string },
500
+ ) {
501
+ return accountsImpl.addMerchantConfiguration(
502
+ this.stripe(),
503
+ this.component,
504
+ ctx,
505
+ opts,
506
+ );
507
+ }
508
+
502
509
  /**
503
510
  * Store (or clear, with `null`) a per-store statement-descriptor suffix on a
504
511
  * seller's account record (BTS-32). Destination charges to that account then
@@ -534,148 +541,6 @@ export class BetterStripe extends FinancialOwnershipHost {
534
541
  );
535
542
  }
536
543
 
537
- // PRODUCT METHODS
538
-
539
- async createProduct(ctx: RunCtx, opts: productsImpl.CreateProductOptions) {
540
- return productsImpl.createProduct(this.stripe(), this.component, ctx, {
541
- ...opts,
542
- // Stamp the per-store descriptor at create so it covers the first invoice
543
- // charge (BTS-67); resolves the store's suffix, else this default.
544
- defaultStatementDescriptorSuffix: this._statementDescriptorSuffix,
545
- });
546
- }
547
-
548
- async updateProduct(
549
- ctx: RunCtx,
550
- opts: {
551
- stripeProductId: string;
552
- name?: string;
553
- description?: string;
554
- active?: boolean;
555
- defaultPrice?: string | null;
556
- metadata?: Record<string, string>;
557
- },
558
- ) {
559
- return productsImpl.updateProduct(this.stripe(), this.component, ctx, {
560
- ...opts,
561
- defaultStatementDescriptorSuffix: this._statementDescriptorSuffix,
562
- });
563
- }
564
-
565
- async deactivateProduct(ctx: RunCtx, opts: { stripeProductId: string }) {
566
- return productsImpl.deactivateProduct(this.stripe(), ctx, opts);
567
- }
568
-
569
- async getProduct(
570
- ctx: RunCtx,
571
- opts: { productId: string },
572
- ): Promise<StripeComponentProduct | null> {
573
- return productsImpl.getProduct(this.component, ctx, opts);
574
- }
575
-
576
- async getProductByStripeId(
577
- ctx: RunCtx,
578
- opts: { stripeProductId: string },
579
- ): Promise<StripeComponentProduct | null> {
580
- return productsImpl.getProductByStripeId(this.component, ctx, opts);
581
- }
582
-
583
- async listProducts(
584
- ctx: RunCtx,
585
- opts?: { accountId?: string; active?: boolean; limit?: number },
586
- ): Promise<StripeComponentProduct[]> {
587
- return productsImpl.listProducts(this.component, ctx, opts);
588
- }
589
-
590
- async upsertProduct(
591
- ctx: RunCtx,
592
- opts: {
593
- stripeProductId: string;
594
- accountId?: string;
595
- name: string;
596
- description?: string;
597
- active: boolean;
598
- metadata?: Record<string, unknown>;
599
- },
600
- ) {
601
- return productsImpl.upsertProduct(this.component, ctx, opts);
602
- }
603
-
604
- async listStripeProducts(
605
- ctx: RunCtx,
606
- opts?: { active?: boolean; limit?: number },
607
- ) {
608
- return productsImpl.listStripeProducts(this.stripe(), ctx, opts);
609
- }
610
-
611
- async deleteProduct(ctx: RunCtx, opts: { stripeProductId: string }) {
612
- return productsImpl.deleteProduct(this.stripe(), ctx, opts);
613
- }
614
-
615
- // PRICE METHODS
616
-
617
- async createPrice(ctx: RunCtx, opts: pricesImpl.CreatePriceOptions) {
618
- return pricesImpl.createPrice(this.stripe(), this.component, ctx, opts);
619
- }
620
-
621
- async updatePrice(
622
- ctx: RunCtx,
623
- opts: {
624
- stripePriceId: string;
625
- active?: boolean;
626
- nickname?: string;
627
- metadata?: Record<string, string>;
628
- },
629
- ) {
630
- return pricesImpl.updatePrice(this.stripe(), ctx, opts);
631
- }
632
-
633
- async deactivatePrice(ctx: RunCtx, opts: { stripePriceId: string }) {
634
- return pricesImpl.deactivatePrice(this.stripe(), ctx, opts);
635
- }
636
-
637
- async getPrice(
638
- ctx: RunCtx,
639
- opts: { priceId: string },
640
- ): Promise<StripeComponentPrice | null> {
641
- return pricesImpl.getPrice(this.component, ctx, opts);
642
- }
643
-
644
- async getPriceByStripeId(
645
- ctx: RunCtx,
646
- opts: { stripePriceId: string },
647
- ): Promise<StripeComponentPrice | null> {
648
- return pricesImpl.getPriceByStripeId(this.component, ctx, opts);
649
- }
650
-
651
- async listPrices(
652
- ctx: RunCtx,
653
- opts?: { productId?: string; active?: boolean; limit?: number },
654
- ): Promise<StripeComponentPrice[]> {
655
- return pricesImpl.listPrices(this.component, ctx, opts);
656
- }
657
-
658
- async listPricesByProduct(
659
- ctx: RunCtx,
660
- opts: { stripeProductId: string },
661
- ): Promise<StripeComponentPrice[]> {
662
- return pricesImpl.listPricesByProduct(this.component, ctx, opts);
663
- }
664
-
665
- async upsertPrice(
666
- ctx: RunCtx,
667
- opts: Parameters<typeof pricesImpl.upsertPrice>[2],
668
- ) {
669
- return pricesImpl.upsertPrice(this.component, ctx, opts);
670
- }
671
-
672
- async listStripePrices(
673
- ctx: RunCtx,
674
- opts?: { productId?: string; active?: boolean; limit?: number },
675
- ) {
676
- return pricesImpl.listStripePrices(this.stripe(), ctx, opts);
677
- }
678
-
679
544
  /** Card-only one-time checkout. Host authorizes price and authenticated customer. */
680
545
  async createPaymentIntent(
681
546
  ctx: RunCtx,
@@ -1133,17 +998,6 @@ export class BetterStripe extends FinancialOwnershipHost {
1133
998
  return accountLinksImpl.getAccountLinkWithStatus(this.stripe(), ctx, opts);
1134
999
  }
1135
1000
 
1136
- async createBillingPortalSession(
1137
- ctx: RunCtx,
1138
- opts: { stripeAccountId: string; returnUrl: string },
1139
- ) {
1140
- return accountLinksImpl.createBillingPortalSession(
1141
- this.stripe(),
1142
- ctx,
1143
- opts,
1144
- );
1145
- }
1146
-
1147
1001
  async getCountrySpecs(ctx: RunCtx, opts: { countryCode: string }) {
1148
1002
  return accountLinksImpl.getCountrySpecs(this.stripe(), ctx, opts);
1149
1003
  }
@@ -1509,10 +1363,6 @@ export class BetterStripe extends FinancialOwnershipHost {
1509
1363
  return accountsImpl.syncAllAccounts(this.stripe(), this.component, ctx);
1510
1364
  }
1511
1365
 
1512
- async syncAllProducts(ctx: RunCtx) {
1513
- return productsImpl.syncAllProducts(this.stripe(), this.component, ctx);
1514
- }
1515
-
1516
1366
  async syncAllSubscriptions(ctx: RunCtx) {
1517
1367
  return subscriptionsImpl.syncAllSubscriptions(
1518
1368
  this.stripe(),