@fantastic.dev/better-stripe 0.38.0 → 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 (127) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/MIGRATION.md +9 -0
  3. package/README.md +21 -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/costRecovery.d.ts +18 -0
  13. package/dist/client/costRecovery.d.ts.map +1 -1
  14. package/dist/client/costRecovery.js +4 -0
  15. package/dist/client/costRecovery.js.map +1 -1
  16. package/dist/client/index.d.ts +1 -0
  17. package/dist/client/index.d.ts.map +1 -1
  18. package/dist/client/index.js +1 -0
  19. package/dist/client/index.js.map +1 -1
  20. package/dist/client/processingCostDeficit/index.d.ts +27 -0
  21. package/dist/client/processingCostDeficit/index.d.ts.map +1 -0
  22. package/dist/client/processingCostDeficit/index.js +54 -0
  23. package/dist/client/processingCostDeficit/index.js.map +1 -0
  24. package/dist/component/_generated/api.d.ts +284 -0
  25. package/dist/component/_generated/api.d.ts.map +1 -0
  26. package/dist/component/_generated/api.js +31 -0
  27. package/dist/component/_generated/api.js.map +1 -0
  28. package/dist/component/_generated/component.d.ts +527 -0
  29. package/dist/component/_generated/component.d.ts.map +1 -1
  30. package/dist/component/balanceFunding/helpers.d.ts +86 -0
  31. package/dist/component/balanceFunding/helpers.d.ts.map +1 -0
  32. package/dist/component/balanceFunding/helpers.js +68 -0
  33. package/dist/component/balanceFunding/helpers.js.map +1 -0
  34. package/dist/component/balanceFunding/importHandler.d.ts +13 -0
  35. package/dist/component/balanceFunding/importHandler.d.ts.map +1 -0
  36. package/dist/component/balanceFunding/importHandler.js +130 -0
  37. package/dist/component/balanceFunding/importHandler.js.map +1 -0
  38. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +85 -0
  39. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -0
  40. package/dist/component/balanceFunding/lifecycleHandlers.js +60 -0
  41. package/dist/component/balanceFunding/lifecycleHandlers.js.map +1 -0
  42. package/dist/component/balanceFunding/mutationValidators.d.ts +238 -0
  43. package/dist/component/balanceFunding/mutationValidators.d.ts.map +1 -0
  44. package/dist/component/balanceFunding/mutationValidators.js +55 -0
  45. package/dist/component/balanceFunding/mutationValidators.js.map +1 -0
  46. package/dist/component/balanceFunding/mutations.d.ts +335 -0
  47. package/dist/component/balanceFunding/mutations.d.ts.map +1 -0
  48. package/dist/component/balanceFunding/mutations.js +106 -0
  49. package/dist/component/balanceFunding/mutations.js.map +1 -0
  50. package/dist/component/balanceFunding/preparationHandlers.d.ts +55 -0
  51. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -0
  52. package/dist/component/balanceFunding/preparationHandlers.js +165 -0
  53. package/dist/component/balanceFunding/preparationHandlers.js.map +1 -0
  54. package/dist/component/balanceFunding/queries.d.ts +151 -0
  55. package/dist/component/balanceFunding/queries.d.ts.map +1 -0
  56. package/dist/component/balanceFunding/queries.js +180 -0
  57. package/dist/component/balanceFunding/queries.js.map +1 -0
  58. package/dist/component/balanceFunding/schema.d.ts +748 -0
  59. package/dist/component/balanceFunding/schema.d.ts.map +1 -0
  60. package/dist/component/balanceFunding/schema.js +124 -0
  61. package/dist/component/balanceFunding/schema.js.map +1 -0
  62. package/dist/component/balanceFunding/stateHandlers.d.ts +58 -0
  63. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -0
  64. package/dist/component/balanceFunding/stateHandlers.js +160 -0
  65. package/dist/component/balanceFunding/stateHandlers.js.map +1 -0
  66. package/dist/component/convex.config.d.ts.map +1 -1
  67. package/dist/component/convex.config.js +2 -0
  68. package/dist/component/convex.config.js.map +1 -1
  69. package/dist/component/costRecovery/completion.d.ts +1 -0
  70. package/dist/component/costRecovery/completion.d.ts.map +1 -1
  71. package/dist/component/costRecovery/helpers.d.ts +1 -0
  72. package/dist/component/costRecovery/helpers.d.ts.map +1 -1
  73. package/dist/component/costRecovery/mutations.d.ts +5 -0
  74. package/dist/component/costRecovery/mutations.d.ts.map +1 -1
  75. package/dist/component/costRecovery/preparation.d.ts +50 -0
  76. package/dist/component/costRecovery/preparation.d.ts.map +1 -0
  77. package/dist/component/costRecovery/preparation.js +108 -0
  78. package/dist/component/costRecovery/preparation.js.map +1 -0
  79. package/dist/component/costRecovery/queries.d.ts +1 -0
  80. package/dist/component/costRecovery/queries.d.ts.map +1 -1
  81. package/dist/component/costRecovery/reservations.d.ts +2 -0
  82. package/dist/component/costRecovery/reservations.d.ts.map +1 -1
  83. package/dist/component/costRecovery/schema.d.ts +7 -2
  84. package/dist/component/costRecovery/schema.d.ts.map +1 -1
  85. package/dist/component/costRecovery/schema.js +1 -0
  86. package/dist/component/costRecovery/schema.js.map +1 -1
  87. package/dist/component/durableExecution/runtime.d.ts +3 -0
  88. package/dist/component/durableExecution/runtime.d.ts.map +1 -0
  89. package/dist/component/durableExecution/runtime.js +12 -0
  90. package/dist/component/durableExecution/runtime.js.map +1 -0
  91. package/dist/component/earnings/triggers.d.ts +242 -2
  92. package/dist/component/earnings/triggers.d.ts.map +1 -1
  93. package/dist/component/schema.d.ts +253 -1
  94. package/dist/component/schema.js +4 -0
  95. package/dist/component/schema.js.map +1 -1
  96. package/package.json +4 -2
  97. package/src/client/costRecovery.test.ts +34 -0
  98. package/src/client/costRecovery.ts +21 -0
  99. package/src/client/index.ts +1 -0
  100. package/src/client/processingCostDeficit/README.md +35 -0
  101. package/src/client/processingCostDeficit/calculator.test.ts +176 -0
  102. package/src/client/processingCostDeficit/index.ts +91 -0
  103. package/src/component/_generated/api.ts +23 -1
  104. package/src/component/_generated/component.ts +693 -0
  105. package/src/component/balanceFunding/failure.test.ts +116 -0
  106. package/src/component/balanceFunding/helpers.ts +102 -0
  107. package/src/component/balanceFunding/import.test.ts +221 -0
  108. package/src/component/balanceFunding/importHandler.ts +146 -0
  109. package/src/component/balanceFunding/lifecycleHandlers.ts +90 -0
  110. package/src/component/balanceFunding/lookup.test.ts +113 -0
  111. package/src/component/balanceFunding/mutationValidators.ts +63 -0
  112. package/src/component/balanceFunding/mutations.ts +136 -0
  113. package/src/component/balanceFunding/preparation.test.ts +146 -0
  114. package/src/component/balanceFunding/preparationHandlers.ts +204 -0
  115. package/src/component/balanceFunding/queries.ts +221 -0
  116. package/src/component/balanceFunding/requestLookup.test.ts +160 -0
  117. package/src/component/balanceFunding/schema.ts +169 -0
  118. package/src/component/balanceFunding/state.test.ts +352 -0
  119. package/src/component/balanceFunding/stateHandlers.ts +198 -0
  120. package/src/component/balanceFunding/validation.test.ts +100 -0
  121. package/src/component/convex.config.ts +2 -0
  122. package/src/component/costRecovery/preparation.test.ts +355 -0
  123. package/src/component/costRecovery/preparation.ts +124 -0
  124. package/src/component/costRecovery/schema.ts +1 -0
  125. package/src/component/durableExecution/composition.test.ts +568 -0
  126. package/src/component/durableExecution/runtime.ts +12 -0
  127. package/src/component/schema.ts +8 -0
@@ -0,0 +1,113 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { makeFunctionReference } from "convex/server";
4
+ import { expect, it } from "vitest";
5
+ import { schema, modules } from "../../test.js";
6
+ const m = (name: string) =>
7
+ makeFunctionReference<"mutation">(`balanceFunding/mutations:${name}`);
8
+ const q = (name: string) =>
9
+ makeFunctionReference<"query">(`balanceFunding/queries:${name}`);
10
+ const scope = { accountId: "acct_lookup", scopeKey: "lookup" };
11
+ const preparation = {
12
+ customerAccount: scope.accountId,
13
+ stripeSubscriptionId: "sub_lookup",
14
+ previousPaymentMethodId: "pm_original",
15
+ previousPaymentMethodTypes: ["card"],
16
+ };
17
+ const args = {
18
+ ...scope,
19
+ preparation,
20
+ consent: true,
21
+ consentAt: 10,
22
+ consentReference: "consent",
23
+ providerApiVersion: "preview",
24
+ requestKey: "prepare",
25
+ };
26
+ it("only verified preparation exposes its reference, including lost-response replay", async () => {
27
+ const t = convexTest(schema, modules);
28
+ const started = await t.mutation(m("prepare"), args);
29
+ const lookup = {
30
+ ...started.operation,
31
+ stripeSubscriptionId: preparation.stripeSubscriptionId,
32
+ };
33
+ expect(await t.query(q("getPreparation"), lookup)).toEqual({
34
+ status: "pending",
35
+ operation: started.operation,
36
+ });
37
+ await t.mutation(m("start"), started.operation);
38
+ await t.mutation(m("markUnknown"), started.operation);
39
+ expect(await t.query(q("getPreparation"), lookup)).toEqual({
40
+ status: "unknown",
41
+ operation: started.operation,
42
+ });
43
+ await t.mutation(m("finishPreparation"), {
44
+ ...started.operation,
45
+ preparation: { ...preparation, paymentMethodId: "pm_balance" },
46
+ providerApiVersion: args.providerApiVersion,
47
+ });
48
+ const replay = await t.mutation(m("prepare"), args);
49
+ expect(replay).toEqual(started);
50
+ const found = await t.query(q("getPreparation"), lookup);
51
+ expect(found.status).toBe("prepared");
52
+ expect(found.preparationId).toEqual(expect.any(String));
53
+ expect(Object.keys(found).sort()).toEqual([
54
+ "operation",
55
+ "preparationId",
56
+ "status",
57
+ "stripeSubscriptionId",
58
+ ]);
59
+ const accepted = await t.mutation(m("begin"), {
60
+ ...scope,
61
+ preparationId: found.preparationId,
62
+ enabled: true,
63
+ consent: true,
64
+ requestKey: "enable",
65
+ });
66
+ expect(accepted.status).toBe("accepted");
67
+ expect(
68
+ await t.query(q("getPreparation"), {
69
+ ...accepted.operation,
70
+ stripeSubscriptionId: "sub_lookup",
71
+ }),
72
+ ).toEqual({
73
+ status: "conflict",
74
+ reason: "identity_changed",
75
+ retryable: false,
76
+ });
77
+ const status = await t.query(q("getOperation"), {
78
+ ...started.operation,
79
+ stripeSubscriptionId: "sub_lookup",
80
+ });
81
+ expect(status).toEqual({
82
+ ...started.operation,
83
+ state: "succeeded",
84
+ cancelRequested: false,
85
+ });
86
+ });
87
+ it("never exposes preparation data for foreign subscription, scope, version or apply operation", async () => {
88
+ const t = convexTest(schema, modules);
89
+ const started = await t.mutation(m("prepare"), args);
90
+ const lookup = {
91
+ ...started.operation,
92
+ stripeSubscriptionId: preparation.stripeSubscriptionId,
93
+ };
94
+ for (const changed of [
95
+ { ...lookup, accountId: "foreign" },
96
+ { ...lookup, scopeKey: "foreign" },
97
+ { ...lookup, stripeSubscriptionId: "foreign" },
98
+ { ...lookup, version: 2 },
99
+ ])
100
+ expect(await t.query(q("getPreparation"), changed)).toEqual({
101
+ status: "conflict",
102
+ reason: "identity_changed",
103
+ retryable: false,
104
+ });
105
+ expect(await t.query(q("getPreparation"), { ...lookup, version: 0 })).toEqual(
106
+ { status: "rejected", reason: "invalid_scope", retryable: false },
107
+ );
108
+ await t.mutation(m("requestCancel"), started.operation);
109
+ expect(await t.query(q("getPreparation"), lookup)).toEqual({
110
+ status: "canceled",
111
+ operation: started.operation,
112
+ });
113
+ });
@@ -0,0 +1,63 @@
1
+ import { v } from "convex/values";
2
+ import {
3
+ scopeFields,
4
+ preparationValue,
5
+ operationRefFields,
6
+ originalValue,
7
+ capturedValue,
8
+ receiptValue,
9
+ } from "./schema.js";
10
+ export const savePreparationArgs = v.object({
11
+ ...scopeFields,
12
+ preparation: preparationValue,
13
+ consentAt: v.number(),
14
+ consentReference: v.string(),
15
+ providerApiVersion: v.string(),
16
+ });
17
+ export const beginArgs = v.object({
18
+ ...scopeFields,
19
+ preparationId: v.id("balanceFundingPreparations"),
20
+ enabled: v.boolean(),
21
+ consent: v.optional(v.literal(true)),
22
+ requestKey: v.string(),
23
+ });
24
+ export const finishArgs = v.object({
25
+ ...operationRefFields,
26
+ enabled: v.boolean(),
27
+ receipt: receiptValue,
28
+ });
29
+ export const startArgs = v.object(operationRefFields);
30
+ export const requestCancelArgs = v.object(operationRefFields);
31
+ export const markUnknownArgs = v.object(operationRefFields);
32
+ export const importPreparationArgs = v.object({
33
+ ...scopeFields,
34
+ sourceKey: v.string(),
35
+ preparation: capturedValue,
36
+ consentAt: v.number(),
37
+ consentReference: v.string(),
38
+ providerApiVersion: v.string(),
39
+ enabled: v.boolean(),
40
+ operationVersion: v.number(),
41
+ pending: v.optional(
42
+ v.object({
43
+ enabled: v.boolean(),
44
+ kind: v.optional(v.union(v.literal("prepare"), v.literal("apply"))),
45
+ providerKey: v.string(),
46
+ requestKey: v.string(),
47
+ }),
48
+ ),
49
+ });
50
+ export const prepareArgs = v.object({
51
+ ...scopeFields,
52
+ preparation: originalValue,
53
+ consent: v.literal(true),
54
+ consentAt: v.number(),
55
+ consentReference: v.string(),
56
+ providerApiVersion: v.string(),
57
+ requestKey: v.string(),
58
+ });
59
+ export const finishPreparationArgs = v.object({
60
+ ...operationRefFields,
61
+ preparation: preparationValue,
62
+ providerApiVersion: v.string(),
63
+ });
@@ -0,0 +1,136 @@
1
+ import { v } from "convex/values";
2
+ import { readPreparation as readSavedPreparation } from "./helpers.js";
3
+ import { readOperation } from "./helpers.js";
4
+ import { scopeFields, failureCode, operationRefFields } from "./schema.js";
5
+ import { mutation } from "../_generated/server.js";
6
+ import { operationDoc, beginResult, importResult } from "./schema.js";
7
+ import {
8
+ savePreparationHandler,
9
+ beginHandler,
10
+ finishHandler,
11
+ } from "./stateHandlers.js";
12
+ export const savePreparation = mutation({
13
+ args: savePreparationArgs,
14
+ returns: v.object({ preparationId: v.id("balanceFundingPreparations") }),
15
+ handler: savePreparationHandler,
16
+ });
17
+ export const begin = mutation({
18
+ args: beginArgs,
19
+ returns: beginResult,
20
+ handler: beginHandler,
21
+ });
22
+ export const finish = mutation({
23
+ args: finishArgs,
24
+ returns: operationDoc,
25
+ handler: finishHandler,
26
+ });
27
+ import {
28
+ startHandler,
29
+ requestCancelHandler,
30
+ markUnknownHandler,
31
+ } from "./lifecycleHandlers.js";
32
+ export const start = mutation({
33
+ args: startArgs,
34
+ returns: operationDoc,
35
+ handler: startHandler,
36
+ });
37
+ export const requestCancel = mutation({
38
+ args: requestCancelArgs,
39
+ returns: operationDoc,
40
+ handler: requestCancelHandler,
41
+ });
42
+ export const markUnknown = mutation({
43
+ args: markUnknownArgs,
44
+ returns: operationDoc,
45
+ handler: markUnknownHandler,
46
+ });
47
+ import { importPreparationHandler } from "./importHandler.js";
48
+ export const importPreparation = mutation({
49
+ args: importPreparationArgs,
50
+ returns: importResult,
51
+ handler: importPreparationHandler,
52
+ });
53
+ import {
54
+ prepareHandler,
55
+ finishPreparationHandler,
56
+ } from "./preparationHandlers.js";
57
+ export const prepare = mutation({
58
+ args: prepareArgs,
59
+ returns: beginResult,
60
+ handler: prepareHandler,
61
+ });
62
+ export const finishPreparation = mutation({
63
+ args: finishPreparationArgs,
64
+ returns: operationDoc,
65
+ handler: finishPreparationHandler,
66
+ });
67
+ import {
68
+ savePreparationArgs,
69
+ beginArgs,
70
+ finishArgs,
71
+ startArgs,
72
+ requestCancelArgs,
73
+ markUnknownArgs,
74
+ importPreparationArgs,
75
+ prepareArgs,
76
+ finishPreparationArgs,
77
+ } from "./mutationValidators.js";
78
+
79
+ /** Migration control: pause new starts while keeping receipt finish/reconciliation available. */
80
+ export const setStartsPaused = mutation({
81
+ args: {
82
+ ...scopeFields,
83
+ preparationId: v.id("balanceFundingPreparations"),
84
+ stripeSubscriptionId: v.string(),
85
+ paused: v.boolean(),
86
+ },
87
+ returns: v.null(),
88
+ handler: async (ctx, args) => {
89
+ const saved = await readSavedPreparation(ctx, args);
90
+ if (
91
+ !saved ||
92
+ saved.preparation.stripeSubscriptionId !== args.stripeSubscriptionId
93
+ )
94
+ throw new Error("Preparation subscription identity does not match.");
95
+ await ctx.db.patch("balanceFundingPreparations", saved._id, {
96
+ startsPaused: args.paused,
97
+ });
98
+ return null;
99
+ },
100
+ });
101
+
102
+ /** Only a pending intent can prove that no provider execution has started. */
103
+ export const failBeforeStart = mutation({
104
+ args: { ...operationRefFields, failureCode },
105
+ returns: operationDoc,
106
+ handler: async (ctx, args) => {
107
+ const op = await readOperation(ctx, args);
108
+ if (!op) throw new Error("Balance funding operation is missing.");
109
+ if (op.state === "failed") {
110
+ if (op.failureCode !== args.failureCode)
111
+ throw new Error("Failure identity changed.");
112
+ return op;
113
+ }
114
+ if (op.state !== "pending")
115
+ throw new Error(
116
+ "Provider execution has started or its outcome is uncertain.",
117
+ );
118
+ const setting = await ctx.db.get(
119
+ "balanceFundingPreparations",
120
+ op.preparationId,
121
+ );
122
+ if (
123
+ setting?.activeOperationId !== op._id ||
124
+ setting.operationVersion !== op.version
125
+ )
126
+ throw new Error("Operation version changed.");
127
+ await ctx.db.patch("balanceFundingOperations", op._id, {
128
+ state: "failed",
129
+ failureCode: args.failureCode,
130
+ });
131
+ await ctx.db.patch("balanceFundingPreparations", setting._id, {
132
+ activeOperationId: undefined,
133
+ });
134
+ return { ...op, state: "failed" as const, failureCode: args.failureCode };
135
+ },
136
+ });
@@ -0,0 +1,146 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { makeFunctionReference } from "convex/server";
4
+ import { expect, it } from "vitest";
5
+ import { schema, modules } from "../../test.js";
6
+ const m = (name: string) =>
7
+ makeFunctionReference<"mutation">(`balanceFunding/mutations:${name}`);
8
+ const q = (name: string) =>
9
+ makeFunctionReference<"query">(`balanceFunding/queries:${name}`);
10
+ const scope = { accountId: "acct_owner", scopeKey: "opaque" };
11
+ const args = {
12
+ ...scope,
13
+ preparation: {
14
+ customerAccount: scope.accountId,
15
+ stripeSubscriptionId: "sub_prepare",
16
+ previousPaymentMethodId: null,
17
+ previousPaymentMethodTypes: null,
18
+ },
19
+ consent: true,
20
+ consentAt: 123,
21
+ consentReference: "signed-consent",
22
+ providerApiVersion: "2026-06-30.preview",
23
+ requestKey: "prepare-1",
24
+ };
25
+ it("persists original settings and stable create/attach keys before provisioning", async () => {
26
+ const t = convexTest(schema, modules);
27
+ const first = await t.mutation(m("prepare"), args);
28
+ expect(first.status).toBe("accepted");
29
+ expect(await t.mutation(m("prepare"), args)).toEqual(first);
30
+ const op = await t.query(q("inspectOperation"), {
31
+ ...first.operation,
32
+ stripeSubscriptionId: "sub_prepare",
33
+ });
34
+ expect(op.kind).toBe("prepare");
35
+ expect(op.providerKeys.create).toBe(`${op.providerKey}:create`);
36
+ expect(op.providerKeys.attach).toBe(`${op.providerKey}:attach`);
37
+ const saved = await t.query(q("readPreparation"), {
38
+ ...{
39
+ ...scope,
40
+ preparationId: op.preparationId,
41
+ },
42
+ stripeSubscriptionId: "sub_prepare",
43
+ });
44
+ expect(saved.preparation.previousPaymentMethodId).toBe(null);
45
+ expect(saved.preparation.previousPaymentMethodTypes).toBe(null);
46
+ expect(saved.preparation.paymentMethodId).toBeUndefined();
47
+ expect(
48
+ await t.mutation(m("begin"), {
49
+ ...scope,
50
+ preparationId: op.preparationId,
51
+ enabled: true,
52
+ consent: true,
53
+ requestKey: "too-early",
54
+ }),
55
+ ).toEqual({
56
+ status: "not_ready",
57
+ reason: "provider_pending",
58
+ retryable: true,
59
+ });
60
+ const preparation = { ...args.preparation, paymentMethodId: "pm_created" };
61
+ await t.mutation(m("finishPreparation"), {
62
+ ...first.operation,
63
+ preparation,
64
+ providerApiVersion: args.providerApiVersion,
65
+ });
66
+ expect(await t.mutation(m("prepare"), args)).toEqual(first);
67
+ expect(
68
+ (
69
+ await t.query(q("inspectOperation"), {
70
+ ...first.operation,
71
+ stripeSubscriptionId: "sub_prepare",
72
+ })
73
+ ).state,
74
+ ).toBe("succeeded");
75
+ const next = await t.mutation(m("begin"), {
76
+ ...scope,
77
+ preparationId: op.preparationId,
78
+ enabled: true,
79
+ consent: true,
80
+ requestKey: "enable",
81
+ });
82
+ expect(next.operation.version).toBe(2);
83
+ });
84
+ it("holds uncertain provisioning against new identities and protects captured restoration", async () => {
85
+ const t = convexTest(schema, modules);
86
+ const first = await t.mutation(m("prepare"), args);
87
+ await t.mutation(m("start"), first.operation);
88
+ await t.mutation(m("markUnknown"), first.operation);
89
+ expect(
90
+ await t.mutation(m("prepare"), { ...args, requestKey: "retry" }),
91
+ ).toEqual(first);
92
+ expect(
93
+ await t.mutation(m("prepare"), {
94
+ ...args,
95
+ requestKey: "changed",
96
+ preparation: {
97
+ ...args.preparation,
98
+ previousPaymentMethodId: "pm_changed",
99
+ },
100
+ }),
101
+ ).toEqual({
102
+ status: "conflict",
103
+ reason: "identity_changed",
104
+ retryable: false,
105
+ });
106
+ await expect(
107
+ t.mutation(m("finishPreparation"), {
108
+ ...first.operation,
109
+ preparation: {
110
+ ...args.preparation,
111
+ paymentMethodId: "pm_created",
112
+ previousPaymentMethodTypes: [],
113
+ },
114
+ providerApiVersion: args.providerApiVersion,
115
+ }),
116
+ ).rejects.toThrow(/restoration|receipt|identity/i);
117
+ await expect(
118
+ t.mutation(m("finishPreparation"), {
119
+ ...first.operation,
120
+ preparation: { ...args.preparation, paymentMethodId: "pm_created" },
121
+ providerApiVersion: "different",
122
+ }),
123
+ ).rejects.toThrow(/version|identity/i);
124
+ });
125
+ it("binds a new request for an already verified preparation to its original operation", async () => {
126
+ const t = convexTest(schema, modules);
127
+ const first = await t.mutation(m("prepare"), args);
128
+ await t.mutation(m("finishPreparation"), {
129
+ ...first.operation,
130
+ preparation: { ...args.preparation, paymentMethodId: "pm_created" },
131
+ providerApiVersion: args.providerApiVersion,
132
+ });
133
+ const repeat = { ...args, requestKey: "another-prepare-request" };
134
+ expect(await t.mutation(m("prepare"), repeat)).toEqual(first);
135
+ expect(
136
+ await t.mutation(m("prepare"), {
137
+ ...repeat,
138
+ accountId: "foreign",
139
+ preparation: { ...args.preparation, customerAccount: "foreign" },
140
+ }),
141
+ ).toEqual({
142
+ status: "conflict",
143
+ reason: "identity_changed",
144
+ retryable: false,
145
+ });
146
+ });
@@ -0,0 +1,204 @@
1
+ import { validateOriginal } from "./helpers.js";
2
+ import type { Infer } from "convex/values";
3
+ import type { MutationCtx } from "../_generated/server.js";
4
+ import {
5
+ text,
6
+ integer,
7
+ validateScope,
8
+ same,
9
+ unavailable,
10
+ readOperation,
11
+ ref,
12
+ fingerprint,
13
+ } from "./helpers.js";
14
+ import { prepareArgs, finishPreparationArgs } from "./mutationValidators.js";
15
+ export async function prepareHandler(
16
+ ctx: MutationCtx,
17
+ args: Infer<typeof prepareArgs>,
18
+ ) {
19
+ validateScope(args);
20
+ integer(args.consentAt);
21
+ text(args.consentReference);
22
+ text(args.providerApiVersion);
23
+ text(args.requestKey);
24
+ validateOriginal(args.preparation);
25
+ text(args.preparation.stripeSubscriptionId);
26
+ if (args.preparation.customerAccount !== args.accountId)
27
+ return unavailable("identity_changed");
28
+ const payload = fingerprint(args);
29
+ const prior = await ctx.db
30
+ .query("balanceFundingRequests")
31
+ .withIndex("by_request", (q) => q.eq("requestKey", args.requestKey))
32
+ .unique();
33
+ if (prior)
34
+ return prior.payload === payload && prior.result
35
+ ? prior.result
36
+ : unavailable("identity_changed");
37
+ let setting = await ctx.db
38
+ .query("balanceFundingPreparations")
39
+ .withIndex("by_account_subscription", (q) =>
40
+ q
41
+ .eq("accountId", args.accountId)
42
+ .eq(
43
+ "preparation.stripeSubscriptionId",
44
+ args.preparation.stripeSubscriptionId,
45
+ ),
46
+ )
47
+ .unique();
48
+ if (setting) {
49
+ if (setting.startsPaused) return unavailable("scope_busy");
50
+ const { paymentMethodId: _, ...original } = setting.preparation;
51
+ if (
52
+ setting.scopeKey !== args.scopeKey ||
53
+ !same(original, args.preparation) ||
54
+ setting.consentReference !== args.consentReference ||
55
+ setting.consentAt !== args.consentAt ||
56
+ setting.providerApiVersion !== args.providerApiVersion
57
+ )
58
+ return unavailable("identity_changed");
59
+ if (
60
+ setting.verified &&
61
+ setting.preparation.paymentMethodId &&
62
+ setting.preparationOperationId
63
+ ) {
64
+ const completed = await ctx.db.get(
65
+ "balanceFundingOperations",
66
+ setting.preparationOperationId,
67
+ );
68
+ if (
69
+ !completed ||
70
+ completed.state !== "succeeded" ||
71
+ completed.kind !== "prepare"
72
+ )
73
+ return unavailable("identity_changed");
74
+ const result = { status: "accepted" as const, operation: ref(completed) };
75
+ await ctx.db.insert("balanceFundingRequests", {
76
+ requestKey: args.requestKey,
77
+ payload,
78
+ preparationId: setting._id,
79
+ result,
80
+ });
81
+ return result;
82
+ }
83
+ if (setting.activeOperationId) {
84
+ const active = await ctx.db.get(
85
+ "balanceFundingOperations",
86
+ setting.activeOperationId,
87
+ );
88
+ if (!active || active.kind !== "prepare")
89
+ return unavailable("scope_busy");
90
+ const result = { status: "accepted" as const, operation: ref(active) };
91
+ await ctx.db.insert("balanceFundingRequests", {
92
+ requestKey: args.requestKey,
93
+ payload,
94
+ preparationId: setting._id,
95
+ result,
96
+ });
97
+ return result;
98
+ }
99
+ } else {
100
+ const preparationId = await ctx.db.insert("balanceFundingPreparations", {
101
+ accountId: args.accountId,
102
+ scopeKey: args.scopeKey,
103
+ preparation: args.preparation,
104
+ consentAt: args.consentAt,
105
+ consentReference: args.consentReference,
106
+ providerApiVersion: args.providerApiVersion,
107
+ enabled: false,
108
+ operationVersion: 0,
109
+ startsPaused: false,
110
+ verified: false,
111
+ });
112
+ setting = await ctx.db.get("balanceFundingPreparations", preparationId);
113
+ }
114
+ if (!setting) throw new Error("Preparation intent was not persisted.");
115
+ const version = setting.operationVersion + 1;
116
+ integer(version, 1);
117
+ const key = `betterstripe_balance_${setting._id}_${version}`;
118
+ const operationId = await ctx.db.insert("balanceFundingOperations", {
119
+ accountId: args.accountId,
120
+ scopeKey: args.scopeKey,
121
+ preparationId: setting._id,
122
+ version,
123
+ enabled: false,
124
+ kind: "prepare",
125
+ providerKey: key,
126
+ state: setting.verified ? "succeeded" : "pending",
127
+ cancelRequested: false,
128
+ providerKeys: {
129
+ create: `${key}:create`,
130
+ attach: `${key}:attach`,
131
+ enable: `${key}:enable`,
132
+ disable: `${key}:disable`,
133
+ },
134
+ });
135
+ await ctx.db.patch("balanceFundingPreparations", setting._id, {
136
+ operationVersion: version,
137
+ ...(setting.verified
138
+ ? { preparationOperationId: operationId }
139
+ : { activeOperationId: operationId }),
140
+ });
141
+ const result = {
142
+ status: "accepted" as const,
143
+ operation: {
144
+ accountId: args.accountId,
145
+ scopeKey: args.scopeKey,
146
+ operationId,
147
+ version,
148
+ },
149
+ };
150
+ await ctx.db.insert("balanceFundingRequests", {
151
+ requestKey: args.requestKey,
152
+ payload,
153
+ preparationId: setting._id,
154
+ result,
155
+ });
156
+ return result;
157
+ }
158
+ export async function finishPreparationHandler(
159
+ ctx: MutationCtx,
160
+ args: Infer<typeof finishPreparationArgs>,
161
+ ) {
162
+ const op = await readOperation(ctx, args);
163
+ if (!op || op.kind !== "prepare")
164
+ throw new Error("Preparation operation identity does not match.");
165
+ const setting = await ctx.db.get(
166
+ "balanceFundingPreparations",
167
+ op.preparationId,
168
+ );
169
+ if (!setting || setting.providerApiVersion !== args.providerApiVersion)
170
+ throw new Error("Preparation provider version identity changed.");
171
+ validateOriginal(args.preparation);
172
+ const { paymentMethodId, ...original } = args.preparation;
173
+ text(paymentMethodId);
174
+ const { paymentMethodId: savedPaymentMethodId, ...savedOriginal } =
175
+ setting.preparation;
176
+ if (
177
+ savedPaymentMethodId !== undefined &&
178
+ savedPaymentMethodId !== paymentMethodId
179
+ )
180
+ throw new Error("Preparation receipt identity changed.");
181
+ if (!same(original, savedOriginal))
182
+ throw new Error("Captured restoration receipt changed.");
183
+ if (op.state === "succeeded") {
184
+ if (savedPaymentMethodId !== paymentMethodId)
185
+ throw new Error("Preparation receipt identity changed.");
186
+ return op;
187
+ }
188
+ if (
189
+ setting.activeOperationId !== op._id ||
190
+ setting.operationVersion !== op.version ||
191
+ op.state === "canceled"
192
+ )
193
+ throw new Error("Preparation operation version changed.");
194
+ await ctx.db.patch("balanceFundingPreparations", setting._id, {
195
+ preparation: args.preparation,
196
+ verified: true,
197
+ preparationOperationId: op._id,
198
+ activeOperationId: undefined,
199
+ });
200
+ await ctx.db.patch("balanceFundingOperations", op._id, {
201
+ state: "succeeded",
202
+ });
203
+ return { ...op, state: "succeeded" as const };
204
+ }