@fantastic.dev/better-stripe 0.45.2 → 0.47.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 (107) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +46 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +39 -16
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +78 -32
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +23 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/connect/refundSync.d.ts +32 -0
  12. package/dist/client/connect/refundSync.d.ts.map +1 -0
  13. package/dist/client/connect/refundSync.js +61 -0
  14. package/dist/client/connect/refundSync.js.map +1 -0
  15. package/dist/client/connect/refundSyncValidation.d.ts +16 -0
  16. package/dist/client/connect/refundSyncValidation.d.ts.map +1 -0
  17. package/dist/client/connect/refundSyncValidation.js +87 -0
  18. package/dist/client/connect/refundSyncValidation.js.map +1 -0
  19. package/dist/client/index.d.ts +54 -1
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/index.js +10 -3
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/client/types/triggers.d.ts +3 -2
  24. package/dist/client/types/triggers.d.ts.map +1 -1
  25. package/dist/client/webhooks/helpers.d.ts.map +1 -1
  26. package/dist/client/webhooks/helpers.js +1 -0
  27. package/dist/client/webhooks/helpers.js.map +1 -1
  28. package/dist/client/webhooks/refundReconciliation.d.ts +10 -0
  29. package/dist/client/webhooks/refundReconciliation.d.ts.map +1 -0
  30. package/dist/client/webhooks/refundReconciliation.js +41 -0
  31. package/dist/client/webhooks/refundReconciliation.js.map +1 -0
  32. package/dist/client/webhooks/refundReconciliationValidators.d.ts +68 -0
  33. package/dist/client/webhooks/refundReconciliationValidators.d.ts.map +1 -0
  34. package/dist/client/webhooks/refundReconciliationValidators.js +11 -0
  35. package/dist/client/webhooks/refundReconciliationValidators.js.map +1 -0
  36. package/dist/component/_generated/api.d.ts +12 -0
  37. package/dist/component/_generated/api.d.ts.map +1 -1
  38. package/dist/component/_generated/api.js.map +1 -1
  39. package/dist/component/_generated/component.d.ts +67 -0
  40. package/dist/component/_generated/component.d.ts.map +1 -1
  41. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  42. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  43. package/dist/component/connect/mutations.d.ts.map +1 -1
  44. package/dist/component/connect/mutations.js +2 -53
  45. package/dist/component/connect/mutations.js.map +1 -1
  46. package/dist/component/connect/refundWrites.d.ts +6 -0
  47. package/dist/component/connect/refundWrites.d.ts.map +1 -0
  48. package/dist/component/connect/refundWrites.js +56 -0
  49. package/dist/component/connect/refundWrites.js.map +1 -0
  50. package/dist/component/earnings/triggers.d.ts +46 -0
  51. package/dist/component/earnings/triggers.d.ts.map +1 -1
  52. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  53. package/dist/component/refundHistory/originalSeller.d.ts +1 -1
  54. package/dist/component/refundHistory/originalSeller.d.ts.map +1 -1
  55. package/dist/component/refundHistory/originalSeller.js.map +1 -1
  56. package/dist/component/refundSync/helpers.d.ts +43 -0
  57. package/dist/component/refundSync/helpers.d.ts.map +1 -0
  58. package/dist/component/refundSync/helpers.js +71 -0
  59. package/dist/component/refundSync/helpers.js.map +1 -0
  60. package/dist/component/refundSync/mutations.d.ts +56 -0
  61. package/dist/component/refundSync/mutations.d.ts.map +1 -0
  62. package/dist/component/refundSync/mutations.js +113 -0
  63. package/dist/component/refundSync/mutations.js.map +1 -0
  64. package/dist/component/refundSync/queries.d.ts +12 -0
  65. package/dist/component/refundSync/queries.d.ts.map +1 -0
  66. package/dist/component/refundSync/queries.js +10 -0
  67. package/dist/component/refundSync/queries.js.map +1 -0
  68. package/dist/component/refundSync/routing.d.ts +8 -0
  69. package/dist/component/refundSync/routing.d.ts.map +1 -0
  70. package/dist/component/refundSync/routing.js +42 -0
  71. package/dist/component/refundSync/routing.js.map +1 -0
  72. package/dist/component/refundSync/schema.d.ts +25 -0
  73. package/dist/component/refundSync/schema.d.ts.map +1 -0
  74. package/dist/component/refundSync/schema.js +15 -0
  75. package/dist/component/refundSync/schema.js.map +1 -0
  76. package/dist/component/refundSync/validators.d.ts +164 -0
  77. package/dist/component/refundSync/validators.d.ts.map +1 -0
  78. package/dist/component/refundSync/validators.js +32 -0
  79. package/dist/component/refundSync/validators.js.map +1 -0
  80. package/dist/component/schema.d.ts +23 -0
  81. package/dist/component/schema.js +2 -0
  82. package/dist/component/schema.js.map +1 -1
  83. package/docs/refund-context.md +82 -0
  84. package/package.json +1 -1
  85. package/src/client/connect/refundSync.test.ts +239 -0
  86. package/src/client/connect/refundSync.transport.test.ts +396 -0
  87. package/src/client/connect/refundSync.ts +125 -0
  88. package/src/client/connect/refundSyncValidation.ts +120 -0
  89. package/src/client/index.ts +34 -6
  90. package/src/client/types/triggers.ts +3 -1
  91. package/src/client/webhooks/helpers.ts +1 -0
  92. package/src/client/webhooks/refund-reconciliation.test.ts +320 -0
  93. package/src/client/webhooks/refundReconciliation.ts +80 -0
  94. package/src/client/webhooks/refundReconciliationValidators.ts +15 -0
  95. package/src/component/_generated/api.ts +12 -0
  96. package/src/component/_generated/component.ts +100 -0
  97. package/src/component/connect/mutations.ts +2 -67
  98. package/src/component/connect/refundWrites.ts +76 -0
  99. package/src/component/refundHistory/originalSeller.ts +4 -1
  100. package/src/component/refundSync/helpers.ts +99 -0
  101. package/src/component/refundSync/mutations.ts +131 -0
  102. package/src/component/refundSync/queries.ts +10 -0
  103. package/src/component/refundSync/refund-sync.test.ts +255 -0
  104. package/src/component/refundSync/routing.ts +55 -0
  105. package/src/component/refundSync/schema.ts +19 -0
  106. package/src/component/refundSync/validators.ts +35 -0
  107. package/src/component/schema.ts +2 -0
@@ -82,3 +82,85 @@ PaymentIntent's refund authority. Deny ambiguous cross-invoice/community scopes
82
82
  until a safe original-payment binding is established. A ready zero remainder
83
83
  must not enable another refund. This reader does not grant authority to remove
84
84
  access, cancel a subscription or change the original financial recipients.
85
+
86
+ ## Current refund synchronization
87
+
88
+ `betterStripe.syncRefundFromStripe(ctx, { stripeRefundId, scope })` is a separate
89
+ trusted-host operation. It retrieves the current provider refund and synchronizes
90
+ the existing component refund/payment projection. It never creates or cancels a
91
+ refund, reverses transfers, changes access or authorizes a retry. Hosts must
92
+ authenticate and authorize the original refund and provider API scope before
93
+ calling it; the method is not an application authorization boundary.
94
+
95
+ ```ts
96
+ const observation = await betterStripe.syncRefundFromStripe(ctx, {
97
+ stripeRefundId: originalRefundId,
98
+ scope: { type: "platform" },
99
+ });
100
+ // Or use { type: "connected", accountId: trustedOriginalApiAccount }.
101
+ ```
102
+
103
+ The API namespace is required and runtime validated before component/provider
104
+ access. A connected API account is not a buyer, destination merchant or seller
105
+ entitlement. Provider metadata cannot select that account. Original merchant
106
+ attribution uses the existing immutable store-allocation proof, or the original
107
+ charge's destination when needed to qualify a legacy destination fallback.
108
+ Known original merchant/PI/charge/currency/amount disagreement or ambiguous evidence
109
+ holds the observation. An unattributed refund can remain unattributed where no
110
+ legacy destination fallback would invent an owner. This does not establish seller
111
+ authorization or historical ingestion completeness.
112
+
113
+ Each current read receives a durable per-refund generation. Only the newest
114
+ claimed generation can commit the qualified snapshot and existing cumulative
115
+ payment projection together. An older completion returns `superseded` without
116
+ writing that snapshot, including when the newer read failed. Superseded is not
117
+ proof that any newer observation succeeded. `accepted` returns the generation,
118
+ `changed` and stored refund; it is an observation, not financial completion.
119
+ Current `succeeded` may legitimately become `requires_action`, `pending` or later
120
+ failure. No status ordering, provider revision or webhook timestamp is invented.
121
+
122
+ Provider or accepting-transaction failures propagate rather than falling back to
123
+ a notification snapshot. A failed pending generation is marked unknown when that
124
+ marker can be saved. Lost responses can leave a pending or accepted generation;
125
+ a fresh explicit observation obtains a new generation. It does not dispatch a
126
+ refund. The original cumulative writer remains a complete indexed collection of
127
+ all refund rows for the payment, excluding failed/canceled contributions. Failed
128
+ history is not cardinality bounded: native resource limits can abort the whole
129
+ accepting transaction, preserving the last committed projection. There is no
130
+ partial sum, silent truncation or all-backlog-capacity guarantee.
131
+
132
+ This primitive does **not** yet route the legacy signed refund webhook pipeline
133
+ through generation qualification. Legacy `upsertRefund` and raw callbacks remain
134
+ unfenced; they can still overwrite observations outside this operation. The
135
+ separate shared-pipeline integration must preserve generation qualification
136
+ through its callback transaction before hosts claim webhook-wide convergence.
137
+ The server-only Vite reference is
138
+ [`example/convex/connect/refundSync.ts`](../example/convex/connect/refundSync.ts).
139
+
140
+ ### Transactional callback seam
141
+
142
+ The maintained `webhookHandlers()` host mutation also recognizes the internal
143
+ `refundReconciled` dispatcher. It accepts a prepared current-refund generation,
144
+ commits the qualified component observation and its changed refund callback in
145
+ one host transaction, then returns the accepted observation with its verified API context. Component
146
+ document IDs are opaque strings in this host receipt; they are not IDs of host
147
+ tables or application authorization. All original refund fields remain validated.
148
+ A callback failure
149
+ rolls back the refund, accepting claim, cumulative payment and transactional host
150
+ writes together. An unchanged accepted observation returns `changed: false`
151
+ without repeating the changed callback.
152
+
153
+ This dispatcher is an internal package integration seam. Do not construct its
154
+ prepared payload from browser input or treat it as application authorization.
155
+ Hosts continue to export the maintained handler pair and supply their generated
156
+ refs; existing dispatchers retain their `null` return. Regenerate host refs when
157
+ adopting the result-bearing refund dispatcher. A legacy host returning `null`,
158
+ failed acceptance or superseded generation is unavailable, not a successful
159
+ reconciliation; the package does not silently retry a raw upsert as fallback.
160
+
161
+ The direct-component path returns the same accepted observation and rejects
162
+ superseded results. It has no application callback because no host handler was
163
+ registered. This seam does not activate signed notification reconciliation or
164
+ change existing reversal recovery. Legacy raw refund delivery remains unfenced
165
+ until that separate consumer is adopted. A successful or unchanged mirror is not
166
+ proof that a prior provider reversal or financial recovery completed.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.45.2",
3
+ "version": "0.47.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -0,0 +1,239 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { componentsGeneric, defineSchema } from "convex/server";
4
+ import { afterEach, expect, it, vi } from "vitest";
5
+ import type Stripe from "stripe";
6
+
7
+ import schema from "../../component/schema.js";
8
+ import { BetterStripe } from "../index.js";
9
+ import { getStripeClient, type Component, type RunCtx } from "../helpers.js";
10
+ import { componentRef } from "../webhooks/helpers.js";
11
+
12
+ const modules = import.meta.glob("../../component/**/*.*s");
13
+ const component = (
14
+ componentsGeneric() as unknown as { betterStripe: Component }
15
+ ).betterStripe;
16
+ const key = "sk_test_refund_sync_scope";
17
+ type Options = {
18
+ stripeRefundId: string;
19
+ scope: { type: "platform" } | { type: "connected"; accountId: string };
20
+ };
21
+ type Client = BetterStripe & {
22
+ syncRefundFromStripe?: (ctx: RunCtx, input: Options) => Promise<unknown>;
23
+ };
24
+ afterEach(() => vi.restoreAllMocks());
25
+
26
+ function fixture() {
27
+ const t = convexTest(defineSchema({}), {
28
+ "./_generated/server.ts": () =>
29
+ import("../../component/_generated/server.js"),
30
+ });
31
+ t.registerComponent("betterStripe", schema, modules);
32
+ const sdk: Client = new BetterStripe(component, { STRIPE_SECRET_KEY: key });
33
+ const ctx = { runQuery: t.query, runMutation: t.mutation } as RunCtx;
34
+ const current: Stripe.Refund = {
35
+ id: "re_original",
36
+ object: "refund",
37
+ amount: 250,
38
+ currency: "usd",
39
+ payment_intent: "pi_original",
40
+ charge: "ch_original",
41
+ status: "succeeded",
42
+ reason: "requested_by_customer",
43
+ balance_transaction: null,
44
+ created: 100,
45
+ customer: null,
46
+ customer_account: null,
47
+ payment_method: null,
48
+ receipt_number: null,
49
+ source_transfer_reversal: null,
50
+ transfer_reversal: null,
51
+ metadata: { betterStripeRefundCommand: "original-command" },
52
+ };
53
+ const retrieve = vi
54
+ .spyOn(getStripeClient(key, sdk.stripeApiVersion).refunds, "retrieve")
55
+ .mockResolvedValue(current as Stripe.Response<Stripe.Refund>);
56
+ return { t, sdk, ctx, current, retrieve };
57
+ }
58
+
59
+ it("control: preserves the current component refund writer and public identity read", async () => {
60
+ const f = fixture();
61
+ await f.t.mutation(component.connect.mutations.upsertRefund, {
62
+ stripeRefundId: "re_original",
63
+ stripePaymentIntentId: "pi_original",
64
+ stripeChargeId: "ch_original",
65
+ accountId: "acct_original_store",
66
+ amount: 250,
67
+ currency: "usd",
68
+ status: "pending",
69
+ });
70
+ expect(
71
+ await f.sdk.getRefundByStripeId(f.ctx, { stripeRefundId: "re_original" }),
72
+ ).toMatchObject({ status: "pending", amount: 250, currency: "usd" });
73
+ expect(f.retrieve).not.toHaveBeenCalled();
74
+ });
75
+
76
+ it("exposes a current-provider refund reconciliation primitive independently of webhook notifications", async () => {
77
+ const f = fixture();
78
+ expect(
79
+ f.sdk.syncRefundFromStripe,
80
+ "current refund reconciliation is missing",
81
+ ).toBeTypeOf("function");
82
+ const result = await f.sdk.syncRefundFromStripe!(f.ctx, {
83
+ stripeRefundId: "re_original",
84
+ scope: { type: "platform" },
85
+ });
86
+ expect(result).toMatchObject({
87
+ status: "accepted",
88
+ generation: 1,
89
+ changed: true,
90
+ });
91
+ expect(f.retrieve).toHaveBeenCalledWith("re_original", {}, {});
92
+ expect(
93
+ await f.sdk.getRefundByStripeId(f.ctx, { stripeRefundId: "re_original" }),
94
+ ).toMatchObject({ status: "succeeded", amount: 250, currency: "usd" });
95
+ });
96
+
97
+ it("allows current succeeded -> requires_action -> pending observations without a status rank", async () => {
98
+ const f = fixture();
99
+ await f.sdk.syncRefundFromStripe!(f.ctx, {
100
+ stripeRefundId: "re_original",
101
+ scope: { type: "platform" },
102
+ });
103
+ for (const status of [
104
+ "requires_action",
105
+ "pending",
106
+ "failed",
107
+ "canceled",
108
+ ] as const) {
109
+ f.retrieve.mockResolvedValue({
110
+ ...f.current,
111
+ status,
112
+ } as Stripe.Response<Stripe.Refund>);
113
+ expect(
114
+ await f.sdk.syncRefundFromStripe!(f.ctx, {
115
+ stripeRefundId: "re_original",
116
+ scope: { type: "platform" },
117
+ }),
118
+ ).toMatchObject({ status: "accepted", changed: true });
119
+ expect(
120
+ await f.sdk.getRefundByStripeId(f.ctx, { stripeRefundId: "re_original" }),
121
+ ).toMatchObject({ status });
122
+ }
123
+ });
124
+
125
+ it("rejects malformed API scopes and identifiers before component or provider reads", async () => {
126
+ const f = fixture();
127
+ const runQuery = vi.fn();
128
+ const runMutation = vi.fn();
129
+ const context = { runQuery, runMutation } as RunCtx;
130
+ for (const input of [
131
+ { stripeRefundId: "re_original" },
132
+ {
133
+ stripeRefundId: { toString: () => "re_original" },
134
+ scope: { type: "platform" },
135
+ },
136
+ {
137
+ stripeRefundId: "re_original",
138
+ scope: { type: "platform", accountId: "acct_guessed" },
139
+ },
140
+ {
141
+ stripeRefundId: "re_original",
142
+ scope: { type: "connected", accountId: "foreign" },
143
+ },
144
+ { stripeRefundId: " re_original", scope: { type: "platform" } },
145
+ ]) {
146
+ await expect(
147
+ f.sdk.syncRefundFromStripe!(context, input as Options),
148
+ ).rejects.toThrow();
149
+ }
150
+ expect(runQuery.mock.calls.length).toBe(0);
151
+ expect(runMutation.mock.calls.length).toBe(0);
152
+ expect(f.retrieve).not.toHaveBeenCalled();
153
+ });
154
+
155
+ it("does not let a failed first API context poison a later verified context", async () => {
156
+ const f = fixture();
157
+ f.retrieve.mockRejectedValueOnce(new Error("Provider read unavailable"));
158
+ await expect(
159
+ f.sdk.syncRefundFromStripe!(f.ctx, {
160
+ stripeRefundId: "re_original",
161
+ scope: { type: "connected", accountId: "acct_wrong" },
162
+ }),
163
+ ).rejects.toThrow("Provider read unavailable");
164
+ expect(
165
+ await f.sdk.syncRefundFromStripe!(f.ctx, {
166
+ stripeRefundId: "re_original",
167
+ scope: { type: "platform" },
168
+ }),
169
+ ).toMatchObject({ status: "accepted", generation: 2 });
170
+ await expect(
171
+ f.sdk.syncRefundFromStripe!(f.ctx, {
172
+ stripeRefundId: "re_original",
173
+ scope: { type: "connected", accountId: "acct_wrong" },
174
+ }),
175
+ ).rejects.toThrow("API context");
176
+ expect(f.retrieve).toHaveBeenCalledTimes(2);
177
+ });
178
+
179
+ it("supersedes an older delayed pending read after a newer current observation commits", async () => {
180
+ const f = fixture();
181
+ let resolve!: (value: Stripe.Response<Stripe.Refund>) => void;
182
+ const response = new Promise<Stripe.Response<Stripe.Refund>>((done) => {
183
+ resolve = done;
184
+ });
185
+ f.retrieve.mockImplementationOnce(() => response);
186
+ const old = f.sdk.syncRefundFromStripe!(f.ctx, {
187
+ stripeRefundId: "re_original",
188
+ scope: { type: "platform" },
189
+ });
190
+ await vi.waitFor(() => expect(f.retrieve).toHaveBeenCalledTimes(1));
191
+ expect(
192
+ await f.sdk.syncRefundFromStripe!(f.ctx, {
193
+ stripeRefundId: "re_original",
194
+ scope: { type: "platform" },
195
+ }),
196
+ ).toMatchObject({ status: "accepted", generation: 2 });
197
+ resolve({
198
+ ...f.current,
199
+ status: "pending",
200
+ } as Stripe.Response<Stripe.Refund>);
201
+ expect(await old).toMatchObject({ status: "superseded", generation: 1 });
202
+ expect(
203
+ await f.sdk.getRefundByStripeId(f.ctx, { stripeRefundId: "re_original" }),
204
+ ).toMatchObject({ status: "succeeded" });
205
+ });
206
+
207
+ it("does not accept an old snapshot when the newer generation's current read failed", async () => {
208
+ const f = fixture();
209
+ let resolve!: (value: Stripe.Response<Stripe.Refund>) => void;
210
+ const response = new Promise<Stripe.Response<Stripe.Refund>>((done) => {
211
+ resolve = done;
212
+ });
213
+ f.retrieve.mockImplementationOnce(() => response);
214
+ const old = f.sdk.syncRefundFromStripe!(f.ctx, {
215
+ stripeRefundId: "re_original",
216
+ scope: { type: "platform" },
217
+ });
218
+ await vi.waitFor(() => expect(f.retrieve).toHaveBeenCalledTimes(1));
219
+ f.retrieve.mockRejectedValueOnce(new Error("Current read failed"));
220
+ await expect(
221
+ f.sdk.syncRefundFromStripe!(f.ctx, {
222
+ stripeRefundId: "re_original",
223
+ scope: { type: "platform" },
224
+ }),
225
+ ).rejects.toThrow("Current read failed");
226
+ resolve(f.current as Stripe.Response<Stripe.Refund>);
227
+ expect(await old).toMatchObject({ status: "superseded" });
228
+ expect(
229
+ await f.sdk.getRefundByStripeId(f.ctx, { stripeRefundId: "re_original" }),
230
+ ).toBeNull();
231
+ expect(
232
+ await f.t.query(componentRef(component, "refundSync/queries/routing"), {
233
+ stripeRefundId: "re_original",
234
+ stripePaymentIntentId: "pi_original",
235
+ stripeChargeId: "ch_original",
236
+ currency: "usd",
237
+ }),
238
+ ).toMatchObject({ status: "unknown" });
239
+ });