@fantastic.dev/better-stripe 0.4.0-bootstrap.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 (762) hide show
  1. package/CHANGELOG.md +318 -0
  2. package/README.md +1117 -0
  3. package/dist/client/billing/checkout.d.ts +75 -0
  4. package/dist/client/billing/checkout.d.ts.map +1 -0
  5. package/dist/client/billing/checkout.js +260 -0
  6. package/dist/client/billing/checkout.js.map +1 -0
  7. package/dist/client/billing/invoices.d.ts +37 -0
  8. package/dist/client/billing/invoices.d.ts.map +1 -0
  9. package/dist/client/billing/invoices.js +29 -0
  10. package/dist/client/billing/invoices.js.map +1 -0
  11. package/dist/client/billing/subscriptions.d.ts +179 -0
  12. package/dist/client/billing/subscriptions.d.ts.map +1 -0
  13. package/dist/client/billing/subscriptions.js +346 -0
  14. package/dist/client/billing/subscriptions.js.map +1 -0
  15. package/dist/client/connect/disputes.d.ts +112 -0
  16. package/dist/client/connect/disputes.d.ts.map +1 -0
  17. package/dist/client/connect/disputes.js +186 -0
  18. package/dist/client/connect/disputes.js.map +1 -0
  19. package/dist/client/connect/paymentMethodUtils.d.ts +17 -0
  20. package/dist/client/connect/paymentMethodUtils.d.ts.map +1 -0
  21. package/dist/client/connect/paymentMethodUtils.js +24 -0
  22. package/dist/client/connect/paymentMethodUtils.js.map +1 -0
  23. package/dist/client/connect/paymentMethods.d.ts +23 -0
  24. package/dist/client/connect/paymentMethods.d.ts.map +1 -0
  25. package/dist/client/connect/paymentMethods.js +27 -0
  26. package/dist/client/connect/paymentMethods.js.map +1 -0
  27. package/dist/client/connect/payouts.d.ts +47 -0
  28. package/dist/client/connect/payouts.d.ts.map +1 -0
  29. package/dist/client/connect/payouts.js +52 -0
  30. package/dist/client/connect/payouts.js.map +1 -0
  31. package/dist/client/connect/refundActor.d.ts +50 -0
  32. package/dist/client/connect/refundActor.d.ts.map +1 -0
  33. package/dist/client/connect/refundActor.js +17 -0
  34. package/dist/client/connect/refundActor.js.map +1 -0
  35. package/dist/client/connect/refunds.d.ts +75 -0
  36. package/dist/client/connect/refunds.d.ts.map +1 -0
  37. package/dist/client/connect/refunds.js +141 -0
  38. package/dist/client/connect/refunds.js.map +1 -0
  39. package/dist/client/connect/transfers.d.ts +189 -0
  40. package/dist/client/connect/transfers.d.ts.map +1 -0
  41. package/dist/client/connect/transfers.js +347 -0
  42. package/dist/client/connect/transfers.js.map +1 -0
  43. package/dist/client/constants.d.ts +15 -0
  44. package/dist/client/constants.d.ts.map +1 -0
  45. package/dist/client/constants.js +14 -0
  46. package/dist/client/constants.js.map +1 -0
  47. package/dist/client/core/accountLinks.d.ts +68 -0
  48. package/dist/client/core/accountLinks.d.ts.map +1 -0
  49. package/dist/client/core/accountLinks.js +131 -0
  50. package/dist/client/core/accountLinks.js.map +1 -0
  51. package/dist/client/core/accountStatus.d.ts +12 -0
  52. package/dist/client/core/accountStatus.d.ts.map +1 -0
  53. package/dist/client/core/accountStatus.js +56 -0
  54. package/dist/client/core/accountStatus.js.map +1 -0
  55. package/dist/client/core/accounts.d.ts +181 -0
  56. package/dist/client/core/accounts.d.ts.map +1 -0
  57. package/dist/client/core/accounts.js +359 -0
  58. package/dist/client/core/accounts.js.map +1 -0
  59. package/dist/client/core/config.d.ts +5 -0
  60. package/dist/client/core/config.d.ts.map +1 -0
  61. package/dist/client/core/config.js +11 -0
  62. package/dist/client/core/config.js.map +1 -0
  63. package/dist/client/core/descriptors.d.ts +24 -0
  64. package/dist/client/core/descriptors.d.ts.map +1 -0
  65. package/dist/client/core/descriptors.js +43 -0
  66. package/dist/client/core/descriptors.js.map +1 -0
  67. package/dist/client/core/fees.d.ts +83 -0
  68. package/dist/client/core/fees.d.ts.map +1 -0
  69. package/dist/client/core/fees.js +178 -0
  70. package/dist/client/core/fees.js.map +1 -0
  71. package/dist/client/errors.d.ts +20 -0
  72. package/dist/client/errors.d.ts.map +1 -0
  73. package/dist/client/errors.js +31 -0
  74. package/dist/client/errors.js.map +1 -0
  75. package/dist/client/helpers.d.ts +20 -0
  76. package/dist/client/helpers.d.ts.map +1 -0
  77. package/dist/client/helpers.js +46 -0
  78. package/dist/client/helpers.js.map +1 -0
  79. package/dist/client/index.d.ts +880 -0
  80. package/dist/client/index.d.ts.map +1 -0
  81. package/dist/client/index.js +791 -0
  82. package/dist/client/index.js.map +1 -0
  83. package/dist/client/products/prices.d.ts +61 -0
  84. package/dist/client/products/prices.d.ts.map +1 -0
  85. package/dist/client/products/prices.js +92 -0
  86. package/dist/client/products/prices.js.map +1 -0
  87. package/dist/client/products/products.d.ts +65 -0
  88. package/dist/client/products/products.d.ts.map +1 -0
  89. package/dist/client/products/products.js +186 -0
  90. package/dist/client/products/products.js.map +1 -0
  91. package/dist/client/stripe-types.d.ts +44 -0
  92. package/dist/client/stripe-types.d.ts.map +1 -0
  93. package/dist/client/stripe-types.js +2 -0
  94. package/dist/client/stripe-types.js.map +1 -0
  95. package/dist/client/types/documents.d.ts +195 -0
  96. package/dist/client/types/documents.d.ts.map +1 -0
  97. package/dist/client/types/documents.js +2 -0
  98. package/dist/client/types/documents.js.map +1 -0
  99. package/dist/client/types/events.d.ts +43 -0
  100. package/dist/client/types/events.d.ts.map +1 -0
  101. package/dist/client/types/events.js +2 -0
  102. package/dist/client/types/events.js.map +1 -0
  103. package/dist/client/types/index.d.ts +5 -0
  104. package/dist/client/types/index.d.ts.map +1 -0
  105. package/dist/client/types/index.js +2 -0
  106. package/dist/client/types/index.js.map +1 -0
  107. package/dist/client/types/options.d.ts +79 -0
  108. package/dist/client/types/options.d.ts.map +1 -0
  109. package/dist/client/types/options.js +2 -0
  110. package/dist/client/types/options.js.map +1 -0
  111. package/dist/client/types/triggers.d.ts +101 -0
  112. package/dist/client/types/triggers.d.ts.map +1 -0
  113. package/dist/client/types/triggers.js +2 -0
  114. package/dist/client/types/triggers.js.map +1 -0
  115. package/dist/client/types.d.ts +2 -0
  116. package/dist/client/types.d.ts.map +1 -0
  117. package/dist/client/types.js +2 -0
  118. package/dist/client/types.js.map +1 -0
  119. package/dist/client/utils/data.d.ts +10 -0
  120. package/dist/client/utils/data.d.ts.map +1 -0
  121. package/dist/client/utils/data.js +13 -0
  122. package/dist/client/utils/data.js.map +1 -0
  123. package/dist/client/utils/owner.d.ts +22 -0
  124. package/dist/client/utils/owner.d.ts.map +1 -0
  125. package/dist/client/utils/owner.js +20 -0
  126. package/dist/client/utils/owner.js.map +1 -0
  127. package/dist/client/utils/stripeDashboardUrl.d.ts +12 -0
  128. package/dist/client/utils/stripeDashboardUrl.d.ts.map +1 -0
  129. package/dist/client/utils/stripeDashboardUrl.js +39 -0
  130. package/dist/client/utils/stripeDashboardUrl.js.map +1 -0
  131. package/dist/client/utils/webhookEndpoints.d.ts +83 -0
  132. package/dist/client/utils/webhookEndpoints.d.ts.map +1 -0
  133. package/dist/client/utils/webhookEndpoints.js +185 -0
  134. package/dist/client/utils/webhookEndpoints.js.map +1 -0
  135. package/dist/client/webhooks/handler.d.ts +4 -0
  136. package/dist/client/webhooks/handler.d.ts.map +1 -0
  137. package/dist/client/webhooks/handler.js +170 -0
  138. package/dist/client/webhooks/handler.js.map +1 -0
  139. package/dist/client/webhooks/helpers.d.ts +56 -0
  140. package/dist/client/webhooks/helpers.d.ts.map +1 -0
  141. package/dist/client/webhooks/helpers.js +229 -0
  142. package/dist/client/webhooks/helpers.js.map +1 -0
  143. package/dist/client/webhooks/hooks.d.ts +11 -0
  144. package/dist/client/webhooks/hooks.d.ts.map +1 -0
  145. package/dist/client/webhooks/hooks.js +134 -0
  146. package/dist/client/webhooks/hooks.js.map +1 -0
  147. package/dist/client/webhooks/index.d.ts +23 -0
  148. package/dist/client/webhooks/index.d.ts.map +1 -0
  149. package/dist/client/webhooks/index.js +35 -0
  150. package/dist/client/webhooks/index.js.map +1 -0
  151. package/dist/client/webhooks/processors.d.ts +4 -0
  152. package/dist/client/webhooks/processors.d.ts.map +1 -0
  153. package/dist/client/webhooks/processors.js +932 -0
  154. package/dist/client/webhooks/processors.js.map +1 -0
  155. package/dist/client/webhooks/v2.d.ts +11 -0
  156. package/dist/client/webhooks/v2.d.ts.map +1 -0
  157. package/dist/client/webhooks/v2.js +94 -0
  158. package/dist/client/webhooks/v2.js.map +1 -0
  159. package/dist/client/webhooks.d.ts +2 -0
  160. package/dist/client/webhooks.d.ts.map +1 -0
  161. package/dist/client/webhooks.js +4 -0
  162. package/dist/client/webhooks.js.map +1 -0
  163. package/dist/component/_generated/component.d.ts +1262 -0
  164. package/dist/component/_generated/component.d.ts.map +1 -0
  165. package/dist/component/_generated/component.js +11 -0
  166. package/dist/component/_generated/component.js.map +1 -0
  167. package/dist/component/_generated/dataModel.d.ts +46 -0
  168. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  169. package/dist/component/_generated/dataModel.js +11 -0
  170. package/dist/component/_generated/dataModel.js.map +1 -0
  171. package/dist/component/_generated/server.d.ts +129 -0
  172. package/dist/component/_generated/server.d.ts.map +1 -0
  173. package/dist/component/_generated/server.js +79 -0
  174. package/dist/component/_generated/server.js.map +1 -0
  175. package/dist/component/billing/mutations.d.ts +86 -0
  176. package/dist/component/billing/mutations.d.ts.map +1 -0
  177. package/dist/component/billing/mutations.js +131 -0
  178. package/dist/component/billing/mutations.js.map +1 -0
  179. package/dist/component/billing/queries.d.ts +425 -0
  180. package/dist/component/billing/queries.d.ts.map +1 -0
  181. package/dist/component/billing/queries.js +304 -0
  182. package/dist/component/billing/queries.js.map +1 -0
  183. package/dist/component/billing/schema.d.ts +228 -0
  184. package/dist/component/billing/schema.d.ts.map +1 -0
  185. package/dist/component/billing/schema.js +33 -0
  186. package/dist/component/billing/schema.js.map +1 -0
  187. package/dist/component/billing/validators.d.ts +364 -0
  188. package/dist/component/billing/validators.d.ts.map +1 -0
  189. package/dist/component/billing/validators.js +98 -0
  190. package/dist/component/billing/validators.js.map +1 -0
  191. package/dist/component/connect/mutations.d.ts +182 -0
  192. package/dist/component/connect/mutations.d.ts.map +1 -0
  193. package/dist/component/connect/mutations.js +480 -0
  194. package/dist/component/connect/mutations.js.map +1 -0
  195. package/dist/component/connect/queries.d.ts +347 -0
  196. package/dist/component/connect/queries.d.ts.map +1 -0
  197. package/dist/component/connect/queries.js +449 -0
  198. package/dist/component/connect/queries.js.map +1 -0
  199. package/dist/component/connect/schema.d.ts +258 -0
  200. package/dist/component/connect/schema.d.ts.map +1 -0
  201. package/dist/component/connect/schema.js +70 -0
  202. package/dist/component/connect/schema.js.map +1 -0
  203. package/dist/component/connect/validators.d.ts +468 -0
  204. package/dist/component/connect/validators.d.ts.map +1 -0
  205. package/dist/component/connect/validators.js +250 -0
  206. package/dist/component/connect/validators.js.map +1 -0
  207. package/dist/component/convex.config.d.ts +5 -0
  208. package/dist/component/convex.config.d.ts.map +1 -0
  209. package/dist/component/convex.config.js +17 -0
  210. package/dist/component/convex.config.js.map +1 -0
  211. package/dist/component/core/mutations.d.ts +52 -0
  212. package/dist/component/core/mutations.d.ts.map +1 -0
  213. package/dist/component/core/mutations.js +153 -0
  214. package/dist/component/core/mutations.js.map +1 -0
  215. package/dist/component/core/queries.d.ts +95 -0
  216. package/dist/component/core/queries.d.ts.map +1 -0
  217. package/dist/component/core/queries.js +86 -0
  218. package/dist/component/core/queries.js.map +1 -0
  219. package/dist/component/core/schema.d.ts +41 -0
  220. package/dist/component/core/schema.d.ts.map +1 -0
  221. package/dist/component/core/schema.js +12 -0
  222. package/dist/component/core/schema.js.map +1 -0
  223. package/dist/component/core/validators.d.ts +65 -0
  224. package/dist/component/core/validators.d.ts.map +1 -0
  225. package/dist/component/core/validators.js +35 -0
  226. package/dist/component/core/validators.js.map +1 -0
  227. package/dist/component/lib/fees.d.ts +74 -0
  228. package/dist/component/lib/fees.d.ts.map +1 -0
  229. package/dist/component/lib/fees.js +51 -0
  230. package/dist/component/lib/fees.js.map +1 -0
  231. package/dist/component/lib/idempotency.d.ts +9 -0
  232. package/dist/component/lib/idempotency.d.ts.map +1 -0
  233. package/dist/component/lib/idempotency.js +18 -0
  234. package/dist/component/lib/idempotency.js.map +1 -0
  235. package/dist/component/lib/reversals.d.ts +48 -0
  236. package/dist/component/lib/reversals.d.ts.map +1 -0
  237. package/dist/component/lib/reversals.js +79 -0
  238. package/dist/component/lib/reversals.js.map +1 -0
  239. package/dist/component/lib/stripeFactory.d.ts +7 -0
  240. package/dist/component/lib/stripeFactory.d.ts.map +1 -0
  241. package/dist/component/lib/stripeFactory.js +28 -0
  242. package/dist/component/lib/stripeFactory.js.map +1 -0
  243. package/dist/component/products/mutations.d.ts +22 -0
  244. package/dist/component/products/mutations.d.ts.map +1 -0
  245. package/dist/component/products/mutations.js +63 -0
  246. package/dist/component/products/mutations.js.map +1 -0
  247. package/dist/component/products/queries.d.ts +109 -0
  248. package/dist/component/products/queries.d.ts.map +1 -0
  249. package/dist/component/products/queries.js +122 -0
  250. package/dist/component/products/queries.js.map +1 -0
  251. package/dist/component/products/schema.d.ts +58 -0
  252. package/dist/component/products/schema.d.ts.map +1 -0
  253. package/dist/component/products/schema.js +20 -0
  254. package/dist/component/products/schema.js.map +1 -0
  255. package/dist/component/products/validators.d.ts +86 -0
  256. package/dist/component/products/validators.d.ts.map +1 -0
  257. package/dist/component/products/validators.js +47 -0
  258. package/dist/component/products/validators.js.map +1 -0
  259. package/dist/component/schema.d.ts +555 -0
  260. package/dist/component/schema.d.ts.map +1 -0
  261. package/dist/component/schema.js +28 -0
  262. package/dist/component/schema.js.map +1 -0
  263. package/dist/component/webhooks/mutations.d.ts +30 -0
  264. package/dist/component/webhooks/mutations.d.ts.map +1 -0
  265. package/dist/component/webhooks/mutations.js +124 -0
  266. package/dist/component/webhooks/mutations.js.map +1 -0
  267. package/dist/component/webhooks/queries.d.ts +35 -0
  268. package/dist/component/webhooks/queries.d.ts.map +1 -0
  269. package/dist/component/webhooks/queries.js +41 -0
  270. package/dist/component/webhooks/queries.js.map +1 -0
  271. package/dist/component/webhooks/schema.d.ts +22 -0
  272. package/dist/component/webhooks/schema.d.ts.map +1 -0
  273. package/dist/component/webhooks/schema.js +9 -0
  274. package/dist/component/webhooks/schema.js.map +1 -0
  275. package/dist/component/webhooks/validators.d.ts +37 -0
  276. package/dist/component/webhooks/validators.d.ts.map +1 -0
  277. package/dist/component/webhooks/validators.js +22 -0
  278. package/dist/component/webhooks/validators.js.map +1 -0
  279. package/dist/react/components/AccountCloseButton.d.ts +42 -0
  280. package/dist/react/components/AccountCloseButton.d.ts.map +1 -0
  281. package/dist/react/components/AccountCloseButton.js +33 -0
  282. package/dist/react/components/AccountCloseButton.js.map +1 -0
  283. package/dist/react/components/AccountCloseCard.d.ts +31 -0
  284. package/dist/react/components/AccountCloseCard.d.ts.map +1 -0
  285. package/dist/react/components/AccountCloseCard.js +22 -0
  286. package/dist/react/components/AccountCloseCard.js.map +1 -0
  287. package/dist/react/components/AccountCreateButton.d.ts +37 -0
  288. package/dist/react/components/AccountCreateButton.d.ts.map +1 -0
  289. package/dist/react/components/AccountCreateButton.js +30 -0
  290. package/dist/react/components/AccountCreateButton.js.map +1 -0
  291. package/dist/react/components/AccountCreateCard.d.ts +48 -0
  292. package/dist/react/components/AccountCreateCard.d.ts.map +1 -0
  293. package/dist/react/components/AccountCreateCard.js +29 -0
  294. package/dist/react/components/AccountCreateCard.js.map +1 -0
  295. package/dist/react/components/AccountLoginButton.d.ts +31 -0
  296. package/dist/react/components/AccountLoginButton.d.ts.map +1 -0
  297. package/dist/react/components/AccountLoginButton.js +31 -0
  298. package/dist/react/components/AccountLoginButton.js.map +1 -0
  299. package/dist/react/components/AccountLoginCard.d.ts +33 -0
  300. package/dist/react/components/AccountLoginCard.d.ts.map +1 -0
  301. package/dist/react/components/AccountLoginCard.js +19 -0
  302. package/dist/react/components/AccountLoginCard.js.map +1 -0
  303. package/dist/react/components/AccountOnboardingButton.d.ts +37 -0
  304. package/dist/react/components/AccountOnboardingButton.d.ts.map +1 -0
  305. package/dist/react/components/AccountOnboardingButton.js +30 -0
  306. package/dist/react/components/AccountOnboardingButton.js.map +1 -0
  307. package/dist/react/components/AccountOnboardingCard.d.ts +56 -0
  308. package/dist/react/components/AccountOnboardingCard.d.ts.map +1 -0
  309. package/dist/react/components/AccountOnboardingCard.js +36 -0
  310. package/dist/react/components/AccountOnboardingCard.js.map +1 -0
  311. package/dist/react/components/AddCardForm.d.ts +18 -0
  312. package/dist/react/components/AddCardForm.d.ts.map +1 -0
  313. package/dist/react/components/AddCardForm.js +49 -0
  314. package/dist/react/components/AddCardForm.js.map +1 -0
  315. package/dist/react/components/BillingPortalLink.d.ts +23 -0
  316. package/dist/react/components/BillingPortalLink.d.ts.map +1 -0
  317. package/dist/react/components/BillingPortalLink.js +55 -0
  318. package/dist/react/components/BillingPortalLink.js.map +1 -0
  319. package/dist/react/components/BuyerBillingView.d.ts +80 -0
  320. package/dist/react/components/BuyerBillingView.d.ts.map +1 -0
  321. package/dist/react/components/BuyerBillingView.js +44 -0
  322. package/dist/react/components/BuyerBillingView.js.map +1 -0
  323. package/dist/react/components/CheckoutSessionProvider.d.ts +34 -0
  324. package/dist/react/components/CheckoutSessionProvider.d.ts.map +1 -0
  325. package/dist/react/components/CheckoutSessionProvider.js +38 -0
  326. package/dist/react/components/CheckoutSessionProvider.js.map +1 -0
  327. package/dist/react/components/CheckoutSessionProviderWithKey.d.ts +36 -0
  328. package/dist/react/components/CheckoutSessionProviderWithKey.d.ts.map +1 -0
  329. package/dist/react/components/CheckoutSessionProviderWithKey.js +36 -0
  330. package/dist/react/components/CheckoutSessionProviderWithKey.js.map +1 -0
  331. package/dist/react/components/CheckoutStatus.d.ts +25 -0
  332. package/dist/react/components/CheckoutStatus.d.ts.map +1 -0
  333. package/dist/react/components/CheckoutStatus.js +22 -0
  334. package/dist/react/components/CheckoutStatus.js.map +1 -0
  335. package/dist/react/components/ConnectProvider.d.ts +29 -0
  336. package/dist/react/components/ConnectProvider.d.ts.map +1 -0
  337. package/dist/react/components/ConnectProvider.js +25 -0
  338. package/dist/react/components/ConnectProvider.js.map +1 -0
  339. package/dist/react/components/ConnectRequirements.d.ts +55 -0
  340. package/dist/react/components/ConnectRequirements.d.ts.map +1 -0
  341. package/dist/react/components/ConnectRequirements.js +58 -0
  342. package/dist/react/components/ConnectRequirements.js.map +1 -0
  343. package/dist/react/components/ConnectStatusBadge.d.ts +26 -0
  344. package/dist/react/components/ConnectStatusBadge.d.ts.map +1 -0
  345. package/dist/react/components/ConnectStatusBadge.js +20 -0
  346. package/dist/react/components/ConnectStatusBadge.js.map +1 -0
  347. package/dist/react/components/DeletePaymentMethodDialog.d.ts +25 -0
  348. package/dist/react/components/DeletePaymentMethodDialog.d.ts.map +1 -0
  349. package/dist/react/components/DeletePaymentMethodDialog.js +16 -0
  350. package/dist/react/components/DeletePaymentMethodDialog.js.map +1 -0
  351. package/dist/react/components/DisputeDetail.d.ts +42 -0
  352. package/dist/react/components/DisputeDetail.d.ts.map +1 -0
  353. package/dist/react/components/DisputeDetail.js +34 -0
  354. package/dist/react/components/DisputeDetail.js.map +1 -0
  355. package/dist/react/components/DisputesList.d.ts +42 -0
  356. package/dist/react/components/DisputesList.d.ts.map +1 -0
  357. package/dist/react/components/DisputesList.js +47 -0
  358. package/dist/react/components/DisputesList.js.map +1 -0
  359. package/dist/react/components/EarningsSummary.d.ts +53 -0
  360. package/dist/react/components/EarningsSummary.d.ts.map +1 -0
  361. package/dist/react/components/EarningsSummary.js +37 -0
  362. package/dist/react/components/EarningsSummary.js.map +1 -0
  363. package/dist/react/components/EmbeddedCheckout.d.ts +18 -0
  364. package/dist/react/components/EmbeddedCheckout.d.ts.map +1 -0
  365. package/dist/react/components/EmbeddedCheckout.js +17 -0
  366. package/dist/react/components/EmbeddedCheckout.js.map +1 -0
  367. package/dist/react/components/EmbeddedDisputes.d.ts +21 -0
  368. package/dist/react/components/EmbeddedDisputes.d.ts.map +1 -0
  369. package/dist/react/components/EmbeddedDisputes.js +17 -0
  370. package/dist/react/components/EmbeddedDisputes.js.map +1 -0
  371. package/dist/react/components/EvidenceForm.d.ts +63 -0
  372. package/dist/react/components/EvidenceForm.d.ts.map +1 -0
  373. package/dist/react/components/EvidenceForm.js +79 -0
  374. package/dist/react/components/EvidenceForm.js.map +1 -0
  375. package/dist/react/components/IntervalSelector.d.ts +20 -0
  376. package/dist/react/components/IntervalSelector.d.ts.map +1 -0
  377. package/dist/react/components/IntervalSelector.js +15 -0
  378. package/dist/react/components/IntervalSelector.js.map +1 -0
  379. package/dist/react/components/PaymentMethodActions.d.ts +27 -0
  380. package/dist/react/components/PaymentMethodActions.d.ts.map +1 -0
  381. package/dist/react/components/PaymentMethodActions.js +23 -0
  382. package/dist/react/components/PaymentMethodActions.js.map +1 -0
  383. package/dist/react/components/PaymentMethodsList.d.ts +32 -0
  384. package/dist/react/components/PaymentMethodsList.d.ts.map +1 -0
  385. package/dist/react/components/PaymentMethodsList.js +18 -0
  386. package/dist/react/components/PaymentMethodsList.js.map +1 -0
  387. package/dist/react/components/PayoutSchedule.d.ts +55 -0
  388. package/dist/react/components/PayoutSchedule.d.ts.map +1 -0
  389. package/dist/react/components/PayoutSchedule.js +51 -0
  390. package/dist/react/components/PayoutSchedule.js.map +1 -0
  391. package/dist/react/components/PriceBadge.d.ts +19 -0
  392. package/dist/react/components/PriceBadge.d.ts.map +1 -0
  393. package/dist/react/components/PriceBadge.js +25 -0
  394. package/dist/react/components/PriceBadge.js.map +1 -0
  395. package/dist/react/components/PriceCard.d.ts +34 -0
  396. package/dist/react/components/PriceCard.d.ts.map +1 -0
  397. package/dist/react/components/PriceCard.js +20 -0
  398. package/dist/react/components/PriceCard.js.map +1 -0
  399. package/dist/react/components/PricePicker.d.ts +28 -0
  400. package/dist/react/components/PricePicker.d.ts.map +1 -0
  401. package/dist/react/components/PricePicker.js +32 -0
  402. package/dist/react/components/PricePicker.js.map +1 -0
  403. package/dist/react/components/SplitBreakdown.d.ts +45 -0
  404. package/dist/react/components/SplitBreakdown.d.ts.map +1 -0
  405. package/dist/react/components/SplitBreakdown.js +48 -0
  406. package/dist/react/components/SplitBreakdown.js.map +1 -0
  407. package/dist/react/components/StripeProvider.d.ts +30 -0
  408. package/dist/react/components/StripeProvider.d.ts.map +1 -0
  409. package/dist/react/components/StripeProvider.js +38 -0
  410. package/dist/react/components/StripeProvider.js.map +1 -0
  411. package/dist/react/components/StripeProviderWithKey.d.ts +33 -0
  412. package/dist/react/components/StripeProviderWithKey.d.ts.map +1 -0
  413. package/dist/react/components/StripeProviderWithKey.js +44 -0
  414. package/dist/react/components/StripeProviderWithKey.js.map +1 -0
  415. package/dist/react/components/SubscriptionActions.d.ts +31 -0
  416. package/dist/react/components/SubscriptionActions.d.ts.map +1 -0
  417. package/dist/react/components/SubscriptionActions.js +30 -0
  418. package/dist/react/components/SubscriptionActions.js.map +1 -0
  419. package/dist/react/components/SubscriptionCard.d.ts +41 -0
  420. package/dist/react/components/SubscriptionCard.d.ts.map +1 -0
  421. package/dist/react/components/SubscriptionCard.js +18 -0
  422. package/dist/react/components/SubscriptionCard.js.map +1 -0
  423. package/dist/react/components/SubscriptionLineItems.d.ts +23 -0
  424. package/dist/react/components/SubscriptionLineItems.d.ts.map +1 -0
  425. package/dist/react/components/SubscriptionLineItems.js +20 -0
  426. package/dist/react/components/SubscriptionLineItems.js.map +1 -0
  427. package/dist/react/components/TrialAlert.d.ts +19 -0
  428. package/dist/react/components/TrialAlert.d.ts.map +1 -0
  429. package/dist/react/components/TrialAlert.js +16 -0
  430. package/dist/react/components/TrialAlert.js.map +1 -0
  431. package/dist/react/hooks/useAccount.d.ts +14 -0
  432. package/dist/react/hooks/useAccount.d.ts.map +1 -0
  433. package/dist/react/hooks/useAccount.js +18 -0
  434. package/dist/react/hooks/useAccount.js.map +1 -0
  435. package/dist/react/hooks/useAccountOnboarding.d.ts +15 -0
  436. package/dist/react/hooks/useAccountOnboarding.d.ts.map +1 -0
  437. package/dist/react/hooks/useAccountOnboarding.js +19 -0
  438. package/dist/react/hooks/useAccountOnboarding.js.map +1 -0
  439. package/dist/react/hooks/useCheckout.d.ts +14 -0
  440. package/dist/react/hooks/useCheckout.d.ts.map +1 -0
  441. package/dist/react/hooks/useCheckout.js +18 -0
  442. package/dist/react/hooks/useCheckout.js.map +1 -0
  443. package/dist/react/hooks/useCheckoutSession.d.ts +62 -0
  444. package/dist/react/hooks/useCheckoutSession.d.ts.map +1 -0
  445. package/dist/react/hooks/useCheckoutSession.js +68 -0
  446. package/dist/react/hooks/useCheckoutSession.js.map +1 -0
  447. package/dist/react/hooks/useConfirmPayment.d.ts +38 -0
  448. package/dist/react/hooks/useConfirmPayment.d.ts.map +1 -0
  449. package/dist/react/hooks/useConfirmPayment.js +91 -0
  450. package/dist/react/hooks/useConfirmPayment.js.map +1 -0
  451. package/dist/react/hooks/useDisputeWithCountdown.d.ts +25 -0
  452. package/dist/react/hooks/useDisputeWithCountdown.d.ts.map +1 -0
  453. package/dist/react/hooks/useDisputeWithCountdown.js +19 -0
  454. package/dist/react/hooks/useDisputeWithCountdown.js.map +1 -0
  455. package/dist/react/hooks/useDisputes.d.ts +14 -0
  456. package/dist/react/hooks/useDisputes.d.ts.map +1 -0
  457. package/dist/react/hooks/useDisputes.js +15 -0
  458. package/dist/react/hooks/useDisputes.js.map +1 -0
  459. package/dist/react/hooks/useEarnings.d.ts +92 -0
  460. package/dist/react/hooks/useEarnings.d.ts.map +1 -0
  461. package/dist/react/hooks/useEarnings.js +35 -0
  462. package/dist/react/hooks/useEarnings.js.map +1 -0
  463. package/dist/react/hooks/useInvoices.d.ts +11 -0
  464. package/dist/react/hooks/useInvoices.d.ts.map +1 -0
  465. package/dist/react/hooks/useInvoices.js +11 -0
  466. package/dist/react/hooks/useInvoices.js.map +1 -0
  467. package/dist/react/hooks/usePaymentMethodActions.d.ts +74 -0
  468. package/dist/react/hooks/usePaymentMethodActions.d.ts.map +1 -0
  469. package/dist/react/hooks/usePaymentMethodActions.js +156 -0
  470. package/dist/react/hooks/usePaymentMethodActions.js.map +1 -0
  471. package/dist/react/hooks/usePaymentMethods.d.ts +23 -0
  472. package/dist/react/hooks/usePaymentMethods.d.ts.map +1 -0
  473. package/dist/react/hooks/usePaymentMethods.js +18 -0
  474. package/dist/react/hooks/usePaymentMethods.js.map +1 -0
  475. package/dist/react/hooks/usePrices.d.ts +12 -0
  476. package/dist/react/hooks/usePrices.d.ts.map +1 -0
  477. package/dist/react/hooks/usePrices.js +16 -0
  478. package/dist/react/hooks/usePrices.js.map +1 -0
  479. package/dist/react/hooks/useProducts.d.ts +10 -0
  480. package/dist/react/hooks/useProducts.d.ts.map +1 -0
  481. package/dist/react/hooks/useProducts.js +11 -0
  482. package/dist/react/hooks/useProducts.js.map +1 -0
  483. package/dist/react/hooks/useSplitBreakdown.d.ts +58 -0
  484. package/dist/react/hooks/useSplitBreakdown.d.ts.map +1 -0
  485. package/dist/react/hooks/useSplitBreakdown.js +59 -0
  486. package/dist/react/hooks/useSplitBreakdown.js.map +1 -0
  487. package/dist/react/hooks/useStripeConfig.d.ts +14 -0
  488. package/dist/react/hooks/useStripeConfig.d.ts.map +1 -0
  489. package/dist/react/hooks/useStripeConfig.js +21 -0
  490. package/dist/react/hooks/useStripeConfig.js.map +1 -0
  491. package/dist/react/hooks/useStripeMode.d.ts +3 -0
  492. package/dist/react/hooks/useStripeMode.d.ts.map +1 -0
  493. package/dist/react/hooks/useStripeMode.js +6 -0
  494. package/dist/react/hooks/useStripeMode.js.map +1 -0
  495. package/dist/react/hooks/useStripePublishableKey.d.ts +2 -0
  496. package/dist/react/hooks/useStripePublishableKey.d.ts.map +1 -0
  497. package/dist/react/hooks/useStripePublishableKey.js +6 -0
  498. package/dist/react/hooks/useStripePublishableKey.js.map +1 -0
  499. package/dist/react/hooks/useSubscription.d.ts +17 -0
  500. package/dist/react/hooks/useSubscription.d.ts.map +1 -0
  501. package/dist/react/hooks/useSubscription.js +30 -0
  502. package/dist/react/hooks/useSubscription.js.map +1 -0
  503. package/dist/react/hooks/useSubscriptions.d.ts +11 -0
  504. package/dist/react/hooks/useSubscriptions.d.ts.map +1 -0
  505. package/dist/react/hooks/useSubscriptions.js +13 -0
  506. package/dist/react/hooks/useSubscriptions.js.map +1 -0
  507. package/dist/react/index.d.ts +108 -0
  508. package/dist/react/index.d.ts.map +1 -0
  509. package/dist/react/index.js +87 -0
  510. package/dist/react/index.js.map +1 -0
  511. package/dist/react/lib/connect-requirement-keys.d.ts +14 -0
  512. package/dist/react/lib/connect-requirement-keys.d.ts.map +1 -0
  513. package/dist/react/lib/connect-requirement-keys.js +57 -0
  514. package/dist/react/lib/connect-requirement-keys.js.map +1 -0
  515. package/dist/react/lib/price-helpers.d.ts +31 -0
  516. package/dist/react/lib/price-helpers.d.ts.map +1 -0
  517. package/dist/react/lib/price-helpers.js +46 -0
  518. package/dist/react/lib/price-helpers.js.map +1 -0
  519. package/dist/react/lib/stripe-element-styles.d.ts +91 -0
  520. package/dist/react/lib/stripe-element-styles.d.ts.map +1 -0
  521. package/dist/react/lib/stripe-element-styles.js +131 -0
  522. package/dist/react/lib/stripe-element-styles.js.map +1 -0
  523. package/dist/react/lib/subscription-helpers.d.ts +33 -0
  524. package/dist/react/lib/subscription-helpers.d.ts.map +1 -0
  525. package/dist/react/lib/subscription-helpers.js +47 -0
  526. package/dist/react/lib/subscription-helpers.js.map +1 -0
  527. package/dist/react/types.d.ts +20 -0
  528. package/dist/react/types.d.ts.map +1 -0
  529. package/dist/react/types.js +2 -0
  530. package/dist/react/types.js.map +1 -0
  531. package/dist/testing/assert-test-env.d.ts +6 -0
  532. package/dist/testing/assert-test-env.d.ts.map +1 -0
  533. package/dist/testing/assert-test-env.js +15 -0
  534. package/dist/testing/assert-test-env.js.map +1 -0
  535. package/dist/testing/fixtures.d.ts +38 -0
  536. package/dist/testing/fixtures.d.ts.map +1 -0
  537. package/dist/testing/fixtures.js +54 -0
  538. package/dist/testing/fixtures.js.map +1 -0
  539. package/dist/testing/index.d.ts +4 -0
  540. package/dist/testing/index.d.ts.map +1 -0
  541. package/dist/testing/index.js +4 -0
  542. package/dist/testing/index.js.map +1 -0
  543. package/dist/testing/mock-webhooks.d.ts +19 -0
  544. package/dist/testing/mock-webhooks.d.ts.map +1 -0
  545. package/dist/testing/mock-webhooks.js +81 -0
  546. package/dist/testing/mock-webhooks.js.map +1 -0
  547. package/package.json +131 -0
  548. package/src/client/billing/checkout.test.ts +1234 -0
  549. package/src/client/billing/checkout.ts +416 -0
  550. package/src/client/billing/invoices.test.ts +237 -0
  551. package/src/client/billing/invoices.ts +93 -0
  552. package/src/client/billing/subscriptions.test.ts +987 -0
  553. package/src/client/billing/subscriptions.ts +604 -0
  554. package/src/client/component-api-types.test.ts +137 -0
  555. package/src/client/connect/disputes.test.ts +487 -0
  556. package/src/client/connect/disputes.ts +302 -0
  557. package/src/client/connect/paymentMethodUtils.test.ts +83 -0
  558. package/src/client/connect/paymentMethodUtils.ts +28 -0
  559. package/src/client/connect/paymentMethods.test.ts +66 -0
  560. package/src/client/connect/paymentMethods.ts +55 -0
  561. package/src/client/connect/payouts.test.ts +132 -0
  562. package/src/client/connect/payouts.ts +105 -0
  563. package/src/client/connect/refundActor.test.ts +121 -0
  564. package/src/client/connect/refundActor.ts +60 -0
  565. package/src/client/connect/refunds.test.ts +341 -0
  566. package/src/client/connect/refunds.ts +256 -0
  567. package/src/client/connect/transfers.test.ts +492 -0
  568. package/src/client/connect/transfers.ts +572 -0
  569. package/src/client/constants.ts +15 -0
  570. package/src/client/core/accountLinks.test.ts +378 -0
  571. package/src/client/core/accountLinks.ts +211 -0
  572. package/src/client/core/accountStatus.test.ts +102 -0
  573. package/src/client/core/accountStatus.ts +91 -0
  574. package/src/client/core/accounts.test.ts +1496 -0
  575. package/src/client/core/accounts.ts +667 -0
  576. package/src/client/core/config.test.ts +68 -0
  577. package/src/client/core/config.ts +27 -0
  578. package/src/client/core/descriptors.test.ts +68 -0
  579. package/src/client/core/descriptors.ts +46 -0
  580. package/src/client/core/fees.test.ts +377 -0
  581. package/src/client/core/fees.ts +268 -0
  582. package/src/client/errors.test.ts +66 -0
  583. package/src/client/errors.ts +70 -0
  584. package/src/client/helpers.test.ts +74 -0
  585. package/src/client/helpers.ts +94 -0
  586. package/src/client/index.test.ts +1848 -0
  587. package/src/client/index.ts +1872 -0
  588. package/src/client/products/prices.test.ts +345 -0
  589. package/src/client/products/prices.ts +194 -0
  590. package/src/client/products/products.test.ts +476 -0
  591. package/src/client/products/products.ts +335 -0
  592. package/src/client/setup.test.ts +47 -0
  593. package/src/client/stripe-types.ts +108 -0
  594. package/src/client/types/documents.ts +245 -0
  595. package/src/client/types/events.ts +72 -0
  596. package/src/client/types/index.ts +43 -0
  597. package/src/client/types/options.ts +103 -0
  598. package/src/client/types/triggers.ts +293 -0
  599. package/src/client/types.ts +35 -0
  600. package/src/client/utils/data.test.ts +59 -0
  601. package/src/client/utils/data.ts +22 -0
  602. package/src/client/utils/owner.test.ts +35 -0
  603. package/src/client/utils/owner.ts +27 -0
  604. package/src/client/utils/stripeDashboardUrl.test.ts +71 -0
  605. package/src/client/utils/stripeDashboardUrl.ts +71 -0
  606. package/src/client/utils/webhookEndpoints.test.ts +454 -0
  607. package/src/client/utils/webhookEndpoints.ts +271 -0
  608. package/src/client/webhook-handlers.test.ts +603 -0
  609. package/src/client/webhooks/handler.test.ts +604 -0
  610. package/src/client/webhooks/handler.ts +256 -0
  611. package/src/client/webhooks/helpers.test.ts +330 -0
  612. package/src/client/webhooks/helpers.ts +277 -0
  613. package/src/client/webhooks/hooks.test.ts +111 -0
  614. package/src/client/webhooks/hooks.ts +177 -0
  615. package/src/client/webhooks/index.ts +51 -0
  616. package/src/client/webhooks/processors.test.ts +2392 -0
  617. package/src/client/webhooks/processors.ts +1166 -0
  618. package/src/client/webhooks/v2.test.ts +396 -0
  619. package/src/client/webhooks/v2.ts +124 -0
  620. package/src/client/webhooks.test.ts +1689 -0
  621. package/src/client/webhooks.ts +3 -0
  622. package/src/component/_generated/api.ts +86 -0
  623. package/src/component/_generated/component.ts +1758 -0
  624. package/src/component/_generated/dataModel.ts +60 -0
  625. package/src/component/_generated/server.ts +164 -0
  626. package/src/component/billing/mutations.ts +155 -0
  627. package/src/component/billing/queries.ts +378 -0
  628. package/src/component/billing/schema.ts +40 -0
  629. package/src/component/billing/validators.ts +137 -0
  630. package/src/component/config-queries.test.ts +47 -0
  631. package/src/component/connect/mutations.ts +624 -0
  632. package/src/component/connect/queries.ts +537 -0
  633. package/src/component/connect/schema.ts +90 -0
  634. package/src/component/connect/validators.ts +333 -0
  635. package/src/component/connect.test.ts +721 -0
  636. package/src/component/convex.config.ts +17 -0
  637. package/src/component/core/mutations.ts +182 -0
  638. package/src/component/core/queries.ts +100 -0
  639. package/src/component/core/schema.ts +13 -0
  640. package/src/component/core/validators.ts +55 -0
  641. package/src/component/earnings-totals.test.ts +196 -0
  642. package/src/component/fee-routing.test.ts +124 -0
  643. package/src/component/lib/fees.ts +64 -0
  644. package/src/component/lib/idempotency.test.ts +37 -0
  645. package/src/component/lib/idempotency.ts +20 -0
  646. package/src/component/lib/reversals.ts +113 -0
  647. package/src/component/lib/stripeFactory.ts +30 -0
  648. package/src/component/products/mutations.ts +73 -0
  649. package/src/component/products/queries.ts +149 -0
  650. package/src/component/products/schema.ts +22 -0
  651. package/src/component/products/validators.ts +63 -0
  652. package/src/component/public.test.ts +1858 -0
  653. package/src/component/reversal-races.test.ts +920 -0
  654. package/src/component/schema.ts +45 -0
  655. package/src/component/subscription-scoping.test.ts +118 -0
  656. package/src/component/transfers.test.ts +402 -0
  657. package/src/component/triggers.test.ts +359 -0
  658. package/src/component/webhooks/mutations.ts +151 -0
  659. package/src/component/webhooks/queries.ts +44 -0
  660. package/src/component/webhooks/schema.ts +10 -0
  661. package/src/component/webhooks/validators.ts +30 -0
  662. package/src/react/components/AccountCloseButton.tsx +91 -0
  663. package/src/react/components/AccountCloseCard.tsx +84 -0
  664. package/src/react/components/AccountCreateButton.tsx +83 -0
  665. package/src/react/components/AccountCreateCard.tsx +123 -0
  666. package/src/react/components/AccountLoginButton.tsx +69 -0
  667. package/src/react/components/AccountLoginCard.tsx +99 -0
  668. package/src/react/components/AccountOnboardingButton.tsx +83 -0
  669. package/src/react/components/AccountOnboardingCard.test.ts +27 -0
  670. package/src/react/components/AccountOnboardingCard.tsx +152 -0
  671. package/src/react/components/AddCardForm.tsx +80 -0
  672. package/src/react/components/BillingPortalLink.tsx +93 -0
  673. package/src/react/components/BuyerBillingView.render.test.tsx +207 -0
  674. package/src/react/components/BuyerBillingView.tsx +193 -0
  675. package/src/react/components/CheckoutSessionProvider.tsx +70 -0
  676. package/src/react/components/CheckoutSessionProviderWithKey.tsx +99 -0
  677. package/src/react/components/CheckoutStatus.tsx +71 -0
  678. package/src/react/components/ConnectProvider.tsx +58 -0
  679. package/src/react/components/ConnectRequirements.tsx +159 -0
  680. package/src/react/components/ConnectStatusBadge.tsx +60 -0
  681. package/src/react/components/DeletePaymentMethodDialog.tsx +61 -0
  682. package/src/react/components/DisputeDetail.render.test.tsx +143 -0
  683. package/src/react/components/DisputeDetail.tsx +111 -0
  684. package/src/react/components/DisputesList.render.test.tsx +244 -0
  685. package/src/react/components/DisputesList.tsx +120 -0
  686. package/src/react/components/EarningsSummary.render.test.tsx +153 -0
  687. package/src/react/components/EarningsSummary.tsx +131 -0
  688. package/src/react/components/EmbeddedCheckout.test.ts +25 -0
  689. package/src/react/components/EmbeddedCheckout.tsx +54 -0
  690. package/src/react/components/EmbeddedDisputes.render.test.tsx +142 -0
  691. package/src/react/components/EmbeddedDisputes.tsx +38 -0
  692. package/src/react/components/EvidenceForm.render.test.tsx +215 -0
  693. package/src/react/components/EvidenceForm.tsx +176 -0
  694. package/src/react/components/IntervalSelector.tsx +58 -0
  695. package/src/react/components/PaymentMethodActions.tsx +68 -0
  696. package/src/react/components/PaymentMethodsList.tsx +81 -0
  697. package/src/react/components/PayoutSchedule.render.test.tsx +178 -0
  698. package/src/react/components/PayoutSchedule.tsx +148 -0
  699. package/src/react/components/PriceBadge.render.test.tsx +134 -0
  700. package/src/react/components/PriceBadge.tsx +49 -0
  701. package/src/react/components/PriceCard.render.test.tsx +135 -0
  702. package/src/react/components/PriceCard.tsx +83 -0
  703. package/src/react/components/PricePicker.tsx +95 -0
  704. package/src/react/components/SplitBreakdown.render.test.tsx +168 -0
  705. package/src/react/components/SplitBreakdown.tsx +121 -0
  706. package/src/react/components/StripeProvider.test.ts +45 -0
  707. package/src/react/components/StripeProvider.tsx +80 -0
  708. package/src/react/components/StripeProviderWithKey.tsx +95 -0
  709. package/src/react/components/SubscriptionActions.tsx +79 -0
  710. package/src/react/components/SubscriptionCard.tsx +92 -0
  711. package/src/react/components/SubscriptionLineItems.tsx +62 -0
  712. package/src/react/components/TrialAlert.render.test.tsx +132 -0
  713. package/src/react/components/TrialAlert.tsx +44 -0
  714. package/src/react/hooks/skipSentinel.test.ts +85 -0
  715. package/src/react/hooks/useAccount.ts +28 -0
  716. package/src/react/hooks/useAccountOnboarding.test.ts +75 -0
  717. package/src/react/hooks/useAccountOnboarding.ts +35 -0
  718. package/src/react/hooks/useCheckout.ts +33 -0
  719. package/src/react/hooks/useCheckoutSession.ts +110 -0
  720. package/src/react/hooks/useConfirmPayment.ts +117 -0
  721. package/src/react/hooks/useDisputeWithCountdown.test.ts +90 -0
  722. package/src/react/hooks/useDisputeWithCountdown.ts +48 -0
  723. package/src/react/hooks/useDisputes.test.ts +75 -0
  724. package/src/react/hooks/useDisputes.ts +28 -0
  725. package/src/react/hooks/useEarnings.test.ts +159 -0
  726. package/src/react/hooks/useEarnings.ts +132 -0
  727. package/src/react/hooks/useInvoices.test.ts +79 -0
  728. package/src/react/hooks/useInvoices.ts +25 -0
  729. package/src/react/hooks/usePaymentMethodActions.ts +206 -0
  730. package/src/react/hooks/usePaymentMethods.ts +44 -0
  731. package/src/react/hooks/usePrices.ts +26 -0
  732. package/src/react/hooks/useProducts.test.ts +75 -0
  733. package/src/react/hooks/useProducts.ts +24 -0
  734. package/src/react/hooks/useSplitBreakdown.test.ts +151 -0
  735. package/src/react/hooks/useSplitBreakdown.ts +118 -0
  736. package/src/react/hooks/useStripeConfig.ts +31 -0
  737. package/src/react/hooks/useStripeMode.test.ts +49 -0
  738. package/src/react/hooks/useStripeMode.ts +9 -0
  739. package/src/react/hooks/useStripePublishableKey.test.ts +35 -0
  740. package/src/react/hooks/useStripePublishableKey.ts +9 -0
  741. package/src/react/hooks/useSubscription.ts +52 -0
  742. package/src/react/hooks/useSubscriptions.ts +33 -0
  743. package/src/react/index.payment-element.test.ts +41 -0
  744. package/src/react/index.test.ts +167 -0
  745. package/src/react/index.ts +279 -0
  746. package/src/react/lib/connect-requirement-keys.test.ts +73 -0
  747. package/src/react/lib/connect-requirement-keys.ts +66 -0
  748. package/src/react/lib/price-helpers.test.ts +199 -0
  749. package/src/react/lib/price-helpers.ts +68 -0
  750. package/src/react/lib/stripe-element-styles.test.ts +94 -0
  751. package/src/react/lib/stripe-element-styles.ts +178 -0
  752. package/src/react/lib/subscription-helpers.test.ts +127 -0
  753. package/src/react/lib/subscription-helpers.ts +64 -0
  754. package/src/react/types.ts +32 -0
  755. package/src/test.ts +5 -0
  756. package/src/testing/assert-test-env.test.ts +33 -0
  757. package/src/testing/assert-test-env.ts +20 -0
  758. package/src/testing/fixtures.ts +95 -0
  759. package/src/testing/index.ts +13 -0
  760. package/src/testing/mock-webhooks.test.ts +97 -0
  761. package/src/testing/mock-webhooks.ts +101 -0
  762. package/src/vite-env.d.ts +4 -0
@@ -0,0 +1,1166 @@
1
+ import type Stripe from "stripe";
2
+
3
+ import type { SplitRecipient } from "../../component/lib/fees.js";
4
+ import {
5
+ createSplitTransfers,
6
+ reinstateTransfers,
7
+ reverseTransfers,
8
+ reverseTransfersForRefund,
9
+ } from "../connect/transfers.js";
10
+ import { validateStatementDescriptorSuffix } from "../core/descriptors.js";
11
+ import { computeFee } from "../core/fees.js";
12
+ import type { PlatformFeeConfig } from "../types.js";
13
+ import { resolveOwnerAccount } from "../utils/owner.js";
14
+ import {
15
+ type WebhookContext,
16
+ componentRef,
17
+ deriveTrialFields,
18
+ dispatchUpsert,
19
+ epochToIso,
20
+ extractIdentifiers,
21
+ } from "./helpers.js";
22
+
23
+ // =============================================================================
24
+ // EVENT PROCESSOR
25
+ // =============================================================================
26
+
27
+ export async function processEvent(
28
+ whCtx: WebhookContext,
29
+ event: Stripe.Event,
30
+ ): Promise<void> {
31
+ // Stripe guarantees the object type matches event.type, so these casts are safe.
32
+ const obj = event.data.object;
33
+
34
+ switch (event.type) {
35
+ case "product.created":
36
+ case "product.updated":
37
+ await handleProductEvent(whCtx, obj as Stripe.Product);
38
+ break;
39
+ case "price.created":
40
+ case "price.updated":
41
+ await handlePriceEvent(whCtx, obj as Stripe.Price);
42
+ break;
43
+ case "customer.subscription.created":
44
+ case "customer.subscription.updated":
45
+ case "customer.subscription.trial_will_end":
46
+ await upsertSubscriptionFromStripe(
47
+ whCtx,
48
+ obj as Stripe.Subscription,
49
+ "subscriptionUpserted",
50
+ );
51
+ break;
52
+ case "customer.subscription.deleted":
53
+ await upsertSubscriptionFromStripe(
54
+ whCtx,
55
+ obj as Stripe.Subscription,
56
+ "subscriptionDeleted",
57
+ );
58
+ break;
59
+ case "checkout.session.completed":
60
+ await handleCheckoutEvent(whCtx, obj as Stripe.Checkout.Session);
61
+ break;
62
+ case "invoice.created":
63
+ // Apply a per-invoice fixed/tier platform fee before finalization, then
64
+ // record the invoice. Percent-only fees use application_fee_percent on the
65
+ // subscription and don't need this.
66
+ await applyPerInvoiceFee(whCtx, obj as Stripe.Invoice);
67
+ // Per-store statement descriptor for destination-charge subscriptions
68
+ // (BTS-32) — set before finalization so the charge carries it.
69
+ await applyStatementDescriptor(whCtx, obj as Stripe.Invoice);
70
+ await upsertInvoiceFromStripe(whCtx, obj as Stripe.Invoice);
71
+ break;
72
+ case "invoice.paid":
73
+ await upsertInvoiceFromStripe(whCtx, obj as Stripe.Invoice);
74
+ // Collect the fixed/tier platform fee the per-invoice path (BTS-51) misses
75
+ // on a subscription's synchronously-finalized FIRST invoice (BTS-68).
76
+ await applyFirstInvoiceFee(whCtx, obj as Stripe.Invoice);
77
+ // Fan funds to split recipients each billing cycle for a separate-charges
78
+ // subscription (BTS-52).
79
+ await handleInvoiceSplitTransfers(whCtx, obj as Stripe.Invoice);
80
+ break;
81
+ case "invoice.finalized":
82
+ case "invoice.payment_failed":
83
+ await upsertInvoiceFromStripe(whCtx, obj as Stripe.Invoice);
84
+ break;
85
+ case "payment_intent.succeeded": {
86
+ const pi = obj as Stripe.PaymentIntent;
87
+ // Collect a deferred fixed/tier fee first so the payments row can carry
88
+ // feeCollectedAmount in the same write (BTS-60).
89
+ const perChargeFee = await applyPerChargeFee(whCtx, pi);
90
+ await upsertPaymentFromStripe(whCtx, pi, perChargeFee);
91
+ // Fan funds out to split recipients for a separate-charges sale.
92
+ await handleSplitTransfers(whCtx, pi);
93
+ break;
94
+ }
95
+ case "payment_intent.payment_failed":
96
+ case "payment_intent.canceled":
97
+ await upsertPaymentFromStripe(whCtx, obj as Stripe.PaymentIntent);
98
+ break;
99
+ case "payout.created":
100
+ case "payout.updated":
101
+ case "payout.paid":
102
+ case "payout.failed":
103
+ await handlePayoutEvent(whCtx, obj as Stripe.Payout);
104
+ break;
105
+ case "refund.created":
106
+ case "refund.updated":
107
+ case "refund.failed":
108
+ await handleRefundEvent(whCtx, obj as Stripe.Refund);
109
+ break;
110
+ case "application_fee.refunded":
111
+ // Keep feeCollectedAmount/feeRefundedAmount accurate on the linked
112
+ // payment (BTS-34, folded in from BTS-51).
113
+ await handleApplicationFeeRefunded(whCtx, obj as Stripe.ApplicationFee);
114
+ break;
115
+ case "charge.dispute.created":
116
+ case "charge.dispute.updated":
117
+ case "charge.dispute.closed":
118
+ case "charge.dispute.funds_withdrawn":
119
+ case "charge.dispute.funds_reinstated":
120
+ await handleDisputeEvent(
121
+ whCtx,
122
+ obj as Stripe.Dispute,
123
+ event.type.replace("charge.dispute.", ""),
124
+ );
125
+ break;
126
+ default:
127
+ console.info(`[better-stripe] Unhandled event type: ${event.type}`);
128
+ }
129
+ }
130
+
131
+ // =============================================================================
132
+ // PER-DOMAIN HANDLERS
133
+ // =============================================================================
134
+
135
+ // Connect products may include an `account` field not present in base SDK types
136
+ type ConnectProduct = Stripe.Product & { account?: string };
137
+
138
+ async function handleProductEvent(
139
+ whCtx: WebhookContext,
140
+ product: Stripe.Product,
141
+ ): Promise<void> {
142
+ const productAccount = (product as ConnectProduct).account;
143
+
144
+ await dispatchUpsert(whCtx, "productUpserted", {
145
+ stripeProductId: product.id,
146
+ accountId: typeof productAccount === "string" ? productAccount : undefined,
147
+ name: product.name,
148
+ description: product.description ?? undefined,
149
+ active: product.active,
150
+ metadata: product.metadata ?? undefined,
151
+ });
152
+ }
153
+
154
+ async function handlePriceEvent(
155
+ whCtx: WebhookContext,
156
+ price: Stripe.Price,
157
+ ): Promise<void> {
158
+ const { ctx, component, stripe } = whCtx;
159
+ const stripeProductId: string =
160
+ typeof price.product === "string"
161
+ ? price.product
162
+ : (price.product?.id ?? "");
163
+
164
+ let internalProduct = (await ctx.runQuery(
165
+ componentRef(component, "products/queries/getProductByStripeId"),
166
+ { stripeProductId },
167
+ )) as { _id: string } | null;
168
+
169
+ if (!internalProduct && stripeProductId) {
170
+ try {
171
+ const stripeProduct = await stripe.products.retrieve(stripeProductId);
172
+ await ctx.runMutation(
173
+ componentRef(component, "products/mutations/upsertProduct"),
174
+ {
175
+ stripeProductId: stripeProduct.id,
176
+ name: stripeProduct.name,
177
+ description: stripeProduct.description ?? undefined,
178
+ active: stripeProduct.active,
179
+ metadata: stripeProduct.metadata ?? undefined,
180
+ },
181
+ );
182
+ internalProduct = (await ctx.runQuery(
183
+ componentRef(component, "products/queries/getProductByStripeId"),
184
+ { stripeProductId },
185
+ )) as { _id: string } | null;
186
+ } catch (err) {
187
+ console.warn(
188
+ `[better-stripe] Could not auto-create product ${stripeProductId}:`,
189
+ err,
190
+ );
191
+ }
192
+ }
193
+
194
+ if (!internalProduct) {
195
+ console.warn(
196
+ `[better-stripe] Skipping price ${price.id}: product ${stripeProductId} not found`,
197
+ );
198
+ return;
199
+ }
200
+
201
+ await dispatchUpsert(whCtx, "priceUpserted", {
202
+ stripePriceId: price.id,
203
+ productId: internalProduct._id as string,
204
+ stripeProductId,
205
+ nickname: price.nickname ?? undefined,
206
+ unitAmount: price.unit_amount ?? 0,
207
+ currency: price.currency,
208
+ active: price.active,
209
+ type: price.type,
210
+ interval: price.recurring?.interval,
211
+ intervalCount: price.recurring?.interval_count ?? undefined,
212
+ metadata: price.metadata ?? undefined,
213
+ });
214
+ }
215
+
216
+ async function upsertSubscriptionFromStripe(
217
+ whCtx: WebhookContext,
218
+ subscription: Stripe.Subscription,
219
+ dispatcherName: "subscriptionUpserted" | "subscriptionDeleted",
220
+ ): Promise<void> {
221
+ const { userId, orgId } = extractIdentifiers(
222
+ subscription.metadata as Record<string, string> | null,
223
+ );
224
+ const trial = deriveTrialFields(subscription);
225
+
226
+ const firstItem = subscription.items?.data?.[0];
227
+ const priceId = firstItem?.price?.id ?? undefined;
228
+ const periodStart = firstItem?.current_period_start ?? undefined;
229
+ const periodEnd = firstItem?.current_period_end ?? undefined;
230
+
231
+ // Prefer the V2 `customer_account` (acct_…) over the legacy `customer`
232
+ // (cus_…) so V2 customer-configured accounts are attributed correctly.
233
+ const accountId = resolveOwnerAccount(subscription) ?? undefined;
234
+
235
+ await dispatchUpsert(whCtx, dispatcherName, {
236
+ stripeSubscriptionId: subscription.id,
237
+ accountId,
238
+ userId,
239
+ orgId,
240
+ status: subscription.status,
241
+ priceId,
242
+ quantity: firstItem?.quantity ?? undefined,
243
+ currentPeriodStart: epochToIso(periodStart),
244
+ currentPeriodEnd: epochToIso(periodEnd),
245
+ cancelAtPeriodEnd: subscription.cancel_at_period_end,
246
+ canceledAt: epochToIso(subscription.canceled_at),
247
+ isTrialing: trial.isTrialing,
248
+ trialStart: trial.trialStart,
249
+ trialEnd: trial.trialEnd,
250
+ metadata: subscription.metadata ?? undefined,
251
+ });
252
+ }
253
+
254
+ async function handleCheckoutEvent(
255
+ whCtx: WebhookContext,
256
+ session: Stripe.Checkout.Session,
257
+ ): Promise<void> {
258
+ const { ctx, component } = whCtx;
259
+ const { userId, orgId } = extractIdentifiers(
260
+ session.metadata as Record<string, string> | null,
261
+ );
262
+
263
+ const lineItems = session.line_items?.data;
264
+ const priceId = lineItems?.[0]?.price?.id;
265
+
266
+ let mergedMetadata: Record<string, string> | undefined =
267
+ (session.metadata as Record<string, string> | undefined) ?? undefined;
268
+ try {
269
+ const existing = (await ctx.runQuery(
270
+ componentRef(component, "billing/queries/getCheckoutSessionByStripeId"),
271
+ { stripeSessionId: session.id },
272
+ )) as { metadata?: Record<string, string> } | null;
273
+ if (existing?.metadata) {
274
+ mergedMetadata = {
275
+ ...(existing.metadata ?? {}),
276
+ ...(session.metadata ?? {}),
277
+ };
278
+ }
279
+ } catch {
280
+ // First time seeing this session
281
+ }
282
+
283
+ await dispatchUpsert(whCtx, "checkoutSessionUpserted", {
284
+ stripeSessionId: session.id,
285
+ userId,
286
+ orgId,
287
+ accountId: resolveOwnerAccount(session) ?? undefined,
288
+ mode: (session.mode ?? "payment") as "payment" | "subscription" | "setup",
289
+ status: (session.status ?? "open") as "open" | "complete" | "expired",
290
+ clientSecret: session.client_secret ?? undefined,
291
+ url: session.url ?? undefined,
292
+ priceId,
293
+ metadata: mergedMetadata,
294
+ });
295
+ }
296
+
297
+ /**
298
+ * Fee/transfer fields (BTS-11) captured off a PaymentIntent for denormalization
299
+ * onto the `payments` row. Returns `{}` when the charge carried no fee/transfer.
300
+ */
301
+ function feeRoutingFromPaymentIntent(pi: Stripe.PaymentIntent): {
302
+ chargeType?: "destination";
303
+ destinationAccountId?: string;
304
+ applicationFeeAmount?: number;
305
+ feeCollectedAmount?: number;
306
+ } {
307
+ const dest = pi.transfer_data?.destination;
308
+ const destinationAccountId = typeof dest === "string" ? dest : dest?.id;
309
+ const fee = pi.application_fee_amount ?? undefined;
310
+ if (!destinationAccountId && fee === undefined) return {};
311
+ return {
312
+ chargeType: "destination",
313
+ ...(destinationAccountId ? { destinationAccountId } : {}),
314
+ ...(fee !== undefined
315
+ ? { applicationFeeAmount: fee, feeCollectedAmount: fee }
316
+ : {}),
317
+ };
318
+ }
319
+
320
+ /**
321
+ * Apply a fixed/tier platform fee to a subscription invoice before it finalizes
322
+ * (BTS-51). Percent-only fees ride on the subscription's `application_fee_percent`
323
+ * and skip this; fixed/tier fees can't be expressed that way, so BTS-15/BTS-17
324
+ * flag the subscription with `bsFeeMode=per_invoice` + `bsFeeConfig`. Here we
325
+ * read that flag off the subscription, compute the exact fee from the invoice
326
+ * amount, and set `application_fee_amount` on the draft invoice. Idempotent via
327
+ * a `bsFeeApplied` invoice-metadata marker; failures never crash the webhook.
328
+ */
329
+ async function applyPerInvoiceFee(
330
+ whCtx: WebhookContext,
331
+ invoice: Stripe.Invoice,
332
+ ): Promise<void> {
333
+ try {
334
+ if (!invoice.id) return;
335
+ if (invoice.metadata?.bsFeeApplied) return; // already applied
336
+
337
+ const parentSub = invoice.parent?.subscription_details?.subscription;
338
+ const subId =
339
+ typeof parentSub === "string" ? parentSub : (parentSub?.id ?? undefined);
340
+ if (!subId) return;
341
+
342
+ const sub = await whCtx.stripe.subscriptions.retrieve(subId);
343
+ const meta = (sub.metadata ?? {}) as Record<string, string>;
344
+ if (meta.bsFeeMode !== "per_invoice" || !meta.bsFeeConfig) return;
345
+
346
+ let config: PlatformFeeConfig;
347
+ try {
348
+ config = JSON.parse(meta.bsFeeConfig) as PlatformFeeConfig;
349
+ } catch {
350
+ return; // malformed marker — nothing safe to apply
351
+ }
352
+
353
+ const fee = computeFee(invoice.amount_due, config).feeAmount;
354
+ // A shape-invalid config (e.g. non-numeric percent) yields NaN; never send
355
+ // a non-finite application_fee_amount to Stripe.
356
+ if (!Number.isFinite(fee) || fee <= 0) return;
357
+
358
+ await whCtx.stripe.invoices.update(invoice.id, {
359
+ application_fee_amount: fee,
360
+ metadata: { ...(invoice.metadata ?? {}), bsFeeApplied: "1" },
361
+ });
362
+ } catch (err) {
363
+ // Never let fee application break webhook processing; Stripe will retry the
364
+ // event, and a missed fixed-fee invoice can be reconciled out of band.
365
+ console.error("[better-stripe] applyPerInvoiceFee failed:", err);
366
+ }
367
+ }
368
+
369
+ /**
370
+ * Set the per-store statement descriptor on a subscription invoice before it
371
+ * finalizes (BTS-32). Destination-charge subscriptions can't carry a suffix
372
+ * directly, so BTS-15/BTS-17 stash the resolved suffix as a
373
+ * `bsStatementDescriptor` subscription-metadata marker; for card charges
374
+ * Stripe renders the invoice's `statement_descriptor` as the dynamic suffix
375
+ * after the platform's shortened descriptor. Idempotent: an invoice whose
376
+ * descriptor is already set (by us on a retry, or by the app) is left alone.
377
+ *
378
+ * FIRST-INVOICE HANDOFF (BTS-67) — this invoice-time path can't reach the FIRST
379
+ * invoice: direct `charge_automatically` subscriptions (and Checkout
380
+ * subscription mode) finalize and pay invoice #1 synchronously at creation,
381
+ * before this `invoice.created` handler runs, so by the time we'd call
382
+ * `invoices.update` the charge already exists. That first charge is instead
383
+ * covered by the **product-level** `statement_descriptor` set at product
384
+ * create/update (BTS-67, `resolveProductStatementDescriptor`): per Stripe's
385
+ * precedence (Invoice → Product → default) the product descriptor applies to
386
+ * every cycle including the first. This per-invoice path still owns LATER
387
+ * invoices and the invoice-level override (which wins over the product), and
388
+ * remains the only mechanism for products created before a store set its
389
+ * descriptor. The two are complementary, not redundant.
390
+ *
391
+ * Failure contract: descriptor application is cosmetic, so failures are
392
+ * swallowed (logged) rather than failing the event — a missed descriptor
393
+ * self-heals on the NEXT billing cycle's invoice and must never block fee
394
+ * application or invoice recording. This is honest: once the event ends
395
+ * `processed`, THIS invoice's descriptor is not retried.
396
+ */
397
+ async function applyStatementDescriptor(
398
+ whCtx: WebhookContext,
399
+ invoice: Stripe.Invoice,
400
+ ): Promise<void> {
401
+ try {
402
+ if (!invoice.id) return;
403
+ if (invoice.statement_descriptor) return; // already set — never overwrite
404
+
405
+ const parentSub = invoice.parent?.subscription_details?.subscription;
406
+ const subId =
407
+ typeof parentSub === "string" ? parentSub : (parentSub?.id ?? undefined);
408
+ if (!subId) return;
409
+
410
+ const sub = await whCtx.stripe.subscriptions.retrieve(subId);
411
+ const marker = (sub.metadata ?? {})["bsStatementDescriptor"];
412
+ if (!marker) return;
413
+
414
+ // Defensive: the marker was validated when stored, but webhooks never
415
+ // trust round-tripped metadata enough to forward a rule-breaking value.
416
+ let suffix: string;
417
+ try {
418
+ suffix = validateStatementDescriptorSuffix(marker);
419
+ } catch {
420
+ console.error(
421
+ `[better-stripe] applyStatementDescriptor: invalid bsStatementDescriptor on ${subId}; skipping`,
422
+ );
423
+ return;
424
+ }
425
+
426
+ await whCtx.stripe.invoices.update(invoice.id, {
427
+ statement_descriptor: suffix,
428
+ });
429
+ } catch (err) {
430
+ console.error("[better-stripe] applyStatementDescriptor failed:", err);
431
+ }
432
+ }
433
+
434
+ /**
435
+ * Collect the fixed/tier platform fee that {@link applyPerInvoiceFee} (BTS-51)
436
+ * silently misses on a subscription's FIRST invoice (BTS-68).
437
+ *
438
+ * Stripe finalizes the first invoice of a `charge_automatically` subscription
439
+ * (and pays the first invoice of a Checkout subscription-mode session)
440
+ * synchronously at creation — it is already `open` by the time `invoice.created`
441
+ * is processed, so the `invoices.update({ application_fee_amount })` that the
442
+ * per-invoice path relies on is rejected (monetary values are uneditable once an
443
+ * invoice finalizes) and the fee is never collected. Renewal invoices are fine:
444
+ * they get Stripe's ~1h draft window, so the per-invoice path applies the fee
445
+ * there.
446
+ *
447
+ * Here — at `invoice.paid`, when the charge and its automatic transfer exist —
448
+ * we realize the missed fee the way Stripe settles application fees on
449
+ * destination charges (and the way BTS-60's per_charge path does): a partial
450
+ * reversal of the destination transfer, sized from the amount actually paid.
451
+ *
452
+ * No double-collection: an invoice whose fee the draft path already applied
453
+ * carries `application_fee_amount`/`bsFeeApplied`, and is skipped — so every
454
+ * renewal (and any invoice that did get its draft window) is untouched.
455
+ * Percent-only subscriptions never reach here (they use
456
+ * `application_fee_percent`); one-time per_charge charges have no invoice.
457
+ * Idempotent via a fresh-invoice `bsFeeCollected` marker plus a deterministic
458
+ * Stripe idempotency key.
459
+ *
460
+ * Failure contract (matching {@link applyPerChargeFee}, NOT the swallow-all of
461
+ * {@link applyPerInvoiceFee}): genuine collection failures (a retrieve/reversal/
462
+ * mark API error, or a paid invoice with no resolvable charge) PROPAGATE so the
463
+ * event is marked `failed` and Stripe retries — a swallowed error would 200 and
464
+ * lose the fee forever. Benign skips a retry can't fix (unflagged subscription,
465
+ * already collected, zero amount, malformed config, no destination transfer)
466
+ * return undefined without throwing.
467
+ *
468
+ * Documented limitation: the fee is recorded on the invoice (`bsFeeAmount`
469
+ * marker) and via the reversal, but — unlike the per_charge path — it is not
470
+ * denormalized onto the `payments` row for the first invoice's PaymentIntent.
471
+ */
472
+ async function applyFirstInvoiceFee(
473
+ whCtx: WebhookContext,
474
+ invoice: Stripe.Invoice,
475
+ ): Promise<number | undefined> {
476
+ if (!invoice.id) return undefined;
477
+ // No money settled → no charge/transfer to reverse (trial, 100%-off, credit).
478
+ if (!(invoice.amount_paid > 0)) return undefined;
479
+
480
+ const parentSub = invoice.parent?.subscription_details?.subscription;
481
+ const subId =
482
+ typeof parentSub === "string" ? parentSub : (parentSub?.id ?? undefined);
483
+ if (!subId) return undefined; // not a subscription invoice
484
+
485
+ const sub = await whCtx.stripe.subscriptions.retrieve(subId);
486
+ const subMeta = (sub?.metadata ?? {}) as Record<string, string>;
487
+ if (subMeta.bsFeeMode !== "per_invoice" || !subMeta.bsFeeConfig) {
488
+ return undefined;
489
+ }
490
+
491
+ // The event payload is a stale snapshot on retries; read fresh so the
492
+ // already-collected guard and our idempotency marker are authoritative.
493
+ const fresh = await whCtx.stripe.invoices.retrieve(invoice.id);
494
+ const freshMeta = (fresh.metadata ?? {}) as Record<string, string>;
495
+
496
+ // The draft-window path already collected this invoice's fee (every renewal,
497
+ // plus any invoice that got its ~1h draft window): Stripe kept the
498
+ // application_fee_amount and marked bsFeeApplied — the two are set atomically,
499
+ // so either signal means "already collected". Checking Stripe's own field
500
+ // (not just our marker) is the authoritative double-collection guard; the SDK
501
+ // doesn't type it on the Invoice object, hence the narrow read.
502
+ const alreadyOnInvoice =
503
+ (fresh as { application_fee_amount?: number | null }).application_fee_amount;
504
+ if (freshMeta.bsFeeApplied || alreadyOnInvoice != null) {
505
+ return undefined;
506
+ }
507
+ // Our own reversal already ran on a prior delivery (idempotency across retries
508
+ // beyond Stripe's idempotency-key window).
509
+ if (freshMeta.bsFeeCollected) {
510
+ const prior = Number(freshMeta.bsFeeAmount);
511
+ return Number.isFinite(prior) && prior > 0 ? prior : undefined;
512
+ }
513
+
514
+ let config: PlatformFeeConfig;
515
+ try {
516
+ config = JSON.parse(subMeta.bsFeeConfig) as PlatformFeeConfig;
517
+ } catch {
518
+ return undefined; // malformed marker — a retry can't fix it
519
+ }
520
+
521
+ const fee = computeFee(fresh.amount_paid, config).feeAmount;
522
+ // A shape-invalid config yields NaN; never send a non-finite reversal.
523
+ if (!Number.isFinite(fee) || fee <= 0) return undefined;
524
+
525
+ // Resolve the charge that paid this invoice and its automatic destination
526
+ // transfer (same resolution as the recurring split path).
527
+ const payments = await whCtx.stripe.invoicePayments.list({
528
+ invoice: invoice.id,
529
+ limit: 1,
530
+ });
531
+ const payment = payments.data?.[0]?.payment;
532
+ let chargeId: string | undefined;
533
+ if (payment?.charge) {
534
+ chargeId =
535
+ typeof payment.charge === "string" ? payment.charge : payment.charge.id;
536
+ } else if (payment?.payment_intent) {
537
+ const piId =
538
+ typeof payment.payment_intent === "string"
539
+ ? payment.payment_intent
540
+ : payment.payment_intent.id;
541
+ const pi = await whCtx.stripe.paymentIntents.retrieve(piId);
542
+ chargeId =
543
+ typeof pi.latest_charge === "string"
544
+ ? pi.latest_charge
545
+ : (pi.latest_charge?.id ?? undefined);
546
+ }
547
+ if (!chargeId) {
548
+ // A paid invoice should have a charge; its absence may be propagation lag, so
549
+ // throw to retry rather than silently skip the fee.
550
+ throw new Error(
551
+ `First-invoice fee: paid invoice ${invoice.id} for per_invoice subscription ${subId} has no resolvable charge`,
552
+ );
553
+ }
554
+ const charge = await whCtx.stripe.charges.retrieve(chargeId);
555
+ const transferId =
556
+ typeof charge.transfer === "string"
557
+ ? charge.transfer
558
+ : (charge.transfer?.id ?? undefined);
559
+ if (!transferId) {
560
+ // A per_invoice sub is a destination charge, so the charge should carry an
561
+ // automatic transfer. Its absence is a config anomaly, not a transient
562
+ // fault — rethrowing would loop the event `failed` forever. Log and skip.
563
+ console.error(
564
+ `[better-stripe] applyFirstInvoiceFee: invoice ${invoice.id} charge ${chargeId} has no destination transfer to reverse`,
565
+ );
566
+ return undefined;
567
+ }
568
+
569
+ // BTS-69: adopt an existing reversal we already created for THIS invoice as the
570
+ // idempotency source of truth, rather than trusting the live-recomputed amount.
571
+ // The `bsFeeCollected` marker write below can fail AFTER the reversal succeeds;
572
+ // if `bsFeeConfig` is then edited and a retry lands past Stripe's ≤24h
573
+ // idempotency-key window, a recomputed (drifted) amount would create a SECOND
574
+ // reversal — double collection. The reversal's own `bsFeeFor:<invoiceId>` tag
575
+ // survives both the marker-write failure and the key TTL, so finding it means
576
+ // "already collected": re-record the marker with the actually-reversed amount
577
+ // and return without reversing again.
578
+ const priorReversals = await whCtx.stripe.transfers.listReversals(transferId, {
579
+ limit: 100,
580
+ });
581
+ const adopted = priorReversals.data.find(
582
+ (r) => r.metadata?.bsFeeFor === invoice.id,
583
+ );
584
+ if (adopted) {
585
+ await whCtx.stripe.invoices.update(invoice.id, {
586
+ metadata: {
587
+ ...freshMeta,
588
+ bsFeeCollected: "1",
589
+ bsFeeAmount: String(adopted.amount),
590
+ },
591
+ });
592
+ return adopted.amount;
593
+ }
594
+
595
+ await whCtx.stripe.transfers.createReversal(
596
+ transferId,
597
+ { amount: fee, metadata: { bsFeeFor: invoice.id } },
598
+ { idempotencyKey: `bs_infee_${invoice.id}` },
599
+ );
600
+ // Invoice metadata is editable post-finalization (only monetary values lock),
601
+ // so the marker records that the missed fee is now collected. A mark failure
602
+ // after a successful reversal propagates: the retry replays the reversal
603
+ // against the same idempotency key (no second money movement) then completes
604
+ // the mark.
605
+ await whCtx.stripe.invoices.update(invoice.id, {
606
+ metadata: { ...freshMeta, bsFeeCollected: "1", bsFeeAmount: String(fee) },
607
+ });
608
+ return fee;
609
+ }
610
+
611
+ /**
612
+ * Collect a deferred platform fee for a one-time destination charge (BTS-60).
613
+ * When the final amount is unknowable at session creation (discounts, custom
614
+ * amounts), checkout flags the PaymentIntent with `bsFeeMode=per_charge` +
615
+ * `bsFeeConfig`. An `application_fee_amount` can't be attached after the PI
616
+ * succeeds, so the fee is realized the way Stripe itself settles application
617
+ * fees on destination charges — by pulling funds back from the connected
618
+ * account: a partial reversal of the automatic transfer, sized from the amount
619
+ * actually charged (never the session's list amount). Idempotent via a
620
+ * `bsFeeCollected` marker read off a freshly-retrieved PI (the event payload is
621
+ * a stale snapshot on retries) plus a deterministic Stripe idempotency key.
622
+ *
623
+ * Failure contract: genuine collection failures (a retrieve/reversal/mark API
624
+ * error) PROPAGATE, so the handler marks the event `failed` and Stripe retries
625
+ * — a swallowed error would 200 and mark the event `processed` (terminal),
626
+ * silently losing the fee forever. Re-runs converge: the fresh-PI marker skips
627
+ * completed collections, the idempotency key replays an unmarked reversal
628
+ * without moving money twice (inputs are immutable post-success, so the params
629
+ * are identical), and the downstream payment upsert / split engine are
630
+ * idempotent. Benign skips a retry can't fix (unflagged PI, malformed config,
631
+ * zero fee, no destination transfer) return undefined without throwing.
632
+ *
633
+ * Documented limitations (both shared with the up-front and per_invoice
634
+ * paths): a fee config's `fixed`/tier bounds are minor units in the session's
635
+ * assumed currency — they are not converted if the charge settles in another
636
+ * currency; and an app that injects `transfer_data.amount` via
637
+ * `sessionOverrides` while relying on per_charge deferral could make the fee
638
+ * exceed the transfer's remainder, which fails the reversal (→ retry/alert)
639
+ * rather than over-reversing.
640
+ *
641
+ * Returns the fee collected — now or on a prior delivery — so the caller can
642
+ * denormalize `feeCollectedAmount` onto the payments row.
643
+ */
644
+ async function applyPerChargeFee(
645
+ whCtx: WebhookContext,
646
+ paymentIntent: Stripe.PaymentIntent,
647
+ ): Promise<number | undefined> {
648
+ if (paymentIntent.status !== "succeeded") return undefined;
649
+ const meta = (paymentIntent.metadata ?? {}) as Record<string, string>;
650
+ if (meta.bsFeeMode !== "per_charge" || !meta.bsFeeConfig) return undefined;
651
+
652
+ const fresh = await whCtx.stripe.paymentIntents.retrieve(paymentIntent.id);
653
+ const freshMeta = (fresh.metadata ?? {}) as Record<string, string>;
654
+ if (freshMeta.bsFeeCollected) {
655
+ const prior = Number(freshMeta.bsFeeAmount);
656
+ return Number.isFinite(prior) && prior > 0 ? prior : undefined;
657
+ }
658
+
659
+ let config: PlatformFeeConfig;
660
+ try {
661
+ config = JSON.parse(
662
+ freshMeta.bsFeeConfig ?? meta.bsFeeConfig,
663
+ ) as PlatformFeeConfig;
664
+ } catch {
665
+ return undefined; // malformed marker — a retry can't fix it
666
+ }
667
+
668
+ const amount = fresh.amount_received ?? paymentIntent.amount;
669
+ const fee = computeFee(amount, config).feeAmount;
670
+ // A shape-invalid config yields NaN; never send a non-finite reversal.
671
+ if (!Number.isFinite(fee) || fee <= 0) return undefined;
672
+
673
+ // Resolve the automatic transfer `transfer_data` created on the charge.
674
+ const chargeId =
675
+ typeof fresh.latest_charge === "string"
676
+ ? fresh.latest_charge
677
+ : (fresh.latest_charge?.id ?? undefined);
678
+ if (!chargeId) return undefined;
679
+ const charge = await whCtx.stripe.charges.retrieve(chargeId);
680
+ const transferId =
681
+ typeof charge.transfer === "string"
682
+ ? charge.transfer
683
+ : (charge.transfer?.id ?? undefined);
684
+ if (!transferId) {
685
+ // Config anomaly, not a transient fault — rethrowing would loop the event
686
+ // `failed` forever. Log and record the sale without a fee.
687
+ console.error(
688
+ `[better-stripe] applyPerChargeFee: per_charge PI ${paymentIntent.id} has no destination transfer to reverse`,
689
+ );
690
+ return undefined;
691
+ }
692
+
693
+ await whCtx.stripe.transfers.createReversal(
694
+ transferId,
695
+ { amount: fee, metadata: { bsFeeFor: paymentIntent.id } },
696
+ { idempotencyKey: `bs_pcfee_${paymentIntent.id}` },
697
+ );
698
+ // A mark failure after a successful reversal also propagates: the retry
699
+ // replays the reversal against the same idempotency key (no second money
700
+ // movement) and then completes the mark + payments-row denormalization.
701
+ await whCtx.stripe.paymentIntents.update(paymentIntent.id, {
702
+ metadata: { ...freshMeta, bsFeeCollected: "1", bsFeeAmount: String(fee) },
703
+ });
704
+ return fee;
705
+ }
706
+
707
+ async function upsertInvoiceFromStripe(
708
+ whCtx: WebhookContext,
709
+ invoice: Stripe.Invoice,
710
+ ): Promise<void> {
711
+ const { userId, orgId } = extractIdentifiers(
712
+ invoice.metadata as Record<string, string> | null,
713
+ );
714
+
715
+ const parentSub = invoice.parent?.subscription_details?.subscription;
716
+ const subscriptionId =
717
+ typeof parentSub === "string" ? parentSub : (parentSub?.id ?? undefined);
718
+
719
+ await dispatchUpsert(whCtx, "invoiceUpserted", {
720
+ stripeInvoiceId: invoice.id!,
721
+ userId,
722
+ orgId,
723
+ accountId: resolveOwnerAccount(invoice) ?? undefined,
724
+ subscriptionId,
725
+ status: invoice.status ?? "draft",
726
+ currency: invoice.currency!,
727
+ amountDue: invoice.amount_due,
728
+ amountPaid: invoice.amount_paid,
729
+ hostedInvoiceUrl: invoice.hosted_invoice_url ?? undefined,
730
+ invoicePdf: invoice.invoice_pdf ?? undefined,
731
+ periodStart: epochToIso(invoice.period_start),
732
+ periodEnd: epochToIso(invoice.period_end),
733
+ // Smart-retry dunning (BTS-33): surface Stripe's retry schedule so a
734
+ // dunning hook can tell the buyer when the next attempt lands.
735
+ nextPaymentAttempt: epochToIso(invoice.next_payment_attempt),
736
+ attemptCount: invoice.attempt_count ?? undefined,
737
+ metadata: invoice.metadata ?? undefined,
738
+ });
739
+ }
740
+
741
+ /**
742
+ * Drive the split transfer engine (BTS-22) for a separate-charges sale. When a
743
+ * PaymentIntent created with `bsChargeType=separate` succeeds, parse the split
744
+ * (and platform fee) from its metadata and fan funds out to each recipient via
745
+ * `source_transaction` on the resulting charge. Errors propagate so Stripe
746
+ * retries; the engine's idempotency keys make retries safe.
747
+ */
748
+ async function handleSplitTransfers(
749
+ whCtx: WebhookContext,
750
+ paymentIntent: Stripe.PaymentIntent,
751
+ ): Promise<void> {
752
+ if (paymentIntent.status !== "succeeded") return;
753
+ const meta = (paymentIntent.metadata ?? {}) as Record<string, string>;
754
+ // Not a split sale — nothing to do.
755
+ if (meta.bsChargeType !== "separate" || !meta.bsSplit) return;
756
+
757
+ // From here the PI IS a separate-charges sale, so a missing charge or
758
+ // malformed split is a real failure: throw so the webhook returns 500 and
759
+ // Stripe retries (visible + recoverable) rather than silently skipping payouts.
760
+ const sourceChargeId =
761
+ typeof paymentIntent.latest_charge === "string"
762
+ ? paymentIntent.latest_charge
763
+ : (paymentIntent.latest_charge?.id ?? undefined);
764
+ if (!sourceChargeId) {
765
+ throw new Error(
766
+ `Split-transfer sale ${paymentIntent.id} succeeded without a latest_charge; cannot create transfers`,
767
+ );
768
+ }
769
+
770
+ let split: SplitRecipient[];
771
+ let feeConfig: PlatformFeeConfig | undefined;
772
+ try {
773
+ split = JSON.parse(meta.bsSplit) as SplitRecipient[];
774
+ feeConfig = meta.bsFeeConfig
775
+ ? (JSON.parse(meta.bsFeeConfig) as PlatformFeeConfig)
776
+ : undefined;
777
+ } catch (err) {
778
+ throw new Error(
779
+ `Split-transfer sale ${paymentIntent.id} has malformed bsSplit/bsFeeConfig metadata: ${String(err)}`,
780
+ );
781
+ }
782
+
783
+ await createSplitTransfers(whCtx.stripe, whCtx.component, whCtx.ctx, {
784
+ sourceChargeId,
785
+ amount: paymentIntent.amount,
786
+ currency: paymentIntent.currency,
787
+ split,
788
+ feeConfig,
789
+ paymentId: paymentIntent.id,
790
+ });
791
+ }
792
+
793
+ /**
794
+ * Drive the split transfer engine for a **recurring** separate-charges sale
795
+ * (BTS-52). On each `invoice.paid` for a subscription flagged
796
+ * `bsChargeType=separate` (markers live on the subscription), resolve this
797
+ * invoice's charge and fan funds out to the recipients — so an affiliate-referred
798
+ * subscription splits every billing cycle. Each cycle has a distinct charge, so
799
+ * the ledger keys per-charge and cycles don't collide. Errors propagate so
800
+ * Stripe retries; the engine's idempotency keeps retries safe.
801
+ */
802
+ async function handleInvoiceSplitTransfers(
803
+ whCtx: WebhookContext,
804
+ invoice: Stripe.Invoice,
805
+ ): Promise<void> {
806
+ // Nothing to split when no money was collected (e.g. 100%-off coupon, account
807
+ // credit, or proration). Skip before any charge resolution so a zero-amount
808
+ // invoice — which has no charge — can't throw and force endless retries.
809
+ if (!(invoice.amount_paid > 0)) return;
810
+
811
+ const parentSub = invoice.parent?.subscription_details?.subscription;
812
+ const subId =
813
+ typeof parentSub === "string" ? parentSub : (parentSub?.id ?? undefined);
814
+ if (!subId) return; // not a subscription invoice
815
+
816
+ const sub = await whCtx.stripe.subscriptions.retrieve(subId);
817
+ const meta = (sub?.metadata ?? {}) as Record<string, string>;
818
+ if (meta.bsChargeType !== "separate" || !meta.bsSplit) return;
819
+
820
+ let split: SplitRecipient[];
821
+ let feeConfig: PlatformFeeConfig | undefined;
822
+ try {
823
+ split = JSON.parse(meta.bsSplit) as SplitRecipient[];
824
+ feeConfig = meta.bsFeeConfig
825
+ ? (JSON.parse(meta.bsFeeConfig) as PlatformFeeConfig)
826
+ : undefined;
827
+ } catch (err) {
828
+ throw new Error(
829
+ `Subscription ${subId} has malformed bsSplit/bsFeeConfig metadata: ${String(err)}`,
830
+ );
831
+ }
832
+
833
+ // Resolve the charge that paid this invoice (source_transaction for transfers).
834
+ const payments = await whCtx.stripe.invoicePayments.list({
835
+ invoice: invoice.id!,
836
+ limit: 1,
837
+ });
838
+ const payment = payments.data?.[0]?.payment;
839
+ let chargeId: string | undefined;
840
+ if (payment?.charge) {
841
+ chargeId =
842
+ typeof payment.charge === "string" ? payment.charge : payment.charge.id;
843
+ } else if (payment?.payment_intent) {
844
+ const piId =
845
+ typeof payment.payment_intent === "string"
846
+ ? payment.payment_intent
847
+ : payment.payment_intent.id;
848
+ const pi = await whCtx.stripe.paymentIntents.retrieve(piId);
849
+ chargeId =
850
+ typeof pi.latest_charge === "string"
851
+ ? pi.latest_charge
852
+ : (pi.latest_charge?.id ?? undefined);
853
+ }
854
+ if (!chargeId) {
855
+ throw new Error(
856
+ `Paid invoice ${invoice.id} for split subscription ${subId} has no resolvable charge; cannot create transfers`,
857
+ );
858
+ }
859
+
860
+ await createSplitTransfers(whCtx.stripe, whCtx.component, whCtx.ctx, {
861
+ sourceChargeId: chargeId,
862
+ amount: invoice.amount_paid,
863
+ currency: invoice.currency,
864
+ split,
865
+ feeConfig,
866
+ });
867
+ }
868
+
869
+ async function upsertPaymentFromStripe(
870
+ whCtx: WebhookContext,
871
+ paymentIntent: Stripe.PaymentIntent,
872
+ perChargeFee?: number,
873
+ ): Promise<void> {
874
+ const { userId, orgId } = extractIdentifiers(
875
+ paymentIntent.metadata as Record<string, string> | null,
876
+ );
877
+
878
+ const statusMap: Record<string, string> = {
879
+ succeeded: "succeeded",
880
+ canceled: "canceled",
881
+ processing: "processing",
882
+ requires_action: "requires_action",
883
+ requires_confirmation: "requires_action",
884
+ requires_payment_method: "requires_action",
885
+ requires_capture: "requires_action",
886
+ };
887
+ const status = (statusMap[paymentIntent.status] ?? "failed") as
888
+ | "succeeded"
889
+ | "failed"
890
+ | "canceled"
891
+ | "processing"
892
+ | "requires_action";
893
+
894
+ await dispatchUpsert(whCtx, "paymentUpserted", {
895
+ stripePaymentIntentId: paymentIntent.id,
896
+ userId,
897
+ orgId,
898
+ accountId: resolveOwnerAccount(paymentIntent) ?? undefined,
899
+ amount: paymentIntent.amount,
900
+ currency: paymentIntent.currency,
901
+ status,
902
+ // Only a succeeded intent actually collected the fee. Failed/canceled
903
+ // intents can still carry transfer_data/application_fee_amount, so don't
904
+ // persist fee/routing for them.
905
+ ...(paymentIntent.status === "succeeded"
906
+ ? feeRoutingFromPaymentIntent(paymentIntent)
907
+ : {}),
908
+ // A per-charge fee is collected via transfer reversal (BTS-60), so it never
909
+ // appears as application_fee_amount on the intent — merge it in directly.
910
+ ...(perChargeFee !== undefined ? { feeCollectedAmount: perChargeFee } : {}),
911
+ metadata: paymentIntent.metadata ?? undefined,
912
+ });
913
+ }
914
+
915
+ async function handlePayoutEvent(
916
+ whCtx: WebhookContext,
917
+ payout: Stripe.Payout,
918
+ ): Promise<void> {
919
+ await dispatchUpsert(whCtx, "payoutUpserted", {
920
+ stripePayoutId: payout.id,
921
+ accountId:
922
+ typeof payout.destination === "string"
923
+ ? payout.destination
924
+ : (payout.destination?.id ?? ""),
925
+ amount: payout.amount,
926
+ currency: payout.currency,
927
+ status: payout.status as
928
+ | "pending"
929
+ | "paid"
930
+ | "failed"
931
+ | "canceled"
932
+ | "in_transit",
933
+ arrivalDate: epochToIso(payout.arrival_date),
934
+ method: payout.method ?? undefined,
935
+ metadata: payout.metadata ?? undefined,
936
+ });
937
+ }
938
+
939
+ // Stripe types Refund.status as `string | null`; clamp to the documented union.
940
+ const REFUND_STATUSES = new Set([
941
+ "pending",
942
+ "requires_action",
943
+ "succeeded",
944
+ "failed",
945
+ "canceled",
946
+ ]);
947
+ const REFUND_REASONS = new Set([
948
+ "duplicate",
949
+ "fraudulent",
950
+ "requested_by_customer",
951
+ "expired_uncaptured_charge",
952
+ ]);
953
+
954
+ async function handleRefundEvent(
955
+ whCtx: WebhookContext,
956
+ refund: Stripe.Refund,
957
+ ): Promise<void> {
958
+ const paymentIntentId =
959
+ typeof refund.payment_intent === "string"
960
+ ? refund.payment_intent
961
+ : (refund.payment_intent?.id ?? undefined);
962
+ const chargeId =
963
+ typeof refund.charge === "string"
964
+ ? refund.charge
965
+ : (refund.charge?.id ?? undefined);
966
+
967
+ const status =
968
+ refund.status && REFUND_STATUSES.has(refund.status)
969
+ ? refund.status
970
+ : "pending";
971
+ const reason =
972
+ refund.reason && REFUND_REASONS.has(refund.reason)
973
+ ? refund.reason
974
+ : undefined;
975
+
976
+ await dispatchUpsert(whCtx, "refundUpserted", {
977
+ stripeRefundId: refund.id,
978
+ stripePaymentIntentId: paymentIntentId,
979
+ stripeChargeId: chargeId,
980
+ amount: refund.amount,
981
+ currency: refund.currency,
982
+ status,
983
+ reason,
984
+ failureReason: refund.failure_reason ?? undefined,
985
+ metadata: refund.metadata ?? undefined,
986
+ });
987
+
988
+ // Split-sale clawback (BTS-34): when a separate-charges sale is refunded,
989
+ // pull the refunded share back from each recipient pro-rata. Only ledger
990
+ // legs identify a split sale — destination-charge auto-transfers are not in
991
+ // the ledger and are handled by Stripe-native `reverse_transfer` at refund
992
+ // creation. Runs on `refund.updated` too so a pending→succeeded refund
993
+ // (e.g. ACH) still claws back. Errors propagate → event `failed` → Stripe
994
+ // retries; `reverseTransfersForRefund`'s delta-to-target math makes the
995
+ // re-run converge without double-reversing.
996
+ if (status !== "succeeded" || !chargeId) return;
997
+ const legs = ((await whCtx.ctx.runQuery(
998
+ componentRef(whCtx.component, "connect/queries/listTransfersByCharge"),
999
+ { sourceChargeId: chargeId },
1000
+ )) ?? []) as unknown[];
1001
+ if (legs.length === 0) return; // not a split sale
1002
+
1003
+ // Fresh charge read for the authoritative cumulative amount_refunded.
1004
+ const charge = await whCtx.stripe.charges.retrieve(chargeId);
1005
+ await reverseTransfersForRefund(whCtx.stripe, whCtx.component, whCtx.ctx, {
1006
+ sourceChargeId: chargeId,
1007
+ refundId: refund.id,
1008
+ chargeAmount: charge.amount,
1009
+ amountRefunded: charge.amount_refunded ?? refund.amount,
1010
+ });
1011
+ }
1012
+
1013
+ /**
1014
+ * Denormalize fee-refund state from `application_fee.refunded` (BTS-34, folded
1015
+ * in from BTS-51): set the linked payment's `feeRefundedAmount` and correct
1016
+ * `feeCollectedAmount` to the net fee kept. Values are Stripe's ABSOLUTE
1017
+ * cumulative totals — this handler never increments, so event redeliveries and
1018
+ * `createRefund(refundApplicationFee: true)`-triggered duplicates can't
1019
+ * double-count. Benign skips (no charge, no payment intent, no payment row)
1020
+ * return quietly; lookup/mutation failures propagate so the event retries.
1021
+ */
1022
+ async function handleApplicationFeeRefunded(
1023
+ whCtx: WebhookContext,
1024
+ fee: Stripe.ApplicationFee,
1025
+ ): Promise<void> {
1026
+ const chargeId =
1027
+ typeof fee.charge === "string" ? fee.charge : (fee.charge?.id ?? undefined);
1028
+ if (!chargeId) return;
1029
+
1030
+ const charge = await whCtx.stripe.charges.retrieve(chargeId);
1031
+ const paymentIntentId =
1032
+ typeof charge.payment_intent === "string"
1033
+ ? charge.payment_intent
1034
+ : (charge.payment_intent?.id ?? undefined);
1035
+ if (!paymentIntentId) return;
1036
+
1037
+ await whCtx.ctx.runMutation(
1038
+ componentRef(whCtx.component, "connect/mutations/recordPaymentFeeRefund"),
1039
+ {
1040
+ stripePaymentIntentId: paymentIntentId,
1041
+ feeCollectedAmount: Math.max(0, fee.amount - fee.amount_refunded),
1042
+ feeRefundedAmount: fee.amount_refunded,
1043
+ },
1044
+ );
1045
+ }
1046
+
1047
+ async function handleDisputeEvent(
1048
+ whCtx: WebhookContext,
1049
+ dispute: Stripe.Dispute,
1050
+ lastEvent: string,
1051
+ ): Promise<void> {
1052
+ const paymentIntentId =
1053
+ typeof dispute.payment_intent === "string"
1054
+ ? dispute.payment_intent
1055
+ : (dispute.payment_intent?.id ?? undefined);
1056
+ const chargeId =
1057
+ typeof dispute.charge === "string"
1058
+ ? dispute.charge
1059
+ : (dispute.charge?.id ?? undefined);
1060
+
1061
+ // Capture the statement descriptor the buyer saw (dispute context) from the
1062
+ // charge — the Dispute object doesn't carry it. Only on `created`, and
1063
+ // best-effort: this is optional metadata, so a transient charge-lookup failure
1064
+ // must never abort the critical dispute side effects (upsert, clawback, cancel).
1065
+ let statementDescriptor: string | undefined;
1066
+ if (lastEvent === "created" && chargeId) {
1067
+ try {
1068
+ const charge = await whCtx.stripe.charges.retrieve(chargeId);
1069
+ statementDescriptor =
1070
+ charge?.calculated_statement_descriptor ??
1071
+ charge?.statement_descriptor ??
1072
+ undefined;
1073
+ } catch {
1074
+ // leave undefined; the descriptor is non-essential context
1075
+ }
1076
+ }
1077
+
1078
+ await dispatchUpsert(whCtx, "disputeUpserted", {
1079
+ stripeDisputeId: dispute.id,
1080
+ stripePaymentIntentId: paymentIntentId,
1081
+ stripeChargeId: chargeId,
1082
+ amount: dispute.amount,
1083
+ currency: dispute.currency,
1084
+ // Stripe.Dispute.Status is exactly the component's disputeStatusValidator union.
1085
+ status: dispute.status,
1086
+ reason: dispute.reason,
1087
+ isChargeRefundable: dispute.is_charge_refundable,
1088
+ evidenceDueBy: epochToIso(dispute.evidence_details?.due_by ?? undefined),
1089
+ ...(statementDescriptor ? { statementDescriptor } : {}),
1090
+ lastEvent,
1091
+ metadata: dispute.metadata ?? undefined,
1092
+ });
1093
+
1094
+ // Clawback (BTS-27): when a dispute is first opened, reverse the transfers
1095
+ // funded by the disputed charge pro-rata to the disputed amount, so recipients
1096
+ // bear their share (losses_collector=application leaves the platform with the
1097
+ // rest). Idempotent via the dispute id; reinstated by BTS-29 if the dispute is
1098
+ // won. Only on `created` — other dispute events don't move funds here.
1099
+ if (lastEvent === "created" && chargeId) {
1100
+ await reverseTransfers(whCtx.stripe, whCtx.component, whCtx.ctx, {
1101
+ sourceChargeId: chargeId,
1102
+ amount: dispute.amount,
1103
+ operationId: dispute.id,
1104
+ });
1105
+ }
1106
+
1107
+ // Reinstatement (BTS-29): when the dispute is won (or funds are explicitly
1108
+ // reinstated), pay recipients back the amounts clawed back on `created`.
1109
+ const isWon =
1110
+ lastEvent === "funds_reinstated" ||
1111
+ (lastEvent === "closed" && dispute.status === "won");
1112
+ if (isWon && chargeId) {
1113
+ await reinstateTransfers(whCtx.stripe, whCtx.component, whCtx.ctx, {
1114
+ sourceChargeId: chargeId,
1115
+ operationId: dispute.id,
1116
+ currency: dispute.currency,
1117
+ });
1118
+ }
1119
+
1120
+ // Auto-cancel the disputed subscription (BTS-28, default on). Resolve the
1121
+ // subscription from the dispute's PaymentIntent (invoice payment → invoice →
1122
+ // subscription) and cancel it. The resulting subscription.updated/deleted
1123
+ // webhook fires the app's subscription trigger to revoke access (Skool model:
1124
+ // cancel now, remove at cycle end).
1125
+ if (lastEvent === "created" && whCtx.config?.autoCancelOnDispute !== false) {
1126
+ await cancelDisputedSubscription(whCtx, dispute);
1127
+ }
1128
+ }
1129
+
1130
+ async function cancelDisputedSubscription(
1131
+ whCtx: WebhookContext,
1132
+ dispute: Stripe.Dispute,
1133
+ ): Promise<void> {
1134
+ const piId =
1135
+ typeof dispute.payment_intent === "string"
1136
+ ? dispute.payment_intent
1137
+ : (dispute.payment_intent?.id ?? undefined);
1138
+ if (!piId) return;
1139
+
1140
+ const payments = await whCtx.stripe.invoicePayments.list({
1141
+ payment: { type: "payment_intent", payment_intent: piId },
1142
+ limit: 1,
1143
+ });
1144
+ const invoiceRef = payments.data?.[0]?.invoice;
1145
+ const invoiceId =
1146
+ typeof invoiceRef === "string" ? invoiceRef : (invoiceRef?.id ?? undefined);
1147
+ if (!invoiceId) return; // not a subscription invoice charge
1148
+
1149
+ const invoice = await whCtx.stripe.invoices.retrieve(invoiceId);
1150
+ const parentSub = invoice.parent?.subscription_details?.subscription;
1151
+ const subId =
1152
+ typeof parentSub === "string" ? parentSub : (parentSub?.id ?? undefined);
1153
+ if (!subId) return;
1154
+
1155
+ // Stable idempotency key so a webhook retry can't double-write the cancel.
1156
+ const idempotency = { idempotencyKey: `bs_dispute_cancel_${dispute.id}` };
1157
+ if (whCtx.config?.cancelDisputedSubscriptionImmediately) {
1158
+ await whCtx.stripe.subscriptions.cancel(subId, undefined, idempotency);
1159
+ } else {
1160
+ await whCtx.stripe.subscriptions.update(
1161
+ subId,
1162
+ { cancel_at_period_end: true },
1163
+ idempotency,
1164
+ );
1165
+ }
1166
+ }