@zonastery/bursar 0.0.2 → 1.0.1

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 (505) hide show
  1. package/README.md +118 -333
  2. package/dist/billing/auto-recharge-port.d.ts +27 -0
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -0
  4. package/dist/billing/auto-recharge-port.js +2 -0
  5. package/dist/billing/auto-recharge-port.js.map +1 -0
  6. package/dist/billing/auto-recharge-service.d.ts +43 -0
  7. package/dist/billing/auto-recharge-service.d.ts.map +1 -0
  8. package/dist/billing/auto-recharge-service.js +218 -0
  9. package/dist/billing/auto-recharge-service.js.map +1 -0
  10. package/dist/billing/billing-service.d.ts +71 -0
  11. package/dist/billing/billing-service.d.ts.map +1 -0
  12. package/dist/billing/billing-service.js +172 -0
  13. package/dist/billing/billing-service.js.map +1 -0
  14. package/dist/billing/billing-store.d.ts +45 -13
  15. package/dist/billing/billing-store.d.ts.map +1 -1
  16. package/dist/billing/billing-store.js.map +1 -1
  17. package/dist/billing/contracts.d.ts +149 -0
  18. package/dist/billing/contracts.d.ts.map +1 -0
  19. package/dist/billing/contracts.js +2 -0
  20. package/dist/billing/contracts.js.map +1 -0
  21. package/dist/billing/event-handlers.d.ts +57 -0
  22. package/dist/billing/event-handlers.d.ts.map +1 -0
  23. package/dist/billing/event-handlers.js +684 -0
  24. package/dist/billing/event-handlers.js.map +1 -0
  25. package/dist/billing/event-processor.d.ts +20 -0
  26. package/dist/billing/event-processor.d.ts.map +1 -0
  27. package/dist/billing/event-processor.js +131 -0
  28. package/dist/billing/event-processor.js.map +1 -0
  29. package/dist/billing/financial-event-handlers.d.ts +26 -0
  30. package/dist/billing/financial-event-handlers.d.ts.map +1 -0
  31. package/dist/billing/financial-event-handlers.js +241 -0
  32. package/dist/billing/financial-event-handlers.js.map +1 -0
  33. package/dist/billing/index.d.ts +9 -5
  34. package/dist/billing/index.d.ts.map +1 -1
  35. package/dist/billing/index.js +4 -4
  36. package/dist/billing/index.js.map +1 -1
  37. package/dist/billing/management.d.ts +59 -0
  38. package/dist/billing/management.d.ts.map +1 -0
  39. package/dist/billing/management.js +113 -0
  40. package/dist/billing/management.js.map +1 -0
  41. package/dist/billing/policy-window.d.ts +24 -0
  42. package/dist/billing/policy-window.d.ts.map +1 -0
  43. package/dist/billing/policy-window.js +88 -0
  44. package/dist/billing/policy-window.js.map +1 -0
  45. package/dist/billing/postgres/repositories/auto-recharge.d.ts +32 -0
  46. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -0
  47. package/dist/billing/postgres/repositories/auto-recharge.js +180 -0
  48. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -0
  49. package/dist/billing/postgres/repositories/customer.d.ts +12 -0
  50. package/dist/billing/postgres/repositories/customer.d.ts.map +1 -0
  51. package/dist/billing/postgres/repositories/customer.js +33 -0
  52. package/dist/billing/postgres/repositories/customer.js.map +1 -0
  53. package/dist/billing/postgres/repositories/dispute.d.ts +7 -0
  54. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -0
  55. package/dist/billing/postgres/repositories/dispute.js +18 -0
  56. package/dist/billing/postgres/repositories/dispute.js.map +1 -0
  57. package/dist/billing/postgres/repositories/event.d.ts +21 -0
  58. package/dist/billing/postgres/repositories/event.d.ts.map +1 -0
  59. package/dist/billing/postgres/repositories/event.js +45 -0
  60. package/dist/billing/postgres/repositories/event.js.map +1 -0
  61. package/dist/billing/postgres/repositories/invoice.d.ts +9 -0
  62. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -0
  63. package/dist/billing/postgres/repositories/invoice.js +36 -0
  64. package/dist/billing/postgres/repositories/invoice.js.map +1 -0
  65. package/dist/billing/postgres/repositories/offer.d.ts +26 -0
  66. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -0
  67. package/dist/billing/postgres/repositories/offer.js +73 -0
  68. package/dist/billing/postgres/repositories/offer.js.map +1 -0
  69. package/dist/billing/postgres/repositories/payment.d.ts +32 -0
  70. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -0
  71. package/dist/billing/postgres/repositories/payment.js +78 -0
  72. package/dist/billing/postgres/repositories/payment.js.map +1 -0
  73. package/dist/billing/postgres/repositories/preferences.d.ts +15 -0
  74. package/dist/billing/postgres/repositories/preferences.d.ts.map +1 -0
  75. package/dist/billing/postgres/repositories/preferences.js +23 -0
  76. package/dist/billing/postgres/repositories/preferences.js.map +1 -0
  77. package/dist/billing/postgres/repositories/refund.d.ts +7 -0
  78. package/dist/billing/postgres/repositories/refund.d.ts.map +1 -0
  79. package/dist/billing/postgres/repositories/refund.js +32 -0
  80. package/dist/billing/postgres/repositories/refund.js.map +1 -0
  81. package/dist/billing/postgres/repositories/subscription.d.ts +46 -0
  82. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -0
  83. package/dist/billing/postgres/repositories/subscription.js +187 -0
  84. package/dist/billing/postgres/repositories/subscription.js.map +1 -0
  85. package/dist/billing/postgres/repositories/topup.d.ts +27 -0
  86. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -0
  87. package/dist/billing/postgres/repositories/topup.js +51 -0
  88. package/dist/billing/postgres/repositories/topup.js.map +1 -0
  89. package/dist/billing/postgres/store.d.ts +89 -0
  90. package/dist/billing/postgres/store.d.ts.map +1 -0
  91. package/dist/billing/postgres/store.js +542 -0
  92. package/dist/billing/postgres/store.js.map +1 -0
  93. package/dist/billing/service-types.d.ts +37 -0
  94. package/dist/billing/service-types.d.ts.map +1 -0
  95. package/dist/billing/service-types.js +2 -0
  96. package/dist/billing/service-types.js.map +1 -0
  97. package/dist/billing/types/auto-recharge.d.ts +56 -0
  98. package/dist/billing/types/auto-recharge.d.ts.map +1 -0
  99. package/dist/billing/types/auto-recharge.js +2 -0
  100. package/dist/billing/types/auto-recharge.js.map +1 -0
  101. package/dist/billing/types/catalog.d.ts +47 -0
  102. package/dist/billing/types/catalog.d.ts.map +1 -0
  103. package/dist/billing/types/catalog.js +2 -0
  104. package/dist/billing/types/catalog.js.map +1 -0
  105. package/dist/billing/types/common.d.ts +16 -0
  106. package/dist/billing/types/common.d.ts.map +1 -0
  107. package/dist/billing/types/common.js +2 -0
  108. package/dist/billing/types/common.js.map +1 -0
  109. package/dist/billing/types/documents.d.ts +39 -0
  110. package/dist/billing/types/documents.d.ts.map +1 -0
  111. package/dist/billing/types/documents.js +2 -0
  112. package/dist/billing/types/documents.js.map +1 -0
  113. package/dist/billing/types/events.d.ts +75 -0
  114. package/dist/billing/types/events.d.ts.map +1 -0
  115. package/dist/billing/types/events.js +38 -0
  116. package/dist/billing/types/events.js.map +1 -0
  117. package/dist/billing/types/index.d.ts +8 -0
  118. package/dist/billing/types/index.d.ts.map +1 -0
  119. package/dist/billing/types/index.js +8 -0
  120. package/dist/billing/types/index.js.map +1 -0
  121. package/dist/billing/types/preferences.d.ts +13 -0
  122. package/dist/billing/types/preferences.d.ts.map +1 -0
  123. package/dist/billing/types/preferences.js +2 -0
  124. package/dist/billing/types/preferences.js.map +1 -0
  125. package/dist/billing/types/subscriptions.d.ts +97 -0
  126. package/dist/billing/types/subscriptions.d.ts.map +1 -0
  127. package/dist/billing/types/subscriptions.js +12 -0
  128. package/dist/billing/types/subscriptions.js.map +1 -0
  129. package/dist/breakdown.d.ts +3 -1
  130. package/dist/breakdown.d.ts.map +1 -1
  131. package/dist/breakdown.js +4 -1
  132. package/dist/breakdown.js.map +1 -1
  133. package/dist/browser.d.ts +8 -0
  134. package/dist/browser.d.ts.map +1 -0
  135. package/dist/browser.js +7 -0
  136. package/dist/browser.js.map +1 -0
  137. package/dist/bursar.d.ts +84 -0
  138. package/dist/bursar.d.ts.map +1 -0
  139. package/dist/bursar.js +137 -0
  140. package/dist/bursar.js.map +1 -0
  141. package/dist/catalog.d.ts +62 -0
  142. package/dist/catalog.d.ts.map +1 -0
  143. package/dist/catalog.js +96 -0
  144. package/dist/catalog.js.map +1 -0
  145. package/dist/commerce/errors.d.ts +68 -0
  146. package/dist/commerce/errors.d.ts.map +1 -0
  147. package/dist/commerce/errors.js +105 -0
  148. package/dist/commerce/errors.js.map +1 -0
  149. package/dist/commerce/index.d.ts +6 -0
  150. package/dist/commerce/index.d.ts.map +1 -0
  151. package/dist/commerce/index.js +6 -0
  152. package/dist/commerce/index.js.map +1 -0
  153. package/dist/commerce/plan-change.d.ts +10 -0
  154. package/dist/commerce/plan-change.d.ts.map +1 -0
  155. package/dist/commerce/plan-change.js +42 -0
  156. package/dist/commerce/plan-change.js.map +1 -0
  157. package/dist/commerce/provider-registry.d.ts +18 -0
  158. package/dist/commerce/provider-registry.d.ts.map +1 -0
  159. package/dist/commerce/provider-registry.js +70 -0
  160. package/dist/commerce/provider-registry.js.map +1 -0
  161. package/dist/commerce/service.d.ts +73 -0
  162. package/dist/commerce/service.d.ts.map +1 -0
  163. package/dist/commerce/service.js +1016 -0
  164. package/dist/commerce/service.js.map +1 -0
  165. package/dist/commerce/types.d.ts +225 -0
  166. package/dist/commerce/types.d.ts.map +1 -0
  167. package/dist/commerce/types.js.map +1 -0
  168. package/dist/config/parse-access.d.ts +6 -0
  169. package/dist/config/parse-access.d.ts.map +1 -0
  170. package/dist/config/parse-access.js +72 -0
  171. package/dist/config/parse-access.js.map +1 -0
  172. package/dist/config/parse-commerce.d.ts +3 -0
  173. package/dist/config/parse-commerce.d.ts.map +1 -0
  174. package/dist/config/parse-commerce.js +236 -0
  175. package/dist/config/parse-commerce.js.map +1 -0
  176. package/dist/config/parse-credits.d.ts +3 -0
  177. package/dist/config/parse-credits.d.ts.map +1 -0
  178. package/dist/config/parse-credits.js +99 -0
  179. package/dist/config/parse-credits.js.map +1 -0
  180. package/dist/config/parse-plans.d.ts +5 -0
  181. package/dist/config/parse-plans.d.ts.map +1 -0
  182. package/dist/config/parse-plans.js +142 -0
  183. package/dist/config/parse-plans.js.map +1 -0
  184. package/dist/config/parse-pricing.d.ts +4 -0
  185. package/dist/config/parse-pricing.d.ts.map +1 -0
  186. package/dist/config/parse-pricing.js +252 -0
  187. package/dist/config/parse-pricing.js.map +1 -0
  188. package/dist/config/parse-utils.d.ts +18 -0
  189. package/dist/config/parse-utils.d.ts.map +1 -0
  190. package/dist/config/parse-utils.js +118 -0
  191. package/dist/config/parse-utils.js.map +1 -0
  192. package/dist/config/types.d.ts +340 -0
  193. package/dist/config/types.d.ts.map +1 -0
  194. package/dist/config/types.js +2 -0
  195. package/dist/config/types.js.map +1 -0
  196. package/dist/config.d.ts +12 -23
  197. package/dist/config.d.ts.map +1 -1
  198. package/dist/config.js +141 -377
  199. package/dist/config.js.map +1 -1
  200. package/dist/{stores → credits}/events.d.ts +6 -6
  201. package/dist/credits/events.d.ts.map +1 -0
  202. package/dist/{stores → credits}/events.js +5 -5
  203. package/dist/credits/events.js.map +1 -0
  204. package/dist/credits/lease-workflow.d.ts +90 -0
  205. package/dist/credits/lease-workflow.d.ts.map +1 -0
  206. package/dist/credits/lease-workflow.js +378 -0
  207. package/dist/credits/lease-workflow.js.map +1 -0
  208. package/dist/credits/low-balance-monitor.d.ts +26 -0
  209. package/dist/credits/low-balance-monitor.d.ts.map +1 -0
  210. package/dist/credits/low-balance-monitor.js +110 -0
  211. package/dist/credits/low-balance-monitor.js.map +1 -0
  212. package/dist/credits/postgres/repositories/analytics.d.ts +81 -0
  213. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -0
  214. package/dist/credits/postgres/repositories/analytics.js +153 -0
  215. package/dist/credits/postgres/repositories/analytics.js.map +1 -0
  216. package/dist/credits/postgres/repositories/balance.d.ts +66 -0
  217. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -0
  218. package/dist/credits/postgres/repositories/balance.js +139 -0
  219. package/dist/credits/postgres/repositories/balance.js.map +1 -0
  220. package/dist/credits/postgres/repositories/bucket.d.ts +25 -0
  221. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -0
  222. package/dist/credits/postgres/repositories/bucket.js +52 -0
  223. package/dist/credits/postgres/repositories/bucket.js.map +1 -0
  224. package/dist/credits/postgres/repositories/deduction.d.ts +64 -0
  225. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -0
  226. package/dist/credits/postgres/repositories/deduction.js +154 -0
  227. package/dist/credits/postgres/repositories/deduction.js.map +1 -0
  228. package/dist/credits/postgres/repositories/lease.d.ts +69 -0
  229. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -0
  230. package/dist/credits/postgres/repositories/lease.js +148 -0
  231. package/dist/credits/postgres/repositories/lease.js.map +1 -0
  232. package/dist/credits/postgres/repositories/plan.d.ts +110 -0
  233. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -0
  234. package/dist/credits/postgres/repositories/plan.js +194 -0
  235. package/dist/credits/postgres/repositories/plan.js.map +1 -0
  236. package/dist/credits/postgres/repositories/pricing.d.ts +28 -0
  237. package/dist/credits/postgres/repositories/pricing.d.ts.map +1 -0
  238. package/dist/credits/postgres/repositories/pricing.js +76 -0
  239. package/dist/credits/postgres/repositories/pricing.js.map +1 -0
  240. package/dist/credits/postgres/repositories/team.d.ts +63 -0
  241. package/dist/credits/postgres/repositories/team.d.ts.map +1 -0
  242. package/dist/credits/postgres/repositories/team.js +120 -0
  243. package/dist/credits/postgres/repositories/team.js.map +1 -0
  244. package/dist/credits/postgres/store.d.ts +89 -0
  245. package/dist/credits/postgres/store.d.ts.map +1 -0
  246. package/dist/credits/postgres/store.js +838 -0
  247. package/dist/credits/postgres/store.js.map +1 -0
  248. package/dist/credits/postgres/value-mappers.d.ts +17 -0
  249. package/dist/credits/postgres/value-mappers.d.ts.map +1 -0
  250. package/dist/credits/postgres/value-mappers.js +102 -0
  251. package/dist/credits/postgres/value-mappers.js.map +1 -0
  252. package/dist/credits/pricing-runtime.d.ts +35 -0
  253. package/dist/credits/pricing-runtime.d.ts.map +1 -0
  254. package/dist/credits/pricing-runtime.js +141 -0
  255. package/dist/credits/pricing-runtime.js.map +1 -0
  256. package/dist/credits/queries.d.ts +33 -0
  257. package/dist/credits/queries.d.ts.map +1 -0
  258. package/dist/credits/queries.js +71 -0
  259. package/dist/credits/queries.js.map +1 -0
  260. package/dist/credits/service-errors.d.ts +4 -0
  261. package/dist/credits/service-errors.d.ts.map +1 -0
  262. package/dist/credits/service-errors.js +57 -0
  263. package/dist/credits/service-errors.js.map +1 -0
  264. package/dist/credits/service-types.d.ts +122 -0
  265. package/dist/credits/service-types.d.ts.map +1 -0
  266. package/dist/credits/service-types.js +2 -0
  267. package/dist/credits/service-types.js.map +1 -0
  268. package/dist/credits/service.d.ts +220 -0
  269. package/dist/credits/service.d.ts.map +1 -0
  270. package/dist/credits/service.js +640 -0
  271. package/dist/credits/service.js.map +1 -0
  272. package/dist/credits/store.d.ts +172 -0
  273. package/dist/credits/store.d.ts.map +1 -0
  274. package/dist/{stores/credit-store.js → credits/store.js} +27 -43
  275. package/dist/credits/store.js.map +1 -0
  276. package/dist/credits/types/account.d.ts +82 -0
  277. package/dist/credits/types/account.d.ts.map +1 -0
  278. package/dist/credits/types/account.js +2 -0
  279. package/dist/credits/types/account.js.map +1 -0
  280. package/dist/credits/types/admission.d.ts +39 -0
  281. package/dist/credits/types/admission.d.ts.map +1 -0
  282. package/dist/credits/types/admission.js +2 -0
  283. package/dist/credits/types/admission.js.map +1 -0
  284. package/dist/credits/types/analytics.d.ts +52 -0
  285. package/dist/credits/types/analytics.d.ts.map +1 -0
  286. package/dist/credits/types/analytics.js +2 -0
  287. package/dist/credits/types/analytics.js.map +1 -0
  288. package/dist/credits/types/catalog.d.ts +71 -0
  289. package/dist/credits/types/catalog.d.ts.map +1 -0
  290. package/dist/credits/types/catalog.js +2 -0
  291. package/dist/credits/types/catalog.js.map +1 -0
  292. package/dist/credits/types/grants.d.ts +24 -0
  293. package/dist/credits/types/grants.d.ts.map +1 -0
  294. package/dist/credits/types/grants.js +2 -0
  295. package/dist/credits/types/grants.js.map +1 -0
  296. package/dist/credits/types/index.d.ts +9 -0
  297. package/dist/credits/types/index.d.ts.map +1 -0
  298. package/dist/credits/types/index.js +2 -0
  299. package/dist/credits/types/index.js.map +1 -0
  300. package/dist/credits/types/ledger.d.ts +87 -0
  301. package/dist/credits/types/ledger.d.ts.map +1 -0
  302. package/dist/credits/types/ledger.js +2 -0
  303. package/dist/credits/types/ledger.js.map +1 -0
  304. package/dist/credits/types/quotas.d.ts +40 -0
  305. package/dist/credits/types/quotas.d.ts.map +1 -0
  306. package/dist/credits/types/quotas.js +2 -0
  307. package/dist/credits/types/quotas.js.map +1 -0
  308. package/dist/credits/types/teams.d.ts +44 -0
  309. package/dist/credits/types/teams.d.ts.map +1 -0
  310. package/dist/credits/types/teams.js +2 -0
  311. package/dist/credits/types/teams.js.map +1 -0
  312. package/dist/engine.d.ts +18 -39
  313. package/dist/engine.d.ts.map +1 -1
  314. package/dist/engine.js +169 -145
  315. package/dist/engine.js.map +1 -1
  316. package/dist/errors.d.ts +133 -25
  317. package/dist/errors.d.ts.map +1 -1
  318. package/dist/errors.js +173 -24
  319. package/dist/errors.js.map +1 -1
  320. package/dist/expr/ast.d.ts +46 -0
  321. package/dist/expr/ast.d.ts.map +1 -0
  322. package/dist/expr/ast.js +18 -0
  323. package/dist/expr/ast.js.map +1 -0
  324. package/dist/expr/evaluator.d.ts +4 -0
  325. package/dist/expr/evaluator.d.ts.map +1 -0
  326. package/dist/expr/evaluator.js +144 -0
  327. package/dist/expr/evaluator.js.map +1 -0
  328. package/dist/expr/language.d.ts +5 -0
  329. package/dist/expr/language.d.ts.map +1 -0
  330. package/dist/expr/language.js +73 -0
  331. package/dist/expr/language.js.map +1 -0
  332. package/dist/expr/parser.d.ts +24 -0
  333. package/dist/expr/parser.d.ts.map +1 -0
  334. package/dist/expr/parser.js +175 -0
  335. package/dist/expr/parser.js.map +1 -0
  336. package/dist/expr/tokenizer.d.ts +7 -0
  337. package/dist/expr/tokenizer.d.ts.map +1 -0
  338. package/dist/expr/tokenizer.js +85 -0
  339. package/dist/expr/tokenizer.js.map +1 -0
  340. package/dist/expr.d.ts +7 -58
  341. package/dist/expr.d.ts.map +1 -1
  342. package/dist/expr.js +41 -640
  343. package/dist/expr.js.map +1 -1
  344. package/dist/generated/pricing-config.schema.json +2792 -0
  345. package/dist/generated/pricing-config.types.d.ts +685 -0
  346. package/dist/generated/pricing-config.types.d.ts.map +1 -0
  347. package/dist/generated/pricing-config.types.js +8 -0
  348. package/dist/generated/pricing-config.types.js.map +1 -0
  349. package/dist/index.d.ts +23 -17
  350. package/dist/index.d.ts.map +1 -1
  351. package/dist/index.js +12 -10
  352. package/dist/index.js.map +1 -1
  353. package/dist/load-pricing-file.d.ts.map +1 -1
  354. package/dist/load-pricing-file.js +8 -4
  355. package/dist/load-pricing-file.js.map +1 -1
  356. package/dist/metrics.d.ts +6 -16
  357. package/dist/metrics.d.ts.map +1 -1
  358. package/dist/metrics.js.map +1 -1
  359. package/dist/node.d.ts +9 -2
  360. package/dist/node.d.ts.map +1 -1
  361. package/dist/node.js +6 -2
  362. package/dist/node.js.map +1 -1
  363. package/dist/providers/_shared.d.ts +9 -0
  364. package/dist/providers/_shared.d.ts.map +1 -0
  365. package/dist/providers/_shared.js +52 -0
  366. package/dist/providers/_shared.js.map +1 -0
  367. package/dist/providers/dodo/client-contract.d.ts +106 -0
  368. package/dist/providers/dodo/client-contract.d.ts.map +1 -0
  369. package/dist/providers/dodo/client-contract.js +2 -0
  370. package/dist/providers/dodo/client-contract.js.map +1 -0
  371. package/dist/providers/dodo/event-mapper.d.ts +5 -3
  372. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  373. package/dist/providers/dodo/event-mapper.js +213 -38
  374. package/dist/providers/dodo/event-mapper.js.map +1 -1
  375. package/dist/providers/dodo/index.d.ts +1 -0
  376. package/dist/providers/dodo/index.d.ts.map +1 -1
  377. package/dist/providers/dodo/index.js.map +1 -1
  378. package/dist/providers/dodo/provider.d.ts +24 -14
  379. package/dist/providers/dodo/provider.d.ts.map +1 -1
  380. package/dist/providers/dodo/provider.js +249 -31
  381. package/dist/providers/dodo/provider.js.map +1 -1
  382. package/dist/providers/index.d.ts +3 -1
  383. package/dist/providers/index.d.ts.map +1 -1
  384. package/dist/providers/index.js +1 -0
  385. package/dist/providers/index.js.map +1 -1
  386. package/dist/providers/mock/index.js.map +1 -1
  387. package/dist/providers/mock/provider.d.ts +14 -10
  388. package/dist/providers/mock/provider.d.ts.map +1 -1
  389. package/dist/providers/mock/provider.js +78 -10
  390. package/dist/providers/mock/provider.js.map +1 -1
  391. package/dist/providers/stripe/event-mapper.d.ts +3 -3
  392. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  393. package/dist/providers/stripe/event-mapper.js +139 -30
  394. package/dist/providers/stripe/event-mapper.js.map +1 -1
  395. package/dist/providers/stripe/index.js.map +1 -1
  396. package/dist/providers/stripe/provider.d.ts +21 -12
  397. package/dist/providers/stripe/provider.d.ts.map +1 -1
  398. package/dist/providers/stripe/provider.js +175 -17
  399. package/dist/providers/stripe/provider.js.map +1 -1
  400. package/dist/providers/types.d.ts +128 -32
  401. package/dist/providers/types.d.ts.map +1 -1
  402. package/dist/providers/types.js +17 -1
  403. package/dist/providers/types.js.map +1 -1
  404. package/dist/retry.d.ts +35 -0
  405. package/dist/retry.d.ts.map +1 -0
  406. package/dist/retry.js +70 -0
  407. package/dist/retry.js.map +1 -0
  408. package/dist/shared/diagnostics.d.ts +7 -0
  409. package/dist/shared/diagnostics.d.ts.map +1 -0
  410. package/dist/shared/diagnostics.js +18 -0
  411. package/dist/shared/diagnostics.js.map +1 -0
  412. package/dist/shared/logger.d.ts +10 -0
  413. package/dist/shared/logger.d.ts.map +1 -0
  414. package/dist/shared/logger.js +15 -0
  415. package/dist/shared/logger.js.map +1 -0
  416. package/dist/shared/postgres-client.d.ts +84 -0
  417. package/dist/shared/postgres-client.d.ts.map +1 -0
  418. package/dist/shared/postgres-client.js +337 -0
  419. package/dist/shared/postgres-client.js.map +1 -0
  420. package/dist/shared/postgres-errors.d.ts +11 -0
  421. package/dist/shared/postgres-errors.d.ts.map +1 -0
  422. package/dist/shared/postgres-errors.js +105 -0
  423. package/dist/shared/postgres-errors.js.map +1 -0
  424. package/dist/shared/postgres-types.d.ts +7 -0
  425. package/dist/shared/postgres-types.d.ts.map +1 -0
  426. package/dist/shared/postgres-types.js +2 -0
  427. package/dist/shared/postgres-types.js.map +1 -0
  428. package/dist/shared/postgres-validation.d.ts +8 -0
  429. package/dist/shared/postgres-validation.d.ts.map +1 -0
  430. package/dist/shared/postgres-validation.js +40 -0
  431. package/dist/shared/postgres-validation.js.map +1 -0
  432. package/dist/storage/adapters/clickhouse.d.ts +61 -0
  433. package/dist/storage/adapters/clickhouse.d.ts.map +1 -0
  434. package/dist/storage/adapters/clickhouse.js +347 -0
  435. package/dist/storage/adapters/clickhouse.js.map +1 -0
  436. package/dist/storage/adapters/s3.d.ts +35 -0
  437. package/dist/storage/adapters/s3.d.ts.map +1 -0
  438. package/dist/storage/adapters/s3.js +100 -0
  439. package/dist/storage/adapters/s3.js.map +1 -0
  440. package/dist/storage/outbox-worker.d.ts +41 -0
  441. package/dist/storage/outbox-worker.d.ts.map +1 -0
  442. package/dist/storage/outbox-worker.js +146 -0
  443. package/dist/storage/outbox-worker.js.map +1 -0
  444. package/dist/storage/ports.d.ts +78 -0
  445. package/dist/storage/ports.d.ts.map +1 -0
  446. package/dist/storage/ports.js +2 -0
  447. package/dist/storage/ports.js.map +1 -0
  448. package/dist/storage/postgres-repository.d.ts +14 -0
  449. package/dist/storage/postgres-repository.d.ts.map +1 -0
  450. package/dist/storage/postgres-repository.js +140 -0
  451. package/dist/storage/postgres-repository.js.map +1 -0
  452. package/dist/storage/runtime.d.ts +77 -0
  453. package/dist/storage/runtime.d.ts.map +1 -0
  454. package/dist/storage/runtime.js +369 -0
  455. package/dist/storage/runtime.js.map +1 -0
  456. package/package.json +43 -21
  457. package/dist/allowance.d.ts +0 -48
  458. package/dist/allowance.d.ts.map +0 -1
  459. package/dist/allowance.js +0 -140
  460. package/dist/allowance.js.map +0 -1
  461. package/dist/billing/billing-manager.d.ts +0 -66
  462. package/dist/billing/billing-manager.d.ts.map +0 -1
  463. package/dist/billing/billing-manager.js +0 -560
  464. package/dist/billing/billing-manager.js.map +0 -1
  465. package/dist/billing/billing-types.d.ts +0 -203
  466. package/dist/billing/billing-types.d.ts.map +0 -1
  467. package/dist/billing/billing-types.js +0 -6
  468. package/dist/billing/billing-types.js.map +0 -1
  469. package/dist/billing/memory-billing-store.d.ts +0 -37
  470. package/dist/billing/memory-billing-store.d.ts.map +0 -1
  471. package/dist/billing/memory-billing-store.js +0 -197
  472. package/dist/billing/memory-billing-store.js.map +0 -1
  473. package/dist/billing/postgres-billing-store.d.ts +0 -35
  474. package/dist/billing/postgres-billing-store.d.ts.map +0 -1
  475. package/dist/billing/postgres-billing-store.js +0 -274
  476. package/dist/billing/postgres-billing-store.js.map +0 -1
  477. package/dist/billing/supabase-billing-store.d.ts +0 -29
  478. package/dist/billing/supabase-billing-store.d.ts.map +0 -1
  479. package/dist/billing/supabase-billing-store.js +0 -250
  480. package/dist/billing/supabase-billing-store.js.map +0 -1
  481. package/dist/manager.d.ts +0 -444
  482. package/dist/manager.d.ts.map +0 -1
  483. package/dist/manager.js +0 -1153
  484. package/dist/manager.js.map +0 -1
  485. package/dist/stores/credit-store.d.ts +0 -198
  486. package/dist/stores/credit-store.d.ts.map +0 -1
  487. package/dist/stores/credit-store.js.map +0 -1
  488. package/dist/stores/events.d.ts.map +0 -1
  489. package/dist/stores/events.js.map +0 -1
  490. package/dist/stores/memory-store.d.ts +0 -187
  491. package/dist/stores/memory-store.d.ts.map +0 -1
  492. package/dist/stores/memory-store.js +0 -1890
  493. package/dist/stores/memory-store.js.map +0 -1
  494. package/dist/stores/postgres-store.d.ts +0 -100
  495. package/dist/stores/postgres-store.d.ts.map +0 -1
  496. package/dist/stores/postgres-store.js +0 -891
  497. package/dist/stores/postgres-store.js.map +0 -1
  498. package/dist/stores/supabase-store.d.ts +0 -87
  499. package/dist/stores/supabase-store.d.ts.map +0 -1
  500. package/dist/stores/supabase-store.js +0 -948
  501. package/dist/stores/supabase-store.js.map +0 -1
  502. package/dist/types.d.ts +0 -463
  503. package/dist/types.d.ts.map +0 -1
  504. package/dist/types.js.map +0 -1
  505. /package/dist/{types.js → commerce/types.js} +0 -0
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Typed event emitter for credit lifecycle events.
3
3
  *
4
- * Events are emitted by ``CreditManager`` after each store operation.
5
- * The emitter is optional — inject into ``CreditManager`` constructor,
4
+ * Events are emitted by ``CreditsService`` after each store operation.
5
+ * The emitter is optional — inject into ``CreditsService`` constructor,
6
6
  * no-op if omitted.
7
7
  *
8
8
  * @example
@@ -11,19 +11,19 @@
11
11
  * emitter.on("credits.deducted", (event) => {
12
12
  * console.log(`Deducted ${event.data?.amount} from ${event.userId}`);
13
13
  * });
14
- * const manager = new CreditManager(store, engine, emitter);
14
+ * const manager = new CreditsService(store, engine, emitter);
15
15
  * ```
16
16
  */
17
17
  /**
18
18
  * All credit lifecycle event types.
19
19
  *
20
20
  * Success events (``credits.deducted``/``credits.refunded``/…) are emitted by
21
- * ``CreditManager`` only after the underlying store operation committed without
21
+ * ``CreditsService`` only after the underlying store operation committed without
22
22
  * an ``error`` (contract §6). 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.cap_reached" | "credits.cap_warning" | "credits.low_balance" | "credits.plan_changed" | "credits.reserved" | "credits.reservation_released" | "credits.lease_expired" | "credits.overdraft" | "credits.floor_breach" | "credits.cycle_renewed" | "credits.feature_limit_reached" | "credits.feature_limit_warning";
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";
27
27
  /**
28
28
  * A typed credit lifecycle event.
29
29
  *
@@ -37,7 +37,7 @@ export interface CreditEvent {
37
37
  userId: string;
38
38
  data?: Record<string, unknown>;
39
39
  }
40
- type EventHandler = (event: CreditEvent) => void;
40
+ type EventHandler = (event: CreditEvent) => void | PromiseLike<void>;
41
41
  /** Typed pub/sub event emitter for credit events. */
42
42
  export declare class CreditEventEmitter {
43
43
  private listeners;
@@ -0,0 +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,qBAAqB,GACrB,sBAAsB,GACtB,kBAAkB,GAClB,8BAA8B,GAC9B,uBAAuB,GACvB,mBAAmB,GACnB,uBAAuB,GACvB,uBAAuB,GACvB,yBAAyB,CAAC;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"}
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Typed event emitter for credit lifecycle events.
3
3
  *
4
- * Events are emitted by ``CreditManager`` after each store operation.
5
- * The emitter is optional — inject into ``CreditManager`` constructor,
4
+ * Events are emitted by ``CreditsService`` after each store operation.
5
+ * The emitter is optional — inject into ``CreditsService`` constructor,
6
6
  * no-op if omitted.
7
7
  *
8
8
  * @example
@@ -11,7 +11,7 @@
11
11
  * emitter.on("credits.deducted", (event) => {
12
12
  * console.log(`Deducted ${event.data?.amount} from ${event.userId}`);
13
13
  * });
14
- * const manager = new CreditManager(store, engine, emitter);
14
+ * const manager = new CreditsService(store, engine, emitter);
15
15
  * ```
16
16
  */
17
17
  /** Typed pub/sub event emitter for credit events. */
@@ -45,8 +45,8 @@ export class CreditEventEmitter {
45
45
  try {
46
46
  const out = handler(event);
47
47
  // Swallow rejections from async handlers so they never become unhandled.
48
- if (out instanceof Promise) {
49
- out.catch((err) => {
48
+ if (out != null && typeof out.then === "function") {
49
+ void Promise.resolve(out).catch((err) => {
50
50
  console.error(`[CreditEventEmitter] async handler error for event ${event.type}:`, err);
51
51
  });
52
52
  }
@@ -0,0 +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,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YAC9B,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,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AyC;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"]}
@@ -0,0 +1,90 @@
1
+ import Decimal from "decimal.js";
2
+ import type { NormalizedLogger } from "../shared/logger.js";
3
+ import type { CreditEventType } from "./events.js";
4
+ import { LowBalanceMonitor } from "./low-balance-monitor.js";
5
+ import { PricingRuntime } from "./pricing-runtime.js";
6
+ import type { CanAffordOptions, BeginBilledOperationOptions, BilledOperation, MetricsOrAmount, PolicyPreset, ReserveOptions, RunBilledOptions, SettleOptions } from "./service-types.js";
7
+ import type { CreditStore } from "./store.js";
8
+ import type { AllowanceResult, BucketBalancesResult, CanAffordResult, DeductionResult, LeaseResult, ReleaseResult } from "./types/index.js";
9
+ export declare class CreditLeaseWorkflow {
10
+ private readonly store;
11
+ private readonly pricing;
12
+ private readonly logger;
13
+ private readonly balanceMonitor;
14
+ private readonly policy;
15
+ private readonly overdraftFloor;
16
+ private readonly defaultMaxConcurrent;
17
+ private readonly defaultTtl;
18
+ private readonly emit;
19
+ private readonly emitQuotaEvents;
20
+ private readonly maybeLazyExpire;
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>);
23
+ private expectedAdmissionPolicy;
24
+ /**
25
+ * Compute the credit cost and model from metrics, or pass a raw amount through.
26
+ *
27
+ * For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact
28
+ * `Decimal`, no truncation); a raw amount is used as-is with no model.
29
+ */
30
+ private costOf;
31
+ /**
32
+ * Atomically acquire a lease — the only admission control (D4).
33
+ *
34
+ * Prices the estimate and delegates entitlement, quota, allowance, credit
35
+ * policy, and concurrency enforcement to the database in one atomic call.
36
+ */
37
+ reserve(userId: string, metricsOrAmount: MetricsOrAmount, options?: ReserveOptions): Promise<LeaseResult>;
38
+ /**
39
+ * Charge the ACTUAL cost against a lease and finalize it (D5).
40
+ *
41
+ * De-clamped: bills the full actual cost even if it exceeds the lease hold
42
+ * (overdraft). Emits ``credits.deducted``, then low-balance and overdraft
43
+ * signals as applicable.
44
+ */
45
+ settle(userId: string, leaseId: string, metricsOrAmount: MetricsOrAmount, options?: SettleOptions): Promise<DeductionResult>;
46
+ /** Release a lease without charging (work failed/aborted) — idempotent (H1). */
47
+ release(userId: string, leaseId: string): Promise<ReleaseResult>;
48
+ /** Extend an active lease's expiry without changing its captured policy. */
49
+ renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseResult>;
50
+ /**
51
+ * Advisory affordability check — UI only, non-locking, may be stale (D4/H3).
52
+ *
53
+ * Never use this as an admission gate; only ``reserve`` is authoritative.
54
+ */
55
+ canAfford(userId: string, metricsOrAmount: MetricsOrAmount, options?: CanAffordOptions): Promise<CanAffordResult>;
56
+ /** Get a user's per-bucket credit balances (credit buckets). Thin pass-through, no event emission. */
57
+ getBucketBalances(userId: string): Promise<BucketBalancesResult>;
58
+ /**
59
+ * Get remaining free allowance for the current billing period.
60
+ *
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).
64
+ *
65
+ * Window calculation is database-owned and supports the full normalized
66
+ * policy tuple, including timezone and arbitrary interval counts.
67
+ */
68
+ checkAllowance(userId: string): Promise<AllowanceResult>;
69
+ /**
70
+ * One-call shortcut wiring reserve → doWork → settle (interface plan §4).
71
+ *
72
+ * ``doWork`` runs the operation and returns ``{ result, actual }`` where
73
+ * ``actual`` is the real usage metrics (or amount) to settle. On any exception
74
+ * from ``doWork`` the lease is released and the error re-raised. For long jobs
75
+ * ``doWork`` may call the configured lease TTL. A crash between reserve and settle is
76
+ * covered by the lease TTL (and the store's reaper).
77
+ */
78
+ runBilled<T>(userId: string, options: RunBilledOptions<T>): Promise<{
79
+ result: T;
80
+ deduction: DeductionResult;
81
+ }>;
82
+ /**
83
+ * Begin a replay-safe billable operation that can span framework callbacks.
84
+ *
85
+ * The operation key is namespaced into distinct reserve and settle keys, so
86
+ * replaying the whole lifecycle cannot acquire a second hold.
87
+ */
88
+ beginBilledOperation(userId: string, options: BeginBilledOperationOptions): Promise<BilledOperation>;
89
+ }
90
+ //# sourceMappingURL=lease-workflow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lease-workflow.d.ts","sourceRoot":"","sources":["../../src/credits/lease-workflow.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAIjC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM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AQG;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"}
@@ -0,0 +1,378 @@
1
+ import Decimal from "decimal.js";
2
+ import { randomUUID } from "node:crypto";
3
+ import { ConfigError } from "../errors.js";
4
+ import { retryBursarOperation } from "../retry.js";
5
+ import { LowBalanceMonitor } from "./low-balance-monitor.js";
6
+ import { isAmount, PricingRuntime } from "./pricing-runtime.js";
7
+ import { raiseLeaseError } from "./service-errors.js";
8
+ export class CreditLeaseWorkflow {
9
+ store;
10
+ pricing;
11
+ logger;
12
+ balanceMonitor;
13
+ policy;
14
+ overdraftFloor;
15
+ defaultMaxConcurrent;
16
+ defaultTtl;
17
+ emit;
18
+ emitQuotaEvents;
19
+ maybeLazyExpire;
20
+ afterDeduction;
21
+ constructor(store, pricing, logger, balanceMonitor, policy, overdraftFloor, defaultMaxConcurrent, defaultTtl, emit, emitQuotaEvents, maybeLazyExpire, afterDeduction) {
22
+ this.store = store;
23
+ this.pricing = pricing;
24
+ this.logger = logger;
25
+ this.balanceMonitor = balanceMonitor;
26
+ this.policy = policy;
27
+ this.overdraftFloor = overdraftFloor;
28
+ this.defaultMaxConcurrent = defaultMaxConcurrent;
29
+ this.defaultTtl = defaultTtl;
30
+ this.emit = emit;
31
+ this.emitQuotaEvents = emitQuotaEvents;
32
+ this.maybeLazyExpire = maybeLazyExpire;
33
+ this.afterDeduction = afterDeduction;
34
+ }
35
+ async expectedAdmissionPolicy(userId, operationType, billingModeOverride) {
36
+ const plan = await this.store.getUserPlan(userId);
37
+ const creditPolicy = plan.planId == null ? null : plan.creditPolicy;
38
+ const planMode = plan.planId == null
39
+ ? this.policy === "overdraft"
40
+ ? "overdraft"
41
+ : "strict"
42
+ : creditPolicy?.type === "credit_line"
43
+ ? "overdraft"
44
+ : "strict";
45
+ const operationAdmission = plan.planId == null ? null : (plan.admission?.operations[operationType] ?? null);
46
+ const billingMode = billingModeOverride ?? planMode;
47
+ const floor = billingMode === "overdraft"
48
+ ? (creditPolicy?.creditLimit?.negated() ?? this.overdraftFloor ?? new Decimal(0))
49
+ : new Decimal(0);
50
+ return {
51
+ billingMode,
52
+ floor,
53
+ maxConcurrent: plan.planId == null
54
+ ? this.defaultMaxConcurrent
55
+ : (operationAdmission?.maxInFlight ?? plan.admission?.maxInFlight ?? null),
56
+ };
57
+ }
58
+ /**
59
+ * Compute the credit cost and model from metrics, or pass a raw amount through.
60
+ *
61
+ * For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact
62
+ * `Decimal`, no truncation); a raw amount is used as-is with no model.
63
+ */
64
+ async costOf(metricsOrAmount, userId, leaseId) {
65
+ return this.pricing.costOf(metricsOrAmount, userId, leaseId);
66
+ }
67
+ /**
68
+ * Atomically acquire a lease — the only admission control (D4).
69
+ *
70
+ * Prices the estimate and delegates entitlement, quota, allowance, credit
71
+ * policy, and concurrency enforcement to the database in one atomic call.
72
+ */
73
+ async reserve(userId, metricsOrAmount, options) {
74
+ await this.maybeLazyExpire(userId);
75
+ this.logger.debug("[CreditsService] reserve", {
76
+ feature: options?.feature,
77
+ operationType: options?.operationType,
78
+ });
79
+ const operationType = options?.operationType ?? (isAmount(metricsOrAmount) ? "usage" : metricsOrAmount.operation);
80
+ const expectedPolicy = await this.expectedAdmissionPolicy(userId, operationType, options?.billingMode);
81
+ const priced = await this.costOf(metricsOrAmount, userId);
82
+ const amount = priced.amount;
83
+ const model = priced.model ?? options?.model ?? null;
84
+ const ttlSeconds = options?.ttl != null ? options.ttl : this.defaultTtl;
85
+ const feature = options?.feature ?? null;
86
+ const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };
87
+ const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };
88
+ const region = typeof dimensions.region === "string" ? dimensions.region : null;
89
+ const leaseIdempotencyKey = options?.idempotencyKey ?? `lease:${randomUUID()}`;
90
+ const result = await this.store.createLease(userId, amount, operationType, {
91
+ idempotencyKey: leaseIdempotencyKey,
92
+ billingMode: expectedPolicy.billingMode,
93
+ floor: expectedPolicy.floor,
94
+ maxConcurrent: expectedPolicy.maxConcurrent,
95
+ ttlSeconds,
96
+ model,
97
+ metadata: options?.metadata,
98
+ feature,
99
+ region,
100
+ measures,
101
+ dimensions,
102
+ });
103
+ if (result.error) {
104
+ if (result.error === "quota_exceeded") {
105
+ await this.emitQuotaEvents(userId, leaseIdempotencyKey);
106
+ }
107
+ this.emit("credits.deduct_failed", userId, {
108
+ error: result.error,
109
+ amount,
110
+ stage: "reserve",
111
+ operationType,
112
+ });
113
+ raiseLeaseError(result.error, userId, amount);
114
+ }
115
+ this.logger.info("[CreditsService] reservation acquired", {
116
+ leaseId: result.leaseId,
117
+ amount: result.amount,
118
+ minimumBalance: result.minimumBalance,
119
+ });
120
+ this.emit("credits.reserved", userId, {
121
+ leaseId: result.leaseId,
122
+ amount: result.amount,
123
+ available: result.available,
124
+ minimumBalance: result.minimumBalance,
125
+ operationType,
126
+ expiresAt: result.expiresAt,
127
+ });
128
+ await this.emitQuotaEvents(userId, leaseIdempotencyKey);
129
+ return result;
130
+ }
131
+ /**
132
+ * Charge the ACTUAL cost against a lease and finalize it (D5).
133
+ *
134
+ * De-clamped: bills the full actual cost even if it exceeds the lease hold
135
+ * (overdraft). Emits ``credits.deducted``, then low-balance and overdraft
136
+ * signals as applicable.
137
+ */
138
+ async settle(userId, leaseId, metricsOrAmount, options) {
139
+ await this.maybeLazyExpire(userId);
140
+ this.logger.debug("[CreditsService] settle", { leaseId });
141
+ const idempotencyKey = options?.idempotencyKey ?? `lease:${leaseId}:settle`;
142
+ const feature = options?.feature ?? null;
143
+ const { amount, model } = await this.costOf(metricsOrAmount, userId, leaseId);
144
+ const measures = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.measures ?? {}) };
145
+ const dimensions = isAmount(metricsOrAmount) ? {} : { ...(metricsOrAmount.dimensions ?? {}) };
146
+ const region = typeof dimensions.region === "string" ? dimensions.region : null;
147
+ // Build ledger metadata: caller fields first, system fields last (M7).
148
+ const txMeta = {};
149
+ if (isAmount(metricsOrAmount)) {
150
+ if (options?.metadata) {
151
+ for (const [k, v] of Object.entries(options.metadata)) {
152
+ if (v != null)
153
+ txMeta[k] = v;
154
+ }
155
+ }
156
+ if (idempotencyKey)
157
+ txMeta["idempotencyKey"] = idempotencyKey;
158
+ }
159
+ else {
160
+ if (options?.metadata) {
161
+ for (const [k, v] of Object.entries(options.metadata)) {
162
+ if (v != null)
163
+ txMeta[k] = v;
164
+ }
165
+ }
166
+ txMeta["operation"] = metricsOrAmount.operation;
167
+ txMeta["measures"] = { ...(metricsOrAmount.measures ?? {}) };
168
+ txMeta["dimensions"] = { ...(metricsOrAmount.dimensions ?? {}) };
169
+ txMeta["breakdownTotal"] = amount.toString();
170
+ if (idempotencyKey)
171
+ txMeta["idempotencyKey"] = idempotencyKey;
172
+ }
173
+ const result = await this.store.settleLease(userId, leaseId, amount, {
174
+ idempotencyKey,
175
+ feature,
176
+ model,
177
+ region,
178
+ measures,
179
+ dimensions,
180
+ metadata: txMeta,
181
+ });
182
+ if (result.error) {
183
+ this.emit("credits.deduct_failed", userId, {
184
+ error: result.error,
185
+ amount,
186
+ stage: "settle",
187
+ leaseId,
188
+ });
189
+ if (result.error === "expired_lease") {
190
+ this.emit("credits.lease_expired", userId, { leaseId });
191
+ }
192
+ raiseLeaseError(result.error, userId, amount);
193
+ }
194
+ this.logger.info("[CreditsService] settled", {
195
+ leaseId,
196
+ amount: result.amount,
197
+ balanceAfter: result.balanceAfter,
198
+ idempotent: result.idempotent,
199
+ });
200
+ this.emit("credits.deducted", userId, {
201
+ entryId: result.entryId,
202
+ amount: result.amount,
203
+ allowanceConsumed: result.allowanceConsumed,
204
+ balanceAfter: result.balanceAfter,
205
+ model,
206
+ leaseId,
207
+ idempotent: result.idempotent,
208
+ });
209
+ await this.balanceMonitor.afterCharge(userId, result);
210
+ if (!result.idempotent) {
211
+ await this.emitQuotaEvents(userId, idempotencyKey);
212
+ await this.afterDeduction(userId, result);
213
+ }
214
+ return result;
215
+ }
216
+ /** Release a lease without charging (work failed/aborted) — idempotent (H1). */
217
+ async release(userId, leaseId) {
218
+ this.logger.debug("[CreditsService] release", { leaseId });
219
+ const result = await this.store.releaseLease(userId, leaseId);
220
+ if (result.released) {
221
+ this.logger.info("[CreditsService] lease released", { leaseId, reason: result.reason });
222
+ this.emit("credits.reservation_released", userId, {
223
+ leaseId,
224
+ reason: result.reason,
225
+ });
226
+ }
227
+ return result;
228
+ }
229
+ /** Extend an active lease's expiry without changing its captured policy. */
230
+ async renew(userId, leaseId, ttl) {
231
+ const ttlSeconds = ttl ?? this.defaultTtl;
232
+ this.logger.debug("[CreditsService] renew", { leaseId, ttlSeconds });
233
+ const result = await this.store.renewLease(userId, leaseId, ttlSeconds);
234
+ if (result.error) {
235
+ if (result.error === "expired_lease") {
236
+ this.emit("credits.lease_expired", userId, { leaseId });
237
+ }
238
+ raiseLeaseError(result.error, userId, new Decimal(0));
239
+ }
240
+ return result;
241
+ }
242
+ /**
243
+ * Advisory affordability check — UI only, non-locking, may be stale (D4/H3).
244
+ *
245
+ * Never use this as an admission gate; only ``reserve`` is authoritative.
246
+ */
247
+ async canAfford(userId, metricsOrAmount, options) {
248
+ await this.maybeLazyExpire(userId);
249
+ const feature = options?.feature ?? null;
250
+ const { amount: worstCase } = await this.costOf(metricsOrAmount, userId);
251
+ const avail = await this.store.getAvailable(userId);
252
+ let expectedPolicy;
253
+ try {
254
+ expectedPolicy = await this.expectedAdmissionPolicy(userId, options?.operationType ?? "usage", options?.billingMode);
255
+ }
256
+ catch {
257
+ return {
258
+ affordable: false,
259
+ spendable: avail.available,
260
+ worstCase,
261
+ reason: "policy_unavailable",
262
+ };
263
+ }
264
+ let allowanceRemaining = new Decimal(0);
265
+ try {
266
+ allowanceRemaining = (await this.store.checkAllowance(userId)).allowanceRemaining;
267
+ }
268
+ catch (error) {
269
+ this.logger.debug("[CreditsService] allowance fetch failed in canAfford", {
270
+ error: error instanceof Error ? error.message : String(error),
271
+ });
272
+ }
273
+ const spendable = avail.available.plus(allowanceRemaining).minus(expectedPolicy.floor);
274
+ let affordable = true;
275
+ let reason = null;
276
+ if (feature != null) {
277
+ const check = await this.store.checkFeature(userId, feature);
278
+ if (!check.hasFeature) {
279
+ affordable = false;
280
+ reason = "feature_not_entitled";
281
+ }
282
+ }
283
+ if (affordable && spendable.lt(worstCase)) {
284
+ affordable = false;
285
+ reason = "insufficient_credits";
286
+ }
287
+ return { affordable, spendable, worstCase, reason };
288
+ }
289
+ /** Get a user's per-bucket credit balances (credit buckets). Thin pass-through, no event emission. */
290
+ async getBucketBalances(userId) {
291
+ await this.maybeLazyExpire(userId);
292
+ return await this.store.getBucketBalances(userId);
293
+ }
294
+ /**
295
+ * Get remaining free allowance for the current billing period.
296
+ *
297
+ * 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).
300
+ *
301
+ * Window calculation is database-owned and supports the full normalized
302
+ * policy tuple, including timezone and arbitrary interval counts.
303
+ */
304
+ async checkAllowance(userId) {
305
+ return await this.store.checkAllowance(userId);
306
+ }
307
+ /**
308
+ * One-call shortcut wiring reserve → doWork → settle (interface plan §4).
309
+ *
310
+ * ``doWork`` runs the operation and returns ``{ result, actual }`` where
311
+ * ``actual`` is the real usage metrics (or amount) to settle. On any exception
312
+ * from ``doWork`` the lease is released and the error re-raised. For long jobs
313
+ * ``doWork`` may call the configured lease TTL. A crash between reserve and settle is
314
+ * covered by the lease TTL (and the store's reaper).
315
+ */
316
+ async runBilled(userId, options) {
317
+ const operationKey = options.operationKey ?? `billed:${randomUUID()}`;
318
+ const operation = await this.beginBilledOperation(userId, {
319
+ estimate: options.estimate,
320
+ operationKey,
321
+ operationType: options.operationType,
322
+ billingMode: options.billingMode,
323
+ ttl: options.ttl,
324
+ feature: options.feature,
325
+ metadata: options.metadata,
326
+ });
327
+ let workResult;
328
+ let actual;
329
+ try {
330
+ ({ result: workResult, actual } = await options.doWork());
331
+ }
332
+ catch (err) {
333
+ await operation.release();
334
+ throw err;
335
+ }
336
+ // Never release after work succeeds. A settlement failure may be a
337
+ // transient/unknown-commit outcome and is safe to replay with operationKey.
338
+ const deduction = await retryBursarOperation(() => operation.settle(actual), {
339
+ maxAttempts: options.settlementAttempts,
340
+ });
341
+ return { result: workResult, deduction };
342
+ }
343
+ /**
344
+ * Begin a replay-safe billable operation that can span framework callbacks.
345
+ *
346
+ * The operation key is namespaced into distinct reserve and settle keys, so
347
+ * replaying the whole lifecycle cannot acquire a second hold.
348
+ */
349
+ async beginBilledOperation(userId, options) {
350
+ if (!options.operationKey.trim()) {
351
+ throw new ConfigError("operationKey must not be empty");
352
+ }
353
+ const lease = await this.reserve(userId, options.estimate, {
354
+ operationType: options.operationType,
355
+ billingMode: options.billingMode,
356
+ ttl: options.ttl,
357
+ feature: options.feature,
358
+ metadata: options.metadata,
359
+ idempotencyKey: `${options.operationKey}:reserve`,
360
+ });
361
+ return {
362
+ leaseId: lease.leaseId,
363
+ operationKey: options.operationKey,
364
+ settle: async (actual, metadata) => this.settle(userId, lease.leaseId, actual, {
365
+ idempotencyKey: `${options.operationKey}:settle`,
366
+ feature: options.feature,
367
+ metadata: metadata ?? options.metadata,
368
+ }),
369
+ renew: async (ttl) => {
370
+ await this.renew(userId, lease.leaseId, ttl);
371
+ },
372
+ release: async () => {
373
+ await this.release(userId, lease.leaseId);
374
+ },
375
+ };
376
+ }
377
+ }
378
+ //# sourceMappingURL=lease-workflow.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lease-work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QAAQ,EAAE;YACzD,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, 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"]}