@fantastic.dev/better-stripe 0.40.0 → 0.42.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 (183) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/dist/client/balanceFundingWorkflow/client.d.ts +172 -0
  4. package/dist/client/balanceFundingWorkflow/client.d.ts.map +1 -0
  5. package/dist/client/balanceFundingWorkflow/client.js +289 -0
  6. package/dist/client/balanceFundingWorkflow/client.js.map +1 -0
  7. package/dist/client/billing/balanceFunding.d.ts +5 -0
  8. package/dist/client/billing/balanceFunding.d.ts.map +1 -1
  9. package/dist/client/billing/balanceFunding.js +30 -0
  10. package/dist/client/billing/balanceFunding.js.map +1 -1
  11. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +808 -2
  12. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +404 -1
  14. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  15. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +808 -2
  16. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  17. package/dist/client/connect/payoutSyncTestHelpers.d.ts +404 -1
  18. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  19. package/dist/client/costRecovery-invoices.d.ts +2 -2
  20. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  21. package/dist/client/costRecovery-invoices.js +4 -1
  22. package/dist/client/costRecovery-invoices.js.map +1 -1
  23. package/dist/client/costRecovery.d.ts +5 -2
  24. package/dist/client/costRecovery.d.ts.map +1 -1
  25. package/dist/client/costRecovery.js +3 -1
  26. package/dist/client/costRecovery.js.map +1 -1
  27. package/dist/client/index.d.ts +3 -0
  28. package/dist/client/index.d.ts.map +1 -1
  29. package/dist/client/index.js +4 -0
  30. package/dist/client/index.js.map +1 -1
  31. package/dist/client/recoveryWorkflow/client.d.ts +14 -0
  32. package/dist/client/recoveryWorkflow/client.d.ts.map +1 -0
  33. package/dist/client/recoveryWorkflow/client.js +34 -0
  34. package/dist/client/recoveryWorkflow/client.js.map +1 -0
  35. package/dist/client/recoveryWorkflow/contracts.d.ts +63 -0
  36. package/dist/client/recoveryWorkflow/contracts.d.ts.map +1 -0
  37. package/dist/client/recoveryWorkflow/contracts.js +11 -0
  38. package/dist/client/recoveryWorkflow/contracts.js.map +1 -0
  39. package/dist/client/recoveryWorkflow/provider.d.ts +10 -0
  40. package/dist/client/recoveryWorkflow/provider.d.ts.map +1 -0
  41. package/dist/client/recoveryWorkflow/provider.js +80 -0
  42. package/dist/client/recoveryWorkflow/provider.js.map +1 -0
  43. package/dist/client/recoveryWorkflow/settlement.d.ts +6 -0
  44. package/dist/client/recoveryWorkflow/settlement.d.ts.map +1 -0
  45. package/dist/client/recoveryWorkflow/settlement.js +43 -0
  46. package/dist/client/recoveryWorkflow/settlement.js.map +1 -0
  47. package/dist/component/_generated/api.d.ts +30 -0
  48. package/dist/component/_generated/api.d.ts.map +1 -1
  49. package/dist/component/_generated/api.js.map +1 -1
  50. package/dist/component/_generated/component.d.ts +637 -0
  51. package/dist/component/_generated/component.d.ts.map +1 -1
  52. package/dist/component/balanceFunding/helpers.d.ts +42 -0
  53. package/dist/component/balanceFunding/helpers.d.ts.map +1 -1
  54. package/dist/component/balanceFunding/internal/actions.d.ts +39 -0
  55. package/dist/component/balanceFunding/internal/actions.d.ts.map +1 -0
  56. package/dist/component/balanceFunding/internal/actions.js +80 -0
  57. package/dist/component/balanceFunding/internal/actions.js.map +1 -0
  58. package/dist/component/balanceFunding/internal/mutations.d.ts +55 -0
  59. package/dist/component/balanceFunding/internal/mutations.d.ts.map +1 -0
  60. package/dist/component/balanceFunding/internal/mutations.js +54 -0
  61. package/dist/component/balanceFunding/internal/mutations.js.map +1 -0
  62. package/dist/component/balanceFunding/internal/queries.d.ts +116 -0
  63. package/dist/component/balanceFunding/internal/queries.d.ts.map +1 -0
  64. package/dist/component/balanceFunding/internal/queries.js +35 -0
  65. package/dist/component/balanceFunding/internal/queries.js.map +1 -0
  66. package/dist/component/balanceFunding/internal/workflow.d.ts +10 -0
  67. package/dist/component/balanceFunding/internal/workflow.d.ts.map +1 -0
  68. package/dist/component/balanceFunding/internal/workflow.js +31 -0
  69. package/dist/component/balanceFunding/internal/workflow.js.map +1 -0
  70. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +126 -0
  71. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -1
  72. package/dist/component/balanceFunding/mutations.d.ts +419 -16
  73. package/dist/component/balanceFunding/mutations.d.ts.map +1 -1
  74. package/dist/component/balanceFunding/mutations.js +24 -0
  75. package/dist/component/balanceFunding/mutations.js.map +1 -1
  76. package/dist/component/balanceFunding/preparationHandlers.d.ts +42 -0
  77. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -1
  78. package/dist/component/balanceFunding/queries.d.ts +78 -0
  79. package/dist/component/balanceFunding/queries.d.ts.map +1 -1
  80. package/dist/component/balanceFunding/queries.js +35 -0
  81. package/dist/component/balanceFunding/queries.js.map +1 -1
  82. package/dist/component/balanceFunding/receipt.d.ts +5 -0
  83. package/dist/component/balanceFunding/receipt.d.ts.map +1 -0
  84. package/dist/component/balanceFunding/receipt.js +37 -0
  85. package/dist/component/balanceFunding/receipt.js.map +1 -0
  86. package/dist/component/balanceFunding/schema.d.ts +506 -2
  87. package/dist/component/balanceFunding/schema.d.ts.map +1 -1
  88. package/dist/component/balanceFunding/schema.js +2 -0
  89. package/dist/component/balanceFunding/schema.js.map +1 -1
  90. package/dist/component/balanceFunding/stateHandlers.d.ts +42 -0
  91. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -1
  92. package/dist/component/balanceFunding/workflowControl.d.ts +19 -0
  93. package/dist/component/balanceFunding/workflowControl.d.ts.map +1 -0
  94. package/dist/component/balanceFunding/workflowControl.js +149 -0
  95. package/dist/component/balanceFunding/workflowControl.js.map +1 -0
  96. package/dist/component/balanceFunding/workflowSchema.d.ts +356 -0
  97. package/dist/component/balanceFunding/workflowSchema.d.ts.map +1 -0
  98. package/dist/component/balanceFunding/workflowSchema.js +48 -0
  99. package/dist/component/balanceFunding/workflowSchema.js.map +1 -0
  100. package/dist/component/balanceFunding/workflowState.d.ts +157 -0
  101. package/dist/component/balanceFunding/workflowState.d.ts.map +1 -0
  102. package/dist/component/balanceFunding/workflowState.js +194 -0
  103. package/dist/component/balanceFunding/workflowState.js.map +1 -0
  104. package/dist/component/balanceFunding/workflowValidators.d.ts +306 -0
  105. package/dist/component/balanceFunding/workflowValidators.d.ts.map +1 -0
  106. package/dist/component/balanceFunding/workflowValidators.js +27 -0
  107. package/dist/component/balanceFunding/workflowValidators.js.map +1 -0
  108. package/dist/component/earnings/triggers.d.ts +280 -2
  109. package/dist/component/earnings/triggers.d.ts.map +1 -1
  110. package/dist/component/payoutRelease/queries.d.ts +2 -2
  111. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  112. package/dist/component/recoveryWorkflow/bridge.d.ts +21 -0
  113. package/dist/component/recoveryWorkflow/bridge.d.ts.map +1 -0
  114. package/dist/component/recoveryWorkflow/bridge.js +52 -0
  115. package/dist/component/recoveryWorkflow/bridge.js.map +1 -0
  116. package/dist/component/recoveryWorkflow/helpers.d.ts +83 -0
  117. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -0
  118. package/dist/component/recoveryWorkflow/helpers.js +48 -0
  119. package/dist/component/recoveryWorkflow/helpers.js.map +1 -0
  120. package/dist/component/recoveryWorkflow/mutations.d.ts +91 -0
  121. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -0
  122. package/dist/component/recoveryWorkflow/mutations.js +177 -0
  123. package/dist/component/recoveryWorkflow/mutations.js.map +1 -0
  124. package/dist/component/recoveryWorkflow/queries.d.ts +118 -0
  125. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -0
  126. package/dist/component/recoveryWorkflow/queries.js +20 -0
  127. package/dist/component/recoveryWorkflow/queries.js.map +1 -0
  128. package/dist/component/recoveryWorkflow/schema.d.ts +653 -0
  129. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -0
  130. package/dist/component/recoveryWorkflow/schema.js +81 -0
  131. package/dist/component/recoveryWorkflow/schema.js.map +1 -0
  132. package/dist/component/recoveryWorkflow/steps.d.ts +70 -0
  133. package/dist/component/recoveryWorkflow/steps.d.ts.map +1 -0
  134. package/dist/component/recoveryWorkflow/steps.js +94 -0
  135. package/dist/component/recoveryWorkflow/steps.js.map +1 -0
  136. package/dist/component/recoveryWorkflow/workflow.d.ts +22 -0
  137. package/dist/component/recoveryWorkflow/workflow.d.ts.map +1 -0
  138. package/dist/component/recoveryWorkflow/workflow.js +56 -0
  139. package/dist/component/recoveryWorkflow/workflow.js.map +1 -0
  140. package/dist/component/schema.d.ts +404 -1
  141. package/dist/component/schema.js +3 -0
  142. package/dist/component/schema.js.map +1 -1
  143. package/package.json +1 -1
  144. package/src/client/balanceFundingWorkflow/capture.test.ts +144 -0
  145. package/src/client/balanceFundingWorkflow/client.ts +419 -0
  146. package/src/client/billing/balanceFunding.ts +50 -0
  147. package/src/client/costRecovery-invoices.ts +6 -0
  148. package/src/client/costRecovery.ts +8 -3
  149. package/src/client/index.ts +15 -0
  150. package/src/client/recoveryWorkflow/client.test.ts +37 -0
  151. package/src/client/recoveryWorkflow/client.ts +76 -0
  152. package/src/client/recoveryWorkflow/contracts.ts +72 -0
  153. package/src/client/recoveryWorkflow/provider.test.ts +424 -0
  154. package/src/client/recoveryWorkflow/provider.ts +119 -0
  155. package/src/client/recoveryWorkflow/settlement.ts +67 -0
  156. package/src/component/_generated/api.ts +30 -0
  157. package/src/component/_generated/component.ts +746 -0
  158. package/src/component/balanceFunding/internal/actions.ts +107 -0
  159. package/src/component/balanceFunding/internal/mutations.ts +66 -0
  160. package/src/component/balanceFunding/internal/queries.ts +34 -0
  161. package/src/component/balanceFunding/internal/workflow.ts +49 -0
  162. package/src/component/balanceFunding/mutations.ts +34 -0
  163. package/src/component/balanceFunding/queries.ts +38 -0
  164. package/src/component/balanceFunding/receipt.ts +48 -0
  165. package/src/component/balanceFunding/schema.ts +2 -0
  166. package/src/component/balanceFunding/scopeLookup.test.ts +94 -0
  167. package/src/component/balanceFunding/workflow.fixtures.ts +366 -0
  168. package/src/component/balanceFunding/workflow.test.ts +552 -0
  169. package/src/component/balanceFunding/workflowControl.ts +198 -0
  170. package/src/component/balanceFunding/workflowSchema.ts +78 -0
  171. package/src/component/balanceFunding/workflowState.ts +285 -0
  172. package/src/component/balanceFunding/workflowValidators.ts +40 -0
  173. package/src/component/recoveryWorkflow/bridge.test.ts +481 -0
  174. package/src/component/recoveryWorkflow/bridge.ts +66 -0
  175. package/src/component/recoveryWorkflow/helpers.ts +58 -0
  176. package/src/component/recoveryWorkflow/journal.test.ts +104 -0
  177. package/src/component/recoveryWorkflow/mutations.ts +224 -0
  178. package/src/component/recoveryWorkflow/queries.ts +19 -0
  179. package/src/component/recoveryWorkflow/schema.ts +92 -0
  180. package/src/component/recoveryWorkflow/state.test.ts +191 -0
  181. package/src/component/recoveryWorkflow/steps.ts +97 -0
  182. package/src/component/recoveryWorkflow/workflow.ts +73 -0
  183. package/src/component/schema.ts +6 -0
@@ -0,0 +1,419 @@
1
+ import type Stripe from "stripe";
2
+ import {
3
+ createFunctionHandle,
4
+ type FunctionReference,
5
+ type GenericActionCtx,
6
+ type GenericDataModel,
7
+ } from "convex/server";
8
+ import type { GenericId } from "convex/values";
9
+ import type { Component } from "../helpers.js";
10
+ import {
11
+ captureBalanceFundingOriginal,
12
+ getBalanceFundingCapability,
13
+ } from "../billing/balanceFunding.js";
14
+ import { resolveOwnerAccount } from "../utils/owner.js";
15
+ import {
16
+ FUNDING_WORKFLOW_VERSION,
17
+ type ProviderResult,
18
+ } from "../../component/balanceFunding/workflowSchema.js";
19
+ import type { FundingPhaseRef } from "../../component/balanceFunding/workflowValidators.js";
20
+ export type FundingProviderPhaseOptions = Omit<
21
+ FundingPhaseRef,
22
+ "operationId"
23
+ > & { operationId: string };
24
+ export type FundingProviderPhaseResult = ProviderResult;
25
+ type Context = Pick<
26
+ GenericActionCtx<GenericDataModel>,
27
+ "runQuery" | "runMutation"
28
+ >;
29
+ export type FundingOperationReference = {
30
+ accountId: string;
31
+ scopeKey: string;
32
+ stripeSubscriptionId: string;
33
+ operationId: string;
34
+ version: number;
35
+ };
36
+ export type PrepareFundingWorkflowOptions = {
37
+ accountId: string;
38
+ scopeKey: string;
39
+ stripeSubscriptionId: string;
40
+ requestKey: string;
41
+ consent: true;
42
+ consentAt: number;
43
+ consentReference: string;
44
+ providerAction: FunctionReference<"action", "public" | "internal">;
45
+ };
46
+ const uncertain = (): ProviderResult => ({
47
+ status: "unknown",
48
+ reason: "provider_outcome_unknown",
49
+ retryable: false,
50
+ });
51
+ export class BalanceFundingWorkflowClient {
52
+ constructor(
53
+ private readonly component: Component,
54
+ private readonly provider: () => Stripe,
55
+ private readonly apiVersion: string,
56
+ ) {}
57
+ private reference(args: FundingOperationReference) {
58
+ return {
59
+ accountId: args.accountId,
60
+ scopeKey: args.scopeKey,
61
+ stripeSubscriptionId: args.stripeSubscriptionId,
62
+ version: args.version,
63
+ operationId: args.operationId as GenericId<"balanceFundingOperations">,
64
+ providerApiVersion: this.apiVersion,
65
+ definitionVersion: FUNDING_WORKFLOW_VERSION,
66
+ };
67
+ }
68
+ async prepare(ctx: Context, options: PrepareFundingWorkflowOptions) {
69
+ if (
70
+ !getBalanceFundingCapability(this.apiVersion).configured ||
71
+ options.consent !== true
72
+ )
73
+ return {
74
+ status: "rejected" as const,
75
+ reason: "policy_invalid" as const,
76
+ retryable: false as const,
77
+ };
78
+ const { providerAction, consentAt, consentReference, ...lookup } = options;
79
+ const query = { ...lookup, providerApiVersion: this.apiVersion };
80
+ const prior = await ctx.runQuery(
81
+ this.component.balanceFunding.queries.findPreparationOperation,
82
+ query,
83
+ );
84
+ let operation;
85
+ if (prior && "operationId" in prior) operation = prior;
86
+ else if (prior) return prior;
87
+ else {
88
+ const { requestKey: _requestKey, consent: _consent, ...scope } = lookup;
89
+ const saved = await ctx.runQuery(
90
+ this.component.balanceFunding.queries.readScopePreparation,
91
+ { ...scope, providerApiVersion: this.apiVersion },
92
+ );
93
+ if (saved && "status" in saved) return saved;
94
+ const captured =
95
+ saved?.preparation ??
96
+ (await captureBalanceFundingOriginal(this.provider(), this.apiVersion, {
97
+ customerAccount: options.accountId,
98
+ stripeSubscriptionId: options.stripeSubscriptionId,
99
+ consent: true,
100
+ }));
101
+ const {
102
+ customerAccount,
103
+ stripeSubscriptionId,
104
+ previousPaymentMethodId,
105
+ previousPaymentMethodTypes,
106
+ } = captured;
107
+ const intent = await ctx.runMutation(
108
+ this.component.balanceFunding.mutations.prepare,
109
+ {
110
+ accountId: options.accountId,
111
+ scopeKey: options.scopeKey,
112
+ requestKey: options.requestKey,
113
+ consent: true,
114
+ consentAt: saved?.consentAt ?? consentAt,
115
+ consentReference: saved?.consentReference ?? consentReference,
116
+ providerApiVersion: this.apiVersion,
117
+ preparation: {
118
+ customerAccount,
119
+ stripeSubscriptionId,
120
+ previousPaymentMethodId,
121
+ previousPaymentMethodTypes,
122
+ },
123
+ },
124
+ );
125
+ if (intent.status !== "accepted") return intent;
126
+ operation = intent.operation;
127
+ }
128
+ return ctx.runMutation(
129
+ this.component.balanceFunding.mutations.startWorkflow,
130
+ {
131
+ ...this.reference({
132
+ ...operation,
133
+ stripeSubscriptionId: options.stripeSubscriptionId,
134
+ }),
135
+ providerAction: await createFunctionHandle(providerAction),
136
+ },
137
+ );
138
+ }
139
+ async apply(
140
+ ctx: Context,
141
+ options: {
142
+ accountId: string;
143
+ scopeKey: string;
144
+ stripeSubscriptionId: string;
145
+ preparationId: string;
146
+ enabled: boolean;
147
+ consent?: true;
148
+ requestKey: string;
149
+ providerAction: FunctionReference<"action", "public" | "internal">;
150
+ },
151
+ ) {
152
+ if (!getBalanceFundingCapability(this.apiVersion).configured)
153
+ return {
154
+ status: "rejected" as const,
155
+ reason: "policy_invalid" as const,
156
+ retryable: false as const,
157
+ };
158
+ const preparation = await ctx.runQuery(
159
+ this.component.balanceFunding.queries.readPreparation,
160
+ {
161
+ accountId: options.accountId,
162
+ scopeKey: options.scopeKey,
163
+ stripeSubscriptionId: options.stripeSubscriptionId,
164
+ preparationId: options.preparationId,
165
+ },
166
+ );
167
+ if (!preparation || preparation.providerApiVersion !== this.apiVersion)
168
+ return {
169
+ status: "conflict" as const,
170
+ reason: "identity_changed" as const,
171
+ retryable: false as const,
172
+ };
173
+ const result = await ctx.runMutation(
174
+ this.component.balanceFunding.mutations.begin,
175
+ {
176
+ accountId: options.accountId,
177
+ scopeKey: options.scopeKey,
178
+ preparationId: options.preparationId,
179
+ enabled: options.enabled,
180
+ ...(options.consent === true ? { consent: true as const } : {}),
181
+ requestKey: options.requestKey,
182
+ },
183
+ );
184
+ if (result.status !== "accepted") return result;
185
+ return ctx.runMutation(
186
+ this.component.balanceFunding.mutations.startWorkflow,
187
+ {
188
+ ...this.reference({
189
+ ...result.operation,
190
+ stripeSubscriptionId: options.stripeSubscriptionId,
191
+ }),
192
+ providerAction: await createFunctionHandle(options.providerAction),
193
+ },
194
+ );
195
+ }
196
+ inspect(ctx: Context, args: FundingOperationReference) {
197
+ return ctx.runQuery(this.component.balanceFunding.queries.getOperation, {
198
+ accountId: args.accountId,
199
+ scopeKey: args.scopeKey,
200
+ operationId: args.operationId,
201
+ version: args.version,
202
+ stripeSubscriptionId: args.stripeSubscriptionId,
203
+ });
204
+ }
205
+ resume(ctx: Context, args: FundingOperationReference) {
206
+ return ctx.runMutation(
207
+ this.component.balanceFunding.mutations.resumeWorkflow,
208
+ this.reference(args),
209
+ );
210
+ }
211
+ cancel(ctx: Context, args: FundingOperationReference) {
212
+ return ctx.runMutation(
213
+ this.component.balanceFunding.mutations.cancelWorkflow,
214
+ this.reference(args),
215
+ );
216
+ }
217
+ async executeProviderPhase(
218
+ ctx: Context,
219
+ input: FundingProviderPhaseOptions,
220
+ ): Promise<ProviderResult> {
221
+ const args = {
222
+ ...input,
223
+ operationId: input.operationId as GenericId<"balanceFundingOperations">,
224
+ };
225
+ try {
226
+ const stripe = this.provider();
227
+ if (
228
+ args.providerApiVersion !== this.apiVersion ||
229
+ stripe.getApiField("version") !== args.providerApiVersion ||
230
+ !getBalanceFundingCapability(this.apiVersion).configured
231
+ )
232
+ return {
233
+ status: "conflict",
234
+ reason: "revision_changed",
235
+ retryable: false,
236
+ };
237
+ const claim = await ctx.runMutation(
238
+ this.component.balanceFunding.mutations.claimProviderPhase,
239
+ args,
240
+ );
241
+ if (claim.status !== "claimed") return claim;
242
+ const operation = await ctx.runQuery(
243
+ this.component.balanceFunding.queries.inspectOperation,
244
+ {
245
+ accountId: args.accountId,
246
+ scopeKey: args.scopeKey,
247
+ operationId: args.operationId,
248
+ version: args.version,
249
+ stripeSubscriptionId: args.stripeSubscriptionId,
250
+ },
251
+ );
252
+ if (!operation) return uncertain();
253
+ const saved = await ctx.runQuery(
254
+ this.component.balanceFunding.queries.readPreparation,
255
+ {
256
+ accountId: args.accountId,
257
+ scopeKey: args.scopeKey,
258
+ preparationId: operation.preparationId,
259
+ stripeSubscriptionId: args.stripeSubscriptionId,
260
+ },
261
+ );
262
+ if (!saved || saved.providerApiVersion !== args.providerApiVersion)
263
+ return uncertain();
264
+ const prep = saved.preparation;
265
+ if (args.phase === "apply") {
266
+ if (!prep.paymentMethodId || !saved.verified) return uncertain();
267
+ const method = await stripe.paymentMethods.retrieve(
268
+ prep.paymentMethodId,
269
+ );
270
+ if (
271
+ method.id !== prep.paymentMethodId ||
272
+ method.type !== "stripe_balance" ||
273
+ resolveOwnerAccount(method) !== args.accountId
274
+ )
275
+ return uncertain();
276
+ let sub = await stripe.subscriptions.retrieve(
277
+ args.stripeSubscriptionId,
278
+ );
279
+ const matches = (id: string | null, types: string[] | null) => {
280
+ const pm =
281
+ typeof sub.default_payment_method === "string"
282
+ ? sub.default_payment_method
283
+ : (sub.default_payment_method?.id ?? null);
284
+ const actual = sub.payment_settings?.payment_method_types ?? null;
285
+ return (
286
+ pm === id &&
287
+ JSON.stringify(actual === null ? null : [...actual].sort()) ===
288
+ JSON.stringify(types === null ? null : [...types].sort())
289
+ );
290
+ };
291
+ const valid = () =>
292
+ sub.id === args.stripeSubscriptionId &&
293
+ sub.object === "subscription" &&
294
+ resolveOwnerAccount(sub) === args.accountId &&
295
+ ["active", "trialing", "past_due"].includes(sub.status);
296
+ const targetMethod = operation.enabled
297
+ ? prep.paymentMethodId
298
+ : prep.previousPaymentMethodId;
299
+ const targetTypes = operation.enabled
300
+ ? ["stripe_balance"]
301
+ : prep.previousPaymentMethodTypes;
302
+ if (!valid()) return uncertain();
303
+ if (!matches(targetMethod, targetTypes)) {
304
+ if (
305
+ claim.mode !== "execute" ||
306
+ (!matches(
307
+ prep.previousPaymentMethodId,
308
+ prep.previousPaymentMethodTypes,
309
+ ) &&
310
+ !matches(prep.paymentMethodId, ["stripe_balance"]))
311
+ )
312
+ return uncertain();
313
+ await stripe.subscriptions.update(
314
+ sub.id,
315
+ {
316
+ default_payment_method: targetMethod ?? "",
317
+ payment_settings: {
318
+ payment_method_types:
319
+ (targetTypes as Stripe.SubscriptionUpdateParams.PaymentSettings.PaymentMethodType[]) ??
320
+ "",
321
+ },
322
+ },
323
+ { idempotencyKey: args.providerKey, maxNetworkRetries: 0 },
324
+ );
325
+ sub = await stripe.subscriptions.retrieve(args.stripeSubscriptionId);
326
+ if (!valid() || !matches(targetMethod, targetTypes))
327
+ return uncertain();
328
+ }
329
+ return {
330
+ status: "ready",
331
+ value: {
332
+ phase: "apply",
333
+ customerAccount: args.accountId,
334
+ stripeSubscriptionId: args.stripeSubscriptionId,
335
+ providerApiVersion: args.providerApiVersion,
336
+ paymentMethodId: targetMethod,
337
+ paymentMethodTypes: targetTypes,
338
+ enabled: operation.enabled,
339
+ },
340
+ };
341
+ }
342
+ let paymentMethodId = claim.paymentMethodId;
343
+ if (args.phase === "create") {
344
+ const method = await stripe.paymentMethods.create(
345
+ { type: "stripe_balance" },
346
+ { idempotencyKey: args.providerKey, maxNetworkRetries: 0 },
347
+ );
348
+ if (
349
+ !method.id ||
350
+ method.object !== "payment_method" ||
351
+ method.type !== "stripe_balance" ||
352
+ resolveOwnerAccount(method)
353
+ )
354
+ return uncertain();
355
+ paymentMethodId = method.id;
356
+ } else {
357
+ if (!paymentMethodId) return uncertain();
358
+ let method = await stripe.paymentMethods.retrieve(paymentMethodId);
359
+ if (
360
+ method.id !== paymentMethodId ||
361
+ method.object !== "payment_method" ||
362
+ method.type !== "stripe_balance"
363
+ )
364
+ return uncertain();
365
+ if (!resolveOwnerAccount(method) && claim.mode === "execute") {
366
+ await stripe.paymentMethods.attach(
367
+ paymentMethodId,
368
+ { customer_account: args.accountId },
369
+ { idempotencyKey: args.providerKey, maxNetworkRetries: 0 },
370
+ );
371
+ method = await stripe.paymentMethods.retrieve(paymentMethodId);
372
+ }
373
+ if (
374
+ method.id !== paymentMethodId ||
375
+ resolveOwnerAccount(method) !== args.accountId
376
+ )
377
+ return uncertain();
378
+ const sub = await stripe.subscriptions.retrieve(
379
+ args.stripeSubscriptionId,
380
+ );
381
+ if (
382
+ sub.id !== args.stripeSubscriptionId ||
383
+ resolveOwnerAccount(sub) !== args.accountId ||
384
+ !["active", "trialing", "past_due"].includes(sub.status)
385
+ )
386
+ return uncertain();
387
+ const currentMethod =
388
+ typeof sub.default_payment_method === "string"
389
+ ? sub.default_payment_method
390
+ : (sub.default_payment_method?.id ?? null);
391
+ const currentTypes = sub.payment_settings?.payment_method_types ?? null;
392
+ if (
393
+ currentMethod !== prep.previousPaymentMethodId ||
394
+ JSON.stringify(
395
+ currentTypes === null ? null : [...currentTypes].sort(),
396
+ ) !==
397
+ JSON.stringify(
398
+ prep.previousPaymentMethodTypes === null
399
+ ? null
400
+ : [...prep.previousPaymentMethodTypes].sort(),
401
+ )
402
+ )
403
+ return uncertain();
404
+ }
405
+ return {
406
+ status: "ready",
407
+ value: {
408
+ phase: args.phase,
409
+ customerAccount: args.accountId,
410
+ stripeSubscriptionId: args.stripeSubscriptionId,
411
+ providerApiVersion: args.providerApiVersion,
412
+ paymentMethodId: paymentMethodId!,
413
+ },
414
+ };
415
+ } catch {
416
+ return uncertain();
417
+ }
418
+ }
419
+ }
@@ -66,6 +66,56 @@ function methodId(sub: Stripe.Subscription) {
66
66
  return typeof pm === "string" ? pm : (pm?.id ?? null);
67
67
  }
68
68
 
69
+ export type BalanceFundingOriginal = Omit<
70
+ BalanceFundingPreparation,
71
+ "paymentMethodId"
72
+ >;
73
+
74
+ /** Read only: persist this snapshot before provisioning any provider resource. */
75
+ export async function captureBalanceFundingOriginal(
76
+ stripe: Stripe,
77
+ version: string,
78
+ opts: BalanceFundingScope & { consent: true },
79
+ ): Promise<BalanceFundingOriginal> {
80
+ if (
81
+ !getBalanceFundingCapability(version).configured ||
82
+ stripe.getApiField("version") !== version
83
+ )
84
+ throw new Error(
85
+ "Balance funding capture requires matching explicit Stripe preview API configuration.",
86
+ );
87
+ if (opts.consent !== true)
88
+ throw new Error("Explicit consent is required for balance funding.");
89
+ const sub = await subscription(stripe, opts);
90
+ if (sub.id !== opts.stripeSubscriptionId || sub.object !== "subscription")
91
+ throw new Error("Captured subscription identity does not match.");
92
+ const previous = methodId(sub);
93
+ const types = sub.payment_settings?.payment_method_types ?? null;
94
+ if (types?.includes("stripe_balance"))
95
+ throw new Error(
96
+ "Balance funding is already configured; reuse the persisted restoration record.",
97
+ );
98
+ if (previous) {
99
+ const method = await stripe.paymentMethods.retrieve(previous);
100
+ if (method.id !== previous || method.object !== "payment_method")
101
+ throw new Error("Captured payment method identity does not match.");
102
+ if (resolveOwnerAccount(method) !== opts.customerAccount)
103
+ throw new Error(
104
+ "Original payment method does not belong to the account.",
105
+ );
106
+ if (method.type === "stripe_balance")
107
+ throw new Error(
108
+ "Balance funding is already configured; reuse the persisted restoration record.",
109
+ );
110
+ }
111
+ return {
112
+ customerAccount: opts.customerAccount,
113
+ stripeSubscriptionId: opts.stripeSubscriptionId,
114
+ previousPaymentMethodId: previous,
115
+ previousPaymentMethodTypes: types === null ? null : [...types],
116
+ };
117
+ }
118
+
69
119
  /** Capture restoration settings, provision and attach; does not enable billing. */
70
120
  export async function prepareBalanceFunding(
71
121
  stripe: Stripe,
@@ -21,6 +21,7 @@ export function attachRecoveryInvoice(
21
21
  opts: RecoveryInvoiceOptions,
22
22
  bind: BindInvoiceItem,
23
23
  create?: true,
24
+ maxItems?: number,
24
25
  ): Promise<InvoiceReceipt>;
25
26
  export function attachRecoveryInvoice(
26
27
  stripe: Stripe,
@@ -28,6 +29,7 @@ export function attachRecoveryInvoice(
28
29
  opts: RecoveryInvoiceOptions,
29
30
  bind: BindInvoiceItem,
30
31
  create: false,
32
+ maxItems?: number,
31
33
  ): Promise<
32
34
  | InvoiceReceipt
33
35
  | (Omit<InvoiceReceipt, "invoiceItemId"> & { invoiceItemId: null })
@@ -40,6 +42,7 @@ export async function attachRecoveryInvoice(
40
42
  opts: RecoveryInvoiceOptions,
41
43
  bind: (invoiceItemId: string) => Promise<RecoveryGroup>,
42
44
  create = true,
45
+ maxItems = Number.POSITIVE_INFINITY,
43
46
  ) {
44
47
  if (
45
48
  !group ||
@@ -66,10 +69,13 @@ export async function attachRecoveryInvoice(
66
69
  if (invoice.currency !== group.currency)
67
70
  throw new Error("Recovery invoice currency does not match.");
68
71
  let found: Stripe.InvoiceItem | undefined;
72
+ let inspected = 0;
69
73
  for await (const item of stripe.invoiceItems.list({
70
74
  invoice: invoice.id,
71
75
  limit: 100,
72
76
  })) {
77
+ if (++inspected > maxItems)
78
+ throw new Error("Recovery invoice history exceeded its item bound.");
73
79
  if (item.metadata?.[marker] !== group._id) continue;
74
80
  if (found)
75
81
  throw new Error(
@@ -1,3 +1,6 @@
1
+ import { RecoveryWorkflowClient } from "./recoveryWorkflow/client.js";
2
+ export type * from "./recoveryWorkflow/contracts.js";
3
+ export type { RecoveryProviderOptions } from "./recoveryWorkflow/provider.js";
1
4
  import type Stripe from "stripe";
2
5
  import {
3
6
  readInvoiceFunding,
@@ -96,11 +99,13 @@ export type RecoveryPreparationResult =
96
99
  retryable: false;
97
100
  };
98
101
  /** Host authorizes policy and scope. Provider methods verify invoice outcomes. */
99
- export class CostRecoveryClient {
102
+ export class CostRecoveryClient extends RecoveryWorkflowClient {
100
103
  constructor(
101
- private readonly component: Component,
104
+ protected readonly component: Component,
102
105
  private readonly provider?: () => Stripe,
103
- ) {}
106
+ ) {
107
+ super();
108
+ }
104
109
  private async mutate<T>(
105
110
  ctx: RunCtx,
106
111
  path: string,
@@ -33,6 +33,13 @@ export type {
33
33
  } from "./products/catalog.js";
34
34
  export type { CreatePriceOptions } from "./products/prices.js";
35
35
  export type { CreateProductOptions } from "./products/products.js";
36
+ import { BalanceFundingWorkflowClient } from "./balanceFundingWorkflow/client.js";
37
+ export type {
38
+ FundingOperationReference,
39
+ FundingProviderPhaseOptions,
40
+ FundingProviderPhaseResult,
41
+ PrepareFundingWorkflowOptions,
42
+ } from "./balanceFundingWorkflow/client.js";
36
43
  import { CostRecoveryClient } from "./costRecovery.js";
37
44
  export * from "./charge-currency.js";
38
45
  export * from "./costRecovery.js";
@@ -1122,6 +1129,14 @@ export class BetterStripe extends PaymentSourceClient {
1122
1129
  return new PayoutPolicyClient(this.component, () => this.stripe());
1123
1130
  }
1124
1131
 
1132
+ get balanceFundingWorkflow() {
1133
+ return new BalanceFundingWorkflowClient(
1134
+ this.component,
1135
+ () => this.stripe(),
1136
+ this.stripeApiVersion,
1137
+ );
1138
+ }
1139
+
1125
1140
  get costRecovery() {
1126
1141
  return new CostRecoveryClient(this.component, () => this.stripe());
1127
1142
  }
@@ -0,0 +1,37 @@
1
+ import { componentsGeneric } from "convex/server";
2
+ import { expect, it } from "vitest";
3
+ import { CostRecoveryClient } from "../costRecovery.js";
4
+ import type { Component, RunCtx } from "../helpers.js";
5
+ it("projects operation refs before sending them to strict component validators", async () => {
6
+ let actual: unknown;
7
+ const client = new CostRecoveryClient(
8
+ componentsGeneric().betterStripe as unknown as Component,
9
+ );
10
+ const ctx = {
11
+ runQuery: async (_ref: unknown, args: unknown) => {
12
+ actual = args;
13
+ return args;
14
+ },
15
+ } as unknown as RunCtx;
16
+ const op = {
17
+ accountId: "acct_a",
18
+ scopeKey: "store",
19
+ currency: "usd",
20
+ groupKey: "g",
21
+ operationId: "operation",
22
+ version: 1,
23
+ status: "completed" as const,
24
+ sourceId: "in_a",
25
+ sourceKind: "invoice" as const,
26
+ cancelRequested: false,
27
+ };
28
+ await client.getGroupOperation(ctx, op);
29
+ expect(actual).toEqual({
30
+ accountId: "acct_a",
31
+ scopeKey: "store",
32
+ currency: "usd",
33
+ groupKey: "g",
34
+ operationId: "operation",
35
+ version: 1,
36
+ });
37
+ });
@@ -0,0 +1,76 @@
1
+ import { createFunctionHandle } from "convex/server";
2
+ import type { Component, RunCtx } from "../helpers.js";
3
+ import { runMutationOrThrow } from "../helpers.js";
4
+ import { componentRef } from "../webhooks/helpers.js";
5
+ import { operationRef } from "./contracts.js";
6
+ import type {
7
+ RecoveryOperationRef,
8
+ RecoveryOperationStatus,
9
+ RecoveryProviderRequest,
10
+ RecoveryStartOptions,
11
+ RecoveryStartResult,
12
+ } from "./contracts.js";
13
+ import {
14
+ executeRecoveryProvider,
15
+ type RecoveryProviderOptions,
16
+ } from "./provider.js";
17
+ export abstract class RecoveryWorkflowClient {
18
+ protected abstract readonly component: Component;
19
+ /** Authorize the full scope and allocation in the host mutation. requestKey is immutable per component. */
20
+ async startGroup(
21
+ ctx: RunCtx,
22
+ opts: RecoveryStartOptions,
23
+ ): Promise<RecoveryStartResult> {
24
+ const { provider, completion, ...args } = opts;
25
+ return (await runMutationOrThrow(
26
+ ctx,
27
+ componentRef(this.component, "recoveryWorkflow/mutations/start"),
28
+ {
29
+ ...args,
30
+ provider: await createFunctionHandle(provider),
31
+ ...(completion
32
+ ? { completion: await createFunctionHandle(completion) }
33
+ : {}),
34
+ maxAttempts: opts.maxAttempts ?? 3,
35
+ retryDelayMs: opts.retryDelayMs ?? 1000,
36
+ },
37
+ )) as RecoveryStartResult;
38
+ }
39
+ getGroupOperation(
40
+ ctx: RunCtx,
41
+ op: RecoveryOperationRef,
42
+ ): Promise<RecoveryOperationStatus> {
43
+ return ctx.runQuery(
44
+ componentRef(this.component, "recoveryWorkflow/queries/get"),
45
+ operationRef(op),
46
+ ) as Promise<RecoveryOperationStatus>;
47
+ }
48
+ resumeGroup(
49
+ ctx: RunCtx,
50
+ op: RecoveryOperationRef,
51
+ ): Promise<RecoveryOperationStatus> {
52
+ return runMutationOrThrow(
53
+ ctx,
54
+ componentRef(this.component, "recoveryWorkflow/mutations/resume"),
55
+ operationRef(op),
56
+ ) as Promise<RecoveryOperationStatus>;
57
+ }
58
+ requestGroupCancel(
59
+ ctx: RunCtx,
60
+ op: RecoveryOperationRef,
61
+ ): Promise<RecoveryOperationStatus> {
62
+ return runMutationOrThrow(
63
+ ctx,
64
+ componentRef(this.component, "recoveryWorkflow/mutations/requestCancel"),
65
+ operationRef(op),
66
+ ) as Promise<RecoveryOperationStatus>;
67
+ }
68
+ /** Call only inside the registered internal host action. Inject credentials from runtime env, never workflow args. */
69
+ executeGroupProvider(
70
+ ctx: RunCtx,
71
+ request: RecoveryProviderRequest,
72
+ options: RecoveryProviderOptions,
73
+ ) {
74
+ return executeRecoveryProvider(this.component, ctx, request, options);
75
+ }
76
+ }