@owlmeans/server-payment 0.1.18-rc.9 → 0.1.18

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 (537) hide show
  1. package/README.md +157 -26
  2. package/agent-meta/manifest.json +30 -4
  3. package/agent-meta/skills/server-payment/SKILL.md +613 -54
  4. package/agent-meta/skills/server-payment/parts/reference.md +174 -0
  5. package/build/access/types.d.ts +46 -0
  6. package/build/access/types.d.ts.map +1 -0
  7. package/build/access/types.js +2 -0
  8. package/build/access/types.js.map +1 -0
  9. package/build/access.d.ts +6 -0
  10. package/build/access.d.ts.map +1 -0
  11. package/build/access.js +45 -0
  12. package/build/access.js.map +1 -0
  13. package/build/actions/index.d.ts +1 -0
  14. package/build/actions/index.d.ts.map +1 -1
  15. package/build/actions/index.js +1 -0
  16. package/build/actions/index.js.map +1 -1
  17. package/build/actions/resync-subscriptions.d.ts +3 -0
  18. package/build/actions/resync-subscriptions.d.ts.map +1 -0
  19. package/build/actions/resync-subscriptions.js +7 -0
  20. package/build/actions/resync-subscriptions.js.map +1 -0
  21. package/build/actions/resync.d.ts +6 -1
  22. package/build/actions/resync.d.ts.map +1 -1
  23. package/build/actions/resync.js +15 -5
  24. package/build/actions/resync.js.map +1 -1
  25. package/build/actions/webhook.d.ts +2 -1
  26. package/build/actions/webhook.d.ts.map +1 -1
  27. package/build/actions/webhook.js +10 -4
  28. package/build/actions/webhook.js.map +1 -1
  29. package/build/bootstrap/types.d.ts +16 -0
  30. package/build/bootstrap/types.d.ts.map +1 -0
  31. package/build/bootstrap/types.js +2 -0
  32. package/build/bootstrap/types.js.map +1 -0
  33. package/build/bootstrap.d.ts +6 -0
  34. package/build/bootstrap.d.ts.map +1 -0
  35. package/build/bootstrap.js +26 -0
  36. package/build/bootstrap.js.map +1 -0
  37. package/build/catalogue/types.d.ts +38 -0
  38. package/build/catalogue/types.d.ts.map +1 -0
  39. package/build/catalogue/types.js +2 -0
  40. package/build/catalogue/types.js.map +1 -0
  41. package/build/catalogue.d.ts +6 -0
  42. package/build/catalogue.d.ts.map +1 -0
  43. package/build/catalogue.js +110 -0
  44. package/build/catalogue.js.map +1 -0
  45. package/build/commit/types.d.ts +22 -0
  46. package/build/commit/types.d.ts.map +1 -0
  47. package/build/commit/types.js +2 -0
  48. package/build/commit/types.js.map +1 -0
  49. package/build/commit.d.ts +6 -0
  50. package/build/commit.d.ts.map +1 -0
  51. package/build/commit.js +125 -0
  52. package/build/commit.js.map +1 -0
  53. package/build/config.d.ts +44 -5
  54. package/build/config.d.ts.map +1 -1
  55. package/build/config.js +216 -10
  56. package/build/config.js.map +1 -1
  57. package/build/consts.d.ts +74 -16
  58. package/build/consts.d.ts.map +1 -1
  59. package/build/consts.js +86 -23
  60. package/build/consts.js.map +1 -1
  61. package/build/consts.local.d.ts +94 -0
  62. package/build/consts.local.d.ts.map +1 -0
  63. package/build/consts.local.js +44 -0
  64. package/build/consts.local.js.map +1 -0
  65. package/build/consumer/cancellation/types.d.ts +11 -0
  66. package/build/consumer/cancellation/types.d.ts.map +1 -0
  67. package/build/consumer/cancellation/types.js +2 -0
  68. package/build/consumer/cancellation/types.js.map +1 -0
  69. package/build/consumer/cancellation.d.ts +6 -0
  70. package/build/consumer/cancellation.d.ts.map +1 -0
  71. package/build/consumer/cancellation.js +33 -0
  72. package/build/consumer/cancellation.js.map +1 -0
  73. package/build/consumer/capture/types.d.ts +50 -0
  74. package/build/consumer/capture/types.d.ts.map +1 -0
  75. package/build/consumer/capture/types.js +2 -0
  76. package/build/consumer/capture/types.js.map +1 -0
  77. package/build/consumer/capture.d.ts +6 -0
  78. package/build/consumer/capture.d.ts.map +1 -0
  79. package/build/consumer/capture.js +284 -0
  80. package/build/consumer/capture.js.map +1 -0
  81. package/build/consumer/consts.local.d.ts +10 -0
  82. package/build/consumer/consts.local.d.ts.map +1 -0
  83. package/build/consumer/consts.local.js +11 -0
  84. package/build/consumer/consts.local.js.map +1 -0
  85. package/build/consumer/format/types.d.ts +30 -0
  86. package/build/consumer/format/types.d.ts.map +1 -0
  87. package/build/consumer/format/types.js +2 -0
  88. package/build/consumer/format/types.js.map +1 -0
  89. package/build/consumer/format.d.ts +4 -0
  90. package/build/consumer/format.d.ts.map +1 -0
  91. package/build/consumer/format.js +73 -0
  92. package/build/consumer/format.js.map +1 -0
  93. package/build/consumer/handlers.d.ts +21 -0
  94. package/build/consumer/handlers.d.ts.map +1 -0
  95. package/build/consumer/handlers.js +174 -0
  96. package/build/consumer/handlers.js.map +1 -0
  97. package/build/consumer/index.d.ts +10 -0
  98. package/build/consumer/index.d.ts.map +1 -0
  99. package/build/consumer/index.js +6 -0
  100. package/build/consumer/index.js.map +1 -0
  101. package/build/consumer/mail/types.d.ts +29 -0
  102. package/build/consumer/mail/types.d.ts.map +1 -0
  103. package/build/consumer/mail/types.js +2 -0
  104. package/build/consumer/mail/types.js.map +1 -0
  105. package/build/consumer/mail.d.ts +6 -0
  106. package/build/consumer/mail.d.ts.map +1 -0
  107. package/build/consumer/mail.js +313 -0
  108. package/build/consumer/mail.js.map +1 -0
  109. package/build/consumer/observers/types.d.ts +15 -0
  110. package/build/consumer/observers/types.d.ts.map +1 -0
  111. package/build/consumer/observers/types.js +2 -0
  112. package/build/consumer/observers/types.js.map +1 -0
  113. package/build/consumer/observers.d.ts +6 -0
  114. package/build/consumer/observers.d.ts.map +1 -0
  115. package/build/consumer/observers.js +74 -0
  116. package/build/consumer/observers.js.map +1 -0
  117. package/build/consumer/origin/types.d.ts +17 -0
  118. package/build/consumer/origin/types.d.ts.map +1 -0
  119. package/build/consumer/origin/types.js +2 -0
  120. package/build/consumer/origin/types.js.map +1 -0
  121. package/build/consumer/origin.d.ts +8 -0
  122. package/build/consumer/origin.d.ts.map +1 -0
  123. package/build/consumer/origin.js +43 -0
  124. package/build/consumer/origin.js.map +1 -0
  125. package/build/consumer/reconcile/types.d.ts +13 -0
  126. package/build/consumer/reconcile/types.d.ts.map +1 -0
  127. package/build/consumer/reconcile/types.js +2 -0
  128. package/build/consumer/reconcile/types.js.map +1 -0
  129. package/build/consumer/reconcile.d.ts +5 -0
  130. package/build/consumer/reconcile.d.ts.map +1 -0
  131. package/build/consumer/reconcile.js +320 -0
  132. package/build/consumer/reconcile.js.map +1 -0
  133. package/build/consumer/records/types.d.ts +66 -0
  134. package/build/consumer/records/types.d.ts.map +1 -0
  135. package/build/consumer/records/types.js +2 -0
  136. package/build/consumer/records/types.js.map +1 -0
  137. package/build/consumer/records.d.ts +6 -0
  138. package/build/consumer/records.d.ts.map +1 -0
  139. package/build/consumer/records.js +243 -0
  140. package/build/consumer/records.js.map +1 -0
  141. package/build/consumer/service.d.ts +28 -0
  142. package/build/consumer/service.d.ts.map +1 -0
  143. package/build/consumer/service.js +706 -0
  144. package/build/consumer/service.js.map +1 -0
  145. package/build/consumer/types.d.ts +84 -0
  146. package/build/consumer/types.d.ts.map +1 -0
  147. package/build/consumer/types.js +2 -0
  148. package/build/consumer/types.js.map +1 -0
  149. package/build/consumer/types.local.d.ts +26 -0
  150. package/build/consumer/types.local.d.ts.map +1 -0
  151. package/build/consumer/types.local.js +2 -0
  152. package/build/consumer/types.local.js.map +1 -0
  153. package/build/consumer/withdrawal/types.d.ts +36 -0
  154. package/build/consumer/withdrawal/types.d.ts.map +1 -0
  155. package/build/consumer/withdrawal/types.js +2 -0
  156. package/build/consumer/withdrawal/types.js.map +1 -0
  157. package/build/consumer/withdrawal.d.ts +6 -0
  158. package/build/consumer/withdrawal.d.ts.map +1 -0
  159. package/build/consumer/withdrawal.js +237 -0
  160. package/build/consumer/withdrawal.js.map +1 -0
  161. package/build/entitlement.d.ts +4 -0
  162. package/build/entitlement.d.ts.map +1 -0
  163. package/build/entitlement.js +72 -0
  164. package/build/entitlement.js.map +1 -0
  165. package/build/entrypoints.d.ts +19 -2
  166. package/build/entrypoints.d.ts.map +1 -1
  167. package/build/entrypoints.js +16 -4
  168. package/build/entrypoints.js.map +1 -1
  169. package/build/gate/request.d.ts +4 -0
  170. package/build/gate/request.d.ts.map +1 -0
  171. package/build/gate/request.js +17 -0
  172. package/build/gate/request.js.map +1 -0
  173. package/build/gate/types.d.ts +15 -0
  174. package/build/gate/types.d.ts.map +1 -0
  175. package/build/gate/types.js +2 -0
  176. package/build/gate/types.js.map +1 -0
  177. package/build/gate.d.ts +13 -9
  178. package/build/gate.d.ts.map +1 -1
  179. package/build/gate.js +36 -21
  180. package/build/gate.js.map +1 -1
  181. package/build/index.d.ts +50 -3
  182. package/build/index.d.ts.map +1 -1
  183. package/build/index.js +29 -3
  184. package/build/index.js.map +1 -1
  185. package/build/limit.d.ts +11 -0
  186. package/build/limit.d.ts.map +1 -0
  187. package/build/limit.js +48 -0
  188. package/build/limit.js.map +1 -0
  189. package/build/log.d.ts +3 -0
  190. package/build/log.d.ts.map +1 -0
  191. package/build/log.js +4 -0
  192. package/build/log.js.map +1 -0
  193. package/build/models/declarations/types.d.ts +22 -0
  194. package/build/models/declarations/types.d.ts.map +1 -0
  195. package/build/models/declarations/types.js +2 -0
  196. package/build/models/declarations/types.js.map +1 -0
  197. package/build/models/declarations.d.ts +4 -0
  198. package/build/models/declarations.d.ts.map +1 -0
  199. package/build/models/declarations.js +26 -0
  200. package/build/models/declarations.js.map +1 -0
  201. package/build/models/purchase/types.d.ts +13 -0
  202. package/build/models/purchase/types.d.ts.map +1 -0
  203. package/build/models/purchase/types.js +2 -0
  204. package/build/models/purchase/types.js.map +1 -0
  205. package/build/models/purchase.d.ts +4 -0
  206. package/build/models/purchase.d.ts.map +1 -0
  207. package/build/models/purchase.js +37 -0
  208. package/build/models/purchase.js.map +1 -0
  209. package/build/observer.d.ts +9 -0
  210. package/build/observer.d.ts.map +1 -1
  211. package/build/observer.js +38 -12
  212. package/build/observer.js.map +1 -1
  213. package/build/plan/types.d.ts +21 -0
  214. package/build/plan/types.d.ts.map +1 -0
  215. package/build/plan/types.js +2 -0
  216. package/build/plan/types.js.map +1 -0
  217. package/build/plan.d.ts +7 -0
  218. package/build/plan.d.ts.map +1 -0
  219. package/build/plan.js +29 -0
  220. package/build/plan.js.map +1 -0
  221. package/build/plugins/checkout-plugins/types.d.ts +25 -0
  222. package/build/plugins/checkout-plugins/types.d.ts.map +1 -0
  223. package/build/plugins/checkout-plugins/types.js +2 -0
  224. package/build/plugins/checkout-plugins/types.js.map +1 -0
  225. package/build/plugins/checkout-plugins.d.ts +12 -0
  226. package/build/plugins/checkout-plugins.d.ts.map +1 -0
  227. package/build/plugins/checkout-plugins.js +72 -0
  228. package/build/plugins/checkout-plugins.js.map +1 -0
  229. package/build/plugins/checkout-policy/types.d.ts +18 -0
  230. package/build/plugins/checkout-policy/types.d.ts.map +1 -0
  231. package/build/plugins/checkout-policy/types.js +2 -0
  232. package/build/plugins/checkout-policy/types.js.map +1 -0
  233. package/build/plugins/checkout-policy.d.ts +4 -0
  234. package/build/plugins/checkout-policy.d.ts.map +1 -0
  235. package/build/plugins/checkout-policy.js +26 -0
  236. package/build/plugins/checkout-policy.js.map +1 -0
  237. package/build/plugins/checkout-registry/types.d.ts +7 -0
  238. package/build/plugins/checkout-registry/types.d.ts.map +1 -0
  239. package/build/plugins/checkout-registry/types.js +2 -0
  240. package/build/plugins/checkout-registry/types.js.map +1 -0
  241. package/build/plugins/checkout-registry.d.ts +8 -0
  242. package/build/plugins/checkout-registry.d.ts.map +1 -0
  243. package/build/plugins/checkout-registry.js +21 -0
  244. package/build/plugins/checkout-registry.js.map +1 -0
  245. package/build/plugins/consts.local.d.ts +13 -0
  246. package/build/plugins/consts.local.d.ts.map +1 -0
  247. package/build/plugins/consts.local.js +22 -0
  248. package/build/plugins/consts.local.js.map +1 -0
  249. package/build/plugins/customer-lock/types.d.ts +6 -0
  250. package/build/plugins/customer-lock/types.d.ts.map +1 -0
  251. package/build/plugins/customer-lock/types.js +2 -0
  252. package/build/plugins/customer-lock/types.js.map +1 -0
  253. package/build/plugins/customer-lock.d.ts +5 -0
  254. package/build/plugins/customer-lock.d.ts.map +1 -0
  255. package/build/plugins/customer-lock.js +22 -0
  256. package/build/plugins/customer-lock.js.map +1 -0
  257. package/build/plugins/estimate/cache.d.ts +4 -0
  258. package/build/plugins/estimate/cache.d.ts.map +1 -0
  259. package/build/plugins/estimate/cache.js +7 -0
  260. package/build/plugins/estimate/cache.js.map +1 -0
  261. package/build/plugins/estimate/types.d.ts +27 -0
  262. package/build/plugins/estimate/types.d.ts.map +1 -0
  263. package/build/plugins/estimate/types.js +2 -0
  264. package/build/plugins/estimate/types.js.map +1 -0
  265. package/build/plugins/estimate.d.ts +6 -0
  266. package/build/plugins/estimate.d.ts.map +1 -0
  267. package/build/plugins/estimate.js +271 -0
  268. package/build/plugins/estimate.js.map +1 -0
  269. package/build/plugins/events/types.d.ts +12 -0
  270. package/build/plugins/events/types.d.ts.map +1 -0
  271. package/build/plugins/events/types.js +2 -0
  272. package/build/plugins/events/types.js.map +1 -0
  273. package/build/plugins/events.d.ts +6 -13
  274. package/build/plugins/events.d.ts.map +1 -1
  275. package/build/plugins/events.js +441 -144
  276. package/build/plugins/events.js.map +1 -1
  277. package/build/plugins/fx/types.d.ts +33 -0
  278. package/build/plugins/fx/types.d.ts.map +1 -0
  279. package/build/plugins/fx/types.js +2 -0
  280. package/build/plugins/fx/types.js.map +1 -0
  281. package/build/plugins/fx.d.ts +6 -0
  282. package/build/plugins/fx.d.ts.map +1 -0
  283. package/build/plugins/fx.js +83 -0
  284. package/build/plugins/fx.js.map +1 -0
  285. package/build/plugins/portal/types.d.ts +44 -0
  286. package/build/plugins/portal/types.d.ts.map +1 -0
  287. package/build/plugins/portal/types.js +2 -0
  288. package/build/plugins/portal/types.js.map +1 -0
  289. package/build/plugins/portal.d.ts +6 -0
  290. package/build/plugins/portal.d.ts.map +1 -0
  291. package/build/plugins/portal.js +255 -0
  292. package/build/plugins/portal.js.map +1 -0
  293. package/build/plugins/refunds/types.d.ts +35 -0
  294. package/build/plugins/refunds/types.d.ts.map +1 -0
  295. package/build/plugins/refunds/types.js +2 -0
  296. package/build/plugins/refunds/types.js.map +1 -0
  297. package/build/plugins/refunds.d.ts +6 -0
  298. package/build/plugins/refunds.d.ts.map +1 -0
  299. package/build/plugins/refunds.js +81 -0
  300. package/build/plugins/refunds.js.map +1 -0
  301. package/build/plugins/session/types.d.ts +32 -0
  302. package/build/plugins/session/types.d.ts.map +1 -0
  303. package/build/plugins/session/types.js +2 -0
  304. package/build/plugins/session/types.js.map +1 -0
  305. package/build/plugins/session.d.ts +4 -0
  306. package/build/plugins/session.d.ts.map +1 -0
  307. package/build/plugins/session.js +58 -0
  308. package/build/plugins/session.js.map +1 -0
  309. package/build/plugins/status.d.ts +8 -0
  310. package/build/plugins/status.d.ts.map +1 -0
  311. package/build/plugins/status.js +21 -0
  312. package/build/plugins/status.js.map +1 -0
  313. package/build/plugins/stripe/types.d.ts +20 -0
  314. package/build/plugins/stripe/types.d.ts.map +1 -0
  315. package/build/plugins/stripe/types.js +2 -0
  316. package/build/plugins/stripe/types.js.map +1 -0
  317. package/build/plugins/stripe.d.ts +5 -13
  318. package/build/plugins/stripe.d.ts.map +1 -1
  319. package/build/plugins/stripe.js +481 -129
  320. package/build/plugins/stripe.js.map +1 -1
  321. package/build/plugins/subscriptions/types.d.ts +41 -0
  322. package/build/plugins/subscriptions/types.d.ts.map +1 -0
  323. package/build/plugins/subscriptions/types.js +2 -0
  324. package/build/plugins/subscriptions/types.js.map +1 -0
  325. package/build/plugins/subscriptions.d.ts +6 -0
  326. package/build/plugins/subscriptions.d.ts.map +1 -0
  327. package/build/plugins/subscriptions.js +169 -0
  328. package/build/plugins/subscriptions.js.map +1 -0
  329. package/build/plugins/types.d.ts +7 -0
  330. package/build/plugins/types.d.ts.map +1 -0
  331. package/build/plugins/types.js +2 -0
  332. package/build/plugins/types.js.map +1 -0
  333. package/build/plugins/types.local.d.ts +75 -0
  334. package/build/plugins/types.local.d.ts.map +1 -0
  335. package/build/plugins/types.local.js +2 -0
  336. package/build/plugins/types.local.js.map +1 -0
  337. package/build/plugins/webhook-manager/types.d.ts +62 -0
  338. package/build/plugins/webhook-manager/types.d.ts.map +1 -0
  339. package/build/plugins/webhook-manager/types.js +2 -0
  340. package/build/plugins/webhook-manager/types.js.map +1 -0
  341. package/build/plugins/webhook-manager.d.ts +8 -0
  342. package/build/plugins/webhook-manager.d.ts.map +1 -0
  343. package/build/plugins/webhook-manager.js +245 -0
  344. package/build/plugins/webhook-manager.js.map +1 -0
  345. package/build/protocol.d.ts +13 -0
  346. package/build/protocol.d.ts.map +1 -0
  347. package/build/protocol.js +17 -0
  348. package/build/protocol.js.map +1 -0
  349. package/build/reconcile/types.d.ts +17 -0
  350. package/build/reconcile/types.d.ts.map +1 -0
  351. package/build/reconcile/types.js +2 -0
  352. package/build/reconcile/types.js.map +1 -0
  353. package/build/reconcile.d.ts +12 -0
  354. package/build/reconcile.d.ts.map +1 -0
  355. package/build/reconcile.js +91 -0
  356. package/build/reconcile.js.map +1 -0
  357. package/build/resource.d.ts +12 -1
  358. package/build/resource.d.ts.map +1 -1
  359. package/build/resource.js +97 -6
  360. package/build/resource.js.map +1 -1
  361. package/build/schemas.d.ts +19 -0
  362. package/build/schemas.d.ts.map +1 -0
  363. package/build/schemas.js +244 -0
  364. package/build/schemas.js.map +1 -0
  365. package/build/service.d.ts +28 -3
  366. package/build/service.d.ts.map +1 -1
  367. package/build/service.js +140 -19
  368. package/build/service.js.map +1 -1
  369. package/build/subscription/types.d.ts +21 -0
  370. package/build/subscription/types.d.ts.map +1 -0
  371. package/build/subscription/types.js +2 -0
  372. package/build/subscription/types.js.map +1 -0
  373. package/build/subscription.d.ts +4 -0
  374. package/build/subscription.d.ts.map +1 -0
  375. package/build/subscription.js +84 -0
  376. package/build/subscription.js.map +1 -0
  377. package/build/sync/types.d.ts +25 -0
  378. package/build/sync/types.d.ts.map +1 -0
  379. package/build/sync/types.js +2 -0
  380. package/build/sync/types.js.map +1 -0
  381. package/build/sync.d.ts +4 -3
  382. package/build/sync.d.ts.map +1 -1
  383. package/build/sync.js +231 -79
  384. package/build/sync.js.map +1 -1
  385. package/build/types.d.ts +1258 -36
  386. package/build/types.d.ts.map +1 -1
  387. package/build/types.local.d.ts +22 -0
  388. package/build/types.local.d.ts.map +1 -0
  389. package/build/types.local.js +2 -0
  390. package/build/types.local.js.map +1 -0
  391. package/build/usage/types.d.ts +56 -0
  392. package/build/usage/types.d.ts.map +1 -0
  393. package/build/usage/types.js +2 -0
  394. package/build/usage/types.js.map +1 -0
  395. package/build/usage.d.ts +6 -0
  396. package/build/usage.d.ts.map +1 -0
  397. package/build/usage.js +365 -0
  398. package/build/usage.js.map +1 -0
  399. package/build/utils/types.d.ts +31 -0
  400. package/build/utils/types.d.ts.map +1 -0
  401. package/build/utils/types.js +2 -0
  402. package/build/utils/types.js.map +1 -0
  403. package/build/utils.d.ts +21 -7
  404. package/build/utils.d.ts.map +1 -1
  405. package/build/utils.js +56 -17
  406. package/build/utils.js.map +1 -1
  407. package/package.json +22 -17
  408. package/src/access/types.ts +52 -0
  409. package/src/access.ts +86 -0
  410. package/src/actions/index.ts +1 -0
  411. package/src/actions/resync-subscriptions.ts +10 -0
  412. package/src/actions/resync.ts +14 -5
  413. package/src/actions/webhook.ts +9 -4
  414. package/src/bootstrap/types.ts +16 -0
  415. package/src/bootstrap.ts +31 -0
  416. package/src/catalogue/types.ts +32 -0
  417. package/src/catalogue.ts +135 -0
  418. package/src/commit/types.ts +27 -0
  419. package/src/commit.ts +152 -0
  420. package/src/config.ts +234 -14
  421. package/src/consts.local.ts +62 -0
  422. package/src/consts.ts +100 -36
  423. package/src/consumer/cancellation/types.ts +13 -0
  424. package/src/consumer/cancellation.ts +43 -0
  425. package/src/consumer/capture/types.ts +53 -0
  426. package/src/consumer/capture.ts +321 -0
  427. package/src/consumer/consts.local.ts +18 -0
  428. package/src/consumer/format/types.ts +29 -0
  429. package/src/consumer/format.ts +85 -0
  430. package/src/consumer/handlers.ts +204 -0
  431. package/src/consumer/index.ts +9 -0
  432. package/src/consumer/mail/types.ts +31 -0
  433. package/src/consumer/mail.ts +353 -0
  434. package/src/consumer/observers/types.ts +22 -0
  435. package/src/consumer/observers.ts +97 -0
  436. package/src/consumer/origin/types.ts +17 -0
  437. package/src/consumer/origin.ts +61 -0
  438. package/src/consumer/reconcile/types.ts +13 -0
  439. package/src/consumer/reconcile.ts +330 -0
  440. package/src/consumer/records/types.ts +64 -0
  441. package/src/consumer/records.ts +288 -0
  442. package/src/consumer/service.ts +768 -0
  443. package/src/consumer/types.local.ts +22 -0
  444. package/src/consumer/types.ts +96 -0
  445. package/src/consumer/withdrawal/types.ts +37 -0
  446. package/src/consumer/withdrawal.ts +268 -0
  447. package/src/entitlement.ts +85 -0
  448. package/src/entrypoints.ts +17 -4
  449. package/src/gate/request.ts +24 -0
  450. package/src/gate/types.ts +13 -0
  451. package/src/gate.ts +47 -30
  452. package/src/index.ts +55 -3
  453. package/src/limit.ts +54 -0
  454. package/src/log.ts +4 -0
  455. package/src/models/declarations/types.ts +22 -0
  456. package/src/models/declarations.ts +30 -0
  457. package/src/models/purchase/types.ts +13 -0
  458. package/src/models/purchase.ts +43 -0
  459. package/src/observer.ts +44 -11
  460. package/src/plan/types.ts +21 -0
  461. package/src/plan.ts +46 -0
  462. package/src/plugins/checkout-plugins/types.ts +25 -0
  463. package/src/plugins/checkout-plugins.ts +90 -0
  464. package/src/plugins/checkout-policy/types.ts +18 -0
  465. package/src/plugins/checkout-policy.ts +34 -0
  466. package/src/plugins/checkout-registry/types.ts +7 -0
  467. package/src/plugins/checkout-registry.ts +23 -0
  468. package/src/plugins/consts.local.ts +30 -0
  469. package/src/plugins/customer-lock/types.ts +5 -0
  470. package/src/plugins/customer-lock.ts +25 -0
  471. package/src/plugins/estimate/cache.ts +12 -0
  472. package/src/plugins/estimate/types.ts +28 -0
  473. package/src/plugins/estimate.ts +305 -0
  474. package/src/plugins/events/types.ts +11 -0
  475. package/src/plugins/events.ts +466 -132
  476. package/src/plugins/fx/types.ts +40 -0
  477. package/src/plugins/fx.ts +101 -0
  478. package/src/plugins/portal/types.ts +45 -0
  479. package/src/plugins/portal.ts +284 -0
  480. package/src/plugins/refunds/types.ts +31 -0
  481. package/src/plugins/refunds.ts +95 -0
  482. package/src/plugins/session/types.ts +28 -0
  483. package/src/plugins/session.ts +73 -0
  484. package/src/plugins/status.ts +22 -0
  485. package/src/plugins/stripe/types.ts +20 -0
  486. package/src/plugins/stripe.ts +523 -135
  487. package/src/plugins/subscriptions/types.ts +39 -0
  488. package/src/plugins/subscriptions.ts +195 -0
  489. package/src/plugins/types.local.ts +61 -0
  490. package/src/plugins/types.ts +7 -0
  491. package/src/plugins/webhook-manager/types.ts +63 -0
  492. package/src/plugins/webhook-manager.ts +288 -0
  493. package/src/protocol.ts +29 -0
  494. package/src/reconcile/types.ts +17 -0
  495. package/src/reconcile.ts +110 -0
  496. package/src/resource.ts +158 -11
  497. package/src/schemas.ts +271 -0
  498. package/src/service.ts +161 -19
  499. package/src/subscription/types.ts +23 -0
  500. package/src/subscription.ts +104 -0
  501. package/src/sync/types.ts +25 -0
  502. package/src/sync.ts +255 -72
  503. package/src/types.local.ts +18 -0
  504. package/src/types.ts +1365 -32
  505. package/src/usage/types.ts +51 -0
  506. package/src/usage.ts +432 -0
  507. package/src/utils/types.ts +30 -0
  508. package/src/utils.ts +94 -29
  509. package/tests/checkout-consumer.spec.ts +366 -0
  510. package/tests/checkout-locks.spec.ts +161 -0
  511. package/tests/checkout-plugins.spec.ts +164 -0
  512. package/tests/checkout.spec.ts +209 -93
  513. package/tests/consumer-events.spec.ts +215 -0
  514. package/tests/consumer-fixtures.ts +134 -0
  515. package/tests/consumer-ops.spec.ts +350 -0
  516. package/tests/consumer-rights.integration.spec.ts +147 -0
  517. package/tests/consumer-rights.spec.ts +572 -0
  518. package/tests/context.ts +110 -0
  519. package/tests/entitlement.spec.ts +139 -0
  520. package/tests/estimate.spec.ts +350 -0
  521. package/tests/events.spec.ts +357 -0
  522. package/tests/fake-stripe.ts +981 -0
  523. package/tests/gate-handlers.spec.ts +120 -0
  524. package/tests/gate.spec.ts +63 -72
  525. package/tests/gateway-options.spec.ts +180 -0
  526. package/tests/limit-gate.spec.ts +66 -0
  527. package/tests/portal.spec.ts +202 -0
  528. package/tests/protocol.spec.ts +17 -3
  529. package/tests/sync.spec.ts +114 -0
  530. package/tests/usage.integration.spec.ts +133 -0
  531. package/tests/usage.spec.ts +169 -0
  532. package/tests/webhook-manager.spec.ts +149 -0
  533. package/build/model.d.ts +0 -6
  534. package/build/model.d.ts.map +0 -1
  535. package/build/model.js +0 -33
  536. package/build/model.js.map +0 -1
  537. package/src/model.ts +0 -37
@@ -0,0 +1,40 @@
1
+ import type Stripe from 'stripe'
2
+
3
+ export interface StripeFxRate {
4
+ fromCurrency: string
5
+ toCurrency: string
6
+ /** Stripe's fee-inclusive conversion rate (`base_rate × (1 − fx_fee_rate)`). */
7
+ exchangeRate: number
8
+ /** The rate before any fee (Stripe's `base_rate`; derived from `exchangeRate` and `fxFeeRate` when absent). */
9
+ baseRate: number
10
+ /** Market/reference rate used to translate catalogue value into settlement value. */
11
+ referenceRate: number
12
+ fxFeeRate?: number
13
+ }
14
+
15
+ export interface SettlementAmount {
16
+ amountMinor: number
17
+ currency: string
18
+ sourceAmountMinor: number
19
+ sourceCurrency: string
20
+ referenceRate: number
21
+ }
22
+
23
+ export type StripeFxRateCache = Map<string, Promise<StripeFxRate | null>>
24
+
25
+ /** Currency conversion through Stripe's FX Quotes, under a context's pricing settings. */
26
+ export interface FxHelper {
27
+ /** One unlocked Stripe FX quote. `toCurrency` units per one `fromCurrency` unit. */
28
+ stripeFxRate: (stripe: Stripe, fromCurrency: string, toCurrency: string, apiVersion: string) => Promise<StripeFxRate | null>
29
+ /**
30
+ * A catalogue amount in the currency the buyer is charged in: unchanged — no FX call — when the
31
+ * currencies are equal; otherwise converted at Stripe's FX reference rate, rounded up.
32
+ */
33
+ chargeAmount: (
34
+ stripe: Stripe, sourceAmountMinor: number, sourceCurrency: string, chargeCurrency: string, cache?: StripeFxRateCache,
35
+ ) => Promise<SettlementAmount>
36
+ /** Translate a catalogue amount into the configured Stripe settlement currency. */
37
+ settlementAmount: (
38
+ stripe: Stripe, sourceAmountMinor: number, sourceCurrency: string, cache?: StripeFxRateCache,
39
+ ) => Promise<SettlementAmount>
40
+ }
@@ -0,0 +1,101 @@
1
+ import type Stripe from 'stripe'
2
+ import { PaygateError } from '@owlmeans/payment'
3
+ import type { Context as ApiContext } from '@owlmeans/server-api'
4
+ import { memoHelper } from '@owlmeans/context'
5
+ import { STRIPE_FX_QUOTES_API_VERSION } from '../consts.js'
6
+ import type { FxQuoteResponse } from './types.local.js'
7
+ import type { SettlementAmount, StripeFxRate, StripeFxRateCache, FxHelper } from './fx/types.js'
8
+ import { paymentAccessOf } from '../access.js'
9
+
10
+ /** Convert whole source minor units at the reference rate, rounding up so value is never lost. */
11
+ const convertMinor = (amountMinor: number, rate: number): number => {
12
+ const converted = Math.ceil(amountMinor * rate)
13
+ if (!Number.isSafeInteger(amountMinor) || amountMinor < 0 || !Number.isFinite(rate) || rate <= 0
14
+ || !Number.isSafeInteger(converted)) {
15
+ throw new PaygateError('fx-amount')
16
+ }
17
+ return converted
18
+ }
19
+
20
+ export const makeFxHelper = (ctx: ApiContext): FxHelper => {
21
+ const access = paymentAccessOf(ctx)
22
+
23
+ const stripeFxRate = async (
24
+ stripe: Stripe, fromCurrency: string, toCurrency: string, apiVersion: string,
25
+ ): Promise<StripeFxRate | null> => {
26
+ const from = fromCurrency.toLowerCase()
27
+ const to = toCurrency.toLowerCase()
28
+ if (from === to) return { fromCurrency: from, toCurrency: to, exchangeRate: 1, baseRate: 1, referenceRate: 1 }
29
+ const response = await stripe.rawRequest(
30
+ 'POST', '/v1/fx_quotes',
31
+ { to_currency: to, 'from_currencies[]': from, lock_duration: 'none' },
32
+ { apiVersion },
33
+ ) as Stripe.Response<FxQuoteResponse>
34
+ const rate = response.rates?.[from]
35
+ if (rate?.exchange_rate == null) return null
36
+ return {
37
+ fromCurrency: from,
38
+ toCurrency: to,
39
+ exchangeRate: rate.exchange_rate,
40
+ baseRate: rate.rate_details?.base_rate ?? rate.exchange_rate / (1 - (rate.rate_details?.fx_fee_rate ?? 0)),
41
+ referenceRate: rate.rate_details?.reference_rate ?? rate.rate_details?.base_rate ?? rate.exchange_rate,
42
+ ...(rate.rate_details?.fx_fee_rate != null ? { fxFeeRate: rate.rate_details.fx_fee_rate } : {}),
43
+ }
44
+ }
45
+
46
+ const chargeAmount = async (
47
+ stripe: Stripe, sourceAmountMinor: number, sourceCurrency: string, chargeCurrency: string,
48
+ cache?: StripeFxRateCache,
49
+ ): Promise<SettlementAmount> => {
50
+ const source = sourceCurrency.toLowerCase()
51
+ const currency = chargeCurrency.toLowerCase()
52
+ if (currency === source) {
53
+ return { amountMinor: sourceAmountMinor, currency, sourceAmountMinor, sourceCurrency: source, referenceRate: 1 }
54
+ }
55
+ const apiVersion = (await access.stripePricingConfig())?.fxApiVersion ?? STRIPE_FX_QUOTES_API_VERSION
56
+ const key = `${source}:${currency}:${apiVersion}`
57
+ let pending = cache?.get(key)
58
+ if (pending == null) {
59
+ pending = stripeFxRate(stripe, source, currency, apiVersion)
60
+ cache?.set(key, pending)
61
+ }
62
+ const quote = await pending
63
+ if (quote == null) throw new PaygateError(`fx-rate:${source}:${currency}`)
64
+
65
+ return {
66
+ amountMinor: convertMinor(sourceAmountMinor, quote.referenceRate), currency,
67
+ sourceAmountMinor, sourceCurrency: source, referenceRate: quote.referenceRate,
68
+ }
69
+ }
70
+
71
+ const settlementAmount = async (
72
+ stripe: Stripe, sourceAmountMinor: number, sourceCurrency: string, cache?: StripeFxRateCache,
73
+ ): Promise<SettlementAmount> => {
74
+ const source = sourceCurrency.toLowerCase()
75
+ const pricing = await access.stripePricingConfig()
76
+ const currency = pricing?.settlementCurrency?.toLowerCase() ?? source
77
+ if (currency === source) {
78
+ return {
79
+ amountMinor: sourceAmountMinor, currency, sourceAmountMinor, sourceCurrency: source, referenceRate: 1,
80
+ }
81
+ }
82
+ const apiVersion = pricing?.fxApiVersion ?? STRIPE_FX_QUOTES_API_VERSION
83
+ const key = `${source}:${currency}:${apiVersion}`
84
+ let pending = cache?.get(key)
85
+ if (pending == null) {
86
+ pending = stripeFxRate(stripe, source, currency, apiVersion)
87
+ cache?.set(key, pending)
88
+ }
89
+ const quote = await pending
90
+ if (quote == null) throw new PaygateError(`fx-rate:${source}:${currency}`)
91
+ return {
92
+ amountMinor: convertMinor(sourceAmountMinor, quote.referenceRate), currency,
93
+ sourceAmountMinor, sourceCurrency: source, referenceRate: quote.referenceRate,
94
+ }
95
+ }
96
+
97
+ return { stripeFxRate, chargeAmount, settlementAmount }
98
+ }
99
+
100
+ /** The FX conversion of a context — one per context. */
101
+ export const fxOf = memoHelper.oncePer(makeFxHelper)
@@ -0,0 +1,45 @@
1
+ import type Stripe from 'stripe'
2
+ import type { PortalLinkOptions } from '../../types.js'
3
+
4
+ export interface EnsurePortalOptions {
5
+ force?: boolean
6
+ }
7
+
8
+ /** The Stripe customer portal of a deployment: its configuration and its sessions. */
9
+ export interface PortalHelper {
10
+ /** The fingerprint sku of an owner's portal configuration: `portal:<owner>`. */
11
+ portalFingerprintSku: (owner: string) => string
12
+ /**
13
+ * Keep this deployment's own Stripe customer-portal configuration: customer, invoice and payment
14
+ * method self-service, cancellation at period end, and switching between the active recurring
15
+ * prices of every product sold through Stripe (both subscription features off when there are none).
16
+ * The customer may edit their tax id always, their e-mail unless `stripe.lockCustomerEmail`, their
17
+ * address unless the consumer-rights `countryLock` or `stripe.lockCustomerCountry`.
18
+ *
19
+ * A deployment's identity is its webhook URL (`webhookUrlOf`, on the gateway's `webhookService`) —
20
+ * also when that URL is undeliverable, as on a local run; its fingerprint row and label carry the
21
+ * gateway's `owner` (`gatewayOwnerOf`). Several deployments of one application may share a Stripe
22
+ * account, so each owns a configuration of its own, tagged
23
+ * `{ owlmeans: 'payment', service: <owner>, deployment: <webhook URL> }`.
24
+ *
25
+ * - An unchanged declaration (catalogue, branding, deployment key) makes no paygate call.
26
+ * - The configuration the `portal:<owner>` fingerprint row names is updated in place — unless its
27
+ * metadata tags it for another deployment (a moved webhook URL included), which is never
28
+ * overwritten; this deployment then proceeds as though it held no row.
29
+ * - Without a usable row, an active configuration tagged with exactly this owner and deployment
30
+ * key is adopted. Nothing else is: not an untagged one, not one carrying only the owner label,
31
+ * not one tagged for another deployment.
32
+ * - Otherwise a new configuration is created. Stripe cannot delete a portal configuration, so one
33
+ * this deployment can no longer identify stays in the account, and a lost row creates a new one
34
+ * unless its tagged configuration is found.
35
+ */
36
+ ensurePortalConfiguration: (stripe: Stripe, opts?: EnsurePortalOptions) => Promise<string | null>
37
+ /**
38
+ * A Stripe customer-portal session for one entity. `Manage` opens the portal home and
39
+ * `PaymentMethod` the payment method form; `Cancel`, `Update` and `Change` act on the entity's
40
+ * entitling Stripe subscription (`Change` confirms a switch of its one item to `planSku`'s price).
41
+ *
42
+ * @throws PortalUnavailable('customer' | 'subscription' | 'plan' | 'item')
43
+ */
44
+ createPortalLink: (stripe: Stripe, entityId: string, opts: PortalLinkOptions) => Promise<string>
45
+ }
@@ -0,0 +1,284 @@
1
+ import { createHash } from 'node:crypto'
2
+ import type Stripe from 'stripe'
3
+ import { ENTITLING_STATUSES, PortalFlow, PortalUnavailable, ProductError, UnknownPlan } from '@owlmeans/payment'
4
+ import type { Context as ApiContext } from '@owlmeans/server-api'
5
+ import { memoHelper } from '@owlmeans/context'
6
+ import {
7
+ FINGERPRINT_PORTAL, STRIPE_DEPLOYMENT_KEY, STRIPE_OWNER_KEY, STRIPE_OWNER_VALUE, STRIPE_PAYGATE_ALIAS,
8
+ } from '../consts.js'
9
+ import type { PaymentProduct, PaymentSubscriptionRecord, PortalLinkOptions } from '../types.js'
10
+ import { log } from '../log.js'
11
+ import type { Claim, ConfigurationParams } from './types.local.js'
12
+ import type { EnsurePortalOptions, PortalHelper } from './portal/types.js'
13
+ import { paymentAccessOf } from '../access.js'
14
+ import { paymentUtils } from '../utils.js'
15
+ import { catalogueOf } from '../catalogue.js'
16
+ import { planHelper } from '../plan.js'
17
+ import { webhookOf } from './webhook-manager.js'
18
+
19
+ /** The fingerprint sku of an owner's portal configuration: `portal:<owner>`. */
20
+ const portalFingerprintSku = (owner: string): string => `${FINGERPRINT_PORTAL}:${owner}`
21
+
22
+ /**
23
+ * Whose a configuration is by its metadata: `ours` carries this owner AND this deployment's key;
24
+ * `foreign` is tagged for another deployment or another owner; `unclaimed` names no deployment.
25
+ */
26
+ const claimOf = (metadata: Stripe.Metadata | null | undefined, owner: string, deployment: string): Claim => {
27
+ const owned = metadata?.[STRIPE_OWNER_KEY] === STRIPE_OWNER_VALUE
28
+ const tagged = metadata?.[STRIPE_DEPLOYMENT_KEY]
29
+ if (owned && metadata?.service === owner && tagged === deployment) {
30
+ return 'ours'
31
+ }
32
+ if ((owned && metadata?.service !== owner) || (tagged != null && tagged !== '')) {
33
+ return 'foreign'
34
+ }
35
+
36
+ return 'unclaimed'
37
+ }
38
+
39
+ export const makePortalHelper = (ctx: ApiContext): PortalHelper => {
40
+ const access = paymentAccessOf(ctx)
41
+
42
+ /** The recurring plans sold through Stripe, per product — what the portal may switch between. */
43
+ const recurringCatalog = async (): Promise<Array<{ product: PaymentProduct, lookupKeys: string[], hashable: unknown[] }>> => {
44
+ // The declared tax behavior decides which Stripe price id `sync.ts` keeps for a plan (an
45
+ // in-place `unspecified` update keeps it, an opposite behavior replaces it) — hashed here too,
46
+ // so a behavior change refreshes this configuration's `products[].prices` to the new ids.
47
+ const behavior = (await access.payment().pricingPolicy()).tax.behavior ?? null
48
+ const result: Array<{ product: PaymentProduct, lookupKeys: string[], hashable: unknown[] }> = []
49
+ for (const { product, plans } of await catalogueOf(ctx).stripePlansOf()) {
50
+ const recurring = plans.filter(plan => plan.recurring != null)
51
+ if (recurring.length === 0) {
52
+ continue
53
+ }
54
+ result.push({
55
+ product,
56
+ lookupKeys: recurring.map(plan => planHelper.planLookupKey(product, plan)),
57
+ hashable: recurring.map(plan => ({
58
+ sku: plan.sku, price: plan.price, currency: plan.currency ?? 'usd', interval: plan.recurring?.interval,
59
+ rank: planHelper.planRank(plan), behavior,
60
+ // A changed currency option replaces the Price — the portal's price list must follow it.
61
+ ...(plan.currencyPrices != null ? { currencyPrices: plan.currencyPrices } : {}),
62
+ })).sort((a, b) => a.sku.localeCompare(b.sku)),
63
+ })
64
+ }
65
+
66
+ return result.sort((a, b) => a.product.sku.localeCompare(b.product.sku))
67
+ }
68
+
69
+ const activeRecurringPrices = async (stripe: Stripe, productSku: string): Promise<Stripe.Price[]> =>
70
+ (await stripe.prices.list({ product: productSku, active: true, limit: 100 })).data
71
+ .filter(price => price.recurring != null)
72
+
73
+ const listActiveConfigurations = async (stripe: Stripe): Promise<Stripe.BillingPortal.Configuration[]> => {
74
+ const configurations: Stripe.BillingPortal.Configuration[] = []
75
+ let startingAfter: string | undefined
76
+ for (;;) {
77
+ const page = await stripe.billingPortal.configurations.list({
78
+ active: true, limit: 100, ...(startingAfter != null ? { starting_after: startingAfter } : {}),
79
+ })
80
+ configurations.push(...page.data)
81
+ if (!page.has_more || page.data.length === 0) {
82
+ return configurations
83
+ }
84
+ startingAfter = page.data[page.data.length - 1].id
85
+ }
86
+ }
87
+
88
+ const ensurePortalConfiguration = async (stripe: Stripe, opts: EnsurePortalOptions = {}): Promise<string | null> => {
89
+ const owner = webhookOf(ctx).gatewayOwnerOf()
90
+ const deployment = webhookOf(ctx).webhookUrlOf()
91
+ const sku = portalFingerprintSku(owner)
92
+ const branding = await access.portalBrandingConfig()
93
+ const catalog = await recurringCatalog()
94
+ const rights = await access.payment().consumerRightsPolicy()
95
+ // A locked billing country is never edited in the portal: tax follows the saved address.
96
+ const stripeConfig = await access.stripePricingConfig()
97
+ const countryLock = rights?.mechanisms.countryLock === true
98
+ // A pinned country and a locked customer e-mail are the application's: never edited in the portal.
99
+ const countryPin = stripeConfig?.lockCustomerCountry === true
100
+ const emailLock = stripeConfig?.lockCustomerEmail === true
101
+ const regionCurrencies = Object.values(rights?.currencies ?? {}).filter(code => code != null).sort()
102
+ const hash = createHash('sha256').update(JSON.stringify({
103
+ service: owner,
104
+ deployment,
105
+ ...(countryLock ? { countryLock } : {}),
106
+ ...(countryPin ? { countryPin } : {}),
107
+ ...(emailLock ? { emailLock } : {}),
108
+ ...(regionCurrencies.length > 0 ? { regionCurrencies } : {}),
109
+ branding: branding != null ? {
110
+ headline: branding.headline ?? null, privacyPolicyUrl: branding.privacyPolicyUrl ?? null,
111
+ termsOfServiceUrl: branding.termsOfServiceUrl ?? null, returnUrl: branding.returnUrl ?? null,
112
+ } : null,
113
+ products: catalog.map(entry => ({ product: entry.product.sku, plans: entry.hashable })),
114
+ })).digest('hex')
115
+
116
+ const stored = await access.fingerprints().bySku(sku)
117
+ if (stored != null && stored.hash === hash && stored.externalId != null && opts.force !== true) {
118
+ return stored.externalId
119
+ }
120
+
121
+ const products: Array<{ product: string, prices: string[] }> = []
122
+ for (const entry of catalog) {
123
+ const prices = (await activeRecurringPrices(stripe, entry.product.sku)).map(price => price.id)
124
+ if (prices.length > 0) {
125
+ products.push({ product: entry.product.sku, prices })
126
+ }
127
+ }
128
+ const cancelable = catalog.length > 0
129
+ const switchable = products.length > 0
130
+ const metadata = { [STRIPE_OWNER_KEY]: STRIPE_OWNER_VALUE, service: owner, [STRIPE_DEPLOYMENT_KEY]: deployment }
131
+ const allowedUpdates: Stripe.BillingPortal.ConfigurationCreateParams.Features.CustomerUpdate.AllowedUpdate[] = [
132
+ ...(emailLock ? [] : ['email' as const]), ...(countryLock || countryPin ? [] : ['address' as const]), 'tax_id',
133
+ ]
134
+ const params: ConfigurationParams = {
135
+ features: {
136
+ customer_update: { enabled: true, allowed_updates: allowedUpdates },
137
+ invoice_history: { enabled: true },
138
+ payment_method_update: { enabled: true },
139
+ subscription_cancel: cancelable
140
+ ? { enabled: true, mode: 'at_period_end', proration_behavior: 'none' }
141
+ : { enabled: false },
142
+ subscription_update: switchable
143
+ ? {
144
+ enabled: true, default_allowed_updates: ['price'], products,
145
+ proration_behavior: 'create_prorations',
146
+ }
147
+ : { enabled: false },
148
+ },
149
+ ...(branding != null ? {
150
+ business_profile: {
151
+ ...(branding.headline != null ? { headline: branding.headline } : {}),
152
+ ...(branding.privacyPolicyUrl != null ? { privacy_policy_url: branding.privacyPolicyUrl } : {}),
153
+ ...(branding.termsOfServiceUrl != null ? { terms_of_service_url: branding.termsOfServiceUrl } : {}),
154
+ },
155
+ default_return_url: branding.returnUrl,
156
+ } : {}),
157
+ metadata,
158
+ }
159
+
160
+ let configurationId: string | null = null
161
+ if (stored?.externalId != null) {
162
+ try {
163
+ const current = await stripe.billingPortal.configurations.retrieve(stored.externalId)
164
+ if (claimOf(current.metadata, owner, deployment) !== 'foreign') {
165
+ await stripe.billingPortal.configurations.update(current.id, params)
166
+ configurationId = current.id
167
+ }
168
+ } catch (error) {
169
+ if (!paymentUtils.isMissingObject(error)) {
170
+ throw error
171
+ }
172
+ }
173
+ }
174
+ if (configurationId == null) {
175
+ const existing = (await listActiveConfigurations(stripe))
176
+ .find(configuration => claimOf(configuration.metadata, owner, deployment) === 'ours')
177
+ if (existing != null) {
178
+ await stripe.billingPortal.configurations.update(existing.id, params)
179
+ configurationId = existing.id
180
+ } else {
181
+ configurationId = (await stripe.billingPortal.configurations.create(params)).id
182
+ }
183
+ }
184
+
185
+ const now = new Date()
186
+ if (stored != null) {
187
+ await access.fingerprints().update({ ...stored, hash, externalId: configurationId, updatedAt: now })
188
+ } else {
189
+ await access.fingerprints().create({ sku, hash, externalId: configurationId, updatedAt: now })
190
+ }
191
+
192
+ return configurationId
193
+ }
194
+
195
+ /** The entity's highest-ranked entitling Stripe subscription, or `null`. */
196
+ const entitlingStripeSubscription = async (
197
+ entityId: string,
198
+ ): Promise<PaymentSubscriptionRecord | null> => await access.subscriptions().load(
199
+ { entityId, paygate: STRIPE_PAYGATE_ALIAS, status: [...ENTITLING_STATUSES] },
200
+ { sort: [{ field: 'rank', order: 'desc' }, { field: 'createdAt', order: 'desc' }] },
201
+ )
202
+
203
+ const createPortalLink = async (stripe: Stripe, entityId: string, opts: PortalLinkOptions): Promise<string> => {
204
+ const customer = await access.paygateCustomers().byEntity(entityId, STRIPE_PAYGATE_ALIAS)
205
+ if (customer == null || customer.deletedAt != null) {
206
+ throw new PortalUnavailable('customer')
207
+ }
208
+
209
+ const sku = portalFingerprintSku(webhookOf(ctx).gatewayOwnerOf())
210
+ let configuration = (await access.fingerprints().bySku(sku))?.externalId ?? null
211
+ if (configuration == null) {
212
+ await ensurePortalConfiguration(stripe).catch(error => {
213
+ log.error('Portal configuration unavailable', error)
214
+ })
215
+ configuration = (await access.fingerprints().bySku(sku))?.externalId ?? null
216
+ }
217
+
218
+ let flowData: Stripe.BillingPortal.SessionCreateParams.FlowData | undefined
219
+ switch (opts.flow) {
220
+ case PortalFlow.Manage:
221
+ break
222
+ case PortalFlow.PaymentMethod:
223
+ flowData = { type: 'payment_method_update' }
224
+ break
225
+ case PortalFlow.Cancel:
226
+ case PortalFlow.Update:
227
+ case PortalFlow.Change: {
228
+ const subscription = await entitlingStripeSubscription(entityId)
229
+ if (subscription == null) {
230
+ throw new PortalUnavailable('subscription')
231
+ }
232
+ if (opts.flow === PortalFlow.Cancel) {
233
+ flowData = { type: 'subscription_cancel', subscription_cancel: { subscription: subscription.externalId } }
234
+ } else if (opts.flow === PortalFlow.Update) {
235
+ flowData = { type: 'subscription_update', subscription_update: { subscription: subscription.externalId } }
236
+ } else {
237
+ if (opts.planSku == null || opts.planSku === '') {
238
+ throw new PortalUnavailable('plan')
239
+ }
240
+ const plan = await catalogueOf(ctx).findPlan(opts.planSku)
241
+ const product = plan != null ? await catalogueOf(ctx).findProduct(plan.productSku) : null
242
+ if (plan == null || product == null) {
243
+ throw new UnknownPlan(opts.planSku)
244
+ }
245
+ if (subscription.itemId == null) {
246
+ throw new PortalUnavailable('item')
247
+ }
248
+ const lookupKey = planHelper.planLookupKey(product, plan)
249
+ const [price] = (await stripe.prices.list({ lookup_keys: [lookupKey], active: true, limit: 1 })).data
250
+ if (price == null) {
251
+ throw new ProductError(`price:${lookupKey}`)
252
+ }
253
+ flowData = {
254
+ type: 'subscription_update_confirm',
255
+ subscription_update_confirm: {
256
+ subscription: subscription.externalId,
257
+ items: [{ id: subscription.itemId, price: price.id, quantity: 1 }],
258
+ },
259
+ }
260
+ }
261
+ break
262
+ }
263
+ default:
264
+ throw new PortalUnavailable(`flow:${String(opts.flow)}`)
265
+ }
266
+ if (flowData != null) {
267
+ flowData.after_completion = { type: 'redirect', redirect: { return_url: opts.returnUrl } }
268
+ }
269
+
270
+ const session = await stripe.billingPortal.sessions.create({
271
+ customer: customer.externalId,
272
+ return_url: opts.returnUrl,
273
+ ...(configuration != null ? { configuration } : {}),
274
+ ...(flowData != null ? { flow_data: flowData } : {}),
275
+ })
276
+
277
+ return session.url
278
+ }
279
+
280
+ return { portalFingerprintSku, ensurePortalConfiguration, createPortalLink }
281
+ }
282
+
283
+ /** The customer portal of a context — one per context. */
284
+ export const portalOf = memoHelper.oncePer(makePortalHelper)
@@ -0,0 +1,31 @@
1
+ import type Stripe from 'stripe'
2
+ import type { PaymentFulfillmentRecord, PaymentSubscriptionRecord } from '../../types.js'
3
+
4
+ /** What a refund or a dispute is about: a one-time fulfillment, or one invoice of a subscription. */
5
+ export type PaymentTarget =
6
+ | { kind: 'fulfillment', record: PaymentFulfillmentRecord, charge: Stripe.Charge | null, paymentIntentId?: string }
7
+ | {
8
+ kind: 'subscription', record: PaymentSubscriptionRecord, charge: Stripe.Charge | null,
9
+ paymentIntentId?: string, invoiceId: string,
10
+ }
11
+
12
+ export interface PaymentReference {
13
+ paymentIntentId?: string
14
+ chargeId?: string
15
+ invoiceId?: string
16
+ /** The charge, when the event already carries it. */
17
+ charge?: Stripe.Charge | null
18
+ }
19
+
20
+ /** What a refund or a dispute of a context is about. */
21
+ export interface PaymentTargetHelper {
22
+ /** A charge by id, or `null` when the paygate has none. */
23
+ retrieveCharge: (stripe: Stripe, chargeId: string) => Promise<Stripe.Charge | null>
24
+ /**
25
+ * Resolve a refund or a dispute to the record it is about: by payment intent to a fulfillment;
26
+ * by charge to a fulfillment (stored charge, else the charge's payment intent — whose charge id is
27
+ * then remembered), else the charge's invoice; by invoice to the subscription whose latest invoice
28
+ * it is, else the invoice's subscription. `null` when nothing here paid for it.
29
+ */
30
+ resolvePaymentTarget: (stripe: Stripe, ref: PaymentReference) => Promise<PaymentTarget | null>
31
+ }
@@ -0,0 +1,95 @@
1
+ import type Stripe from 'stripe'
2
+ import type { Context as ApiContext } from '@owlmeans/server-api'
3
+ import { memoHelper } from '@owlmeans/context'
4
+ import { STRIPE_PAYGATE_ALIAS } from '../consts.js'
5
+ import type { PaymentSubscriptionRecord } from '../types.js'
6
+ import type { PaymentReference, PaymentTarget, PaymentTargetHelper } from './refunds/types.js'
7
+ import { paymentAccessOf } from '../access.js'
8
+ import { paymentUtils } from '../utils.js'
9
+
10
+ export const makePaymentTargetHelper = (ctx: ApiContext): PaymentTargetHelper => {
11
+ const access = paymentAccessOf(ctx)
12
+
13
+ const retrieveCharge = async (stripe: Stripe, chargeId: string): Promise<Stripe.Charge | null> => {
14
+ try {
15
+ return await stripe.charges.retrieve(chargeId)
16
+ } catch (error) {
17
+ if (paymentUtils.isMissingObject(error)) {
18
+ return null
19
+ }
20
+ throw error
21
+ }
22
+ }
23
+
24
+ const subscriptionOfInvoice = async (
25
+ stripe: Stripe, invoiceId: string,
26
+ ): Promise<PaymentSubscriptionRecord | null> => {
27
+ const latest = await access.subscriptions().load({ paygate: STRIPE_PAYGATE_ALIAS, latestInvoiceId: invoiceId })
28
+ if (latest != null) {
29
+ return latest
30
+ }
31
+ let invoice: Stripe.Invoice
32
+ try {
33
+ invoice = await stripe.invoices.retrieve(invoiceId)
34
+ } catch (error) {
35
+ if (paymentUtils.isMissingObject(error)) {
36
+ return null
37
+ }
38
+ throw error
39
+ }
40
+ // `invoice.subscription` is top-level on the API version the client is pinned to.
41
+ const subscriptionId = paymentUtils.idOf((invoice as unknown as { subscription?: string | { id?: string } | null }).subscription)
42
+
43
+ return subscriptionId != null
44
+ ? await access.subscriptions().byExternalId(subscriptionId, STRIPE_PAYGATE_ALIAS)
45
+ : null
46
+ }
47
+
48
+ const resolvePaymentTarget = async (stripe: Stripe, ref: PaymentReference): Promise<PaymentTarget | null> => {
49
+ const ledger = access.fulfillments()
50
+ let charge = ref.charge ?? null
51
+ let paymentIntentId = ref.paymentIntentId
52
+ const chargeId = ref.chargeId ?? charge?.id
53
+
54
+ if (paymentIntentId != null) {
55
+ const record = await ledger.load({ paygate: STRIPE_PAYGATE_ALIAS, paymentIntentId })
56
+ if (record != null) {
57
+ return { kind: 'fulfillment', record, charge, paymentIntentId }
58
+ }
59
+ }
60
+
61
+ let invoiceId = ref.invoiceId
62
+ if (chargeId != null) {
63
+ const record = await ledger.load({ paygate: STRIPE_PAYGATE_ALIAS, chargeId })
64
+ if (record != null) {
65
+ return { kind: 'fulfillment', record, charge, paymentIntentId: paymentIntentId ?? record.paymentIntentId }
66
+ }
67
+ charge = charge ?? await retrieveCharge(stripe, chargeId)
68
+ const chargeIntent = paymentUtils.idOf(charge?.payment_intent)
69
+ if (chargeIntent != null && chargeIntent !== paymentIntentId) {
70
+ paymentIntentId = chargeIntent
71
+ const byIntent = await ledger.load({ paygate: STRIPE_PAYGATE_ALIAS, paymentIntentId: chargeIntent })
72
+ if (byIntent != null) {
73
+ const record = byIntent.chargeId == null ? await ledger.update({ ...byIntent, chargeId }) : byIntent
74
+ return { kind: 'fulfillment', record, charge, paymentIntentId: chargeIntent }
75
+ }
76
+ }
77
+ // `charge.invoice` is top-level on the API version the client is pinned to.
78
+ invoiceId = invoiceId ?? paymentUtils.idOf((charge as unknown as { invoice?: string | { id?: string } | null } | null)?.invoice)
79
+ }
80
+
81
+ if (invoiceId != null) {
82
+ const record = await subscriptionOfInvoice(stripe, invoiceId)
83
+ if (record != null) {
84
+ return { kind: 'subscription', record, charge, paymentIntentId, invoiceId }
85
+ }
86
+ }
87
+
88
+ return null
89
+ }
90
+
91
+ return { retrieveCharge, resolvePaymentTarget }
92
+ }
93
+
94
+ /** The refund and dispute targets of a context — one per context. */
95
+ export const paymentTargetOf = memoHelper.oncePer(makePaymentTargetHelper)
@@ -0,0 +1,28 @@
1
+ import type Stripe from 'stripe'
2
+ import type { TaxBehavior } from '@owlmeans/payment'
3
+ import type { PaymentPlan, PaymentProduct } from '../../types.js'
4
+
5
+ /** The parts of a Stripe Checkout Session read from a plan or an answer alone — pure. */
6
+ export interface StripeSessionHelper {
7
+ /** The line item of an amount checkout, its pre-tax charge and its currency. @throws ProductError */
8
+ amountCheckoutLineItem: (
9
+ product: PaymentProduct, plan: PaymentPlan, amountMinor: number, behavior?: TaxBehavior,
10
+ ) => { lineItem: Stripe.Checkout.SessionCreateParams.LineItem; chargeMinor: number; currency: string }
11
+ /** The adjustable-quantity line item of a quantity checkout. */
12
+ quantityCheckoutLineItem: (
13
+ price: Stripe.Price, policy: { minimum: number; maximum: number; default: number },
14
+ ) => Stripe.Checkout.SessionCreateParams.LineItem
15
+ /**
16
+ * Whether Stripe Tax can calculate on a saved address alone — Checkout refuses a session that keeps
17
+ * the saved address (`customer_update.address: 'never'`) when it cannot.
18
+ */
19
+ isTaxLocatable: (address: Stripe.Address | null | undefined) => boolean
20
+ /**
21
+ * Stripe refuses `consent_collection.terms_of_service` while the account has no terms-of-service URL
22
+ * in its Dashboard (Settings → Public details): an `invalid_request_error` on the param
23
+ * `consent_collection[terms_of_service]` saying "You cannot collect consent to your terms of service
24
+ * unless a URL is set in the Stripe Dashboard …". Matched on the param with a terms message, or on
25
+ * the message alone; any other error type never matches.
26
+ */
27
+ isMissingTermsUrl: (error: unknown) => boolean
28
+ }