@zonastery/bursar 2.1.1 → 2.2.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 (334) hide show
  1. package/README.md +20 -3
  2. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  3. package/dist/billing/auto-recharge-service.js +6 -4
  4. package/dist/billing/auto-recharge-service.js.map +1 -1
  5. package/dist/billing/billing-service.d.ts +19 -3
  6. package/dist/billing/billing-service.d.ts.map +1 -1
  7. package/dist/billing/billing-service.js +34 -5
  8. package/dist/billing/billing-service.js.map +1 -1
  9. package/dist/billing/billing-store.d.ts +12 -6
  10. package/dist/billing/billing-store.d.ts.map +1 -1
  11. package/dist/billing/billing-store.js +2 -0
  12. package/dist/billing/billing-store.js.map +1 -1
  13. package/dist/billing/contracts.d.ts +20 -3
  14. package/dist/billing/contracts.d.ts.map +1 -1
  15. package/dist/billing/contracts.js.map +1 -1
  16. package/dist/billing/event-handlers.d.ts +1 -0
  17. package/dist/billing/event-handlers.d.ts.map +1 -1
  18. package/dist/billing/event-handlers.js +40 -13
  19. package/dist/billing/event-handlers.js.map +1 -1
  20. package/dist/billing/event-processor.d.ts +2 -1
  21. package/dist/billing/event-processor.d.ts.map +1 -1
  22. package/dist/billing/event-processor.js +82 -16
  23. package/dist/billing/event-processor.js.map +1 -1
  24. package/dist/billing/financial-event-handlers.d.ts +2 -0
  25. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  26. package/dist/billing/financial-event-handlers.js +160 -48
  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 +6 -3
  32. package/dist/billing/management.d.ts.map +1 -1
  33. package/dist/billing/management.js +5 -2
  34. package/dist/billing/management.js.map +1 -1
  35. package/dist/billing/postgres/repositories/auto-recharge.d.ts +3 -1
  36. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.js +23 -7
  38. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  39. package/dist/billing/postgres/repositories/invoice.d.ts +3 -2
  40. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  41. package/dist/billing/postgres/repositories/invoice.js +33 -3
  42. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  43. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  44. package/dist/billing/postgres/repositories/offer.js +2 -1
  45. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  46. package/dist/billing/postgres/repositories/payment.d.ts +6 -1
  47. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  48. package/dist/billing/postgres/repositories/payment.js +25 -17
  49. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  50. package/dist/billing/postgres/repositories/subscription-change.d.ts +1 -0
  51. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  52. package/dist/billing/postgres/repositories/subscription-change.js +24 -4
  53. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  54. package/dist/billing/postgres/repositories/subscription.d.ts +1 -0
  55. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  56. package/dist/billing/postgres/repositories/subscription.js +40 -43
  57. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  58. package/dist/billing/postgres/repositories/topup.d.ts +6 -1
  59. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  60. package/dist/billing/postgres/repositories/topup.js +9 -5
  61. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  62. package/dist/billing/postgres/store.d.ts +24 -31
  63. package/dist/billing/postgres/store.d.ts.map +1 -1
  64. package/dist/billing/postgres/store.js +110 -113
  65. package/dist/billing/postgres/store.js.map +1 -1
  66. package/dist/billing/types/catalog.d.ts +1 -0
  67. package/dist/billing/types/catalog.d.ts.map +1 -1
  68. package/dist/billing/types/catalog.js.map +1 -1
  69. package/dist/billing/types/documents.d.ts +15 -1
  70. package/dist/billing/types/documents.d.ts.map +1 -1
  71. package/dist/billing/types/documents.js.map +1 -1
  72. package/dist/billing/types/events.d.ts +2 -0
  73. package/dist/billing/types/events.d.ts.map +1 -1
  74. package/dist/billing/types/events.js +15 -0
  75. package/dist/billing/types/events.js.map +1 -1
  76. package/dist/billing/types/subscriptions.d.ts +10 -0
  77. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  78. package/dist/billing/types/subscriptions.js.map +1 -1
  79. package/dist/breakdown.d.ts +2 -24
  80. package/dist/breakdown.d.ts.map +1 -1
  81. package/dist/breakdown.js +1 -29
  82. package/dist/breakdown.js.map +1 -1
  83. package/dist/bursar.d.ts +5 -17
  84. package/dist/bursar.d.ts.map +1 -1
  85. package/dist/bursar.js +26 -44
  86. package/dist/bursar.js.map +1 -1
  87. package/dist/cli.js +0 -6
  88. package/dist/cli.js.map +1 -1
  89. package/dist/commerce/service.d.ts +1 -0
  90. package/dist/commerce/service.d.ts.map +1 -1
  91. package/dist/commerce/service.js +162 -38
  92. package/dist/commerce/service.js.map +1 -1
  93. package/dist/commerce/types.d.ts +2 -0
  94. package/dist/commerce/types.d.ts.map +1 -1
  95. package/dist/commerce/types.js.map +1 -1
  96. package/dist/config/normalize.d.ts +3 -1
  97. package/dist/config/normalize.d.ts.map +1 -1
  98. package/dist/config/normalize.js +12 -5
  99. package/dist/config/normalize.js.map +1 -1
  100. package/dist/config/parse-access.d.ts.map +1 -1
  101. package/dist/config/parse-access.js +4 -1
  102. package/dist/config/parse-access.js.map +1 -1
  103. package/dist/config/parse-commerce.d.ts.map +1 -1
  104. package/dist/config/parse-commerce.js +32 -17
  105. package/dist/config/parse-commerce.js.map +1 -1
  106. package/dist/config/parse-credits.d.ts.map +1 -1
  107. package/dist/config/parse-credits.js +5 -5
  108. package/dist/config/parse-credits.js.map +1 -1
  109. package/dist/config/parse-plans.d.ts.map +1 -1
  110. package/dist/config/parse-plans.js +13 -9
  111. package/dist/config/parse-plans.js.map +1 -1
  112. package/dist/config/parse-pricing.d.ts.map +1 -1
  113. package/dist/config/parse-pricing.js +7 -5
  114. package/dist/config/parse-pricing.js.map +1 -1
  115. package/dist/config/parse-utils.d.ts +2 -0
  116. package/dist/config/parse-utils.d.ts.map +1 -1
  117. package/dist/config/parse-utils.js +11 -1
  118. package/dist/config/parse-utils.js.map +1 -1
  119. package/dist/config.d.ts +2 -2
  120. package/dist/config.d.ts.map +1 -1
  121. package/dist/config.js +94 -86
  122. package/dist/config.js.map +1 -1
  123. package/dist/credits/amount.d.ts.map +1 -1
  124. package/dist/credits/amount.js +5 -4
  125. package/dist/credits/amount.js.map +1 -1
  126. package/dist/credits/catalog-runtime.d.ts +15 -2
  127. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  128. package/dist/credits/catalog-runtime.js +74 -18
  129. package/dist/credits/catalog-runtime.js.map +1 -1
  130. package/dist/credits/lease-workflow.d.ts +3 -1
  131. package/dist/credits/lease-workflow.d.ts.map +1 -1
  132. package/dist/credits/lease-workflow.js +47 -38
  133. package/dist/credits/lease-workflow.js.map +1 -1
  134. package/dist/credits/low-balance-monitor.d.ts +2 -7
  135. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  136. package/dist/credits/low-balance-monitor.js +6 -57
  137. package/dist/credits/low-balance-monitor.js.map +1 -1
  138. package/dist/credits/postgres/repositories/analytics.d.ts +3 -3
  139. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  140. package/dist/credits/postgres/repositories/analytics.js +25 -7
  141. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  142. package/dist/credits/postgres/repositories/balance.d.ts +28 -0
  143. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  144. package/dist/credits/postgres/repositories/balance.js +33 -14
  145. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  146. package/dist/credits/postgres/repositories/bucket.d.ts.map +1 -1
  147. package/dist/credits/postgres/repositories/bucket.js +2 -2
  148. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  149. package/dist/credits/postgres/repositories/catalog.d.ts +2 -2
  150. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  151. package/dist/credits/postgres/repositories/catalog.js +2 -12
  152. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  153. package/dist/credits/postgres/repositories/deduction.d.ts +2 -0
  154. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  155. package/dist/credits/postgres/repositories/deduction.js +9 -2
  156. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  157. package/dist/credits/postgres/repositories/lease.d.ts +3 -0
  158. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  159. package/dist/credits/postgres/repositories/lease.js +46 -12
  160. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  161. package/dist/credits/postgres/repositories/plan.d.ts +1 -1
  162. package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
  163. package/dist/credits/postgres/repositories/plan.js +4 -1
  164. package/dist/credits/postgres/repositories/plan.js.map +1 -1
  165. package/dist/credits/postgres/repositories/team.d.ts +1 -1
  166. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  167. package/dist/credits/postgres/repositories/team.js +9 -5
  168. package/dist/credits/postgres/repositories/team.js.map +1 -1
  169. package/dist/credits/postgres/store.d.ts +29 -20
  170. package/dist/credits/postgres/store.d.ts.map +1 -1
  171. package/dist/credits/postgres/store.js +329 -250
  172. package/dist/credits/postgres/store.js.map +1 -1
  173. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  174. package/dist/credits/postgres/value-mappers.js +4 -4
  175. package/dist/credits/postgres/value-mappers.js.map +1 -1
  176. package/dist/credits/rated-wire.d.ts +7 -0
  177. package/dist/credits/rated-wire.d.ts.map +1 -0
  178. package/dist/credits/rated-wire.js +70 -0
  179. package/dist/credits/rated-wire.js.map +1 -0
  180. package/dist/credits/service-errors.d.ts.map +1 -1
  181. package/dist/credits/service-errors.js +8 -1
  182. package/dist/credits/service-errors.js.map +1 -1
  183. package/dist/credits/service-types.d.ts +5 -7
  184. package/dist/credits/service-types.d.ts.map +1 -1
  185. package/dist/credits/service-types.js.map +1 -1
  186. package/dist/credits/service.d.ts +11 -9
  187. package/dist/credits/service.d.ts.map +1 -1
  188. package/dist/credits/service.js +156 -138
  189. package/dist/credits/service.js.map +1 -1
  190. package/dist/credits/store.d.ts +11 -3
  191. package/dist/credits/store.d.ts.map +1 -1
  192. package/dist/credits/store.js +9 -0
  193. package/dist/credits/store.js.map +1 -1
  194. package/dist/credits/types/account.d.ts +9 -1
  195. package/dist/credits/types/account.d.ts.map +1 -1
  196. package/dist/credits/types/account.js.map +1 -1
  197. package/dist/credits/types/admission.d.ts +1 -0
  198. package/dist/credits/types/admission.d.ts.map +1 -1
  199. package/dist/credits/types/admission.js.map +1 -1
  200. package/dist/credits/types/grants.d.ts +12 -0
  201. package/dist/credits/types/grants.d.ts.map +1 -1
  202. package/dist/credits/types/grants.js.map +1 -1
  203. package/dist/credits/types/ledger.d.ts +13 -0
  204. package/dist/credits/types/ledger.d.ts.map +1 -1
  205. package/dist/credits/types/ledger.js.map +1 -1
  206. package/dist/credits/types/quotas.d.ts +2 -1
  207. package/dist/credits/types/quotas.d.ts.map +1 -1
  208. package/dist/credits/types/quotas.js.map +1 -1
  209. package/dist/engine.d.ts.map +1 -1
  210. package/dist/engine.js +51 -34
  211. package/dist/engine.js.map +1 -1
  212. package/dist/errors.d.ts +12 -1
  213. package/dist/errors.d.ts.map +1 -1
  214. package/dist/errors.js +13 -0
  215. package/dist/errors.js.map +1 -1
  216. package/dist/expr/evaluator.d.ts.map +1 -1
  217. package/dist/expr/evaluator.js +29 -9
  218. package/dist/expr/evaluator.js.map +1 -1
  219. package/dist/expr/language.js +1 -1
  220. package/dist/expr/language.js.map +1 -1
  221. package/dist/expr.d.ts.map +1 -1
  222. package/dist/expr.js +5 -6
  223. package/dist/expr.js.map +1 -1
  224. package/dist/generated/pricing-config.schema.json +102 -202
  225. package/dist/generated/pricing-config.types.d.ts +7 -1
  226. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  227. package/dist/generated/pricing-config.types.js.map +1 -1
  228. package/dist/index.d.ts +6 -5
  229. package/dist/index.d.ts.map +1 -1
  230. package/dist/index.js +3 -2
  231. package/dist/index.js.map +1 -1
  232. package/dist/load-config-file.d.ts.map +1 -1
  233. package/dist/load-config-file.js +38 -12
  234. package/dist/load-config-file.js.map +1 -1
  235. package/dist/metrics.d.ts +1 -1
  236. package/dist/metrics.d.ts.map +1 -1
  237. package/dist/metrics.js.map +1 -1
  238. package/dist/node.d.ts +1 -1
  239. package/dist/node.d.ts.map +1 -1
  240. package/dist/node.js.map +1 -1
  241. package/dist/pricing-decimal.d.ts +7 -0
  242. package/dist/pricing-decimal.d.ts.map +1 -0
  243. package/dist/pricing-decimal.js +43 -0
  244. package/dist/pricing-decimal.js.map +1 -0
  245. package/dist/providers/dodo/better-auth-core.d.ts +1 -1
  246. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -1
  247. package/dist/providers/dodo/better-auth-core.js +2 -2
  248. package/dist/providers/dodo/better-auth-core.js.map +1 -1
  249. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  250. package/dist/providers/dodo/better-auth.js +16 -2
  251. package/dist/providers/dodo/better-auth.js.map +1 -1
  252. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  253. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  254. package/dist/providers/dodo/event-mapper.js +120 -18
  255. package/dist/providers/dodo/event-mapper.js.map +1 -1
  256. package/dist/providers/dodo/nextjs-core.d.ts +1 -1
  257. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -1
  258. package/dist/providers/dodo/nextjs-core.js +2 -2
  259. package/dist/providers/dodo/nextjs-core.js.map +1 -1
  260. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  261. package/dist/providers/dodo/nextjs.js +16 -6
  262. package/dist/providers/dodo/nextjs.js.map +1 -1
  263. package/dist/providers/dodo/provider.d.ts +5 -2
  264. package/dist/providers/dodo/provider.d.ts.map +1 -1
  265. package/dist/providers/dodo/provider.js +33 -6
  266. package/dist/providers/dodo/provider.js.map +1 -1
  267. package/dist/providers/dodo/verified-payment-payload.d.ts +6 -0
  268. package/dist/providers/dodo/verified-payment-payload.d.ts.map +1 -0
  269. package/dist/providers/dodo/verified-payment-payload.js +42 -0
  270. package/dist/providers/dodo/verified-payment-payload.js.map +1 -0
  271. package/dist/providers/index.d.ts +1 -1
  272. package/dist/providers/index.d.ts.map +1 -1
  273. package/dist/providers/index.js.map +1 -1
  274. package/dist/providers/mock/provider.d.ts +4 -1
  275. package/dist/providers/mock/provider.d.ts.map +1 -1
  276. package/dist/providers/mock/provider.js +3 -1
  277. package/dist/providers/mock/provider.js.map +1 -1
  278. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  279. package/dist/providers/stripe/event-mapper.js +48 -20
  280. package/dist/providers/stripe/event-mapper.js.map +1 -1
  281. package/dist/providers/stripe/provider.d.ts +4 -1
  282. package/dist/providers/stripe/provider.d.ts.map +1 -1
  283. package/dist/providers/stripe/provider.js +64 -23
  284. package/dist/providers/stripe/provider.js.map +1 -1
  285. package/dist/providers/types.d.ts +11 -1
  286. package/dist/providers/types.d.ts.map +1 -1
  287. package/dist/providers/types.js +9 -0
  288. package/dist/providers/types.js.map +1 -1
  289. package/dist/shared/postgres-client.d.ts +3 -0
  290. package/dist/shared/postgres-client.d.ts.map +1 -1
  291. package/dist/shared/postgres-client.js +61 -49
  292. package/dist/shared/postgres-client.js.map +1 -1
  293. package/dist/shared/provider-rejection.d.ts +3 -0
  294. package/dist/shared/provider-rejection.d.ts.map +1 -0
  295. package/dist/shared/provider-rejection.js +17 -0
  296. package/dist/shared/provider-rejection.js.map +1 -0
  297. package/dist/shared/timestamp.d.ts +2 -0
  298. package/dist/shared/timestamp.d.ts.map +1 -1
  299. package/dist/shared/timestamp.js +7 -0
  300. package/dist/shared/timestamp.js.map +1 -1
  301. package/dist/storage/adapters/clickhouse.d.ts +1 -1
  302. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  303. package/dist/storage/adapters/clickhouse.js +18 -17
  304. package/dist/storage/adapters/clickhouse.js.map +1 -1
  305. package/dist/storage/adapters/s3.d.ts +5 -0
  306. package/dist/storage/adapters/s3.d.ts.map +1 -1
  307. package/dist/storage/adapters/s3.js +46 -14
  308. package/dist/storage/adapters/s3.js.map +1 -1
  309. package/dist/storage/diagnostics.d.ts +3 -7
  310. package/dist/storage/diagnostics.d.ts.map +1 -1
  311. package/dist/storage/diagnostics.js +6 -15
  312. package/dist/storage/diagnostics.js.map +1 -1
  313. package/dist/storage/outbox-worker.d.ts.map +1 -1
  314. package/dist/storage/outbox-worker.js +4 -3
  315. package/dist/storage/outbox-worker.js.map +1 -1
  316. package/dist/storage/ports.d.ts +3 -0
  317. package/dist/storage/ports.d.ts.map +1 -1
  318. package/dist/storage/ports.js.map +1 -1
  319. package/dist/storage/postgres-repository.d.ts +1 -3
  320. package/dist/storage/postgres-repository.d.ts.map +1 -1
  321. package/dist/storage/postgres-repository.js +10 -4
  322. package/dist/storage/postgres-repository.js.map +1 -1
  323. package/dist/storage/runtime.d.ts +15 -10
  324. package/dist/storage/runtime.d.ts.map +1 -1
  325. package/dist/storage/runtime.js +74 -68
  326. package/dist/storage/runtime.js.map +1 -1
  327. package/dist/telemetry/index.d.ts +1 -1
  328. package/dist/telemetry/index.js +1 -1
  329. package/dist/telemetry/index.js.map +1 -1
  330. package/package.json +73 -71
  331. package/dist/credits/queries.d.ts +0 -33
  332. package/dist/credits/queries.d.ts.map +0 -1
  333. package/dist/credits/queries.js +0 -71
  334. package/dist/credits/queries.js.map +0 -1
@@ -1,11 +1,11 @@
1
1
  import { Decimal } from "decimal.js";
2
2
  import { z } from "zod";
3
- import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError, StoreError, } from "../errors.js";
3
+ import { CapReachedError, ConfigError, IdempotencyConflictError, InsufficientCreditsError, OperationNotAllowedError, RefundError, StoreError, } from "../errors.js";
4
4
  import { raiseDeductError } from "./service-errors.js";
5
5
  import { LowBalanceMonitor } from "./low-balance-monitor.js";
6
- import { CreditQueries } from "./queries.js";
7
6
  import { CatalogRuntime } from "./catalog-runtime.js";
8
7
  import { toDecimal } from "./amount.js";
8
+ import { ratedMeasures, ratedDimensions, callerMetadata } from "./rated-wire.js";
9
9
  import { CreditLeaseWorkflow } from "./lease-workflow.js";
10
10
  import { requireStableKey } from "../shared/idempotency.js";
11
11
  import { getDefaultInstrumentation } from "../telemetry/index.js";
@@ -37,11 +37,16 @@ import { normalizeLogger } from "../shared/logger.js";
37
37
  * low_balance).
38
38
  */
39
39
  export class CreditsService {
40
+ /** Look up a durable charge or lease after an ambiguous outcome. */
41
+ async getOperationReceipt(userId, key, kind) {
42
+ return this.store.getOperationReceipt(userId, requireStableKey(key), kind);
43
+ }
40
44
  store;
41
45
  get providerEnvironment() {
42
46
  return this.store.providerEnvironment;
43
47
  }
44
- queries;
48
+ analytics;
49
+ usageStore;
45
50
  catalogRuntime;
46
51
  leases;
47
52
  emitter = null;
@@ -56,7 +61,8 @@ export class CreditsService {
56
61
  constructor(store, engine, emitter, options) {
57
62
  this.store = store;
58
63
  this.instrumentation = options?.instrumentation ?? getDefaultInstrumentation();
59
- this.queries = new CreditQueries(store, options?.analytics ?? store, options?.usageStore ?? store);
64
+ this.analytics = options?.analytics ?? store;
65
+ this.usageStore = options?.usageStore ?? store;
60
66
  const policy = options?.policy ?? "strict_prepaid";
61
67
  if (!POLICY_PRESETS.has(policy)) {
62
68
  throw new ConfigError(`unknown policy preset '${policy}'; expected one of ${[...POLICY_PRESETS].sort().join(", ")}`);
@@ -94,28 +100,28 @@ export class CreditsService {
94
100
  }
95
101
  }
96
102
  async getActiveCatalog() {
97
- return this.queries.getActiveCatalog();
103
+ return this.store.getActiveCatalog();
98
104
  }
99
105
  async getUserPlan(userId) {
100
- return this.queries.getUserPlan(userId);
106
+ return this.store.getUserPlan(userId);
101
107
  }
102
108
  async checkFeature(userId, feature) {
103
- return this.queries.checkFeature(userId, feature);
109
+ return this.store.checkFeature(userId, feature);
104
110
  }
105
111
  async getQuotaState(userId, quotaKey) {
106
- return this.queries.getQuotaState(userId, quotaKey);
112
+ return this.store.getQuotaState(userId, quotaKey);
107
113
  }
108
114
  async listQuotaEvents(userId, options) {
109
- return this.queries.listQuotaEvents(userId, options);
115
+ return this.store.listQuotaEvents(userId, options);
110
116
  }
111
117
  async startPlanMigration(fromPlanId, toPlanId) {
112
- return this.queries.startPlanMigration(fromPlanId, toPlanId);
118
+ return this.store.startPlanMigration(fromPlanId, toPlanId);
113
119
  }
114
120
  async migratePlanBatch(migrationId, batchSize) {
115
- return this.queries.migratePlanBatch(migrationId, batchSize);
121
+ return this.store.migratePlanBatch(migrationId, batchSize);
116
122
  }
117
123
  async revokeCreditsByEntryType(userId, entryType) {
118
- const result = await this.queries.revokeCreditsByEntryType(userId, entryType);
124
+ const result = await this.store.revokeCreditsByEntryType(userId, entryType);
119
125
  if (result.revoked.gt(0)) {
120
126
  this.emit("credits.revoked", userId, {
121
127
  userId,
@@ -123,6 +129,7 @@ export class CreditsService {
123
129
  amount: result.revoked,
124
130
  balanceAfter: result.balanceAfter,
125
131
  });
132
+ await this.balanceMonitor.signalCrossing(userId, result.balanceAfter.plus(result.revoked), result.balanceAfter);
126
133
  }
127
134
  return result;
128
135
  }
@@ -131,44 +138,57 @@ export class CreditsService {
131
138
  return this.instrumentation.run("credits.grant_program", undefined, () => this.store.executeGrantProgram(request));
132
139
  }
133
140
  async getLedgerEntry(userId, entryId) {
134
- return this.queries.getLedgerEntry(userId, entryId);
141
+ return this.store.getLedgerEntry(userId, entryId);
135
142
  }
136
143
  async getAvailable(userId) {
137
- return this.queries.getAvailable(userId);
144
+ return this.store.getAvailable(userId);
138
145
  }
139
146
  async aggregateStats(start, end) {
140
- return this.queries.aggregateStats(start, end);
147
+ return this.analytics.aggregateStats(start, end);
141
148
  }
142
149
  async spendByUser(start, end) {
143
- return this.queries.spendByUser(start, end);
150
+ return this.analytics.spendByUser(start, end);
144
151
  }
145
152
  async spendByModel(start, end) {
146
- return this.queries.spendByModel(start, end);
153
+ return this.analytics.spendByModel(start, end);
147
154
  }
148
155
  async listLedgerEntries(userId, options) {
149
- return this.queries.listLedgerEntries(userId, options);
156
+ return this.store.listLedgerEntries(userId, options);
150
157
  }
151
158
  async listUsageEntries(userId, options) {
152
- return this.queries.listUsageEntries(userId, options);
159
+ return this.store.listUsageEntries(userId, options);
153
160
  }
154
161
  async listUsageCharges(userId, options) {
155
- return this.queries.listUsageCharges(userId, options);
162
+ return this.usageStore.listUsageCharges(userId, options);
156
163
  }
157
164
  async topUsers(limit, start, end) {
158
- return this.queries.topUsers(limit, start, end);
165
+ return this.analytics.topUsers(limit, start, end);
159
166
  }
160
167
  async dailySpend(start, end) {
161
- return this.queries.dailySpend(start, end);
168
+ return this.analytics.dailySpend(start, end);
162
169
  }
163
170
  /** Emit a credit lifecycle event. No-op if no emitter is configured. */
164
171
  emit(type, userId, data) {
165
172
  this.emitter?.emit({ type, timestamp: new Date(), userId, data });
166
173
  }
167
174
  async emitQuotaEvents(userId, idempotencyKey) {
168
- const events = await this.store.listQuotaEvents(userId, {
169
- idempotencyKey,
170
- limit: 100,
171
- });
175
+ if (!this.emitter)
176
+ return;
177
+ let events;
178
+ try {
179
+ events = await this.store.listQuotaEvents(userId, {
180
+ idempotencyKey,
181
+ limit: 100,
182
+ });
183
+ }
184
+ catch (error) {
185
+ this.logger.warn("[CreditsService] failed to fetch quota events", {
186
+ userId,
187
+ idempotencyKey,
188
+ error: error instanceof Error ? error.message : String(error),
189
+ });
190
+ return;
191
+ }
172
192
  for (const event of events) {
173
193
  const data = {
174
194
  quotaKey: event.quotaKey,
@@ -240,7 +260,10 @@ export class CreditsService {
240
260
  * The event is emitted only after the store write succeeds.
241
261
  */
242
262
  async setUserPlan(userId, planKey, planAssignedAt) {
243
- this.logger.info("[CreditsService] setUserPlan", { planKey, planAssignedAt });
263
+ this.logger.info("[CreditsService] setUserPlan", {
264
+ planKey,
265
+ planAssignedAt,
266
+ });
244
267
  const result = await this.store.setUserPlan(userId, planKey, planAssignedAt);
245
268
  this.emit("credits.plan_changed", userId, {
246
269
  userId,
@@ -286,7 +309,11 @@ export class CreditsService {
286
309
  async addCreditsUninstrumented(userId, amount, options) {
287
310
  const idempotencyKey = requireStableKey(options?.idempotencyKey);
288
311
  const type = options.type ?? "adjustment";
289
- this.logger.info("[CreditsService] addCredits", { amount, type, bucket: options.bucket });
312
+ this.logger.info("[CreditsService] addCredits", {
313
+ amount,
314
+ type,
315
+ bucket: options.bucket,
316
+ });
290
317
  const result = await this.store.addCredits(userId, positiveAmount(amount, "addCredits"), {
291
318
  ...options,
292
319
  type,
@@ -299,7 +326,6 @@ export class CreditsService {
299
326
  type,
300
327
  idempotent: result.idempotent ?? false,
301
328
  });
302
- this.balanceMonitor.rearmAfterCredit(userId, result.newBalance);
303
329
  return result;
304
330
  }
305
331
  /**
@@ -332,6 +358,7 @@ export class CreditsService {
332
358
  idempotent: result.idempotent ?? false,
333
359
  });
334
360
  if (!result.idempotent) {
361
+ await this.balanceMonitor.signalCrossing(userId, result.newBalance.plus(result.amount.abs()), result.newBalance);
335
362
  await this.afterDeduction(userId, "raw", {
336
363
  entryId: result.entryId,
337
364
  userId,
@@ -351,17 +378,15 @@ export class CreditsService {
351
378
  * payment-provider webhook handler (Stripe, etc. — bursar stays
352
379
  * provider-agnostic) to call even on webhook redelivery.
353
380
  *
354
- * 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws
355
- * ``ConfigError`` otherwise).
356
- * 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.
357
- * 3. The new cycle is granted via a direct ``store.addCredits`` call
381
+ * 1. Supply a stable absolute ``expiresAt`` across retries, if the grant expires.
382
+ * 2. The new cycle is granted via a direct ``store.addCredits`` call
358
383
  * (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,
359
384
  * not a duplicate ``credits.added``), threading ``idempotencyKey`` so a
360
385
  * redelivered webhook replays the prior grant instead of double-crediting.
361
- * 4. Existing bucket credits are never removed here. Subscription renewal
386
+ * 3. Existing bucket credits are never removed here. Subscription renewal
362
387
  * policies that replace prior lots run atomically through BillingService.
363
- * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.
364
- * 6. Emits ``credits.cycle_renewed`` and returns the grant result.
388
+ * 4. Emits ``credits.cycle_renewed`` and returns the grant result. Plan
389
+ * assignment is a separate operation managed by the caller.
365
390
  */
366
391
  async grantSubscriptionCycle(userId, amount, options) {
367
392
  return this.instrumentation.run("credits.grant_subscription_cycle", undefined, () => this.grantSubscriptionCycleUninstrumented(userId, amount, options));
@@ -371,15 +396,15 @@ export class CreditsService {
371
396
  this.logger.info("[CreditsService] grantSubscriptionCycle", {
372
397
  amount,
373
398
  bucket: options.bucket,
374
- planKey: options.planKey,
375
399
  });
376
- if (options.expiresAt != null && options.ttlDays != null) {
377
- throw new ConfigError("grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both");
400
+ if ("ttlDays" in options) {
401
+ throw new ConfigError("grantSubscriptionCycle: use a stable absolute expiresAt instead of ttlDays");
402
+ }
403
+ if ("planKey" in options) {
404
+ throw new ConfigError("grantSubscriptionCycle: assign plans separately with setUserPlan");
378
405
  }
379
406
  const bucket = options.bucket ?? "subscription";
380
- const expiresAt = options.ttlDays != null
381
- ? new Date(Date.now() + options.ttlDays * 86_400_000)
382
- : options.expiresAt;
407
+ const expiresAt = options.expiresAt;
383
408
  const amountDec = positiveAmount(amount, "grantSubscriptionCycle");
384
409
  const result = await this.store.addCredits(userId, amountDec, {
385
410
  type: "purchase",
@@ -388,23 +413,11 @@ export class CreditsService {
388
413
  bucket,
389
414
  idempotencyKey,
390
415
  });
391
- // The store contract exposes the mutation's replay result directly, avoiding
392
- // a racy lifetime-balance comparison and an extra database round trip.
393
- const isFreshGrant = !result.idempotent;
394
- if (options.planKey) {
395
- // A fresh cycle intentionally re-anchors plan-assignment windows. On a
396
- // webhook replay, repair a previously interrupted grant->assignment saga
397
- // without re-anchoring an assignment that already succeeded.
398
- if (isFreshGrant || (await this.getUserPlan(userId)).planKey !== options.planKey) {
399
- await this.setUserPlan(userId, options.planKey);
400
- }
401
- }
402
416
  this.emit("credits.cycle_renewed", userId, {
403
417
  entryId: result.entryId,
404
418
  amount: amountDec,
405
419
  newBalance: result.newBalance,
406
420
  bucket,
407
- planKey: options.planKey ?? null,
408
421
  idempotencyKey,
409
422
  idempotent: result.idempotent,
410
423
  });
@@ -450,7 +463,7 @@ export class CreditsService {
450
463
  * typed exception is thrown. No success event is emitted on error.
451
464
  */
452
465
  async deduct(userId, metrics, options) {
453
- return this.instrumentation.run("credits.deduct", undefined, () => this.deductUninstrumented(userId, metrics, options));
466
+ return this.instrumentation.run("credits.deduct", undefined, () => this.catalogRuntime.withFreshQuote(() => this.deductUninstrumented(userId, metrics, options)));
454
467
  }
455
468
  async deductUninstrumented(userId, metrics, options, flatJob = false) {
456
469
  await this.maybeLazyExpire(userId);
@@ -458,38 +471,38 @@ export class CreditsService {
458
471
  model: metrics.dimensions?.model,
459
472
  feature: options.feature,
460
473
  });
461
- const engine = await this.catalogRuntime.engineForUser(userId);
474
+ const plan = await this.store.getUserPlan(userId);
475
+ const engine = await this.catalogRuntime.engineForPlan(plan);
476
+ const quoteVersion = plan.catalogVersion ?? this.catalogRuntime.pricingVersion(engine);
462
477
  if (flatJob && engine.hasMeasure(metrics.operation, "jobs"))
463
478
  metrics = { ...metrics, measures: { jobs: 1 } };
464
- const plan = await this.store.getUserPlan(userId);
465
479
  const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
466
480
  const model = z.string().safeParse(metrics.dimensions?.model).data ?? null;
467
481
  const region = z.string().safeParse(metrics.dimensions?.region).data ?? null;
468
482
  // 1) Calculate cost as an exact Decimal, never truncated.
469
- const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
483
+ const breakdown = engine.calculate(metrics, {
484
+ rateCard: plan.rateCard ?? undefined,
485
+ });
470
486
  const cost = breakdown.total;
487
+ const measures = ratedMeasures(metrics.measures);
488
+ const dimensions = ratedDimensions(metrics.dimensions);
471
489
  // Build ledger metadata: caller fields FIRST, system fields LAST so the
472
490
  // protected system fields win.
473
- const meta = {};
474
- if (options.metadata) {
475
- for (const [k, v] of Object.entries(options.metadata)) {
476
- if (v != null)
477
- meta[k] = v;
478
- }
479
- }
491
+ const meta = callerMetadata(options.metadata, true);
480
492
  meta["operation"] = metrics.operation;
481
- meta["measures"] = { ...(metrics.measures ?? {}) };
482
- meta["dimensions"] = { ...(metrics.dimensions ?? {}) };
483
- meta["breakdownTotal"] = breakdown.total.toString();
484
- meta["idempotencyKey"] = effectiveIdempotencyKey;
493
+ meta["measures"] = measures;
494
+ meta["dimensions"] = dimensions;
495
+ meta["breakdownTotal"] = breakdown.total.toFixed(6);
496
+ meta["idempotency_key"] = effectiveIdempotencyKey;
485
497
  const deductionOptions = {
486
498
  idempotencyKey: effectiveIdempotencyKey,
499
+ expectedPricing: this.catalogRuntime.expectedPricing(plan, quoteVersion),
487
500
  operation: metrics.operation,
488
501
  feature: options.feature ?? null,
489
502
  model,
490
503
  region,
491
- measures: { ...(metrics.measures ?? {}) },
492
- dimensions: { ...(metrics.dimensions ?? {}) },
504
+ measures,
505
+ dimensions,
493
506
  metadata: meta,
494
507
  };
495
508
  // 2) Atomic charge. This records zero-cost usage too, so authorization,
@@ -523,7 +536,7 @@ export class CreditsService {
523
536
  });
524
537
  // low_balance is edge-triggered: only fire when this deduction crossed
525
538
  // the threshold. A replayed (idempotent) result did not move the balance, so
526
- // it never crosses. balanceBefore = balanceAfter + amount charged.
539
+ // it never crosses. The store's amount is already net of allowance.
527
540
  if (!result.idempotent) {
528
541
  const balanceBefore = result.balanceAfter.plus(result.amount);
529
542
  await this.balanceMonitor.signalCrossing(userId, balanceBefore, result.balanceAfter);
@@ -539,34 +552,39 @@ export class CreditsService {
539
552
  * affecting the account balance, such as externally billed usage.
540
553
  */
541
554
  async recordUsage(userId, metrics, options) {
542
- const engine = await this.catalogRuntime.engineForUser(userId);
555
+ return this.catalogRuntime.withFreshQuote(() => this.recordUsageOnce(userId, metrics, options));
556
+ }
557
+ async recordUsageOnce(userId, metrics, options) {
543
558
  const plan = await this.store.getUserPlan(userId);
559
+ const engine = await this.catalogRuntime.engineForPlan(plan);
544
560
  const effectiveIdempotencyKey = requireStableKey(options?.idempotencyKey);
545
561
  const model = z.string().safeParse(metrics.dimensions?.model).data ?? null;
546
562
  const region = z.string().safeParse(metrics.dimensions?.region).data ?? null;
547
- const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
548
- const meta = {};
549
- if (options.metadata) {
550
- for (const [key, value] of Object.entries(options.metadata)) {
551
- if (value != null)
552
- meta[key] = value;
553
- }
554
- }
563
+ const breakdown = engine.calculate(metrics, {
564
+ rateCard: plan.rateCard ?? undefined,
565
+ });
566
+ const measures = ratedMeasures(metrics.measures);
567
+ const dimensions = ratedDimensions(metrics.dimensions);
568
+ const meta = callerMetadata(options.metadata, true);
555
569
  meta.operation = metrics.operation;
556
- meta.measures = { ...(metrics.measures ?? {}) };
557
- meta.dimensions = { ...(metrics.dimensions ?? {}) };
558
- meta.breakdownTotal = breakdown.total.toString();
559
- meta.idempotencyKey = effectiveIdempotencyKey;
570
+ meta.measures = measures;
571
+ meta.dimensions = dimensions;
572
+ meta.breakdownTotal = breakdown.total.toFixed(6);
573
+ meta.idempotency_key = effectiveIdempotencyKey;
560
574
  const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {
561
575
  idempotencyKey: effectiveIdempotencyKey,
576
+ expectedPricing: this.catalogRuntime.expectedPricing(plan, plan.catalogVersion ?? this.catalogRuntime.pricingVersion(engine)),
562
577
  operation: metrics.operation,
563
578
  model,
564
579
  region,
565
- measures: { ...(metrics.measures ?? {}) },
566
- dimensions: { ...(metrics.dimensions ?? {}) },
580
+ measures,
581
+ dimensions,
567
582
  metadata: meta,
568
583
  });
569
584
  if (result.error !== null) {
585
+ if (result.error === "idempotency_conflict") {
586
+ throw new IdempotencyConflictError(`Idempotency key conflicts with a prior request. user=${userId}`);
587
+ }
570
588
  throw new StoreError(`Usage record failed: ${result.error}`);
571
589
  }
572
590
  return result;
@@ -581,7 +599,7 @@ export class CreditsService {
581
599
  */
582
600
  /** Deduct the configured fixed cost for one named job. */
583
601
  async deductFlatJob(userId, jobName, options) {
584
- return this.instrumentation.run("credits.deduct", undefined, () => this.deductUninstrumented(userId, { operation: jobName }, options, true));
602
+ return this.instrumentation.run("credits.deduct", undefined, () => this.catalogRuntime.withFreshQuote(() => this.deductUninstrumented(userId, { operation: jobName }, options, true)));
585
603
  }
586
604
  async refundCredits(entryId, options) {
587
605
  return this.instrumentation.run("credits.refund", undefined, () => this.refundCreditsUninstrumented(entryId, options));
@@ -631,62 +649,62 @@ export class CreditsService {
631
649
  */
632
650
  async deductTeam(teamId, userId, metrics, options) {
633
651
  const idempotencyKey = requireStableKey(options?.idempotencyKey);
634
- await this.maybeLazyExpire(userId);
635
- // Lazy expiry is scoped to the individual member's credits, not the team's
636
- // shared pool — there's no per-team expiry concept.
637
- const engine = await this.catalogRuntime.engineForUser(userId);
638
- const plan = await this.store.getUserPlan(userId);
639
- const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
640
- const cost = breakdown.total;
641
- if (cost.lte(0)) {
642
- const teamBal = await this.store.getTeamBalance(teamId);
643
- if (teamBal === null) {
644
- throw new StoreError(`Team not found: ${teamId}`);
645
- }
646
- return {
647
- entryId: null,
648
- teamId,
649
- userId,
650
- amount: new Decimal(0),
651
- teamBalanceAfter: teamBal.balance,
652
- idempotent: false,
653
- error: null,
652
+ return this.catalogRuntime.withFreshQuote(async () => {
653
+ await this.maybeLazyExpire(userId);
654
+ const plan = await this.store.getUserPlan(userId);
655
+ const engine = await this.catalogRuntime.engineForPlan(plan);
656
+ const breakdown = engine.calculate(metrics, {
657
+ rateCard: plan.rateCard ?? undefined,
658
+ });
659
+ const cost = breakdown.total;
660
+ const teamMetadata = {
661
+ ...callerMetadata(options.metadata, true),
662
+ operation: metrics.operation,
663
+ measures: ratedMeasures(metrics.measures),
664
+ dimensions: ratedDimensions(metrics.dimensions),
665
+ breakdownTotal: breakdown.total.toFixed(6),
654
666
  };
655
- }
656
- const teamMetadata = {
657
- ...(options.metadata ?? {}),
658
- operation: metrics.operation,
659
- measures: { ...(metrics.measures ?? {}) },
660
- dimensions: Object.fromEntries(Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)])),
661
- breakdownTotal: breakdown.total.toString(),
662
- };
663
- const result = await this.store.deductTeam(teamId, userId, cost, {
664
- metadata: teamMetadata,
665
- idempotencyKey,
666
- });
667
- // Surface store errors: emit credits.deduct_failed and throw,
668
- // mirroring the Python credit service implementation. Previously returned a silent
669
- // success-shaped object with an .error field, so failed charges looked OK.
670
- if (result.error !== null) {
671
- this.emit("credits.deduct_failed", userId, {
672
- error: result.error,
673
- amount: cost,
667
+ const result = await this.store.deductTeam(teamId, userId, cost, {
668
+ metadata: teamMetadata,
669
+ idempotencyKey,
670
+ expectedPricing: this.catalogRuntime.expectedPricing(plan, plan.catalogVersion ?? this.catalogRuntime.pricingVersion(engine)),
671
+ });
672
+ // Surface store errors: emit credits.deduct_failed and throw,
673
+ // mirroring the Python credit service implementation. Previously returned a silent
674
+ // success-shaped object with an .error field, so failed charges looked OK.
675
+ if (result.error !== null) {
676
+ this.emit("credits.deduct_failed", userId, {
677
+ error: result.error,
678
+ amount: cost,
679
+ teamId,
680
+ deductType: "team",
681
+ });
682
+ if (result.error === "member_spend_cap_exceeded") {
683
+ throw new CapReachedError(`Team member spend cap exceeded. Team=${teamId}, user=${userId}, requested=${cost}`);
684
+ }
685
+ if (result.error === "idempotency_conflict") {
686
+ throw new IdempotencyConflictError(`Team idempotency key conflicts with a prior request. Team=${teamId}`);
687
+ }
688
+ if (result.error === "not_team_member") {
689
+ throw new OperationNotAllowedError(`Active team membership is required. Team=${teamId}, user=${userId}`);
690
+ }
691
+ if (result.error === "insufficient_credits" || result.error === "insufficient_headroom") {
692
+ throw new InsufficientCreditsError(`Insufficient team credits. Team=${teamId}, user=${userId}, requested=${cost}`);
693
+ }
694
+ throw new StoreError(`Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}`);
695
+ }
696
+ this.emit("credits.deducted", userId, {
697
+ entryId: result.entryId,
698
+ amount: result.amount,
699
+ teamBalanceAfter: result.teamBalanceAfter,
674
700
  teamId,
675
701
  deductType: "team",
676
702
  });
677
- if (result.error === "member_spend_cap_exceeded") {
678
- throw new CapReachedError(`Team member spend cap exceeded. Team=${teamId}, user=${userId}, requested=${cost}`);
703
+ if (!result.idempotent) {
704
+ await this.balanceMonitor.signalCrossing(userId, result.teamBalanceAfter.plus(result.amount), result.teamBalanceAfter, { teamId });
679
705
  }
680
- throw new InsufficientCreditsError(`Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}, requested=${cost}`);
681
- }
682
- this.emit("credits.deducted", userId, {
683
- entryId: result.entryId,
684
- amount: result.amount,
685
- teamBalanceAfter: result.teamBalanceAfter,
686
- teamId,
687
- deductType: "team",
706
+ return result;
688
707
  });
689
- return result;
690
708
  }
691
709
  async runSweep(dryRun, userId) {
692
710
  const result = await this.store.sweepExpiredCredits(dryRun, userId);