@owlmeans/server-payment 0.1.20-rc.1 → 0.2.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/README.md +52 -54
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/server-payment/SKILL.md +272 -330
  4. package/agent-meta/skills/server-payment/parts/reference.md +3 -3
  5. package/build/access/types.d.ts +7 -16
  6. package/build/access/types.d.ts.map +1 -1
  7. package/build/access.d.ts.map +1 -1
  8. package/build/access.js +6 -8
  9. package/build/access.js.map +1 -1
  10. package/build/actions/resync.d.ts +3 -3
  11. package/build/actions/resync.js +5 -5
  12. package/build/actions/resync.js.map +1 -1
  13. package/build/actions/webhook.d.ts +4 -1
  14. package/build/actions/webhook.d.ts.map +1 -1
  15. package/build/actions/webhook.js +8 -4
  16. package/build/actions/webhook.js.map +1 -1
  17. package/build/bootstrap/types.d.ts +13 -7
  18. package/build/bootstrap/types.d.ts.map +1 -1
  19. package/build/bootstrap.d.ts +4 -4
  20. package/build/bootstrap.d.ts.map +1 -1
  21. package/build/bootstrap.js +19 -10
  22. package/build/bootstrap.js.map +1 -1
  23. package/build/catalogue/types.d.ts +3 -3
  24. package/build/catalogue/types.d.ts.map +1 -1
  25. package/build/catalogue.d.ts.map +1 -1
  26. package/build/catalogue.js +4 -8
  27. package/build/catalogue.js.map +1 -1
  28. package/build/checkout/types.d.ts +21 -0
  29. package/build/checkout/types.d.ts.map +1 -0
  30. package/build/{plugins/stripe → checkout}/types.js.map +1 -1
  31. package/build/checkout.d.ts +6 -0
  32. package/build/checkout.d.ts.map +1 -0
  33. package/build/checkout.js +374 -0
  34. package/build/checkout.js.map +1 -0
  35. package/build/config.d.ts +10 -16
  36. package/build/config.d.ts.map +1 -1
  37. package/build/config.js +18 -59
  38. package/build/config.js.map +1 -1
  39. package/build/consts.d.ts +3 -49
  40. package/build/consts.d.ts.map +1 -1
  41. package/build/consts.js +3 -61
  42. package/build/consts.js.map +1 -1
  43. package/build/consumer/cancellation/types.d.ts +6 -4
  44. package/build/consumer/cancellation/types.d.ts.map +1 -1
  45. package/build/consumer/cancellation.d.ts.map +1 -1
  46. package/build/consumer/cancellation.js +11 -5
  47. package/build/consumer/cancellation.js.map +1 -1
  48. package/build/consumer/capture/types.d.ts +8 -12
  49. package/build/consumer/capture/types.d.ts.map +1 -1
  50. package/build/consumer/capture.d.ts.map +1 -1
  51. package/build/consumer/capture.js +48 -53
  52. package/build/consumer/capture.js.map +1 -1
  53. package/build/consumer/index.d.ts +4 -0
  54. package/build/consumer/index.d.ts.map +1 -1
  55. package/build/consumer/index.js +2 -0
  56. package/build/consumer/index.js.map +1 -1
  57. package/build/consumer/reconcile.d.ts.map +1 -1
  58. package/build/consumer/reconcile.js +82 -72
  59. package/build/consumer/reconcile.js.map +1 -1
  60. package/build/consumer/records/types.d.ts +4 -4
  61. package/build/consumer/records/types.d.ts.map +1 -1
  62. package/build/consumer/records.d.ts.map +1 -1
  63. package/build/consumer/records.js +16 -13
  64. package/build/consumer/records.js.map +1 -1
  65. package/build/consumer/service.d.ts +2 -2
  66. package/build/consumer/service.d.ts.map +1 -1
  67. package/build/consumer/service.js +28 -21
  68. package/build/consumer/service.js.map +1 -1
  69. package/build/consumer/types.d.ts +1 -4
  70. package/build/consumer/types.d.ts.map +1 -1
  71. package/build/consumer/types.local.d.ts +1 -9
  72. package/build/consumer/types.local.d.ts.map +1 -1
  73. package/build/consumer/withdrawal/types.d.ts +14 -12
  74. package/build/consumer/withdrawal/types.d.ts.map +1 -1
  75. package/build/consumer/withdrawal.d.ts.map +1 -1
  76. package/build/consumer/withdrawal.js +55 -71
  77. package/build/consumer/withdrawal.js.map +1 -1
  78. package/build/index.d.ts +12 -6
  79. package/build/index.d.ts.map +1 -1
  80. package/build/index.js +7 -4
  81. package/build/index.js.map +1 -1
  82. package/build/paygate/providers.d.ts +13 -0
  83. package/build/paygate/providers.d.ts.map +1 -0
  84. package/build/paygate/providers.js +38 -0
  85. package/build/paygate/providers.js.map +1 -0
  86. package/build/paygate/registry.d.ts +6 -0
  87. package/build/paygate/registry.d.ts.map +1 -0
  88. package/build/paygate/registry.js +37 -0
  89. package/build/paygate/registry.js.map +1 -0
  90. package/build/paygate/types.d.ts +577 -0
  91. package/build/paygate/types.d.ts.map +1 -0
  92. package/build/{plugins/session → paygate}/types.js.map +1 -1
  93. package/build/plan/types.d.ts +6 -1
  94. package/build/plan/types.d.ts.map +1 -1
  95. package/build/plan.d.ts.map +1 -1
  96. package/build/plan.js +16 -2
  97. package/build/plan.js.map +1 -1
  98. package/build/plugins/checkout-policy/types.d.ts +5 -3
  99. package/build/plugins/checkout-policy/types.d.ts.map +1 -1
  100. package/build/plugins/checkout-policy.d.ts.map +1 -1
  101. package/build/plugins/checkout-policy.js +5 -3
  102. package/build/plugins/checkout-policy.js.map +1 -1
  103. package/build/plugins/consts.local.d.ts +8 -10
  104. package/build/plugins/consts.local.d.ts.map +1 -1
  105. package/build/plugins/consts.local.js +2 -19
  106. package/build/plugins/consts.local.js.map +1 -1
  107. package/build/plugins/customer-lock/types.d.ts +2 -2
  108. package/build/plugins/customer-lock/types.d.ts.map +1 -1
  109. package/build/plugins/customer-lock.js +2 -2
  110. package/build/plugins/customer-lock.js.map +1 -1
  111. package/build/plugins/estimate/cache.js +1 -1
  112. package/build/plugins/estimate/cache.js.map +1 -1
  113. package/build/plugins/estimate/types.d.ts +10 -10
  114. package/build/plugins/estimate/types.d.ts.map +1 -1
  115. package/build/plugins/estimate.d.ts.map +1 -1
  116. package/build/plugins/estimate.js +48 -122
  117. package/build/plugins/estimate.js.map +1 -1
  118. package/build/plugins/events/types.d.ts +17 -10
  119. package/build/plugins/events/types.d.ts.map +1 -1
  120. package/build/plugins/events.d.ts +6 -5
  121. package/build/plugins/events.d.ts.map +1 -1
  122. package/build/plugins/events.js +162 -173
  123. package/build/plugins/events.js.map +1 -1
  124. package/build/plugins/fx/types.d.ts +10 -21
  125. package/build/plugins/fx/types.d.ts.map +1 -1
  126. package/build/plugins/fx.d.ts +1 -1
  127. package/build/plugins/fx.d.ts.map +1 -1
  128. package/build/plugins/fx.js +17 -54
  129. package/build/plugins/fx.js.map +1 -1
  130. package/build/plugins/portal/types.d.ts +8 -37
  131. package/build/plugins/portal/types.d.ts.map +1 -1
  132. package/build/plugins/portal.d.ts.map +1 -1
  133. package/build/plugins/portal.js +38 -208
  134. package/build/plugins/portal.js.map +1 -1
  135. package/build/plugins/refunds/types.d.ts +11 -11
  136. package/build/plugins/refunds/types.d.ts.map +1 -1
  137. package/build/plugins/refunds.d.ts.map +1 -1
  138. package/build/plugins/refunds.js +14 -39
  139. package/build/plugins/refunds.js.map +1 -1
  140. package/build/plugins/snapshot/types.d.ts +11 -0
  141. package/build/plugins/snapshot/types.d.ts.map +1 -0
  142. package/build/plugins/snapshot/types.js +2 -0
  143. package/build/plugins/snapshot/types.js.map +1 -0
  144. package/build/plugins/snapshot.d.ts +4 -0
  145. package/build/plugins/snapshot.d.ts.map +1 -0
  146. package/build/plugins/snapshot.js +19 -0
  147. package/build/plugins/snapshot.js.map +1 -0
  148. package/build/plugins/subscriptions/types.d.ts +17 -17
  149. package/build/plugins/subscriptions/types.d.ts.map +1 -1
  150. package/build/plugins/subscriptions.d.ts +4 -4
  151. package/build/plugins/subscriptions.d.ts.map +1 -1
  152. package/build/plugins/subscriptions.js +69 -77
  153. package/build/plugins/subscriptions.js.map +1 -1
  154. package/build/plugins/types.local.d.ts +9 -43
  155. package/build/plugins/types.local.d.ts.map +1 -1
  156. package/build/plugins/webhook-manager/types.d.ts +15 -43
  157. package/build/plugins/webhook-manager/types.d.ts.map +1 -1
  158. package/build/plugins/webhook-manager.d.ts +3 -3
  159. package/build/plugins/webhook-manager.d.ts.map +1 -1
  160. package/build/plugins/webhook-manager.js +21 -199
  161. package/build/plugins/webhook-manager.js.map +1 -1
  162. package/build/protocol.d.ts +1 -1
  163. package/build/protocol.d.ts.map +1 -1
  164. package/build/protocol.js +1 -1
  165. package/build/protocol.js.map +1 -1
  166. package/build/service.d.ts +11 -11
  167. package/build/service.d.ts.map +1 -1
  168. package/build/service.js +59 -23
  169. package/build/service.js.map +1 -1
  170. package/build/sync/types.d.ts +17 -13
  171. package/build/sync/types.d.ts.map +1 -1
  172. package/build/sync.d.ts.map +1 -1
  173. package/build/sync.js +22 -122
  174. package/build/sync.js.map +1 -1
  175. package/build/types.d.ts +46 -101
  176. package/build/types.d.ts.map +1 -1
  177. package/build/utils/types.d.ts +0 -8
  178. package/build/utils/types.d.ts.map +1 -1
  179. package/build/utils.d.ts +1 -4
  180. package/build/utils.d.ts.map +1 -1
  181. package/build/utils.js +1 -15
  182. package/build/utils.js.map +1 -1
  183. package/package.json +20 -22
  184. package/src/access/types.ts +7 -16
  185. package/src/access.ts +7 -15
  186. package/src/actions/resync.ts +5 -5
  187. package/src/actions/webhook.ts +8 -4
  188. package/src/bootstrap/types.ts +13 -7
  189. package/src/bootstrap.ts +23 -13
  190. package/src/catalogue/types.ts +3 -3
  191. package/src/catalogue.ts +4 -8
  192. package/src/checkout/types.ts +21 -0
  193. package/src/checkout.ts +414 -0
  194. package/src/config.ts +19 -66
  195. package/src/consts.ts +3 -69
  196. package/src/consumer/cancellation/types.ts +6 -4
  197. package/src/consumer/cancellation.ts +13 -7
  198. package/src/consumer/capture/types.ts +8 -12
  199. package/src/consumer/capture.ts +50 -59
  200. package/src/consumer/index.ts +4 -0
  201. package/src/consumer/reconcile.ts +69 -68
  202. package/src/consumer/records/types.ts +4 -4
  203. package/src/consumer/records.ts +19 -14
  204. package/src/consumer/service.ts +35 -22
  205. package/src/consumer/types.local.ts +1 -8
  206. package/src/consumer/types.ts +1 -4
  207. package/src/consumer/withdrawal/types.ts +14 -12
  208. package/src/consumer/withdrawal.ts +61 -77
  209. package/src/index.ts +12 -6
  210. package/src/paygate/providers.ts +48 -0
  211. package/src/paygate/registry.ts +53 -0
  212. package/src/paygate/types.ts +640 -0
  213. package/src/plan/types.ts +6 -1
  214. package/src/plan.ts +21 -3
  215. package/src/plugins/checkout-policy/types.ts +5 -3
  216. package/src/plugins/checkout-policy.ts +6 -5
  217. package/src/plugins/consts.local.ts +2 -26
  218. package/src/plugins/customer-lock/types.ts +2 -2
  219. package/src/plugins/customer-lock.ts +2 -2
  220. package/src/plugins/estimate/cache.ts +1 -1
  221. package/src/plugins/estimate/types.ts +10 -10
  222. package/src/plugins/estimate.ts +52 -128
  223. package/src/plugins/events/types.ts +17 -9
  224. package/src/plugins/events.ts +172 -190
  225. package/src/plugins/fx/types.ts +10 -23
  226. package/src/plugins/fx.ts +28 -64
  227. package/src/plugins/portal/types.ts +8 -38
  228. package/src/plugins/portal.ts +48 -229
  229. package/src/plugins/refunds/types.ts +11 -11
  230. package/src/plugins/refunds.ts +16 -40
  231. package/src/plugins/snapshot/types.ts +11 -0
  232. package/src/plugins/snapshot.ts +22 -0
  233. package/src/plugins/subscriptions/types.ts +17 -17
  234. package/src/plugins/subscriptions.ts +81 -81
  235. package/src/plugins/types.local.ts +9 -33
  236. package/src/plugins/webhook-manager/types.ts +15 -43
  237. package/src/plugins/webhook-manager.ts +24 -220
  238. package/src/protocol.ts +1 -1
  239. package/src/service.ts +66 -30
  240. package/src/sync/types.ts +17 -13
  241. package/src/sync.ts +25 -143
  242. package/src/types.ts +47 -97
  243. package/src/utils/types.ts +0 -9
  244. package/src/utils.ts +2 -20
  245. package/tests/capabilities.spec.ts +219 -0
  246. package/tests/entitlement.spec.ts +4 -4
  247. package/tests/gate-handlers.spec.ts +6 -6
  248. package/tests/gate.spec.ts +2 -2
  249. package/tests/grants.spec.ts +2 -2
  250. package/tests/internal-plan.spec.ts +2 -2
  251. package/tests/limit-gate.spec.ts +2 -2
  252. package/tests/paygates.spec.ts +132 -0
  253. package/tests/protocol.spec.ts +4 -5
  254. package/tests/usage.spec.ts +2 -2
  255. package/tests/webhook.spec.ts +137 -0
  256. package/build/plugins/session/types.d.ts +0 -34
  257. package/build/plugins/session/types.d.ts.map +0 -1
  258. package/build/plugins/session.d.ts +0 -4
  259. package/build/plugins/session.d.ts.map +0 -1
  260. package/build/plugins/session.js +0 -71
  261. package/build/plugins/session.js.map +0 -1
  262. package/build/plugins/status.d.ts +0 -8
  263. package/build/plugins/status.d.ts.map +0 -1
  264. package/build/plugins/status.js +0 -21
  265. package/build/plugins/status.js.map +0 -1
  266. package/build/plugins/stripe/types.d.ts +0 -20
  267. package/build/plugins/stripe/types.d.ts.map +0 -1
  268. package/build/plugins/stripe.d.ts +0 -6
  269. package/build/plugins/stripe.d.ts.map +0 -1
  270. package/build/plugins/stripe.js +0 -518
  271. package/build/plugins/stripe.js.map +0 -1
  272. package/src/plugins/session/types.ts +0 -30
  273. package/src/plugins/session.ts +0 -86
  274. package/src/plugins/status.ts +0 -22
  275. package/src/plugins/stripe/types.ts +0 -20
  276. package/src/plugins/stripe.ts +0 -571
  277. package/tests/checkout-consumer.spec.ts +0 -366
  278. package/tests/checkout-locks.spec.ts +0 -161
  279. package/tests/checkout-plugins.spec.ts +0 -164
  280. package/tests/checkout.spec.ts +0 -313
  281. package/tests/consumer-events.spec.ts +0 -215
  282. package/tests/consumer-fixtures.ts +0 -141
  283. package/tests/consumer-ops.spec.ts +0 -361
  284. package/tests/consumer-rights.integration.spec.ts +0 -147
  285. package/tests/consumer-rights.spec.ts +0 -606
  286. package/tests/context.ts +0 -110
  287. package/tests/estimate.spec.ts +0 -350
  288. package/tests/events.spec.ts +0 -367
  289. package/tests/fake-stripe.ts +0 -1004
  290. package/tests/gateway-options.spec.ts +0 -180
  291. package/tests/portal.spec.ts +0 -202
  292. package/tests/sync.spec.ts +0 -114
  293. package/tests/usage.integration.spec.ts +0 -165
  294. package/tests/webhook-manager.spec.ts +0 -149
  295. /package/build/{plugins/session → checkout}/types.js +0 -0
  296. /package/build/{plugins/stripe → paygate}/types.js +0 -0
@@ -1,5 +1,6 @@
1
1
  import type { AmountPolicyView } from '@owlmeans/payment'
2
2
  import type { CheckoutPlugin } from '../../types.js'
3
+ import type { PaygateFeatures } from '../../paygate/types.js'
3
4
 
4
5
  /** What a narrowed amount policy and the plugins' declarations allow a checkout — pure. */
5
6
  export interface CheckoutPolicyHelper {
@@ -11,8 +12,9 @@ export interface CheckoutPolicyHelper {
11
12
  */
12
13
  assertAmountAllowed: (view: AmountPolicyView, amountMinor: number) => void
13
14
  /**
14
- * The session lifetime: the smallest `sessionTtlSeconds` any plugin declares, clamped to Stripe's
15
- * 30 minutes – 24 hours; `undefined` when none declares one (Stripe's own default).
15
+ * The session lifetime: the smallest `sessionTtlSeconds` any plugin declares, clamped into the
16
+ * paygate's `bounds` (`features.sessionTtl`); `undefined` when none declares one, or the paygate
17
+ * takes no lifetime (no bounds) — the paygate's own default.
16
18
  */
17
- sessionTtlOf: (plugins: readonly CheckoutPlugin[]) => number | undefined
19
+ sessionTtlOf: (plugins: readonly CheckoutPlugin[], bounds?: PaygateFeatures['sessionTtl']) => number | undefined
18
20
  }
@@ -1,6 +1,6 @@
1
1
  import { CheckoutLimitExceeded, type AmountPolicyView } from '@owlmeans/payment'
2
- import { STRIPE_SESSION_TTL_MAX_SECONDS, STRIPE_SESSION_TTL_MIN_SECONDS } from '../consts.js'
3
2
  import type { CheckoutPlugin } from '../types.js'
3
+ import type { PaygateFeatures } from '../paygate/types.js'
4
4
  import type { CheckoutPolicyHelper } from './checkout-policy/types.js'
5
5
 
6
6
  export const createCheckoutPolicyHelper = (): CheckoutPolicyHelper => {
@@ -15,7 +15,10 @@ export const createCheckoutPolicyHelper = (): CheckoutPolicyHelper => {
15
15
  })
16
16
  }
17
17
 
18
- const sessionTtlOf = (plugins: readonly CheckoutPlugin[]): number | undefined => {
18
+ const sessionTtlOf = (plugins: readonly CheckoutPlugin[], bounds?: PaygateFeatures['sessionTtl']): number | undefined => {
19
+ if (bounds == null) {
20
+ return undefined
21
+ }
19
22
  const declared = plugins
20
23
  .map(plugin => plugin.sessionTtlSeconds)
21
24
  .filter((ttl): ttl is number => typeof ttl === 'number' && Number.isFinite(ttl))
@@ -23,9 +26,7 @@ export const createCheckoutPolicyHelper = (): CheckoutPolicyHelper => {
23
26
  return undefined
24
27
  }
25
28
 
26
- return Math.min(
27
- STRIPE_SESSION_TTL_MAX_SECONDS, Math.max(STRIPE_SESSION_TTL_MIN_SECONDS, Math.floor(Math.min(...declared))),
28
- )
29
+ return Math.min(bounds.maxSeconds, Math.max(bounds.minSeconds, Math.floor(Math.min(...declared))))
29
30
  }
30
31
 
31
32
  return { assertAmountAllowed, sessionTtlOf }
@@ -1,30 +1,6 @@
1
- import { TaxType } from '@owlmeans/payment'
2
- import type { DisputePhase } from '../types.js'
3
-
4
- export const NON_SCALABLE_REASONS = new Set([
5
- 'portion_product_exempt', 'portion_reduced_rated', 'portion_standard_rated', 'taxable_basis_reduced',
6
- 'proportionally_rated',
7
- ])
8
-
9
- export const TAX_TYPE_MAP: Readonly<Record<string, TaxType>> = Object.freeze({
10
- vat: TaxType.Vat, gst: TaxType.Gst, sales_tax: TaxType.SalesTax,
11
- })
12
-
13
1
  export const RESYNC_PAGE = 200
14
2
 
15
- export const DISPUTE_PHASES: Record<string, DisputePhase> = {
16
- 'charge.dispute.created': 'opened',
17
- 'charge.dispute.funds_withdrawn': 'funds-withdrawn',
18
- 'charge.dispute.funds_reinstated': 'funds-reinstated',
19
- 'charge.dispute.closed': 'closed',
20
- }
21
-
22
- /** Stripe's limit on every `custom_text` message. */
23
- export const CUSTOM_TEXT_MAX = 1200
24
-
25
3
  export const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
26
4
 
27
- /** Countries where Stripe Tax cannot place a customer from the country alone (docs: tax/customer-locations). */
28
- export const NEEDS_POSTAL_CODE = new Set(['US'])
29
-
30
- export const NEEDS_POSTAL_CODE_OR_STATE = new Set(['CA', 'IN'])
5
+ /** The highest-ranked entitling subscription first, the newest on a tie. */
6
+ export const ENTITLING_SORT = [{ field: 'rank', order: 'desc' }, { field: 'createdAt', order: 'desc' }] as const
@@ -1,5 +1,5 @@
1
1
  /** Serialized work per paygate customer, within this process. */
2
2
  export interface CustomerLockHelper {
3
- /** Serialize the work on one paygate customer within this process. */
4
- withCustomerLock: <T>(customerId: string | undefined, fn: () => Promise<T>) => Promise<T>
3
+ /** Serialize the work on one customer of one paygate within this process (key `<paygate>:<customer id>`). */
4
+ withCustomerLock: <T>(paygate: string, customerId: string | undefined, fn: () => Promise<T>) => Promise<T>
5
5
  }
@@ -4,8 +4,8 @@ import type { CustomerLockHelper } from './customer-lock/types.js'
4
4
  export const createCustomerLockHelper = (): CustomerLockHelper => {
5
5
  const customerMutex: Record<string, Mutex> = {}
6
6
 
7
- const withCustomerLock = async <T>(customerId: string | undefined, fn: () => Promise<T>): Promise<T> => {
8
- const key = customerId ?? ''
7
+ const withCustomerLock = async <T>(paygate: string, customerId: string | undefined, fn: () => Promise<T>): Promise<T> => {
8
+ const key = `${paygate}:${customerId ?? ''}`
9
9
  const mutex = customerMutex[key] = customerMutex[key] ?? new Mutex()
10
10
  const release = await mutex.acquire()
11
11
  try {
@@ -1,7 +1,7 @@
1
1
  import type { EstimateCache } from './types.js'
2
2
 
3
3
  // One instance per gateway service, never module-level (a test builds many contexts in one process,
4
- // and a module-level cache would make "no Stripe call" assertions order-dependent).
4
+ // and a module-level cache would make "no paygate call" assertions order-dependent).
5
5
 
6
6
  /** @param taxTtlMs default 24h; @param fxTtlMs default 1h; @param customerTtlMs default 5min. */
7
7
  export const makeEstimateCache = (
@@ -1,6 +1,6 @@
1
- import type Stripe from 'stripe'
2
1
  import type { PriceEstimate } from '@owlmeans/payment'
3
2
  import type { PriceEstimateParams } from '../../types.js'
3
+ import type { PaygateCustomer } from '../../paygate/types.js'
4
4
  import type { CacheEntry, FxOutcome, TaxOutcome } from '../types.local.js'
5
5
 
6
6
  export interface EstimateCache {
@@ -9,20 +9,20 @@ export interface EstimateCache {
9
9
  customerTtlMs: number
10
10
  tax: Map<string, CacheEntry<TaxOutcome>>
11
11
  fx: Map<string, CacheEntry<FxOutcome>>
12
- customer: Map<string, CacheEntry<Stripe.Customer | null>>
12
+ customer: Map<string, CacheEntry<PaygateCustomer | null>>
13
13
  inflight: Map<string, Promise<unknown>>
14
14
  }
15
15
 
16
- /** Price estimates of a context: Stripe Tax and the local-currency line. */
16
+ /** Price estimates of a context: the paygate's tax calculation and the local-currency line. */
17
17
  export interface EstimateHelper {
18
18
  /**
19
- * A Stripe Tax estimate (and, when the pricing policy asks for it, a local-currency conversion) for
20
- * one product/plan, at a billing country the request names or the entity's paygate customer does.
19
+ * A tax estimate (and, when the pricing policy asks for it, a local-currency conversion) for one
20
+ * product/plan, at a billing country the request names or the entity's paygate customer does —
21
+ * through `params.paygate`, else the first registered paygate the plan is for sale through.
21
22
  *
22
- * Costs one Tax Calculation API call ($0.05) per distinct (currency, country, amount, tax code,
23
- * behavior, matching tax ids) within `cache`'s TTL, and one free FX Quotes call per distinct
24
- * (currency, local currency) — never more, and never for a rate-limit or connection error, which is
25
- * never cached.
23
+ * One tax calculation per distinct (paygate, currency, country, amount, tax code, behavior,
24
+ * matching tax ids) within `cache`'s TTL, and one FX quote per distinct (currency, local currency)
25
+ * — never more; a failed call is never cached. A paygate without `tax` answers `at-checkout`.
26
26
  */
27
- estimateStripePrice: (stripe: Stripe, params: PriceEstimateParams, cache: EstimateCache) => Promise<PriceEstimate>
27
+ estimatePrice: (params: PriceEstimateParams, cache: EstimateCache) => Promise<PriceEstimate>
28
28
  }
@@ -1,17 +1,13 @@
1
- import type Stripe from 'stripe'
2
- import { CheckoutPricingMode, currencyOfCountry, ProductError, TaxBehavior, TaxEstimateStatus, TaxType, UnknownProduct, type PriceEstimate, type TaxEstimate, type TaxRateEstimate, checkoutPricingHelper, consumerRegionHelper, priceEstimateHelper } from '@owlmeans/payment'
1
+ import { CheckoutPricingMode, currencyOfCountry, ProductError, TaxBehavior, TaxEstimateStatus, UnknownProduct, type PriceEstimate, type TaxEstimate, checkoutPricingHelper, consumerRegionHelper } from '@owlmeans/payment'
3
2
  import type { Context as ApiContext } from '@owlmeans/server-api'
4
3
  import { memoHelper } from '@owlmeans/context'
5
- import { STRIPE_FX_QUOTES_API_VERSION, STRIPE_PAYGATE_ALIAS } from '../consts.js'
6
4
  import type { PaymentPlan, PaymentProduct, PriceEstimateParams } from '../types.js'
7
- import { NON_SCALABLE_REASONS, TAX_TYPE_MAP } from './consts.local.js'
8
5
  import type { CacheEntry, FxOutcome, TaxOutcome } from './types.local.js'
9
6
  import type { EstimateCache, EstimateHelper } from './estimate/types.js'
10
- import { fxOf } from './fx.js'
7
+ import type { Paygate, PaygateCustomer } from '../paygate/types.js'
11
8
  import { paymentAccessOf } from '../access.js'
12
- import { paymentUtils } from '../utils.js'
13
9
  import { catalogueOf } from '../catalogue.js'
14
- import { planHelper } from '../plan.js'
10
+ import { paygatesOf } from '../paygate/registry.js'
15
11
 
16
12
  /**
17
13
  * A keyed value cached for `ttlMs`, with in-flight requests shared across concurrent callers. Only
@@ -43,54 +39,6 @@ const cached = async <T>(
43
39
  return promise
44
40
  }
45
41
 
46
- // -------------------------------------------------------------------------------------------
47
- // Tax
48
- // -------------------------------------------------------------------------------------------
49
-
50
- /** A duck-typed check, matching `isMissingObject` above: the installed SDK's own error classes. */
51
- const isInvalidRequest = (error: unknown): error is { code?: string } =>
52
- (error as { type?: unknown } | null)?.type === 'StripeInvalidRequestError'
53
-
54
- /** A linear percentage rate scales with the amount; a flat fee, a partial exemption, or several inclusive rates do not. */
55
- const scalableOf = (breakdown: Stripe.Tax.Calculation.TaxBreakdown[], behavior: TaxBehavior): boolean => {
56
- if (breakdown.some(row => row.tax_rate_details?.rate_type === 'flat_amount')) return false
57
- if (breakdown.some(row => NON_SCALABLE_REASONS.has(row.taxability_reason))) return false
58
- if (behavior === TaxBehavior.Inclusive && breakdown.length > 1) return false
59
- return true
60
- }
61
-
62
- const statusOf = (breakdown: Stripe.Tax.Calculation.TaxBreakdown[], taxMinor: number): TaxEstimateStatus => {
63
- if (breakdown.some(row => row.taxability_reason === 'reverse_charge')) return TaxEstimateStatus.ReverseCharge
64
- if (taxMinor > 0) return TaxEstimateStatus.Taxed
65
- if (breakdown.some(row => row.taxability_reason === 'not_supported')) return TaxEstimateStatus.AtCheckout
66
- return TaxEstimateStatus.None
67
- }
68
-
69
- const taxTypeOf = (raw: string | null | undefined): TaxType => raw != null && raw in TAX_TYPE_MAP ? TAX_TYPE_MAP[raw] : TaxType.Tax
70
-
71
- const ratesOf = (breakdown: Stripe.Tax.Calculation.TaxBreakdown[]): TaxRateEstimate[] => breakdown
72
- .filter((row): row is Stripe.Tax.Calculation.TaxBreakdown & {
73
- tax_rate_details: NonNullable<Stripe.Tax.Calculation.TaxBreakdown['tax_rate_details']>
74
- } => row.tax_rate_details != null)
75
- .map(row => ({
76
- type: taxTypeOf(row.tax_rate_details.tax_type),
77
- percentage: row.tax_rate_details.percentage_decimal,
78
- ratePpm: priceEstimateHelper.ratePpmOf(row.tax_rate_details.percentage_decimal),
79
- ...(row.tax_rate_details.country != null ? { country: row.tax_rate_details.country } : {}),
80
- ...(row.tax_rate_details.state != null ? { state: row.tax_rate_details.state } : {}),
81
- }))
82
-
83
- const taxEstimateOf = (calculation: Stripe.Tax.Calculation, behavior: TaxBehavior, subtotalMinor: number): TaxEstimate => {
84
- const breakdown = calculation.tax_breakdown ?? []
85
- const taxMinor = calculation.tax_amount_exclusive + calculation.tax_amount_inclusive
86
- const status = statusOf(breakdown, taxMinor)
87
-
88
- return {
89
- status, subtotalMinor, taxMinor, totalMinor: calculation.amount_total,
90
- scalable: scalableOf(breakdown, behavior), rates: ratesOf(breakdown),
91
- }
92
- }
93
-
94
42
  /** The reference amount and currency of the estimate: an amount plan's default preset, else the plan's own price. */
95
43
  const referenceOf = (plan: PaymentPlan): { subtotalMinor: number; currency: string } => {
96
44
  if (plan.pricingMode === CheckoutPricingMode.Amount) {
@@ -113,19 +61,14 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
113
61
 
114
62
  // Customer lookup — the fallback country and the tax ids a request-given country still checks.
115
63
  const cachedCustomer = async (
116
- stripe: Stripe, entityId: string, cache: EstimateCache,
117
- ): Promise<Stripe.Customer | null> => cached(cache.customer, cache.inflight, `customer:${entityId}`, cache.customerTtlMs, async () => {
118
- const record = await access.paygateCustomers().byEntity(entityId, STRIPE_PAYGATE_ALIAS)
64
+ paygate: Paygate, entityId: string, cache: EstimateCache,
65
+ ): Promise<PaygateCustomer | null> => cached(cache.customer, cache.inflight, `customer:${paygate.id}:${entityId}`, cache.customerTtlMs, async () => {
66
+ const record = await access.paygateCustomers().byEntity(entityId, paygate.id)
119
67
  if (record == null || record.deletedAt != null) {
120
68
  return null
121
69
  }
122
- try {
123
- const retrieved = await stripe.customers.retrieve(record.externalId, { expand: ['tax_ids'] })
124
- return (retrieved as Stripe.DeletedCustomer).deleted ? null : retrieved as Stripe.Customer
125
- } catch (error) {
126
- if (paymentUtils.isMissingObject(error)) return null
127
- throw error
128
- }
70
+
71
+ return await paygate.customers.retrieve(record.externalId, { taxIds: true })
129
72
  })
130
73
 
131
74
  /**
@@ -152,24 +95,25 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
152
95
  return option != null ? { subtotalMinor: option.unitAmount, currency: chargeCurrency } : reference
153
96
  }
154
97
 
155
- // Currency: Stripe FX Quotes, a PREVIEW endpoint — see `STRIPE_FX_QUOTES_API_VERSION`. A buyer's
156
- // local currency is priced by Adaptive Pricing at the BASE rate plus its own conversion fee
157
- // (`price × (1 + fee)`, 2–4% as Stripe decides), which the quote's fee-inclusive `exchange_rate`
158
- // (base × (1 − `fx_fee_rate`), 2%) understates; a policy declaring `adaptiveFeeRate` is estimated
159
- // the way Checkout prices it, one without keeps the quote's rate.
98
+ // Currency: the paygate's FX quotes. A buyer's local currency is priced at the BASE rate plus the
99
+ // paygate's own conversion fee (`price × (1 + fee)`), which a quote's fee-inclusive `exchangeRate`
100
+ // understates; a policy declaring `adaptiveFeeRate` is estimated the way checkout prices it, one
101
+ // without keeps the quote's rate.
160
102
  const fetchFxRate = async (
161
- stripe: Stripe, currency: string, localCurrency: string, apiVersion: string,
103
+ paygate: Paygate, currency: string, localCurrency: string,
162
104
  settlementCurrency: string = currency, adaptiveFeeRate?: number,
163
105
  ): Promise<FxOutcome> => {
106
+ const fx = paygate.fx
107
+ if (fx == null) return null
164
108
  const settlement = settlementCurrency.toLowerCase()
165
109
  const sourceRate = settlement === currency
166
110
  ? { referenceRate: 1 }
167
- : await fxOf(ctx).stripeFxRate(stripe, currency, settlement, apiVersion)
111
+ : await fx.quote(currency, settlement)
168
112
  if (sourceRate == null) return null
169
113
  if (localCurrency === settlement) {
170
114
  return { currency: localCurrency, exchangeRate: 1 / sourceRate.referenceRate }
171
115
  }
172
- const localRate = await fxOf(ctx).stripeFxRate(stripe, localCurrency, settlement, apiVersion)
116
+ const localRate = await fx.quote(localCurrency, settlement)
173
117
  if (localRate == null) return null
174
118
  const settlementPerLocal = adaptiveFeeRate != null ? localRate.baseRate / (1 + adaptiveFeeRate) : localRate.exchangeRate
175
119
  const feeRate = adaptiveFeeRate ?? localRate.fxFeeRate
@@ -179,17 +123,17 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
179
123
  }
180
124
  }
181
125
 
182
- const estimateStripePrice = async (
183
- stripe: Stripe, params: PriceEstimateParams, cache: EstimateCache,
184
- ): Promise<PriceEstimate> => {
126
+ const estimatePrice = async (params: PriceEstimateParams, cache: EstimateCache): Promise<PriceEstimate> => {
185
127
  const product = await catalogueOf(ctx).findProduct(params.productSku) as PaymentProduct | null
186
128
  if (product == null) throw new UnknownProduct(params.productSku)
129
+ const paygates = paygatesOf(ctx)
187
130
  const plans = (await access.payment().allPlans(product.sku) as PaymentPlan[])
188
- .filter(plan => planHelper.isSoldThrough(product, plan, STRIPE_PAYGATE_ALIAS))
131
+ .filter(plan => paygates.forSale(product, plan, params.paygate).length > 0)
189
132
  const plan = params.planSku != null
190
133
  ? plans.find(item => item.sku === params.planSku)
191
134
  : plans.find(item => item.recurring != null) ?? plans[0]
192
135
  if (plan == null) throw new ProductError(params.planSku != null ? `plan:${params.planSku}` : 'plan')
136
+ const paygate = paygates.forSale(product, plan, params.paygate)[0]
193
137
 
194
138
  const pricing = await access.payment().pricingPolicy()
195
139
  const behavior = pricing.tax.behavior ?? TaxBehavior.Exclusive
@@ -201,25 +145,25 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
201
145
  let country = locked ? profile.country as string : params.country?.toUpperCase()
202
146
  let source: 'request' | 'customer' | 'profile' | undefined = locked ? 'profile' : country != null ? 'request' : undefined
203
147
  let matchingTaxIds: Array<{ type: string; value: string }> = []
204
- let taxabilityOverride: 'customer_exempt' | 'reverse_charge' | undefined
148
+ let exemption: 'exempt' | 'reverse' | undefined
205
149
 
206
- const customer = await cachedCustomer(stripe, params.entityId, cache)
150
+ const customer = await cachedCustomer(paygate, params.entityId, cache)
207
151
  if (customer != null) {
208
- if (country == null && customer.address?.country != null) {
209
- country = customer.address.country
152
+ if (country == null && customer.country != null) {
153
+ country = customer.country
210
154
  source = 'customer'
211
155
  }
212
156
  if (country != null) {
213
- matchingTaxIds = (customer.tax_ids?.data ?? [])
157
+ matchingTaxIds = (customer.taxIds ?? [])
214
158
  .filter(taxId => taxId.country === country)
215
159
  .map(taxId => ({ type: taxId.type, value: taxId.value }))
216
- if (customer.tax_exempt === 'exempt') taxabilityOverride = 'customer_exempt'
217
- else if (customer.tax_exempt === 'reverse') taxabilityOverride = 'reverse_charge'
160
+ if (customer.taxExempt === 'exempt') exemption = 'exempt'
161
+ else if (customer.taxExempt === 'reverse') exemption = 'reverse'
218
162
  }
219
163
  }
220
164
 
221
165
  const region = rights != null ? consumerRegionHelper.regionOf(country, rights) : null
222
- const settlementCurrency = (await access.stripePricingConfig())?.settlementCurrency?.toLowerCase()
166
+ const settlementCurrency = (await paygate.settlementCurrency())?.toLowerCase()
223
167
  // The currency the checkout session charges: the region's (or the locked profile's) under a policy
224
168
  // with region currencies, else none forced.
225
169
  const chargeCurrency = rights != null && rights.currencies != null && Object.keys(rights.currencies).length > 0
@@ -232,44 +176,26 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
232
176
  return { currency, behavior, tax: unresolvedEstimate(TaxEstimateStatus.LocationRequired, subtotalMinor), ...where }
233
177
  }
234
178
 
179
+ if (paygate.tax == null) {
180
+ return { country, source, currency, behavior, tax: unresolvedEstimate(TaxEstimateStatus.AtCheckout, subtotalMinor), ...where } as PriceEstimate
181
+ }
182
+ const tax = paygate.tax
235
183
  const cacheKey = JSON.stringify([
236
- currency, country, subtotalMinor, product.taxCode ?? null, behavior,
237
- matchingTaxIds.map(id => `${id.type}:${id.value}`).sort(), taxabilityOverride ?? null,
184
+ paygate.id, currency, country, subtotalMinor, product.taxCode ?? null, behavior,
185
+ matchingTaxIds.map(id => `${id.type}:${id.value}`).sort(), exemption ?? null,
238
186
  ])
239
- const outcome = await cached(cache.tax, cache.inflight, `tax:${cacheKey}`, cache.taxTtlMs, async (): Promise<TaxOutcome> => {
240
- try {
241
- const calculation = await stripe.tax.calculations.create({
242
- currency,
243
- line_items: [{
244
- amount: subtotalMinor, reference: plan.sku, tax_behavior: behavior,
245
- ...(product.taxCode != null ? { tax_code: product.taxCode } : {}),
246
- }],
247
- customer_details: {
248
- address: { country },
249
- address_source: 'billing',
250
- // Cast: `Stripe.TaxId.type` (the customer's saved tax id) and the Tax Calculation
251
- // parameter's own tax-id-type enum are independently generated from Stripe's OpenAPI
252
- // spec and can drift apart in this pinned SDK; every value here still came from a real
253
- // Stripe `TaxId` record, so it is valid at the API even where the two types disagree.
254
- ...(matchingTaxIds.length > 0
255
- ? { tax_ids: matchingTaxIds as Stripe.Tax.CalculationCreateParams.CustomerDetails['tax_ids'] }
256
- : {}),
257
- ...(taxabilityOverride != null ? { taxability_override: taxabilityOverride } : {}),
258
- },
259
- })
260
- return { ok: true, calculation }
261
- } catch (error) {
262
- if (isInvalidRequest(error)) return { ok: false, code: error.code }
263
- throw error
264
- }
265
- })
266
-
267
- const tax = outcome.ok
268
- ? taxEstimateOf(outcome.calculation, behavior, subtotalMinor)
269
- : unresolvedEstimate(TaxEstimateStatus.AtCheckout, subtotalMinor)
270
-
271
- const result: PriceEstimate = { country, source, currency, behavior, tax, ...where }
272
- // Adaptive Pricing — and so a local-currency line — applies only to a session CHARGED in the
187
+ const outcome = await cached(cache.tax, cache.inflight, `tax:${cacheKey}`, cache.taxTtlMs, async (): Promise<TaxOutcome> =>
188
+ await tax.calculate({
189
+ currency, amountMinor: subtotalMinor, reference: plan.sku, taxBehavior: behavior,
190
+ ...(product.taxCode != null ? { taxCode: product.taxCode } : {}),
191
+ country: country as string, taxIds: matchingTaxIds,
192
+ ...(exemption != null ? { exemption } : {}),
193
+ }))
194
+
195
+ const estimated: TaxEstimate = outcome ?? unresolvedEstimate(TaxEstimateStatus.AtCheckout, subtotalMinor)
196
+
197
+ const result: PriceEstimate = { country, source, currency, behavior, tax: estimated, ...where }
198
+ // Local-currency pricing — and so a local-currency line — applies only to a session CHARGED in the
273
199
  // settlement currency; a forced region currency (exact USD) is shown as it is. An amount plan is
274
200
  // estimated in its policy currency but charged in the region's currency (converted per session,
275
201
  // `chargeAmount`), so the session's currency decides, never the reference's: a EUR-charged top-up
@@ -280,14 +206,12 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
280
206
  if (pricing.currency.estimate && pricing.currency.adaptive === true && adaptive) {
281
207
  const localCurrency = currencyOfCountry(country)
282
208
  if (localCurrency != null && localCurrency !== currency) {
283
- const stripePricing = await access.stripePricingConfig()
284
- const apiVersion = stripePricing?.fxApiVersion ?? STRIPE_FX_QUOTES_API_VERSION
285
- const settlementCurrency = stripePricing?.settlementCurrency?.toLowerCase() ?? currency
286
- // A preview endpoint: unreachable or erroring never fails the estimate, it only drops `local`.
209
+ const settlement = settlementCurrency ?? currency
210
+ // A rate that cannot be read never fails the estimate, it only drops `local`.
287
211
  const feeRate = pricing.currency.adaptiveFeeRate
288
212
  const fx = await cached(
289
- cache.fx, cache.inflight, `fx:${currency}:${settlementCurrency}:${localCurrency}:${apiVersion}:${feeRate ?? ''}`, cache.fxTtlMs,
290
- () => fetchFxRate(stripe, currency, localCurrency, apiVersion, settlementCurrency, feeRate),
213
+ cache.fx, cache.inflight, `fx:${paygate.id}:${currency}:${settlement}:${localCurrency}:${feeRate ?? ''}`, cache.fxTtlMs,
214
+ () => fetchFxRate(paygate, currency, localCurrency, settlement, feeRate),
291
215
  ).catch(() => null)
292
216
  if (fx != null) {
293
217
  result.local = { currency: fx.currency, exchangeRate: fx.exchangeRate, ...(fx.fxFeeRate != null ? { fxFeeRate: fx.fxFeeRate } : {}) }
@@ -298,7 +222,7 @@ export const makeEstimateHelper = (ctx: ApiContext): EstimateHelper => {
298
222
  return result
299
223
  }
300
224
 
301
- return { estimateStripePrice }
225
+ return { estimatePrice }
302
226
  }
303
227
 
304
228
  /** The price estimates of a context — one per context. */
@@ -1,11 +1,19 @@
1
- import type Stripe from 'stripe'
1
+ import type { Paygate, PaygateEvent } from '../../paygate/types.js'
2
2
 
3
- export interface EventHandler { (event: Stripe.Event): Promise<void> }
4
-
5
- /** The Stripe event dispatch table of one context and client. */
6
- export interface StripeEventHandler {
7
- /** The handler of each event type this package processes. */
8
- handlers: Record<string, EventHandler>
9
- /** Run the handler of an event's type; every other type is ignored. A throw escapes so Stripe delivers again. */
10
- process: (event: Stripe.Event) => Promise<void>
3
+ /** The paygate events of a context, applied to the stores and told to the observers. */
4
+ export interface PaymentEventsHelper {
5
+ /**
6
+ * Apply one event a paygate's webhook produced. A throw escapes so the paygate delivers again:
7
+ *
8
+ * - `customer` — the customer row upserted (`country`, `currency`) or marked deleted;
9
+ * - `checkout` `completed` — a paid one-time checkout fulfilled (purchase, lock, confirmation mail,
10
+ * fulfillment, `onTopUp`), a subscription checkout completed; `failed` — `onPaymentFailed`;
11
+ * `expired` — the unfulfilled row purged; the checkout plugins hear `settled`;
12
+ * - `subscription` — applied to its row (`onSubscription`), a deleted one as canceled;
13
+ * - `invoice` — a renewal re-reads and applies its subscription, a failed payment tells
14
+ * `onPaymentFailed`, others keep the row's latest invoice;
15
+ * - `refund` (succeeded) and `dispute` — resolved to their fulfillment or subscription, recorded,
16
+ * told to `onRefund` / `onDispute`.
17
+ */
18
+ apply: (paygate: Paygate, event: PaygateEvent) => Promise<void>
11
19
  }