@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.54.0",
3
+ "version": "0.56.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -103,7 +103,10 @@
103
103
  "docs/development.md",
104
104
  "docs/usage-ledger.md",
105
105
  "docs/usage-catalog.md",
106
- "docs/usage-delivery.md"
106
+ "docs/usage-delivery.md",
107
+ "docs/usage-observations.md",
108
+ "docs/usage-subscriptions.md",
109
+ "docs/evidence/native-metering"
107
110
  ],
108
111
  "scripts": {
109
112
  "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
@@ -1,3 +1,4 @@
1
+ export { UsageSubscriptionError } from "./usage/subscriptionErrors.js";
1
2
  export { UsageCatalogError } from "./usage/catalogTypes.js";
2
3
  export type {
3
4
  UsageCatalogScope,
@@ -1843,3 +1844,28 @@ export {
1843
1844
  usageDeliveryArgs,
1844
1845
  usageDeliveryResult,
1845
1846
  } from "./usage/deliveryProtocol.js";
1847
+
1848
+ export type {
1849
+ UsageObservationOptions,
1850
+ UsageAggregateValue,
1851
+ UsageAggregateObservation,
1852
+ } from "./usage/observationTypes.js";
1853
+ export type {
1854
+ UsageLocalSummary,
1855
+ UsageLocalGroup,
1856
+ UsageCreditSummary,
1857
+ } from "./usage/summary.js";
1858
+ export type { UsageComparison } from "./usage/reconciliation.js";
1859
+ export type { UsageReconciliationOptions } from "./usage/observationClient.js";
1860
+
1861
+ export type {
1862
+ UsageInvoiceObservation,
1863
+ UsageInvoiceLine,
1864
+ } from "./usage/invoiceObservation.js";
1865
+
1866
+ export type {
1867
+ UsageSubscriptionOptions,
1868
+ UsageSubscriptionView,
1869
+ } from "./usage/subscriptionTerms.js";
1870
+ export type { UsageSubscriptionRef } from "./usage/subscriptionLifecycle.js";
1871
+ export type { UsageSubscriptionInvoice } from "./usage/subscriptionInvoiceSchema.js";
@@ -249,3 +249,24 @@ export async function ensureUsagePrice(
249
249
  });
250
250
  return price;
251
251
  }
252
+
253
+ /** Validate an already pinned native price without creating or adopting it. */
254
+ export function verifyPinnedUsagePrice(
255
+ price: Stripe.Price,
256
+ scope: UsagePriceOptions["scope"],
257
+ plan: UsagePriceOptions["plan"],
258
+ meterId: string,
259
+ ) {
260
+ const productId =
261
+ typeof price.product === "string" ? price.product : price.product.id;
262
+ if (!price.lookup_key) return incompatible();
263
+ const opts = {
264
+ scope,
265
+ plan,
266
+ meterId,
267
+ stripeProductId: productId,
268
+ lookupKey: price.lookup_key,
269
+ };
270
+ const { rate, included } = termsFor(opts);
271
+ verifyPrice(price, opts, rate, included);
272
+ }
@@ -1,4 +1,4 @@
1
- import { UsageDeliveryClient } from "./deliveryClient.js";
1
+ import { UsageSubscriptionClient } from "./subscriptionClient.js";
2
2
  import type { Component, RunCtx } from "../helpers.js";
3
3
  import { runMutationOrThrow } from "../helpers.js";
4
4
  import { componentRef } from "../webhooks/helpers.js";
@@ -46,7 +46,7 @@ function decode({ event, delivery }: StoredView): UsageEventView {
46
46
  };
47
47
  }
48
48
  /** Trusted host facade. Authenticate and authorize each exact scope first. */
49
- export class UsageLedgerClient extends UsageDeliveryClient {
49
+ export class UsageLedgerClient extends UsageSubscriptionClient {
50
50
  constructor(component: Component) {
51
51
  super(component);
52
52
  }
@@ -11,7 +11,11 @@ const scope = {
11
11
  meterId: "mtr_calls",
12
12
  livemode: false,
13
13
  };
14
- function setup(status = 200, errorCode = "parameter_invalid_integer") {
14
+ function setup(
15
+ status = 200,
16
+ errorCode = "parameter_invalid_integer",
17
+ nativeOverrides: Record<string, unknown> = {},
18
+ ) {
15
19
  const now = Math.floor(Date.now() / 1000);
16
20
  const record = prepareUsageRecord({
17
21
  scope,
@@ -32,6 +36,12 @@ function setup(status = 200, errorCode = "parameter_invalid_integer") {
32
36
  occurredAt: now,
33
37
  });
34
38
  const saved = {
39
+ billingCutoff: null as number | null,
40
+ managedCollection: null as {
41
+ method: "send_invoice" | "charge_automatically";
42
+ daysUntilDue: number | null;
43
+ defaultPaymentMethod: string | null;
44
+ } | null,
35
45
  event: {
36
46
  recordJson: JSON.stringify(record),
37
47
  subscriptionJson: JSON.stringify({
@@ -88,6 +98,7 @@ function setup(status = 200, errorCode = "parameter_invalid_integer") {
88
98
  livemode: false,
89
99
  customer: "cus_buyer",
90
100
  customer_account: "acct_buyer",
101
+ ...nativeOverrides,
91
102
  }
92
103
  : status === 200
93
104
  ? {
@@ -205,3 +216,61 @@ it("holds duplicate/uncertain errors and a lost response instead of retrying tra
205
216
  ).toHaveLength(1);
206
217
  }
207
218
  });
219
+
220
+ it("withholds a managed send that reaches its billing cutoff during preflight", async () => {
221
+ const f = setup();
222
+ const now = Math.floor(Date.now() / 1000);
223
+ f.saved.billingCutoff = now + 100;
224
+ let reads = 0;
225
+ vi.mocked(f.ctx.runQuery).mockImplementation(async () => {
226
+ reads++;
227
+ return { ...f.saved, billingCutoff: reads === 1 ? now + 100 : now + 10 };
228
+ });
229
+ const result = await deliverUsageProvider(
230
+ componentsGeneric().betterStripe as unknown as Component,
231
+ f.ctx,
232
+ f.request,
233
+ { stripeSecretKey: "sk_test_usage", httpClient: f.httpClient },
234
+ );
235
+ expect(result.outcome.status).toBe("unknown");
236
+ expect(f.requests.some((r) => r.path === "/v1/billing/meter_events")).toBe(
237
+ false,
238
+ );
239
+ });
240
+
241
+ it("withholds a managed send when native manual invoicing drifts to automatic charging", async () => {
242
+ const now = Math.floor(Date.now() / 1000);
243
+ const f = setup(200, "parameter_invalid_integer", {
244
+ status: "active",
245
+ collection_method: "charge_automatically",
246
+ days_until_due: null,
247
+ default_payment_method: "pm_owned",
248
+ items: {
249
+ has_more: false,
250
+ data: [
251
+ {
252
+ id: "si_calls",
253
+ price: { id: "price_calls" },
254
+ current_period_start: now - 1,
255
+ current_period_end: now + 86400,
256
+ },
257
+ ],
258
+ },
259
+ });
260
+ f.saved.billingCutoff = now + 86400 - 60;
261
+ f.saved.managedCollection = {
262
+ method: "send_invoice",
263
+ daysUntilDue: 30,
264
+ defaultPaymentMethod: null,
265
+ };
266
+ const result = await deliverUsageProvider(
267
+ componentsGeneric().betterStripe as unknown as Component,
268
+ f.ctx,
269
+ f.request,
270
+ { stripeSecretKey: "sk_test_usage", httpClient: f.httpClient },
271
+ );
272
+ expect(result.outcome.status).toBe("unavailable");
273
+ expect(f.requests.some((r) => r.path === "/v1/billing/meter_events")).toBe(
274
+ false,
275
+ );
276
+ });
@@ -1,3 +1,4 @@
1
+ import type { UsageSubscriptionView } from "./subscriptionTerms.js";
1
2
  import Stripe from "stripe";
2
3
  import type { StripeApiVersion } from "../stripe-types.js";
3
4
  import { z } from "zod";
@@ -50,7 +51,12 @@ export async function deliverUsageProvider(
50
51
  ctx.runQuery(componentRef(component, "usageDelivery/queries/snapshot"), {
51
52
  scope: args.scope,
52
53
  eventId: args.eventId,
53
- }) as Promise<{ event: Doc<"usageEvents">; outbox: Doc<"usageOutbox"> }>;
54
+ }) as Promise<{
55
+ event: Doc<"usageEvents">;
56
+ outbox: Doc<"usageOutbox">;
57
+ billingCutoff: number | null;
58
+ managedCollection: UsageSubscriptionView["collection"] | null;
59
+ }>;
54
60
  const saved = await read(),
55
61
  record = JSON.parse(saved.event.recordJson) as PreparedUsageRecord;
56
62
  const eligible = (outbox: Doc<"usageOutbox">) =>
@@ -64,6 +70,8 @@ export async function deliverUsageProvider(
64
70
  (outbox.leaseUntil ?? 0) > Date.now() / 1000 + 60;
65
71
  if (
66
72
  !eligible(saved.outbox) ||
73
+ (saved.billingCutoff !== null &&
74
+ Date.now() / 1000 + 15 >= saved.billingCutoff) ||
67
75
  record.binding.apiVersion !== apiVersion ||
68
76
  JSON.stringify(record.scope) !== JSON.stringify(args.scope)
69
77
  )
@@ -96,7 +104,40 @@ export async function deliverUsageProvider(
96
104
  eventName: record.binding.eventName,
97
105
  displayName: meter.display_name,
98
106
  });
99
- if (!eligible((await read()).outbox)) return done({ status: "unknown" });
107
+ const current = await read();
108
+ if (
109
+ !eligible(current.outbox) ||
110
+ (current.billingCutoff !== null &&
111
+ Date.now() / 1000 + 15 >= current.billingCutoff)
112
+ )
113
+ return done({ status: "unknown" });
114
+ if (current.billingCutoff !== null) {
115
+ const collection = current.managedCollection;
116
+ const method =
117
+ typeof subscription.default_payment_method === "string"
118
+ ? subscription.default_payment_method
119
+ : (subscription.default_payment_method?.id ?? null);
120
+ if (
121
+ !collection ||
122
+ collection.method !== subscription.collection_method ||
123
+ (collection.method === "send_invoice"
124
+ ? collection.daysUntilDue !== subscription.days_until_due
125
+ : collection.defaultPaymentMethod !== method)
126
+ )
127
+ return done({ status: "unavailable" });
128
+ const item = subscription.items.data.find(
129
+ (item) => item.id === binding.subscriptionItemId,
130
+ );
131
+ if (
132
+ subscription.status !== "active" ||
133
+ subscription.items.has_more ||
134
+ !item ||
135
+ item.price.id !== binding.stripePriceId ||
136
+ item.current_period_start !== binding.period.start ||
137
+ item.current_period_end !== binding.period.end
138
+ )
139
+ return done({ status: "unavailable" });
140
+ }
100
141
  writing = true;
101
142
  const response = await stripe.billing.meterEvents.create(
102
143
  {
@@ -45,3 +45,30 @@ export type {
45
45
  } from "./deliveryClient.js";
46
46
 
47
47
  export { usageDeliveryArgs, usageDeliveryResult } from "./deliveryProtocol.js";
48
+
49
+ export type {
50
+ UsageObservationOptions,
51
+ UsageAggregateValue,
52
+ UsageAggregateObservation,
53
+ } from "./observationTypes.js";
54
+ export type {
55
+ UsageLocalSummary,
56
+ UsageLocalGroup,
57
+ UsageCreditSummary,
58
+ } from "./summary.js";
59
+ export type { UsageComparison } from "./reconciliation.js";
60
+ export type { UsageReconciliationOptions } from "./observationClient.js";
61
+
62
+ export type {
63
+ UsageInvoiceObservation,
64
+ UsageInvoiceLine,
65
+ } from "./invoiceObservation.js";
66
+
67
+ export type {
68
+ UsageSubscriptionOptions,
69
+ UsageSubscriptionView,
70
+ } from "./subscriptionTerms.js";
71
+ export type { UsageSubscriptionRef } from "./subscriptionLifecycle.js";
72
+ export type { UsageSubscriptionInvoice } from "./subscriptionInvoiceSchema.js";
73
+
74
+ export { UsageSubscriptionError } from "./subscriptionErrors.js";
@@ -0,0 +1,195 @@
1
+ import Stripe from "stripe";
2
+ import { convexToJson } from "convex/values";
3
+ import { expect, it } from "vitest";
4
+ import { STRIPE_API_VERSION } from "../constants.js";
5
+ import { prepareUsageRecord } from "./records.js";
6
+ import { observeUsageInvoice } from "./invoiceObservation.js";
7
+ const scope = {
8
+ stripeAccountId: "acct_platform",
9
+ customerAccount: "acct_buyer",
10
+ meterId: "mtr_calls",
11
+ livemode: false,
12
+ },
13
+ period = { start: 600, end: 1200 };
14
+ const binding = prepareUsageRecord({
15
+ scope,
16
+ binding: {
17
+ stripeCustomerId: "cus_buyer",
18
+ stripePriceId: "price_calls",
19
+ eventName: "calls",
20
+ plan: {
21
+ key: "calls",
22
+ version: "v1",
23
+ model: "pay_as_you_go",
24
+ unit: { name: "call", precision: 0 },
25
+ rate: { currency: "usd", unitAmountDecimal: "2" },
26
+ },
27
+ },
28
+ sourceEventId: "read",
29
+ quantity: "0",
30
+ occurredAt: 600,
31
+ }).binding;
32
+ const options = {
33
+ scope,
34
+ binding,
35
+ subscription: {
36
+ subscriptionId: "sub_calls",
37
+ subscriptionItemId: "si_calls",
38
+ stripePriceId: "price_calls",
39
+ period,
40
+ interval: "month" as const,
41
+ },
42
+ period,
43
+ };
44
+ function setup(hasMore = false, wrongPayer = false, missingQuantity = false) {
45
+ const requests: Array<{ method: string; path: string }> = [];
46
+ const stripe = new Stripe("sk_test_invoice_read", {
47
+ apiVersion: STRIPE_API_VERSION,
48
+ maxNetworkRetries: 0,
49
+ httpClient: Stripe.createFetchHttpClient(async (input, init) => {
50
+ const url = new URL(String(input)),
51
+ path = url.pathname;
52
+ requests.push({ method: init?.method ?? "GET", path });
53
+ const result =
54
+ path === "/v1/account"
55
+ ? { id: "acct_platform" }
56
+ : path === "/v1/balance"
57
+ ? { livemode: false }
58
+ : path === "/v1/billing/meters/mtr_calls"
59
+ ? {
60
+ id: "mtr_calls",
61
+ livemode: false,
62
+ status: "active",
63
+ event_name: "calls",
64
+ default_aggregation: { formula: "sum" },
65
+ customer_mapping: {
66
+ type: "by_id",
67
+ event_payload_key: "stripe_customer_id",
68
+ },
69
+ value_settings: { event_payload_key: "value" },
70
+ event_time_window: null,
71
+ }
72
+ : path === "/v1/subscriptions/sub_calls"
73
+ ? {
74
+ id: "sub_calls",
75
+ livemode: false,
76
+ customer: "cus_buyer",
77
+ customer_account: "acct_buyer",
78
+ }
79
+ : {
80
+ id: "in_one",
81
+ object: "invoice",
82
+ livemode: false,
83
+ customer_account: wrongPayer ? "acct_other" : "acct_buyer",
84
+ customer: "cus_buyer",
85
+ currency: "usd",
86
+ status: path.endsWith("create_preview") ? "draft" : "paid",
87
+ status_transitions: {
88
+ finalized_at: path.endsWith("create_preview")
89
+ ? null
90
+ : 1200,
91
+ },
92
+ amount_due: 20,
93
+ amount_paid: 20,
94
+ total: 20,
95
+ parent: {
96
+ subscription_details: { subscription: "sub_calls" },
97
+ },
98
+ lines: {
99
+ data: [
100
+ {
101
+ id: "il_one",
102
+ object: "line_item",
103
+ currency: "usd",
104
+ amount: 10,
105
+ quantity: 2,
106
+ quantity_decimal: missingQuantity ? null : "2.5",
107
+ pricing: {
108
+ type: "price_details",
109
+ price_details: { price: "price_calls" },
110
+ unit_amount_decimal: null,
111
+ },
112
+ parent: {
113
+ subscription_item_details: {
114
+ subscription: "sub_calls",
115
+ subscription_item: "si_calls",
116
+ proration: false,
117
+ },
118
+ },
119
+ period,
120
+ pretax_credit_amounts: [],
121
+ },
122
+ ],
123
+ has_more: hasMore,
124
+ },
125
+ };
126
+ return new Response(JSON.stringify(result), {
127
+ status: 200,
128
+ headers: { "content-type": "application/json" },
129
+ });
130
+ }),
131
+ });
132
+ return { stripe, requests };
133
+ }
134
+ it("distinguishes full invoice amounts and matching metered lines with decimal quantities", async () => {
135
+ const f = setup(),
136
+ result = await observeUsageInvoice(f.stripe, options, "in_one");
137
+ expect(result).toMatchObject({
138
+ status: "available",
139
+ value: {
140
+ kind: "invoice",
141
+ invoiceId: "in_one",
142
+ finalized: true,
143
+ amountDue: "20",
144
+ amountPaid: "20",
145
+ total: "20",
146
+ meterAmount: {
147
+ status: "available",
148
+ value: { amount: "10", currency: "usd" },
149
+ },
150
+ lines: [{ quantity: "2.5", unitAmountDecimal: null }],
151
+ },
152
+ });
153
+ expect(() => convexToJson(result)).not.toThrow();
154
+ expect(f.requests.every((r) => r.method === "GET")).toBe(true);
155
+ });
156
+ it("does not call a preview finalized or an incomplete line page a complete meter amount", async () => {
157
+ const f = setup(true),
158
+ result = await observeUsageInvoice(f.stripe, options);
159
+ expect(result).toMatchObject({
160
+ status: "available",
161
+ value: {
162
+ kind: "preview",
163
+ finalized: false,
164
+ linesComplete: false,
165
+ meterAmount: {
166
+ status: "unavailable",
167
+ reason: "invoice_history_incomplete",
168
+ },
169
+ },
170
+ });
171
+ expect(f.requests.filter((r) => r.method === "POST")).toEqual([
172
+ { method: "POST", path: "/v1/invoices/create_preview" },
173
+ ]);
174
+ });
175
+ it("rejects another payer's invoice", async () => {
176
+ expect(
177
+ await observeUsageInvoice(setup(false, true).stripe, options, "in_one"),
178
+ ).toMatchObject({
179
+ status: "unsupported",
180
+ reason: "invoice_binding_mismatch",
181
+ });
182
+ });
183
+
184
+ it("does not treat the legacy truncated invoice quantity as full precision", async () => {
185
+ expect(
186
+ await observeUsageInvoice(
187
+ setup(false, false, true).stripe,
188
+ options,
189
+ "in_one",
190
+ ),
191
+ ).toMatchObject({
192
+ status: "available",
193
+ value: { lines: [{ quantity: null, providerQuantityDecimal: null }] },
194
+ });
195
+ });
@@ -0,0 +1,203 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import {
4
+ observationOptions,
5
+ verifyObservationSource,
6
+ type UsageObservationOptions,
7
+ } from "./observationTypes.js";
8
+ import type { UsageAvailability } from "./boundaries.js";
9
+ import { UsageCatalogError } from "./catalogTypes.js";
10
+ import { decimalFromScaled } from "./summary.js";
11
+ export type UsageInvoiceLine = {
12
+ lineId: string;
13
+ stripePriceId: string;
14
+ subscriptionItemId: string;
15
+ amount: string;
16
+ currency: string;
17
+ quantity: string | null;
18
+ providerQuantityDecimal: string | null;
19
+ unitAmountDecimal: string | null;
20
+ creditAppliedAmount: string;
21
+ nativePeriod: { start: number; end: number };
22
+ proration: boolean;
23
+ };
24
+ export type UsageInvoiceObservation = {
25
+ kind: "preview" | "invoice";
26
+ invoiceId: string;
27
+ status: "draft" | "open" | "paid" | "void" | "uncollectible";
28
+ finalized: boolean;
29
+ amountDue: string;
30
+ amountPaid: string;
31
+ total: string;
32
+ currency: string;
33
+ linesComplete: boolean;
34
+ lines: UsageInvoiceLine[];
35
+ meterAmount: UsageAvailability<{ amount: string; currency: string }>;
36
+ paymentEvidence: "not_resolved";
37
+ };
38
+ const idOf = (value: string | { id: string } | null | undefined) =>
39
+ typeof value === "string" ? value : value?.id;
40
+ function amount(value: number): string {
41
+ if (!Number.isSafeInteger(value)) throw new Error("Unsafe native amount");
42
+ return String(value);
43
+ }
44
+ function decimal(value: Stripe.Decimal | null | undefined): string | null {
45
+ if (value == null) return null;
46
+ const text = value.toString();
47
+ if (!/^\d+(\.\d{1,12})?$/.test(text) || text.length > 64)
48
+ throw new Error("Unsupported native decimal");
49
+ return text;
50
+ }
51
+ export async function observeUsageInvoice(
52
+ stripe: Stripe,
53
+ input: UsageObservationOptions,
54
+ invoiceId?: string,
55
+ ): Promise<UsageAvailability<UsageInvoiceObservation>> {
56
+ const opts = observationOptions(input),
57
+ observedAt = Math.floor(Date.now() / 1000);
58
+ if (invoiceId !== undefined)
59
+ z.string()
60
+ .regex(/^in_[a-zA-Z0-9]+$/)
61
+ .max(100)
62
+ .parse(invoiceId);
63
+ try {
64
+ if (!(await verifyObservationSource(stripe, opts)))
65
+ return {
66
+ status: "unsupported",
67
+ reason: "provider_binding_mismatch",
68
+ retryable: false,
69
+ };
70
+ const invoice = invoiceId
71
+ ? await stripe.invoices.retrieve(invoiceId)
72
+ : await stripe.invoices.createPreview({
73
+ subscription: opts.subscription.subscriptionId,
74
+ customer_account: opts.scope.customerAccount,
75
+ });
76
+ const status = z
77
+ .enum(["draft", "open", "paid", "void", "uncollectible"])
78
+ .safeParse(invoice.status);
79
+ if (
80
+ !status.success ||
81
+ !invoice.id ||
82
+ invoice.id.length > 100 ||
83
+ (invoiceId && invoice.id !== invoiceId) ||
84
+ invoice.livemode !== opts.scope.livemode ||
85
+ invoice.customer_account !== opts.scope.customerAccount ||
86
+ idOf(invoice.customer) !== opts.binding.stripeCustomerId ||
87
+ idOf(invoice.parent?.subscription_details?.subscription) !==
88
+ opts.subscription.subscriptionId ||
89
+ invoice.currency !== opts.binding.plan.rate.currency
90
+ )
91
+ return {
92
+ status: "unsupported",
93
+ reason: "invoice_binding_mismatch",
94
+ retryable: false,
95
+ };
96
+ const lines: UsageInvoiceLine[] = [];
97
+ let ambiguous = false;
98
+ const linesComplete =
99
+ !invoice.lines.has_more && invoice.lines.data.length <= 100;
100
+ for (const line of invoice.lines.data.slice(0, 100)) {
101
+ if (line.pricing?.price_details?.price !== opts.binding.stripePriceId)
102
+ continue;
103
+ const parent = line.parent?.subscription_item_details;
104
+ if (
105
+ parent?.subscription !== opts.subscription.subscriptionId ||
106
+ parent.subscription_item !== opts.subscription.subscriptionItemId ||
107
+ line.currency !== invoice.currency
108
+ ) {
109
+ ambiguous = true;
110
+ continue;
111
+ }
112
+ const providerQuantity = decimal(line.quantity_decimal);
113
+ let quantity: string | null = null;
114
+ if (providerQuantity !== null) {
115
+ const [whole, fraction = ""] = providerQuantity.split(".");
116
+ quantity = decimalFromScaled(
117
+ BigInt(whole + fraction),
118
+ fraction.length + opts.binding.plan.unit.precision,
119
+ );
120
+ }
121
+ const creditApplied = (line.pretax_credit_amounts ?? [])
122
+ .filter((value) => value.type === "credit_balance_transaction")
123
+ .reduce((sum, value) => sum + BigInt(amount(value.amount)), 0n);
124
+ lines.push({
125
+ lineId: line.id,
126
+ stripePriceId: opts.binding.stripePriceId,
127
+ subscriptionItemId: parent.subscription_item,
128
+ amount: amount(line.amount),
129
+ currency: line.currency,
130
+ quantity,
131
+ providerQuantityDecimal: providerQuantity,
132
+ unitAmountDecimal: decimal(line.pricing.unit_amount_decimal),
133
+ creditAppliedAmount: creditApplied.toString(),
134
+ nativePeriod: { start: line.period.start, end: line.period.end },
135
+ proration: parent.proration,
136
+ });
137
+ }
138
+ const meterAmount: UsageInvoiceObservation["meterAmount"] = !linesComplete
139
+ ? {
140
+ status: "unavailable",
141
+ reason: "invoice_history_incomplete",
142
+ retryable: true,
143
+ }
144
+ : ambiguous
145
+ ? {
146
+ status: "unavailable",
147
+ reason: "ambiguous_invoice_items",
148
+ retryable: false,
149
+ }
150
+ : !lines.length
151
+ ? {
152
+ status: "unavailable",
153
+ reason: "metered_lines_not_observed",
154
+ retryable: true,
155
+ }
156
+ : {
157
+ status: "available",
158
+ observedAt,
159
+ value: {
160
+ amount: lines
161
+ .reduce((sum, line) => sum + BigInt(line.amount), 0n)
162
+ .toString(),
163
+ currency: invoice.currency,
164
+ },
165
+ };
166
+ return {
167
+ status: "available",
168
+ observedAt,
169
+ value: {
170
+ kind: invoiceId ? "invoice" : "preview",
171
+ invoiceId: invoice.id,
172
+ status: status.data,
173
+ finalized:
174
+ invoiceId !== undefined &&
175
+ invoice.status !== "draft" &&
176
+ Number.isSafeInteger(invoice.status_transitions?.finalized_at),
177
+ amountDue: amount(invoice.amount_due),
178
+ amountPaid: amount(invoice.amount_paid),
179
+ total: amount(invoice.total),
180
+ currency: invoice.currency,
181
+ linesComplete,
182
+ lines,
183
+ meterAmount,
184
+ paymentEvidence: "not_resolved",
185
+ },
186
+ };
187
+ } catch (error) {
188
+ if (
189
+ error instanceof UsageCatalogError &&
190
+ error.code === "unsupported_scope"
191
+ )
192
+ return {
193
+ status: "unsupported",
194
+ reason: "unsupported_scope",
195
+ retryable: false,
196
+ };
197
+ return {
198
+ status: "unavailable",
199
+ reason: "invoice_unavailable",
200
+ retryable: true,
201
+ };
202
+ }
203
+ }