@owlmeans/server-payment 0.1.18-rc.8 → 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
@@ -1,62 +1,63 @@
1
- import Stripe from 'stripe'
2
- import {
3
- assertCheckoutAmount, chargeAmountMinor, CheckoutPricingMode, PaygateError, ProductError, ProductType,
4
- } from '@owlmeans/payment'
1
+ import type Stripe from 'stripe'
2
+ import { BillingCountryLocked, CheckoutPricingMode, CONSUMER_RIGHTS_COPY_VERSION, ConsumerRightsError, PaygateError, ProductError, ProductType, TaxBehavior, type PricingPolicy, consumerCopyHelper, consumerRegionHelper, consumerRightsPolicyHelper } from '@owlmeans/payment'
5
3
  import type { Context as ApiContext } from '@owlmeans/server-api'
6
- import { STRIPE_PAYGATE_ALIAS, STRIPE_SIGNATURE } from '../consts.js'
7
- import { paygateCustomers, payment, stripeClient, stripeConfig } from '../utils.js'
8
- import { planLookupKey } from '../sync.js'
9
- import { createEventHandler } from './events.js'
10
- import type { CreateLinkParams, PaymentPlan, PaymentPlugin, PaymentProduct } from '../types.js'
11
-
12
- const taxOptions = (promotions: boolean): Partial<Stripe.Checkout.SessionCreateParams> => ({
13
- automatic_tax: { enabled: true },
14
- billing_address_collection: 'required',
15
- tax_id_collection: { enabled: true },
16
- customer_update: { address: 'auto', name: 'auto' },
17
- allow_promotion_codes: promotions,
18
- })
4
+ import { memoHelper } from '@owlmeans/context'
5
+ import { STRIPE_PAYGATE_ALIAS } from '../consts.js'
6
+ import type { Admitted } from './types.js'
7
+ import type {
8
+ CheckoutAttempt, CheckoutPlugin, CheckoutTextContext, CreateLinkParams, PaymentPlan, PaymentProduct,
9
+ } from '../types.js'
10
+ import { log } from '../log.js'
11
+ import { CUSTOM_TEXT_MAX, EMAIL } from './consts.local.js'
12
+ import type { BuyerContext, CheckoutOptionsFlags, StripeErrorShape } from './types.local.js'
13
+ import { fxOf } from './fx.js'
14
+ import { paymentAccessOf } from '../access.js'
15
+ import { paymentUtils } from '../utils.js'
16
+ import { planHelper } from '../plan.js'
17
+ import { checkoutPluginsOf } from './checkout-plugins.js'
18
+ import { checkoutPolicyHelper } from './checkout-policy.js'
19
+ import type { StripeCheckoutHelper } from './stripe/types.js'
20
+ import { stripeSessionHelper } from './session.js'
21
+ import { consumerFormatHelper } from '../consumer/format.js'
22
+ import { consumerRecordsOf } from '../consumer/records.js'
19
23
 
20
- const ensureStripeCustomer = async (
21
- ctx: ApiContext, stripe: Stripe, params: CreateLinkParams,
22
- ): Promise<Stripe.Customer> => {
23
- const resource = paygateCustomers(ctx)
24
- const existing = await resource.byEntity(params.entityId, STRIPE_PAYGATE_ALIAS)
25
- if (existing != null) {
26
- const retrieved = await stripe.customers.retrieve(existing.externalId)
27
- if (!(retrieved as Stripe.DeletedCustomer).deleted) return retrieved as Stripe.Customer
28
- }
29
- const created = await stripe.customers.create({
30
- metadata: {
31
- entityId: params.entityId, ...(params.profileId && { profileId: params.profileId }),
32
- service: params.service,
33
- },
34
- })
35
- if (existing != null) {
36
- Object.assign(existing, { externalId: created.id })
37
- await resource.save(existing)
38
- } else {
39
- await resource.create({
40
- paygate: STRIPE_PAYGATE_ALIAS, externalId: created.id, entityId: params.entityId,
41
- profileId: params.profileId,
42
- })
43
- }
44
- return created
45
- }
24
+ /**
25
+ * A Checkout Session's tax and currency options, entirely driven by the declared `PricingPolicy` —
26
+ * an undeclared one (`DEFAULT_PRICING_POLICY`) reproduces exactly what every session hard-coded
27
+ * before this policy existed: automatic tax and tax-id collection on, no Adaptive Pricing.
28
+ *
29
+ * `customer_update.address` lets automatic tax use the billing address Checkout just collected
30
+ * rather than only a previously saved one; `customer_update.name` lets tax-id collection save the
31
+ * business name it collects. Each is included only for the concern that needs it. Under a country
32
+ * lock the saved address is kept (`address: 'never'`, collection `'auto'`), so tax follows the
33
+ * locked country and Checkout cannot move it.
34
+ */
35
+ const checkoutOptions = (
36
+ policy: PricingPolicy, promotions: boolean, flags: CheckoutOptionsFlags = {},
37
+ ): Partial<Stripe.Checkout.SessionCreateParams> => {
38
+ const customerUpdate: Stripe.Checkout.SessionCreateParams.CustomerUpdate = {}
39
+ if (policy.tax.automatic) customerUpdate.address = flags.locked === true ? 'never' : 'auto'
40
+ if (policy.tax.collectTaxId) customerUpdate.name = 'auto'
46
41
 
47
- const findPrice = async (stripe: Stripe, productSku: string, lookupKey: string): Promise<Stripe.Price> => {
48
- const prices = await stripe.prices.list({ product: productSku, active: true, lookup_keys: [lookupKey] })
49
- if (prices.data.length === 0) throw new ProductError(`price:${lookupKey}`)
50
- return prices.data[0]
42
+ return {
43
+ ...(policy.tax.automatic
44
+ ? { automatic_tax: { enabled: true }, billing_address_collection: flags.locked === true ? 'auto' as const : 'required' as const }
45
+ : {}),
46
+ ...(policy.tax.collectTaxId ? { tax_id_collection: { enabled: true } } : {}),
47
+ ...(Object.keys(customerUpdate).length > 0 ? { customer_update: customerUpdate } : {}),
48
+ adaptive_pricing: { enabled: policy.currency.adaptive === true && flags.adaptive !== false },
49
+ allow_promotion_codes: promotions,
50
+ }
51
51
  }
52
52
 
53
53
  const sharedSession = (
54
54
  customer: Stripe.Customer, params: CreateLinkParams, product: PaymentProduct,
55
55
  plan: PaymentPlan, metadata: Record<string, string>,
56
- ): Pick<Stripe.Checkout.SessionCreateParams, 'customer' | 'success_url' | 'cancel_url' | 'metadata'> => ({
56
+ ): Pick<Stripe.Checkout.SessionCreateParams, 'customer' | 'success_url' | 'cancel_url' | 'metadata' | 'locale'> => ({
57
57
  customer: customer.id,
58
58
  success_url: params.successUrl,
59
59
  cancel_url: params.cancelUrl ?? params.successUrl,
60
+ ...(params.locale != null ? { locale: params.locale as Stripe.Checkout.SessionCreateParams.Locale } : {}),
60
61
  metadata: {
61
62
  pricingMode: plan.pricingMode ?? CheckoutPricingMode.Quantity,
62
63
  currency: (plan.currency ?? 'usd').toLowerCase(),
@@ -69,115 +70,502 @@ const sharedSession = (
69
70
  },
70
71
  })
71
72
 
72
- export const amountCheckoutLineItem = (
73
- product: PaymentProduct, plan: PaymentPlan, amountMinor: number,
74
- ): { lineItem: Stripe.Checkout.SessionCreateParams.LineItem; chargeMinor: number; currency: string } => {
75
- if (plan.amountPolicy == null) throw new ProductError(`amount-policy:${plan.sku}`)
76
- assertCheckoutAmount(plan.amountPolicy, amountMinor)
77
- const chargeMinor = chargeAmountMinor(amountMinor, plan.amountPolicy)
78
- const currency = plan.amountPolicy.currency.toLowerCase()
73
+ /** A saved address holding only `country` — stale lines and a postal code of another country cleared. */
74
+ const countryOnlyAddress = (country: string): Stripe.AddressParam => ({
75
+ country, line1: '', line2: '', city: '', state: '', postal_code: '',
76
+ })
77
+
78
+ /**
79
+ * The consumer-rights metadata every session (and its subscription) carries. `termsCollected`
80
+ * says whether Checkout asked for the terms checkbox — `'false'` also after the fallback of a
81
+ * Dashboard without a terms URL; `countryPinned` that tax was calculated on `country`, held on the
82
+ * customer by `stripe.lockCustomerCountry`, so that country is the one the purchase locks.
83
+ */
84
+ const consumerMetadata = (buyer: BuyerContext, params: CreateLinkParams, startRequestId?: string): Record<string, string> =>
85
+ buyer.policy == null ? {} : paymentUtils.compact({
86
+ region: buyer.region ?? undefined,
87
+ country: buyer.country,
88
+ language: buyer.language,
89
+ termsVersion: buyer.policy.textVersion,
90
+ copyVersion: CONSUMER_RIGHTS_COPY_VERSION,
91
+ termsCollected: String(buyer.policy.mechanisms.checkoutTerms === true),
92
+ ipCountry: params.ipCountry?.toUpperCase(),
93
+ startRequestId,
94
+ countryPinned: buyer.countryPinned ? 'true' : undefined,
95
+ }) as Record<string, string>
96
+
97
+ const limited = (message: string, field: string): string => {
98
+ if (message.length > CUSTOM_TEXT_MAX) {
99
+ throw new ConsumerRightsError(`copy:length:${field}`)
100
+ }
101
+
102
+ return message
103
+ }
104
+
105
+ /** The terms checkbox and its text, when the policy asks for them on every checkout. */
106
+ const termsOptions = (buyer: BuyerContext): Partial<Stripe.Checkout.SessionCreateParams> & { terms?: string } => {
107
+ const policy = buyer.policy
108
+ if (policy?.mechanisms.checkoutTerms !== true) {
109
+ return {}
110
+ }
111
+ const links = consumerRightsPolicyHelper.linksOf(policy, buyer.language)
112
+ const withInformation = buyer.inScope && links.withdrawalInformation != null
113
+ const message = limited(consumerCopyHelper.consumerText(buyer.language, `checkout.terms-acceptance.${withInformation ? 'in-scope' : 'other'}`, {
114
+ billingTerms: links.billingTerms, ...(withInformation ? { withdrawalInformation: links.withdrawalInformation as string } : {}),
115
+ }), 'terms')
116
+
117
+ return { consent_collection: { terms_of_service: 'required' }, terms: message }
118
+ }
119
+
120
+ const textContextOf = (buyer: BuyerContext, currency: string, extra: Partial<CheckoutTextContext> = {}): CheckoutTextContext => paymentUtils.compact({
121
+ language: buyer.language, currency, region: buyer.region, country: buyer.country, ...extra,
122
+ }) as CheckoutTextContext
123
+
124
+ const submitTextOf = (params: CreateLinkParams, context: CheckoutTextContext): string | undefined => {
125
+ if (params.submitText == null) {
126
+ return undefined
127
+ }
128
+ const message = typeof params.submitText === 'function' ? params.submitText(context) : params.submitText
129
+
130
+ return message.trim() === '' ? undefined : message
131
+ }
132
+
133
+ /** The same session without the terms checkbox and its text — and saying so in its metadata. */
134
+ const withoutTerms = (params: Stripe.Checkout.SessionCreateParams): Stripe.Checkout.SessionCreateParams => {
135
+ const { consent_collection: consent, custom_text: customText, ...rest } = params
136
+ const { terms_of_service: _terms, ...otherConsent } = consent ?? {}
137
+ const { terms_of_service_acceptance: _acceptance, ...otherText } = customText ?? {}
138
+ const marked = (metadata: Stripe.MetadataParam | undefined): Stripe.MetadataParam | undefined =>
139
+ metadata != null ? { ...metadata, termsCollected: 'false' } : metadata
140
+
79
141
  return {
80
- lineItem: {
81
- price_data: {
82
- product: product.sku, currency, unit_amount: chargeMinor, tax_behavior: 'exclusive',
83
- },
84
- quantity: 1,
85
- },
86
- chargeMinor,
87
- currency,
142
+ ...rest,
143
+ ...(Object.keys(otherConsent).length > 0 ? { consent_collection: otherConsent } : {}),
144
+ ...(Object.keys(otherText).length > 0 ? { custom_text: otherText } : {}),
145
+ metadata: marked(rest.metadata) ?? { termsCollected: 'false' },
146
+ ...(rest.subscription_data != null
147
+ ? { subscription_data: { ...rest.subscription_data, metadata: marked(rest.subscription_data.metadata) ?? { termsCollected: 'false' } } }
148
+ : {}),
88
149
  }
89
150
  }
90
151
 
91
- export const quantityCheckoutLineItem = (
92
- price: Stripe.Price, policy: { minimum: number; maximum: number; default: number },
93
- ): Stripe.Checkout.SessionCreateParams.LineItem => ({
94
- price: price.id,
95
- adjustable_quantity: { enabled: true, minimum: policy.minimum, maximum: policy.maximum },
96
- quantity: policy.default,
97
- })
152
+ /** One console warning per context — a process builds one. */
153
+ const warnedTermsFallback = new WeakSet<object>()
154
+
155
+ export const makeStripeCheckoutHelper = (ctx: ApiContext): StripeCheckoutHelper => {
156
+ const access = paymentAccessOf(ctx)
157
+
158
+ /**
159
+ * The e-mail a checkout pins on its Stripe customer: `params.email` under
160
+ * `stripe.lockCustomerEmail`, `undefined` without the lock.
161
+ *
162
+ * @throws PaygateError('customer-email') — the lock is declared and no usable e-mail was passed
163
+ */
164
+ const lockedEmailOf = async (params: CreateLinkParams): Promise<string | undefined> => {
165
+ if ((await access.stripePricingConfig())?.lockCustomerEmail !== true) {
166
+ return undefined
167
+ }
168
+ const email = params.email?.trim()
169
+ if (email == null || !EMAIL.test(email)) {
170
+ throw new PaygateError('customer-email')
171
+ }
172
+
173
+ return email
174
+ }
98
175
 
99
- export const stripePlugin: PaymentPlugin = {
100
- createLink: async (ctx, params) => {
101
- const stripe = await stripeClient(ctx)
102
- const product = await payment(ctx).product(params.productSku) as PaymentProduct
103
- const plans = await payment(ctx).allPlans(product.sku) as PaymentPlan[]
104
- const customer = await ensureStripeCustomer(ctx, stripe, params)
105
-
106
- if (product.type === ProductType.Consumable) {
107
- const plan = plans.find(item => item.sku === params.planSku) ?? plans[0]
108
- if (plan == null) throw new ProductError('plan')
109
-
110
- if (plan.pricingMode === CheckoutPricingMode.Amount) {
111
- if (params.amountMinor == null) throw new ProductError('amount')
112
- const { lineItem, chargeMinor, currency } = amountCheckoutLineItem(product, plan, params.amountMinor)
113
- const session = await stripe.checkout.sessions.create({
114
- mode: 'payment', line_items: [lineItem], invoice_creation: { enabled: true },
115
- ...taxOptions(false),
116
- ...sharedSession(customer, params, product, plan, {
117
- pricingMode: CheckoutPricingMode.Amount,
118
- currency,
119
- amountMinor: String(params.amountMinor),
120
- chargeAmountMinor: String(chargeMinor),
121
- }),
122
- })
123
- if (session.url == null) throw new PaygateError('session')
124
- return session.url
176
+ /**
177
+ * The entity's Stripe customer, created on first use. Under `stripe.lockCustomerEmail` it carries
178
+ * the buyer's e-mail — written over any other one — because Checkout shows a customer's valid
179
+ * e-mail read-only (and only asks for one, then saves it, while the customer has none).
180
+ */
181
+ const ensureStripeCustomer = async (stripe: Stripe, params: CreateLinkParams): Promise<Stripe.Customer> => {
182
+ const email = await lockedEmailOf(params)
183
+ const resource = access.paygateCustomers()
184
+ const existing = await resource.byEntity(params.entityId, STRIPE_PAYGATE_ALIAS)
185
+ if (existing != null && existing.deletedAt == null) {
186
+ const retrieved = await stripe.customers.retrieve(existing.externalId)
187
+ if (!(retrieved as Stripe.DeletedCustomer).deleted) {
188
+ const customer = retrieved as Stripe.Customer
189
+ const update: Stripe.CustomerUpdateParams = {
190
+ ...(params.locale != null && customer.preferred_locales?.[0] !== params.locale ? { preferred_locales: [params.locale] } : {}),
191
+ ...(email != null && customer.email?.toLowerCase() !== email.toLowerCase() ? { email } : {}),
192
+ }
193
+ return Object.keys(update).length > 0 ? await stripe.customers.update(customer.id, update) : customer
125
194
  }
195
+ }
196
+ const created = await stripe.customers.create({
197
+ metadata: {
198
+ entityId: params.entityId, ...(params.profileId && { profileId: params.profileId }),
199
+ service: params.service,
200
+ },
201
+ ...(params.locale != null ? { preferred_locales: [params.locale] } : {}),
202
+ ...(email != null ? { email } : {}),
203
+ })
204
+ if (existing != null) {
205
+ const { deletedAt: _deleted, ...kept } = existing
206
+ await resource.update({ ...kept, externalId: created.id })
207
+ } else {
208
+ await resource.create({
209
+ paygate: STRIPE_PAYGATE_ALIAS, externalId: created.id, entityId: params.entityId,
210
+ ...(params.profileId != null ? { profileId: params.profileId } : {}),
211
+ })
212
+ }
213
+ return created
214
+ }
215
+
216
+ const findPrice = async (stripe: Stripe, productSku: string, lookupKey: string): Promise<Stripe.Price> => {
217
+ const prices = await stripe.prices.list({ product: productSku, active: true, lookup_keys: [lookupKey] })
218
+ if (prices.data.length === 0) throw new ProductError(`price:${lookupKey}`)
219
+ return prices.data[0]
220
+ }
221
+
222
+ /**
223
+ * The buyer as the consumer-rights policy sees it — a locked profile overrides the declared
224
+ * country (a different one is `BillingCountryLocked`), an organization that already paid before
225
+ * its country was locked is locked lazily from its paygate customer's address, and a locked
226
+ * customer address that no longer carries the locked country refuses (the operator relocks).
227
+ *
228
+ * Under `stripe.lockCustomerCountry` the known country (the locked one, else the declared one) is
229
+ * written to the customer — over a saved address of another country only before any lock — and
230
+ * Checkout keeps it wherever Stripe Tax can calculate on it.
231
+ */
232
+ const buyerOf = async (
233
+ stripe: Stripe, params: CreateLinkParams, catalogueCurrency: string,
234
+ ): Promise<{ buyer: BuyerContext, customer: Stripe.Customer }> => {
235
+ const policy = await access.payment().consumerRightsPolicy()
236
+ const rights = policy != null ? access.consumerRightsOf() : null
237
+ let profile = rights != null ? await rights.profile(params.entityId) : null
238
+ const declared = params.country != null && params.country.trim() !== '' ? params.country.trim().toUpperCase() : undefined
239
+ if (profile?.locked === true && declared != null && declared !== profile.country) {
240
+ throw new BillingCountryLocked({ country: profile.country as string, requested: declared })
241
+ }
242
+ let customer = await ensureStripeCustomer(stripe, params)
243
+ const customerCountry = customer.address?.country?.toUpperCase() ?? undefined
244
+ if (rights != null && policy?.mechanisms.countryLock === true && profile == null && customerCountry != null
245
+ && await consumerRecordsOf(ctx).hasPaid(params.entityId)
246
+ && !await consumerRecordsOf(ctx).wasUnlocked(params.entityId)) {
247
+ // An organization that paid before countries were locked: its saved address is its country.
248
+ // One an operator unlocked is locked again by its next completed purchase instead.
249
+ profile = await rights.lock(params.entityId, customerCountry, 'customer', { customerId: customer.id })
250
+ }
251
+ if (profile?.locked === true && declared != null && declared !== profile.country) {
252
+ throw new BillingCountryLocked({ country: profile.country as string, requested: declared })
253
+ }
254
+ if (profile?.locked === true && customerCountry != null && customerCountry !== profile.country) {
255
+ throw new BillingCountryLocked({ country: profile.country as string, requested: customerCountry })
256
+ }
257
+ const pinning = (await access.stripePricingConfig())?.lockCustomerCountry === true
258
+ const country = profile?.country ?? declared
259
+ if (pinning && country != null && customerCountry !== country) {
260
+ // Pinned: the known country replaces whatever an unlocked customer saved (a locked customer's
261
+ // other country was refused above), so Checkout has nothing else to offer.
262
+ customer = await stripe.customers.update(customer.id, { address: countryOnlyAddress(country) })
263
+ } else if (policy != null && profile == null && declared != null && customerCountry == null) {
264
+ // Preselect the declared country on Checkout's address form; never over a saved address.
265
+ customer = await stripe.customers.update(customer.id, { address: { country: declared } })
266
+ }
267
+ const savedCountry = customer.address?.country?.toUpperCase() ?? undefined
268
+ const kept = savedCountry != null && savedCountry === country && stripeSessionHelper.isTaxLocatable(customer.address)
269
+ const countryPinned = pinning && kept
270
+ const region = policy != null ? consumerRegionHelper.regionOf(country, policy) : null
271
+ const settlement = (await access.stripePricingConfig())?.settlementCurrency?.toLowerCase()
272
+ const regional = policy?.currencies != null && Object.keys(policy.currencies).length > 0
273
+
274
+ return {
275
+ customer,
276
+ buyer: {
277
+ policy,
278
+ profile,
279
+ ...(country != null ? { country } : {}),
280
+ region,
281
+ inScope: policy != null ? consumerRegionHelper.inScope(region, country, policy) : false,
282
+ language: params.consumerLanguage ?? profile?.language ?? consumerRegionHelper.billingLanguageOf(country, policy),
283
+ chargeCurrency: regional
284
+ ? (profile?.currency ?? consumerRegionHelper.chargeCurrencyOf(region, policy, settlement ?? catalogueCurrency)).toLowerCase()
285
+ : null,
286
+ addressLocked: kept && (profile?.locked === true || countryPinned),
287
+ countryPinned,
288
+ },
289
+ }
290
+ }
126
291
 
127
- const price = await findPrice(stripe, product.sku, planLookupKey(product, plan))
128
- const policy = plan.quantityPolicy ?? {
129
- minimum: plan.minQuantity ?? plan.limits?.['consumable:units']?.limit ?? 1,
292
+ /** Whether the synced reusable price of a plan can be charged in `currency` (its default or an option). */
293
+ const priceCarries = async (
294
+ product: PaymentProduct, plan: PaymentPlan, price: Stripe.Price, currency: string,
295
+ ): Promise<{ carries: boolean, unitAmount?: number }> => {
296
+ if (price.currency === currency) {
297
+ return { carries: true, ...(price.unit_amount != null ? { unitAmount: price.unit_amount } : {}) }
298
+ }
299
+ const listed = (price as unknown as { currency_options?: Record<string, { unit_amount?: number | null }> }).currency_options?.[currency]
300
+ if (listed != null) {
301
+ return { carries: true, ...(listed.unit_amount != null ? { unitAmount: listed.unit_amount } : {}) }
302
+ }
303
+ const synced = (await access.fingerprints().bySku(product.sku))?.prices?.find(entry => entry.planSku === plan.sku && entry.priceId === price.id)
304
+ const option = synced?.options.find(entry => entry.currency === currency)
305
+
306
+ return option != null ? { carries: true, unitAmount: option.unitAmount } : { carries: false }
307
+ }
308
+
309
+ /**
310
+ * A Dashboard without a terms-of-service URL must never stop a payment: the session is created
311
+ * once more without the checkbox, an operator is told (once), and the degraded checkout is audited
312
+ * as a `checkout-terms-fallback` event of the organization (`externalId` = the session).
313
+ */
314
+ const createWithoutTerms = async (
315
+ stripe: Stripe, attempt: CheckoutAttempt, params: Stripe.Checkout.SessionCreateParams, refusal: unknown,
316
+ ): Promise<Stripe.Checkout.Session> => {
317
+ const stripeMessage = paymentUtils.errorText(refusal)
318
+ if (!warnedTermsFallback.has(ctx)) {
319
+ warnedTermsFallback.add(ctx)
320
+ log.warn('Stripe refused the terms-of-service checkbox: this account has no terms of service URL. '
321
+ + 'Checkouts continue WITHOUT the checkbox (metadata termsCollected=false). Operator: set the Billing Terms URL '
322
+ + 'in the Stripe Dashboard → Settings → Public details (test and live mode alike).')
323
+ }
324
+ const typed = refusal as StripeErrorShape
325
+ const detail = JSON.stringify(paymentUtils.compact({
326
+ message: stripeMessage, code: typed.code ?? typed.raw?.code, param: typed.param ?? typed.raw?.param,
327
+ mode: attempt.mode, productSku: attempt.productSku, planSku: attempt.planSku,
328
+ }))
329
+ try {
330
+ const session = await stripe.checkout.sessions.create(withoutTerms(params))
331
+ await consumerRecordsOf(ctx).recordEvent({
332
+ recordId: attempt.entityId, recordKind: 'checkout', entityId: attempt.entityId, action: 'checkout-terms-fallback',
333
+ ok: false, externalId: session.id, detail,
334
+ })
335
+
336
+ return session
337
+ } catch (error) {
338
+ await consumerRecordsOf(ctx).recordEvent({
339
+ recordId: attempt.entityId, recordKind: 'checkout', entityId: attempt.entityId, action: 'checkout-terms-fallback',
340
+ ok: false, detail, error: paymentUtils.errorText(error),
341
+ })
342
+ throw error
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Create the session, then tell the plugins it exists. A plugin's `created` that throws expires
348
+ * the fresh session and releases every admission before the error propagates. A session Stripe
349
+ * refuses for the terms checkbox alone (no terms URL in the Dashboard) is created once more
350
+ * without it — under the same admissions.
351
+ */
352
+ const createSession = async (
353
+ stripe: Stripe, plugins: readonly CheckoutPlugin[], attempt: CheckoutAttempt,
354
+ params: Stripe.Checkout.SessionCreateParams,
355
+ ): Promise<string> => {
356
+ const admitted: Admitted[] = await checkoutPluginsOf(ctx).admitCheckout(plugins, attempt)
357
+ const holders = admitted.filter(entry => entry.plugin.admit != null)
358
+ let session: Stripe.Checkout.Session
359
+ try {
360
+ try {
361
+ session = await stripe.checkout.sessions.create(params)
362
+ } catch (error) {
363
+ if (params.consent_collection?.terms_of_service !== 'required' || !stripeSessionHelper.isMissingTermsUrl(error)) {
364
+ throw error
365
+ }
366
+ session = await createWithoutTerms(stripe, attempt, params, error)
367
+ }
368
+ } catch (error) {
369
+ await checkoutPluginsOf(ctx).releaseAdmitted(holders, attempt)
370
+ throw error
371
+ }
372
+ if (session.url == null) {
373
+ await checkoutPluginsOf(ctx).releaseAdmitted(holders, attempt, session.id)
374
+ throw new PaygateError('session')
375
+ }
376
+ for (const { plugin, reservationId } of admitted) {
377
+ if (plugin.created == null) {
378
+ continue
379
+ }
380
+ try {
381
+ await plugin.created(ctx, { ...attempt, sessionId: session.id, url: session.url, ...(reservationId != null ? { reservationId } : {}) })
382
+ } catch (error) {
383
+ try {
384
+ await stripe.checkout.sessions.expire(session.id)
385
+ } catch (expireError) {
386
+ log.error('Could not expire a checkout a plugin refused', { sessionId: session.id, error: expireError })
387
+ }
388
+ await checkoutPluginsOf(ctx).releaseAdmitted(holders, attempt, session.id)
389
+ throw error
390
+ }
391
+ }
392
+
393
+ return session.url
394
+ }
395
+
396
+ const createCheckoutLink = async (
397
+ stripe: Stripe, params: CreateLinkParams, plugins: readonly CheckoutPlugin[] = [],
398
+ ): Promise<string> => {
399
+ const product = await access.payment().product(params.productSku) as PaymentProduct
400
+ const plans = (await access.payment().allPlans(product.sku) as PaymentPlan[])
401
+ .filter(plan => planHelper.isSoldThrough(product, plan, STRIPE_PAYGATE_ALIAS))
402
+ if (params.planSku != null && !plans.some(plan => plan.sku === params.planSku)) {
403
+ throw new ProductError(`plan:${params.planSku}`)
404
+ }
405
+ const consumable = product.type === ProductType.Consumable
406
+ const plan = consumable
407
+ ? plans.find(item => item.sku === params.planSku) ?? plans[0]
408
+ : plans.find(item => item.sku === params.planSku) ?? plans.find(item => item.recurring != null) ?? plans[0]
409
+ if (plan == null) throw new ProductError('plan')
410
+ const catalogueCurrency = (plan.amountPolicy?.currency ?? plan.currency ?? 'usd').toLowerCase()
411
+ const { buyer, customer } = await buyerOf(stripe, params, catalogueCurrency)
412
+ const pricing = await access.payment().pricingPolicy()
413
+ const settlement = (await access.stripePricingConfig())?.settlementCurrency?.toLowerCase()
414
+ const ttl = checkoutPolicyHelper.sessionTtlOf(plugins)
415
+ const now = new Date()
416
+ const expiresAt = ttl != null ? new Date((Math.floor(now.getTime() / 1000) + ttl) * 1000) : undefined
417
+ const expiry = expiresAt != null ? { expires_at: Math.floor(expiresAt.getTime() / 1000) } : {}
418
+ const { terms, ...termsParams } = termsOptions(buyer)
419
+ const base = {
420
+ entityId: params.entityId, productSku: product.sku, planSku: plan.sku, at: now,
421
+ ...(ttl != null ? { sessionTtlSeconds: ttl } : {}), ...(expiresAt != null ? { expiresAt } : {}),
422
+ }
423
+
424
+ if (consumable && plan.pricingMode === CheckoutPricingMode.Amount) {
425
+ if (params.amountMinor == null) throw new ProductError('amount')
426
+ const { chargeMinor: sourceChargeMinor, currency: amountCurrency } = stripeSessionHelper.amountCheckoutLineItem(
427
+ product, plan, params.amountMinor, pricing.tax.behavior,
428
+ )
429
+ const view = await checkoutPluginsOf(ctx).narrowAmountFor(plugins, {
430
+ entityId: params.entityId, productSku: product.sku, planSku: plan.sku,
431
+ base: plan.amountPolicy as NonNullable<PaymentPlan['amountPolicy']>, at: now,
432
+ })
433
+ checkoutPolicyHelper.assertAmountAllowed(view, params.amountMinor)
434
+ const charged = buyer.chargeCurrency != null
435
+ ? await fxOf(ctx).chargeAmount(stripe, sourceChargeMinor, amountCurrency, buyer.chargeCurrency)
436
+ : await fxOf(ctx).settlementAmount(stripe, sourceChargeMinor, amountCurrency)
437
+ const adaptive = buyer.chargeCurrency == null || charged.currency === (settlement ?? amountCurrency)
438
+ const context = textContextOf(buyer, charged.currency, { unitAmountMinor: charged.amountMinor })
439
+ const submit = submitTextOf(params, context)
440
+ ?? (buyer.policy != null && buyer.inScope && buyer.country != null
441
+ ? consumerCopyHelper.consumerText(buyer.language, 'checkout.top-up', {
442
+ product: product.title, country: consumerFormatHelper.countryName(buyer.country, buyer.language),
443
+ })
444
+ : undefined)
445
+ const customText = paymentUtils.compact({
446
+ ...(submit != null ? { submit: { message: limited(submit, 'submit') } } : {}),
447
+ ...(terms != null ? { terms_of_service_acceptance: { message: terms } } : {}),
448
+ })
449
+ const lineItem: Stripe.Checkout.SessionCreateParams.LineItem = {
450
+ price_data: {
451
+ product: product.sku, currency: charged.currency, unit_amount: charged.amountMinor,
452
+ tax_behavior: pricing.tax.behavior,
453
+ },
454
+ quantity: 1,
455
+ }
456
+
457
+ return await createSession(stripe, plugins, {
458
+ ...base, mode: 'amount', amountMinor: params.amountMinor, amountCurrency, chargeMinor: charged.amountMinor,
459
+ currency: charged.currency,
460
+ }, {
461
+ mode: 'payment', line_items: [lineItem], invoice_creation: { enabled: true },
462
+ ...checkoutOptions(pricing, false, { locked: buyer.addressLocked, adaptive }),
463
+ ...termsParams,
464
+ ...(Object.keys(customText).length > 0 ? { custom_text: customText } : {}),
465
+ ...expiry,
466
+ ...sharedSession(customer, params, product, plan, {
467
+ pricingMode: CheckoutPricingMode.Amount,
468
+ currency: charged.currency,
469
+ amountCurrency,
470
+ amountMinor: String(params.amountMinor),
471
+ sourceChargeAmountMinor: String(sourceChargeMinor),
472
+ chargeAmountMinor: String(charged.amountMinor),
473
+ ...consumerMetadata(buyer, params),
474
+ }),
475
+ })
476
+ }
477
+
478
+ const price = await findPrice(stripe, product.sku, planHelper.planLookupKey(product, plan))
479
+ const forced = buyer.chargeCurrency != null
480
+ ? await priceCarries(product, plan, price, buyer.chargeCurrency) : { carries: false }
481
+ if (buyer.chargeCurrency != null && !forced.carries) {
482
+ log.warn('Plan has no price in the charge currency; Stripe picks the currency', { plan: plan.sku, currency: buyer.chargeCurrency })
483
+ }
484
+ const currency = forced.carries ? buyer.chargeCurrency as string : price.currency
485
+ const adaptive = buyer.chargeCurrency == null || currency === (settlement ?? price.currency)
486
+ // Forced only when the synced price carries it: a session currency the price lacks is refused.
487
+ const currencyParam = forced.carries ? { currency } : {}
488
+
489
+ if (consumable) {
490
+ const quantityPolicy = plan.quantityPolicy ?? {
491
+ minimum: plan.minQuantity ?? 1,
130
492
  maximum: plan.maxQuantity ?? Math.max(100_000, plan.minQuantity ?? 1),
131
493
  default: plan.defaultQuantity ?? plan.minQuantity ?? 1,
132
494
  }
133
- const session = await stripe.checkout.sessions.create({
495
+ const submit = submitTextOf(params, textContextOf(buyer, currency, paymentUtils.compact({ unitAmountMinor: forced.unitAmount ?? price.unit_amount ?? undefined })))
496
+ const customText = paymentUtils.compact({
497
+ ...(submit != null ? { submit: { message: limited(submit, 'submit') } } : {}),
498
+ ...(terms != null ? { terms_of_service_acceptance: { message: terms } } : {}),
499
+ })
500
+
501
+ return await createSession(stripe, plugins, { ...base, mode: 'quantity', currency }, {
134
502
  mode: 'payment',
135
- line_items: [quantityCheckoutLineItem(price, policy)],
503
+ line_items: [stripeSessionHelper.quantityCheckoutLineItem(price, quantityPolicy)],
136
504
  invoice_creation: { enabled: true },
137
- ...taxOptions(true),
138
- ...sharedSession(customer, params, product, plan, { pricingMode: CheckoutPricingMode.Quantity }),
505
+ ...currencyParam,
506
+ ...checkoutOptions(pricing, true, { locked: buyer.addressLocked, adaptive }),
507
+ ...termsParams,
508
+ ...(Object.keys(customText).length > 0 ? { custom_text: customText } : {}),
509
+ ...expiry,
510
+ ...sharedSession(customer, params, product, plan, {
511
+ pricingMode: CheckoutPricingMode.Quantity,
512
+ ...(forced.carries ? { currency } : {}),
513
+ ...consumerMetadata(buyer, params),
514
+ }),
139
515
  })
140
- if (session.url == null) throw new PaygateError('session')
141
- return session.url
142
516
  }
143
517
 
144
- const plan = plans.find(item => item.sku === params.planSku)
145
- ?? plans.find(item => item.recurring != null) ?? plans[0]
146
- if (plan == null) throw new ProductError('plan')
147
- const price = await findPrice(stripe, product.sku, planLookupKey(product, plan))
148
- const session = await stripe.checkout.sessions.create({
518
+ // A subscription starts services at once: in scope (or unknown and protected) it needs the
519
+ // consumer's express start request, fresh and bound to this organization and plan.
520
+ const start = buyer.policy != null ? await access.consumerRightsOf()?.assertStartRequest(params.entityId, plan.sku, params.startRequestId) ?? null : null
521
+ const stripePricing = await access.stripePricingConfig()
522
+ const subscriptionPaymentMethodTypes = (stripePricing?.subscriptionPaymentMethodTypesByCurrency?.[currency]
523
+ ?? stripePricing?.subscriptionPaymentMethodTypes) as string[] | undefined
524
+ const unitAmount = forced.unitAmount ?? price.unit_amount ?? undefined
525
+ const interval = plan.recurring?.interval
526
+ const context = textContextOf(buyer, currency, paymentUtils.compact({ unitAmountMinor: unitAmount, interval }))
527
+ const renewal = buyer.policy != null && unitAmount != null && interval != null
528
+ ? consumerCopyHelper.consumerText(buyer.language, `checkout.renewal.${interval}`, {
529
+ price: consumerCopyHelper.consumerText(buyer.language, `checkout.price.${pricing.tax.behavior === TaxBehavior.Inclusive ? 'inclusive' : 'exclusive'}`, {
530
+ amount: consumerFormatHelper.formatMoney(unitAmount, currency, buyer.language),
531
+ }),
532
+ })
533
+ : undefined
534
+ const submit = submitTextOf(params, context) ?? renewal
535
+ const links = buyer.policy != null ? consumerRightsPolicyHelper.linksOf(buyer.policy, buyer.language) : null
536
+ const afterSubmit = buyer.policy?.mechanisms.cancellation === true && links?.cancellation != null
537
+ ? consumerCopyHelper.consumerText(buyer.language, 'checkout.renewal.after-submit', { cancelUrl: links.cancellation })
538
+ : undefined
539
+ const customText = paymentUtils.compact({
540
+ ...(submit != null ? { submit: { message: limited(submit, 'submit') } } : {}),
541
+ ...(afterSubmit != null ? { after_submit: { message: limited(afterSubmit, 'after-submit') } } : {}),
542
+ ...(terms != null ? { terms_of_service_acceptance: { message: terms } } : {}),
543
+ })
544
+ const startRequestId = start?.id ?? undefined
545
+ const metadata = consumerMetadata(buyer, params, startRequestId)
546
+
547
+ return await createSession(stripe, plugins, { ...base, mode: 'subscription', currency }, {
149
548
  mode: 'subscription', line_items: [{ price: price.id, quantity: 1 }],
549
+ ...currencyParam,
550
+ ...(subscriptionPaymentMethodTypes != null ? { payment_method_types: subscriptionPaymentMethodTypes } : {}),
551
+ ...(Object.keys(customText).length > 0 ? { custom_text: customText } : {}),
150
552
  subscription_data: {
151
553
  metadata: {
152
554
  pricingMode: CheckoutPricingMode.Quantity, entityId: params.entityId,
153
555
  service: params.service, productSku: product.sku, planSku: plan.sku,
556
+ ...(params.profileId != null ? { profileId: params.profileId } : {}),
557
+ ...metadata,
154
558
  },
155
559
  },
156
- ...taxOptions(true),
157
- ...sharedSession(customer, params, product, plan, {}),
560
+ ...checkoutOptions(pricing, true, { locked: buyer.addressLocked, adaptive }),
561
+ ...termsParams,
562
+ ...expiry,
563
+ ...sharedSession(customer, params, product, plan, metadata),
158
564
  })
159
- if (session.url == null) throw new PaygateError('session')
160
- return session.url
161
- },
162
-
163
- handleWebhook: async (request, ctx) => {
164
- const config = await stripeConfig(ctx)
165
- const stripe = await stripeClient(ctx)
166
- const typed = request as {
167
- original?: { rawBody?: string | Buffer }; rawBody?: string | Buffer
168
- headers: Record<string, string | string[] | undefined>
169
- }
170
- const rawBody = typed.original?.rawBody ?? typed.rawBody
171
- const signature = typed.headers[STRIPE_SIGNATURE.toLowerCase()]
172
- if (rawBody == null || typeof signature !== 'string') throw new PaygateError('signature')
173
- const event = await stripe.webhooks.constructEventAsync(rawBody, signature, config.webhook)
174
- await createEventHandler(ctx, stripe).process(event)
175
- },
565
+ }
176
566
 
177
- manageSubscription: async (ctx, entityId, returnUrl) => {
178
- const stripe = await stripeClient(ctx)
179
- const customer = await paygateCustomers(ctx).byEntity(entityId, STRIPE_PAYGATE_ALIAS)
180
- if (customer == null) throw new PaygateError('customer')
181
- return (await stripe.billingPortal.sessions.create({ customer: customer.externalId, return_url: returnUrl })).url
182
- },
567
+ return { createCheckoutLink }
183
568
  }
569
+
570
+ /** The Stripe Checkout of a context — one per context. */
571
+ export const stripeCheckoutOf = memoHelper.oncePer(makeStripeCheckoutHelper)