@zonastery/bursar 1.0.1 → 2.0.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 (366) hide show
  1. package/README.md +86 -3
  2. package/dist/billing/auto-recharge-port.d.ts +3 -3
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-port.js.map +1 -1
  5. package/dist/billing/auto-recharge-service.d.ts +5 -4
  6. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  7. package/dist/billing/auto-recharge-service.js +64 -34
  8. package/dist/billing/auto-recharge-service.js.map +1 -1
  9. package/dist/billing/billing-service.d.ts +5 -5
  10. package/dist/billing/billing-service.d.ts.map +1 -1
  11. package/dist/billing/billing-service.js +2 -2
  12. package/dist/billing/billing-service.js.map +1 -1
  13. package/dist/billing/billing-store.d.ts +8 -7
  14. package/dist/billing/billing-store.d.ts.map +1 -1
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +31 -31
  17. package/dist/billing/contracts.d.ts.map +1 -1
  18. package/dist/billing/contracts.js.map +1 -1
  19. package/dist/billing/event-handlers.d.ts.map +1 -1
  20. package/dist/billing/event-handlers.js +31 -9
  21. package/dist/billing/event-handlers.js.map +1 -1
  22. package/dist/billing/event-processor.d.ts.map +1 -1
  23. package/dist/billing/event-processor.js +2 -1
  24. package/dist/billing/event-processor.js.map +1 -1
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +69 -72
  27. package/dist/billing/financial-event-handlers.js.map +1 -1
  28. package/dist/billing/index.d.ts +1 -1
  29. package/dist/billing/index.d.ts.map +1 -1
  30. package/dist/billing/index.js.map +1 -1
  31. package/dist/billing/management.d.ts +5 -5
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js +2 -2
  34. package/dist/billing/management.js.map +1 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -3
  36. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.js +202 -59
  38. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  39. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -1
  40. package/dist/billing/postgres/repositories/customer.js +19 -11
  41. package/dist/billing/postgres/repositories/customer.js.map +1 -1
  42. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  43. package/dist/billing/postgres/repositories/dispute.js +3 -1
  44. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  45. package/dist/billing/postgres/repositories/event.d.ts +12 -5
  46. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  47. package/dist/billing/postgres/repositories/event.js +18 -15
  48. package/dist/billing/postgres/repositories/event.js.map +1 -1
  49. package/dist/billing/postgres/repositories/invoice.d.ts +3 -3
  50. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  51. package/dist/billing/postgres/repositories/invoice.js +53 -11
  52. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  53. package/dist/billing/postgres/repositories/offer.d.ts +20 -17
  54. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  55. package/dist/billing/postgres/repositories/offer.js +123 -57
  56. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  57. package/dist/billing/postgres/repositories/payment.d.ts +23 -20
  58. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  59. package/dist/billing/postgres/repositories/payment.js +43 -37
  60. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  61. package/dist/billing/postgres/repositories/preferences.d.ts +3 -9
  62. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -1
  63. package/dist/billing/postgres/repositories/preferences.js +45 -7
  64. package/dist/billing/postgres/repositories/preferences.js.map +1 -1
  65. package/dist/billing/postgres/repositories/refund.d.ts +1 -1
  66. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -1
  67. package/dist/billing/postgres/repositories/refund.js +13 -9
  68. package/dist/billing/postgres/repositories/refund.js.map +1 -1
  69. package/dist/billing/postgres/repositories/subscription-change.d.ts +15 -0
  70. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -0
  71. package/dist/billing/postgres/repositories/subscription-change.js +234 -0
  72. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -0
  73. package/dist/billing/postgres/repositories/subscription.d.ts +38 -17
  74. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  75. package/dist/billing/postgres/repositories/subscription.js +199 -91
  76. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  77. package/dist/billing/postgres/repositories/topup.d.ts +13 -15
  78. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  79. package/dist/billing/postgres/repositories/topup.js +65 -34
  80. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  81. package/dist/billing/postgres/store.d.ts +18 -11
  82. package/dist/billing/postgres/store.d.ts.map +1 -1
  83. package/dist/billing/postgres/store.js +260 -238
  84. package/dist/billing/postgres/store.js.map +1 -1
  85. package/dist/billing/service-types.d.ts +6 -5
  86. package/dist/billing/service-types.d.ts.map +1 -1
  87. package/dist/billing/service-types.js.map +1 -1
  88. package/dist/billing/types/auto-recharge.d.ts +6 -4
  89. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  90. package/dist/billing/types/auto-recharge.js.map +1 -1
  91. package/dist/billing/types/catalog.d.ts +18 -35
  92. package/dist/billing/types/catalog.d.ts.map +1 -1
  93. package/dist/billing/types/catalog.js.map +1 -1
  94. package/dist/billing/types/common.d.ts +0 -1
  95. package/dist/billing/types/common.d.ts.map +1 -1
  96. package/dist/billing/types/common.js.map +1 -1
  97. package/dist/billing/types/documents.d.ts +38 -12
  98. package/dist/billing/types/documents.d.ts.map +1 -1
  99. package/dist/billing/types/documents.js.map +1 -1
  100. package/dist/billing/types/events.d.ts +2 -0
  101. package/dist/billing/types/events.d.ts.map +1 -1
  102. package/dist/billing/types/events.js +238 -0
  103. package/dist/billing/types/events.js.map +1 -1
  104. package/dist/billing/types/subscriptions.d.ts +8 -8
  105. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  106. package/dist/billing/types/subscriptions.js.map +1 -1
  107. package/dist/bursar.d.ts +27 -9
  108. package/dist/bursar.d.ts.map +1 -1
  109. package/dist/bursar.js +48 -20
  110. package/dist/bursar.js.map +1 -1
  111. package/dist/catalog.d.ts +1 -1
  112. package/dist/catalog.d.ts.map +1 -1
  113. package/dist/catalog.js +1 -1
  114. package/dist/catalog.js.map +1 -1
  115. package/dist/commerce/errors.d.ts +1 -10
  116. package/dist/commerce/errors.d.ts.map +1 -1
  117. package/dist/commerce/errors.js +1 -16
  118. package/dist/commerce/errors.js.map +1 -1
  119. package/dist/commerce/index.d.ts +1 -0
  120. package/dist/commerce/index.d.ts.map +1 -1
  121. package/dist/commerce/index.js.map +1 -1
  122. package/dist/commerce/provider-registry.d.ts.map +1 -1
  123. package/dist/commerce/provider-registry.js +27 -2
  124. package/dist/commerce/provider-registry.js.map +1 -1
  125. package/dist/commerce/service.d.ts +15 -7
  126. package/dist/commerce/service.d.ts.map +1 -1
  127. package/dist/commerce/service.js +85 -67
  128. package/dist/commerce/service.js.map +1 -1
  129. package/dist/commerce/types.d.ts +27 -15
  130. package/dist/commerce/types.d.ts.map +1 -1
  131. package/dist/commerce/types.js.map +1 -1
  132. package/dist/config/parse-plans.d.ts.map +1 -1
  133. package/dist/config/parse-plans.js +16 -15
  134. package/dist/config/parse-plans.js.map +1 -1
  135. package/dist/config/parse-pricing.d.ts.map +1 -1
  136. package/dist/config/parse-pricing.js +16 -5
  137. package/dist/config/parse-pricing.js.map +1 -1
  138. package/dist/config/types.d.ts +2 -2
  139. package/dist/config/types.d.ts.map +1 -1
  140. package/dist/config/types.js.map +1 -1
  141. package/dist/credits/{pricing-runtime.d.ts → catalog-runtime.d.ts} +8 -8
  142. package/dist/credits/catalog-runtime.d.ts.map +1 -0
  143. package/dist/credits/{pricing-runtime.js → catalog-runtime.js} +58 -38
  144. package/dist/credits/catalog-runtime.js.map +1 -0
  145. package/dist/credits/events.d.ts +4 -4
  146. package/dist/credits/events.d.ts.map +1 -1
  147. package/dist/credits/events.js +1 -1
  148. package/dist/credits/events.js.map +1 -1
  149. package/dist/credits/lease-workflow.d.ts +14 -14
  150. package/dist/credits/lease-workflow.d.ts.map +1 -1
  151. package/dist/credits/lease-workflow.js +18 -17
  152. package/dist/credits/lease-workflow.js.map +1 -1
  153. package/dist/credits/low-balance-monitor.d.ts +2 -2
  154. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  155. package/dist/credits/low-balance-monitor.js.map +1 -1
  156. package/dist/credits/postgres/repositories/analytics.d.ts +34 -34
  157. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  158. package/dist/credits/postgres/repositories/analytics.js +52 -52
  159. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  160. package/dist/credits/postgres/repositories/balance.d.ts +28 -30
  161. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  162. package/dist/credits/postgres/repositories/balance.js +100 -59
  163. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  164. package/dist/credits/postgres/repositories/bucket.d.ts +14 -8
  165. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  166. package/dist/credits/postgres/repositories/bucket.js +22 -21
  167. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  168. package/dist/credits/postgres/repositories/catalog.d.ts +31 -0
  169. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -0
  170. package/dist/credits/postgres/repositories/catalog.js +90 -0
  171. package/dist/credits/postgres/repositories/catalog.js.map +1 -0
  172. package/dist/credits/postgres/repositories/deduction.d.ts +28 -26
  173. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  174. package/dist/credits/postgres/repositories/deduction.js +153 -68
  175. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  176. package/dist/credits/postgres/repositories/lease.d.ts +21 -18
  177. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  178. package/dist/credits/postgres/repositories/lease.js +157 -65
  179. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  180. package/dist/credits/postgres/repositories/plan.d.ts +90 -43
  181. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  182. package/dist/credits/postgres/repositories/plan.js +126 -108
  183. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  184. package/dist/credits/postgres/repositories/team.d.ts +36 -27
  185. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  186. package/dist/credits/postgres/repositories/team.js +96 -52
  187. package/dist/credits/postgres/repositories/team.js.map +1 -1
  188. package/dist/credits/postgres/store.d.ts +23 -18
  189. package/dist/credits/postgres/store.d.ts.map +1 -1
  190. package/dist/credits/postgres/store.js +282 -265
  191. package/dist/credits/postgres/store.js.map +1 -1
  192. package/dist/credits/postgres/value-mappers.d.ts +7 -9
  193. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  194. package/dist/credits/postgres/value-mappers.js +36 -61
  195. package/dist/credits/postgres/value-mappers.js.map +1 -1
  196. package/dist/credits/queries.d.ts +5 -5
  197. package/dist/credits/queries.d.ts.map +1 -1
  198. package/dist/credits/queries.js +4 -4
  199. package/dist/credits/queries.js.map +1 -1
  200. package/dist/credits/service-types.d.ts +42 -7
  201. package/dist/credits/service-types.d.ts.map +1 -1
  202. package/dist/credits/service-types.js.map +1 -1
  203. package/dist/credits/service.d.ts +42 -62
  204. package/dist/credits/service.d.ts.map +1 -1
  205. package/dist/credits/service.js +140 -121
  206. package/dist/credits/service.js.map +1 -1
  207. package/dist/credits/store.d.ts +20 -22
  208. package/dist/credits/store.d.ts.map +1 -1
  209. package/dist/credits/store.js +5 -5
  210. package/dist/credits/store.js.map +1 -1
  211. package/dist/credits/types/account.d.ts +49 -11
  212. package/dist/credits/types/account.d.ts.map +1 -1
  213. package/dist/credits/types/account.js.map +1 -1
  214. package/dist/credits/types/admission.d.ts +17 -6
  215. package/dist/credits/types/admission.d.ts.map +1 -1
  216. package/dist/credits/types/admission.js.map +1 -1
  217. package/dist/credits/types/analytics.d.ts +2 -2
  218. package/dist/credits/types/analytics.d.ts.map +1 -1
  219. package/dist/credits/types/analytics.js.map +1 -1
  220. package/dist/credits/types/catalog.d.ts +20 -15
  221. package/dist/credits/types/catalog.d.ts.map +1 -1
  222. package/dist/credits/types/catalog.js.map +1 -1
  223. package/dist/credits/types/grants.d.ts +22 -8
  224. package/dist/credits/types/grants.d.ts.map +1 -1
  225. package/dist/credits/types/grants.js.map +1 -1
  226. package/dist/credits/types/ledger.d.ts +12 -3
  227. package/dist/credits/types/ledger.d.ts.map +1 -1
  228. package/dist/credits/types/ledger.js.map +1 -1
  229. package/dist/credits/types/teams.d.ts +18 -6
  230. package/dist/credits/types/teams.d.ts.map +1 -1
  231. package/dist/credits/types/teams.js.map +1 -1
  232. package/dist/engine.d.ts.map +1 -1
  233. package/dist/engine.js +24 -10
  234. package/dist/engine.js.map +1 -1
  235. package/dist/errors.d.ts +52 -4
  236. package/dist/errors.d.ts.map +1 -1
  237. package/dist/errors.js +76 -4
  238. package/dist/errors.js.map +1 -1
  239. package/dist/expr/ast.d.ts.map +1 -1
  240. package/dist/expr/ast.js.map +1 -1
  241. package/dist/expr/evaluator.d.ts.map +1 -1
  242. package/dist/expr/evaluator.js +29 -17
  243. package/dist/expr/evaluator.js.map +1 -1
  244. package/dist/expr/parser.d.ts.map +1 -1
  245. package/dist/expr/parser.js +11 -4
  246. package/dist/expr/parser.js.map +1 -1
  247. package/dist/expr/tokenizer.d.ts.map +1 -1
  248. package/dist/expr/tokenizer.js +17 -13
  249. package/dist/expr/tokenizer.js.map +1 -1
  250. package/dist/expr.d.ts +2 -2
  251. package/dist/expr.d.ts.map +1 -1
  252. package/dist/expr.js +5 -7
  253. package/dist/expr.js.map +1 -1
  254. package/dist/generated/pricing-config.schema.json +5 -12
  255. package/dist/generated/pricing-config.types.d.ts +3 -3
  256. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  257. package/dist/generated/pricing-config.types.js.map +1 -1
  258. package/dist/index.d.ts +6 -4
  259. package/dist/index.d.ts.map +1 -1
  260. package/dist/index.js +1 -1
  261. package/dist/index.js.map +1 -1
  262. package/dist/integrations/better-auth.d.ts +23 -0
  263. package/dist/integrations/better-auth.d.ts.map +1 -0
  264. package/dist/integrations/better-auth.js +54 -0
  265. package/dist/integrations/better-auth.js.map +1 -0
  266. package/dist/{load-pricing-file.d.ts → load-config-file.d.ts} +4 -4
  267. package/dist/load-config-file.d.ts.map +1 -0
  268. package/dist/{load-pricing-file.js → load-config-file.js} +15 -10
  269. package/dist/load-config-file.js.map +1 -0
  270. package/dist/node.d.ts +3 -3
  271. package/dist/node.d.ts.map +1 -1
  272. package/dist/node.js +2 -2
  273. package/dist/node.js.map +1 -1
  274. package/dist/providers/_shared.d.ts +5 -0
  275. package/dist/providers/_shared.d.ts.map +1 -1
  276. package/dist/providers/_shared.js +36 -0
  277. package/dist/providers/_shared.js.map +1 -1
  278. package/dist/providers/dodo/better-auth.d.ts +29 -0
  279. package/dist/providers/dodo/better-auth.d.ts.map +1 -0
  280. package/dist/providers/dodo/better-auth.js +23 -0
  281. package/dist/providers/dodo/better-auth.js.map +1 -0
  282. package/dist/providers/dodo/client-contract.d.ts +32 -70
  283. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  284. package/dist/providers/dodo/client-contract.js.map +1 -1
  285. package/dist/providers/dodo/event-mapper.d.ts +3 -1
  286. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  287. package/dist/providers/dodo/event-mapper.js +219 -148
  288. package/dist/providers/dodo/event-mapper.js.map +1 -1
  289. package/dist/providers/dodo/index.d.ts +5 -2
  290. package/dist/providers/dodo/index.d.ts.map +1 -1
  291. package/dist/providers/dodo/index.js +2 -1
  292. package/dist/providers/dodo/index.js.map +1 -1
  293. package/dist/providers/dodo/nextjs.d.ts +16 -0
  294. package/dist/providers/dodo/nextjs.d.ts.map +1 -0
  295. package/dist/providers/dodo/nextjs.js +16 -0
  296. package/dist/providers/dodo/nextjs.js.map +1 -0
  297. package/dist/providers/dodo/provider.d.ts +30 -11
  298. package/dist/providers/dodo/provider.d.ts.map +1 -1
  299. package/dist/providers/dodo/provider.js +192 -122
  300. package/dist/providers/dodo/provider.js.map +1 -1
  301. package/dist/providers/dodo/react-native.d.ts +56 -0
  302. package/dist/providers/dodo/react-native.d.ts.map +1 -0
  303. package/dist/providers/dodo/react-native.js +57 -0
  304. package/dist/providers/dodo/react-native.js.map +1 -0
  305. package/dist/providers/dodo/webhook-bridge.d.ts +17 -0
  306. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -0
  307. package/dist/providers/dodo/webhook-bridge.js +21 -0
  308. package/dist/providers/dodo/webhook-bridge.js.map +1 -0
  309. package/dist/providers/index.d.ts +1 -1
  310. package/dist/providers/index.d.ts.map +1 -1
  311. package/dist/providers/index.js.map +1 -1
  312. package/dist/providers/mock/index.d.ts +1 -0
  313. package/dist/providers/mock/index.d.ts.map +1 -1
  314. package/dist/providers/mock/index.js.map +1 -1
  315. package/dist/providers/mock/provider.d.ts +8 -8
  316. package/dist/providers/mock/provider.d.ts.map +1 -1
  317. package/dist/providers/mock/provider.js +26 -19
  318. package/dist/providers/mock/provider.js.map +1 -1
  319. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  320. package/dist/providers/stripe/event-mapper.js +214 -173
  321. package/dist/providers/stripe/event-mapper.js.map +1 -1
  322. package/dist/providers/stripe/index.d.ts +1 -0
  323. package/dist/providers/stripe/index.d.ts.map +1 -1
  324. package/dist/providers/stripe/index.js.map +1 -1
  325. package/dist/providers/stripe/provider.d.ts +13 -11
  326. package/dist/providers/stripe/provider.d.ts.map +1 -1
  327. package/dist/providers/stripe/provider.js +287 -107
  328. package/dist/providers/stripe/provider.js.map +1 -1
  329. package/dist/providers/types.d.ts +1 -2
  330. package/dist/providers/types.d.ts.map +1 -1
  331. package/dist/providers/types.js.map +1 -1
  332. package/dist/shared/postgres-client.d.ts +5 -0
  333. package/dist/shared/postgres-client.d.ts.map +1 -1
  334. package/dist/shared/postgres-client.js +23 -7
  335. package/dist/shared/postgres-client.js.map +1 -1
  336. package/dist/shared/postgres-validation.d.ts +15 -3
  337. package/dist/shared/postgres-validation.d.ts.map +1 -1
  338. package/dist/shared/postgres-validation.js +58 -14
  339. package/dist/shared/postgres-validation.js.map +1 -1
  340. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  341. package/dist/storage/adapters/clickhouse.js +2 -5
  342. package/dist/storage/adapters/clickhouse.js.map +1 -1
  343. package/dist/storage/adapters/s3.d.ts +0 -6
  344. package/dist/storage/adapters/s3.d.ts.map +1 -1
  345. package/dist/storage/adapters/s3.js +0 -2
  346. package/dist/storage/adapters/s3.js.map +1 -1
  347. package/dist/storage/ports.d.ts +0 -1
  348. package/dist/storage/ports.d.ts.map +1 -1
  349. package/dist/storage/ports.js.map +1 -1
  350. package/dist/storage/postgres-repository.d.ts +1 -1
  351. package/dist/storage/postgres-repository.d.ts.map +1 -1
  352. package/dist/storage/postgres-repository.js +2 -2
  353. package/dist/storage/postgres-repository.js.map +1 -1
  354. package/dist/storage/runtime.d.ts +24 -6
  355. package/dist/storage/runtime.d.ts.map +1 -1
  356. package/dist/storage/runtime.js +87 -30
  357. package/dist/storage/runtime.js.map +1 -1
  358. package/package.json +56 -7
  359. package/dist/credits/postgres/repositories/pricing.d.ts +0 -28
  360. package/dist/credits/postgres/repositories/pricing.d.ts.map +0 -1
  361. package/dist/credits/postgres/repositories/pricing.js +0 -76
  362. package/dist/credits/postgres/repositories/pricing.js.map +0 -1
  363. package/dist/credits/pricing-runtime.d.ts.map +0 -1
  364. package/dist/credits/pricing-runtime.js.map +0 -1
  365. package/dist/load-pricing-file.d.ts.map +0 -1
  366. package/dist/load-pricing-file.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog-runtime.js","sourceRoot":"","sources":["../../src/credits/catalog-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,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jB,MAAM,IAAI,qBAAqB,CAC7B,kFAAkF,CACnF,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\nimport { canonicalBursarConfigDict, type CatalogRollout } from \"../config.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport { PricingEngine as PricingEngineClass } from \"../engine.js\";\nimport { LeaseNotFoundError, CatalogNotLoadedError } from \"../errors.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { MetricsOrAmount } from \"./service-types.js\";\n\nexport function toDecimal(value: Decimal | number): Decimal {\n if (value instanceof Decimal) return value;\n if (typeof value !== \"number\") {\n throw new TypeError(\"amount must be a Decimal or number\");\n }\n return new Decimal(value);\n}\n\nfunction toNonNegativeAmount(value: Decimal | number): Decimal {\n const amount = toDecimal(value);\n if (!amount.isFinite() || amount.isNegative()) {\n throw new RangeError(\"amount must be finite and non-negative\");\n }\n return amount;\n}\n\nexport function isAmount(value: MetricsOrAmount): value is Decimal | number {\n return value instanceof Decimal || typeof value === \"number\";\n}\n\n/** Owns catalog publication, cache refresh, and revision-aware pricing engines. */\nexport class CatalogRuntime {\n private engine: PricingEngine | null;\n private readonly cache: LRUCache<string, PricingEngine>;\n private readonly versionEngines = new Map<number, PricingEngine>();\n\n constructor(\n private readonly store: CreditStore,\n engine: PricingEngine | null,\n private readonly logger: NormalizedLogger,\n private readonly cacheTtlMs: number,\n ) {\n this.engine = engine;\n this.cache = new LRUCache<string, PricingEngine>({\n max: 1,\n ttl: cacheTtlMs,\n // Consumers must never proceed against a known-stale catalog. The cache\n // still deduplicates concurrent refreshes, but every caller awaits the\n // same fresh value just like the Python SDK's refresh lock.\n allowStale: false,\n fetchMethod: async () => {\n const engine = await this.fetchEngineFromStore();\n // `lru-cache` installs the returned value when the fetch completes.\n // Calling cache.set() from inside fetchMethod aborts the in-flight\n // refresh with a \"replaced\" error.\n this.engine = engine;\n this.versionEngines.clear();\n return engine;\n },\n });\n if (engine) this.cache.set(\"catalog\", engine);\n }\n\n get currentEngine(): PricingEngine | null {\n return this.engine;\n }\n\n async loadFromStore(): Promise<void> {\n this.setEngine(await this.fetchEngineFromStore());\n }\n\n private async fetchEngineFromStore(): Promise<PricingEngine> {\n this.logger.info(\"[CatalogService] loading active catalog\");\n const active = await this.store.getActiveCatalog();\n if (!active) {\n this.logger.warn(\"[CatalogService] no active catalog revision in store\");\n throw new CatalogNotLoadedError(\"No active catalog revision is available\");\n }\n return PricingEngineClass.fromDict(active.config as Record<string, unknown>);\n }\n\n async refreshIfStale(): Promise<void> {\n if (this.cacheTtlMs === 0) return;\n await this.cache.fetch(\"catalog\");\n }\n\n invalidate(): void {\n this.cache.delete(\"catalog\");\n }\n\n async publishAndActivate(\n config: Record<string, unknown>,\n label?: string | null,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string> {\n this.logger.info(\"[CatalogService] publishing and activating catalog\", { label });\n const canonical = canonicalBursarConfigDict(config);\n const nextEngine = PricingEngineClass.fromDict(canonical);\n const revisionId = await this.store.publishAndActivateCatalog(canonical, label, rollout);\n this.setEngine(nextEngine);\n return revisionId;\n }\n\n async publishDraft(config: Record<string, unknown>, label?: string | null): Promise<string> {\n return this.store.publishCatalogDraft(canonicalBursarConfigDict(config), label);\n }\n\n async activateRevision(\n version: number,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string> {\n const id = await this.store.activateCatalogRevision(version, rollout);\n await this.loadFromStore();\n return id;\n }\n\n async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n if (isAmount(metricsOrAmount)) {\n return { amount: toNonNegativeAmount(metricsOrAmount), model: null };\n }\n let engine: PricingEngine;\n let rateCard: string | undefined;\n if (leaseId != null) {\n if (userId == null) throw new TypeError(\"userId is required when pricing a lease\");\n const context = await this.store.getLeasePricingContext(userId, leaseId);\n if (!context) throw new LeaseNotFoundError(`Lease not found. User=${userId}`);\n engine = await this.engineForCatalogVersion(context.catalogVersion);\n rateCard = context.rateCard ?? engine.getRateCardForPlan(context.planKey);\n } else {\n engine = await this.engineForUser(userId ?? null);\n const plan = userId == null ? null : await this.store.getUserPlan(userId);\n rateCard = plan?.rateCard ?? undefined;\n }\n const breakdown = engine.calculate(metricsOrAmount, {\n rateCard,\n });\n return {\n amount: breakdown.total,\n model:\n typeof metricsOrAmount.dimensions?.model === \"string\"\n ? metricsOrAmount.dimensions.model\n : null,\n };\n }\n\n private setEngine(engine: PricingEngine): void {\n this.engine = engine;\n this.versionEngines.clear();\n this.cache.set(\"catalog\", engine);\n }\n\n async engineForUser(userId: string | null): Promise<PricingEngine> {\n if (userId == null) return this.requireEngine();\n\n const plan = await this.store.getUserPlan(userId);\n const catalogVersion = plan.catalogVersion ?? null;\n if (catalogVersion == null) {\n await this.refreshIfStale();\n return this.requireEngine();\n }\n\n return this.engineForCatalogVersion(catalogVersion);\n }\n\n private async engineForCatalogVersion(catalogVersion: number): Promise<PricingEngine> {\n const cached = this.versionEngines.get(catalogVersion);\n if (cached) return cached;\n\n const config = await this.store.getCatalogRevision(catalogVersion);\n if (!config?.config) {\n throw new CatalogNotLoadedError(\n `Catalog revision ${catalogVersion} is unavailable for the pinned plan`,\n );\n }\n\n const engine = PricingEngineClass.fromDict(config.config as Record<string, unknown>);\n this.versionEngines.set(catalogVersion, engine);\n return engine;\n }\n\n private requireEngine(): PricingEngine {\n if (!this.engine) {\n throw new CatalogNotLoadedError(\n \"Catalog is not loaded; call catalog.load() or catalog.publishAndActivate() first\",\n );\n }\n return this.engine;\n }\n}\n"]}
@@ -19,17 +19,17 @@
19
19
  *
20
20
  * Success events (``credits.deducted``/``credits.refunded``/…) are emitted by
21
21
  * ``CreditsService`` only after the underlying store operation committed without
22
- * an ``error`` (contract §6). Failure events (``credits.deduct_failed`` /
22
+ * an ``error``. Failure events (``credits.deduct_failed`` /
23
23
  * ``credits.refund_failed``) carry the store's business-error code in
24
24
  * ``data.error`` for observability/fraud monitoring.
25
25
  */
26
- export type CreditEventType = "credits.deducted" | "credits.deduct_failed" | "credits.added" | "credits.refunded" | "credits.refund_failed" | "credits.expired" | "credits.low_balance" | "credits.plan_changed" | "credits.reserved" | "credits.reservation_released" | "credits.lease_expired" | "credits.overdraft" | "credits.cycle_renewed" | "credits.quota_blocked" | "credits.quota_threshold";
26
+ export type CreditEventType = "credits.deducted" | "credits.deduct_failed" | "credits.added" | "credits.refunded" | "credits.refund_failed" | "credits.expired" | "credits.low_balance" | "credits.plan_changed" | "credits.reserved" | "credits.reservation_released" | "credits.lease_expired" | "credits.overdraft" | "credits.cycle_renewed" | "credits.revoked" | "credits.quota_blocked" | "credits.quota_threshold";
27
27
  /**
28
28
  * A typed credit lifecycle event.
29
29
  *
30
30
  * Money values inside ``data`` (``amount``, ``balanceAfter``,
31
31
  * ``allowanceConsumed``, ``threshold``, …) are exact `Decimal` instances
32
- * (contract §1/§6), never binary `number`.
32
+ * and never binary `number`.
33
33
  */
34
34
  export interface CreditEvent {
35
35
  type: CreditEventType;
@@ -51,7 +51,7 @@ export declare class CreditEventEmitter {
51
51
  * Each handler is isolated: a synchronous throw (or a rejected promise from an
52
52
  * async handler) is caught and logged, never propagated. This guarantees a
53
53
  * misbehaving listener can never break the manager's main flow and never
54
- * produces an unhandled promise rejection (contract §6).
54
+ * produces an unhandled promise rejection.
55
55
  */
56
56
  emit(event: CreditEvent): void;
57
57
  /** Remove all handlers for a specific type. */
@@ -1 +1 @@
1
- {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../src/credits/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;GAQG;AACH,MAAM,MAAM,eAAe,GACvB,kBAAkB,GAClB,uBAAuB,GACvB,eAAe,GACf,kBAAkB,GAClB,uBAAuB,GACvB,iBAAiB,GACjB,q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;AAE9B;;;;;;GAMG;AACH,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,eAAe,CAAC;IACtB,SAAS,EAAE,IAAI,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAChC;AAED,KAAK,YAAY,GAAG,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;AAErE,qDAAqD;AACrD,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,SAAS,CAAiD;IAElE,oDAAoD;IACpD,EAAE,CAAC,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,YAAY,GAAG,IAAI;IAOtD,8CAA8C;IAC9C,GAAG,CAAC,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,YAAY,GAAG,IAAI;IAIvD;;;;;;;OAOG;IACH,IAAI,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI;IAmB9B,+CAA+C;IAC/C,SAAS,CAAC,IAAI,EAAE,eAAe,GAAG,IAAI;IAItC,yCAAyC;IACzC,QAAQ,IAAI,IAAI;CAGjB"}
@@ -34,7 +34,7 @@ export class CreditEventEmitter {
34
34
  * Each handler is isolated: a synchronous throw (or a rejected promise from an
35
35
  * async handler) is caught and logged, never propagated. This guarantees a
36
36
  * misbehaving listener can never break the manager's main flow and never
37
- * produces an unhandled promise rejection (contract §6).
37
+ * produces an unhandled promise rejection.
38
38
  */
39
39
  emit(event) {
40
40
  const handlers = this.listeners.get(event.type);
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/credits/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AA4CH,qDAAqD;AACrD,MAAM,OAAO,kBAAkB;IACrB,SAAS,GAAG,IAAI,GAAG,EAAsC,CAAC;IAElE,oDAAoD;IACpD,EAAE,CAAC,IAAqB,EAAE,OAAqB;QAC7C,IAAI,CA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,+CAA+C;IAC/C,SAAS,CAAC,IAAqB;QAC7B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;IAED,yCAAyC;IACzC,QAAQ;QACN,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["/**\n * Typed event emitter for credit lifecycle events.\n *\n * Events are emitted by ``CreditsService`` after each store operation.\n * The emitter is optional — inject into ``CreditsService`` constructor,\n * no-op if omitted.\n *\n * @example\n * ```ts\n * const emitter = new CreditEventEmitter();\n * emitter.on(\"credits.deducted\", (event) => {\n * console.log(`Deducted ${event.data?.amount} from ${event.userId}`);\n * });\n * const manager = new CreditsService(store, engine, emitter);\n * ```\n */\n\n/**\n * All credit lifecycle event types.\n *\n * Success events (``credits.deducted``/``credits.refunded``/…) are emitted by\n * ``CreditsService`` only after the underlying store operation committed without\n * an ``error`` (contract §6). Failure events (``credits.deduct_failed`` /\n * ``credits.refund_failed``) carry the store's business-error code in\n * ``data.error`` for observability/fraud monitoring.\n */\nexport type CreditEventType =\n | \"credits.deducted\"\n | \"credits.deduct_failed\"\n | \"credits.added\"\n | \"credits.refunded\"\n | \"credits.refund_failed\"\n | \"credits.expired\"\n | \"credits.low_balance\"\n | \"credits.plan_changed\"\n | \"credits.reserved\"\n | \"credits.reservation_released\"\n | \"credits.lease_expired\"\n | \"credits.overdraft\"\n | \"credits.cycle_renewed\"\n | \"credits.quota_blocked\"\n | \"credits.quota_threshold\";\n\n/**\n * A typed credit lifecycle event.\n *\n * Money values inside ``data`` (``amount``, ``balanceAfter``,\n * ``allowanceConsumed``, ``threshold``, …) are exact `Decimal` instances\n * (contract §1/§6), never binary `number`.\n */\nexport interface CreditEvent {\n type: CreditEventType;\n timestamp: Date;\n userId: string;\n data?: Record<string, unknown>;\n}\n\ntype EventHandler = (event: CreditEvent) => void | PromiseLike<void>;\n\n/** Typed pub/sub event emitter for credit events. */\nexport class CreditEventEmitter {\n private listeners = new Map<CreditEventType, Set<EventHandler>>();\n\n /** Register a handler for a specific event type. */\n on(type: CreditEventType, handler: EventHandler): void {\n if (!this.listeners.has(type)) {\n this.listeners.set(type, new Set());\n }\n this.listeners.get(type)!.add(handler);\n }\n\n /** Remove a previously registered handler. */\n off(type: CreditEventType, handler: EventHandler): void {\n this.listeners.get(type)?.delete(handler);\n }\n\n /**\n * Emit an event to all registered handlers. No-op if no handlers exist.\n *\n * Each handler is isolated: a synchronous throw (or a rejected promise from an\n * async handler) is caught and logged, never propagated. This guarantees a\n * misbehaving listener can never break the manager's main flow and never\n * produces an unhandled promise rejection (contract §6).\n */\n emit(event: CreditEvent): void {\n const handlers = this.listeners.get(event.type);\n if (!handlers) return;\n // Iterate a snapshot so a handler that mutates the set during emit is safe.\n for (const handler of [...handlers]) {\n try {\n const out = handler(event);\n // Swallow rejections from async handlers so they never become unhandled.\n if (out != null && typeof out.then === \"function\") {\n void Promise.resolve(out).catch((err: unknown) => {\n console.error(`[CreditEventEmitter] async handler error for event ${event.type}:`, err);\n });\n }\n } catch (err) {\n console.error(`[CreditEventEmitter] handler error for event ${event.type}:`, err);\n }\n }\n }\n\n /** Remove all handlers for a specific type. */\n clearType(type: CreditEventType): void {\n this.listeners.delete(type);\n }\n\n /** Remove all handlers for all types. */\n clearAll(): void {\n this.listeners.clear();\n }\n}\n"]}
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/credits/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AA6CH,qDAAqD;AACrD,MAAM,OAAO,kBAAkB;IACrB,SAAS,GAAG,IAAI,GAAG,EAAsC,CAAC;IAElE,oDAAoD;IACpD,EAAE,CAAC,IAAqB,EAAE,OAAqB;QAC7C,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YAC9B,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,GAAG,EAAE,CAAC,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AAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["/**\n * Typed event emitter for credit lifecycle events.\n *\n * Events are emitted by ``CreditsService`` after each store operation.\n * The emitter is optional — inject into ``CreditsService`` constructor,\n * no-op if omitted.\n *\n * @example\n * ```ts\n * const emitter = new CreditEventEmitter();\n * emitter.on(\"credits.deducted\", (event) => {\n * console.log(`Deducted ${event.data?.amount} from ${event.userId}`);\n * });\n * const manager = new CreditsService(store, engine, emitter);\n * ```\n */\n\n/**\n * All credit lifecycle event types.\n *\n * Success events (``credits.deducted``/``credits.refunded``/…) are emitted by\n * ``CreditsService`` only after the underlying store operation committed without\n * an ``error``. Failure events (``credits.deduct_failed`` /\n * ``credits.refund_failed``) carry the store's business-error code in\n * ``data.error`` for observability/fraud monitoring.\n */\nexport type CreditEventType =\n | \"credits.deducted\"\n | \"credits.deduct_failed\"\n | \"credits.added\"\n | \"credits.refunded\"\n | \"credits.refund_failed\"\n | \"credits.expired\"\n | \"credits.low_balance\"\n | \"credits.plan_changed\"\n | \"credits.reserved\"\n | \"credits.reservation_released\"\n | \"credits.lease_expired\"\n | \"credits.overdraft\"\n | \"credits.cycle_renewed\"\n | \"credits.revoked\"\n | \"credits.quota_blocked\"\n | \"credits.quota_threshold\";\n\n/**\n * A typed credit lifecycle event.\n *\n * Money values inside ``data`` (``amount``, ``balanceAfter``,\n * ``allowanceConsumed``, ``threshold``, …) are exact `Decimal` instances\n * and never binary `number`.\n */\nexport interface CreditEvent {\n type: CreditEventType;\n timestamp: Date;\n userId: string;\n data?: Record<string, unknown>;\n}\n\ntype EventHandler = (event: CreditEvent) => void | PromiseLike<void>;\n\n/** Typed pub/sub event emitter for credit events. */\nexport class CreditEventEmitter {\n private listeners = new Map<CreditEventType, Set<EventHandler>>();\n\n /** Register a handler for a specific event type. */\n on(type: CreditEventType, handler: EventHandler): void {\n if (!this.listeners.has(type)) {\n this.listeners.set(type, new Set());\n }\n this.listeners.get(type)!.add(handler);\n }\n\n /** Remove a previously registered handler. */\n off(type: CreditEventType, handler: EventHandler): void {\n this.listeners.get(type)?.delete(handler);\n }\n\n /**\n * Emit an event to all registered handlers. No-op if no handlers exist.\n *\n * Each handler is isolated: a synchronous throw (or a rejected promise from an\n * async handler) is caught and logged, never propagated. This guarantees a\n * misbehaving listener can never break the manager's main flow and never\n * produces an unhandled promise rejection.\n */\n emit(event: CreditEvent): void {\n const handlers = this.listeners.get(event.type);\n if (!handlers) return;\n // Iterate a snapshot so a handler that mutates the set during emit is safe.\n for (const handler of [...handlers]) {\n try {\n const out = handler(event);\n // Swallow rejections from async handlers so they never become unhandled.\n if (out != null && typeof out.then === \"function\") {\n void Promise.resolve(out).catch((err: unknown) => {\n console.error(`[CreditEventEmitter] async handler error for event ${event.type}:`, err);\n });\n }\n } catch (err) {\n console.error(`[CreditEventEmitter] handler error for event ${event.type}:`, err);\n }\n }\n }\n\n /** Remove all handlers for a specific type. */\n clearType(type: CreditEventType): void {\n this.listeners.delete(type);\n }\n\n /** Remove all handlers for all types. */\n clearAll(): void {\n this.listeners.clear();\n }\n}\n"]}
@@ -2,13 +2,13 @@ import Decimal from "decimal.js";
2
2
  import type { NormalizedLogger } from "../shared/logger.js";
3
3
  import type { CreditEventType } from "./events.js";
4
4
  import { LowBalanceMonitor } from "./low-balance-monitor.js";
5
- import { PricingRuntime } from "./pricing-runtime.js";
5
+ import { CatalogRuntime } from "./catalog-runtime.js";
6
6
  import type { CanAffordOptions, BeginBilledOperationOptions, BilledOperation, MetricsOrAmount, PolicyPreset, ReserveOptions, RunBilledOptions, SettleOptions } from "./service-types.js";
7
7
  import type { CreditStore } from "./store.js";
8
- import type { AllowanceResult, BucketBalancesResult, CanAffordResult, DeductionResult, LeaseResult, ReleaseResult } from "./types/index.js";
8
+ import type { AllowanceResult, BucketBalancesResult, CanAffordResult, DeductionResult, DeductionSuccess, LeaseSuccess, ReleaseResult } from "./types/index.js";
9
9
  export declare class CreditLeaseWorkflow {
10
10
  private readonly store;
11
- private readonly pricing;
11
+ private readonly catalogRuntime;
12
12
  private readonly logger;
13
13
  private readonly balanceMonitor;
14
14
  private readonly policy;
@@ -19,7 +19,7 @@ export declare class CreditLeaseWorkflow {
19
19
  private readonly emitQuotaEvents;
20
20
  private readonly maybeLazyExpire;
21
21
  private readonly afterDeduction;
22
- constructor(store: CreditStore, pricing: PricingRuntime, logger: NormalizedLogger, balanceMonitor: LowBalanceMonitor, policy: PolicyPreset, overdraftFloor: Decimal | null, defaultMaxConcurrent: number | null, defaultTtl: number, emit: (type: CreditEventType, userId: string, data?: Record<string, unknown>) => void, emitQuotaEvents: (userId: string, idempotencyKey: string) => Promise<void>, maybeLazyExpire: (userId: string) => Promise<void>, afterDeduction: (userId: string, result: DeductionResult) => Promise<void>);
22
+ constructor(store: CreditStore, catalogRuntime: CatalogRuntime, logger: NormalizedLogger, balanceMonitor: LowBalanceMonitor, policy: PolicyPreset, overdraftFloor: Decimal | null, defaultMaxConcurrent: number | null, defaultTtl: number, emit: (type: CreditEventType, userId: string, data?: Record<string, unknown>) => void, emitQuotaEvents: (userId: string, idempotencyKey: string) => Promise<void>, maybeLazyExpire: (userId: string) => Promise<void>, afterDeduction: (userId: string, result: DeductionSuccess) => Promise<void>);
23
23
  private expectedAdmissionPolicy;
24
24
  /**
25
25
  * Compute the credit cost and model from metrics, or pass a raw amount through.
@@ -29,26 +29,26 @@ export declare class CreditLeaseWorkflow {
29
29
  */
30
30
  private costOf;
31
31
  /**
32
- * Atomically acquire a lease — the only admission control (D4).
32
+ * Atomically acquire a lease — the only authoritative admission control.
33
33
  *
34
34
  * Prices the estimate and delegates entitlement, quota, allowance, credit
35
35
  * policy, and concurrency enforcement to the database in one atomic call.
36
36
  */
37
- reserve(userId: string, metricsOrAmount: MetricsOrAmount, options?: ReserveOptions): Promise<LeaseResult>;
37
+ reserve(userId: string, metricsOrAmount: MetricsOrAmount, options?: ReserveOptions): Promise<LeaseSuccess>;
38
38
  /**
39
- * Charge the ACTUAL cost against a lease and finalize it (D5).
39
+ * Charge the actual cost against a lease and finalize it.
40
40
  *
41
41
  * De-clamped: bills the full actual cost even if it exceeds the lease hold
42
42
  * (overdraft). Emits ``credits.deducted``, then low-balance and overdraft
43
43
  * signals as applicable.
44
44
  */
45
45
  settle(userId: string, leaseId: string, metricsOrAmount: MetricsOrAmount, options?: SettleOptions): Promise<DeductionResult>;
46
- /** Release a lease without charging (work failed/aborted) — idempotent (H1). */
46
+ /** Release a lease without charging; safe to repeat after failed or aborted work. */
47
47
  release(userId: string, leaseId: string): Promise<ReleaseResult>;
48
48
  /** Extend an active lease's expiry without changing its captured policy. */
49
- renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseResult>;
49
+ renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess>;
50
50
  /**
51
- * Advisory affordability check — UI only, non-locking, may be stale (D4/H3).
51
+ * Advisory affordability check — UI only, non-locking, and potentially stale.
52
52
  *
53
53
  * Never use this as an admission gate; only ``reserve`` is authoritative.
54
54
  */
@@ -59,15 +59,15 @@ export declare class CreditLeaseWorkflow {
59
59
  * Get remaining free allowance for the current billing period.
60
60
  *
61
61
  * Convenience wrapper that routes through the manager so callers never need
62
- * to reach past it into the raw store. Returns a zero-allowance result for
63
- * planless users (no exception).
62
+ * to reach past it into the raw store. Returns `null` when the subject has no
63
+ * active allowance policy.
64
64
  *
65
65
  * Window calculation is database-owned and supports the full normalized
66
66
  * policy tuple, including timezone and arbitrary interval counts.
67
67
  */
68
- checkAllowance(userId: string): Promise<AllowanceResult>;
68
+ checkAllowance(userId: string): Promise<AllowanceResult | null>;
69
69
  /**
70
- * One-call shortcut wiring reserve → doWork → settle (interface plan §4).
70
+ * One-call shortcut wiring reserve → doWork → settle.
71
71
  *
72
72
  * ``doWork`` runs the operation and returns ``{ result, actual }`` where
73
73
  * ``actual`` is the real usage metrics (or amount) to settle. On any exception
@@ -1 +1 @@
1
- {"version":3,"file":"lease-workflow.d.ts","sourceRoot":"","sources":["../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ACG,MAAM,CACV,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,eAAe,EAAE,eAAe,EAChC,OAAO,CAAC,EAAE,aAAa,GACtB,OAAO,CAAC,eAAe,CAAC;IA+E3B,qFAAqF;IAC/E,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC;IAatE,4EAA4E;IACtE,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,YAAY,CAAC;IAaxF;;;;OAIG;IACG,SAAS,CACb,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,eAAe,EAChC,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,eAAe,CAAC;IAgD3B,sGAAsG;IAChG,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAKtE;;;;;;;;;OASG;IACG,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAIrE;;;;;;;;OAQG;IACG,SAAS,CAAC,CAAC,EACf,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAC3B,OAAO,CAAC;QAAE,MAAM,EAAE,CAAC,CAAC;QAAC,SAAS,EAAE,eAAe,CAAA;KAAE,CAAC;IA6BrD;;;;;OAKG;IACG,oBAAoB,CACxB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,eAAe,CAAC;CA6B5B"}
@@ -3,11 +3,11 @@ import { randomUUID } from "node:crypto";
3
3
  import { ConfigError } from "../errors.js";
4
4
  import { retryBursarOperation } from "../retry.js";
5
5
  import { LowBalanceMonitor } from "./low-balance-monitor.js";
6
- import { isAmount, PricingRuntime } from "./pricing-runtime.js";
6
+ import { isAmount, CatalogRuntime } from "./catalog-runtime.js";
7
7
  import { raiseLeaseError } from "./service-errors.js";
8
8
  export class CreditLeaseWorkflow {
9
9
  store;
10
- pricing;
10
+ catalogRuntime;
11
11
  logger;
12
12
  balanceMonitor;
13
13
  policy;
@@ -18,9 +18,9 @@ export class CreditLeaseWorkflow {
18
18
  emitQuotaEvents;
19
19
  maybeLazyExpire;
20
20
  afterDeduction;
21
- constructor(store, pricing, logger, balanceMonitor, policy, overdraftFloor, defaultMaxConcurrent, defaultTtl, emit, emitQuotaEvents, maybeLazyExpire, afterDeduction) {
21
+ constructor(store, catalogRuntime, logger, balanceMonitor, policy, overdraftFloor, defaultMaxConcurrent, defaultTtl, emit, emitQuotaEvents, maybeLazyExpire, afterDeduction) {
22
22
  this.store = store;
23
- this.pricing = pricing;
23
+ this.catalogRuntime = catalogRuntime;
24
24
  this.logger = logger;
25
25
  this.balanceMonitor = balanceMonitor;
26
26
  this.policy = policy;
@@ -62,10 +62,10 @@ export class CreditLeaseWorkflow {
62
62
  * `Decimal`, no truncation); a raw amount is used as-is with no model.
63
63
  */
64
64
  async costOf(metricsOrAmount, userId, leaseId) {
65
- return this.pricing.costOf(metricsOrAmount, userId, leaseId);
65
+ return this.catalogRuntime.costOf(metricsOrAmount, userId, leaseId);
66
66
  }
67
67
  /**
68
- * Atomically acquire a lease — the only admission control (D4).
68
+ * Atomically acquire a lease — the only authoritative admission control.
69
69
  *
70
70
  * Prices the estimate and delegates entitlement, quota, allowance, credit
71
71
  * policy, and concurrency enforcement to the database in one atomic call.
@@ -100,7 +100,7 @@ export class CreditLeaseWorkflow {
100
100
  measures,
101
101
  dimensions,
102
102
  });
103
- if (result.error) {
103
+ if (result.error !== null) {
104
104
  if (result.error === "quota_exceeded") {
105
105
  await this.emitQuotaEvents(userId, leaseIdempotencyKey);
106
106
  }
@@ -129,7 +129,7 @@ export class CreditLeaseWorkflow {
129
129
  return result;
130
130
  }
131
131
  /**
132
- * Charge the ACTUAL cost against a lease and finalize it (D5).
132
+ * Charge the actual cost against a lease and finalize it.
133
133
  *
134
134
  * De-clamped: bills the full actual cost even if it exceeds the lease hold
135
135
  * (overdraft). Emits ``credits.deducted``, then low-balance and overdraft
@@ -144,7 +144,7 @@ export class CreditLeaseWorkflow {
144
144
  const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };
145
145
  const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };
146
146
  const region = typeof dimensions.region === "string" ? dimensions.region : null;
147
- // Build ledger metadata: caller fields first, system fields last (M7).
147
+ // Build ledger metadata with caller fields first and protected system fields last.
148
148
  const txMeta = {};
149
149
  if (isAmount(metricsOrAmount)) {
150
150
  if (options?.metadata) {
@@ -179,7 +179,7 @@ export class CreditLeaseWorkflow {
179
179
  dimensions,
180
180
  metadata: txMeta,
181
181
  });
182
- if (result.error) {
182
+ if (result.error !== null) {
183
183
  this.emit("credits.deduct_failed", userId, {
184
184
  error: result.error,
185
185
  amount,
@@ -213,7 +213,7 @@ export class CreditLeaseWorkflow {
213
213
  }
214
214
  return result;
215
215
  }
216
- /** Release a lease without charging (work failed/aborted) — idempotent (H1). */
216
+ /** Release a lease without charging; safe to repeat after failed or aborted work. */
217
217
  async release(userId, leaseId) {
218
218
  this.logger.debug("[CreditsService] release", { leaseId });
219
219
  const result = await this.store.releaseLease(userId, leaseId);
@@ -231,7 +231,7 @@ export class CreditLeaseWorkflow {
231
231
  const ttlSeconds = ttl ?? this.defaultTtl;
232
232
  this.logger.debug("[CreditsService] renew", { leaseId, ttlSeconds });
233
233
  const result = await this.store.renewLease(userId, leaseId, ttlSeconds);
234
- if (result.error) {
234
+ if (result.error !== null) {
235
235
  if (result.error === "expired_lease") {
236
236
  this.emit("credits.lease_expired", userId, { leaseId });
237
237
  }
@@ -240,7 +240,7 @@ export class CreditLeaseWorkflow {
240
240
  return result;
241
241
  }
242
242
  /**
243
- * Advisory affordability check — UI only, non-locking, may be stale (D4/H3).
243
+ * Advisory affordability check — UI only, non-locking, and potentially stale.
244
244
  *
245
245
  * Never use this as an admission gate; only ``reserve`` is authoritative.
246
246
  */
@@ -263,7 +263,8 @@ export class CreditLeaseWorkflow {
263
263
  }
264
264
  let allowanceRemaining = new Decimal(0);
265
265
  try {
266
- allowanceRemaining = (await this.store.checkAllowance(userId)).allowanceRemaining;
266
+ allowanceRemaining =
267
+ (await this.store.checkAllowance(userId))?.allowanceRemaining ?? new Decimal(0);
267
268
  }
268
269
  catch (error) {
269
270
  this.logger.debug("[CreditsService] allowance fetch failed in canAfford", {
@@ -295,8 +296,8 @@ export class CreditLeaseWorkflow {
295
296
  * Get remaining free allowance for the current billing period.
296
297
  *
297
298
  * Convenience wrapper that routes through the manager so callers never need
298
- * to reach past it into the raw store. Returns a zero-allowance result for
299
- * planless users (no exception).
299
+ * to reach past it into the raw store. Returns `null` when the subject has no
300
+ * active allowance policy.
300
301
  *
301
302
  * Window calculation is database-owned and supports the full normalized
302
303
  * policy tuple, including timezone and arbitrary interval counts.
@@ -305,7 +306,7 @@ export class CreditLeaseWorkflow {
305
306
  return await this.store.checkAllowance(userId);
306
307
  }
307
308
  /**
308
- * One-call shortcut wiring reserve → doWork → settle (interface plan §4).
309
+ * One-call shortcut wiring reserve → doWork → settle.
309
310
  *
310
311
  * ``doWork`` runs the operation and returns ``{ result, actual }`` where
311
312
  * ``actual`` is the real usage metrics (or amount) to settle. On any exception
@@ -1 +1 @@
1
- {"version":3,"file":"lease-workflow.js","sourceRoot":"","sources":["../../src/credits/lease-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,QAAQ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,EAAE,OAAO,CAAC,YAAY;YAClC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CACjC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE;gBACzC,cAAc,EAAE,GAAG,OAAO,CAAC,YAAY,SAAS;gBAChD,OAAO,EAAE,OAAO,CAAC,OAAO;gBACxB,QAAQ,EAAE,QAAQ,IAAI,OAAO,CAAC,QAAQ;aACvC,CAAC;YACJ,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE;gBACnB,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;YAC/C,CAAC;YACD,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;YAC5C,CAAC;SACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { ConfigError } from \"../errors.js\";\nimport { retryBursarOperation } from \"../retry.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEventType } from \"./events.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { isAmount, PricingRuntime } from \"./pricing-runtime.js\";\nimport { raiseLeaseError } from \"./service-errors.js\";\nimport type {\n CanAffordOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n MetricsOrAmount,\n PolicyPreset,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type {\n AllowanceResult,\n BillingMode,\n BucketBalancesResult,\n CanAffordResult,\n CreditMetadata,\n DeductionResult,\n LeaseResult,\n ReleaseResult,\n} from \"./types/index.js\";\n\nexport class CreditLeaseWorkflow {\n constructor(\n private readonly store: CreditStore,\n private readonly pricing: PricingRuntime,\n private readonly logger: NormalizedLogger,\n private readonly balanceMonitor: LowBalanceMonitor,\n private readonly policy: PolicyPreset,\n private readonly overdraftFloor: Decimal | null,\n private readonly defaultMaxConcurrent: number | null,\n private readonly defaultTtl: number,\n private readonly emit: (\n type: CreditEventType,\n userId: string,\n data?: Record<string, unknown>,\n ) => void,\n private readonly emitQuotaEvents: (userId: string, idempotencyKey: string) => Promise<void>,\n private readonly maybeLazyExpire: (userId: string) => Promise<void>,\n private readonly afterDeduction: (userId: string, result: DeductionResult) => Promise<void>,\n ) {}\n\n private async expectedAdmissionPolicy(\n userId: string,\n operationType: string,\n billingModeOverride?: BillingMode | null,\n ): Promise<{\n billingMode: BillingMode;\n floor: Decimal;\n maxConcurrent: number | null;\n }> {\n const plan = await this.store.getUserPlan(userId);\n const creditPolicy = plan.planId == null ? null : plan.creditPolicy;\n const planMode: BillingMode =\n plan.planId == null\n ? this.policy === \"overdraft\"\n ? \"overdraft\"\n : \"strict\"\n : creditPolicy?.type === \"credit_line\"\n ? \"overdraft\"\n : \"strict\";\n const operationAdmission =\n plan.planId == null ? null : (plan.admission?.operations[operationType] ?? null);\n const billingMode = billingModeOverride ?? planMode;\n const floor =\n billingMode === \"overdraft\"\n ? (creditPolicy?.creditLimit?.negated() ?? this.overdraftFloor ?? new Decimal(0))\n : new Decimal(0);\n return {\n billingMode,\n floor,\n maxConcurrent:\n plan.planId == null\n ? this.defaultMaxConcurrent\n : (operationAdmission?.maxInFlight ?? plan.admission?.maxInFlight ?? null),\n };\n }\n\n /**\n * Compute the credit cost and model from metrics, or pass a raw amount through.\n *\n * For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact\n * `Decimal`, no truncation); a raw amount is used as-is with no model.\n */\n private async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n return this.pricing.costOf(metricsOrAmount, userId, leaseId);\n }\n\n /**\n * Atomically acquire a lease — the only admission control (D4).\n *\n * Prices the estimate and delegates entitlement, quota, allowance, credit\n * policy, and concurrency enforcement to the database in one atomic call.\n */\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: ReserveOptions,\n ): Promise<LeaseResult> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] reserve\", {\n feature: options?.feature,\n operationType: options?.operationType,\n });\n const operationType =\n options?.operationType ?? (isAmount(metricsOrAmount) ? \"usage\" : metricsOrAmount.operation);\n const expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n operationType,\n options?.billingMode,\n );\n const priced = await this.costOf(metricsOrAmount, userId);\n const amount = priced.amount;\n const model = priced.model ?? options?.model ?? null;\n const ttlSeconds = options?.ttl != null ? options.ttl : this.defaultTtl;\n const feature = options?.feature ?? null;\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = typeof dimensions.region === \"string\" ? dimensions.region : null;\n const leaseIdempotencyKey = options?.idempotencyKey ?? `lease:${randomUUID()}`;\n\n const result = await this.store.createLease(userId, amount, operationType, {\n idempotencyKey: leaseIdempotencyKey,\n billingMode: expectedPolicy.billingMode,\n floor: expectedPolicy.floor,\n maxConcurrent: expectedPolicy.maxConcurrent,\n ttlSeconds,\n model,\n metadata: options?.metadata,\n feature,\n region,\n measures,\n dimensions,\n });\n\n if (result.error) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n }\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"reserve\",\n operationType,\n });\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] reservation acquired\", {\n leaseId: result.leaseId,\n amount: result.amount,\n minimumBalance: result.minimumBalance,\n });\n this.emit(\"credits.reserved\", userId, {\n leaseId: result.leaseId,\n amount: result.amount,\n available: result.available,\n minimumBalance: result.minimumBalance,\n operationType,\n expiresAt: result.expiresAt,\n });\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n return result;\n }\n\n /**\n * Charge the ACTUAL cost against a lease and finalize it (D5).\n *\n * De-clamped: bills the full actual cost even if it exceeds the lease hold\n * (overdraft). Emits ``credits.deducted``, then low-balance and overdraft\n * signals as applicable.\n */\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] settle\", { leaseId });\n const idempotencyKey = options?.idempotencyKey ?? `lease:${leaseId}:settle`;\n const feature = options?.feature ?? null;\n const { amount, model } = await this.costOf(metricsOrAmount, userId, leaseId);\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = typeof dimensions.region === \"string\" ? dimensions.region : null;\n\n // Build ledger metadata: caller fields first, system fields last (M7).\n const txMeta: Record<string, unknown> = {};\n if (isAmount(metricsOrAmount)) {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n } else {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n txMeta[\"operation\"] = metricsOrAmount.operation;\n txMeta[\"measures\"] = { ...(metricsOrAmount.measures ?? {}) };\n txMeta[\"dimensions\"] = { ...(metricsOrAmount.dimensions ?? {}) };\n txMeta[\"breakdownTotal\"] = amount.toString();\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n }\n\n const result = await this.store.settleLease(userId, leaseId, amount, {\n idempotencyKey,\n feature,\n model,\n region,\n measures,\n dimensions,\n metadata: txMeta as CreditMetadata,\n });\n\n if (result.error) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"settle\",\n leaseId,\n });\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] settled\", {\n leaseId,\n amount: result.amount,\n balanceAfter: result.balanceAfter,\n idempotent: result.idempotent,\n });\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model,\n leaseId,\n idempotent: result.idempotent,\n });\n\n await this.balanceMonitor.afterCharge(userId, result);\n if (!result.idempotent) {\n await this.emitQuotaEvents(userId, idempotencyKey);\n await this.afterDeduction(userId, result);\n }\n return result;\n }\n\n /** Release a lease without charging (work failed/aborted) — idempotent (H1). */\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n this.logger.debug(\"[CreditsService] release\", { leaseId });\n const result = await this.store.releaseLease(userId, leaseId);\n if (result.released) {\n this.logger.info(\"[CreditsService] lease released\", { leaseId, reason: result.reason });\n this.emit(\"credits.reservation_released\", userId, {\n leaseId,\n reason: result.reason,\n });\n }\n return result;\n }\n\n /** Extend an active lease's expiry without changing its captured policy. */\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseResult> {\n const ttlSeconds = ttl ?? this.defaultTtl;\n this.logger.debug(\"[CreditsService] renew\", { leaseId, ttlSeconds });\n const result = await this.store.renewLease(userId, leaseId, ttlSeconds);\n if (result.error) {\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, new Decimal(0));\n }\n return result;\n }\n\n /**\n * Advisory affordability check — UI only, non-locking, may be stale (D4/H3).\n *\n * Never use this as an admission gate; only ``reserve`` is authoritative.\n */\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n await this.maybeLazyExpire(userId);\n const feature = options?.feature ?? null;\n const { amount: worstCase } = await this.costOf(metricsOrAmount, userId);\n const avail = await this.store.getAvailable(userId);\n let expectedPolicy;\n try {\n expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n options?.operationType ?? \"usage\",\n options?.billingMode,\n );\n } catch {\n return {\n affordable: false,\n spendable: avail.available,\n worstCase,\n reason: \"policy_unavailable\",\n };\n }\n let allowanceRemaining = new Decimal(0);\n try {\n allowanceRemaining = (await this.store.checkAllowance(userId)).allowanceRemaining;\n } catch (error) {\n this.logger.debug(\"[CreditsService] allowance fetch failed in canAfford\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n const spendable = avail.available.plus(allowanceRemaining).minus(expectedPolicy.floor);\n\n let affordable = true;\n let reason: string | null = null;\n if (feature != null) {\n const check = await this.store.checkFeature(userId, feature);\n if (!check.hasFeature) {\n affordable = false;\n reason = \"feature_not_entitled\";\n }\n }\n if (affordable && spendable.lt(worstCase)) {\n affordable = false;\n reason = \"insufficient_credits\";\n }\n\n return { affordable, spendable, worstCase, reason };\n }\n\n /** Get a user's per-bucket credit balances (credit buckets). Thin pass-through, no event emission. */\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBucketBalances(userId);\n }\n\n /**\n * Get remaining free allowance for the current billing period.\n *\n * Convenience wrapper that routes through the manager so callers never need\n * to reach past it into the raw store. Returns a zero-allowance result for\n * planless users (no exception).\n *\n * Window calculation is database-owned and supports the full normalized\n * policy tuple, including timezone and arbitrary interval counts.\n */\n async checkAllowance(userId: string): Promise<AllowanceResult> {\n return await this.store.checkAllowance(userId);\n }\n\n /**\n * One-call shortcut wiring reserve → doWork → settle (interface plan §4).\n *\n * ``doWork`` runs the operation and returns ``{ result, actual }`` where\n * ``actual`` is the real usage metrics (or amount) to settle. On any exception\n * from ``doWork`` the lease is released and the error re-raised. For long jobs\n * ``doWork`` may call the configured lease TTL. A crash between reserve and settle is\n * covered by the lease TTL (and the store's reaper).\n */\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n const operationKey = options.operationKey ?? `billed:${randomUUID()}`;\n const operation = await this.beginBilledOperation(userId, {\n estimate: options.estimate,\n operationKey,\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n });\n\n let workResult: T;\n let actual: MetricsOrAmount;\n try {\n ({ result: workResult, actual } = await options.doWork());\n } catch (err) {\n await operation.release();\n throw err;\n }\n\n // Never release after work succeeds. A settlement failure may be a\n // transient/unknown-commit outcome and is safe to replay with operationKey.\n const deduction = await retryBursarOperation(() => operation.settle(actual), {\n maxAttempts: options.settlementAttempts,\n });\n return { result: workResult, deduction };\n }\n\n /**\n * Begin a replay-safe billable operation that can span framework callbacks.\n *\n * The operation key is namespaced into distinct reserve and settle keys, so\n * replaying the whole lifecycle cannot acquire a second hold.\n */\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n if (!options.operationKey.trim()) {\n throw new ConfigError(\"operationKey must not be empty\");\n }\n const lease = await this.reserve(userId, options.estimate, {\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n idempotencyKey: `${options.operationKey}:reserve`,\n });\n return {\n leaseId: lease.leaseId,\n operationKey: options.operationKey,\n settle: async (actual, metadata) =>\n this.settle(userId, lease.leaseId, actual, {\n idempotencyKey: `${options.operationKey}:settle`,\n feature: options.feature,\n metadata: metadata ?? options.metadata,\n }),\n renew: async (ttl) => {\n await this.renew(userId, lease.leaseId, ttl);\n },\n release: async () => {\n await this.release(userId, lease.leaseId);\n },\n };\n }\n}\n"]}
1
+ {"version":3,"file":"lease-workflow.js","sourceRoot":"","sources":["../../src/credits/lease-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACj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D,aAAa,EAAE,OAAO,CAAC,aAAa;YACpC,WAAW,EAAE,OAAO,CAAC,WAAW;YAChC,GAAG,EAAE,OAAO,CAAC,GAAG;YAChB,OAAO,EAAE,OAAO,CAAC,OAAO;YACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ;YAC1B,cAAc,EAAE,GAAG,OAAO,CAAC,YAAY,UAAU;SAClD,CAAC,CAAC;QACH,OAAO;YACL,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,YAAY,EAAE,OAAO,CAAC,YAAY;YAClC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,CACjC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE;gBACzC,cAAc,EAAE,GAAG,OAAO,CAAC,YAAY,SAAS;gBAChD,OAAO,EAAE,OAAO,CAAC,OAAO;gBACxB,QAAQ,EAAE,QAAQ,IAAI,OAAO,CAAC,QAAQ;aACvC,CAAC;YACJ,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE;gBACnB,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;YAC/C,CAAC;YACD,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;YAC5C,CAAC;SACF,CAAC;IACJ,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { ConfigError } from \"../errors.js\";\nimport { retryBursarOperation } from \"../retry.js\";\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEventType } from \"./events.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { isAmount, CatalogRuntime } from \"./catalog-runtime.js\";\nimport { raiseLeaseError } from \"./service-errors.js\";\nimport type {\n CanAffordOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n MetricsOrAmount,\n PolicyPreset,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n} from \"./service-types.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type {\n AllowanceResult,\n BillingMode,\n BucketBalancesResult,\n CanAffordResult,\n CreditMetadata,\n DeductionResult,\n DeductionSuccess,\n LeaseSuccess,\n ReleaseResult,\n} from \"./types/index.js\";\n\nexport class CreditLeaseWorkflow {\n constructor(\n private readonly store: CreditStore,\n private readonly catalogRuntime: CatalogRuntime,\n private readonly logger: NormalizedLogger,\n private readonly balanceMonitor: LowBalanceMonitor,\n private readonly policy: PolicyPreset,\n private readonly overdraftFloor: Decimal | null,\n private readonly defaultMaxConcurrent: number | null,\n private readonly defaultTtl: number,\n private readonly emit: (\n type: CreditEventType,\n userId: string,\n data?: Record<string, unknown>,\n ) => void,\n private readonly emitQuotaEvents: (userId: string, idempotencyKey: string) => Promise<void>,\n private readonly maybeLazyExpire: (userId: string) => Promise<void>,\n private readonly afterDeduction: (userId: string, result: DeductionSuccess) => Promise<void>,\n ) {}\n\n private async expectedAdmissionPolicy(\n userId: string,\n operationType: string,\n billingModeOverride?: BillingMode | null,\n ): Promise<{\n billingMode: BillingMode;\n floor: Decimal;\n maxConcurrent: number | null;\n }> {\n const plan = await this.store.getUserPlan(userId);\n const creditPolicy = plan.planId == null ? null : plan.creditPolicy;\n const planMode: BillingMode =\n plan.planId == null\n ? this.policy === \"overdraft\"\n ? \"overdraft\"\n : \"strict\"\n : creditPolicy?.type === \"credit_line\"\n ? \"overdraft\"\n : \"strict\";\n const operationAdmission =\n plan.planId == null ? null : (plan.admission?.operations[operationType] ?? null);\n const billingMode = billingModeOverride ?? planMode;\n const floor =\n billingMode === \"overdraft\"\n ? (creditPolicy?.creditLimit?.negated() ?? this.overdraftFloor ?? new Decimal(0))\n : new Decimal(0);\n return {\n billingMode,\n floor,\n maxConcurrent:\n plan.planId == null\n ? this.defaultMaxConcurrent\n : (operationAdmission?.maxInFlight ?? plan.admission?.maxInFlight ?? null),\n };\n }\n\n /**\n * Compute the credit cost and model from metrics, or pass a raw amount through.\n *\n * For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact\n * `Decimal`, no truncation); a raw amount is used as-is with no model.\n */\n private async costOf(\n metricsOrAmount: MetricsOrAmount,\n userId?: string | null,\n leaseId?: string | null,\n ): Promise<{ amount: Decimal; model: string | null }> {\n return this.catalogRuntime.costOf(metricsOrAmount, userId, leaseId);\n }\n\n /**\n * Atomically acquire a lease — the only authoritative admission control.\n *\n * Prices the estimate and delegates entitlement, quota, allowance, credit\n * policy, and concurrency enforcement to the database in one atomic call.\n */\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: ReserveOptions,\n ): Promise<LeaseSuccess> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] reserve\", {\n feature: options?.feature,\n operationType: options?.operationType,\n });\n const operationType =\n options?.operationType ?? (isAmount(metricsOrAmount) ? \"usage\" : metricsOrAmount.operation);\n const expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n operationType,\n options?.billingMode,\n );\n const priced = await this.costOf(metricsOrAmount, userId);\n const amount = priced.amount;\n const model = priced.model ?? options?.model ?? null;\n const ttlSeconds = options?.ttl != null ? options.ttl : this.defaultTtl;\n const feature = options?.feature ?? null;\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = typeof dimensions.region === \"string\" ? dimensions.region : null;\n const leaseIdempotencyKey = options?.idempotencyKey ?? `lease:${randomUUID()}`;\n\n const result = await this.store.createLease(userId, amount, operationType, {\n idempotencyKey: leaseIdempotencyKey,\n billingMode: expectedPolicy.billingMode,\n floor: expectedPolicy.floor,\n maxConcurrent: expectedPolicy.maxConcurrent,\n ttlSeconds,\n model,\n metadata: options?.metadata,\n feature,\n region,\n measures,\n dimensions,\n });\n\n if (result.error !== null) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n }\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"reserve\",\n operationType,\n });\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] reservation acquired\", {\n leaseId: result.leaseId,\n amount: result.amount,\n minimumBalance: result.minimumBalance,\n });\n this.emit(\"credits.reserved\", userId, {\n leaseId: result.leaseId,\n amount: result.amount,\n available: result.available,\n minimumBalance: result.minimumBalance,\n operationType,\n expiresAt: result.expiresAt,\n });\n await this.emitQuotaEvents(userId, leaseIdempotencyKey);\n return result;\n }\n\n /**\n * Charge the actual cost against a lease and finalize it.\n *\n * De-clamped: bills the full actual cost even if it exceeds the lease hold\n * (overdraft). Emits ``credits.deducted``, then low-balance and overdraft\n * signals as applicable.\n */\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] settle\", { leaseId });\n const idempotencyKey = options?.idempotencyKey ?? `lease:${leaseId}:settle`;\n const feature = options?.feature ?? null;\n const { amount, model } = await this.costOf(metricsOrAmount, userId, leaseId);\n const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };\n const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };\n const region = typeof dimensions.region === \"string\" ? dimensions.region : null;\n\n // Build ledger metadata with caller fields first and protected system fields last.\n const txMeta: Record<string, unknown> = {};\n if (isAmount(metricsOrAmount)) {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n } else {\n if (options?.metadata) {\n for (const [k, v] of Object.entries(options.metadata)) {\n if (v != null) txMeta[k] = v;\n }\n }\n txMeta[\"operation\"] = metricsOrAmount.operation;\n txMeta[\"measures\"] = { ...(metricsOrAmount.measures ?? {}) };\n txMeta[\"dimensions\"] = { ...(metricsOrAmount.dimensions ?? {}) };\n txMeta[\"breakdownTotal\"] = amount.toString();\n if (idempotencyKey) txMeta[\"idempotencyKey\"] = idempotencyKey;\n }\n\n const result = await this.store.settleLease(userId, leaseId, amount, {\n idempotencyKey,\n feature,\n model,\n region,\n measures,\n dimensions,\n metadata: txMeta as CreditMetadata,\n });\n\n if (result.error !== null) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount,\n stage: \"settle\",\n leaseId,\n });\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, amount);\n }\n\n this.logger.info(\"[CreditsService] settled\", {\n leaseId,\n amount: result.amount,\n balanceAfter: result.balanceAfter,\n idempotent: result.idempotent,\n });\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model,\n leaseId,\n idempotent: result.idempotent,\n });\n\n await this.balanceMonitor.afterCharge(userId, result);\n if (!result.idempotent) {\n await this.emitQuotaEvents(userId, idempotencyKey);\n await this.afterDeduction(userId, result);\n }\n return result;\n }\n\n /** Release a lease without charging; safe to repeat after failed or aborted work. */\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n this.logger.debug(\"[CreditsService] release\", { leaseId });\n const result = await this.store.releaseLease(userId, leaseId);\n if (result.released) {\n this.logger.info(\"[CreditsService] lease released\", { leaseId, reason: result.reason });\n this.emit(\"credits.reservation_released\", userId, {\n leaseId,\n reason: result.reason,\n });\n }\n return result;\n }\n\n /** Extend an active lease's expiry without changing its captured policy. */\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseSuccess> {\n const ttlSeconds = ttl ?? this.defaultTtl;\n this.logger.debug(\"[CreditsService] renew\", { leaseId, ttlSeconds });\n const result = await this.store.renewLease(userId, leaseId, ttlSeconds);\n if (result.error !== null) {\n if (result.error === \"expired_lease\") {\n this.emit(\"credits.lease_expired\", userId, { leaseId });\n }\n raiseLeaseError(result.error, userId, new Decimal(0));\n }\n return result;\n }\n\n /**\n * Advisory affordability check — UI only, non-locking, and potentially stale.\n *\n * Never use this as an admission gate; only ``reserve`` is authoritative.\n */\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n await this.maybeLazyExpire(userId);\n const feature = options?.feature ?? null;\n const { amount: worstCase } = await this.costOf(metricsOrAmount, userId);\n const avail = await this.store.getAvailable(userId);\n let expectedPolicy;\n try {\n expectedPolicy = await this.expectedAdmissionPolicy(\n userId,\n options?.operationType ?? \"usage\",\n options?.billingMode,\n );\n } catch {\n return {\n affordable: false,\n spendable: avail.available,\n worstCase,\n reason: \"policy_unavailable\",\n };\n }\n let allowanceRemaining = new Decimal(0);\n try {\n allowanceRemaining =\n (await this.store.checkAllowance(userId))?.allowanceRemaining ?? new Decimal(0);\n } catch (error) {\n this.logger.debug(\"[CreditsService] allowance fetch failed in canAfford\", {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n const spendable = avail.available.plus(allowanceRemaining).minus(expectedPolicy.floor);\n\n let affordable = true;\n let reason: string | null = null;\n if (feature != null) {\n const check = await this.store.checkFeature(userId, feature);\n if (!check.hasFeature) {\n affordable = false;\n reason = \"feature_not_entitled\";\n }\n }\n if (affordable && spendable.lt(worstCase)) {\n affordable = false;\n reason = \"insufficient_credits\";\n }\n\n return { affordable, spendable, worstCase, reason };\n }\n\n /** Get a user's per-bucket credit balances (credit buckets). Thin pass-through, no event emission. */\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBucketBalances(userId);\n }\n\n /**\n * Get remaining free allowance for the current billing period.\n *\n * Convenience wrapper that routes through the manager so callers never need\n * to reach past it into the raw store. Returns `null` when the subject has no\n * active allowance policy.\n *\n * Window calculation is database-owned and supports the full normalized\n * policy tuple, including timezone and arbitrary interval counts.\n */\n async checkAllowance(userId: string): Promise<AllowanceResult | null> {\n return await this.store.checkAllowance(userId);\n }\n\n /**\n * One-call shortcut wiring reserve → doWork → settle.\n *\n * ``doWork`` runs the operation and returns ``{ result, actual }`` where\n * ``actual`` is the real usage metrics (or amount) to settle. On any exception\n * from ``doWork`` the lease is released and the error re-raised. For long jobs\n * ``doWork`` may call the configured lease TTL. A crash between reserve and settle is\n * covered by the lease TTL (and the store's reaper).\n */\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n const operationKey = options.operationKey ?? `billed:${randomUUID()}`;\n const operation = await this.beginBilledOperation(userId, {\n estimate: options.estimate,\n operationKey,\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n });\n\n let workResult: T;\n let actual: MetricsOrAmount;\n try {\n ({ result: workResult, actual } = await options.doWork());\n } catch (err) {\n await operation.release();\n throw err;\n }\n\n // Never release after work succeeds. A settlement failure may be a\n // transient/unknown-commit outcome and is safe to replay with operationKey.\n const deduction = await retryBursarOperation(() => operation.settle(actual), {\n maxAttempts: options.settlementAttempts,\n });\n return { result: workResult, deduction };\n }\n\n /**\n * Begin a replay-safe billable operation that can span framework callbacks.\n *\n * The operation key is namespaced into distinct reserve and settle keys, so\n * replaying the whole lifecycle cannot acquire a second hold.\n */\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n if (!options.operationKey.trim()) {\n throw new ConfigError(\"operationKey must not be empty\");\n }\n const lease = await this.reserve(userId, options.estimate, {\n operationType: options.operationType,\n billingMode: options.billingMode,\n ttl: options.ttl,\n feature: options.feature,\n metadata: options.metadata,\n idempotencyKey: `${options.operationKey}:reserve`,\n });\n return {\n leaseId: lease.leaseId,\n operationKey: options.operationKey,\n settle: async (actual, metadata) =>\n this.settle(userId, lease.leaseId, actual, {\n idempotencyKey: `${options.operationKey}:settle`,\n feature: options.feature,\n metadata: metadata ?? options.metadata,\n }),\n renew: async (ttl) => {\n await this.renew(userId, lease.leaseId, ttl);\n },\n release: async () => {\n await this.release(userId, lease.leaseId);\n },\n };\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import Decimal from "decimal.js";
2
2
  import type { NormalizedLogger } from "../shared/logger.js";
3
3
  import type { CreditEventType } from "./events.js";
4
- import type { DeductionResult } from "./types/index.js";
4
+ import type { DeductionSuccess } from "./types/index.js";
5
5
  import type { LowBalanceConfig } from "./service-types.js";
6
6
  type EmitCreditEvent = (type: CreditEventType, userId: string, data?: Record<string, unknown>) => void;
7
7
  /**
@@ -18,7 +18,7 @@ export declare class LowBalanceMonitor {
18
18
  private readonly breachedByUser;
19
19
  constructor(config: LowBalanceConfig | null | undefined, emit: EmitCreditEvent, logger: NormalizedLogger);
20
20
  rearmAfterCredit(userId: string, balance: Decimal): void;
21
- afterCharge(userId: string, result: DeductionResult): Promise<void>;
21
+ afterCharge(userId: string, result: DeductionSuccess): Promise<void>;
22
22
  signalCrossing(userId: string, balanceBefore: Decimal, balanceAfter: Decimal): Promise<void>;
23
23
  private fire;
24
24
  }
@@ -1 +1 @@
1
- {"version":3,"file":"low-balance-monitor.d.ts","sourceRoot":"","sources":["../../src/credits/low-balance-monitor.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAGjC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAe,eAAe,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACxD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI3D,KAAK,eAAe,GAAG,CACrB,IAAI,EAAE,eAAe,EACrB,MAA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AAM;gBACN,IAAI;aACL,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8CAA8C,EAAE;gBAChE,MAAM;gBACN,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC9D,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\n\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEvent, CreditEventType } from \"./events.js\";\nimport type { DeductionResult } from \"./types/index.js\";\nimport type { LowBalanceConfig } from \"./service-types.js\";\n\nconst DEFAULT_MAX_TRACKED_USERS = 100_000;\n\ntype EmitCreditEvent = (\n type: CreditEventType,\n userId: string,\n data?: Record<string, unknown>,\n) => void;\n\n/**\n * Owns edge-trigger state for low-balance and overdraft notifications.\n *\n * Keeping this state outside CreditsService makes the event semantics\n * independently testable and keeps the service focused on orchestration.\n */\nexport class LowBalanceMonitor {\n private readonly thresholds: Decimal[] | null;\n private readonly handler: ((event: CreditEvent) => void | Promise<void>) | null;\n private readonly breachedByUser: LRUCache<string, Set<string>>;\n\n constructor(\n config: LowBalanceConfig | null | undefined,\n private readonly emit: EmitCreditEvent,\n private readonly logger: NormalizedLogger,\n ) {\n this.thresholds = config?.thresholds?.length\n ? config.thresholds\n .map((value) => (value instanceof Decimal ? value : new Decimal(value)))\n .sort((left, right) => right.comparedTo(left))\n : null;\n this.handler = config?.onTrigger ?? null;\n const maxTrackedUsers = config?.maxTrackedUsers ?? DEFAULT_MAX_TRACKED_USERS;\n if (!Number.isSafeInteger(maxTrackedUsers) || maxTrackedUsers < 1) {\n throw new RangeError(\"lowBalance.maxTrackedUsers must be a positive safe integer\");\n }\n this.breachedByUser = new LRUCache({ max: maxTrackedUsers });\n }\n\n rearmAfterCredit(userId: string, balance: Decimal): void {\n if (!this.thresholds) return;\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n for (const threshold of this.thresholds) {\n if (balance.gt(threshold)) breached.delete(threshold.toString());\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n }\n\n async afterCharge(userId: string, result: DeductionResult): Promise<void> {\n if (result.idempotent) return;\n if (result.balanceAfter.lt(0)) {\n this.emit(\"credits.overdraft\", userId, {\n balance: result.balanceAfter,\n amount: result.amount,\n });\n }\n await this.signalCrossing(userId, result.balanceAfter.plus(result.amount), result.balanceAfter);\n }\n\n async signalCrossing(\n userId: string,\n balanceBefore: Decimal,\n balanceAfter: Decimal,\n ): Promise<void> {\n if (!this.thresholds) {\n const threshold = new Decimal(0);\n if (balanceBefore.gt(threshold) && balanceAfter.lte(threshold)) {\n await this.fire(userId, balanceAfter, threshold);\n }\n return;\n }\n\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n const newlyCrossed: Decimal[] = [];\n for (const threshold of this.thresholds) {\n if (balanceAfter.lte(threshold)) {\n if (!breached.has(threshold.toString())) {\n breached.add(threshold.toString());\n newlyCrossed.push(threshold);\n }\n } else {\n breached.delete(threshold.toString());\n }\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n if (newlyCrossed.length > 0) {\n const lowest = newlyCrossed.reduce((minimum, threshold) =>\n threshold.lt(minimum) ? threshold : minimum,\n );\n await this.fire(userId, balanceAfter, lowest);\n }\n }\n\n private async fire(userId: string, balance: Decimal, threshold: Decimal): Promise<void> {\n const data = { balance, threshold };\n this.emit(\"credits.low_balance\", userId, data);\n if (!this.handler) return;\n\n try {\n await this.handler({\n type: \"credits.low_balance\",\n timestamp: new Date(),\n userId,\n data,\n });\n } catch (error) {\n this.logger.error(\"[CreditsService] onLowBalance handler failed\", {\n userId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n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,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAC5C,CAAC;YACF,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,CAAC,CAAC;QAChD,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,IAAI,CAAC,MAAc,EAAE,OAAgB,EAAE,SAAkB;QACrE,MAAM,IAAI,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;QACpC,IAAI,CAAC,IAAI,CAAC,qBAAqB,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,IAAI,CAAC,OAAO;YAAE,OAAO;QAE1B,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,OAAO,CAAC;gBACjB,IAAI,EAAE,qBAAqB;gBAC3B,SAAS,EAAE,IAAI,IAAI,EAAE;gBACrB,MAAM;gBACN,IAAI;aACL,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,8CAA8C,EAAE;gBAChE,MAAM;gBACN,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC9D,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { LRUCache } from \"lru-cache\";\n\nimport type { NormalizedLogger } from \"../shared/logger.js\";\nimport type { CreditEvent, CreditEventType } from \"./events.js\";\nimport type { DeductionSuccess } from \"./types/index.js\";\nimport type { LowBalanceConfig } from \"./service-types.js\";\n\nconst DEFAULT_MAX_TRACKED_USERS = 100_000;\n\ntype EmitCreditEvent = (\n type: CreditEventType,\n userId: string,\n data?: Record<string, unknown>,\n) => void;\n\n/**\n * Owns edge-trigger state for low-balance and overdraft notifications.\n *\n * Keeping this state outside CreditsService makes the event semantics\n * independently testable and keeps the service focused on orchestration.\n */\nexport class LowBalanceMonitor {\n private readonly thresholds: Decimal[] | null;\n private readonly handler: ((event: CreditEvent) => void | Promise<void>) | null;\n private readonly breachedByUser: LRUCache<string, Set<string>>;\n\n constructor(\n config: LowBalanceConfig | null | undefined,\n private readonly emit: EmitCreditEvent,\n private readonly logger: NormalizedLogger,\n ) {\n this.thresholds = config?.thresholds?.length\n ? config.thresholds\n .map((value) => (value instanceof Decimal ? value : new Decimal(value)))\n .sort((left, right) => right.comparedTo(left))\n : null;\n this.handler = config?.onTrigger ?? null;\n const maxTrackedUsers = config?.maxTrackedUsers ?? DEFAULT_MAX_TRACKED_USERS;\n if (!Number.isSafeInteger(maxTrackedUsers) || maxTrackedUsers < 1) {\n throw new RangeError(\"lowBalance.maxTrackedUsers must be a positive safe integer\");\n }\n this.breachedByUser = new LRUCache({ max: maxTrackedUsers });\n }\n\n rearmAfterCredit(userId: string, balance: Decimal): void {\n if (!this.thresholds) return;\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n for (const threshold of this.thresholds) {\n if (balance.gt(threshold)) breached.delete(threshold.toString());\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n }\n\n async afterCharge(userId: string, result: DeductionSuccess): Promise<void> {\n if (result.idempotent) return;\n if (result.balanceAfter.lt(0)) {\n this.emit(\"credits.overdraft\", userId, {\n balance: result.balanceAfter,\n amount: result.amount,\n });\n }\n await this.signalCrossing(userId, result.balanceAfter.plus(result.amount), result.balanceAfter);\n }\n\n async signalCrossing(\n userId: string,\n balanceBefore: Decimal,\n balanceAfter: Decimal,\n ): Promise<void> {\n if (!this.thresholds) {\n const threshold = new Decimal(0);\n if (balanceBefore.gt(threshold) && balanceAfter.lte(threshold)) {\n await this.fire(userId, balanceAfter, threshold);\n }\n return;\n }\n\n const breached = this.breachedByUser.get(userId) ?? new Set<string>();\n const newlyCrossed: Decimal[] = [];\n for (const threshold of this.thresholds) {\n if (balanceAfter.lte(threshold)) {\n if (!breached.has(threshold.toString())) {\n breached.add(threshold.toString());\n newlyCrossed.push(threshold);\n }\n } else {\n breached.delete(threshold.toString());\n }\n }\n if (breached.size === 0) {\n this.breachedByUser.delete(userId);\n } else {\n this.breachedByUser.set(userId, breached);\n }\n if (newlyCrossed.length > 0) {\n const lowest = newlyCrossed.reduce((minimum, threshold) =>\n threshold.lt(minimum) ? threshold : minimum,\n );\n await this.fire(userId, balanceAfter, lowest);\n }\n }\n\n private async fire(userId: string, balance: Decimal, threshold: Decimal): Promise<void> {\n const data = { balance, threshold };\n this.emit(\"credits.low_balance\", userId, data);\n if (!this.handler) return;\n\n try {\n await this.handler({\n type: \"credits.low_balance\",\n timestamp: new Date(),\n userId,\n data,\n });\n } catch (error) {\n this.logger.error(\"[CreditsService] onLowBalance handler failed\", {\n userId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"]}