@fantastic.dev/better-stripe 0.40.0 → 0.41.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 (98) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +442 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +237 -16
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +442 -0
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +237 -16
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/costRecovery-invoices.d.ts +2 -2
  12. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  13. package/dist/client/costRecovery-invoices.js +4 -1
  14. package/dist/client/costRecovery-invoices.js.map +1 -1
  15. package/dist/client/costRecovery.d.ts +5 -2
  16. package/dist/client/costRecovery.d.ts.map +1 -1
  17. package/dist/client/costRecovery.js +3 -1
  18. package/dist/client/costRecovery.js.map +1 -1
  19. package/dist/client/recoveryWorkflow/client.d.ts +14 -0
  20. package/dist/client/recoveryWorkflow/client.d.ts.map +1 -0
  21. package/dist/client/recoveryWorkflow/client.js +34 -0
  22. package/dist/client/recoveryWorkflow/client.js.map +1 -0
  23. package/dist/client/recoveryWorkflow/contracts.d.ts +63 -0
  24. package/dist/client/recoveryWorkflow/contracts.d.ts.map +1 -0
  25. package/dist/client/recoveryWorkflow/contracts.js +11 -0
  26. package/dist/client/recoveryWorkflow/contracts.js.map +1 -0
  27. package/dist/client/recoveryWorkflow/provider.d.ts +10 -0
  28. package/dist/client/recoveryWorkflow/provider.d.ts.map +1 -0
  29. package/dist/client/recoveryWorkflow/provider.js +80 -0
  30. package/dist/client/recoveryWorkflow/provider.js.map +1 -0
  31. package/dist/client/recoveryWorkflow/settlement.d.ts +6 -0
  32. package/dist/client/recoveryWorkflow/settlement.d.ts.map +1 -0
  33. package/dist/client/recoveryWorkflow/settlement.js +43 -0
  34. package/dist/client/recoveryWorkflow/settlement.js.map +1 -0
  35. package/dist/component/_generated/api.d.ts +12 -0
  36. package/dist/component/_generated/api.d.ts.map +1 -1
  37. package/dist/component/_generated/api.js.map +1 -1
  38. package/dist/component/_generated/component.d.ts +164 -0
  39. package/dist/component/_generated/component.d.ts.map +1 -1
  40. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  41. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  42. package/dist/component/earnings/triggers.d.ts +210 -16
  43. package/dist/component/earnings/triggers.d.ts.map +1 -1
  44. package/dist/component/payoutRelease/queries.d.ts +2 -2
  45. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  46. package/dist/component/recoveryWorkflow/bridge.d.ts +21 -0
  47. package/dist/component/recoveryWorkflow/bridge.d.ts.map +1 -0
  48. package/dist/component/recoveryWorkflow/bridge.js +52 -0
  49. package/dist/component/recoveryWorkflow/bridge.js.map +1 -0
  50. package/dist/component/recoveryWorkflow/helpers.d.ts +83 -0
  51. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -0
  52. package/dist/component/recoveryWorkflow/helpers.js +48 -0
  53. package/dist/component/recoveryWorkflow/helpers.js.map +1 -0
  54. package/dist/component/recoveryWorkflow/mutations.d.ts +91 -0
  55. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -0
  56. package/dist/component/recoveryWorkflow/mutations.js +177 -0
  57. package/dist/component/recoveryWorkflow/mutations.js.map +1 -0
  58. package/dist/component/recoveryWorkflow/queries.d.ts +118 -0
  59. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -0
  60. package/dist/component/recoveryWorkflow/queries.js +20 -0
  61. package/dist/component/recoveryWorkflow/queries.js.map +1 -0
  62. package/dist/component/recoveryWorkflow/schema.d.ts +653 -0
  63. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -0
  64. package/dist/component/recoveryWorkflow/schema.js +81 -0
  65. package/dist/component/recoveryWorkflow/schema.js.map +1 -0
  66. package/dist/component/recoveryWorkflow/steps.d.ts +70 -0
  67. package/dist/component/recoveryWorkflow/steps.d.ts.map +1 -0
  68. package/dist/component/recoveryWorkflow/steps.js +94 -0
  69. package/dist/component/recoveryWorkflow/steps.js.map +1 -0
  70. package/dist/component/recoveryWorkflow/workflow.d.ts +22 -0
  71. package/dist/component/recoveryWorkflow/workflow.d.ts.map +1 -0
  72. package/dist/component/recoveryWorkflow/workflow.js +56 -0
  73. package/dist/component/recoveryWorkflow/workflow.js.map +1 -0
  74. package/dist/component/schema.d.ts +221 -0
  75. package/dist/component/schema.js +3 -0
  76. package/dist/component/schema.js.map +1 -1
  77. package/package.json +1 -1
  78. package/src/client/costRecovery-invoices.ts +6 -0
  79. package/src/client/costRecovery.ts +8 -3
  80. package/src/client/recoveryWorkflow/client.test.ts +37 -0
  81. package/src/client/recoveryWorkflow/client.ts +76 -0
  82. package/src/client/recoveryWorkflow/contracts.ts +72 -0
  83. package/src/client/recoveryWorkflow/provider.test.ts +424 -0
  84. package/src/client/recoveryWorkflow/provider.ts +119 -0
  85. package/src/client/recoveryWorkflow/settlement.ts +67 -0
  86. package/src/component/_generated/api.ts +12 -0
  87. package/src/component/_generated/component.ts +222 -0
  88. package/src/component/recoveryWorkflow/bridge.test.ts +481 -0
  89. package/src/component/recoveryWorkflow/bridge.ts +66 -0
  90. package/src/component/recoveryWorkflow/helpers.ts +58 -0
  91. package/src/component/recoveryWorkflow/journal.test.ts +104 -0
  92. package/src/component/recoveryWorkflow/mutations.ts +224 -0
  93. package/src/component/recoveryWorkflow/queries.ts +19 -0
  94. package/src/component/recoveryWorkflow/schema.ts +92 -0
  95. package/src/component/recoveryWorkflow/state.test.ts +191 -0
  96. package/src/component/recoveryWorkflow/steps.ts +97 -0
  97. package/src/component/recoveryWorkflow/workflow.ts +73 -0
  98. package/src/component/schema.ts +6 -0
@@ -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,
@@ -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
+ }
@@ -0,0 +1,72 @@
1
+ import type { FunctionReference } from "convex/server";
2
+ import type { RecoveryScope } from "../costRecovery.js";
3
+ import type { ResolvedSettlement } from "../settlement/execution.js";
4
+ export type RecoveryOperationRef = RecoveryScope & {
5
+ groupKey: string;
6
+ operationId: string;
7
+ version: number;
8
+ };
9
+ export type RecoveryOperationStatus = RecoveryOperationRef & {
10
+ sourceKind: "settlement" | "invoice";
11
+ sourceId: string;
12
+ status:
13
+ "queued" | "running" | "waiting" | "unknown" | "completed" | "canceled";
14
+ cancelRequested: boolean;
15
+ outcome?: "collect" | "release";
16
+ };
17
+ export type RecoveryProviderRequest = RecoveryOperationRef & {
18
+ phase: "execute" | "reconcile";
19
+ providerApiVersion: string;
20
+ definitionVersion: number;
21
+ };
22
+ export type RecoveryProviderReceipt = RecoveryProviderRequest & {
23
+ sourceId: string;
24
+ } & (
25
+ | { status: "ready"; outcome: "collect" | "release" }
26
+ | { status: "not_ready"; reason: "provider_pending" }
27
+ | { status: "unknown"; reason: "provider_outcome_unknown" }
28
+ );
29
+ export type RecoveryStartOptions = RecoveryScope & {
30
+ groupKey: string;
31
+ requestKey: string;
32
+ provider: FunctionReference<
33
+ "action",
34
+ "internal",
35
+ RecoveryProviderRequest,
36
+ RecoveryProviderReceipt
37
+ >;
38
+ completion?: FunctionReference<
39
+ "mutation",
40
+ "internal",
41
+ RecoveryOperationStatus,
42
+ unknown
43
+ >;
44
+ providerApiVersion: string;
45
+ definitionVersion: 1;
46
+ releaseUncollectible: boolean;
47
+ allocation?: ResolvedSettlement;
48
+ maxAttempts?: number;
49
+ retryDelayMs?: number;
50
+ };
51
+ export type RecoveryStartResult =
52
+ | RecoveryOperationStatus
53
+ | { status: "conflict"; reason: "identity_changed"; retryable: false }
54
+ | { status: "not_ready"; reason: "history_incomplete"; retryable: true };
55
+ export type RecoverySnapshot = RecoveryOperationStatus & {
56
+ providerStarted: boolean;
57
+ activePhase?: "execute" | "reconcile";
58
+ providerApiVersion: string;
59
+ definitionVersion: number;
60
+ allocation?: ResolvedSettlement;
61
+ releaseUncollectible: boolean;
62
+ };
63
+ export function operationRef(op: RecoveryOperationRef): RecoveryOperationRef {
64
+ return {
65
+ accountId: op.accountId,
66
+ scopeKey: op.scopeKey,
67
+ currency: op.currency,
68
+ groupKey: op.groupKey,
69
+ operationId: op.operationId,
70
+ version: op.version,
71
+ };
72
+ }
@@ -0,0 +1,424 @@
1
+ import Stripe from "stripe";
2
+ import workflowTest from "@convex-dev/workflow/test";
3
+ import { componentsGeneric, type FunctionReference } from "convex/server";
4
+ import { expect, it } from "vitest";
5
+ import { initConvexTest } from "../setup.test.js";
6
+ import schema from "../../component/schema.js";
7
+ import { CostRecoveryClient } from "../costRecovery.js";
8
+ import type { Component, RunCtx } from "../helpers.js";
9
+ import type { RecoveryProviderRequest } from "./contracts.js";
10
+ const modules = import.meta.glob("../../component/**/*.ts");
11
+ const nested = componentsGeneric();
12
+ const scope = {
13
+ accountId: "acct_owner",
14
+ scopeKey: "store",
15
+ currency: "usd",
16
+ groupKey: "group",
17
+ };
18
+ async function setup(
19
+ kind: "invoice" | "settlement" = "invoice",
20
+ dispatch = true,
21
+ releaseUncollectible = false,
22
+ ) {
23
+ const t = initConvexTest();
24
+ t.registerComponent("betterStripe", schema, modules);
25
+ workflowTest.register(t, "betterStripe/workflow");
26
+ const component = nested.betterStripe as unknown as Component;
27
+ const client = new CostRecoveryClient(component);
28
+ let writes = 0,
29
+ failWrite = 0;
30
+ const ctx = {
31
+ runQuery: (
32
+ ref: FunctionReference<"query">,
33
+ args: Record<string, unknown>,
34
+ ) => t.query(ref, args),
35
+ runMutation: (
36
+ ref: FunctionReference<"mutation">,
37
+ args: Record<string, unknown>,
38
+ ) => {
39
+ if (++writes === failWrite) throw new Error("private database detail");
40
+ return t.mutation(ref, args);
41
+ },
42
+ } as unknown as RunCtx;
43
+ await client.recordClaim(ctx, {
44
+ accountId: scope.accountId,
45
+ scopeKey: scope.scopeKey,
46
+ currency: scope.currency,
47
+ claimKey: "claim",
48
+ sourceChargeId: "ch_original",
49
+ sourceGross: 1000,
50
+ sourceProcessingFee: 30,
51
+ amountDue: 30,
52
+ revision: 1,
53
+ });
54
+ const allocation = {
55
+ sourceChargeId: "ch_source",
56
+ gross: 1000,
57
+ currency: "usd",
58
+ processingFee: 30,
59
+ platformNet: 40,
60
+ adjustmentAmount: 30,
61
+ transfers: [
62
+ {
63
+ destinationAccountId: "acct_seller",
64
+ role: "store" as const,
65
+ amount: 900,
66
+ },
67
+ ],
68
+ };
69
+ await client.prepareGroup(ctx, {
70
+ ...scope,
71
+ ...(kind === "settlement"
72
+ ? {
73
+ sourceKind: "settlement" as const,
74
+ sourceId: "ch_source",
75
+ sourceGross: 1000,
76
+ sourceProcessingFee: 30,
77
+ }
78
+ : { sourceKind: "invoice" as const, sourceId: "in_source" }),
79
+ maxDebit: 1000,
80
+ maxCredit: 0,
81
+ });
82
+ const op = await t.mutation(
83
+ nested.betterStripe.recoveryWorkflow.mutations.start,
84
+ {
85
+ ...scope,
86
+ requestKey: "request",
87
+ provider: "function://fixture/provider",
88
+ providerApiVersion: "2026-09-30.endive",
89
+ definitionVersion: 1,
90
+ releaseUncollectible,
91
+ maxAttempts: 2,
92
+ retryDelayMs: 1,
93
+ ...(kind === "settlement" ? { allocation } : {}),
94
+ },
95
+ );
96
+ const request: RecoveryProviderRequest = {
97
+ ...scope,
98
+ operationId: op.operationId,
99
+ version: op.version,
100
+ phase: "execute",
101
+ providerApiVersion: "2026-09-30.endive",
102
+ definitionVersion: 1,
103
+ };
104
+ if (dispatch)
105
+ await t.mutation(nested.betterStripe.recoveryWorkflow.steps.beginProvider, {
106
+ ...scope,
107
+ operationId: op.operationId,
108
+ version: 1,
109
+ phase: "execute",
110
+ });
111
+ return {
112
+ dispatchReconcile: () =>
113
+ t.mutation(nested.betterStripe.recoveryWorkflow.steps.beginProvider, {
114
+ ...scope,
115
+ operationId: op.operationId,
116
+ version: 1,
117
+ phase: "reconcile",
118
+ }),
119
+ t,
120
+ client,
121
+ ctx,
122
+ request,
123
+ group: (await client.getGroup(ctx, { groupKey: scope.groupKey }))!,
124
+ failNext: (offset = 1) => {
125
+ failWrite = writes + offset;
126
+ },
127
+ };
128
+ }
129
+ it("recovers invoice-item provider success/database failure with the real Stripe SDK and original key", async () => {
130
+ const f = await setup();
131
+ let status = "draft";
132
+ let item: Record<string, unknown> | null = null;
133
+ let creates = 0;
134
+ const headers: {
135
+ version: string | null;
136
+ authorized: boolean;
137
+ key: string | null;
138
+ }[] = [];
139
+ const httpClient = Stripe.createFetchHttpClient(async (url, init) => {
140
+ const h = new Headers(init?.headers);
141
+ headers.push({
142
+ version: h.get("Stripe-Version"),
143
+ authorized: h.get("Authorization") === "Bearer sk_test_runtime_only",
144
+ key: h.get("Idempotency-Key"),
145
+ });
146
+ let body: unknown;
147
+ if (String(url).includes("/invoices/"))
148
+ body = {
149
+ id: "in_source",
150
+ customer_account: scope.accountId,
151
+ currency: "usd",
152
+ status,
153
+ };
154
+ else if (init?.method === "POST") {
155
+ creates++;
156
+ item = {
157
+ id: "ii_recovery",
158
+ invoice: "in_source",
159
+ customer_account: scope.accountId,
160
+ currency: "usd",
161
+ amount: 30,
162
+ discountable: false,
163
+ metadata: { bsRecoveryGroup: f.group._id },
164
+ };
165
+ body = item;
166
+ } else body = { object: "list", data: item ? [item] : [], has_more: false };
167
+ return new Response(JSON.stringify(body), {
168
+ status: 200,
169
+ headers: { "content-type": "application/json" },
170
+ });
171
+ });
172
+ f.failNext();
173
+ expect(
174
+ await f.client.executeGroupProvider(f.ctx, f.request, {
175
+ stripeSecretKey: "sk_test_runtime_only",
176
+ httpClient,
177
+ }),
178
+ ).toMatchObject({ status: "unknown" });
179
+ expect(creates).toBe(1);
180
+ status = "paid";
181
+ await f.dispatchReconcile();
182
+ expect(
183
+ await f.client.executeGroupProvider(
184
+ f.ctx,
185
+ { ...f.request, phase: "reconcile" },
186
+ { stripeSecretKey: "sk_test_runtime_only", httpClient },
187
+ ),
188
+ ).toMatchObject({
189
+ status: "ready",
190
+ outcome: "collect",
191
+ sourceId: "in_source",
192
+ });
193
+ expect(creates).toBe(1);
194
+ expect(
195
+ headers.every(
196
+ (h) => h.authorized && h.version === f.request.providerApiVersion,
197
+ ),
198
+ ).toBe(true);
199
+ expect(headers.find((h) => h.key)?.key).toBe(
200
+ `better-stripe:recovery:${f.group._id}`,
201
+ );
202
+ expect(
203
+ (await f.client.getGroup(f.ctx, { groupKey: scope.groupKey }))?.status,
204
+ ).toBe("sealed");
205
+ });
206
+ it("recovers a successful transfer after mirror failure without another provider write", async () => {
207
+ const f = await setup("settlement");
208
+ let transfer: Record<string, unknown> | null = null;
209
+ let creates = 0;
210
+ const httpClient = Stripe.createFetchHttpClient(async (url, init) => {
211
+ let body: unknown;
212
+ if (String(url).includes("/charges/"))
213
+ body = { id: "ch_source", created: 1 };
214
+ else if (init?.method === "POST") {
215
+ creates++;
216
+ transfer = {
217
+ id: "tr_source",
218
+ destination: "acct_seller",
219
+ amount: 900,
220
+ currency: "usd",
221
+ source_transaction: "ch_source",
222
+ amount_reversed: 0,
223
+ metadata: { bsRole: "store", bsSourceCharge: "ch_source" },
224
+ };
225
+ body = transfer;
226
+ } else
227
+ body = {
228
+ object: "list",
229
+ data: transfer ? [transfer] : [],
230
+ has_more: false,
231
+ };
232
+ return new Response(JSON.stringify(body), {
233
+ status: 200,
234
+ headers: { "content-type": "application/json" },
235
+ });
236
+ });
237
+ f.failNext(2); // Reserve allocation succeeds; transfer mirror fails after provider success.
238
+ expect(
239
+ await f.client.executeGroupProvider(f.ctx, f.request, {
240
+ stripeSecretKey: "sk_test_runtime_only",
241
+ httpClient,
242
+ }),
243
+ ).toMatchObject({ status: "unknown" });
244
+ expect(creates).toBe(1);
245
+ await f.dispatchReconcile();
246
+ expect(
247
+ await f.client.executeGroupProvider(
248
+ f.ctx,
249
+ { ...f.request, phase: "reconcile" },
250
+ { stripeSecretKey: "sk_test_runtime_only", httpClient },
251
+ ),
252
+ ).toMatchObject({ status: "ready", outcome: "collect" });
253
+ expect(creates).toBe(1);
254
+ expect(
255
+ await f.t.query(nested.betterStripe.connect.queries.listTransfersByCharge, {
256
+ sourceChargeId: "ch_source",
257
+ }),
258
+ ).toMatchObject([{ stripeTransferId: "tr_source", amount: 900 }]);
259
+ });
260
+ it("holds missing settlement legs on reconciliation and never creates them", async () => {
261
+ const f = await setup("settlement");
262
+ let creates = 0;
263
+ const httpClient = Stripe.createFetchHttpClient(async (url, init) => {
264
+ if (init?.method === "POST") creates++;
265
+ const body = String(url).includes("/charges/")
266
+ ? { id: "ch_source", created: 1 }
267
+ : { object: "list", data: [], has_more: false };
268
+ return new Response(JSON.stringify(body), {
269
+ status: 200,
270
+ headers: { "content-type": "application/json" },
271
+ });
272
+ });
273
+ await f.dispatchReconcile();
274
+ expect(
275
+ await f.client.executeGroupProvider(
276
+ f.ctx,
277
+ { ...f.request, phase: "reconcile" },
278
+ { stripeSecretKey: "sk_test_runtime_only", httpClient },
279
+ ),
280
+ ).toMatchObject({ status: "unknown" });
281
+ expect(creates).toBe(0);
282
+ });
283
+
284
+ it("refuses provider work without an active persisted dispatch", async () => {
285
+ const f = await setup("invoice", false);
286
+ let calls = 0;
287
+ const httpClient = Stripe.createFetchHttpClient(async () => {
288
+ calls++;
289
+ return new Response("{}", { status: 200 });
290
+ });
291
+ expect(
292
+ await f.client.executeGroupProvider(f.ctx, f.request, {
293
+ stripeSecretKey: "sk_test_runtime_only",
294
+ httpClient,
295
+ }),
296
+ ).toMatchObject({ status: "unknown" });
297
+ expect(calls).toBe(0);
298
+ });
299
+ it("holds incomplete invoice history instead of creating an item after the scan bound", async () => {
300
+ const f = await setup();
301
+ let creates = 0;
302
+ const httpClient = Stripe.createFetchHttpClient(async (url, init) => {
303
+ if (init?.method === "POST") creates++;
304
+ const body = String(url).includes("/invoices/")
305
+ ? {
306
+ id: "in_source",
307
+ customer_account: scope.accountId,
308
+ currency: "usd",
309
+ status: "draft",
310
+ }
311
+ : {
312
+ object: "list",
313
+ data: Array.from({ length: 10001 }, (_, i) => ({
314
+ id: `ii_other_${i}`,
315
+ metadata: {},
316
+ })),
317
+ has_more: false,
318
+ };
319
+ return new Response(JSON.stringify(body), {
320
+ status: 200,
321
+ headers: { "content-type": "application/json" },
322
+ });
323
+ });
324
+ expect(
325
+ await f.client.executeGroupProvider(f.ctx, f.request, {
326
+ stripeSecretKey: "sk_test_runtime_only",
327
+ httpClient,
328
+ }),
329
+ ).toMatchObject({ status: "unknown" });
330
+ expect(creates).toBe(0);
331
+ });
332
+ it("rejects a changed provider definition or API version before transport", async () => {
333
+ const f = await setup();
334
+ let calls = 0;
335
+ const httpClient = Stripe.createFetchHttpClient(async () => {
336
+ calls++;
337
+ return new Response("{}", { status: 200 });
338
+ });
339
+ for (const patch of [
340
+ { providerApiVersion: "2026-01-01.changed" },
341
+ { definitionVersion: 2 },
342
+ { phase: "reconcile" as const },
343
+ ]) {
344
+ expect(
345
+ await f.client.executeGroupProvider(
346
+ f.ctx,
347
+ { ...f.request, ...patch },
348
+ { stripeSecretKey: "sk_test_runtime_only", httpClient },
349
+ ),
350
+ ).toMatchObject({ status: "unknown" });
351
+ }
352
+ expect(calls).toBe(0);
353
+ });
354
+ it("accepts a terminal void invoice without attempting to create an item", async () => {
355
+ const f = await setup();
356
+ let creates = 0;
357
+ const httpClient = Stripe.createFetchHttpClient(async (url, init) => {
358
+ if (init?.method === "POST") creates++;
359
+ const body = String(url).includes("/invoices/")
360
+ ? {
361
+ id: "in_source",
362
+ customer_account: scope.accountId,
363
+ currency: "usd",
364
+ status: "void",
365
+ }
366
+ : { object: "list", data: [], has_more: false };
367
+ return new Response(JSON.stringify(body), {
368
+ status: 200,
369
+ headers: { "content-type": "application/json" },
370
+ });
371
+ });
372
+ expect(
373
+ await f.client.executeGroupProvider(f.ctx, f.request, {
374
+ stripeSecretKey: "sk_test_runtime_only",
375
+ httpClient,
376
+ }),
377
+ ).toMatchObject({ status: "ready", outcome: "release" });
378
+ expect(creates).toBe(0);
379
+ });
380
+
381
+ it.each([false, true])(
382
+ "pins explicit uncollectible release policy %s",
383
+ async (release) => {
384
+ const f = await setup("invoice", true, release);
385
+ const httpClient = Stripe.createFetchHttpClient(async (url) => {
386
+ const body = String(url).includes("/invoices/")
387
+ ? {
388
+ id: "in_source",
389
+ customer_account: scope.accountId,
390
+ currency: "usd",
391
+ status: "uncollectible",
392
+ }
393
+ : {
394
+ object: "list",
395
+ data: [
396
+ {
397
+ id: "ii_recovery",
398
+ invoice: "in_source",
399
+ customer_account: scope.accountId,
400
+ currency: "usd",
401
+ amount: 30,
402
+ discountable: false,
403
+ metadata: { bsRecoveryGroup: f.group._id },
404
+ },
405
+ ],
406
+ has_more: false,
407
+ };
408
+ return new Response(JSON.stringify(body), {
409
+ status: 200,
410
+ headers: { "content-type": "application/json" },
411
+ });
412
+ });
413
+ expect(
414
+ await f.client.executeGroupProvider(f.ctx, f.request, {
415
+ stripeSecretKey: "sk_test_runtime_only",
416
+ httpClient,
417
+ }),
418
+ ).toMatchObject(
419
+ release
420
+ ? { status: "ready", outcome: "release" }
421
+ : { status: "not_ready", reason: "provider_pending" },
422
+ );
423
+ },
424
+ );