@fantastic.dev/better-stripe 0.54.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 (282) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +264 -8
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +132 -4
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +264 -8
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +132 -4
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +9 -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 +9 -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/invoiceObservation.d.ts +38 -0
  31. package/dist/client/usage/invoiceObservation.d.ts.map +1 -0
  32. package/dist/client/usage/invoiceObservation.js +157 -0
  33. package/dist/client/usage/invoiceObservation.js.map +1 -0
  34. package/dist/client/usage/observationClient.d.ts +83 -0
  35. package/dist/client/usage/observationClient.d.ts.map +1 -0
  36. package/dist/client/usage/observationClient.js +157 -0
  37. package/dist/client/usage/observationClient.js.map +1 -0
  38. package/dist/client/usage/observationTypes.d.ts +63 -0
  39. package/dist/client/usage/observationTypes.d.ts.map +1 -0
  40. package/dist/client/usage/observationTypes.js +59 -0
  41. package/dist/client/usage/observationTypes.js.map +1 -0
  42. package/dist/client/usage/providerObservation.d.ts +4 -0
  43. package/dist/client/usage/providerObservation.d.ts.map +1 -0
  44. package/dist/client/usage/providerObservation.js +96 -0
  45. package/dist/client/usage/providerObservation.js.map +1 -0
  46. package/dist/client/usage/reconciliation.d.ts +12 -0
  47. package/dist/client/usage/reconciliation.d.ts.map +1 -0
  48. package/dist/client/usage/reconciliation.js +48 -0
  49. package/dist/client/usage/reconciliation.js.map +1 -0
  50. package/dist/client/usage/subscription.fixtures.d.ts +118 -0
  51. package/dist/client/usage/subscription.fixtures.d.ts.map +1 -0
  52. package/dist/client/usage/subscription.fixtures.js +84 -0
  53. package/dist/client/usage/subscription.fixtures.js.map +1 -0
  54. package/dist/client/usage/subscriptionAbandonment.d.ts +8 -0
  55. package/dist/client/usage/subscriptionAbandonment.d.ts.map +1 -0
  56. package/dist/client/usage/subscriptionAbandonment.js +82 -0
  57. package/dist/client/usage/subscriptionAbandonment.js.map +1 -0
  58. package/dist/client/usage/subscriptionCancellation.d.ts +9 -0
  59. package/dist/client/usage/subscriptionCancellation.d.ts.map +1 -0
  60. package/dist/client/usage/subscriptionCancellation.js +39 -0
  61. package/dist/client/usage/subscriptionCancellation.js.map +1 -0
  62. package/dist/client/usage/subscriptionCheckout.d.ts +52 -0
  63. package/dist/client/usage/subscriptionCheckout.d.ts.map +1 -0
  64. package/dist/client/usage/subscriptionCheckout.js +94 -0
  65. package/dist/client/usage/subscriptionCheckout.js.map +1 -0
  66. package/dist/client/usage/subscriptionClient.d.ts +267 -0
  67. package/dist/client/usage/subscriptionClient.d.ts.map +1 -0
  68. package/dist/client/usage/subscriptionClient.js +93 -0
  69. package/dist/client/usage/subscriptionClient.js.map +1 -0
  70. package/dist/client/usage/subscriptionErrors.d.ts +5 -0
  71. package/dist/client/usage/subscriptionErrors.d.ts.map +1 -0
  72. package/dist/client/usage/subscriptionErrors.js +9 -0
  73. package/dist/client/usage/subscriptionErrors.js.map +1 -0
  74. package/dist/client/usage/subscriptionInvoiceSchema.d.ts +203 -0
  75. package/dist/client/usage/subscriptionInvoiceSchema.d.ts.map +1 -0
  76. package/dist/client/usage/subscriptionInvoiceSchema.js +108 -0
  77. package/dist/client/usage/subscriptionInvoiceSchema.js.map +1 -0
  78. package/dist/client/usage/subscriptionLifecycle.d.ts +80 -0
  79. package/dist/client/usage/subscriptionLifecycle.d.ts.map +1 -0
  80. package/dist/client/usage/subscriptionLifecycle.js +87 -0
  81. package/dist/client/usage/subscriptionLifecycle.js.map +1 -0
  82. package/dist/client/usage/subscriptionProvider.d.ts +111 -0
  83. package/dist/client/usage/subscriptionProvider.d.ts.map +1 -0
  84. package/dist/client/usage/subscriptionProvider.js +147 -0
  85. package/dist/client/usage/subscriptionProvider.js.map +1 -0
  86. package/dist/client/usage/subscriptionTerms.d.ts +161 -0
  87. package/dist/client/usage/subscriptionTerms.d.ts.map +1 -0
  88. package/dist/client/usage/subscriptionTerms.js +242 -0
  89. package/dist/client/usage/subscriptionTerms.js.map +1 -0
  90. package/dist/client/usage/subscriptionTransport.fixtures.d.ts +25 -0
  91. package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -0
  92. package/dist/client/usage/subscriptionTransport.fixtures.js +203 -0
  93. package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -0
  94. package/dist/client/usage/summary.d.ts +50 -0
  95. package/dist/client/usage/summary.d.ts.map +1 -0
  96. package/dist/client/usage/summary.js +110 -0
  97. package/dist/client/usage/summary.js.map +1 -0
  98. package/dist/client/webhooks/processors.d.ts.map +1 -1
  99. package/dist/client/webhooks/processors.js +2 -0
  100. package/dist/client/webhooks/processors.js.map +1 -1
  101. package/dist/client/webhooks/usageSubscriptions.d.ts +5 -0
  102. package/dist/client/webhooks/usageSubscriptions.d.ts.map +1 -0
  103. package/dist/client/webhooks/usageSubscriptions.js +54 -0
  104. package/dist/client/webhooks/usageSubscriptions.js.map +1 -0
  105. package/dist/component/_generated/api.d.ts +22 -0
  106. package/dist/component/_generated/api.d.ts.map +1 -1
  107. package/dist/component/_generated/api.js.map +1 -1
  108. package/dist/component/_generated/component.d.ts +255 -5
  109. package/dist/component/_generated/component.d.ts.map +1 -1
  110. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  111. package/dist/component/accountClosure/mutations.js +10 -0
  112. package/dist/component/accountClosure/mutations.js.map +1 -1
  113. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  114. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  115. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  116. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  117. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  118. package/dist/component/earnings/triggers.d.ts +296 -22
  119. package/dist/component/earnings/triggers.d.ts.map +1 -1
  120. package/dist/component/payoutRelease/queries.d.ts +2 -2
  121. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  122. package/dist/component/refundHistory/queries.d.ts +1 -1
  123. package/dist/component/schema.d.ts +132 -4
  124. package/dist/component/schema.js +8 -0
  125. package/dist/component/schema.js.map +1 -1
  126. package/dist/component/usage/mutations.d.ts.map +1 -1
  127. package/dist/component/usage/mutations.js +5 -0
  128. package/dist/component/usage/mutations.js.map +1 -1
  129. package/dist/component/usage/queries.d.ts +2 -0
  130. package/dist/component/usage/queries.d.ts.map +1 -1
  131. package/dist/component/usage/schema.d.ts +21 -9
  132. package/dist/component/usage/schema.d.ts.map +1 -1
  133. package/dist/component/usage/schema.js +5 -1
  134. package/dist/component/usage/schema.js.map +1 -1
  135. package/dist/component/usageDelivery/fields.d.ts +4 -2
  136. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  137. package/dist/component/usageDelivery/fields.js +3 -1
  138. package/dist/component/usageDelivery/fields.js.map +1 -1
  139. package/dist/component/usageDelivery/helpers.d.ts +5 -3
  140. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  141. package/dist/component/usageDelivery/mutations.d.ts +3 -3
  142. package/dist/component/usageDelivery/mutations.d.ts.map +1 -1
  143. package/dist/component/usageDelivery/mutations.js +8 -1
  144. package/dist/component/usageDelivery/mutations.js.map +1 -1
  145. package/dist/component/usageDelivery/queries.d.ts +19 -3
  146. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  147. package/dist/component/usageDelivery/queries.js +20 -3
  148. package/dist/component/usageDelivery/queries.js.map +1 -1
  149. package/dist/component/usageDelivery/schema.d.ts +2 -2
  150. package/dist/component/usageDelivery/steps.d.ts +1 -1
  151. package/dist/component/usageDelivery/steps.d.ts.map +1 -1
  152. package/dist/component/usageDelivery/steps.js +20 -2
  153. package/dist/component/usageDelivery/steps.js.map +1 -1
  154. package/dist/component/usageObservations/helpers.d.ts +38 -0
  155. package/dist/component/usageObservations/helpers.d.ts.map +1 -0
  156. package/dist/component/usageObservations/helpers.js +80 -0
  157. package/dist/component/usageObservations/helpers.js.map +1 -0
  158. package/dist/component/usageObservations/history.d.ts +6 -0
  159. package/dist/component/usageObservations/history.d.ts.map +1 -0
  160. package/dist/component/usageObservations/history.js +29 -0
  161. package/dist/component/usageObservations/history.js.map +1 -0
  162. package/dist/component/usageObservations/mutations.d.ts +6 -0
  163. package/dist/component/usageObservations/mutations.d.ts.map +1 -0
  164. package/dist/component/usageObservations/mutations.js +39 -0
  165. package/dist/component/usageObservations/mutations.js.map +1 -0
  166. package/dist/component/usageObservations/queries.d.ts +78 -0
  167. package/dist/component/usageObservations/queries.d.ts.map +1 -0
  168. package/dist/component/usageObservations/queries.js +131 -0
  169. package/dist/component/usageObservations/queries.js.map +1 -0
  170. package/dist/component/usageObservations/schema.d.ts +72 -0
  171. package/dist/component/usageObservations/schema.d.ts.map +1 -0
  172. package/dist/component/usageObservations/schema.js +29 -0
  173. package/dist/component/usageObservations/schema.js.map +1 -0
  174. package/dist/component/usageSubscriptions/abandonment.d.ts +4 -0
  175. package/dist/component/usageSubscriptions/abandonment.d.ts.map +1 -0
  176. package/dist/component/usageSubscriptions/abandonment.js +59 -0
  177. package/dist/component/usageSubscriptions/abandonment.js.map +1 -0
  178. package/dist/component/usageSubscriptions/acceptance.d.ts +11 -0
  179. package/dist/component/usageSubscriptions/acceptance.d.ts.map +1 -0
  180. package/dist/component/usageSubscriptions/acceptance.js +38 -0
  181. package/dist/component/usageSubscriptions/acceptance.js.map +1 -0
  182. package/dist/component/usageSubscriptions/helpers.d.ts +39 -0
  183. package/dist/component/usageSubscriptions/helpers.d.ts.map +1 -0
  184. package/dist/component/usageSubscriptions/helpers.js +28 -0
  185. package/dist/component/usageSubscriptions/helpers.js.map +1 -0
  186. package/dist/component/usageSubscriptions/history.d.ts +46 -0
  187. package/dist/component/usageSubscriptions/history.d.ts.map +1 -0
  188. package/dist/component/usageSubscriptions/history.js +46 -0
  189. package/dist/component/usageSubscriptions/history.js.map +1 -0
  190. package/dist/component/usageSubscriptions/mutations.d.ts +64 -0
  191. package/dist/component/usageSubscriptions/mutations.d.ts.map +1 -0
  192. package/dist/component/usageSubscriptions/mutations.js +252 -0
  193. package/dist/component/usageSubscriptions/mutations.js.map +1 -0
  194. package/dist/component/usageSubscriptions/queries.d.ts +81 -0
  195. package/dist/component/usageSubscriptions/queries.d.ts.map +1 -0
  196. package/dist/component/usageSubscriptions/queries.js +70 -0
  197. package/dist/component/usageSubscriptions/queries.js.map +1 -0
  198. package/dist/component/usageSubscriptions/retirement.d.ts +4 -0
  199. package/dist/component/usageSubscriptions/retirement.d.ts.map +1 -0
  200. package/dist/component/usageSubscriptions/retirement.js +80 -0
  201. package/dist/component/usageSubscriptions/retirement.js.map +1 -0
  202. package/dist/component/usageSubscriptions/schema.d.ts +191 -0
  203. package/dist/component/usageSubscriptions/schema.d.ts.map +1 -0
  204. package/dist/component/usageSubscriptions/schema.js +69 -0
  205. package/dist/component/usageSubscriptions/schema.js.map +1 -0
  206. package/dist/test.d.ts +6 -0
  207. package/dist/test.d.ts.map +1 -0
  208. package/dist/test.js +15 -0
  209. package/dist/test.js.map +1 -0
  210. package/docs/README.md +4 -0
  211. package/docs/evidence/native-metering/clock-finalization-run.json +129 -0
  212. package/docs/evidence/native-metering/clock-lag-run.json +111 -0
  213. package/docs/evidence/native-metering/paid-run.json +107 -0
  214. package/docs/evidence/native-metering/promotional-run.json +103 -0
  215. package/docs/metered-usage.md +14 -0
  216. package/docs/metering-setup.md +7 -1
  217. package/docs/usage-observations.md +152 -0
  218. package/docs/usage-subscriptions.md +278 -0
  219. package/package.json +5 -2
  220. package/src/client/index.ts +26 -0
  221. package/src/client/usage/catalogPrices.ts +21 -0
  222. package/src/client/usage/client.ts +2 -2
  223. package/src/client/usage/deliveryProvider.test.ts +70 -1
  224. package/src/client/usage/deliveryProvider.ts +43 -2
  225. package/src/client/usage/index.ts +27 -0
  226. package/src/client/usage/invoiceObservation.test.ts +195 -0
  227. package/src/client/usage/invoiceObservation.ts +203 -0
  228. package/src/client/usage/observationClient.ts +233 -0
  229. package/src/client/usage/observationTypes.ts +101 -0
  230. package/src/client/usage/providerObservation.test.ts +207 -0
  231. package/src/client/usage/providerObservation.ts +124 -0
  232. package/src/client/usage/reconciliation.test.ts +117 -0
  233. package/src/client/usage/reconciliation.ts +86 -0
  234. package/src/client/usage/subscription.fixtures.ts +84 -0
  235. package/src/client/usage/subscriptionAbandonment.test.ts +124 -0
  236. package/src/client/usage/subscriptionAbandonment.ts +116 -0
  237. package/src/client/usage/subscriptionCancellation.ts +90 -0
  238. package/src/client/usage/subscriptionCheckout.test.ts +31 -0
  239. package/src/client/usage/subscriptionCheckout.ts +152 -0
  240. package/src/client/usage/subscriptionClient.test.ts +316 -0
  241. package/src/client/usage/subscriptionClient.ts +204 -0
  242. package/src/client/usage/subscriptionErrors.ts +14 -0
  243. package/src/client/usage/subscriptionInvoiceSchema.ts +116 -0
  244. package/src/client/usage/subscriptionLifecycle.ts +165 -0
  245. package/src/client/usage/subscriptionProvider.test.ts +48 -0
  246. package/src/client/usage/subscriptionProvider.ts +247 -0
  247. package/src/client/usage/subscriptionTerms.test.ts +158 -0
  248. package/src/client/usage/subscriptionTerms.ts +294 -0
  249. package/src/client/usage/subscriptionTransport.fixtures.ts +241 -0
  250. package/src/client/usage/summary.test.ts +222 -0
  251. package/src/client/usage/summary.ts +188 -0
  252. package/src/client/webhooks/processors.ts +2 -0
  253. package/src/client/webhooks/usageSubscriptions.test.ts +162 -0
  254. package/src/client/webhooks/usageSubscriptions.ts +81 -0
  255. package/src/component/_generated/api.ts +22 -0
  256. package/src/component/_generated/component.ts +335 -0
  257. package/src/component/accountClosure/mutations.ts +12 -0
  258. package/src/component/schema.ts +16 -0
  259. package/src/component/usage/mutations.ts +5 -0
  260. package/src/component/usage/schema.ts +5 -1
  261. package/src/component/usageDelivery/fields.ts +3 -0
  262. package/src/component/usageDelivery/mutations.ts +26 -1
  263. package/src/component/usageDelivery/queries.ts +30 -3
  264. package/src/component/usageDelivery/steps.ts +61 -2
  265. package/src/component/usageObservations/helpers.ts +95 -0
  266. package/src/component/usageObservations/history.test.ts +87 -0
  267. package/src/component/usageObservations/history.ts +39 -0
  268. package/src/component/usageObservations/mutations.ts +39 -0
  269. package/src/component/usageObservations/queries.test.ts +162 -0
  270. package/src/component/usageObservations/queries.ts +145 -0
  271. package/src/component/usageObservations/schema.ts +40 -0
  272. package/src/component/usageSubscriptions/abandonment.ts +80 -0
  273. package/src/component/usageSubscriptions/acceptance.test.ts +122 -0
  274. package/src/component/usageSubscriptions/acceptance.ts +66 -0
  275. package/src/component/usageSubscriptions/helpers.ts +33 -0
  276. package/src/component/usageSubscriptions/history.test.ts +69 -0
  277. package/src/component/usageSubscriptions/history.ts +68 -0
  278. package/src/component/usageSubscriptions/mutations.test.ts +205 -0
  279. package/src/component/usageSubscriptions/mutations.ts +275 -0
  280. package/src/component/usageSubscriptions/queries.ts +78 -0
  281. package/src/component/usageSubscriptions/retirement.ts +105 -0
  282. package/src/component/usageSubscriptions/schema.ts +73 -0
@@ -0,0 +1,158 @@
1
+ import { expect, it } from "vitest";
2
+ import {
3
+ subscriptionTerms,
4
+ subscriptionView,
5
+ closeoutPolicy,
6
+ } from "./subscriptionTerms.js";
7
+ import { request, nativeSubscription, meter } from "./subscription.fixtures.js";
8
+ it("normalizes all model bindings and rejects cross-payer or duplicated meters", () => {
9
+ expect(subscriptionTerms(request).meters[0].binding.plan.model).toBe(
10
+ "included_overage",
11
+ );
12
+ expect(() =>
13
+ subscriptionTerms({ ...request, meters: [meter, meter] }),
14
+ ).toThrow();
15
+ expect(() =>
16
+ subscriptionTerms({
17
+ ...request,
18
+ meters: [
19
+ meter,
20
+ {
21
+ ...meter,
22
+ scope: {
23
+ ...meter.scope,
24
+ customerAccount: "acct_other",
25
+ meterId: "mtr_other",
26
+ },
27
+ },
28
+ ],
29
+ }),
30
+ ).toThrow();
31
+ });
32
+ it("retains every native item and original half-open metered period, including nullable tiered rates", () => {
33
+ const view = subscriptionView(
34
+ nativeSubscription(),
35
+ subscriptionTerms(request),
36
+ );
37
+ expect(view.bindings[0].subscription).toEqual({
38
+ subscriptionId: "sub_calls",
39
+ subscriptionItemId: "si_calls",
40
+ stripePriceId: "price_calls",
41
+ period: { start: 600, end: 1200 },
42
+ interval: "month",
43
+ });
44
+ expect(view.items).toHaveLength(2);
45
+ expect(view.items[0]).toMatchObject({
46
+ quantity: null,
47
+ unitAmountDecimal: null,
48
+ });
49
+ expect(() =>
50
+ subscriptionView(
51
+ {
52
+ ...nativeSubscription(),
53
+ items: { ...nativeSubscription().items, has_more: true },
54
+ },
55
+ subscriptionTerms(request),
56
+ ),
57
+ ).toThrow();
58
+ expect(() =>
59
+ subscriptionView(
60
+ { ...nativeSubscription(), customer_account: "acct_other" },
61
+ subscriptionTerms(request),
62
+ ),
63
+ ).toThrow();
64
+ });
65
+ it("keeps renewal periods separate and refuses changed native pricing or duplicate meter items", () => {
66
+ const sub = nativeSubscription();
67
+ sub.items.data[0].current_period_start = 1200;
68
+ sub.items.data[0].current_period_end = 1800;
69
+ expect(
70
+ subscriptionView(sub, subscriptionTerms(request)).bindings[0].subscription
71
+ .period,
72
+ ).toEqual({ start: 1200, end: 1800 });
73
+ sub.items.data[0].price.id = "price_other";
74
+ expect(() => subscriptionView(sub, subscriptionTerms(request))).toThrow();
75
+ const duplicate = nativeSubscription();
76
+ duplicate.items.data.push({ ...duplicate.items.data[0], id: "si_duplicate" });
77
+ expect(() =>
78
+ subscriptionView(duplicate, subscriptionTerms(request)),
79
+ ).toThrow();
80
+ });
81
+ it("exposes cutoff uncertainty and refuses immediate cancellation or silent repricing", () => {
82
+ expect(
83
+ closeoutPolicy({
84
+ queued: 1,
85
+ unknown: 0,
86
+ reservations: 0,
87
+ finalized: false,
88
+ }),
89
+ ).toMatchObject({ ready: false, reason: "pending_usage" });
90
+ expect(
91
+ closeoutPolicy({
92
+ queued: 0,
93
+ unknown: 1,
94
+ reservations: 0,
95
+ finalized: false,
96
+ }),
97
+ ).toMatchObject({ ready: false });
98
+ expect(
99
+ closeoutPolicy({
100
+ queued: 0,
101
+ unknown: 0,
102
+ reservations: 1,
103
+ finalized: false,
104
+ }),
105
+ ).toMatchObject({ ready: false, reason: "pending_reservations" });
106
+ expect(
107
+ closeoutPolicy({
108
+ queued: 0,
109
+ unknown: 0,
110
+ reservations: 0,
111
+ finalized: false,
112
+ }),
113
+ ).toMatchObject({ ready: false, reason: "invoice_not_finalized" });
114
+ expect(
115
+ closeoutPolicy({ queued: 0, unknown: 0, reservations: 0, finalized: true }),
116
+ ).toMatchObject({ ready: true, paymentEvidence: "not_resolved" });
117
+ });
118
+
119
+ it("uses the same subscription contract for all three models without mixing currencies", () => {
120
+ const { key, version, unit, rate } = meter.binding.plan;
121
+ const common = { key, version, unit, rate };
122
+ const plans = [
123
+ { ...common, model: "pay_as_you_go" },
124
+ {
125
+ ...common,
126
+ model: "included_overage",
127
+ includedQuantity: "10",
128
+ reset: "billing_period",
129
+ },
130
+ { ...common, model: "prepaid", insufficientBalance: "reject" },
131
+ ];
132
+ for (const plan of plans)
133
+ expect(
134
+ subscriptionTerms({
135
+ ...request,
136
+ meters: [{ ...meter, binding: { ...meter.binding, plan } }],
137
+ }).meters[0].binding.plan.model,
138
+ ).toBe(plan.model);
139
+ });
140
+
141
+ it("rejects native collection-policy drift instead of hiding an automatic charge policy", () => {
142
+ const sub = {
143
+ ...nativeSubscription(),
144
+ collection_method: "charge_automatically",
145
+ days_until_due: null,
146
+ default_payment_method: "pm_other",
147
+ };
148
+ expect(() => subscriptionView(sub, subscriptionTerms(request))).toThrow();
149
+ expect(
150
+ subscriptionView(nativeSubscription(), subscriptionTerms(request)),
151
+ ).toMatchObject({
152
+ collection: {
153
+ method: "send_invoice",
154
+ daysUntilDue: 30,
155
+ defaultPaymentMethod: null,
156
+ },
157
+ });
158
+ });
@@ -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
+ }