@zonastery/bursar 2.0.2 → 2.0.4

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 (395) hide show
  1. package/README.md +1 -0
  2. package/dist/billing/auto-recharge-port.d.ts +3 -2
  3. package/dist/billing/auto-recharge-port.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-port.js.map +1 -1
  5. package/dist/billing/auto-recharge-service.d.ts +1 -1
  6. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  7. package/dist/billing/auto-recharge-service.js +5 -4
  8. package/dist/billing/auto-recharge-service.js.map +1 -1
  9. package/dist/billing/billing-service.d.ts +3 -2
  10. package/dist/billing/billing-service.d.ts.map +1 -1
  11. package/dist/billing/billing-service.js +2 -10
  12. package/dist/billing/billing-service.js.map +1 -1
  13. package/dist/billing/billing-store.d.ts +7 -7
  14. package/dist/billing/billing-store.d.ts.map +1 -1
  15. package/dist/billing/billing-store.js.map +1 -1
  16. package/dist/billing/contracts.d.ts +10 -8
  17. package/dist/billing/contracts.d.ts.map +1 -1
  18. package/dist/billing/contracts.js.map +1 -1
  19. package/dist/billing/event-handlers.d.ts +5 -9
  20. package/dist/billing/event-handlers.d.ts.map +1 -1
  21. package/dist/billing/event-handlers.js +191 -285
  22. package/dist/billing/event-handlers.js.map +1 -1
  23. package/dist/billing/event-processor.d.ts +1 -1
  24. package/dist/billing/event-processor.d.ts.map +1 -1
  25. package/dist/billing/event-processor.js +42 -21
  26. package/dist/billing/event-processor.js.map +1 -1
  27. package/dist/billing/financial-event-handlers.d.ts +3 -9
  28. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  29. package/dist/billing/financial-event-handlers.js +10 -12
  30. package/dist/billing/financial-event-handlers.js.map +1 -1
  31. package/dist/billing/index.d.ts +1 -1
  32. package/dist/billing/index.d.ts.map +1 -1
  33. package/dist/billing/index.js.map +1 -1
  34. package/dist/billing/management.d.ts +3 -2
  35. package/dist/billing/management.d.ts.map +1 -1
  36. package/dist/billing/management.js.map +1 -1
  37. package/dist/billing/postgres/repositories/auto-recharge.d.ts +2 -1
  38. package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
  39. package/dist/billing/postgres/repositories/auto-recharge.js +59 -41
  40. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  41. package/dist/billing/postgres/repositories/dispute.d.ts +2 -1
  42. package/dist/billing/postgres/repositories/dispute.d.ts.map +1 -1
  43. package/dist/billing/postgres/repositories/dispute.js.map +1 -1
  44. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  45. package/dist/billing/postgres/repositories/event.js +33 -1
  46. package/dist/billing/postgres/repositories/event.js.map +1 -1
  47. package/dist/billing/postgres/repositories/invoice.d.ts +2 -1
  48. package/dist/billing/postgres/repositories/invoice.d.ts.map +1 -1
  49. package/dist/billing/postgres/repositories/invoice.js +8 -12
  50. package/dist/billing/postgres/repositories/invoice.js.map +1 -1
  51. package/dist/billing/postgres/repositories/offer.d.ts +1 -1
  52. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  53. package/dist/billing/postgres/repositories/offer.js +6 -1
  54. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  55. package/dist/billing/postgres/repositories/payment.d.ts +1 -1
  56. package/dist/billing/postgres/repositories/payment.d.ts.map +1 -1
  57. package/dist/billing/postgres/repositories/payment.js +1 -1
  58. package/dist/billing/postgres/repositories/payment.js.map +1 -1
  59. package/dist/billing/postgres/repositories/subscription-change.d.ts.map +1 -1
  60. package/dist/billing/postgres/repositories/subscription-change.js +1 -9
  61. package/dist/billing/postgres/repositories/subscription-change.js.map +1 -1
  62. package/dist/billing/postgres/repositories/subscription.d.ts +6 -6
  63. package/dist/billing/postgres/repositories/subscription.d.ts.map +1 -1
  64. package/dist/billing/postgres/repositories/subscription.js +29 -30
  65. package/dist/billing/postgres/repositories/subscription.js.map +1 -1
  66. package/dist/billing/postgres/repositories/topup.d.ts +1 -1
  67. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  68. package/dist/billing/postgres/repositories/topup.js +1 -1
  69. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  70. package/dist/billing/postgres/store.d.ts +7 -6
  71. package/dist/billing/postgres/store.d.ts.map +1 -1
  72. package/dist/billing/postgres/store.js +31 -19
  73. package/dist/billing/postgres/store.js.map +1 -1
  74. package/dist/billing/types/auto-recharge.d.ts +3 -2
  75. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  76. package/dist/billing/types/auto-recharge.js.map +1 -1
  77. package/dist/billing/types/catalog.d.ts +1 -1
  78. package/dist/billing/types/catalog.d.ts.map +1 -1
  79. package/dist/billing/types/catalog.js.map +1 -1
  80. package/dist/billing/types/documents.d.ts +3 -2
  81. package/dist/billing/types/documents.d.ts.map +1 -1
  82. package/dist/billing/types/documents.js.map +1 -1
  83. package/dist/billing/types/events.d.ts +11 -2
  84. package/dist/billing/types/events.d.ts.map +1 -1
  85. package/dist/billing/types/events.js +73 -39
  86. package/dist/billing/types/events.js.map +1 -1
  87. package/dist/billing/types/subscriptions.d.ts +4 -1
  88. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  89. package/dist/billing/types/subscriptions.js.map +1 -1
  90. package/dist/breakdown.d.ts +4 -3
  91. package/dist/breakdown.d.ts.map +1 -1
  92. package/dist/breakdown.js +1 -1
  93. package/dist/breakdown.js.map +1 -1
  94. package/dist/bursar.d.ts.map +1 -1
  95. package/dist/bursar.js +4 -3
  96. package/dist/bursar.js.map +1 -1
  97. package/dist/catalog.d.ts.map +1 -1
  98. package/dist/catalog.js +45 -42
  99. package/dist/catalog.js.map +1 -1
  100. package/dist/commerce/provider-registry.d.ts.map +1 -1
  101. package/dist/commerce/provider-registry.js +11 -6
  102. package/dist/commerce/provider-registry.js.map +1 -1
  103. package/dist/commerce/service.d.ts.map +1 -1
  104. package/dist/commerce/service.js +70 -68
  105. package/dist/commerce/service.js.map +1 -1
  106. package/dist/commerce/types.d.ts +1 -1
  107. package/dist/commerce/types.d.ts.map +1 -1
  108. package/dist/commerce/types.js.map +1 -1
  109. package/dist/config/parse-access.d.ts +5 -2
  110. package/dist/config/parse-access.d.ts.map +1 -1
  111. package/dist/config/parse-access.js +60 -41
  112. package/dist/config/parse-access.js.map +1 -1
  113. package/dist/config/parse-commerce.d.ts +2 -1
  114. package/dist/config/parse-commerce.d.ts.map +1 -1
  115. package/dist/config/parse-commerce.js +49 -29
  116. package/dist/config/parse-commerce.js.map +1 -1
  117. package/dist/config/parse-credits.d.ts +2 -1
  118. package/dist/config/parse-credits.d.ts.map +1 -1
  119. package/dist/config/parse-credits.js +39 -23
  120. package/dist/config/parse-credits.js.map +1 -1
  121. package/dist/config/parse-plans.d.ts +7 -2
  122. package/dist/config/parse-plans.d.ts.map +1 -1
  123. package/dist/config/parse-plans.js +49 -22
  124. package/dist/config/parse-plans.js.map +1 -1
  125. package/dist/config/parse-pricing.d.ts +2 -1
  126. package/dist/config/parse-pricing.d.ts.map +1 -1
  127. package/dist/config/parse-pricing.js +41 -31
  128. package/dist/config/parse-pricing.js.map +1 -1
  129. package/dist/config/parse-utils.d.ts +16 -12
  130. package/dist/config/parse-utils.d.ts.map +1 -1
  131. package/dist/config/parse-utils.js +91 -28
  132. package/dist/config/parse-utils.js.map +1 -1
  133. package/dist/config/types.d.ts +1 -1
  134. package/dist/config/types.d.ts.map +1 -1
  135. package/dist/config/types.js.map +1 -1
  136. package/dist/config.d.ts +6 -5
  137. package/dist/config.d.ts.map +1 -1
  138. package/dist/config.js +66 -36
  139. package/dist/config.js.map +1 -1
  140. package/dist/credits/amount.d.ts +2 -2
  141. package/dist/credits/amount.d.ts.map +1 -1
  142. package/dist/credits/amount.js +6 -5
  143. package/dist/credits/amount.js.map +1 -1
  144. package/dist/credits/catalog-runtime.d.ts +1 -1
  145. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  146. package/dist/credits/catalog-runtime.js +3 -4
  147. package/dist/credits/catalog-runtime.js.map +1 -1
  148. package/dist/credits/events.d.ts +12 -1
  149. package/dist/credits/events.d.ts.map +1 -1
  150. package/dist/credits/events.js +35 -21
  151. package/dist/credits/events.js.map +1 -1
  152. package/dist/credits/lease-workflow.d.ts +3 -2
  153. package/dist/credits/lease-workflow.d.ts.map +1 -1
  154. package/dist/credits/lease-workflow.js +4 -3
  155. package/dist/credits/lease-workflow.js.map +1 -1
  156. package/dist/credits/low-balance-monitor.d.ts +3 -2
  157. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  158. package/dist/credits/low-balance-monitor.js +1 -1
  159. package/dist/credits/low-balance-monitor.js.map +1 -1
  160. package/dist/credits/postgres/repositories/analytics.d.ts +2 -2
  161. package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
  162. package/dist/credits/postgres/repositories/analytics.js +14 -6
  163. package/dist/credits/postgres/repositories/analytics.js.map +1 -1
  164. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  165. package/dist/credits/postgres/repositories/balance.js +7 -7
  166. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  167. package/dist/credits/postgres/repositories/bucket.js +1 -1
  168. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  169. package/dist/credits/postgres/repositories/catalog.d.ts +4 -3
  170. package/dist/credits/postgres/repositories/catalog.d.ts.map +1 -1
  171. package/dist/credits/postgres/repositories/catalog.js +4 -3
  172. package/dist/credits/postgres/repositories/catalog.js.map +1 -1
  173. package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
  174. package/dist/credits/postgres/repositories/deduction.js +2 -2
  175. package/dist/credits/postgres/repositories/deduction.js.map +1 -1
  176. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  177. package/dist/credits/postgres/repositories/lease.js +4 -2
  178. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  179. package/dist/credits/postgres/repositories/plan.d.ts +1 -1
  180. package/dist/credits/postgres/repositories/team.d.ts +2 -1
  181. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  182. package/dist/credits/postgres/repositories/team.js +19 -5
  183. package/dist/credits/postgres/repositories/team.js.map +1 -1
  184. package/dist/credits/postgres/store.d.ts +6 -5
  185. package/dist/credits/postgres/store.d.ts.map +1 -1
  186. package/dist/credits/postgres/store.js +23 -13
  187. package/dist/credits/postgres/store.js.map +1 -1
  188. package/dist/credits/postgres/value-mappers.d.ts +5 -4
  189. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  190. package/dist/credits/postgres/value-mappers.js +11 -12
  191. package/dist/credits/postgres/value-mappers.js.map +1 -1
  192. package/dist/credits/service-errors.d.ts +1 -1
  193. package/dist/credits/service-errors.d.ts.map +1 -1
  194. package/dist/credits/service-errors.js +1 -1
  195. package/dist/credits/service-errors.js.map +1 -1
  196. package/dist/credits/service-types.d.ts +4 -1
  197. package/dist/credits/service-types.d.ts.map +1 -1
  198. package/dist/credits/service-types.js.map +1 -1
  199. package/dist/credits/service.d.ts +5 -0
  200. package/dist/credits/service.d.ts.map +1 -1
  201. package/dist/credits/service.js +30 -10
  202. package/dist/credits/service.js.map +1 -1
  203. package/dist/credits/store.d.ts +15 -5
  204. package/dist/credits/store.d.ts.map +1 -1
  205. package/dist/credits/store.js +1 -1
  206. package/dist/credits/store.js.map +1 -1
  207. package/dist/credits/types/account.d.ts +5 -4
  208. package/dist/credits/types/account.d.ts.map +1 -1
  209. package/dist/credits/types/account.js.map +1 -1
  210. package/dist/credits/types/catalog.d.ts +2 -1
  211. package/dist/credits/types/catalog.d.ts.map +1 -1
  212. package/dist/credits/types/catalog.js.map +1 -1
  213. package/dist/credits/types/grants.d.ts.map +1 -1
  214. package/dist/credits/types/grants.js.map +1 -1
  215. package/dist/credits/types/ledger.d.ts +3 -2
  216. package/dist/credits/types/ledger.d.ts.map +1 -1
  217. package/dist/credits/types/ledger.js.map +1 -1
  218. package/dist/credits/types/teams.d.ts +1 -0
  219. package/dist/credits/types/teams.d.ts.map +1 -1
  220. package/dist/credits/types/teams.js.map +1 -1
  221. package/dist/engine.d.ts +2 -2
  222. package/dist/engine.d.ts.map +1 -1
  223. package/dist/engine.js +40 -11
  224. package/dist/engine.js.map +1 -1
  225. package/dist/errors.d.ts +10 -3
  226. package/dist/errors.d.ts.map +1 -1
  227. package/dist/errors.js +50 -9
  228. package/dist/errors.js.map +1 -1
  229. package/dist/expr/ast.d.ts.map +1 -1
  230. package/dist/expr/ast.js.map +1 -1
  231. package/dist/expr/evaluator.d.ts +1 -1
  232. package/dist/expr/evaluator.d.ts.map +1 -1
  233. package/dist/expr/evaluator.js +1 -1
  234. package/dist/expr/evaluator.js.map +1 -1
  235. package/dist/expr/parser.d.ts.map +1 -1
  236. package/dist/expr/parser.js.map +1 -1
  237. package/dist/expr/tokenizer.d.ts.map +1 -1
  238. package/dist/expr/tokenizer.js +34 -12
  239. package/dist/expr/tokenizer.js.map +1 -1
  240. package/dist/expr.d.ts +1 -1
  241. package/dist/expr.d.ts.map +1 -1
  242. package/dist/expr.js +13 -7
  243. package/dist/expr.js.map +1 -1
  244. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  245. package/dist/generated/pricing-config.types.js.map +1 -1
  246. package/dist/index.d.ts +3 -1
  247. package/dist/index.d.ts.map +1 -1
  248. package/dist/index.js +1 -0
  249. package/dist/index.js.map +1 -1
  250. package/dist/integrations/better-auth.d.ts +4 -1
  251. package/dist/integrations/better-auth.d.ts.map +1 -1
  252. package/dist/integrations/better-auth.js +7 -4
  253. package/dist/integrations/better-auth.js.map +1 -1
  254. package/dist/load-config-file.d.ts +2 -1
  255. package/dist/load-config-file.d.ts.map +1 -1
  256. package/dist/load-config-file.js +19 -13
  257. package/dist/load-config-file.js.map +1 -1
  258. package/dist/metrics.d.ts +3 -2
  259. package/dist/metrics.d.ts.map +1 -1
  260. package/dist/metrics.js.map +1 -1
  261. package/dist/node.d.ts +6 -3
  262. package/dist/node.d.ts.map +1 -1
  263. package/dist/node.js +1 -0
  264. package/dist/node.js.map +1 -1
  265. package/dist/providers/_shared.d.ts +11 -8
  266. package/dist/providers/_shared.d.ts.map +1 -1
  267. package/dist/providers/_shared.js +26 -17
  268. package/dist/providers/_shared.js.map +1 -1
  269. package/dist/providers/dodo/better-auth-core.d.ts +32 -0
  270. package/dist/providers/dodo/better-auth-core.d.ts.map +1 -0
  271. package/dist/providers/dodo/better-auth-core.js +14 -0
  272. package/dist/providers/dodo/better-auth-core.js.map +1 -0
  273. package/dist/providers/dodo/better-auth.d.ts +5 -7
  274. package/dist/providers/dodo/better-auth.d.ts.map +1 -1
  275. package/dist/providers/dodo/better-auth.js +16 -13
  276. package/dist/providers/dodo/better-auth.js.map +1 -1
  277. package/dist/providers/dodo/client-contract.d.ts +16 -22
  278. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  279. package/dist/providers/dodo/client-contract.js.map +1 -1
  280. package/dist/providers/dodo/event-mapper.d.ts +7 -4
  281. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  282. package/dist/providers/dodo/event-mapper.js +130 -106
  283. package/dist/providers/dodo/event-mapper.js.map +1 -1
  284. package/dist/providers/dodo/nextjs-core.d.ts +22 -0
  285. package/dist/providers/dodo/nextjs-core.d.ts.map +1 -0
  286. package/dist/providers/dodo/nextjs-core.js +14 -0
  287. package/dist/providers/dodo/nextjs-core.js.map +1 -0
  288. package/dist/providers/dodo/nextjs.d.ts +5 -7
  289. package/dist/providers/dodo/nextjs.d.ts.map +1 -1
  290. package/dist/providers/dodo/nextjs.js +11 -10
  291. package/dist/providers/dodo/nextjs.js.map +1 -1
  292. package/dist/providers/dodo/provider.d.ts +3 -3
  293. package/dist/providers/dodo/provider.d.ts.map +1 -1
  294. package/dist/providers/dodo/provider.js +76 -58
  295. package/dist/providers/dodo/provider.js.map +1 -1
  296. package/dist/providers/dodo/react-native-core.d.ts +56 -0
  297. package/dist/providers/dodo/react-native-core.d.ts.map +1 -0
  298. package/dist/providers/dodo/react-native-core.js +56 -0
  299. package/dist/providers/dodo/react-native-core.js.map +1 -0
  300. package/dist/providers/dodo/react-native.d.ts +6 -50
  301. package/dist/providers/dodo/react-native.d.ts.map +1 -1
  302. package/dist/providers/dodo/react-native.js +5 -49
  303. package/dist/providers/dodo/react-native.js.map +1 -1
  304. package/dist/providers/dodo/webhook-bridge.d.ts +4 -2
  305. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  306. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  307. package/dist/providers/environment.d.ts +1 -1
  308. package/dist/providers/environment.d.ts.map +1 -1
  309. package/dist/providers/environment.js +4 -2
  310. package/dist/providers/environment.js.map +1 -1
  311. package/dist/providers/mock/provider.d.ts.map +1 -1
  312. package/dist/providers/mock/provider.js +5 -10
  313. package/dist/providers/mock/provider.js.map +1 -1
  314. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  315. package/dist/providers/stripe/event-mapper.js +104 -12
  316. package/dist/providers/stripe/event-mapper.js.map +1 -1
  317. package/dist/providers/stripe/provider.d.ts.map +1 -1
  318. package/dist/providers/stripe/provider.js +100 -60
  319. package/dist/providers/stripe/provider.js.map +1 -1
  320. package/dist/providers/types.d.ts +0 -1
  321. package/dist/providers/types.d.ts.map +1 -1
  322. package/dist/providers/types.js.map +1 -1
  323. package/dist/retry.d.ts.map +1 -1
  324. package/dist/retry.js +16 -9
  325. package/dist/retry.js.map +1 -1
  326. package/dist/shared/diagnostics.d.ts +10 -2
  327. package/dist/shared/diagnostics.d.ts.map +1 -1
  328. package/dist/shared/diagnostics.js +65 -6
  329. package/dist/shared/diagnostics.js.map +1 -1
  330. package/dist/shared/idempotency.d.ts +4 -3
  331. package/dist/shared/idempotency.d.ts.map +1 -1
  332. package/dist/shared/idempotency.js +21 -10
  333. package/dist/shared/idempotency.js.map +1 -1
  334. package/dist/shared/json.d.ts +28 -0
  335. package/dist/shared/json.d.ts.map +1 -0
  336. package/dist/shared/json.js +41 -0
  337. package/dist/shared/json.js.map +1 -0
  338. package/dist/shared/logger.d.ts +10 -4
  339. package/dist/shared/logger.d.ts.map +1 -1
  340. package/dist/shared/logger.js.map +1 -1
  341. package/dist/shared/postgres-client.d.ts +10 -5
  342. package/dist/shared/postgres-client.d.ts.map +1 -1
  343. package/dist/shared/postgres-client.js +80 -45
  344. package/dist/shared/postgres-client.js.map +1 -1
  345. package/dist/shared/postgres-errors.d.ts +1 -1
  346. package/dist/shared/postgres-errors.d.ts.map +1 -1
  347. package/dist/shared/postgres-errors.js +32 -31
  348. package/dist/shared/postgres-errors.js.map +1 -1
  349. package/dist/shared/postgres-types.d.ts +3 -2
  350. package/dist/shared/postgres-types.d.ts.map +1 -1
  351. package/dist/shared/postgres-types.js.map +1 -1
  352. package/dist/shared/postgres-validation.d.ts +7 -6
  353. package/dist/shared/postgres-validation.d.ts.map +1 -1
  354. package/dist/shared/postgres-validation.js +17 -10
  355. package/dist/shared/postgres-validation.js.map +1 -1
  356. package/dist/storage/adapters/clickhouse.d.ts +20 -6
  357. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  358. package/dist/storage/adapters/clickhouse.js +150 -42
  359. package/dist/storage/adapters/clickhouse.js.map +1 -1
  360. package/dist/storage/adapters/s3.d.ts +67 -6
  361. package/dist/storage/adapters/s3.d.ts.map +1 -1
  362. package/dist/storage/adapters/s3.js +79 -26
  363. package/dist/storage/adapters/s3.js.map +1 -1
  364. package/dist/storage/diagnostics.d.ts +105 -0
  365. package/dist/storage/diagnostics.d.ts.map +1 -0
  366. package/dist/storage/diagnostics.js +228 -0
  367. package/dist/storage/diagnostics.js.map +1 -0
  368. package/dist/storage/maintenance.d.ts +88 -0
  369. package/dist/storage/maintenance.d.ts.map +1 -0
  370. package/dist/storage/maintenance.js +272 -0
  371. package/dist/storage/maintenance.js.map +1 -0
  372. package/dist/storage/outbox-worker.d.ts +21 -1
  373. package/dist/storage/outbox-worker.d.ts.map +1 -1
  374. package/dist/storage/outbox-worker.js +157 -28
  375. package/dist/storage/outbox-worker.js.map +1 -1
  376. package/dist/storage/ports.d.ts +52 -7
  377. package/dist/storage/ports.d.ts.map +1 -1
  378. package/dist/storage/ports.js.map +1 -1
  379. package/dist/storage/postgres-repository.d.ts +9 -2
  380. package/dist/storage/postgres-repository.d.ts.map +1 -1
  381. package/dist/storage/postgres-repository.js +97 -11
  382. package/dist/storage/postgres-repository.js.map +1 -1
  383. package/dist/storage/runtime.d.ts +20 -3
  384. package/dist/storage/runtime.d.ts.map +1 -1
  385. package/dist/storage/runtime.js +326 -156
  386. package/dist/storage/runtime.js.map +1 -1
  387. package/dist/telemetry/index.d.ts +41 -0
  388. package/dist/telemetry/index.d.ts.map +1 -0
  389. package/dist/telemetry/index.js +118 -0
  390. package/dist/telemetry/index.js.map +1 -0
  391. package/dist/telemetry/opentelemetry.d.ts +25 -0
  392. package/dist/telemetry/opentelemetry.d.ts.map +1 -0
  393. package/dist/telemetry/opentelemetry.js +74 -0
  394. package/dist/telemetry/opentelemetry.js.map +1 -0
  395. package/package.json +24 -14
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/credits/store.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAuF3D;;;;;;;;;;;GAWG;AACH,MAAM,OAAgB,WAAW;IAC/B,uEAAuE;IAC9D,mBAAmB,CAAuB;IACnD,gBAAe,CAAC;IAmFhB,iFAAiF;IACjF,KAAK,CAAC,YAAY,CAAC,MAAe;QAChC,MAAM,IAAI,2BAA2B,CAAC,6CAA6C,CAAC,CAAC;IACvF,CAAC;IAiFD,kDAAkD;IAClD,KAAK,CAAC,mBAAmB,CACvB,QAAoC;QAEpC,MAAM,IAAI,2BAA2B,CAAC,oDAAoD,CAAC,CAAC;IAC9F,CAAC;IAED,wEAAwE;IACxE,KAAK,CAAC,WAAW,CAAC,MAAY,EAAE,IAAU;QACxC,MAAM,IAAI,2BAA2B,CAAC,4CAA4C,CAAC,CAAC;IACtF,CAAC;IACD,KAAK,CAAC,YAAY,CAAC,MAAY,EAAE,IAAU;QACzC,MAAM,IAAI,2BAA2B,CAAC,6CAA6C,CAA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A0B;QAE1B,MAAM,IAAI,2BAA2B,CAAC,8CAA8C,CAAC,CAAC;IACxF,CAAC;IACD,KAAK,CAAC,cAAc,CAAC,OAAe;QAClC,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,gBAAgB,CAAC,OAAe,EAAE,OAAe;QACrD,MAAM,IAAI,2BAA2B,CAAC,iDAAiD,CAAC,CAAC;IAC3F,CAAC;IACD,KAAK,CAAC,UAAU,CACd,OAAe,EACf,OAAe,EACf,OAAgB,EAChB,QAA2B;QAE3B,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;CACF","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport { CapabilityNotSupportedError } from \"../errors.js\";\nimport type {\n AddCreditsResult,\n AddTeamMemberResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n BillingMode,\n BucketBalancesResult,\n CheckFeatureResult,\n CreateTeamResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GrantProgramAwardResult,\n GetUserPlanResult,\n ListQuotaEventsOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n LeaseResult,\n LeasePricingContext,\n ListLedgerEntriesOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n LedgerPage,\n UsageChargePage,\n UsageRecordResult,\n CatalogRevisionSummary,\n CatalogRevision,\n RefundResult,\n RevokeCreditsResult,\n ReleaseResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamBalanceResult,\n TeamDeductionResult,\n TeamMember,\n TeamRole,\n TopUserRow,\n LedgerEntry,\n} from \"./types/index.js\";\nimport type { BursarConfigData, CatalogRollout } from \"../config.js\";\nimport type { ProviderEnvironment } from \"../providers/environment.js\";\nimport type {\n AddCreditsOptions,\n DeductTeamOptions,\n RefundCreditsOptions,\n} from \"./service-types.js\";\n\nexport interface OperationUsageOptions {\n /** Entitlement feature that must be enabled for the operation. */\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, unknown> | null;\n}\n\n/** Options for atomically acquiring a lease. */\nexport interface CreateLeaseOptions extends OperationUsageOptions {\n /**\n * Replay-safe acquisition key. Supplying the same key with the same request\n * returns the original lease; conflicting reuse is rejected.\n */\n idempotencyKey: string;\n billingMode?: BillingMode;\n floor?: Decimal;\n maxConcurrent?: number | null;\n overdraftFloor?: Decimal | null;\n ttlSeconds?: number;\n metadata?: CreditMetadata | null;\n}\n\n/** Options for charging the actual cost against a lease. */\nexport interface SettleLeaseOptions extends OperationUsageOptions {\n idempotencyKey?: string;\n metadata?: CreditMetadata | null;\n}\n\n/**\n * Abstract base for credit storage backends.\n *\n * Split into two tiers:\n * - **Core** (abstract, must be implemented): balance/credit ops, the atomic\n * lease lifecycle, bursar-config versioning, plan management,\n * refunds, and expiry sweeping. Every backend needs these.\n * - **Optional capabilities** (concrete, default-throwing): usage analytics,\n * ledger listing, and shared team-balance pools. A custom store that\n * doesn't need these can skip them entirely — the default implementation\n * throws {@link CapabilityNotSupportedError} instead of forcing a stub.\n */\nexport abstract class CreditStore {\n /** Optional provider namespace exposed by environment-aware stores. */\n readonly providerEnvironment?: ProviderEnvironment;\n constructor() {}\n\n abstract getBalance(userId: string): Promise<BalanceResult>;\n abstract addCredits(\n userId: string,\n amount: Decimal,\n options: AddCreditsOptions,\n ): Promise<AddCreditsResult>;\n /**\n * Atomically calculate-and-charge in one server-side transaction:\n * consume free allowance, enforce plan policy and quotas, and debit the net\n * amount, idempotency-keyed end-to-end.\n */\n abstract deductWithAllowance(\n userId: string,\n amount: Decimal,\n options: DeductWithAllowanceOptions,\n ): Promise<DeductionResult>;\n\n // ── Lease lifecycle (atomic admission) ─────────────────────────────\n //\n // The lease is the canonical admission primitive.\n // ``reserve``/``settle``/``release`` on the manager map onto these.\n // Leases reuse the credit_reservations table/records extended with a status\n // (active → settled | released | expired), a billing mode, and an overdraft\n // floor. ``available = balance − Σ(amount WHERE status='active' AND unexpired)``.\n\n /**\n * Atomically acquire a lease (hold) — the only authoritative admission control.\n *\n * Under one critical section the store: (1) ensures the balance row exists;\n * (2) enforces ``maxConcurrent`` by counting active leases for ``(userId,\n * operationType)``; (3) enforces plan entitlements and quotas; (4) computes\n * ``available = balance − Σ active holds`` and rejects with\n * ``error=\"insufficient_credits\"`` if ``available − amount < floor``; (5) inserts\n * an ``active`` lease expiring after ``ttlSeconds``. Business failures are\n * returned via ``LeaseResult.error``; the store never raises domain exceptions.\n */\n abstract createLease(\n userId: string,\n amount: Decimal,\n operationType: string,\n options: CreateLeaseOptions,\n ): Promise<LeaseResult>;\n\n /**\n * Charge the actual cost against a lease, then mark it settled.\n *\n * De-clamped: charges ``amount`` even if it exceeds the lease hold (overdraft)\n * and never clamps to the reserved ceiling. The balance may go negative in\n * overdraft. ``amount === 0`` releases the lease without charging.\n * Lease-state failures (``lease_not_found``/``lease_expired``) are returned via\n * ``DeductionResult.error``; a replay returns the original result idempotently.\n */\n abstract settleLease(\n userId: string,\n leaseId: string,\n amount: Decimal,\n options?: SettleLeaseOptions,\n ): Promise<DeductionResult>;\n\n /** Read the immutable catalog and rate card captured at lease admission. */\n abstract getLeasePricingContext(\n userId: string,\n leaseId: string,\n ): Promise<LeasePricingContext | null>;\n\n /**\n * Release a lease without charging; safe to repeat after failed or aborted work.\n *\n * Transitions an ``active``/``expired`` lease to ``released`` and reports\n * ``released=true``; otherwise reports ``released=false`` with a ``reason``.\n */\n abstract releaseLease(userId: string, leaseId: string): Promise<ReleaseResult>;\n\n /**\n * Extend an active lease's TTL (long batch/agentic jobs, resolves B4).\n *\n * Returns ``error=\"lease_expired\"`` if the TTL already elapsed and\n * ``error=\"lease_not_found\"`` if missing/other-user/finalized.\n */\n abstract renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseResult>;\n\n /** Expire a bounded batch of abandoned leases and release their reservations. */\n async expireLeases(_limit?: number): Promise<number> {\n throw new CapabilityNotSupportedError(\"expireLeases is not supported by this store\");\n }\n\n /**\n * Advisory, non-locking read of ``available = balance − Σ active holds``.\n *\n * For UI only — never an admission gate; may be stale the instant it is read.\n */\n\n abstract getAvailable(userId: string): Promise<AvailableResult>;\n\n abstract getActiveCatalog(): Promise<CatalogRevision | null>;\n abstract publishAndActivateCatalog(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string>;\n abstract publishCatalogDraft(config: BursarConfigData, label?: string | null): Promise<string>;\n\n // Catalog revision history and activation.\n abstract getCatalogHistory(): Promise<CatalogRevisionSummary[]>;\n abstract getCatalogRevision(version: number): Promise<CatalogRevision | null>;\n abstract activateCatalogRevision(\n version: number,\n rollout?: CatalogRollout | null,\n ): Promise<string>;\n\n abstract getUserPlan(userId: string): Promise<GetUserPlanResult>;\n abstract setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult>;\n abstract unsetUserPlan(userId: string): Promise<UnsetUserPlanResult>;\n abstract setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean>;\n abstract applyDuePlanChanges(limit?: number): Promise<number>;\n abstract startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult>;\n abstract migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult>;\n abstract checkFeature(userId: string, feature: string): Promise<CheckFeatureResult>;\n abstract getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]>;\n abstract listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]>;\n abstract checkAllowance(userId: string): Promise<AllowanceResult | null>;\n\n abstract revokeCreditsByEntryType(\n userId: string,\n entryType: string,\n ): Promise<RevokeCreditsResult>;\n\n // ── Refunds ────────────────────────────────────────────────────────\n abstract refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundResult>;\n\n // ── Credit expiry ────────────────────────────────────────────────────\n /**\n * Sweep expired credit grants and debit the aggregate/tier balances.\n *\n * When `userId` is omitted (default), sweeps globally across every user —\n * unchanged behaviour/output shape from before this parameter existed. When\n * given, restricts the scan/expiry to that user's transactions only (used by\n * bounded expiry sweep operation).\n */\n abstract sweepExpiredCredits(\n dryRun?: boolean,\n userId?: string,\n limit?: number,\n ): Promise<SweepResult>;\n\n // ── Credit buckets ─────────────────────────────────────────────────────\n /**\n * Per-bucket credit balances for a user (credit buckets).\n *\n * Sorted by `priority` ascending. When no buckets are configured, synthesizes\n * a single `\"default\"` entry from the aggregate balance so the shape is\n * uniform either way.\n */\n abstract getBucketBalances(userId: string): Promise<BucketBalancesResult>;\n\n /** Execute one configured grant-program event. */\n async executeGrantProgram(\n _request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n throw new CapabilityNotSupportedError(\"executeGrantProgram is not supported by this store\");\n }\n\n // ── Usage analytics (optional capability) ────────────────────────────\n async spendByUser(_start: Date, _end: Date): Promise<SpendByUserRow[]> {\n throw new CapabilityNotSupportedError(\"spendByUser is not supported by this store\");\n }\n async spendByModel(_start: Date, _end: Date): Promise<SpendByModelRow[]> {\n throw new CapabilityNotSupportedError(\"spendByModel is not supported by this store\");\n }\n async topUsers(_limit: number, _start: Date, _end: Date): Promise<TopUserRow[]> {\n throw new CapabilityNotSupportedError(\"topUsers is not supported by this store\");\n }\n async dailySpend(_start: Date, _end: Date): Promise<DailySpendRow[]> {\n throw new CapabilityNotSupportedError(\"dailySpend is not supported by this store\");\n }\n async aggregateStats(_start: Date, _end: Date): Promise<AggregateStats> {\n throw new CapabilityNotSupportedError(\"aggregateStats is not supported by this store\");\n }\n\n // ── Transaction listing (optional capability) ────────────────────────\n async listLedgerEntries(\n _userId: string,\n _options?: ListLedgerEntriesOptions,\n ): Promise<LedgerPage> {\n throw new CapabilityNotSupportedError(\"listLedgerEntries is not supported by this store\");\n }\n abstract listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage>;\n\n /** Read metered usage charges, including allowance-covered events. */\n async listUsageCharges(\n _userId: string,\n _options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n throw new CapabilityNotSupportedError(\"listUsageCharges is not supported by this store\");\n }\n\n /** Append priced usage telemetry without debiting the account again. */\n async recordUsage(\n _userId: string,\n _operation: string,\n _requested: Decimal,\n _options: DeductWithAllowanceOptions,\n ): Promise<UsageRecordResult> {\n throw new CapabilityNotSupportedError(\"recordUsage is not supported by this store\");\n }\n\n // ── Single transaction lookup (optional capability) ──────────────────\n /**\n * Fetch a single transaction by ID. Returns `null` when the transaction\n * does not exist or belongs to a different user.\n */\n async getLedgerEntry(_userId: string, _entryId: string): Promise<LedgerEntry | null> {\n throw new CapabilityNotSupportedError(\"getLedgerEntry is not supported by this store\");\n }\n\n // ── Team/shared balance pools (optional capability) ──────────────────\n async createTeam(\n _ownerSubjectId: string,\n _name: string,\n _initialBalance?: Decimal,\n ): Promise<CreateTeamResult> {\n throw new CapabilityNotSupportedError(\"createTeam is not supported by this store\");\n }\n async getTeamBalance(_teamId: string): Promise<TeamBalanceResult | null> {\n throw new CapabilityNotSupportedError(\"getTeamBalance is not supported by this store\");\n }\n async addTeamMember(\n _teamId: string,\n _userId: string,\n _role?: TeamRole,\n _spendCap?: Decimal | null,\n ): Promise<AddTeamMemberResult> {\n throw new CapabilityNotSupportedError(\"addTeamMember is not supported by this store\");\n }\n async getTeamMembers(_teamId: string): Promise<TeamMember[]> {\n throw new CapabilityNotSupportedError(\"getTeamMembers is not supported by this store\");\n }\n async removeTeamMember(_teamId: string, _userId: string): Promise<boolean> {\n throw new CapabilityNotSupportedError(\"removeTeamMember is not supported by this store\");\n }\n async deductTeam(\n _teamId: string,\n _userId: string,\n _amount: Decimal,\n _options: DeductTeamOptions,\n ): Promise<TeamDeductionResult> {\n throw new CapabilityNotSupportedError(\"deductTeam is not supported by this store\");\n }\n}\n"]}
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/credits/store.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAiG3D;;;;;;;;;;;GAWG;AACH,MAAM,OAAgB,WAAW;IAC/B,uEAAuE;IAC9D,mBAAmB,CAAuB;IACnD,gBAAe,CAAC;IAmFhB,iFAAiF;IACjF,KAAK,CAAC,YAAY,CAAC,MAAe;QAChC,MAAM,IAAI,2BAA2B,CAAC,6CAA6C,CAAC,CAAC;IACvF,CAAC;IAoFD,kDAAkD;IAClD,KAAK,CAAC,mBAAmB,CACvB,QAAoC;QAEpC,MAAM,IAAI,2BAA2B,CAAC,oDAAoD,CAAC,CAAC;IAC9F,CAAC;IAED,wEAAwE;IACxE,KAAK,CAAC,WAAW,CAAC,MAAY,EAAE,IAAU;QACxC,MAAM,IAAI,2BAA2B,CAAC,4CAA4C,CAAC,CAAC;IACtF,CAAC;IACD,KAAK,CAAC,YAAY,CAAC,MAAY,EAAE,IAAU;QACzC,MAAM,IAAI,2BAA2B,CAAC,6CAA6C,CAAC,CAAC;IACvF,CAAC;IACD,KAAK,CAAC,QAAQ,CAAC,MAAc,EAAE,MAAY,EAAE,IAAU;QACrD,MAAM,IAAI,2BAA2B,CAAC,yCAAyC,CAAC,CAAC;IACnF,CAAC;IACD,KAAK,CAAC,UAAU,CAAC,MAAY,EAAE,IAAU;QACvC,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;IACD,KAAK,CAAC,cAAc,CAAC,MAAY,EAAE,IAAU;QAC3C,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IAED,wEAAwE;IACxE,KAAK,CAAC,iBAAiB,CACrB,OAAe,EACf,QAAmC;QAEnC,MAAM,IAAI,2BAA2B,CAAC,kDAAkD,CAAC,CAAC;IAC5F,CAAC;IAGD,sEAAsE;IACtE,KAAK,CAAC,gBAAgB,CACpB,OAAe,EACf,QAAkC;QAElC,MAAM,IAAI,2BAA2B,CAAC,iDAAiD,CAAC,CAAC;IAC3F,CAAC;IAED,wEAAwE;IACxE,KAAK,CAAC,WAAW,CACf,OAAe,EACf,UAAkB,EAClB,UAAmB,EACnB,QAAoC;QAEpC,MAAM,IAAI,2BAA2B,CAAC,4CAA4C,CAAC,CAAC;IACtF,CAAC;IAED,wEAAwE;IACxE;;;OAGG;IACH,KAAK,CAAC,cAAc,CAAC,OAAe,EAAE,QAAgB;QACpD,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IAED,wEAAwE;IACxE,KAAK,CAAC,UAAU,CACd,eAAuB,EACvB,KAAa,EACb,QAA2B;QAE3B,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;IACD,KAAK,CAAC,cAAc,CAAC,OAAe;QAClC,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,aAAa,CACjB,OAAe,EACf,OAAe,EACf,KAAgB,EAChB,SAA0B;QAE1B,MAAM,IAAI,2BAA2B,CAAC,8CAA8C,CAAC,CAAC;IACxF,CAAC;IACD,KAAK,CAAC,cAAc,CAAC,OAAe;QAClC,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,gBAAgB,CAAC,OAAe,EAAE,OAAe;QACrD,MAAM,IAAI,2BAA2B,CAAC,iDAAiD,CAAC,CAAC;IAC3F,CAAC;IACD,KAAK,CAAC,UAAU,CACd,OAAe,EACf,OAAe,EACf,OAAgB,EAChB,QAA2B;QAE3B,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;CACF","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { JsonObject } from \"../shared/json.js\";\nimport { CapabilityNotSupportedError } from \"../errors.js\";\nimport type {\n AddCreditsResult,\n AddTeamMemberResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n BillingMode,\n BucketBalancesResult,\n CheckFeatureResult,\n CreateTeamResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GrantProgramAwardResult,\n GetUserPlanResult,\n ListQuotaEventsOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n LeaseResult,\n LeasePricingContext,\n ListLedgerEntriesOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n LedgerPage,\n UsageChargePage,\n UsageRecordResult,\n CatalogRevisionSummary,\n CatalogRevision,\n RefundResult,\n RevokeCreditsResult,\n ReleaseResult,\n SetUserPlanResult,\n UnsetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamBalanceResult,\n TeamDeductionResult,\n TeamMember,\n TeamRole,\n TopUserRow,\n LedgerEntry,\n} from \"./types/index.js\";\nimport type { BursarConfigData, CatalogRollout } from \"../config.js\";\nimport type { ProviderEnvironment } from \"../providers/environment.js\";\nimport type {\n AddCreditsOptions,\n DeductTeamOptions,\n RefundCreditsOptions,\n} from \"./service-types.js\";\n\nexport interface OperationUsageOptions {\n /** Entitlement feature that must be enabled for the operation. */\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, string | number | boolean | Decimal.Value> | null;\n dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;\n}\n\n/** Options for atomically acquiring a lease. */\nexport interface CreateLeaseOptions extends OperationUsageOptions {\n /**\n * Replay-safe acquisition key. Supplying the same key with the same request\n * returns the original lease; conflicting reuse is rejected.\n */\n idempotencyKey: string;\n billingMode?: BillingMode;\n floor?: Decimal;\n maxConcurrent?: number | null;\n overdraftFloor?: Decimal | null;\n ttlSeconds?: number;\n metadata?: CreditMetadata | null;\n}\n\n/** Options for replay-safe team creation. */\nexport interface CreateTeamOptions {\n /**\n * Caller-owned operation key. Reusing it with the same request returns the\n * original team; changing the owner, name, or balance is rejected.\n */\n idempotencyKey: string;\n initialBalance?: Decimal;\n}\n\n/** Options for charging the actual cost against a lease. */\nexport interface SettleLeaseOptions extends OperationUsageOptions {\n idempotencyKey?: string;\n metadata?: CreditMetadata | null;\n}\n\n/**\n * Abstract base for credit storage backends.\n *\n * Split into two tiers:\n * - **Core** (abstract, must be implemented): balance/credit ops, the atomic\n * lease lifecycle, bursar-config versioning, plan management,\n * refunds, and expiry sweeping. Every backend needs these.\n * - **Optional capabilities** (concrete, default-throwing): usage analytics,\n * ledger listing, and shared team-balance pools. A custom store that\n * doesn't need these can skip them entirely — the default implementation\n * throws {@link CapabilityNotSupportedError} instead of forcing a stub.\n */\nexport abstract class CreditStore {\n /** Optional provider namespace exposed by environment-aware stores. */\n readonly providerEnvironment?: ProviderEnvironment;\n constructor() {}\n\n abstract getBalance(userId: string): Promise<BalanceResult>;\n abstract addCredits(\n userId: string,\n amount: Decimal,\n options: AddCreditsOptions,\n ): Promise<AddCreditsResult>;\n /**\n * Atomically calculate-and-charge in one server-side transaction:\n * consume free allowance, enforce plan policy and quotas, and debit the net\n * amount, idempotency-keyed end-to-end.\n */\n abstract deductWithAllowance(\n userId: string,\n amount: Decimal,\n options: DeductWithAllowanceOptions,\n ): Promise<DeductionResult>;\n\n // ── Lease lifecycle (atomic admission) ─────────────────────────────\n //\n // The lease is the canonical admission primitive.\n // ``reserve``/``settle``/``release`` on the manager map onto these.\n // Leases reuse the credit_reservations table/records extended with a status\n // (active → settled | released | expired), a billing mode, and an overdraft\n // floor. ``available = balance − Σ(amount WHERE status='active' AND unexpired)``.\n\n /**\n * Atomically acquire a lease (hold) — the only authoritative admission control.\n *\n * Under one critical section the store: (1) ensures the balance row exists;\n * (2) enforces ``maxConcurrent`` by counting active leases for ``(userId,\n * operationType)``; (3) enforces plan entitlements and quotas; (4) computes\n * ``available = balance − Σ active holds`` and rejects with\n * ``error=\"insufficient_credits\"`` if ``available − amount < floor``; (5) inserts\n * an ``active`` lease expiring after ``ttlSeconds``. Business failures are\n * returned via ``LeaseResult.error``; the store never raises domain exceptions.\n */\n abstract createLease(\n userId: string,\n amount: Decimal,\n operationType: string,\n options: CreateLeaseOptions,\n ): Promise<LeaseResult>;\n\n /**\n * Charge the actual cost against a lease, then mark it settled.\n *\n * De-clamped: charges ``amount`` even if it exceeds the lease hold (overdraft)\n * and never clamps to the reserved ceiling. The balance may go negative in\n * overdraft. ``amount === 0`` releases the lease without charging.\n * Lease-state failures (``lease_not_found``/``lease_expired``) are returned via\n * ``DeductionResult.error``; a replay returns the original result idempotently.\n */\n abstract settleLease(\n userId: string,\n leaseId: string,\n amount: Decimal,\n options?: SettleLeaseOptions,\n ): Promise<DeductionResult>;\n\n /** Read the immutable catalog and rate card captured at lease admission. */\n abstract getLeasePricingContext(\n userId: string,\n leaseId: string,\n ): Promise<LeasePricingContext | null>;\n\n /**\n * Release a lease without charging; safe to repeat after failed or aborted work.\n *\n * Transitions an ``active``/``expired`` lease to ``released`` and reports\n * ``released=true``; otherwise reports ``released=false`` with a ``reason``.\n */\n abstract releaseLease(userId: string, leaseId: string): Promise<ReleaseResult>;\n\n /**\n * Extend an active lease's TTL (long batch/agentic jobs, resolves B4).\n *\n * Returns ``error=\"lease_expired\"`` if the TTL already elapsed and\n * ``error=\"lease_not_found\"`` if missing/other-user/finalized.\n */\n abstract renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseResult>;\n\n /** Expire a bounded batch of abandoned leases and release their reservations. */\n async expireLeases(_limit?: number): Promise<number> {\n throw new CapabilityNotSupportedError(\"expireLeases is not supported by this store\");\n }\n\n /**\n * Advisory, non-locking read of ``available = balance − Σ active holds``.\n *\n * For UI only — never an admission gate; may be stale the instant it is read.\n */\n\n abstract getAvailable(userId: string): Promise<AvailableResult>;\n\n abstract getActiveCatalog(): Promise<CatalogRevision | null>;\n abstract publishAndActivateCatalog(\n config: BursarConfigData | JsonObject,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string>;\n abstract publishCatalogDraft(\n config: BursarConfigData | JsonObject,\n label?: string | null,\n ): Promise<string>;\n\n // Catalog revision history and activation.\n abstract getCatalogHistory(): Promise<CatalogRevisionSummary[]>;\n abstract getCatalogRevision(version: number): Promise<CatalogRevision | null>;\n abstract activateCatalogRevision(\n version: number,\n rollout?: CatalogRollout | null,\n ): Promise<string>;\n\n abstract getUserPlan(userId: string): Promise<GetUserPlanResult>;\n abstract setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult>;\n abstract unsetUserPlan(userId: string): Promise<UnsetUserPlanResult>;\n abstract setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean>;\n abstract applyDuePlanChanges(limit?: number): Promise<number>;\n abstract startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult>;\n abstract migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult>;\n abstract checkFeature(userId: string, feature: string): Promise<CheckFeatureResult>;\n abstract getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]>;\n abstract listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]>;\n abstract checkAllowance(userId: string): Promise<AllowanceResult | null>;\n\n abstract revokeCreditsByEntryType(\n userId: string,\n entryType: string,\n ): Promise<RevokeCreditsResult>;\n\n // ── Refunds ────────────────────────────────────────────────────────\n abstract refundCredits(entryId: string, options: RefundCreditsOptions): Promise<RefundResult>;\n\n // ── Credit expiry ────────────────────────────────────────────────────\n /**\n * Sweep expired credit grants and debit the aggregate/tier balances.\n *\n * When `userId` is omitted (default), sweeps globally across every user —\n * unchanged behaviour/output shape from before this parameter existed. When\n * given, restricts the scan/expiry to that user's transactions only (used by\n * bounded expiry sweep operation).\n */\n abstract sweepExpiredCredits(\n dryRun?: boolean,\n userId?: string,\n limit?: number,\n ): Promise<SweepResult>;\n\n // ── Credit buckets ─────────────────────────────────────────────────────\n /**\n * Per-bucket credit balances for a user (credit buckets).\n *\n * Sorted by `priority` ascending. When no buckets are configured, synthesizes\n * a single `\"default\"` entry from the aggregate balance so the shape is\n * uniform either way.\n */\n abstract getBucketBalances(userId: string): Promise<BucketBalancesResult>;\n\n /** Execute one configured grant-program event. */\n async executeGrantProgram(\n _request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n throw new CapabilityNotSupportedError(\"executeGrantProgram is not supported by this store\");\n }\n\n // ── Usage analytics (optional capability) ────────────────────────────\n async spendByUser(_start: Date, _end: Date): Promise<SpendByUserRow[]> {\n throw new CapabilityNotSupportedError(\"spendByUser is not supported by this store\");\n }\n async spendByModel(_start: Date, _end: Date): Promise<SpendByModelRow[]> {\n throw new CapabilityNotSupportedError(\"spendByModel is not supported by this store\");\n }\n async topUsers(_limit: number, _start: Date, _end: Date): Promise<TopUserRow[]> {\n throw new CapabilityNotSupportedError(\"topUsers is not supported by this store\");\n }\n async dailySpend(_start: Date, _end: Date): Promise<DailySpendRow[]> {\n throw new CapabilityNotSupportedError(\"dailySpend is not supported by this store\");\n }\n async aggregateStats(_start: Date, _end: Date): Promise<AggregateStats> {\n throw new CapabilityNotSupportedError(\"aggregateStats is not supported by this store\");\n }\n\n // ── Transaction listing (optional capability) ────────────────────────\n async listLedgerEntries(\n _userId: string,\n _options?: ListLedgerEntriesOptions,\n ): Promise<LedgerPage> {\n throw new CapabilityNotSupportedError(\"listLedgerEntries is not supported by this store\");\n }\n abstract listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage>;\n\n /** Read metered usage charges, including allowance-covered events. */\n async listUsageCharges(\n _userId: string,\n _options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n throw new CapabilityNotSupportedError(\"listUsageCharges is not supported by this store\");\n }\n\n /** Append priced usage telemetry without debiting the account again. */\n async recordUsage(\n _userId: string,\n _operation: string,\n _requested: Decimal,\n _options: DeductWithAllowanceOptions,\n ): Promise<UsageRecordResult> {\n throw new CapabilityNotSupportedError(\"recordUsage is not supported by this store\");\n }\n\n // ── Single transaction lookup (optional capability) ──────────────────\n /**\n * Fetch a single transaction by ID. Returns `null` when the transaction\n * does not exist or belongs to a different user.\n */\n async getLedgerEntry(_userId: string, _entryId: string): Promise<LedgerEntry | null> {\n throw new CapabilityNotSupportedError(\"getLedgerEntry is not supported by this store\");\n }\n\n // ── Team/shared balance pools (optional capability) ──────────────────\n async createTeam(\n _ownerSubjectId: string,\n _name: string,\n _options: CreateTeamOptions,\n ): Promise<CreateTeamResult> {\n throw new CapabilityNotSupportedError(\"createTeam is not supported by this store\");\n }\n async getTeamBalance(_teamId: string): Promise<TeamBalanceResult | null> {\n throw new CapabilityNotSupportedError(\"getTeamBalance is not supported by this store\");\n }\n async addTeamMember(\n _teamId: string,\n _userId: string,\n _role?: TeamRole,\n _spendCap?: Decimal | null,\n ): Promise<AddTeamMemberResult> {\n throw new CapabilityNotSupportedError(\"addTeamMember is not supported by this store\");\n }\n async getTeamMembers(_teamId: string): Promise<TeamMember[]> {\n throw new CapabilityNotSupportedError(\"getTeamMembers is not supported by this store\");\n }\n async removeTeamMember(_teamId: string, _userId: string): Promise<boolean> {\n throw new CapabilityNotSupportedError(\"removeTeamMember is not supported by this store\");\n }\n async deductTeam(\n _teamId: string,\n _userId: string,\n _amount: Decimal,\n _options: DeductTeamOptions,\n ): Promise<TeamDeductionResult> {\n throw new CapabilityNotSupportedError(\"deductTeam is not supported by this store\");\n }\n}\n"]}
@@ -1,8 +1,9 @@
1
1
  import type { Decimal } from "decimal.js";
2
+ import type { StructuredValue } from "../../shared/json.js";
2
3
  export type BillingMode = "strict" | "overdraft";
3
4
  export interface CreditMetadata {
4
5
  operation?: string | null;
5
- measures?: Record<string, unknown> | null;
6
+ measures?: Record<string, string | number | boolean | Decimal.Value> | null;
6
7
  dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;
7
8
  breakdownTotal?: string | null;
8
9
  referenceType?: string | null;
@@ -11,7 +12,7 @@ export interface CreditMetadata {
11
12
  providerRequestId?: string | null;
12
13
  traceId?: string | null;
13
14
  spanId?: string | null;
14
- [key: string]: unknown;
15
+ [key: string]: StructuredValue;
15
16
  }
16
17
  export interface BucketDefinition {
17
18
  label: string;
@@ -79,8 +80,8 @@ export interface DeductWithAllowanceOptions {
79
80
  feature?: string | null;
80
81
  model?: string | null;
81
82
  region?: string | null;
82
- measures?: Record<string, unknown> | null;
83
- dimensions?: Record<string, unknown> | null;
83
+ measures?: Record<string, string | number | boolean | Decimal.Value> | null;
84
+ dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;
84
85
  metadata?: CreditMetadata | null;
85
86
  }
86
87
  interface RefundResultBase {
@@ -1 +1 @@
1
- {"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;AAEjD,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAC1C,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;IAC9E,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,OAAO,CAAC,EAAE,MA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M,CAAC;IACrB,aAAa,EAAE,OAAO,CAAC;IACvB,MAAM,EAAE,OAAO,CAAC;IAChB,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC1C"}
@@ -1 +1 @@
1
- {"version":3,"file":"account.js","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport type BillingMode = \"strict\" | \"overdraft\";\n\nexport interface CreditMetadata {\n operation?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;\n breakdownTotal?: string | null;\n referenceType?: string | null;\n referenceId?: string | null;\n idempotencyKey?: string | null;\n providerRequestId?: string | null;\n traceId?: string | null;\n spanId?: string | null;\n [key: string]: unknown;\n}\n\nexport interface BucketDefinition {\n label: string;\n priority: number;\n expires: boolean;\n ttlDays?: number | null;\n allowOverdraft?: boolean;\n default?: boolean;\n}\n\nexport interface BucketBalance {\n bucketKey: string;\n label: string;\n priority: number;\n expires: boolean;\n balance: Decimal;\n}\n\nexport interface BucketBalancesResult {\n userId: string;\n buckets: BucketBalance[];\n totalBalance: Decimal;\n}\n\nexport interface BalanceResult {\n userId: string;\n balance: Decimal;\n lifetimePurchased: Decimal;\n}\n\nexport interface AddCreditsResult {\n entryId: string;\n userId: string;\n amount: Decimal;\n newBalance: Decimal;\n lifetimePurchased: Decimal;\n /** Destination bucket for grants; `null` when a debit spans one or more lots. */\n bucket: string | null;\n idempotent: boolean;\n}\n\ninterface DeductionResultBase {\n userId: string;\n amount: Decimal;\n allowanceConsumed: Decimal;\n idempotent: boolean;\n}\n\n/** A committed usage charge. Allowance-only charges legitimately have no ledger entry. */\nexport interface DeductionSuccess extends DeductionResultBase {\n error: null;\n entryId: string | null;\n /** Canonical usage receipt, including zero-cost or allowance-only charges. */\n usageChargeId: string | null;\n balanceAfter: Decimal;\n bucketBreakdown: Record<string, Decimal> | null;\n}\n\n/** An expected database rejection. Nullable fields were not committed and are not fabricated. */\nexport interface DeductionFailure extends DeductionResultBase {\n error: string;\n entryId: null;\n usageChargeId: string | null;\n balanceAfter: Decimal | null;\n idempotent: false;\n bucketBreakdown: null;\n}\n\nexport type DeductionResult = DeductionSuccess | DeductionFailure;\n\nexport interface DeductWithAllowanceOptions {\n idempotencyKey: string;\n operation?: string | null;\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, unknown> | null;\n metadata?: CreditMetadata | null;\n}\n\ninterface RefundResultBase {\n originalEntryId: string;\n userId: string | null;\n}\n\nexport interface RefundSuccess extends RefundResultBase {\n error: null;\n refundEntryId: string;\n userId: string;\n amount: Decimal;\n newBalance: Decimal;\n bucketBreakdown: Record<string, Decimal> | null;\n}\n\nexport interface RefundFailure extends RefundResultBase {\n error: string;\n refundEntryId: null;\n amount: Decimal | null;\n newBalance: Decimal | null;\n bucketBreakdown: null;\n}\n\nexport type RefundResult = RefundSuccess | RefundFailure;\n\n/** Credits removed from all remaining lots created by one ledger operation. */\nexport interface RevokeCreditsResult {\n userId: string;\n entryType: string;\n revoked: Decimal;\n balanceAfter: Decimal;\n}\n\nexport interface SweepResult {\n expiredCount: number;\n expiredAmount: Decimal;\n dryRun: boolean;\n expiredByBucket: Record<string, Decimal>;\n}\n"]}
1
+ {"version":3,"file":"account.js","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { StructuredValue } from \"../../shared/json.js\";\n\nexport type BillingMode = \"strict\" | \"overdraft\";\n\nexport interface CreditMetadata {\n operation?: string | null;\n measures?: Record<string, string | number | boolean | Decimal.Value> | null;\n dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;\n breakdownTotal?: string | null;\n referenceType?: string | null;\n referenceId?: string | null;\n idempotencyKey?: string | null;\n providerRequestId?: string | null;\n traceId?: string | null;\n spanId?: string | null;\n [key: string]: StructuredValue;\n}\n\nexport interface BucketDefinition {\n label: string;\n priority: number;\n expires: boolean;\n ttlDays?: number | null;\n allowOverdraft?: boolean;\n default?: boolean;\n}\n\nexport interface BucketBalance {\n bucketKey: string;\n label: string;\n priority: number;\n expires: boolean;\n balance: Decimal;\n}\n\nexport interface BucketBalancesResult {\n userId: string;\n buckets: BucketBalance[];\n totalBalance: Decimal;\n}\n\nexport interface BalanceResult {\n userId: string;\n balance: Decimal;\n lifetimePurchased: Decimal;\n}\n\nexport interface AddCreditsResult {\n entryId: string;\n userId: string;\n amount: Decimal;\n newBalance: Decimal;\n lifetimePurchased: Decimal;\n /** Destination bucket for grants; `null` when a debit spans one or more lots. */\n bucket: string | null;\n idempotent: boolean;\n}\n\ninterface DeductionResultBase {\n userId: string;\n amount: Decimal;\n allowanceConsumed: Decimal;\n idempotent: boolean;\n}\n\n/** A committed usage charge. Allowance-only charges legitimately have no ledger entry. */\nexport interface DeductionSuccess extends DeductionResultBase {\n error: null;\n entryId: string | null;\n /** Canonical usage receipt, including zero-cost or allowance-only charges. */\n usageChargeId: string | null;\n balanceAfter: Decimal;\n bucketBreakdown: Record<string, Decimal> | null;\n}\n\n/** An expected database rejection. Nullable fields were not committed and are not fabricated. */\nexport interface DeductionFailure extends DeductionResultBase {\n error: string;\n entryId: null;\n usageChargeId: string | null;\n balanceAfter: Decimal | null;\n idempotent: false;\n bucketBreakdown: null;\n}\n\nexport type DeductionResult = DeductionSuccess | DeductionFailure;\n\nexport interface DeductWithAllowanceOptions {\n idempotencyKey: string;\n operation?: string | null;\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, string | number | boolean | Decimal.Value> | null;\n dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;\n metadata?: CreditMetadata | null;\n}\n\ninterface RefundResultBase {\n originalEntryId: string;\n userId: string | null;\n}\n\nexport interface RefundSuccess extends RefundResultBase {\n error: null;\n refundEntryId: string;\n userId: string;\n amount: Decimal;\n newBalance: Decimal;\n bucketBreakdown: Record<string, Decimal> | null;\n}\n\nexport interface RefundFailure extends RefundResultBase {\n error: string;\n refundEntryId: null;\n amount: Decimal | null;\n newBalance: Decimal | null;\n bucketBreakdown: null;\n}\n\nexport type RefundResult = RefundSuccess | RefundFailure;\n\n/** Credits removed from all remaining lots created by one ledger operation. */\nexport interface RevokeCreditsResult {\n userId: string;\n entryType: string;\n revoked: Decimal;\n balanceAfter: Decimal;\n}\n\nexport interface SweepResult {\n expiredCount: number;\n expiredAmount: Decimal;\n dryRun: boolean;\n expiredByBucket: Record<string, Decimal>;\n}\n"]}
@@ -1,7 +1,8 @@
1
1
  import type { Decimal } from "decimal.js";
2
+ import type { JsonObject } from "../../shared/json.js";
2
3
  export interface CatalogRevision {
3
4
  id: string;
4
- config: Record<string, unknown>;
5
+ config: JsonObject;
5
6
  version: number;
6
7
  }
7
8
  export interface CatalogRevisionSummary {
@@ -1 +1 @@
1
- {"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../../src/credits/types/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,sBAAsB;IACrC,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,OAAO,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,QAAQ,GAAG,QAAQ,GAAG,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;IAC5E,UAAU,E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,QAAQ,GAAG,IAAI,CAAC;IAChF,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,qBAAqB,EAAE,OAAO,CAAC;IAC/B,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B;AAED,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,IAAI,CAAC;IACrB,eAAe,EAAE,SAAS,GAAG,WAAW,CAAC;CAC1C;AAED,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,wBAAwB;IACvC,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,wBAAwB;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,OAAO,CAAC;IACd,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B"}
@@ -1 +1 @@
1
- {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../../src/credits/types/catalog.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport interface CatalogRevision {\n id: string;\n config: Record<string, unknown>;\n version: number;\n}\n\nexport interface CatalogRevisionSummary {\n id: string;\n version: number;\n label: string | null;\n active: boolean;\n createdAt: string;\n}\n\nexport interface PlanAllowancePolicy {\n amount: Decimal;\n priority: number;\n resetUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n resetCount: number;\n resetAnchor: \"calendar\" | \"plan_assignment\" | \"rolling\";\n resetTimezone: string;\n}\n\nexport interface PlanCreditPolicy {\n type: \"prepaid\" | \"credit_line\";\n creditLimit: Decimal | null;\n}\n\nexport interface PlanAdmissionPolicy {\n maxInFlight: number | null;\n operations: Record<string, { maxInFlight: number | null }>;\n}\n\nexport interface AllowanceResult {\n planId: string;\n allowanceRemaining: Decimal;\n periodStart: string;\n periodEnd: string;\n}\n\nexport interface GetUserPlanResult {\n userId: string;\n planId: string | null;\n planKey: string | null;\n planLabel: string | null;\n allowance: PlanAllowancePolicy | null;\n entitlements: Record<string, { value: unknown }>;\n rateCard: string | null;\n creditPolicy: PlanCreditPolicy | null;\n admission: PlanAdmissionPolicy | null;\n allowedOperations: string[];\n planAssignedAt: Date | null;\n planAssignmentEndsAt: Date | null;\n assignmentSourceType: \"manual\" | \"subscription\" | \"migration\" | \"system\" | null;\n assignmentSourceId: string | null;\n catalogRevisionPinned: boolean;\n catalogVersion: number | null;\n}\n\nexport interface SetUserPlanResult {\n userId: string;\n planId: string;\n planKey: string;\n planAssignedAt: Date;\n assignmentState: \"applied\" | \"scheduled\";\n}\n\nexport interface UnsetUserPlanResult {\n userId: string;\n}\n\nexport interface PlanMigrationStartResult {\n migrationId: string;\n}\n\nexport interface PlanMigrationBatchResult {\n migrated: number;\n done: boolean;\n nextCursor: string | null;\n}\n"]}
1
+ {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../../src/credits/types/catalog.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { JsonObject } from \"../../shared/json.js\";\n\nexport interface CatalogRevision {\n id: string;\n config: JsonObject;\n version: number;\n}\n\nexport interface CatalogRevisionSummary {\n id: string;\n version: number;\n label: string | null;\n active: boolean;\n createdAt: string;\n}\n\nexport interface PlanAllowancePolicy {\n amount: Decimal;\n priority: number;\n resetUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n resetCount: number;\n resetAnchor: \"calendar\" | \"plan_assignment\" | \"rolling\";\n resetTimezone: string;\n}\n\nexport interface PlanCreditPolicy {\n type: \"prepaid\" | \"credit_line\";\n creditLimit: Decimal | null;\n}\n\nexport interface PlanAdmissionPolicy {\n maxInFlight: number | null;\n operations: Record<string, { maxInFlight: number | null }>;\n}\n\nexport interface AllowanceResult {\n planId: string;\n allowanceRemaining: Decimal;\n periodStart: string;\n periodEnd: string;\n}\n\nexport interface GetUserPlanResult {\n userId: string;\n planId: string | null;\n planKey: string | null;\n planLabel: string | null;\n allowance: PlanAllowancePolicy | null;\n entitlements: Record<string, { value: unknown }>;\n rateCard: string | null;\n creditPolicy: PlanCreditPolicy | null;\n admission: PlanAdmissionPolicy | null;\n allowedOperations: string[];\n planAssignedAt: Date | null;\n planAssignmentEndsAt: Date | null;\n assignmentSourceType: \"manual\" | \"subscription\" | \"migration\" | \"system\" | null;\n assignmentSourceId: string | null;\n catalogRevisionPinned: boolean;\n catalogVersion: number | null;\n}\n\nexport interface SetUserPlanResult {\n userId: string;\n planId: string;\n planKey: string;\n planAssignedAt: Date;\n assignmentState: \"applied\" | \"scheduled\";\n}\n\nexport interface UnsetUserPlanResult {\n userId: string;\n}\n\nexport interface PlanMigrationStartResult {\n migrationId: string;\n}\n\nexport interface PlanMigrationBatchResult {\n migrated: number;\n done: boolean;\n nextCursor: string | null;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"grants.d.ts","sourceRoot":"","sources":["../../../src/credits/types/grants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAEnD,MAAM,MAAM,mBAAmB,GAC7B,iBAAiB,GAAG,oBAAoB,GAAG,qBAAqB,GAAG,QAAQ,CAAC;AAE9E,uEAAuE;AACvE,MAAM,WAAW,0BAA0B;IACzC,OAAO,EAAE,mBAAmB,CAAC;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,QAAQ,CAAC,EAAE,cAAc,GAAG,IAAI,CAAC;CAClC;AAED,UAAU,qBAAqB;IAC7B,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B,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,iEAAiE;AACjE,MAAM,WAAW,wBAAyB,SAAQ,qBAAqB;IACrE,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,OAAO,CAAC;IAChB,KAAK,EAAE,IAAI,CAAC;CACb;AAED,mFAAmF;AACnF,MAAM,WAAW,wBAAyB,SAAQ,qBAAqB;IACrE,YAAY,EAAE,IAAI,CAAC;IACnB,YAAY,EAAE,IAAI,CAAC;IACnB,kBAAkB,EAAE,IAAI,CAAC;IACzB,aAAa,EAAE,IAAI,CAAC;IACpB,MAAM,EAAE,IAAI,CAAC;IACb,QAAQ,EAAE,KAAK,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,MAAM,uBAAuB,GAAG,wBAAwB,GAAG,wBAAwB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"grants.js","sourceRoot":"","sources":["../../../src/credits/types/grants.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { CreditMetadata } from \"./account.js\";\n\nexport type GrantProgramTrigger =\n \"account_created\" | \"referral_completed\" | \"promo_code_redeemed\" | \"manual\";\n\n/** One application event that may award one or more catalog grants. */\nexport interface ExecuteGrantProgramRequest {\n trigger: GrantProgramTrigger;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId?: string | null;\n region?: string | null;\n metadata?: CreditMetadata | null;\n}\n\ninterface GrantProgramAwardBase {\n replayed: boolean;\n}\n\n/** One committed award produced by a grant-program execution. */\nexport interface GrantProgramAwardSuccess extends GrantProgramAwardBase {\n grantEventId: string;\n grantAwardId: string;\n recipientSubjectId: string;\n ledgerEntryId: string;\n amount: Decimal;\n error: null;\n}\n\n/** A rejected grant-program execution. No financial identifiers are fabricated. */\nexport interface GrantProgramAwardFailure extends GrantProgramAwardBase {\n grantEventId: null;\n grantAwardId: null;\n recipientSubjectId: null;\n ledgerEntryId: null;\n amount: null;\n replayed: false;\n error: string;\n}\n\nexport type GrantProgramAwardResult = GrantProgramAwardSuccess | GrantProgramAwardFailure;\n"]}
1
+ {"version":3,"file":"grants.js","sourceRoot":"","sources":["../../../src/credits/types/grants.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { CreditMetadata } from \"./account.js\";\n\nexport type GrantProgramTrigger =\n | \"account_created\"\n | \"referral_completed\"\n | \"promo_code_redeemed\"\n | \"manual\";\n\n/** One application event that may award one or more catalog grants. */\nexport interface ExecuteGrantProgramRequest {\n trigger: GrantProgramTrigger;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId?: string | null;\n region?: string | null;\n metadata?: CreditMetadata | null;\n}\n\ninterface GrantProgramAwardBase {\n replayed: boolean;\n}\n\n/** One committed award produced by a grant-program execution. */\nexport interface GrantProgramAwardSuccess extends GrantProgramAwardBase {\n grantEventId: string;\n grantAwardId: string;\n recipientSubjectId: string;\n ledgerEntryId: string;\n amount: Decimal;\n error: null;\n}\n\n/** A rejected grant-program execution. No financial identifiers are fabricated. */\nexport interface GrantProgramAwardFailure extends GrantProgramAwardBase {\n grantEventId: null;\n grantAwardId: null;\n recipientSubjectId: null;\n ledgerEntryId: null;\n amount: null;\n replayed: false;\n error: string;\n}\n\nexport type GrantProgramAwardResult = GrantProgramAwardSuccess | GrantProgramAwardFailure;\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { Decimal } from "decimal.js";
2
+ import type { JsonObject } from "../../shared/json.js";
2
3
  /** One immutable monetary entry on a canonical credit account. */
3
4
  export interface LedgerEntry {
4
5
  entryId: string;
@@ -9,7 +10,7 @@ export interface LedgerEntry {
9
10
  operation: string;
10
11
  referenceEntryId: string | null;
11
12
  idempotencyKey: string | null;
12
- metadata: Record<string, unknown> | null;
13
+ metadata: JsonObject | null;
13
14
  createdAt: string;
14
15
  }
15
16
  /** Stable position in an account ledger. */
@@ -51,7 +52,7 @@ export interface UsageCharge {
51
52
  region: string | null;
52
53
  eventAt: string;
53
54
  idempotencyKey: string;
54
- metadata: Record<string, unknown> | null;
55
+ metadata: JsonObject | null;
55
56
  createdAt: string;
56
57
  }
57
58
  export interface UsageChargeCursor {
@@ -1 +1 @@
1
- {"version":3,"file":"ledger.d.ts","sourceRoot":"","sources":["../../../src/credits/types/ledger.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAI1C,kEAAkE;AAClE,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACzC,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,4CAA4C;AAC5C,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,8DAA8D;AAC9D,MAAM,WAAW,wBAAwB;IACvC,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,QAAQ,CAAC,EAAE,IAAI,CAAC;IAChB,MAAM,CAAC,EAAE,IAAI,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,YAAY,GAAG,IAAI,CAAC;CAC9B;AAED,8BAA8B;AAC9B,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,WAAW,EAAE,CAAC;IACrB,UAAU,EAAE,YAAY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E,WAAW,EAAE,CAAC;IACrB,UAAU,EAAE,iBAAiB,GAAG,IAAI,CAAC;CACtC;AAED,gFAAgF;AAChF,UAAU,qBAAqB;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,OAAO,CAAC;IACnB,UAAU,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,kBAAmB,SAAQ,qBAAqB;IAC/D,KAAK,EAAE,IAAI,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,kBAAmB,SAAQ,qBAAqB;IAC/D,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,IAAI,CAAC;IACd,UAAU,EAAE,KAAK,CAAC;CACnB;AAED,MAAM,MAAM,iBAAiB,GAAG,kBAAkB,GAAG,kBAAkB,CAAC;AAExE,0DAA0D;AAC1D,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,EAAE,IAAI,CAAC;IAChB,MAAM,CAAC,EAAE,IAAI,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,YAAY,GAAG,IAAI,CAAC;CAC9B"}
@@ -1 +1 @@
1
- {"version":3,"file":"ledger.js","sourceRoot":"","sources":["../../../src/credits/types/ledger.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\n// ── Canonical ledger history ─────────────────────────────────────────\n\n/** One immutable monetary entry on a canonical credit account. */\nexport interface LedgerEntry {\n entryId: string;\n accountId: string;\n actorUserId: string | null;\n amount: Decimal;\n entryType: string;\n operation: string;\n referenceEntryId: string | null;\n idempotencyKey: string | null;\n metadata: Record<string, unknown> | null;\n createdAt: string;\n}\n\n/** Stable position in an account ledger. */\nexport interface LedgerCursor {\n createdAt: string;\n entryId: string;\n}\n\n/** Cursor-only options for listing account ledger entries. */\nexport interface ListLedgerEntriesOptions {\n entryTypes?: string[];\n fromDate?: Date;\n toDate?: Date;\n limit?: number;\n cursor?: LedgerCursor | null;\n}\n\n/** One stable cursor page. */\nexport interface LedgerPage {\n items: LedgerEntry[];\n nextCursor: LedgerCursor | null;\n}\n\n/**\n * A metered usage charge from the usage charge journal.\n *\n * Usage charges are deliberately separate from ledger entries: included\n * allowance consumption does not create a monetary ledger debit, but it is\n * still a billable usage event that belongs in the usage history.\n */\nexport interface UsageCharge {\n usageId: string;\n accountId: string;\n operation: string;\n requested: Decimal;\n charged: Decimal;\n allowanceRequested: Decimal;\n allowanceCovered: Decimal;\n billingDisposition: \"billable\" | \"record_only\";\n feature: string | null;\n model: string | null;\n region: string | null;\n eventAt: string;\n idempotencyKey: string;\n metadata: Record<string, unknown> | null;\n createdAt: string;\n}\n\nexport interface UsageChargeCursor {\n eventAt: string;\n usageId: string;\n}\n\nexport interface ListUsageChargesOptions {\n fromDate?: Date;\n toDate?: Date;\n limit?: number;\n cursor?: UsageChargeCursor | null;\n includeRecordOnly?: boolean;\n}\n\nexport interface UsageChargePage {\n items: UsageCharge[];\n nextCursor: UsageChargeCursor | null;\n}\n\n/** Result of appending a usage event without creating another balance debit. */\ninterface UsageRecordResultBase {\n userId: string;\n requested: Decimal;\n idempotent: boolean;\n}\n\nexport interface UsageRecordSuccess extends UsageRecordResultBase {\n error: null;\n usageId: string;\n}\n\nexport interface UsageRecordFailure extends UsageRecordResultBase {\n error: string;\n usageId: null;\n idempotent: false;\n}\n\nexport type UsageRecordResult = UsageRecordSuccess | UsageRecordFailure;\n\n/** Cursor-only options for the usage-only ledger view. */\nexport interface ListUsageEntriesOptions {\n fromDate?: Date;\n toDate?: Date;\n limit?: number;\n cursor?: LedgerCursor | null;\n}\n"]}
1
+ {"version":3,"file":"ledger.js","sourceRoot":"","sources":["../../../src/credits/types/ledger.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { JsonObject } from \"../../shared/json.js\";\n\n// ── Canonical ledger history ─────────────────────────────────────────\n\n/** One immutable monetary entry on a canonical credit account. */\nexport interface LedgerEntry {\n entryId: string;\n accountId: string;\n actorUserId: string | null;\n amount: Decimal;\n entryType: string;\n operation: string;\n referenceEntryId: string | null;\n idempotencyKey: string | null;\n metadata: JsonObject | null;\n createdAt: string;\n}\n\n/** Stable position in an account ledger. */\nexport interface LedgerCursor {\n createdAt: string;\n entryId: string;\n}\n\n/** Cursor-only options for listing account ledger entries. */\nexport interface ListLedgerEntriesOptions {\n entryTypes?: string[];\n fromDate?: Date;\n toDate?: Date;\n limit?: number;\n cursor?: LedgerCursor | null;\n}\n\n/** One stable cursor page. */\nexport interface LedgerPage {\n items: LedgerEntry[];\n nextCursor: LedgerCursor | null;\n}\n\n/**\n * A metered usage charge from the usage charge journal.\n *\n * Usage charges are deliberately separate from ledger entries: included\n * allowance consumption does not create a monetary ledger debit, but it is\n * still a billable usage event that belongs in the usage history.\n */\nexport interface UsageCharge {\n usageId: string;\n accountId: string;\n operation: string;\n requested: Decimal;\n charged: Decimal;\n allowanceRequested: Decimal;\n allowanceCovered: Decimal;\n billingDisposition: \"billable\" | \"record_only\";\n feature: string | null;\n model: string | null;\n region: string | null;\n eventAt: string;\n idempotencyKey: string;\n metadata: JsonObject | null;\n createdAt: string;\n}\n\nexport interface UsageChargeCursor {\n eventAt: string;\n usageId: string;\n}\n\nexport interface ListUsageChargesOptions {\n fromDate?: Date;\n toDate?: Date;\n limit?: number;\n cursor?: UsageChargeCursor | null;\n includeRecordOnly?: boolean;\n}\n\nexport interface UsageChargePage {\n items: UsageCharge[];\n nextCursor: UsageChargeCursor | null;\n}\n\n/** Result of appending a usage event without creating another balance debit. */\ninterface UsageRecordResultBase {\n userId: string;\n requested: Decimal;\n idempotent: boolean;\n}\n\nexport interface UsageRecordSuccess extends UsageRecordResultBase {\n error: null;\n usageId: string;\n}\n\nexport interface UsageRecordFailure extends UsageRecordResultBase {\n error: string;\n usageId: null;\n idempotent: false;\n}\n\nexport type UsageRecordResult = UsageRecordSuccess | UsageRecordFailure;\n\n/** Cursor-only options for the usage-only ledger view. */\nexport interface ListUsageEntriesOptions {\n fromDate?: Date;\n toDate?: Date;\n limit?: number;\n cursor?: LedgerCursor | null;\n}\n"]}
@@ -26,6 +26,7 @@ export interface TeamBalanceResult {
26
26
  export interface CreateTeamResult {
27
27
  teamId: string;
28
28
  name: string;
29
+ idempotent: boolean;
29
30
  }
30
31
  /** Result of adding a team member. */
31
32
  export interface AddTeamMemberResult {
@@ -1 +1 @@
1
- {"version":3,"file":"teams.d.ts","sourceRoot":"","sources":["../../../src/credits/types/teams.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,OAAO,GAAG,QAAQ,CAAC;AAGpD,gDAAgD;AAChD,MAAM,WAAW,IAAI;IACnB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,OAAO,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,mDAAmD;AACnD,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,QAAQ,CAAC;IACf,QAAQ,EAAE,OAAO,GAAG,IAAI,CAAC;IACzB,UAAU,EAAE,OAAO,CAAC;CACrB;AAED,uCAAuC;AACvC,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,OAAO,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,iCAAiC;AACjC,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;CACd;AAED,sCAAsC;AACtC,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,QAAQ,CAAC;CAChB;AAED,oDAAoD;AACp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;IACjB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,iCAAiC;AACjC,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,OAAO,CAAC;CACrB;AAED,sCAAsC;AACtC,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,QAAQ,CAAC;CAChB;AAED,oDAAoD;AACpD,UAAU,uBAAuB;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,OAAO,CAAC;IAChB,UAAU,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,oBAAqB,SAAQ,uBAAuB;IACnE,KAAK,EAAE,IAAI,CAAC;IACZ,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,gBAAgB,EAAE,OAAO,CAAC;CAC3B;AAED,MAAM,WAAW,oBAAqB,SAAQ,uBAAuB;IACnE,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,IAAI,CAAC;IACd,gBAAgB,EAAE,OAAO,GAAG,IAAI,CAAC;IACjC,UAAU,EAAE,KAAK,CAAC;CACnB;AAED,MAAM,MAAM,mBAAmB,GAAG,oBAAoB,GAAG,oBAAoB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"teams.js","sourceRoot":"","sources":["../../../src/credits/types/teams.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport type TeamRole = \"owner\" | \"admin\" | \"member\";\n\n// ── Team/shared balance pools ─────────────────────────────────────────\n/** A team with a shared credit balance pool. */\nexport interface Team {\n id: string;\n name: string;\n balance: Decimal;\n memberCount: number;\n createdAt: string;\n}\n\n/** A member of a team, with optional spend cap. */\nexport interface TeamMember {\n userId: string;\n role: TeamRole;\n spendCap: Decimal | null;\n totalSpent: Decimal;\n}\n\n/** Result of fetching team balance. */\nexport interface TeamBalanceResult {\n teamId: string;\n name: string;\n balance: Decimal;\n memberCount: number;\n}\n\n/** Result of creating a team. */\nexport interface CreateTeamResult {\n teamId: string;\n name: string;\n}\n\n/** Result of adding a team member. */\nexport interface AddTeamMemberResult {\n teamId: string;\n userId: string;\n role: TeamRole;\n}\n\n/** Result of deducting credits from a team pool. */\ninterface TeamDeductionResultBase {\n teamId: string;\n userId: string;\n amount: Decimal;\n idempotent: boolean;\n}\n\nexport interface TeamDeductionSuccess extends TeamDeductionResultBase {\n error: null;\n entryId: string | null;\n teamBalanceAfter: Decimal;\n}\n\nexport interface TeamDeductionFailure extends TeamDeductionResultBase {\n error: string;\n entryId: null;\n teamBalanceAfter: Decimal | null;\n idempotent: false;\n}\n\nexport type TeamDeductionResult = TeamDeductionSuccess | TeamDeductionFailure;\n"]}
1
+ {"version":3,"file":"teams.js","sourceRoot":"","sources":["../../../src/credits/types/teams.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport type TeamRole = \"owner\" | \"admin\" | \"member\";\n\n// ── Team/shared balance pools ─────────────────────────────────────────\n/** A team with a shared credit balance pool. */\nexport interface Team {\n id: string;\n name: string;\n balance: Decimal;\n memberCount: number;\n createdAt: string;\n}\n\n/** A member of a team, with optional spend cap. */\nexport interface TeamMember {\n userId: string;\n role: TeamRole;\n spendCap: Decimal | null;\n totalSpent: Decimal;\n}\n\n/** Result of fetching team balance. */\nexport interface TeamBalanceResult {\n teamId: string;\n name: string;\n balance: Decimal;\n memberCount: number;\n}\n\n/** Result of creating a team. */\nexport interface CreateTeamResult {\n teamId: string;\n name: string;\n idempotent: boolean;\n}\n\n/** Result of adding a team member. */\nexport interface AddTeamMemberResult {\n teamId: string;\n userId: string;\n role: TeamRole;\n}\n\n/** Result of deducting credits from a team pool. */\ninterface TeamDeductionResultBase {\n teamId: string;\n userId: string;\n amount: Decimal;\n idempotent: boolean;\n}\n\nexport interface TeamDeductionSuccess extends TeamDeductionResultBase {\n error: null;\n entryId: string | null;\n teamBalanceAfter: Decimal;\n}\n\nexport interface TeamDeductionFailure extends TeamDeductionResultBase {\n error: string;\n entryId: null;\n teamBalanceAfter: Decimal | null;\n idempotent: false;\n}\n\nexport type TeamDeductionResult = TeamDeductionSuccess | TeamDeductionFailure;\n"]}
package/dist/engine.d.ts CHANGED
@@ -4,8 +4,8 @@ import type { UsageMetrics } from "./metrics.js";
4
4
  export declare class PricingEngine {
5
5
  private readonly config;
6
6
  constructor(config: ParsedBursarConfig);
7
- static fromDict(data: BursarConfigData | Record<string, unknown>): PricingEngine;
8
- get pricingSchema(): Record<string, unknown>;
7
+ static fromDict<T extends object>(data: T): PricingEngine;
8
+ get pricingSchema(): BursarConfigData;
9
9
  calculate(metrics: UsageMetrics, options?: {
10
10
  rateCard?: string;
11
11
  } | Record<string, string> | null): CostBreakdown;
@@ -1 +1 @@
1
- {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAIL,KAAK,gBAAgB,EAGrB,KAAK,kBAAkB,EAExB,MAAM,aAAa,CAAC;AAGrB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAcjD,qBAAa,aAAa;IACZ,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,kBAAkB;IAEvD,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,aAAa;IAIhF,IAAI,aAAa,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAE3C;IAED,SAAS,CACP,OAAO,EAAE,YAAY,EACrB,OAAO,GAAE;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAS,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IAKzE,OAAO,CAAC,eAAe;IAYvB,OAAO,CAAC,gBAAgB;IAUxB,OAAO,CAAC,OAAO;IAMf,OAAO,CAAC,UAAU;IAmBlB,OAAO,CAAC,YAAY;IAoBpB,OAAO,CAAC,cAAc;CA6CvB"}
package/dist/engine.js CHANGED
@@ -1,4 +1,5 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
+ import { z } from "zod";
2
3
  import { makeCostBreakdown } from "./breakdown.js";
3
4
  import { canonicalParsedBursarConfigDict, loadConfigFromDict, } from "./config.js";
4
5
  import { ConfigError } from "./errors.js";
@@ -46,17 +47,28 @@ export class PricingEngine {
46
47
  continue;
47
48
  }
48
49
  if (definition.type === "string") {
49
- if (typeof input !== "string")
50
+ const parsed = z.string().safeParse(input);
51
+ if (!parsed.success)
50
52
  throw new ConfigError(`dimension '${name}' must be string`);
51
- dimensions[name] = input;
53
+ dimensions[name] = parsed.data;
52
54
  }
53
55
  else if (definition.type === "boolean") {
54
- if (typeof input !== "boolean")
56
+ const parsed = z.boolean().safeParse(input);
57
+ if (!parsed.success)
55
58
  throw new ConfigError(`dimension '${name}' must be boolean`);
56
- dimensions[name] = input;
59
+ dimensions[name] = parsed.data;
57
60
  }
58
61
  else {
59
- const numeric = new Decimal(input);
62
+ let numeric;
63
+ if (input instanceof Decimal) {
64
+ numeric = input;
65
+ }
66
+ else {
67
+ const parsed = z.union([z.string(), z.number(), z.bigint()]).safeParse(input);
68
+ if (!parsed.success)
69
+ throw new ConfigError(`dimension '${name}' must be number`);
70
+ numeric = new Decimal(parsed.data);
71
+ }
60
72
  if (!numeric.isFinite())
61
73
  throw new ConfigError(`dimension '${name}' must be finite`);
62
74
  dimensions[name] = numeric;
@@ -88,7 +100,14 @@ export class PricingEngine {
88
100
  rateCard: cardKey,
89
101
  chargeType: selected.type,
90
102
  measures: Object.fromEntries(Object.entries(measures).map(([key, amount]) => [key, amount.toString()])),
91
- dimensions: dimensionsInput,
103
+ dimensions: Object.fromEntries(Object.entries(dimensionsInput).map(([key, value]) => [
104
+ key,
105
+ value instanceof Decimal
106
+ ? value.toString()
107
+ : z.bigint().safeParse(value).success
108
+ ? String(value)
109
+ : value,
110
+ ])),
92
111
  },
93
112
  });
94
113
  }
@@ -136,8 +155,10 @@ export class PricingEngine {
136
155
  return matcher.values.some((candidate) => this.scalarEquals(value, candidate));
137
156
  if (matcher.op === "not_in")
138
157
  return !matcher.values.some((candidate) => this.scalarEquals(value, candidate));
139
- if (matcher.op === "prefix")
140
- return typeof value === "string" && value.startsWith(matcher.value);
158
+ if (matcher.op === "prefix") {
159
+ const parsed = z.string().safeParse(value);
160
+ return parsed.success && parsed.data.startsWith(matcher.value);
161
+ }
141
162
  if (matcher.op !== "range" || !(value instanceof Decimal))
142
163
  return false;
143
164
  if (matcher.gt && !value.gt(matcher.gt))
@@ -152,8 +173,16 @@ export class PricingEngine {
152
173
  }
153
174
  scalarEquals(left, right) {
154
175
  if (left instanceof Decimal || right instanceof Decimal) {
176
+ const leftValue = left instanceof Decimal
177
+ ? { success: true, data: left }
178
+ : z.union([z.string(), z.number(), z.bigint()]).safeParse(left);
179
+ const rightValue = right instanceof Decimal
180
+ ? { success: true, data: right }
181
+ : z.union([z.string(), z.number(), z.bigint()]).safeParse(right);
182
+ if (!leftValue.success || !rightValue.success)
183
+ return false;
155
184
  try {
156
- return new Decimal(left).eq(new Decimal(right));
185
+ return new Decimal(leftValue.data).eq(new Decimal(rightValue.data));
157
186
  }
158
187
  catch {
159
188
  return false;
@@ -204,7 +233,7 @@ export class PricingEngine {
204
233
  return evaluateExpression(charge.formula, measures);
205
234
  if (charge.type === "sum")
206
235
  return Decimal.sum(...charge.components.map((component) => this.evaluateCharge(component, measures)));
207
- throw new ConfigError(`unsupported charge type '${String(charge.type)}'`);
236
+ throw new ConfigError("unsupported charge type");
208
237
  }
209
238
  }
210
239
  //# sourceMappingURL=engine.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"engine.js","sourceRoot":"","sources":["../src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WAAW,CAAC,4BAA4B,MAAM,CAAE,MAAiB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACxF,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\n\nimport { makeCostBreakdown } from \"./breakdown.js\";\nimport type { CostBreakdown } from \"./breakdown.js\";\nimport {\n canonicalParsedBursarConfigDict,\n loadConfigFromDict,\n type Charge,\n type BursarConfigData,\n type DimensionMatcher,\n type OperationPricing,\n type ParsedBursarConfig,\n type PriceRule,\n} from \"./config.js\";\nimport { ConfigError } from \"./errors.js\";\nimport { evaluateExpression } from \"./expr.js\";\nimport type { UsageMetrics } from \"./metrics.js\";\n\nconst quantize = (value: Decimal): Decimal => value.toDecimalPlaces(6, Decimal.ROUND_HALF_UP);\n\ntype DimensionValue = string | Decimal | boolean;\n\nfunction requiredMeasure(measures: Record<string, Decimal>, name: string): Decimal {\n const measure = measures[name];\n if (measure === undefined) {\n throw new ConfigError(`price charge references missing usage measure '${name}'`);\n }\n return measure;\n}\n\nexport class PricingEngine {\n constructor(private readonly config: ParsedBursarConfig) {}\n\n static fromDict(data: BursarConfigData | Record<string, unknown>): PricingEngine {\n return new PricingEngine(loadConfigFromDict(data));\n }\n\n get pricingSchema(): Record<string, unknown> {\n return canonicalParsedBursarConfigDict(this.config);\n }\n\n calculate(\n metrics: UsageMetrics,\n options: { rateCard?: string } | Record<string, string> | null = {},\n ): CostBreakdown {\n const pricing = this.config.pricing;\n if (!pricing) throw new ConfigError(\"usage pricing not configured\");\n const operation = pricing.operations[metrics.operation];\n if (!operation) throw new ConfigError(`unknown usage operation '${metrics.operation}'`);\n const measuresInput = metrics.measures ?? {};\n const dimensionsInput = metrics.dimensions ?? {};\n const unknownMeasures = Object.keys(measuresInput).filter((key) => !operation.measures[key]);\n const unknownDimensions = Object.keys(dimensionsInput).filter(\n (key) => !operation.dimensions[key],\n );\n if (unknownMeasures.length)\n throw new ConfigError(\n `operation '${metrics.operation}' received undeclared measures ${unknownMeasures.join(\", \")}`,\n );\n if (unknownDimensions.length)\n throw new ConfigError(\n `operation '${metrics.operation}' received undeclared dimensions ${unknownDimensions.join(\", \")}`,\n );\n\n const dimensions: Record<string, DimensionValue> = {};\n for (const [name, definition] of Object.entries(operation.dimensions)) {\n const input = dimensionsInput[name];\n if (input == null) {\n if (definition.required)\n throw new ConfigError(`operation '${metrics.operation}' requires dimension '${name}'`);\n continue;\n }\n if (definition.type === \"string\") {\n if (typeof input !== \"string\") throw new ConfigError(`dimension '${name}' must be string`);\n dimensions[name] = input;\n } else if (definition.type === \"boolean\") {\n if (typeof input !== \"boolean\")\n throw new ConfigError(`dimension '${name}' must be boolean`);\n dimensions[name] = input;\n } else {\n const numeric = new Decimal(input as Decimal.Value);\n if (!numeric.isFinite()) throw new ConfigError(`dimension '${name}' must be finite`);\n dimensions[name] = numeric;\n }\n }\n\n const measures: Record<string, Decimal> = {};\n for (const name of Object.keys(operation.measures)) {\n const value = new Decimal(measuresInput[name] ?? 0);\n if (!value.isFinite() || value.isNegative())\n throw new ConfigError(`usage measure '${name}' must be finite and non-negative`);\n measures[name] = value;\n }\n const requestedRateCard =\n options != null && \"rateCard\" in options ? options.rateCard : undefined;\n const cardKey = this.resolveRateCard(requestedRateCard);\n const operationPrice = this.operationPricing(cardKey, metrics.operation);\n const matched = operationPrice.rules.find((rule) => this.matches(rule, dimensions));\n const selected =\n matched?.charge ??\n (operationPrice.unmatched.action === \"charge\" ? operationPrice.unmatched.charge : undefined);\n if (!selected)\n throw new ConfigError(\n `no price rule matched operation '${metrics.operation}' in rate card '${cardKey}'`,\n );\n const value = this.evaluateCharge(selected, measures);\n if (!value.isFinite() || value.isNegative())\n throw new ConfigError(\n `price charge for '${metrics.operation}' produced a negative or non-finite credit cost`,\n );\n const total = quantize(value);\n return makeCostBreakdown({\n operationCredits: total,\n breakdown: {\n operation: metrics.operation,\n rateCard: cardKey,\n chargeType: selected.type,\n measures: Object.fromEntries(\n Object.entries(measures).map(([key, amount]) => [key, amount.toString()]),\n ),\n dimensions: dimensionsInput,\n },\n });\n }\n\n calculateBatch(metrics: UsageMetrics[], options: { rateCard?: string } = {}): CostBreakdown[] {\n return metrics.map((item) => this.calculate(item, options));\n }\n\n getRateCardForPlan(planId: string | null | undefined): string | undefined {\n if (!planId) return undefined;\n return this.config.plans[planId]?.rateCard;\n }\n\n private resolveRateCard(requested?: string): string {\n const cards = this.config.pricing!.rateCards;\n if (requested) {\n if (!cards[requested]) throw new ConfigError(`unknown rate card '${requested}'`);\n return requested;\n }\n const keys = Object.keys(cards);\n const onlyCard = keys[0];\n if (keys.length === 1 && onlyCard !== undefined) return onlyCard;\n throw new ConfigError(\"rateCard is required when more than one rate card is configured\");\n }\n\n private operationPricing(cardKey: string, operation: string): OperationPricing {\n const card = this.config.pricing!.rateCards[cardKey];\n if (!card) throw new ConfigError(`unknown rate card '${cardKey}'`);\n const operationPrice = card.operations[operation];\n if (operationPrice) return operationPrice;\n if (!card.extends)\n throw new ConfigError(`rate card '${cardKey}' has no price for operation '${operation}'`);\n return this.operationPricing(card.extends, operation);\n }\n\n private matches(rule: PriceRule, dimensions: Record<string, DimensionValue>): boolean {\n return Object.entries(rule.when).every(([name, matcher]) =>\n this.matchesOne(matcher, dimensions[name]),\n );\n }\n\n private matchesOne(matcher: DimensionMatcher, value: DimensionValue | undefined): boolean {\n if (value == null) return false;\n if (matcher.op === \"eq\") return this.scalarEquals(value, matcher.value);\n if (matcher.op === \"in\")\n return matcher.values.some((candidate) => this.scalarEquals(value, candidate));\n if (matcher.op === \"not_in\")\n return !matcher.values.some((candidate) => this.scalarEquals(value, candidate));\n if (matcher.op === \"prefix\")\n return typeof value === \"string\" && value.startsWith(matcher.value);\n if (matcher.op !== \"range\" || !(value instanceof Decimal)) return false;\n if (matcher.gt && !value.gt(matcher.gt)) return false;\n if (matcher.gte && !value.gte(matcher.gte)) return false;\n if (matcher.lt && !value.lt(matcher.lt)) return false;\n if (matcher.lte && !value.lte(matcher.lte)) return false;\n return true;\n }\n\n private scalarEquals(left: DimensionValue, right: string | Decimal | boolean): boolean {\n if (left instanceof Decimal || right instanceof Decimal) {\n try {\n return new Decimal(left as Decimal.Value).eq(new Decimal(right as Decimal.Value));\n } catch {\n return false;\n }\n }\n return left === right;\n }\n\n private evaluateCharge(charge: Charge, measures: Record<string, Decimal>): Decimal {\n if (charge.type === \"flat\") return charge.amount;\n if (charge.type === \"per_unit\")\n return requiredMeasure(measures, charge.measure).div(charge.unitSize).mul(charge.rate);\n if (charge.type === \"package\") {\n const packages = requiredMeasure(measures, charge.measure).div(charge.units);\n const rounded =\n charge.rounding === \"ceil\"\n ? packages.ceil()\n : charge.rounding === \"floor\"\n ? packages.floor()\n : packages.toDecimalPlaces(0, Decimal.ROUND_HALF_UP);\n return rounded.mul(charge.amount);\n }\n if (charge.type === \"graduated\") {\n let remaining = requiredMeasure(measures, charge.measure);\n let previous = new Decimal(0);\n let total = new Decimal(0);\n for (const tier of charge.tiers) {\n const units =\n tier.upTo == null ? remaining : Decimal.min(remaining, tier.upTo.sub(previous));\n if (units.isPositive()) {\n total = total.add(units.mul(tier.rate));\n remaining = remaining.sub(units);\n }\n if (!remaining.isPositive()) break;\n if (tier.upTo != null) previous = tier.upTo;\n }\n return total;\n }\n if (charge.type === \"volume\") {\n const value = requiredMeasure(measures, charge.measure);\n const tier =\n charge.tiers.find((candidate) => candidate.upTo == null || value.lte(candidate.upTo)) ??\n charge.tiers.at(-1);\n if (!tier) throw new ConfigError(\"volume charge requires at least one tier\");\n return value.mul(tier.rate);\n }\n if (charge.type === \"expression\") return evaluateExpression(charge.formula, measures);\n if (charge.type === \"sum\")\n return Decimal.sum(\n ...charge.components.map((component) => this.evaluateCharge(component, measures)),\n );\n throw new ConfigError(`unsupported charge type '${String((charge as Charge).type)}'`);\n }\n}\n"]}
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,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M,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;YACtB,IAAI,CAAC,IAAI;gBAAE,MAAM,IAAI,WAAW,CAAC,0CAA0C,CAAC,CAAC;YAC7E,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC9B,CAAC;QACD,IAAI,MAAM,CAAC,IAAI,KAAK,YAAY;YAAE,OAAO,kBAAkB,CAAC,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACtF,IAAI,MAAM,CAAC,IAAI,KAAK,KAAK;YACvB,OAAO,OAAO,CAAC,GAAG,CAChB,GAAG,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC,CAClF,CAAC;QACJ,MAAM,IAAI,WAAW,CAAC,yBAAyB,CAAC,CAAC;IACnD,CAAC;CACF","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { z } from \"zod\";\n\nimport { makeCostBreakdown } from \"./breakdown.js\";\nimport type { CostBreakdown } from \"./breakdown.js\";\nimport {\n canonicalParsedBursarConfigDict,\n loadConfigFromDict,\n type BursarConfigData,\n type Charge,\n type DimensionMatcher,\n type OperationPricing,\n type ParsedBursarConfig,\n type PriceRule,\n} from \"./config.js\";\nimport { ConfigError } from \"./errors.js\";\nimport { evaluateExpression } from \"./expr.js\";\nimport type { UsageMetrics } from \"./metrics.js\";\n\nconst quantize = (value: Decimal): Decimal => value.toDecimalPlaces(6, Decimal.ROUND_HALF_UP);\n\ntype DimensionValue = string | Decimal | boolean;\n\nfunction requiredMeasure(measures: Record<string, Decimal>, name: string): Decimal {\n const measure = measures[name];\n if (measure === undefined) {\n throw new ConfigError(`price charge references missing usage measure '${name}'`);\n }\n return measure;\n}\n\nexport class PricingEngine {\n constructor(private readonly config: ParsedBursarConfig) {}\n\n static fromDict<T extends object>(data: T): PricingEngine {\n return new PricingEngine(loadConfigFromDict(data));\n }\n\n get pricingSchema(): BursarConfigData {\n return canonicalParsedBursarConfigDict(this.config);\n }\n\n calculate(\n metrics: UsageMetrics,\n options: { rateCard?: string } | Record<string, string> | null = {},\n ): CostBreakdown {\n const pricing = this.config.pricing;\n if (!pricing) throw new ConfigError(\"usage pricing not configured\");\n const operation = pricing.operations[metrics.operation];\n if (!operation) throw new ConfigError(`unknown usage operation '${metrics.operation}'`);\n const measuresInput = metrics.measures ?? {};\n const dimensionsInput = metrics.dimensions ?? {};\n const unknownMeasures = Object.keys(measuresInput).filter((key) => !operation.measures[key]);\n const unknownDimensions = Object.keys(dimensionsInput).filter(\n (key) => !operation.dimensions[key],\n );\n if (unknownMeasures.length)\n throw new ConfigError(\n `operation '${metrics.operation}' received undeclared measures ${unknownMeasures.join(\", \")}`,\n );\n if (unknownDimensions.length)\n throw new ConfigError(\n `operation '${metrics.operation}' received undeclared dimensions ${unknownDimensions.join(\", \")}`,\n );\n\n const dimensions: Record<string, DimensionValue> = {};\n for (const [name, definition] of Object.entries(operation.dimensions)) {\n const input = dimensionsInput[name];\n if (input == null) {\n if (definition.required)\n throw new ConfigError(`operation '${metrics.operation}' requires dimension '${name}'`);\n continue;\n }\n if (definition.type === \"string\") {\n const parsed = z.string().safeParse(input);\n if (!parsed.success) throw new ConfigError(`dimension '${name}' must be string`);\n dimensions[name] = parsed.data;\n } else if (definition.type === \"boolean\") {\n const parsed = z.boolean().safeParse(input);\n if (!parsed.success) throw new ConfigError(`dimension '${name}' must be boolean`);\n dimensions[name] = parsed.data;\n } else {\n let numeric: Decimal;\n if (input instanceof Decimal) {\n numeric = input;\n } else {\n const parsed = z.union([z.string(), z.number(), z.bigint()]).safeParse(input);\n if (!parsed.success) throw new ConfigError(`dimension '${name}' must be number`);\n numeric = new Decimal(parsed.data);\n }\n if (!numeric.isFinite()) throw new ConfigError(`dimension '${name}' must be finite`);\n dimensions[name] = numeric;\n }\n }\n\n const measures: Record<string, Decimal> = {};\n for (const name of Object.keys(operation.measures)) {\n const value = new Decimal(measuresInput[name] ?? 0);\n if (!value.isFinite() || value.isNegative())\n throw new ConfigError(`usage measure '${name}' must be finite and non-negative`);\n measures[name] = value;\n }\n const requestedRateCard =\n options != null && \"rateCard\" in options ? options.rateCard : undefined;\n const cardKey = this.resolveRateCard(requestedRateCard);\n const operationPrice = this.operationPricing(cardKey, metrics.operation);\n const matched = operationPrice.rules.find((rule) => this.matches(rule, dimensions));\n const selected =\n matched?.charge ??\n (operationPrice.unmatched.action === \"charge\" ? operationPrice.unmatched.charge : undefined);\n if (!selected)\n throw new ConfigError(\n `no price rule matched operation '${metrics.operation}' in rate card '${cardKey}'`,\n );\n const value = this.evaluateCharge(selected, measures);\n if (!value.isFinite() || value.isNegative())\n throw new ConfigError(\n `price charge for '${metrics.operation}' produced a negative or non-finite credit cost`,\n );\n const total = quantize(value);\n return makeCostBreakdown({\n operationCredits: total,\n breakdown: {\n operation: metrics.operation,\n rateCard: cardKey,\n chargeType: selected.type,\n measures: Object.fromEntries(\n Object.entries(measures).map(([key, amount]) => [key, amount.toString()]),\n ),\n dimensions: Object.fromEntries(\n Object.entries(dimensionsInput).map(([key, value]) => [\n key,\n value instanceof Decimal\n ? value.toString()\n : z.bigint().safeParse(value).success\n ? String(value)\n : value,\n ]),\n ),\n },\n });\n }\n\n calculateBatch(metrics: UsageMetrics[], options: { rateCard?: string } = {}): CostBreakdown[] {\n return metrics.map((item) => this.calculate(item, options));\n }\n\n getRateCardForPlan(planId: string | null | undefined): string | undefined {\n if (!planId) return undefined;\n return this.config.plans[planId]?.rateCard;\n }\n\n private resolveRateCard(requested?: string): string {\n const cards = this.config.pricing!.rateCards;\n if (requested) {\n if (!cards[requested]) throw new ConfigError(`unknown rate card '${requested}'`);\n return requested;\n }\n const keys = Object.keys(cards);\n const onlyCard = keys[0];\n if (keys.length === 1 && onlyCard !== undefined) return onlyCard;\n throw new ConfigError(\"rateCard is required when more than one rate card is configured\");\n }\n\n private operationPricing(cardKey: string, operation: string): OperationPricing {\n const card = this.config.pricing!.rateCards[cardKey];\n if (!card) throw new ConfigError(`unknown rate card '${cardKey}'`);\n const operationPrice = card.operations[operation];\n if (operationPrice) return operationPrice;\n if (!card.extends)\n throw new ConfigError(`rate card '${cardKey}' has no price for operation '${operation}'`);\n return this.operationPricing(card.extends, operation);\n }\n\n private matches(rule: PriceRule, dimensions: Record<string, DimensionValue>): boolean {\n return Object.entries(rule.when).every(([name, matcher]) =>\n this.matchesOne(matcher, dimensions[name]),\n );\n }\n\n private matchesOne(matcher: DimensionMatcher, value: DimensionValue | undefined): boolean {\n if (value == null) return false;\n if (matcher.op === \"eq\") return this.scalarEquals(value, matcher.value);\n if (matcher.op === \"in\")\n return matcher.values.some((candidate) => this.scalarEquals(value, candidate));\n if (matcher.op === \"not_in\")\n return !matcher.values.some((candidate) => this.scalarEquals(value, candidate));\n if (matcher.op === \"prefix\") {\n const parsed = z.string().safeParse(value);\n return parsed.success && parsed.data.startsWith(matcher.value);\n }\n if (matcher.op !== \"range\" || !(value instanceof Decimal)) return false;\n if (matcher.gt && !value.gt(matcher.gt)) return false;\n if (matcher.gte && !value.gte(matcher.gte)) return false;\n if (matcher.lt && !value.lt(matcher.lt)) return false;\n if (matcher.lte && !value.lte(matcher.lte)) return false;\n return true;\n }\n\n private scalarEquals(left: DimensionValue, right: string | Decimal | boolean): boolean {\n if (left instanceof Decimal || right instanceof Decimal) {\n const leftValue =\n left instanceof Decimal\n ? { success: true as const, data: left }\n : z.union([z.string(), z.number(), z.bigint()]).safeParse(left);\n const rightValue =\n right instanceof Decimal\n ? { success: true as const, data: right }\n : z.union([z.string(), z.number(), z.bigint()]).safeParse(right);\n if (!leftValue.success || !rightValue.success) return false;\n try {\n return new Decimal(leftValue.data).eq(new Decimal(rightValue.data));\n } catch {\n return false;\n }\n }\n return left === right;\n }\n\n private evaluateCharge(charge: Charge, measures: Record<string, Decimal>): Decimal {\n if (charge.type === \"flat\") return charge.amount;\n if (charge.type === \"per_unit\")\n return requiredMeasure(measures, charge.measure).div(charge.unitSize).mul(charge.rate);\n if (charge.type === \"package\") {\n const packages = requiredMeasure(measures, charge.measure).div(charge.units);\n const rounded =\n charge.rounding === \"ceil\"\n ? packages.ceil()\n : charge.rounding === \"floor\"\n ? packages.floor()\n : packages.toDecimalPlaces(0, Decimal.ROUND_HALF_UP);\n return rounded.mul(charge.amount);\n }\n if (charge.type === \"graduated\") {\n let remaining = requiredMeasure(measures, charge.measure);\n let previous = new Decimal(0);\n let total = new Decimal(0);\n for (const tier of charge.tiers) {\n const units =\n tier.upTo == null ? remaining : Decimal.min(remaining, tier.upTo.sub(previous));\n if (units.isPositive()) {\n total = total.add(units.mul(tier.rate));\n remaining = remaining.sub(units);\n }\n if (!remaining.isPositive()) break;\n if (tier.upTo != null) previous = tier.upTo;\n }\n return total;\n }\n if (charge.type === \"volume\") {\n const value = requiredMeasure(measures, charge.measure);\n const tier =\n charge.tiers.find((candidate) => candidate.upTo == null || value.lte(candidate.upTo)) ??\n charge.tiers.at(-1);\n if (!tier) throw new ConfigError(\"volume charge requires at least one tier\");\n return value.mul(tier.rate);\n }\n if (charge.type === \"expression\") return evaluateExpression(charge.formula, measures);\n if (charge.type === \"sum\")\n return Decimal.sum(\n ...charge.components.map((component) => this.evaluateCharge(component, measures)),\n );\n throw new ConfigError(\"unsupported charge type\");\n }\n}\n"]}
package/dist/errors.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { StructuredValue } from "./shared/json.js";
1
2
  /**
2
3
  * Transport-neutral failure categories for SaaS application boundaries.
3
4
  *
@@ -7,7 +8,9 @@
7
8
  */
8
9
  export type BursarErrorCategory = "invalid_request" | "payment_required" | "forbidden" | "not_found" | "conflict" | "rate_limited" | "unavailable" | "internal";
9
10
  /** Structured, non-secret context that is safe to attach to an SDK error. */
10
- export type BursarErrorDetails = Readonly<Record<string, unknown>>;
11
+ export interface BursarErrorDetails {
12
+ readonly [key: string]: StructuredValue;
13
+ }
11
14
  /** Options shared by all Bursar errors. */
12
15
  export interface BursarErrorOptions extends ErrorOptions {
13
16
  details?: BursarErrorDetails;
@@ -16,6 +19,10 @@ export interface StoreErrorOptions extends BursarErrorOptions {
16
19
  indeterminate?: boolean;
17
20
  retryable?: boolean;
18
21
  }
22
+ /** Bounded SDK-owned codes safe for diagnostics and low-cardinality telemetry. */
23
+ export declare const BURSAR_ERROR_CODES: readonly ["AUTO_RECHARGE_DISABLED", "AUTO_RECHARGE_NOT_CONFIGURED", "BILLING_ERROR", "BURSAR_ERROR", "BURSAR_IMPORT_ERROR", "CAPABILITY_NOT_CONFIGURED", "CAPABILITY_NOT_SUPPORTED", "CAP_REACHED", "CATALOG_NOT_LOADED", "CONCURRENCY_LIMIT_REACHED", "CONFIG_ERROR", "CREDIT_ERROR", "EXPRESSION_ERROR", "FEATURE_NOT_ENTITLED", "INSUFFICIENT_CREDITS", "LEASE_EXPIRED", "LEASE_NOT_FOUND", "OPERATION_NOT_ALLOWED", "PAYMENT_METHOD_REQUIRED", "PROVIDER_CAPABILITY_NOT_SUPPORTED", "PROVIDER_RESPONSE_INVALID", "QUOTA_EXCEEDED", "REFUND_REJECTED", "STORE_CLOSED", "STORE_ERROR", "STORE_TIMEOUT", "STORE_UNAVAILABLE"];
24
+ export type BursarErrorCode = (typeof BURSAR_ERROR_CODES)[number];
25
+ export declare function isBursarErrorCode(cause: unknown): cause is BursarErrorCode;
19
26
  export interface SerializedBursarError {
20
27
  name: string;
21
28
  message: string;
@@ -201,9 +208,9 @@ export declare class CapabilityNotConfiguredError extends BursarError {
201
208
  * Cross-package-copy-safe check for an SDK error. `instanceof` alone fails
202
209
  * when an application installs two copies of the package.
203
210
  */
204
- export declare function isBursarError(error: unknown): error is BursarError;
211
+ export declare function isBursarError(cause: unknown): cause is BursarError;
205
212
  /** Return whether retrying the failed Bursar operation can be useful. */
206
- export declare function isRetryableBursarError(error: unknown): boolean;
213
+ export declare function isRetryableBursarError(cause: unknown): boolean;
207
214
  /** Project a Bursar failure category to its conventional HTTP status. */
208
215
  export declare function bursarErrorHttpStatus(error: BursarError): number;
209
216
  /** Return safe default copy for exposing a Bursar failure to an end user. */
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,MAAM,mBAAmB,GAC3B,iBAAiB,GACjB,kBAAkB,GAClB,WAAW,GACX,WAAW,GACX,UAAU,GACV,cAAc,GACd,aAAa,GACb,UAAU,CAAC;AAEf,6EAA6E;AAC7E,MAAM,MAAM,kBAAkB,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAEnE,2CAA2C;AAC3C,MAAM,WAAW,kBAAmB,SAAQ,YAAY;IACtD,OAAO,CAAC,EAAE,kBAAkB,CAAC;CAC9B;AAED,MAAM,WAAW,iBAAkB,SAAQ,kBAAkB;IAC3D,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,SAAS,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,kBAAkB,CAAC;IAC7B,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAID,8CAA8C;AAC9C,qBAAa,WAAY,SAAQ,KAAK;IACpC,SAAkB,IAAI,EAAE,MAAM,CAAiB;IAC/C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAkB;IACvC,QAAQ,CAAC,QAAQ,EAAE,mBAAmB,CAAc;IACpD,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAS;IAEpC,QAAQ,CAAC,OAAO,CAAC,EAAE,kBAAkB,CAAC;gBAE1B,OAAO,EAAE,MAAM,EAAE,OAAO,GA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