@fantastic.dev/better-stripe 0.55.0 → 0.56.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 (212) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +216 -38
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +92 -3
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +216 -38
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +92 -3
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +4 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +1 -0
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/usage/catalogPrices.d.ts +2 -0
  16. package/dist/client/usage/catalogPrices.d.ts.map +1 -1
  17. package/dist/client/usage/catalogPrices.js +15 -0
  18. package/dist/client/usage/catalogPrices.js.map +1 -1
  19. package/dist/client/usage/client.d.ts +2 -2
  20. package/dist/client/usage/client.d.ts.map +1 -1
  21. package/dist/client/usage/client.js +2 -2
  22. package/dist/client/usage/client.js.map +1 -1
  23. package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
  24. package/dist/client/usage/deliveryProvider.js +26 -1
  25. package/dist/client/usage/deliveryProvider.js.map +1 -1
  26. package/dist/client/usage/index.d.ts +4 -0
  27. package/dist/client/usage/index.d.ts.map +1 -1
  28. package/dist/client/usage/index.js +1 -0
  29. package/dist/client/usage/index.js.map +1 -1
  30. package/dist/client/usage/subscription.fixtures.d.ts +118 -0
  31. package/dist/client/usage/subscription.fixtures.d.ts.map +1 -0
  32. package/dist/client/usage/subscription.fixtures.js +84 -0
  33. package/dist/client/usage/subscription.fixtures.js.map +1 -0
  34. package/dist/client/usage/subscriptionAbandonment.d.ts +8 -0
  35. package/dist/client/usage/subscriptionAbandonment.d.ts.map +1 -0
  36. package/dist/client/usage/subscriptionAbandonment.js +82 -0
  37. package/dist/client/usage/subscriptionAbandonment.js.map +1 -0
  38. package/dist/client/usage/subscriptionCancellation.d.ts +9 -0
  39. package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -0
  40. package/dist/client/usage/subscriptionCancellation.js +39 -0
  41. package/dist/client/usage/subscriptionCancellation.js.map +1 -0
  42. package/dist/client/usage/subscriptionCheckout.d.ts +52 -0
  43. package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -0
  44. package/dist/client/usage/subscriptionCheckout.js +94 -0
  45. package/dist/client/usage/subscriptionCheckout.js.map +1 -0
  46. package/dist/client/usage/subscriptionClient.d.ts +267 -0
  47. package/dist/client/usage/subscriptionClient.d.ts.map +1 -0
  48. package/dist/client/usage/subscriptionClient.js +93 -0
  49. package/dist/client/usage/subscriptionClient.js.map +1 -0
  50. package/dist/client/usage/subscriptionErrors.d.ts +5 -0
  51. package/dist/client/usage/subscriptionErrors.d.ts.map +1 -0
  52. package/dist/client/usage/subscriptionErrors.js +9 -0
  53. package/dist/client/usage/subscriptionErrors.js.map +1 -0
  54. package/dist/client/usage/subscriptionInvoiceSchema.d.ts +203 -0
  55. package/dist/client/usage/subscriptionInvoiceSchema.d.ts.map +1 -0
  56. package/dist/client/usage/subscriptionInvoiceSchema.js +108 -0
  57. package/dist/client/usage/subscriptionInvoiceSchema.js.map +1 -0
  58. package/dist/client/usage/subscriptionLifecycle.d.ts +80 -0
  59. package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -0
  60. package/dist/client/usage/subscriptionLifecycle.js +87 -0
  61. package/dist/client/usage/subscriptionLifecycle.js.map +1 -0
  62. package/dist/client/usage/subscriptionProvider.d.ts +111 -0
  63. package/dist/client/usage/subscriptionProvider.d.ts.map +1 -0
  64. package/dist/client/usage/subscriptionProvider.js +147 -0
  65. package/dist/client/usage/subscriptionProvider.js.map +1 -0
  66. package/dist/client/usage/subscriptionTerms.d.ts +161 -0
  67. package/dist/client/usage/subscriptionTerms.d.ts.map +1 -0
  68. package/dist/client/usage/subscriptionTerms.js +242 -0
  69. package/dist/client/usage/subscriptionTerms.js.map +1 -0
  70. package/dist/client/usage/subscriptionTransport.fixtures.d.ts +25 -0
  71. package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -0
  72. package/dist/client/usage/subscriptionTransport.fixtures.js +203 -0
  73. package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -0
  74. package/dist/client/webhooks/processors.d.ts.map +1 -1
  75. package/dist/client/webhooks/processors.js +2 -0
  76. package/dist/client/webhooks/processors.js.map +1 -1
  77. package/dist/client/webhooks/usageSubscriptions.d.ts +5 -0
  78. package/dist/client/webhooks/usageSubscriptions.d.ts.map +1 -0
  79. package/dist/client/webhooks/usageSubscriptions.js +54 -0
  80. package/dist/client/webhooks/usageSubscriptions.js.map +1 -0
  81. package/dist/component/_generated/api.d.ts +14 -0
  82. package/dist/component/_generated/api.d.ts.map +1 -1
  83. package/dist/component/_generated/api.js.map +1 -1
  84. package/dist/component/_generated/component.d.ts +160 -5
  85. package/dist/component/_generated/component.d.ts.map +1 -1
  86. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  87. package/dist/component/accountClosure/mutations.js +10 -0
  88. package/dist/component/accountClosure/mutations.js.map +1 -1
  89. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  90. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  91. package/dist/component/earnings/triggers.d.ts +192 -4
  92. package/dist/component/earnings/triggers.d.ts.map +1 -1
  93. package/dist/component/payoutRelease/queries.d.ts +2 -2
  94. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  95. package/dist/component/schema.d.ts +92 -3
  96. package/dist/component/schema.js +5 -0
  97. package/dist/component/schema.js.map +1 -1
  98. package/dist/component/usage/mutations.d.ts.map +1 -1
  99. package/dist/component/usage/mutations.js +5 -0
  100. package/dist/component/usage/mutations.js.map +1 -1
  101. package/dist/component/usage/queries.d.ts +2 -0
  102. package/dist/component/usage/queries.d.ts.map +1 -1
  103. package/dist/component/usage/schema.d.ts +14 -7
  104. package/dist/component/usage/schema.d.ts.map +1 -1
  105. package/dist/component/usage/schema.js +5 -1
  106. package/dist/component/usage/schema.js.map +1 -1
  107. package/dist/component/usageDelivery/fields.d.ts +3 -2
  108. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  109. package/dist/component/usageDelivery/fields.js +2 -1
  110. package/dist/component/usageDelivery/fields.js.map +1 -1
  111. package/dist/component/usageDelivery/helpers.d.ts +4 -3
  112. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  113. package/dist/component/usageDelivery/mutations.d.ts +3 -3
  114. package/dist/component/usageDelivery/queries.d.ts +17 -3
  115. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  116. package/dist/component/usageDelivery/queries.js +20 -3
  117. package/dist/component/usageDelivery/queries.js.map +1 -1
  118. package/dist/component/usageDelivery/schema.d.ts +2 -2
  119. package/dist/component/usageDelivery/steps.d.ts +1 -1
  120. package/dist/component/usageDelivery/steps.d.ts.map +1 -1
  121. package/dist/component/usageDelivery/steps.js +12 -1
  122. package/dist/component/usageDelivery/steps.js.map +1 -1
  123. package/dist/component/usageSubscriptions/abandonment.d.ts +4 -0
  124. package/dist/component/usageSubscriptions/abandonment.d.ts.map +1 -0
  125. package/dist/component/usageSubscriptions/abandonment.js +59 -0
  126. package/dist/component/usageSubscriptions/abandonment.js.map +1 -0
  127. package/dist/component/usageSubscriptions/acceptance.d.ts +11 -0
  128. package/dist/component/usageSubscriptions/acceptance.d.ts.map +1 -0
  129. package/dist/component/usageSubscriptions/acceptance.js +38 -0
  130. package/dist/component/usageSubscriptions/acceptance.js.map +1 -0
  131. package/dist/component/usageSubscriptions/helpers.d.ts +39 -0
  132. package/dist/component/usageSubscriptions/helpers.d.ts.map +1 -0
  133. package/dist/component/usageSubscriptions/helpers.js +28 -0
  134. package/dist/component/usageSubscriptions/helpers.js.map +1 -0
  135. package/dist/component/usageSubscriptions/history.d.ts +46 -0
  136. package/dist/component/usageSubscriptions/history.d.ts.map +1 -0
  137. package/dist/component/usageSubscriptions/history.js +46 -0
  138. package/dist/component/usageSubscriptions/history.js.map +1 -0
  139. package/dist/component/usageSubscriptions/mutations.d.ts +64 -0
  140. package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -0
  141. package/dist/component/usageSubscriptions/mutations.js +252 -0
  142. package/dist/component/usageSubscriptions/mutations.js.map +1 -0
  143. package/dist/component/usageSubscriptions/queries.d.ts +81 -0
  144. package/dist/component/usageSubscriptions/queries.d.ts.map +1 -0
  145. package/dist/component/usageSubscriptions/queries.js +70 -0
  146. package/dist/component/usageSubscriptions/queries.js.map +1 -0
  147. package/dist/component/usageSubscriptions/retirement.d.ts +4 -0
  148. package/dist/component/usageSubscriptions/retirement.d.ts.map +1 -0
  149. package/dist/component/usageSubscriptions/retirement.js +80 -0
  150. package/dist/component/usageSubscriptions/retirement.js.map +1 -0
  151. package/dist/component/usageSubscriptions/schema.d.ts +191 -0
  152. package/dist/component/usageSubscriptions/schema.d.ts.map +1 -0
  153. package/dist/component/usageSubscriptions/schema.js +69 -0
  154. package/dist/component/usageSubscriptions/schema.js.map +1 -0
  155. package/dist/test.d.ts +6 -0
  156. package/dist/test.d.ts.map +1 -0
  157. package/dist/test.js +15 -0
  158. package/dist/test.js.map +1 -0
  159. package/docs/README.md +2 -0
  160. package/docs/evidence/native-metering/clock-finalization-run.json +129 -0
  161. package/docs/evidence/native-metering/clock-lag-run.json +111 -0
  162. package/docs/evidence/native-metering/paid-run.json +107 -0
  163. package/docs/evidence/native-metering/promotional-run.json +103 -0
  164. package/docs/metered-usage.md +14 -0
  165. package/docs/metering-setup.md +5 -1
  166. package/docs/usage-subscriptions.md +278 -0
  167. package/package.json +4 -2
  168. package/src/client/index.ts +8 -0
  169. package/src/client/usage/catalogPrices.ts +21 -0
  170. package/src/client/usage/client.ts +2 -2
  171. package/src/client/usage/deliveryProvider.test.ts +70 -1
  172. package/src/client/usage/deliveryProvider.ts +43 -2
  173. package/src/client/usage/index.ts +9 -0
  174. package/src/client/usage/subscription.fixtures.ts +84 -0
  175. package/src/client/usage/subscriptionAbandonment.test.ts +124 -0
  176. package/src/client/usage/subscriptionAbandonment.ts +116 -0
  177. package/src/client/usage/subscriptionCancellation.ts +90 -0
  178. package/src/client/usage/subscriptionCheckout.test.ts +31 -0
  179. package/src/client/usage/subscriptionCheckout.ts +152 -0
  180. package/src/client/usage/subscriptionClient.test.ts +316 -0
  181. package/src/client/usage/subscriptionClient.ts +204 -0
  182. package/src/client/usage/subscriptionErrors.ts +14 -0
  183. package/src/client/usage/subscriptionInvoiceSchema.ts +116 -0
  184. package/src/client/usage/subscriptionLifecycle.ts +165 -0
  185. package/src/client/usage/subscriptionProvider.test.ts +48 -0
  186. package/src/client/usage/subscriptionProvider.ts +247 -0
  187. package/src/client/usage/subscriptionTerms.test.ts +158 -0
  188. package/src/client/usage/subscriptionTerms.ts +294 -0
  189. package/src/client/usage/subscriptionTransport.fixtures.ts +241 -0
  190. package/src/client/webhooks/processors.ts +2 -0
  191. package/src/client/webhooks/usageSubscriptions.test.ts +162 -0
  192. package/src/client/webhooks/usageSubscriptions.ts +81 -0
  193. package/src/component/_generated/api.ts +14 -0
  194. package/src/component/_generated/component.ts +200 -0
  195. package/src/component/accountClosure/mutations.ts +12 -0
  196. package/src/component/schema.ts +10 -0
  197. package/src/component/usage/mutations.ts +5 -0
  198. package/src/component/usage/schema.ts +5 -1
  199. package/src/component/usageDelivery/fields.ts +2 -0
  200. package/src/component/usageDelivery/queries.ts +30 -3
  201. package/src/component/usageDelivery/steps.ts +22 -1
  202. package/src/component/usageSubscriptions/abandonment.ts +80 -0
  203. package/src/component/usageSubscriptions/acceptance.test.ts +122 -0
  204. package/src/component/usageSubscriptions/acceptance.ts +66 -0
  205. package/src/component/usageSubscriptions/helpers.ts +33 -0
  206. package/src/component/usageSubscriptions/history.test.ts +69 -0
  207. package/src/component/usageSubscriptions/history.ts +68 -0
  208. package/src/component/usageSubscriptions/mutations.test.ts +205 -0
  209. package/src/component/usageSubscriptions/mutations.ts +275 -0
  210. package/src/component/usageSubscriptions/queries.ts +78 -0
  211. package/src/component/usageSubscriptions/retirement.ts +105 -0
  212. package/src/component/usageSubscriptions/schema.ts +73 -0
@@ -0,0 +1,294 @@
1
+ import { z } from "zod";
2
+ import {
3
+ prepareUsageRecord,
4
+ type PreparedUsageRecord,
5
+ type UsageScope,
6
+ } from "./records.js";
7
+ import type { UsageSubscriptionBinding } from "./boundaries.js";
8
+ export type UsageSubscriptionOptions = {
9
+ requestId: string;
10
+ meters: Array<{
11
+ scope: UsageScope;
12
+ binding: Omit<PreparedUsageRecord["binding"], "apiVersion"> & {
13
+ apiVersion?: string;
14
+ };
15
+ }>;
16
+ fixedPriceIds?: string[];
17
+ collection:
18
+ | { method: "send_invoice"; daysUntilDue: number }
19
+ | { method: "charge_automatically"; defaultPaymentMethod: string }
20
+ | { method: "checkout"; successUrl: string; cancelUrl: string };
21
+ };
22
+ const id = (prefix: string) =>
23
+ z
24
+ .string()
25
+ .regex(new RegExp(`^${prefix}_[a-zA-Z0-9]+$`))
26
+ .max(100);
27
+ const seconds = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
28
+ const requestSchema = z.strictObject({
29
+ requestId: z.string().min(1).max(100),
30
+ meters: z
31
+ .array(z.strictObject({ scope: z.unknown(), binding: z.unknown() }))
32
+ .min(1)
33
+ .max(10),
34
+ fixedPriceIds: z.array(id("price")).max(10).default([]),
35
+ collection: z.discriminatedUnion("method", [
36
+ z.strictObject({
37
+ method: z.literal("send_invoice"),
38
+ daysUntilDue: z.number().int().min(1).max(365),
39
+ }),
40
+ z.strictObject({
41
+ method: z.literal("charge_automatically"),
42
+ defaultPaymentMethod: id("pm"),
43
+ }),
44
+ z.strictObject({
45
+ method: z.literal("checkout"),
46
+ successUrl: z.url({ protocol: /^https?$/ }).max(2048),
47
+ cancelUrl: z.url({ protocol: /^https?$/ }).max(2048),
48
+ }),
49
+ ]),
50
+ });
51
+ export function subscriptionTerms(input: unknown) {
52
+ const parsed = requestSchema.parse(input);
53
+ const meters = parsed.meters.map((meter) => {
54
+ const { scope, binding } = prepareUsageRecord({
55
+ ...meter,
56
+ sourceEventId: "subscription",
57
+ quantity: "0",
58
+ occurredAt: 0,
59
+ });
60
+ return { scope, binding };
61
+ });
62
+ const first = meters[0],
63
+ prices = new Set(parsed.fixedPriceIds),
64
+ meterIds = new Set<string>();
65
+ if (prices.size !== parsed.fixedPriceIds.length)
66
+ throw new Error("Duplicate fixed price");
67
+ for (const meter of meters) {
68
+ if (
69
+ meter.scope.stripeAccountId !== first.scope.stripeAccountId ||
70
+ meter.scope.livemode !== first.scope.livemode ||
71
+ meter.scope.customerAccount !== first.scope.customerAccount ||
72
+ meter.binding.stripeCustomerId !== first.binding.stripeCustomerId ||
73
+ meter.binding.apiVersion !== first.binding.apiVersion ||
74
+ meter.binding.plan.rate.currency !== first.binding.plan.rate.currency ||
75
+ prices.has(meter.binding.stripePriceId) ||
76
+ meterIds.has(meter.scope.meterId)
77
+ )
78
+ throw new Error("Incompatible or duplicate usage subscription bindings");
79
+ prices.add(meter.binding.stripePriceId);
80
+ meterIds.add(meter.scope.meterId);
81
+ }
82
+ return { ...parsed, meters };
83
+ }
84
+ export type UsageSubscriptionTerms = ReturnType<typeof subscriptionTerms>;
85
+ export function subscriptionScope(terms: UsageSubscriptionTerms) {
86
+ const { stripeAccountId, customerAccount, livemode } = terms.meters[0].scope;
87
+ return { stripeAccountId, customerAccount, livemode };
88
+ }
89
+ export const subscriptionScopeSchema = z.strictObject({
90
+ stripeAccountId: id("acct"),
91
+ customerAccount: id("acct"),
92
+ livemode: z.boolean(),
93
+ });
94
+ const nativeSchema = z.object({
95
+ id: id("sub"),
96
+ livemode: z.boolean(),
97
+ customer_account: id("acct"),
98
+ customer: z.union([id("cus"), z.object({ id: id("cus") })]),
99
+ status: z.enum([
100
+ "active",
101
+ "trialing",
102
+ "past_due",
103
+ "canceled",
104
+ "incomplete",
105
+ "incomplete_expired",
106
+ "unpaid",
107
+ "paused",
108
+ ]),
109
+ currency: z.string().regex(/^[a-z]{3}$/),
110
+ collection_method: z.enum(["send_invoice", "charge_automatically"]),
111
+ days_until_due: z.number().int().min(1).max(365).nullable().default(null),
112
+ default_payment_method: z
113
+ .union([id("pm"), z.object({ id: id("pm") })])
114
+ .nullable()
115
+ .default(null),
116
+ billing_mode: z.object({ type: z.enum(["classic", "flexible"]) }),
117
+ cancel_at_period_end: z.boolean(),
118
+ cancel_at: seconds.nullable().default(null),
119
+ items: z.object({
120
+ has_more: z.literal(false),
121
+ data: z
122
+ .array(
123
+ z.object({
124
+ id: id("si"),
125
+ current_period_start: seconds,
126
+ current_period_end: seconds,
127
+ quantity: z
128
+ .number()
129
+ .int()
130
+ .nonnegative()
131
+ .max(Number.MAX_SAFE_INTEGER)
132
+ .nullable()
133
+ .optional(),
134
+ price: z.object({
135
+ id: id("price"),
136
+ currency: z.string(),
137
+ recurring: z.object({
138
+ interval: z.literal("month"),
139
+ interval_count: z.literal(1),
140
+ usage_type: z.enum(["metered", "licensed"]),
141
+ meter: z.string().nullable().optional(),
142
+ }),
143
+ unit_amount_decimal: z.unknown().optional(),
144
+ }),
145
+ }),
146
+ )
147
+ .min(1)
148
+ .max(20),
149
+ }),
150
+ });
151
+ export function subscriptionEvidence(input: unknown) {
152
+ const sub = nativeSchema.parse(input);
153
+ return {
154
+ ...sub,
155
+ items: {
156
+ ...sub.items,
157
+ data: sub.items.data.map((item) => {
158
+ const amount = item.price.unit_amount_decimal?.toString() ?? null;
159
+ if (amount !== null && !/^\d+(\.\d{1,12})?$/.test(amount))
160
+ throw new Error("Invalid native rate precision");
161
+ return {
162
+ ...item,
163
+ price: { ...item.price, unit_amount_decimal: amount },
164
+ };
165
+ }),
166
+ },
167
+ };
168
+ }
169
+ export function subscriptionView(
170
+ input: unknown,
171
+ terms: UsageSubscriptionTerms,
172
+ ) {
173
+ const sub = subscriptionEvidence(input),
174
+ first = terms.meters[0];
175
+ const customer =
176
+ typeof sub.customer === "string" ? sub.customer : sub.customer.id;
177
+ if (
178
+ sub.customer_account !== first.scope.customerAccount ||
179
+ customer !== first.binding.stripeCustomerId ||
180
+ sub.livemode !== first.scope.livemode ||
181
+ sub.currency !== first.binding.plan.rate.currency ||
182
+ sub.billing_mode.type !== "flexible"
183
+ )
184
+ throw new Error("Native subscription scope or billing mode mismatch");
185
+ const defaultPaymentMethod =
186
+ typeof sub.default_payment_method === "string"
187
+ ? sub.default_payment_method
188
+ : (sub.default_payment_method?.id ?? null);
189
+ if (
190
+ terms.collection.method === "send_invoice"
191
+ ? sub.collection_method !== "send_invoice" ||
192
+ sub.days_until_due !== terms.collection.daysUntilDue
193
+ : sub.collection_method !== "charge_automatically" ||
194
+ (terms.collection.method === "charge_automatically" &&
195
+ defaultPaymentMethod !== terms.collection.defaultPaymentMethod)
196
+ )
197
+ throw new Error("Native subscription collection terms changed");
198
+ const expectedPrices = new Set([
199
+ ...terms.fixedPriceIds,
200
+ ...terms.meters.map((m) => m.binding.stripePriceId),
201
+ ]);
202
+ const seen = new Set<string>();
203
+ const items = sub.items.data.map((item) => {
204
+ if (
205
+ item.current_period_end <= item.current_period_start ||
206
+ !expectedPrices.has(item.price.id) ||
207
+ seen.has(item.price.id) ||
208
+ item.price.currency !== sub.currency
209
+ )
210
+ throw new Error("Native subscription items changed or are incomplete");
211
+ seen.add(item.price.id);
212
+ const metered = terms.meters.find(
213
+ (m) => m.binding.stripePriceId === item.price.id,
214
+ );
215
+ if (
216
+ metered
217
+ ? item.price.recurring.usage_type !== "metered" ||
218
+ item.price.recurring.meter !== metered.scope.meterId
219
+ : item.price.recurring.usage_type !== "licensed"
220
+ )
221
+ throw new Error("Native subscription meter mismatch");
222
+ const amount = item.price.unit_amount_decimal?.toString() ?? null;
223
+ if (amount !== null && !/^\d+(\.\d{1,12})?$/.test(amount))
224
+ throw new Error("Invalid native rate precision");
225
+ return {
226
+ id: item.id,
227
+ stripePriceId: item.price.id,
228
+ meterId: metered?.scope.meterId ?? null,
229
+ period: {
230
+ start: item.current_period_start,
231
+ end: item.current_period_end,
232
+ },
233
+ quantity:
234
+ item.quantity === undefined || item.quantity === null
235
+ ? null
236
+ : String(item.quantity),
237
+ unitAmountDecimal: amount,
238
+ };
239
+ });
240
+ if (seen.size !== expectedPrices.size)
241
+ throw new Error("Native subscription has missing items");
242
+ const bindings = terms.meters.map((meter) => {
243
+ const item = items.find(
244
+ (i) => i.stripePriceId === meter.binding.stripePriceId,
245
+ )!;
246
+ const subscription: UsageSubscriptionBinding = {
247
+ subscriptionId: sub.id,
248
+ subscriptionItemId: item.id,
249
+ stripePriceId: item.stripePriceId,
250
+ period: item.period,
251
+ interval: "month",
252
+ };
253
+ return { ...meter, subscription };
254
+ });
255
+ return {
256
+ subscriptionId: sub.id,
257
+ status: sub.status,
258
+ currency: sub.currency,
259
+ billingMode: sub.billing_mode.type,
260
+ collection: {
261
+ method: sub.collection_method,
262
+ daysUntilDue: sub.days_until_due,
263
+ defaultPaymentMethod,
264
+ },
265
+ cancelAtPeriodEnd: sub.cancel_at_period_end,
266
+ cancelAt: sub.cancel_at,
267
+ items,
268
+ bindings,
269
+ };
270
+ }
271
+ export type UsageSubscriptionView = ReturnType<typeof subscriptionView>;
272
+ export function closeoutPolicy(input: {
273
+ queued: number;
274
+ unknown: number;
275
+ reservations: number;
276
+ finalized: boolean;
277
+ }) {
278
+ for (const count of [input.queued, input.unknown, input.reservations])
279
+ if (!Number.isSafeInteger(count) || count < 0)
280
+ throw new Error("Invalid closeout counters");
281
+ const reason =
282
+ input.queued || input.unknown
283
+ ? "pending_usage"
284
+ : input.reservations
285
+ ? "pending_reservations"
286
+ : !input.finalized
287
+ ? "invoice_not_finalized"
288
+ : "finalized_observation";
289
+ return {
290
+ ready: reason === "finalized_observation",
291
+ reason,
292
+ paymentEvidence: "not_resolved" as const,
293
+ };
294
+ }
@@ -0,0 +1,241 @@
1
+ import Stripe from "stripe";
2
+ import { componentsGeneric } from "convex/server";
3
+ import { schema, modules } from "../../test.js";
4
+ import { initConvexTest } from "../setup.test.js";
5
+ import type { Component } from "../helpers.js";
6
+ import { nativeSubscription } from "./subscription.fixtures.js";
7
+ export function fixture(
8
+ external = false,
9
+ failCreate = false,
10
+ ): {
11
+ t: ReturnType<typeof initConvexTest>;
12
+ component: Component;
13
+ stripe: Stripe;
14
+ httpClient: Stripe.HttpClient;
15
+ calls: Array<{
16
+ path: string;
17
+ method: string;
18
+ body: URLSearchParams;
19
+ key: string | null;
20
+ }>;
21
+ state: {
22
+ native?: ReturnType<typeof nativeSubscription> & {
23
+ metadata?: Record<string, string>;
24
+ };
25
+ session?: Record<string, unknown>;
26
+ missingNative?: boolean;
27
+ realmId?: string;
28
+ };
29
+ } {
30
+ const t = initConvexTest();
31
+ t.registerComponent("betterStripe", schema, modules);
32
+ const component = componentsGeneric().betterStripe as unknown as Component;
33
+ const calls: Array<{
34
+ path: string;
35
+ method: string;
36
+ body: URLSearchParams;
37
+ key: string | null;
38
+ }> = [];
39
+ type Native = ReturnType<typeof nativeSubscription> & {
40
+ metadata?: Record<string, string>;
41
+ };
42
+ const state: {
43
+ native?: Native;
44
+ session?: Record<string, unknown>;
45
+ missingNative?: boolean;
46
+ realmId?: string;
47
+ } = {};
48
+ let subscriptionCreates = 0,
49
+ checkoutCreates = 0;
50
+ const httpClient: Stripe.HttpClient = Stripe.createFetchHttpClient(
51
+ async (input, init) => {
52
+ const path = new URL(String(input)).pathname,
53
+ method = init?.method ?? "GET",
54
+ body = new URLSearchParams(String(init?.body ?? ""));
55
+ calls.push({
56
+ path,
57
+ method,
58
+ body,
59
+ key: new Headers(init?.headers).get("idempotency-key"),
60
+ });
61
+ let value: unknown;
62
+ if (path === "/v1/account")
63
+ value = { id: state.realmId ?? "acct_platform" };
64
+ else if (path === "/v1/balance") value = { livemode: false };
65
+ else if (path === "/v1/customers/acct_buyer")
66
+ value = {
67
+ id: "cus_buyer",
68
+ customer_account: "acct_buyer",
69
+ livemode: false,
70
+ };
71
+ else if (path === "/v1/subscriptions" && method === "GET")
72
+ value = {
73
+ data: state.native
74
+ ? [state.native]
75
+ : external
76
+ ? [nativeSubscription()]
77
+ : [],
78
+ has_more: false,
79
+ };
80
+ else if (path === "/v1/subscriptions" && method === "POST") {
81
+ if (failCreate) throw new Error("private transport failure");
82
+ state.native = {
83
+ ...nativeSubscription(),
84
+ id:
85
+ ++subscriptionCreates === 1
86
+ ? "sub_calls"
87
+ : `sub_calls${subscriptionCreates}`,
88
+ metadata: { bsUsageIntent: body.get("metadata[bsUsageIntent]")! },
89
+ };
90
+ value = state.native;
91
+ } else if (path.startsWith("/v1/subscriptions/sub_calls")) {
92
+ if (state.missingNative)
93
+ return new Response(
94
+ JSON.stringify({
95
+ error: {
96
+ type: "invalid_request_error",
97
+ code: "resource_missing",
98
+ message: "private missing identity",
99
+ },
100
+ }),
101
+ { status: 404, headers: { "content-type": "application/json" } },
102
+ );
103
+ if (method === "POST" && state.native)
104
+ state.native.cancel_at_period_end =
105
+ body.get("cancel_at_period_end") === "true";
106
+ value = state.native;
107
+ } else if (path === "/v1/checkout/sessions" && method === "GET")
108
+ value = { data: state.session ? [state.session] : [], has_more: false };
109
+ else if (path === "/v1/checkout/sessions" && method === "POST") {
110
+ state.session = {
111
+ id:
112
+ ++checkoutCreates === 1
113
+ ? "cs_test_example"
114
+ : `cs_test_example${checkoutCreates}`,
115
+ mode: "subscription",
116
+ status: "open",
117
+ livemode: false,
118
+ customer_account: "acct_buyer",
119
+ customer: "cus_buyer",
120
+ metadata: { bsUsageIntent: body.get("metadata[bsUsageIntent]") },
121
+ url: "https://checkout.stripe.test/example",
122
+ subscription: null,
123
+ };
124
+ value = state.session;
125
+ } else if (path.startsWith("/v1/checkout/sessions/cs_test_example"))
126
+ value = state.session;
127
+ else if (path === "/v1/invoices/in_initial")
128
+ value = {
129
+ id: "in_initial",
130
+ livemode: false,
131
+ customer_account: "acct_buyer",
132
+ customer: "cus_buyer",
133
+ currency: "usd",
134
+ status: "void",
135
+ amount_paid: 0,
136
+ billing_reason: "subscription_create",
137
+ parent: { subscription_details: { subscription: "sub_calls" } },
138
+ };
139
+ else if (path === "/v1/invoices/in_closeout")
140
+ value = {
141
+ id: "in_closeout",
142
+ livemode: false,
143
+ customer_account: "acct_buyer",
144
+ customer: "cus_buyer",
145
+ currency: "usd",
146
+ status: "paid",
147
+ billing_reason: "subscription_cycle",
148
+ period_start: 600,
149
+ period_end: 1200,
150
+ status_transitions: { finalized_at: 1300 },
151
+ amount_due: 1010,
152
+ amount_paid: 1010,
153
+ total: 1010,
154
+ parent: {
155
+ subscription_details: {
156
+ subscription: "sub_calls",
157
+ metadata: state.native?.metadata ?? {},
158
+ },
159
+ },
160
+ lines: {
161
+ has_more: false,
162
+ data: [
163
+ {
164
+ id: "il_usage",
165
+ currency: "usd",
166
+ amount: 10,
167
+ quantity_decimal: "15",
168
+ quantity: 15,
169
+ pricing: {
170
+ type: "price_details",
171
+ price_details: { price: "price_calls" },
172
+ unit_amount_decimal: null,
173
+ },
174
+ parent: {
175
+ subscription_item_details: {
176
+ subscription: "sub_calls",
177
+ subscription_item: "si_calls",
178
+ proration: false,
179
+ },
180
+ },
181
+ period: { start: 600, end: 1200 },
182
+ pretax_credit_amounts: [],
183
+ },
184
+ ],
185
+ },
186
+ };
187
+ else if (path.startsWith("/v1/prices/")) {
188
+ const metered = path.endsWith("price_calls");
189
+ value = {
190
+ id: metered ? "price_calls" : "price_base",
191
+ active: true,
192
+ livemode: false,
193
+ product: "prod_calls",
194
+ lookup_key: "calls",
195
+ currency: "usd",
196
+ type: "recurring",
197
+ transform_quantity: null,
198
+ recurring: {
199
+ interval: "month",
200
+ interval_count: 1,
201
+ usage_type: metered ? "metered" : "licensed",
202
+ ...(metered ? { meter: "mtr_calls" } : {}),
203
+ },
204
+ ...(metered
205
+ ? {
206
+ billing_scheme: "tiered",
207
+ tiers_mode: "graduated",
208
+ tiers: [
209
+ { up_to: 10, unit_amount: 0 },
210
+ { up_to: null, unit_amount: 2 },
211
+ ],
212
+ }
213
+ : { billing_scheme: "per_unit", unit_amount: 1000 }),
214
+ };
215
+ } else if (path === "/v1/billing/meters/mtr_calls")
216
+ value = {
217
+ id: "mtr_calls",
218
+ livemode: false,
219
+ status: "active",
220
+ event_name: "calls",
221
+ default_aggregation: { formula: "sum" },
222
+ customer_mapping: {
223
+ type: "by_id",
224
+ event_payload_key: "stripe_customer_id",
225
+ },
226
+ value_settings: { event_payload_key: "value" },
227
+ event_time_window: null,
228
+ };
229
+ else throw new Error(`Unexpected test path ${path}`);
230
+ return new Response(JSON.stringify(value), {
231
+ status: 200,
232
+ headers: { "content-type": "application/json" },
233
+ });
234
+ },
235
+ );
236
+ const stripe = new Stripe("sk_test_subscription", {
237
+ maxNetworkRetries: 0,
238
+ httpClient,
239
+ });
240
+ return { t, component, stripe, calls, httpClient, state };
241
+ }
@@ -1,3 +1,4 @@
1
+ import { syncManagedUsageEvent } from "./usageSubscriptions.js";
1
2
  import { isFixedPrice } from "../products/fixedPrice.js";
2
3
  import { handleRefundEvent } from "./refundDelivery.js";
3
4
  import { handlePayoutEvent } from "./payoutReconciliation.js";
@@ -31,6 +32,7 @@ export async function processEvent(
31
32
  event: Stripe.Event,
32
33
  ): Promise<void> {
33
34
  // Stripe guarantees the object type matches event.type, so these casts are safe.
35
+ await syncManagedUsageEvent(whCtx, event);
34
36
  const obj = event.data.object;
35
37
 
36
38
  switch (event.type) {
@@ -0,0 +1,162 @@
1
+ import { expect, it } from "vitest";
2
+ import type Stripe from "stripe";
3
+ import { fixture } from "../usage/subscriptionTransport.fixtures.js";
4
+ import { request } from "../usage/subscription.fixtures.js";
5
+ import { BetterStripe } from "../index.js";
6
+ import type { RunCtx } from "../helpers.js";
7
+ import type { WebhookContext } from "./helpers.js";
8
+ import { syncManagedUsageEvent } from "./usageSubscriptions.js";
9
+ const ref = {
10
+ scope: {
11
+ stripeAccountId: "acct_platform",
12
+ customerAccount: "acct_buyer",
13
+ livemode: false,
14
+ },
15
+ requestId: "signup1",
16
+ };
17
+ it("refreshes managed native state rather than trusting an old subscription payload", async () => {
18
+ const f = fixture(),
19
+ client = new BetterStripe(f.component),
20
+ options = {
21
+ stripeSecretKey: "sk_test_subscription",
22
+ httpClient: f.httpClient,
23
+ };
24
+ await f.t.action((ctx) =>
25
+ client.usage.ensureSubscription(ctx as RunCtx, request, options),
26
+ );
27
+ const event = {
28
+ type: "customer.subscription.updated",
29
+ livemode: false,
30
+ data: { object: { ...f.state.native, status: "past_due" } },
31
+ } as unknown as Stripe.Event;
32
+ await f.t.action((ctx) =>
33
+ syncManagedUsageEvent(
34
+ {
35
+ ctx,
36
+ component: f.component,
37
+ stripe: f.stripe,
38
+ webhookSecret: "whsec_fixture",
39
+ } as WebhookContext,
40
+ event,
41
+ ),
42
+ );
43
+ expect(
44
+ await f.t.query((ctx) => client.usage.getSubscription(ctx as RunCtx, ref)),
45
+ ).toMatchObject({ status: "available", value: { status: "active" } });
46
+ f.state.missingNative = true;
47
+ await expect(
48
+ f.t.action((ctx) =>
49
+ syncManagedUsageEvent(
50
+ {
51
+ ctx,
52
+ component: f.component,
53
+ stripe: f.stripe,
54
+ webhookSecret: "whsec_fixture",
55
+ } as WebhookContext,
56
+ event,
57
+ ),
58
+ ),
59
+ ).rejects.toThrow("Native usage lifecycle observation unavailable");
60
+ });
61
+ it("records managed paid invoice observations without treating paid status as new cash", async () => {
62
+ const f = fixture(),
63
+ client = new BetterStripe(f.component),
64
+ options = {
65
+ stripeSecretKey: "sk_test_subscription",
66
+ httpClient: f.httpClient,
67
+ };
68
+ await f.t.action((ctx) =>
69
+ client.usage.ensureSubscription(ctx as RunCtx, request, options),
70
+ );
71
+ const event = {
72
+ type: "invoice.paid",
73
+ livemode: false,
74
+ data: {
75
+ object: {
76
+ id: "in_closeout",
77
+ parent: {
78
+ subscription_details: {
79
+ subscription: "sub_calls",
80
+ metadata: f.state.native!.metadata,
81
+ },
82
+ },
83
+ },
84
+ },
85
+ } as unknown as Stripe.Event;
86
+ await f.t.action((ctx) =>
87
+ syncManagedUsageEvent(
88
+ {
89
+ ctx,
90
+ component: f.component,
91
+ stripe: f.stripe,
92
+ webhookSecret: "whsec_fixture",
93
+ } as WebhookContext,
94
+ event,
95
+ ),
96
+ );
97
+ const history = await f.t.query((ctx) =>
98
+ client.usage.readSubscriptionHistory(ctx as RunCtx, {
99
+ ...ref,
100
+ kind: "invoice",
101
+ limit: 10,
102
+ cursor: null,
103
+ }),
104
+ );
105
+ expect(history.records[0].observation).toMatchObject([
106
+ {
107
+ observation: {
108
+ status: "available",
109
+ value: { status: "paid", paymentEvidence: "not_resolved" },
110
+ },
111
+ },
112
+ ]);
113
+ expect(
114
+ f.calls
115
+ .filter((call) => call.path.includes("/invoices/"))
116
+ .every((call) => call.method === "GET"),
117
+ ).toBe(true);
118
+ });
119
+ it("leaves existing fixed-price flows untouched and rejects foreign managed event context", async () => {
120
+ const f = fixture();
121
+ await f.t.action((ctx) =>
122
+ syncManagedUsageEvent(
123
+ {
124
+ ctx,
125
+ component: f.component,
126
+ stripe: f.stripe,
127
+ webhookSecret: "whsec_fixture",
128
+ } as WebhookContext,
129
+ {
130
+ type: "customer.subscription.updated",
131
+ livemode: false,
132
+ data: { object: { id: "sub_fixed", metadata: {} } },
133
+ } as unknown as Stripe.Event,
134
+ ),
135
+ );
136
+ expect(f.calls).toHaveLength(0);
137
+ const client = new BetterStripe(f.component);
138
+ await f.t.action((ctx) =>
139
+ client.usage.ensureSubscription(ctx as RunCtx, request, {
140
+ stripeSecretKey: "sk_test_subscription",
141
+ httpClient: f.httpClient,
142
+ }),
143
+ );
144
+ await expect(
145
+ f.t.action((ctx) =>
146
+ syncManagedUsageEvent(
147
+ {
148
+ ctx,
149
+ component: f.component,
150
+ stripe: f.stripe,
151
+ webhookSecret: "whsec_fixture",
152
+ } as WebhookContext,
153
+ {
154
+ type: "customer.subscription.updated",
155
+ account: "acct_foreign",
156
+ livemode: false,
157
+ data: { object: f.state.native },
158
+ } as unknown as Stripe.Event,
159
+ ),
160
+ ),
161
+ ).rejects.toThrow("Native usage lifecycle observation unavailable");
162
+ });