@zonastery/bursar 2.0.1 → 2.0.3

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 (285) hide show
  1. package/README.md +22 -14
  2. package/dist/billing/auto-recharge-service.d.ts +1 -1
  3. package/dist/billing/auto-recharge-service.d.ts.map +1 -1
  4. package/dist/billing/auto-recharge-service.js +9 -6
  5. package/dist/billing/auto-recharge-service.js.map +1 -1
  6. package/dist/billing/billing-store.d.ts +4 -1
  7. package/dist/billing/billing-store.d.ts.map +1 -1
  8. package/dist/billing/billing-store.js +2 -0
  9. package/dist/billing/billing-store.js.map +1 -1
  10. package/dist/billing/contracts.d.ts +2 -1
  11. package/dist/billing/contracts.d.ts.map +1 -1
  12. package/dist/billing/contracts.js.map +1 -1
  13. package/dist/billing/event-handlers.d.ts +2 -3
  14. package/dist/billing/event-handlers.d.ts.map +1 -1
  15. package/dist/billing/event-handlers.js +38 -49
  16. package/dist/billing/event-handlers.js.map +1 -1
  17. package/dist/billing/event-processor.d.ts.map +1 -1
  18. package/dist/billing/event-processor.js +22 -10
  19. package/dist/billing/event-processor.js.map +1 -1
  20. package/dist/billing/financial-event-handlers.d.ts +2 -2
  21. package/dist/billing/financial-event-handlers.d.ts.map +1 -1
  22. package/dist/billing/financial-event-handlers.js +7 -7
  23. package/dist/billing/financial-event-handlers.js.map +1 -1
  24. package/dist/billing/postgres/repositories/auto-recharge.js +1 -1
  25. package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
  26. package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
  27. package/dist/billing/postgres/repositories/event.js +33 -1
  28. package/dist/billing/postgres/repositories/event.js.map +1 -1
  29. package/dist/billing/postgres/repositories/offer.d.ts +1 -1
  30. package/dist/billing/postgres/repositories/offer.d.ts.map +1 -1
  31. package/dist/billing/postgres/repositories/offer.js +1 -1
  32. package/dist/billing/postgres/repositories/offer.js.map +1 -1
  33. package/dist/billing/postgres/repositories/topup.d.ts +1 -1
  34. package/dist/billing/postgres/repositories/topup.d.ts.map +1 -1
  35. package/dist/billing/postgres/repositories/topup.js +1 -1
  36. package/dist/billing/postgres/repositories/topup.js.map +1 -1
  37. package/dist/billing/postgres/store.d.ts +6 -2
  38. package/dist/billing/postgres/store.d.ts.map +1 -1
  39. package/dist/billing/postgres/store.js +21 -6
  40. package/dist/billing/postgres/store.js.map +1 -1
  41. package/dist/billing/service-types.d.ts +2 -15
  42. package/dist/billing/service-types.d.ts.map +1 -1
  43. package/dist/billing/service-types.js.map +1 -1
  44. package/dist/billing/types/auto-recharge.d.ts +1 -1
  45. package/dist/billing/types/auto-recharge.d.ts.map +1 -1
  46. package/dist/billing/types/auto-recharge.js.map +1 -1
  47. package/dist/billing/types/catalog.d.ts +1 -1
  48. package/dist/billing/types/catalog.d.ts.map +1 -1
  49. package/dist/billing/types/catalog.js.map +1 -1
  50. package/dist/billing/types/documents.d.ts +1 -1
  51. package/dist/billing/types/documents.d.ts.map +1 -1
  52. package/dist/billing/types/documents.js.map +1 -1
  53. package/dist/billing/types/events.d.ts +11 -2
  54. package/dist/billing/types/events.d.ts.map +1 -1
  55. package/dist/billing/types/events.js +2 -2
  56. package/dist/billing/types/events.js.map +1 -1
  57. package/dist/billing/types/subscriptions.d.ts.map +1 -1
  58. package/dist/billing/types/subscriptions.js.map +1 -1
  59. package/dist/breakdown.d.ts +1 -1
  60. package/dist/breakdown.d.ts.map +1 -1
  61. package/dist/breakdown.js +1 -1
  62. package/dist/breakdown.js.map +1 -1
  63. package/dist/bursar.d.ts +21 -11
  64. package/dist/bursar.d.ts.map +1 -1
  65. package/dist/bursar.js +40 -4
  66. package/dist/bursar.js.map +1 -1
  67. package/dist/catalog.d.ts.map +1 -1
  68. package/dist/catalog.js +1 -1
  69. package/dist/catalog.js.map +1 -1
  70. package/dist/commerce/index.d.ts +0 -1
  71. package/dist/commerce/index.d.ts.map +1 -1
  72. package/dist/commerce/index.js +0 -1
  73. package/dist/commerce/index.js.map +1 -1
  74. package/dist/commerce/service.d.ts.map +1 -1
  75. package/dist/commerce/service.js +154 -106
  76. package/dist/commerce/service.js.map +1 -1
  77. package/dist/commerce/types.d.ts +9 -5
  78. package/dist/commerce/types.d.ts.map +1 -1
  79. package/dist/commerce/types.js.map +1 -1
  80. package/dist/config/parse-credits.d.ts.map +1 -1
  81. package/dist/config/parse-credits.js +0 -6
  82. package/dist/config/parse-credits.js.map +1 -1
  83. package/dist/config/parse-utils.d.ts +1 -1
  84. package/dist/config/parse-utils.d.ts.map +1 -1
  85. package/dist/config/parse-utils.js +1 -1
  86. package/dist/config/parse-utils.js.map +1 -1
  87. package/dist/config/types.d.ts +1 -6
  88. package/dist/config/types.d.ts.map +1 -1
  89. package/dist/config/types.js.map +1 -1
  90. package/dist/config.d.ts.map +1 -1
  91. package/dist/config.js +8 -1
  92. package/dist/config.js.map +1 -1
  93. package/dist/credits/amount.d.ts +8 -0
  94. package/dist/credits/amount.d.ts.map +1 -0
  95. package/dist/credits/amount.js +32 -0
  96. package/dist/credits/amount.js.map +1 -0
  97. package/dist/credits/catalog-runtime.d.ts +5 -7
  98. package/dist/credits/catalog-runtime.d.ts.map +1 -1
  99. package/dist/credits/catalog-runtime.js +4 -13
  100. package/dist/credits/catalog-runtime.js.map +1 -1
  101. package/dist/credits/lease-workflow.d.ts +2 -2
  102. package/dist/credits/lease-workflow.d.ts.map +1 -1
  103. package/dist/credits/lease-workflow.js +24 -21
  104. package/dist/credits/lease-workflow.js.map +1 -1
  105. package/dist/credits/low-balance-monitor.d.ts +1 -1
  106. package/dist/credits/low-balance-monitor.d.ts.map +1 -1
  107. package/dist/credits/low-balance-monitor.js +3 -4
  108. package/dist/credits/low-balance-monitor.js.map +1 -1
  109. package/dist/credits/postgres/repositories/balance.d.ts.map +1 -1
  110. package/dist/credits/postgres/repositories/balance.js +1 -1
  111. package/dist/credits/postgres/repositories/balance.js.map +1 -1
  112. package/dist/credits/postgres/repositories/bucket.js +1 -1
  113. package/dist/credits/postgres/repositories/bucket.js.map +1 -1
  114. package/dist/credits/postgres/repositories/lease.d.ts.map +1 -1
  115. package/dist/credits/postgres/repositories/lease.js +4 -2
  116. package/dist/credits/postgres/repositories/lease.js.map +1 -1
  117. package/dist/credits/postgres/repositories/team.d.ts +2 -1
  118. package/dist/credits/postgres/repositories/team.d.ts.map +1 -1
  119. package/dist/credits/postgres/repositories/team.js +19 -5
  120. package/dist/credits/postgres/repositories/team.js.map +1 -1
  121. package/dist/credits/postgres/store.d.ts +18 -14
  122. package/dist/credits/postgres/store.d.ts.map +1 -1
  123. package/dist/credits/postgres/store.js +30 -18
  124. package/dist/credits/postgres/store.js.map +1 -1
  125. package/dist/credits/postgres/value-mappers.d.ts +1 -1
  126. package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
  127. package/dist/credits/postgres/value-mappers.js +1 -1
  128. package/dist/credits/postgres/value-mappers.js.map +1 -1
  129. package/dist/credits/service-errors.d.ts +1 -1
  130. package/dist/credits/service-errors.d.ts.map +1 -1
  131. package/dist/credits/service-errors.js +1 -1
  132. package/dist/credits/service-errors.js.map +1 -1
  133. package/dist/credits/service-types.d.ts +21 -16
  134. package/dist/credits/service-types.d.ts.map +1 -1
  135. package/dist/credits/service-types.js.map +1 -1
  136. package/dist/credits/service.d.ts +21 -17
  137. package/dist/credits/service.d.ts.map +1 -1
  138. package/dist/credits/service.js +81 -38
  139. package/dist/credits/service.js.map +1 -1
  140. package/dist/credits/store.d.ts +26 -23
  141. package/dist/credits/store.d.ts.map +1 -1
  142. package/dist/credits/store.js +4 -2
  143. package/dist/credits/store.js.map +1 -1
  144. package/dist/credits/types/account.d.ts +1 -1
  145. package/dist/credits/types/account.d.ts.map +1 -1
  146. package/dist/credits/types/account.js.map +1 -1
  147. package/dist/credits/types/grants.d.ts.map +1 -1
  148. package/dist/credits/types/grants.js.map +1 -1
  149. package/dist/credits/types/teams.d.ts +1 -0
  150. package/dist/credits/types/teams.d.ts.map +1 -1
  151. package/dist/credits/types/teams.js.map +1 -1
  152. package/dist/engine.js +1 -1
  153. package/dist/engine.js.map +1 -1
  154. package/dist/errors.d.ts +4 -0
  155. package/dist/errors.d.ts.map +1 -1
  156. package/dist/errors.js +34 -0
  157. package/dist/errors.js.map +1 -1
  158. package/dist/expr/ast.d.ts.map +1 -1
  159. package/dist/expr/ast.js.map +1 -1
  160. package/dist/expr/evaluator.d.ts +1 -1
  161. package/dist/expr/evaluator.d.ts.map +1 -1
  162. package/dist/expr/evaluator.js +1 -1
  163. package/dist/expr/evaluator.js.map +1 -1
  164. package/dist/expr/parser.d.ts +1 -0
  165. package/dist/expr/parser.d.ts.map +1 -1
  166. package/dist/expr/parser.js +15 -3
  167. package/dist/expr/parser.js.map +1 -1
  168. package/dist/expr.d.ts +1 -1
  169. package/dist/expr.d.ts.map +1 -1
  170. package/dist/expr.js +1 -1
  171. package/dist/expr.js.map +1 -1
  172. package/dist/generated/pricing-config.schema.json +31 -29
  173. package/dist/generated/pricing-config.types.d.ts +6 -18
  174. package/dist/generated/pricing-config.types.d.ts.map +1 -1
  175. package/dist/generated/pricing-config.types.js.map +1 -1
  176. package/dist/index.d.ts +7 -3
  177. package/dist/index.d.ts.map +1 -1
  178. package/dist/index.js +2 -0
  179. package/dist/index.js.map +1 -1
  180. package/dist/load-config-file.d.ts +2 -3
  181. package/dist/load-config-file.d.ts.map +1 -1
  182. package/dist/load-config-file.js +14 -29
  183. package/dist/load-config-file.js.map +1 -1
  184. package/dist/metrics.d.ts +1 -1
  185. package/dist/metrics.d.ts.map +1 -1
  186. package/dist/metrics.js.map +1 -1
  187. package/dist/node.d.ts +6 -3
  188. package/dist/node.d.ts.map +1 -1
  189. package/dist/node.js +1 -0
  190. package/dist/node.js.map +1 -1
  191. package/dist/providers/_shared.d.ts +3 -3
  192. package/dist/providers/_shared.d.ts.map +1 -1
  193. package/dist/providers/_shared.js +11 -6
  194. package/dist/providers/_shared.js.map +1 -1
  195. package/dist/providers/dodo/client-contract.d.ts +8 -13
  196. package/dist/providers/dodo/client-contract.d.ts.map +1 -1
  197. package/dist/providers/dodo/client-contract.js.map +1 -1
  198. package/dist/providers/dodo/event-mapper.d.ts +1 -1
  199. package/dist/providers/dodo/event-mapper.d.ts.map +1 -1
  200. package/dist/providers/dodo/event-mapper.js +23 -15
  201. package/dist/providers/dodo/event-mapper.js.map +1 -1
  202. package/dist/providers/dodo/provider.d.ts +4 -6
  203. package/dist/providers/dodo/provider.d.ts.map +1 -1
  204. package/dist/providers/dodo/provider.js +44 -82
  205. package/dist/providers/dodo/provider.js.map +1 -1
  206. package/dist/providers/dodo/webhook-bridge.d.ts +1 -2
  207. package/dist/providers/dodo/webhook-bridge.d.ts.map +1 -1
  208. package/dist/providers/dodo/webhook-bridge.js +0 -1
  209. package/dist/providers/dodo/webhook-bridge.js.map +1 -1
  210. package/dist/providers/environment.d.ts +6 -0
  211. package/dist/providers/environment.d.ts.map +1 -0
  212. package/dist/providers/environment.js +10 -0
  213. package/dist/providers/environment.js.map +1 -0
  214. package/dist/providers/index.d.ts +3 -7
  215. package/dist/providers/index.d.ts.map +1 -1
  216. package/dist/providers/index.js +1 -5
  217. package/dist/providers/index.js.map +1 -1
  218. package/dist/providers/mock/provider.d.ts +6 -8
  219. package/dist/providers/mock/provider.d.ts.map +1 -1
  220. package/dist/providers/mock/provider.js +18 -50
  221. package/dist/providers/mock/provider.js.map +1 -1
  222. package/dist/providers/stripe/event-mapper.d.ts.map +1 -1
  223. package/dist/providers/stripe/event-mapper.js +82 -14
  224. package/dist/providers/stripe/event-mapper.js.map +1 -1
  225. package/dist/providers/stripe/provider.d.ts +3 -3
  226. package/dist/providers/stripe/provider.d.ts.map +1 -1
  227. package/dist/providers/stripe/provider.js +37 -24
  228. package/dist/providers/stripe/provider.js.map +1 -1
  229. package/dist/providers/types.d.ts +9 -20
  230. package/dist/providers/types.d.ts.map +1 -1
  231. package/dist/providers/types.js.map +1 -1
  232. package/dist/shared/diagnostics.d.ts +8 -0
  233. package/dist/shared/diagnostics.d.ts.map +1 -1
  234. package/dist/shared/diagnostics.js +49 -0
  235. package/dist/shared/diagnostics.js.map +1 -1
  236. package/dist/shared/idempotency.d.ts +9 -0
  237. package/dist/shared/idempotency.d.ts.map +1 -0
  238. package/dist/shared/idempotency.js +34 -0
  239. package/dist/shared/idempotency.js.map +1 -0
  240. package/dist/shared/postgres-client.d.ts +7 -0
  241. package/dist/shared/postgres-client.d.ts.map +1 -1
  242. package/dist/shared/postgres-client.js +21 -4
  243. package/dist/shared/postgres-client.js.map +1 -1
  244. package/dist/shared/postgres-errors.d.ts.map +1 -1
  245. package/dist/shared/postgres-errors.js.map +1 -1
  246. package/dist/storage/adapters/clickhouse.d.ts +9 -2
  247. package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
  248. package/dist/storage/adapters/clickhouse.js +142 -36
  249. package/dist/storage/adapters/clickhouse.js.map +1 -1
  250. package/dist/storage/adapters/s3.d.ts +44 -6
  251. package/dist/storage/adapters/s3.d.ts.map +1 -1
  252. package/dist/storage/adapters/s3.js +59 -21
  253. package/dist/storage/adapters/s3.js.map +1 -1
  254. package/dist/storage/diagnostics.d.ts +105 -0
  255. package/dist/storage/diagnostics.d.ts.map +1 -0
  256. package/dist/storage/diagnostics.js +227 -0
  257. package/dist/storage/diagnostics.js.map +1 -0
  258. package/dist/storage/maintenance.d.ts +88 -0
  259. package/dist/storage/maintenance.d.ts.map +1 -0
  260. package/dist/storage/maintenance.js +266 -0
  261. package/dist/storage/maintenance.js.map +1 -0
  262. package/dist/storage/outbox-worker.d.ts +20 -0
  263. package/dist/storage/outbox-worker.d.ts.map +1 -1
  264. package/dist/storage/outbox-worker.js +172 -42
  265. package/dist/storage/outbox-worker.js.map +1 -1
  266. package/dist/storage/ports.d.ts +43 -1
  267. package/dist/storage/ports.d.ts.map +1 -1
  268. package/dist/storage/ports.js.map +1 -1
  269. package/dist/storage/postgres-repository.d.ts +7 -2
  270. package/dist/storage/postgres-repository.d.ts.map +1 -1
  271. package/dist/storage/postgres-repository.js +155 -54
  272. package/dist/storage/postgres-repository.js.map +1 -1
  273. package/dist/storage/runtime.d.ts +30 -9
  274. package/dist/storage/runtime.d.ts.map +1 -1
  275. package/dist/storage/runtime.js +268 -37
  276. package/dist/storage/runtime.js.map +1 -1
  277. package/dist/telemetry/index.d.ts +37 -0
  278. package/dist/telemetry/index.d.ts.map +1 -0
  279. package/dist/telemetry/index.js +115 -0
  280. package/dist/telemetry/index.js.map +1 -0
  281. package/dist/telemetry/opentelemetry.d.ts +25 -0
  282. package/dist/telemetry/opentelemetry.d.ts.map +1 -0
  283. package/dist/telemetry/opentelemetry.js +74 -0
  284. package/dist/telemetry/opentelemetry.js.map +1 -0
  285. package/package.json +62 -36
@@ -1 +1 @@
1
- {"version":3,"file":"auto-recharge.js","sourceRoot":"","sources":["../../../src/billing/types/auto-recharge.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAU,CAAC","sourcesContent":["import type Decimal from \"decimal.js\";\n\nexport const AUTO_RECHARGE_STATES = [\"disabled\", \"active\", \"paused\"] as const;\nexport type BillingAutoRechargeState = (typeof AUTO_RECHARGE_STATES)[number];\n\nexport type BillingAutoRechargeAttemptState =\n | \"claimed\"\n | \"submitted\"\n | \"processing\"\n | \"unknown\"\n | \"succeeded\"\n | \"failed\"\n | \"action_required\";\n\nexport interface BillingAutoRechargeProfile {\n userId: string;\n enabled: boolean;\n state: BillingAutoRechargeState;\n armed?: boolean;\n provider: string | null;\n topupId: string | null;\n quantity: number;\n threshold: Decimal;\n maxChargesPerWindow: number | null;\n windowUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n windowCount: number;\n windowAnchor: \"calendar\" | \"rolling\";\n windowTimezone: string;\n updatedAt?: string | null;\n}\n\nexport interface BillingAutoRechargeAttempt {\n id: string;\n userId: string;\n provider: string;\n idempotencyKey: string;\n providerAttemptId: string | null;\n topupId: string;\n quantity: number;\n state: BillingAutoRechargeAttemptState;\n windowStart: string;\n windowEnd: string;\n quotedAmountMinor: number | null;\n currency: string | null;\n failureCode: string | null;\n failureMessage: string | null;\n metadata: Record<string, unknown>;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface BillingAutoRechargeStatus {\n enabled: boolean;\n state: BillingAutoRechargeState;\n thresholdCredits: Decimal;\n topupKey: string;\n quantity: number;\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n rechargesInWindow: number;\n paymentMethodId: string | null;\n paymentMethodLast4: string | null;\n paymentMethodBrand: string | null;\n suspendedReason: string | null;\n pendingAttemptId: string | null;\n quoteAmountMinor: number | null;\n quoteCurrency: string | null;\n}\n"]}
1
+ {"version":3,"file":"auto-recharge.js","sourceRoot":"","sources":["../../../src/billing/types/auto-recharge.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,UAAU,EAAE,QAAQ,EAAE,QAAQ,CAAU,CAAC","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport const AUTO_RECHARGE_STATES = [\"disabled\", \"active\", \"paused\"] as const;\nexport type BillingAutoRechargeState = (typeof AUTO_RECHARGE_STATES)[number];\n\nexport type BillingAutoRechargeAttemptState =\n \"claimed\" | \"submitted\" | \"processing\" | \"unknown\" | \"succeeded\" | \"failed\" | \"action_required\";\n\nexport interface BillingAutoRechargeProfile {\n userId: string;\n enabled: boolean;\n state: BillingAutoRechargeState;\n armed?: boolean;\n provider: string | null;\n topupId: string | null;\n quantity: number;\n threshold: Decimal;\n maxChargesPerWindow: number | null;\n windowUnit: \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n windowCount: number;\n windowAnchor: \"calendar\" | \"rolling\";\n windowTimezone: string;\n updatedAt?: string | null;\n}\n\nexport interface BillingAutoRechargeAttempt {\n id: string;\n userId: string;\n provider: string;\n idempotencyKey: string;\n providerAttemptId: string | null;\n topupId: string;\n quantity: number;\n state: BillingAutoRechargeAttemptState;\n windowStart: string;\n windowEnd: string;\n quotedAmountMinor: number | null;\n currency: string | null;\n failureCode: string | null;\n failureMessage: string | null;\n metadata: Record<string, unknown>;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface BillingAutoRechargeStatus {\n enabled: boolean;\n state: BillingAutoRechargeState;\n thresholdCredits: Decimal;\n topupKey: string;\n quantity: number;\n maxRecharges: number;\n windowStart: string;\n windowEnd: string;\n rechargesInWindow: number;\n paymentMethodId: string | null;\n paymentMethodLast4: string | null;\n paymentMethodBrand: string | null;\n suspendedReason: string | null;\n pendingAttemptId: string | null;\n quoteAmountMinor: number | null;\n quoteCurrency: string | null;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type Decimal from "decimal.js";
1
+ import type { Decimal } from "decimal.js";
2
2
  export interface BillingGrantResult {
3
3
  mode: "cycle_grant";
4
4
  credits: Decimal;
@@ -1 +1 @@
1
- {"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../../src/billing/types/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,YAAY,CAAC;AAEtC,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,aAAa,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,EAAE,OAAO,CAAC;CACvB;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,KAAK,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;IAC5C,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,kBAAkB,GAAG,IAAI,CAAC;CAClC;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,OAAO,CAAC;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;CACxB"}
1
+ {"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../../src/billing/types/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,aAAa,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,EAAE,OAAO,CAAC;CACvB;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,KAAK,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;IAC5C,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,kBAAkB,GAAG,IAAI,CAAC;CAClC;AAED,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EAAE,OAAO,CAAC;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;IACxB,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;CACxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../../src/billing/types/catalog.ts"],"names":[],"mappings":"","sourcesContent":["import type Decimal from \"decimal.js\";\n\nexport interface BillingGrantResult {\n mode: \"cycle_grant\";\n credits: Decimal;\n bucket: string;\n replacePrior: boolean;\n}\n\nexport interface BillingOfferResult {\n offerId: string;\n offerKey: string;\n planId: string;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n intervalCount: number;\n grant: BillingGrantResult | null;\n}\n\nexport interface BillingTopupResult {\n topupId: string;\n topupKey: string;\n creditsPerUnit: Decimal;\n depositTo: string;\n amountMinor: number;\n currency: string;\n minQuantity: number;\n maxQuantity: number;\n defaultQuantity: number;\n minAmountMinor: number;\n maxAmountMinor: number;\n}\n"]}
1
+ {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../../src/billing/types/catalog.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport interface BillingGrantResult {\n mode: \"cycle_grant\";\n credits: Decimal;\n bucket: string;\n replacePrior: boolean;\n}\n\nexport interface BillingOfferResult {\n offerId: string;\n offerKey: string;\n planId: string;\n plan: string;\n interval: \"day\" | \"week\" | \"month\" | \"year\";\n intervalCount: number;\n grant: BillingGrantResult | null;\n}\n\nexport interface BillingTopupResult {\n topupId: string;\n topupKey: string;\n creditsPerUnit: Decimal;\n depositTo: string;\n amountMinor: number;\n currency: string;\n minQuantity: number;\n maxQuantity: number;\n defaultQuantity: number;\n minAmountMinor: number;\n maxAmountMinor: number;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type Decimal from "decimal.js";
1
+ import type { Decimal } from "decimal.js";
2
2
  import type { ProviderRef } from "./common.js";
3
3
  export interface BillingCustomerInfo {
4
4
  providerCustomerId?: string | null;
@@ -1 +1 @@
1
- {"version":3,"file":"documents.d.ts","sourceRoot":"","sources":["../../../src/billing/types/documents.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,YAAY,CAAC;AACtC,OAAO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AO,CAAC,CAAC;CACnC;AAED,wEAAwE;AACxE,MAAM,WAAW,0BAA0B;IACzC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,YAAY,EAAE,OAAO,GAAG,IAAI,CAAC;IAC7B,QAAQ,EAAE,OAAO,CAAC;IAClB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IAChC,gBAAgB,EAAE,MAAM,CAAC;IACzB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,MAAM,EAAE,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,UAAU,CAAC;CACzD;AAED,MAAM,WAAW,kBAAkB;IACjC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,MAAM,EAAE,gBAAgB,GAAG,cAAc,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,CAAC;IACtE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"documents.js","sourceRoot":"","sources":["../../../src/billing/types/documents.ts"],"names":[],"mappings":"","sourcesContent":["import type Decimal from \"decimal.js\";\nimport type { ProviderRef } from \"./common.js\";\n\nexport interface BillingCustomerInfo {\n providerCustomerId?: string | null;\n email?: string | null;\n}\n\nexport interface BillingInvoiceInfo {\n providerInvoiceId: string;\n status: \"draft\" | \"open\" | \"paid\" | \"void\" | \"uncollectible\";\n amountPaidMinor: number;\n amountDueMinor: number;\n currency: string;\n periodStart?: string | null;\n periodEnd?: string | null;\n}\n\n/** Persisted invoice document returned from account-level billing queries. */\nexport interface BillingInvoiceRecord extends BillingInvoiceInfo {\n provider: string;\n}\n\nexport interface BillingPaymentInfo {\n providerPaymentId: string;\n amountMinor: number;\n taxMinor: number;\n currency: string;\n refs?: ProviderRef | null;\n purpose: \"subscription\" | \"credit_topup\";\n status: \"pending\" | \"succeeded\" | \"failed\" | \"canceled\";\n}\n\n/** Persisted payment state used by billing lifecycle handlers. */\nexport interface BillingPaymentRecord {\n id: string;\n provider: string;\n providerPaymentId: string;\n providerInvoiceId: string | null;\n userId: string;\n amountMinor: number;\n taxMinor: number;\n currency: string;\n purpose: \"subscription\" | \"credit_topup\";\n status: \"pending\" | \"succeeded\" | \"failed\" | \"canceled\";\n providerUpdatedAt: string;\n metadata: Record<string, unknown>;\n}\n\n/** Result of posting a billing grant or refund to the credit ledger. */\nexport interface BillingCreditPostingResult {\n ledgerEntryId: string | null;\n balanceAfter: Decimal | null;\n replayed: boolean;\n errorCode: string | null;\n}\n\nexport interface BillingRefundInfo {\n providerRefundId: string;\n providerPaymentId: string;\n amountMinor: number;\n currency: string;\n reason?: string | null;\n status: \"pending\" | \"succeeded\" | \"failed\" | \"canceled\";\n}\n\nexport interface BillingDisputeInfo {\n providerDisputeId: string;\n providerPaymentId: string;\n status: \"needs_response\" | \"under_review\" | \"won\" | \"lost\" | \"closed\";\n reason?: string | null;\n}\n"]}
1
+ {"version":3,"file":"documents.js","sourceRoot":"","sources":["../../../src/billing/types/documents.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { ProviderRef } from \"./common.js\";\n\nexport interface BillingCustomerInfo {\n providerCustomerId?: string | null;\n email?: string | null;\n}\n\nexport interface BillingInvoiceInfo {\n providerInvoiceId: string;\n status: \"draft\" | \"open\" | \"paid\" | \"void\" | \"uncollectible\";\n amountPaidMinor: number;\n amountDueMinor: number;\n currency: string;\n periodStart?: string | null;\n periodEnd?: string | null;\n}\n\n/** Persisted invoice document returned from account-level billing queries. */\nexport interface BillingInvoiceRecord extends BillingInvoiceInfo {\n provider: string;\n}\n\nexport interface BillingPaymentInfo {\n providerPaymentId: string;\n amountMinor: number;\n taxMinor: number;\n currency: string;\n refs?: ProviderRef | null;\n purpose: \"subscription\" | \"credit_topup\";\n status: \"pending\" | \"succeeded\" | \"failed\" | \"canceled\";\n}\n\n/** Persisted payment state used by billing lifecycle handlers. */\nexport interface BillingPaymentRecord {\n id: string;\n provider: string;\n providerPaymentId: string;\n providerInvoiceId: string | null;\n userId: string;\n amountMinor: number;\n taxMinor: number;\n currency: string;\n purpose: \"subscription\" | \"credit_topup\";\n status: \"pending\" | \"succeeded\" | \"failed\" | \"canceled\";\n providerUpdatedAt: string;\n metadata: Record<string, unknown>;\n}\n\n/** Result of posting a billing grant or refund to the credit ledger. */\nexport interface BillingCreditPostingResult {\n ledgerEntryId: string | null;\n balanceAfter: Decimal | null;\n replayed: boolean;\n errorCode: string | null;\n}\n\nexport interface BillingRefundInfo {\n providerRefundId: string;\n providerPaymentId: string;\n amountMinor: number;\n currency: string;\n reason?: string | null;\n status: \"pending\" | \"succeeded\" | \"failed\" | \"canceled\";\n}\n\nexport interface BillingDisputeInfo {\n providerDisputeId: string;\n providerPaymentId: string;\n status: \"needs_response\" | \"under_review\" | \"won\" | \"lost\" | \"closed\";\n reason?: string | null;\n}\n"]}
@@ -43,7 +43,8 @@ export interface BillingEvent {
43
43
  eventId: string;
44
44
  eventType: BillingEventType;
45
45
  occurredAt: string;
46
- userId?: string | null;
46
+ /** Financial subject affected by this provider event. */
47
+ accountId?: string | null;
47
48
  customer?: BillingCustomerInfo | null;
48
49
  subscription?: BillingSubscriptionInfo | null;
49
50
  invoice?: BillingInvoiceInfo | null;
@@ -56,7 +57,7 @@ export interface BillingEvent {
56
57
  }
57
58
  /** Validate an event at the public ingestion boundary before claiming it. */
58
59
  export declare function assertBillingEvent(value: unknown): asserts value is BillingEvent;
59
- export type BillingEventHandler = (event: BillingEvent, userId: string) => Promise<void>;
60
+ export type BillingEventHandler = (event: BillingEvent, accountId: string) => Promise<void>;
60
61
  export interface BillingEventResult {
61
62
  handled: boolean;
62
63
  action?: string | null;
@@ -71,6 +72,14 @@ export type BillingEventClaim = {
71
72
  status: "duplicate";
72
73
  } | {
73
74
  status: "busy";
75
+ } | {
76
+ status: "invalid_request";
77
+ } | {
78
+ status: "idempotency_conflict";
79
+ billingEventId: string;
80
+ } | {
81
+ status: "max_retries_exceeded";
82
+ billingEventId: string;
74
83
  } | {
75
84
  status: "retry";
76
85
  };
@@ -1 +1 @@
1
- {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../../src/billing/types/events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,kBAAkB,EAClB,kBAAkB,EAClB,kBAAkB,EAClB,iBAAiB,EAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAElE,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoCnB,CAAC;AAEX,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,OAAO,gBAAgB,CAAC,CAAC;AAExF,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,gBAAgB,CAAC;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,QAAQ,CAAC,EAAE,mBAAmB,GAAG,IAAI,CAAC;IACtC,YAAY,CAAC,EAAE,uBAAuB,GAAG,IAAI,CAAC;IAC9C,OAAO,CAAC,EAAE,kBAAkB,GAAG,IAAI,CAAC;IACpC,OAAO,CAAC,EAAE,kBAAkB,GAAG,IAAI,CAAC;IACpC,MAAM,CAAC,EAAE,iBAAiB,GAAG,IAAI,CAAC;IAClC,OAAO,CAAC,EAAE,kBAAkB,GAAG,IAAI,CAAC;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAC1C,GAAG,CAAC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vB;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,GAClB;IAAE,MAAM,EAAE,iBAAiB,CAAA;CAAE,GAC7B;IAAE,MAAM,EAAE,sBAAsB,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,GAC1D;IAAE,MAAM,EAAE,sBAAsB,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,GAC1D;IAAE,MAAM,EAAE,OAAO,CAAA;CAAE,CAAC"}
@@ -129,7 +129,7 @@ export function assertBillingEvent(value) {
129
129
  "eventId",
130
130
  "eventType",
131
131
  "occurredAt",
132
- "userId",
132
+ "accountId",
133
133
  "customer",
134
134
  "subscription",
135
135
  "invoice",
@@ -143,7 +143,7 @@ export function assertBillingEvent(value) {
143
143
  const event = record;
144
144
  requireNonEmptyString(event.provider, "billing event provider");
145
145
  requireNonEmptyString(event.eventId, "billing event id");
146
- requireOptionalNonEmptyString(event.userId, "billing event userId");
146
+ requireOptionalNonEmptyString(event.accountId, "billing event accountId");
147
147
  requireOptionalNonEmptyString(event.billingEventId, "billing event billingEventId");
148
148
  if (event.metadata !== null && event.metadata !== undefined) {
149
149
  requireObject(event.metadata, "billing event metadata");
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","sourceRoot":"","sources":["../../../src/billing/types/events.ts"],"names":[],"mappings":"AASA,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,gBAAgB,EAAE,kBAAkB;IACpC,gBAAgB,EAAE,kBAAkB;IACpC,gBAAgB,EAAE,kBAAkB;IACpC,kBAAkB,EAAE,oBAAoB;IACxC,gBAAgB,EAAE,kBAAkB;IACpC,oBAAoB,EAAE,sBAAsB;IAC5C,oBAAoB,EAAE,sBAAsB;IAC5C,sBAAsB,EAAE,wBAAwB;IAChD,oBAAoB,EAAE,sBAAsB;IAC5C,yBAAyB,EAAE,2BAA2B;IACtD,mCAAmC,EAAE,qCAAqC;IAC1E,qCAAqC,EAAE,uCAAuC;IAC9E,qBAAqB,EAAE,uBAAu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,SAAS,4BAA4B,CAAC,CAAC;QAC3F,qBAAqB,CAAC,OAAO,CAAC,iBAAiB,EAAE,GAAG,SAAS,4BAA4B,CAAC,CAAC;QAC3F,YAAY,CAAC,OAAO,CAAC,MAAM,EAAE,gBAAgB,EAAE,GAAG,SAAS,iBAAiB,CAAC,CAAC;QAC9E,qBAAqB,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,SAAS,iBAAiB,CAAC,CAAC;IACvE,CAAC;SAAM,IAAI,SAAS,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;QAC5C,MAAM,IAAI,SAAS,CAAC,GAAG,SAAS,wBAAwB,CAAC,CAAC;IAC5D,CAAC;AACH,CAAC","sourcesContent":["import type {\n BillingCustomerInfo,\n BillingDisputeInfo,\n BillingInvoiceInfo,\n BillingPaymentInfo,\n BillingRefundInfo,\n} from \"./documents.js\";\nimport type { BillingSubscriptionInfo } from \"./subscriptions.js\";\n\nexport const BillingEventType = {\n CUSTOMER_CREATED: \"customer.created\",\n CUSTOMER_UPDATED: \"customer.updated\",\n CUSTOMER_DELETED: \"customer.deleted\",\n CHECKOUT_COMPLETED: \"checkout.completed\",\n CHECKOUT_EXPIRED: \"checkout.expired\",\n SUBSCRIPTION_CREATED: \"subscription.created\",\n SUBSCRIPTION_UPDATED: \"subscription.updated\",\n SUBSCRIPTION_ACTIVATED: \"subscription.activated\",\n SUBSCRIPTION_RENEWED: \"subscription.renewed\",\n SUBSCRIPTION_PLAN_CHANGED: \"subscription.plan_changed\",\n SUBSCRIPTION_CANCELLATION_SCHEDULED: \"subscription.cancellation_scheduled\",\n SUBSCRIPTION_CANCELLATION_UNSCHEDULED: \"subscription.cancellation_unscheduled\",\n SUBSCRIPTION_CANCELED: \"subscription.canceled\",\n SUBSCRIPTION_EXPIRED: \"subscription.expired\",\n SUBSCRIPTION_PAUSED: \"subscription.paused\",\n SUBSCRIPTION_RESUMED: \"subscription.resumed\",\n SUBSCRIPTION_TRIAL_WILL_END: \"subscription.trial_will_end\",\n INVOICE_CREATED: \"invoice.created\",\n INVOICE_FINALIZED: \"invoice.finalized\",\n INVOICE_FINALIZATION_FAILED: \"invoice.finalization_failed\",\n INVOICE_UPCOMING: \"invoice.upcoming\",\n INVOICE_PAID: \"invoice.paid\",\n INVOICE_PAYMENT_FAILED: \"invoice.payment_failed\",\n INVOICE_PAYMENT_ACTION_REQUIRED: \"invoice.payment_action_required\",\n INVOICE_VOIDED: \"invoice.voided\",\n PAYMENT_SUCCEEDED: \"payment.succeeded\",\n PAYMENT_FAILED: \"payment.failed\",\n REFUND_CREATED: \"refund.created\",\n REFUND_UPDATED: \"refund.updated\",\n REFUND_FAILED: \"refund.failed\",\n DISPUTE_CREATED: \"dispute.created\",\n DISPUTE_CLOSED: \"dispute.closed\",\n PAYMENT_METHOD_ATTACHED: \"payment_method.attached\",\n PAYMENT_METHOD_UPDATED: \"payment_method.updated\",\n PAYMENT_METHOD_DETACHED: \"payment_method.detached\",\n} as const;\n\nexport type BillingEventType = (typeof BillingEventType)[keyof typeof BillingEventType];\n\nexport interface BillingEvent {\n provider: string;\n eventId: string;\n eventType: BillingEventType;\n occurredAt: string;\n userId?: string | null;\n customer?: BillingCustomerInfo | null;\n subscription?: BillingSubscriptionInfo | null;\n invoice?: BillingInvoiceInfo | null;\n payment?: BillingPaymentInfo | null;\n refund?: BillingRefundInfo | null;\n dispute?: BillingDisputeInfo | null;\n metadata?: Record<string, unknown> | null;\n raw?: unknown;\n billingEventId?: string;\n}\n\nconst BILLING_EVENT_TYPES = new Set<string>(Object.values(BillingEventType));\nconst SUBSCRIPTION_STATUSES = new Set([\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"canceled\",\n \"unpaid\",\n \"paused\",\n \"expired\",\n]);\nconst BILLING_INTERVALS = new Set([\"day\", \"week\", \"month\", \"year\"]);\nconst INVOICE_STATUSES = new Set([\"draft\", \"open\", \"paid\", \"void\", \"uncollectible\"]);\nconst PAYMENT_PURPOSES = new Set([\"subscription\", \"credit_topup\"]);\nconst PAYMENT_STATUSES = new Set([\"pending\", \"succeeded\", \"failed\", \"canceled\"]);\nconst DISPUTE_STATUSES = new Set([\"needs_response\", \"under_review\", \"won\", \"lost\", \"closed\"]);\nconst ISO_INSTANT_WITH_OFFSET = /(?:Z|[+-]\\d{2}:\\d{2})$/;\n\nfunction requireObject(value: unknown, field: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${field} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction rejectUnknownKeys(\n value: Record<string, unknown>,\n allowed: readonly string[],\n field: string,\n) {\n const known = new Set(allowed);\n const unknown = Object.keys(value).filter((key) => !known.has(key));\n if (unknown.length > 0) {\n throw new TypeError(\n `${field} contains unsupported field${unknown.length === 1 ? \"\" : \"s\"}: ${unknown.join(\", \")}`,\n );\n }\n}\n\nfunction requireNonEmptyString(value: unknown, field: string): void {\n if (typeof value !== \"string\" || !value.trim()) {\n throw new TypeError(`${field} must be a non-empty string`);\n }\n}\n\nfunction requireOptionalNonEmptyString(value: unknown, field: string): void {\n if (value !== null && value !== undefined) requireNonEmptyString(value, field);\n}\n\nfunction requireOptionalString(value: unknown, field: string): void {\n if (value !== null && value !== undefined && typeof value !== \"string\") {\n throw new TypeError(`${field} must be a string`);\n }\n}\n\nfunction requireOptionalBoolean(value: unknown, field: string): void {\n if (value !== null && value !== undefined && typeof value !== \"boolean\") {\n throw new TypeError(`${field} must be a boolean`);\n }\n}\n\nfunction requireOneOf(value: unknown, allowed: ReadonlySet<string>, field: string): void {\n if (typeof value !== \"string\" || !allowed.has(value)) {\n throw new TypeError(`${field} has an unsupported value`);\n }\n}\n\nfunction validateProviderRef(value: unknown, field: string): void {\n if (value === null || value === undefined) return;\n const reference = requireObject(value, field);\n const keys = [\"productId\", \"priceId\", \"variantId\", \"lookupKey\"] as const;\n rejectUnknownKeys(reference, keys, field);\n for (const key of keys) requireOptionalNonEmptyString(reference[key], `${field}.${key}`);\n if (!keys.some((key) => reference[key] !== null && reference[key] !== undefined)) {\n throw new TypeError(`${field} must contain a provider identifier`);\n }\n}\n\nfunction requireMinorUnits(value: unknown, field: string, positive = false): void {\n if (!Number.isSafeInteger(value) || (value as number) < (positive ? 1 : 0)) {\n throw new TypeError(\n `${field} must be a ${positive ? \"positive\" : \"non-negative\"} safe integer`,\n );\n }\n}\n\nfunction requireCurrency(value: unknown, field: string): void {\n if (typeof value !== \"string\" || !/^[A-Z]{3}$/.test(value)) {\n throw new TypeError(`${field} must be an uppercase three-letter currency code`);\n }\n}\n\nfunction requireOptionalInstant(value: unknown, field: string): void {\n if (value === null || value === undefined) return;\n if (\n typeof value !== \"string\" ||\n !ISO_INSTANT_WITH_OFFSET.test(value) ||\n Number.isNaN(Date.parse(value))\n ) {\n throw new TypeError(`${field} must be an ISO 8601 instant with an offset`);\n }\n}\n\n/** Validate an event at the public ingestion boundary before claiming it. */\nexport function assertBillingEvent(value: unknown): asserts value is BillingEvent {\n const record = requireObject(value, \"billing event\");\n rejectUnknownKeys(\n record,\n [\n \"provider\",\n \"eventId\",\n \"eventType\",\n \"occurredAt\",\n \"userId\",\n \"customer\",\n \"subscription\",\n \"invoice\",\n \"payment\",\n \"refund\",\n \"dispute\",\n \"metadata\",\n \"raw\",\n \"billingEventId\",\n ],\n \"billing event\",\n );\n const event = record as unknown as BillingEvent;\n requireNonEmptyString(event.provider, \"billing event provider\");\n requireNonEmptyString(event.eventId, \"billing event id\");\n requireOptionalNonEmptyString(event.userId, \"billing event userId\");\n requireOptionalNonEmptyString(event.billingEventId, \"billing event billingEventId\");\n if (event.metadata !== null && event.metadata !== undefined) {\n requireObject(event.metadata, \"billing event metadata\");\n }\n if (!BILLING_EVENT_TYPES.has(event.eventType)) {\n throw new TypeError(`unsupported billing event type: ${String(event.eventType)}`);\n }\n if (\n typeof event.occurredAt !== \"string\" ||\n !ISO_INSTANT_WITH_OFFSET.test(event.occurredAt) ||\n Number.isNaN(Date.parse(event.occurredAt))\n ) {\n throw new TypeError(\"billing event occurredAt must be an ISO 8601 instant with an offset\");\n }\n\n const eventName: string = event.eventType;\n if (event.customer !== null && event.customer !== undefined) {\n const customer = requireObject(event.customer, `${eventName} customer`);\n rejectUnknownKeys(customer, [\"providerCustomerId\", \"email\"], `${eventName} customer`);\n requireOptionalNonEmptyString(\n customer.providerCustomerId,\n `${eventName} customer.providerCustomerId`,\n );\n requireOptionalNonEmptyString(customer.email, `${eventName} customer.email`);\n if (customer.providerCustomerId == null && customer.email == null) {\n throw new TypeError(`${eventName} customer requires providerCustomerId or email`);\n }\n } else if (eventName.startsWith(\"customer.\")) {\n throw new TypeError(`${eventName} requires customer data`);\n }\n if (event.subscription !== null && event.subscription !== undefined) {\n const subscription = requireObject(event.subscription, `${eventName} subscription`);\n rejectUnknownKeys(\n subscription,\n [\n \"providerSubscriptionId\",\n \"status\",\n \"cancelAtPeriodEnd\",\n \"periodStart\",\n \"periodEnd\",\n \"trialEnd\",\n \"cancelAt\",\n \"endedAt\",\n \"refs\",\n \"interval\",\n \"intervalCount\",\n ],\n `${eventName} subscription`,\n );\n requireNonEmptyString(\n subscription.providerSubscriptionId,\n `${eventName} subscription.providerSubscriptionId`,\n );\n if (subscription.status != null) {\n requireOneOf(subscription.status, SUBSCRIPTION_STATUSES, `${eventName} subscription.status`);\n }\n requireOptionalBoolean(\n subscription.cancelAtPeriodEnd,\n `${eventName} subscription.cancelAtPeriodEnd`,\n );\n for (const [field, value] of [\n [\"periodStart\", subscription.periodStart],\n [\"periodEnd\", subscription.periodEnd],\n [\"trialEnd\", subscription.trialEnd],\n [\"cancelAt\", subscription.cancelAt],\n [\"endedAt\", subscription.endedAt],\n ] as const) {\n requireOptionalInstant(value, `${eventName} subscription.${field}`);\n }\n validateProviderRef(subscription.refs, `${eventName} subscription.refs`);\n if (subscription.interval != null) {\n requireOneOf(subscription.interval, BILLING_INTERVALS, `${eventName} subscription.interval`);\n }\n if (\n subscription.intervalCount !== null &&\n subscription.intervalCount !== undefined &&\n (!Number.isSafeInteger(subscription.intervalCount) ||\n (subscription.intervalCount as number) <= 0)\n ) {\n throw new TypeError(\n `${eventName} subscription.intervalCount must be a positive safe integer`,\n );\n }\n } else if (eventName.startsWith(\"subscription.\")) {\n throw new TypeError(`${eventName} requires subscription data`);\n }\n if (event.invoice !== null && event.invoice !== undefined) {\n const invoice = requireObject(event.invoice, `${eventName} invoice`);\n rejectUnknownKeys(\n invoice,\n [\n \"providerInvoiceId\",\n \"status\",\n \"amountPaidMinor\",\n \"amountDueMinor\",\n \"currency\",\n \"periodStart\",\n \"periodEnd\",\n ],\n `${eventName} invoice`,\n );\n requireNonEmptyString(invoice.providerInvoiceId, `${eventName} invoice.providerInvoiceId`);\n requireOneOf(invoice.status, INVOICE_STATUSES, `${eventName} invoice.status`);\n requireMinorUnits(invoice.amountPaidMinor, `${eventName} invoice.amountPaidMinor`);\n requireMinorUnits(invoice.amountDueMinor, `${eventName} invoice.amountDueMinor`);\n requireCurrency(invoice.currency, `${eventName} invoice.currency`);\n requireOptionalInstant(invoice.periodStart, `${eventName} invoice.periodStart`);\n requireOptionalInstant(invoice.periodEnd, `${eventName} invoice.periodEnd`);\n } else if (eventName.startsWith(\"invoice.\")) {\n throw new TypeError(`${eventName} requires invoice data`);\n }\n if (event.payment !== null && event.payment !== undefined) {\n const payment = requireObject(event.payment, `${eventName} payment`);\n rejectUnknownKeys(\n payment,\n [\"providerPaymentId\", \"amountMinor\", \"taxMinor\", \"currency\", \"refs\", \"purpose\", \"status\"],\n `${eventName} payment`,\n );\n requireNonEmptyString(payment.providerPaymentId, `${eventName} payment.providerPaymentId`);\n requireMinorUnits(payment.amountMinor, `${eventName} payment.amountMinor`);\n requireMinorUnits(payment.taxMinor, `${eventName} payment.taxMinor`);\n requireCurrency(payment.currency, `${eventName} payment.currency`);\n validateProviderRef(payment.refs, `${eventName} payment.refs`);\n requireOneOf(payment.purpose, PAYMENT_PURPOSES, `${eventName} payment.purpose`);\n requireOneOf(payment.status, PAYMENT_STATUSES, `${eventName} payment.status`);\n } else if (eventName.startsWith(\"payment.\")) {\n throw new TypeError(`${eventName} requires payment data`);\n }\n if (event.refund !== null && event.refund !== undefined) {\n const refund = requireObject(event.refund, `${eventName} refund`);\n rejectUnknownKeys(\n refund,\n [\"providerRefundId\", \"providerPaymentId\", \"amountMinor\", \"currency\", \"reason\", \"status\"],\n `${eventName} refund`,\n );\n requireNonEmptyString(refund.providerRefundId, `${eventName} refund.providerRefundId`);\n requireNonEmptyString(refund.providerPaymentId, `${eventName} refund.providerPaymentId`);\n requireMinorUnits(refund.amountMinor, `${eventName} refund.amountMinor`, true);\n requireCurrency(refund.currency, `${eventName} refund.currency`);\n requireOptionalString(refund.reason, `${eventName} refund.reason`);\n requireOneOf(refund.status, PAYMENT_STATUSES, `${eventName} refund.status`);\n } else if (eventName.startsWith(\"refund.\")) {\n throw new TypeError(`${eventName} requires refund data`);\n }\n if (event.dispute !== null && event.dispute !== undefined) {\n const dispute = requireObject(event.dispute, `${eventName} dispute`);\n rejectUnknownKeys(\n dispute,\n [\"providerDisputeId\", \"providerPaymentId\", \"status\", \"reason\"],\n `${eventName} dispute`,\n );\n requireNonEmptyString(dispute.providerDisputeId, `${eventName} dispute.providerDisputeId`);\n requireNonEmptyString(dispute.providerPaymentId, `${eventName} dispute.providerPaymentId`);\n requireOneOf(dispute.status, DISPUTE_STATUSES, `${eventName} dispute.status`);\n requireOptionalString(dispute.reason, `${eventName} dispute.reason`);\n } else if (eventName.startsWith(\"dispute.\")) {\n throw new TypeError(`${eventName} requires dispute data`);\n }\n}\n\nexport type BillingEventHandler = (event: BillingEvent, userId: string) => Promise<void>;\n\nexport interface BillingEventResult {\n handled: boolean;\n action?: string | null;\n error?: string | null;\n subscriptionId?: string | null;\n}\n\nexport type BillingEventClaim =\n | { status: \"claimed\"; claimToken: string; billingEventId: string }\n | { status: \"duplicate\" }\n | { status: \"busy\" }\n | { status: \"retry\" };\n"]}
1
+ {"version":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AAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QAC3C,MAAM,IAAI,SAAS,CAAC,GAAG,SAAS,uBAAuB,CAAC,CAAC;IAC3D,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1D,MAAM,OAAO,GAAG,aAAa,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,SAAS,UAAU,CAAC,CAAC;QACrE,iBAAiB,CACf,OAAO,EACP,CAAC,mBAAmB,EAAE,mBAAmB,EAAE,QAAQ,EAAE,QAAQ,CAAC,EAC9D,GAAG,SAAS,UAAU,CACvB,CAAC;QACF,qBAAqB,CAAC,OAAO,CAAC,iBAAiB,EAAE,GAAG,SAAS,4BAA4B,CAAC,CAAC;QAC3F,qBAAqB,CAAC,OAAO,CAAC,iBAAiB,EAAE,GAAG,SAAS,4BAA4B,CAAC,CAAC;QAC3F,YAAY,CAAC,OAAO,CAAC,MAAM,EAAE,gBAAgB,EAAE,GAAG,SAAS,iBAAiB,CAAC,CAAC;QAC9E,qBAAqB,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,SAAS,iBAAiB,CAAC,CAAC;IACvE,CAAC;SAAM,IAAI,SAAS,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;QAC5C,MAAM,IAAI,SAAS,CAAC,GAAG,SAAS,wBAAwB,CAAC,CAAC;IAC5D,CAAC;AACH,CAAC","sourcesContent":["import type {\n BillingCustomerInfo,\n BillingDisputeInfo,\n BillingInvoiceInfo,\n BillingPaymentInfo,\n BillingRefundInfo,\n} from \"./documents.js\";\nimport type { BillingSubscriptionInfo } from \"./subscriptions.js\";\n\nexport const BillingEventType = {\n CUSTOMER_CREATED: \"customer.created\",\n CUSTOMER_UPDATED: \"customer.updated\",\n CUSTOMER_DELETED: \"customer.deleted\",\n CHECKOUT_COMPLETED: \"checkout.completed\",\n CHECKOUT_EXPIRED: \"checkout.expired\",\n SUBSCRIPTION_CREATED: \"subscription.created\",\n SUBSCRIPTION_UPDATED: \"subscription.updated\",\n SUBSCRIPTION_ACTIVATED: \"subscription.activated\",\n SUBSCRIPTION_RENEWED: \"subscription.renewed\",\n SUBSCRIPTION_PLAN_CHANGED: \"subscription.plan_changed\",\n SUBSCRIPTION_CANCELLATION_SCHEDULED: \"subscription.cancellation_scheduled\",\n SUBSCRIPTION_CANCELLATION_UNSCHEDULED: \"subscription.cancellation_unscheduled\",\n SUBSCRIPTION_CANCELED: \"subscription.canceled\",\n SUBSCRIPTION_EXPIRED: \"subscription.expired\",\n SUBSCRIPTION_PAUSED: \"subscription.paused\",\n SUBSCRIPTION_RESUMED: \"subscription.resumed\",\n SUBSCRIPTION_TRIAL_WILL_END: \"subscription.trial_will_end\",\n INVOICE_CREATED: \"invoice.created\",\n INVOICE_FINALIZED: \"invoice.finalized\",\n INVOICE_FINALIZATION_FAILED: \"invoice.finalization_failed\",\n INVOICE_UPCOMING: \"invoice.upcoming\",\n INVOICE_PAID: \"invoice.paid\",\n INVOICE_PAYMENT_FAILED: \"invoice.payment_failed\",\n INVOICE_PAYMENT_ACTION_REQUIRED: \"invoice.payment_action_required\",\n INVOICE_VOIDED: \"invoice.voided\",\n PAYMENT_SUCCEEDED: \"payment.succeeded\",\n PAYMENT_FAILED: \"payment.failed\",\n REFUND_CREATED: \"refund.created\",\n REFUND_UPDATED: \"refund.updated\",\n REFUND_FAILED: \"refund.failed\",\n DISPUTE_CREATED: \"dispute.created\",\n DISPUTE_CLOSED: \"dispute.closed\",\n PAYMENT_METHOD_ATTACHED: \"payment_method.attached\",\n PAYMENT_METHOD_UPDATED: \"payment_method.updated\",\n PAYMENT_METHOD_DETACHED: \"payment_method.detached\",\n} as const;\n\nexport type BillingEventType = (typeof BillingEventType)[keyof typeof BillingEventType];\n\nexport interface BillingEvent {\n provider: string;\n eventId: string;\n eventType: BillingEventType;\n occurredAt: string;\n /** Financial subject affected by this provider event. */\n accountId?: string | null;\n customer?: BillingCustomerInfo | null;\n subscription?: BillingSubscriptionInfo | null;\n invoice?: BillingInvoiceInfo | null;\n payment?: BillingPaymentInfo | null;\n refund?: BillingRefundInfo | null;\n dispute?: BillingDisputeInfo | null;\n metadata?: Record<string, unknown> | null;\n raw?: unknown;\n billingEventId?: string;\n}\n\nconst BILLING_EVENT_TYPES = new Set<string>(Object.values(BillingEventType));\nconst SUBSCRIPTION_STATUSES = new Set([\n \"incomplete\",\n \"incomplete_expired\",\n \"trialing\",\n \"active\",\n \"past_due\",\n \"canceled\",\n \"unpaid\",\n \"paused\",\n \"expired\",\n]);\nconst BILLING_INTERVALS = new Set([\"day\", \"week\", \"month\", \"year\"]);\nconst INVOICE_STATUSES = new Set([\"draft\", \"open\", \"paid\", \"void\", \"uncollectible\"]);\nconst PAYMENT_PURPOSES = new Set([\"subscription\", \"credit_topup\"]);\nconst PAYMENT_STATUSES = new Set([\"pending\", \"succeeded\", \"failed\", \"canceled\"]);\nconst DISPUTE_STATUSES = new Set([\"needs_response\", \"under_review\", \"won\", \"lost\", \"closed\"]);\nconst ISO_INSTANT_WITH_OFFSET = /(?:Z|[+-]\\d{2}:\\d{2})$/;\n\nfunction requireObject(value: unknown, field: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${field} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction rejectUnknownKeys(\n value: Record<string, unknown>,\n allowed: readonly string[],\n field: string,\n) {\n const known = new Set(allowed);\n const unknown = Object.keys(value).filter((key) => !known.has(key));\n if (unknown.length > 0) {\n throw new TypeError(\n `${field} contains unsupported field${unknown.length === 1 ? \"\" : \"s\"}: ${unknown.join(\", \")}`,\n );\n }\n}\n\nfunction requireNonEmptyString(value: unknown, field: string): void {\n if (typeof value !== \"string\" || !value.trim()) {\n throw new TypeError(`${field} must be a non-empty string`);\n }\n}\n\nfunction requireOptionalNonEmptyString(value: unknown, field: string): void {\n if (value !== null && value !== undefined) requireNonEmptyString(value, field);\n}\n\nfunction requireOptionalString(value: unknown, field: string): void {\n if (value !== null && value !== undefined && typeof value !== \"string\") {\n throw new TypeError(`${field} must be a string`);\n }\n}\n\nfunction requireOptionalBoolean(value: unknown, field: string): void {\n if (value !== null && value !== undefined && typeof value !== \"boolean\") {\n throw new TypeError(`${field} must be a boolean`);\n }\n}\n\nfunction requireOneOf(value: unknown, allowed: ReadonlySet<string>, field: string): void {\n if (typeof value !== \"string\" || !allowed.has(value)) {\n throw new TypeError(`${field} has an unsupported value`);\n }\n}\n\nfunction validateProviderRef(value: unknown, field: string): void {\n if (value === null || value === undefined) return;\n const reference = requireObject(value, field);\n const keys = [\"productId\", \"priceId\", \"variantId\", \"lookupKey\"] as const;\n rejectUnknownKeys(reference, keys, field);\n for (const key of keys) requireOptionalNonEmptyString(reference[key], `${field}.${key}`);\n if (!keys.some((key) => reference[key] !== null && reference[key] !== undefined)) {\n throw new TypeError(`${field} must contain a provider identifier`);\n }\n}\n\nfunction requireMinorUnits(value: unknown, field: string, positive = false): void {\n if (!Number.isSafeInteger(value) || (value as number) < (positive ? 1 : 0)) {\n throw new TypeError(\n `${field} must be a ${positive ? \"positive\" : \"non-negative\"} safe integer`,\n );\n }\n}\n\nfunction requireCurrency(value: unknown, field: string): void {\n if (typeof value !== \"string\" || !/^[A-Z]{3}$/.test(value)) {\n throw new TypeError(`${field} must be an uppercase three-letter currency code`);\n }\n}\n\nfunction requireOptionalInstant(value: unknown, field: string): void {\n if (value === null || value === undefined) return;\n if (\n typeof value !== \"string\" ||\n !ISO_INSTANT_WITH_OFFSET.test(value) ||\n Number.isNaN(Date.parse(value))\n ) {\n throw new TypeError(`${field} must be an ISO 8601 instant with an offset`);\n }\n}\n\n/** Validate an event at the public ingestion boundary before claiming it. */\nexport function assertBillingEvent(value: unknown): asserts value is BillingEvent {\n const record = requireObject(value, \"billing event\");\n rejectUnknownKeys(\n record,\n [\n \"provider\",\n \"eventId\",\n \"eventType\",\n \"occurredAt\",\n \"accountId\",\n \"customer\",\n \"subscription\",\n \"invoice\",\n \"payment\",\n \"refund\",\n \"dispute\",\n \"metadata\",\n \"raw\",\n \"billingEventId\",\n ],\n \"billing event\",\n );\n const event = record as unknown as BillingEvent;\n requireNonEmptyString(event.provider, \"billing event provider\");\n requireNonEmptyString(event.eventId, \"billing event id\");\n requireOptionalNonEmptyString(event.accountId, \"billing event accountId\");\n requireOptionalNonEmptyString(event.billingEventId, \"billing event billingEventId\");\n if (event.metadata !== null && event.metadata !== undefined) {\n requireObject(event.metadata, \"billing event metadata\");\n }\n if (!BILLING_EVENT_TYPES.has(event.eventType)) {\n throw new TypeError(`unsupported billing event type: ${String(event.eventType)}`);\n }\n if (\n typeof event.occurredAt !== \"string\" ||\n !ISO_INSTANT_WITH_OFFSET.test(event.occurredAt) ||\n Number.isNaN(Date.parse(event.occurredAt))\n ) {\n throw new TypeError(\"billing event occurredAt must be an ISO 8601 instant with an offset\");\n }\n\n const eventName: string = event.eventType;\n if (event.customer !== null && event.customer !== undefined) {\n const customer = requireObject(event.customer, `${eventName} customer`);\n rejectUnknownKeys(customer, [\"providerCustomerId\", \"email\"], `${eventName} customer`);\n requireOptionalNonEmptyString(\n customer.providerCustomerId,\n `${eventName} customer.providerCustomerId`,\n );\n requireOptionalNonEmptyString(customer.email, `${eventName} customer.email`);\n if (customer.providerCustomerId == null && customer.email == null) {\n throw new TypeError(`${eventName} customer requires providerCustomerId or email`);\n }\n } else if (eventName.startsWith(\"customer.\")) {\n throw new TypeError(`${eventName} requires customer data`);\n }\n if (event.subscription !== null && event.subscription !== undefined) {\n const subscription = requireObject(event.subscription, `${eventName} subscription`);\n rejectUnknownKeys(\n subscription,\n [\n \"providerSubscriptionId\",\n \"status\",\n \"cancelAtPeriodEnd\",\n \"periodStart\",\n \"periodEnd\",\n \"trialEnd\",\n \"cancelAt\",\n \"endedAt\",\n \"refs\",\n \"interval\",\n \"intervalCount\",\n ],\n `${eventName} subscription`,\n );\n requireNonEmptyString(\n subscription.providerSubscriptionId,\n `${eventName} subscription.providerSubscriptionId`,\n );\n if (subscription.status != null) {\n requireOneOf(subscription.status, SUBSCRIPTION_STATUSES, `${eventName} subscription.status`);\n }\n requireOptionalBoolean(\n subscription.cancelAtPeriodEnd,\n `${eventName} subscription.cancelAtPeriodEnd`,\n );\n for (const [field, value] of [\n [\"periodStart\", subscription.periodStart],\n [\"periodEnd\", subscription.periodEnd],\n [\"trialEnd\", subscription.trialEnd],\n [\"cancelAt\", subscription.cancelAt],\n [\"endedAt\", subscription.endedAt],\n ] as const) {\n requireOptionalInstant(value, `${eventName} subscription.${field}`);\n }\n validateProviderRef(subscription.refs, `${eventName} subscription.refs`);\n if (subscription.interval != null) {\n requireOneOf(subscription.interval, BILLING_INTERVALS, `${eventName} subscription.interval`);\n }\n if (\n subscription.intervalCount !== null &&\n subscription.intervalCount !== undefined &&\n (!Number.isSafeInteger(subscription.intervalCount) ||\n (subscription.intervalCount as number) <= 0)\n ) {\n throw new TypeError(\n `${eventName} subscription.intervalCount must be a positive safe integer`,\n );\n }\n } else if (eventName.startsWith(\"subscription.\")) {\n throw new TypeError(`${eventName} requires subscription data`);\n }\n if (event.invoice !== null && event.invoice !== undefined) {\n const invoice = requireObject(event.invoice, `${eventName} invoice`);\n rejectUnknownKeys(\n invoice,\n [\n \"providerInvoiceId\",\n \"status\",\n \"amountPaidMinor\",\n \"amountDueMinor\",\n \"currency\",\n \"periodStart\",\n \"periodEnd\",\n ],\n `${eventName} invoice`,\n );\n requireNonEmptyString(invoice.providerInvoiceId, `${eventName} invoice.providerInvoiceId`);\n requireOneOf(invoice.status, INVOICE_STATUSES, `${eventName} invoice.status`);\n requireMinorUnits(invoice.amountPaidMinor, `${eventName} invoice.amountPaidMinor`);\n requireMinorUnits(invoice.amountDueMinor, `${eventName} invoice.amountDueMinor`);\n requireCurrency(invoice.currency, `${eventName} invoice.currency`);\n requireOptionalInstant(invoice.periodStart, `${eventName} invoice.periodStart`);\n requireOptionalInstant(invoice.periodEnd, `${eventName} invoice.periodEnd`);\n } else if (eventName.startsWith(\"invoice.\")) {\n throw new TypeError(`${eventName} requires invoice data`);\n }\n if (event.payment !== null && event.payment !== undefined) {\n const payment = requireObject(event.payment, `${eventName} payment`);\n rejectUnknownKeys(\n payment,\n [\"providerPaymentId\", \"amountMinor\", \"taxMinor\", \"currency\", \"refs\", \"purpose\", \"status\"],\n `${eventName} payment`,\n );\n requireNonEmptyString(payment.providerPaymentId, `${eventName} payment.providerPaymentId`);\n requireMinorUnits(payment.amountMinor, `${eventName} payment.amountMinor`);\n requireMinorUnits(payment.taxMinor, `${eventName} payment.taxMinor`);\n requireCurrency(payment.currency, `${eventName} payment.currency`);\n validateProviderRef(payment.refs, `${eventName} payment.refs`);\n requireOneOf(payment.purpose, PAYMENT_PURPOSES, `${eventName} payment.purpose`);\n requireOneOf(payment.status, PAYMENT_STATUSES, `${eventName} payment.status`);\n } else if (eventName.startsWith(\"payment.\")) {\n throw new TypeError(`${eventName} requires payment data`);\n }\n if (event.refund !== null && event.refund !== undefined) {\n const refund = requireObject(event.refund, `${eventName} refund`);\n rejectUnknownKeys(\n refund,\n [\"providerRefundId\", \"providerPaymentId\", \"amountMinor\", \"currency\", \"reason\", \"status\"],\n `${eventName} refund`,\n );\n requireNonEmptyString(refund.providerRefundId, `${eventName} refund.providerRefundId`);\n requireNonEmptyString(refund.providerPaymentId, `${eventName} refund.providerPaymentId`);\n requireMinorUnits(refund.amountMinor, `${eventName} refund.amountMinor`, true);\n requireCurrency(refund.currency, `${eventName} refund.currency`);\n requireOptionalString(refund.reason, `${eventName} refund.reason`);\n requireOneOf(refund.status, PAYMENT_STATUSES, `${eventName} refund.status`);\n } else if (eventName.startsWith(\"refund.\")) {\n throw new TypeError(`${eventName} requires refund data`);\n }\n if (event.dispute !== null && event.dispute !== undefined) {\n const dispute = requireObject(event.dispute, `${eventName} dispute`);\n rejectUnknownKeys(\n dispute,\n [\"providerDisputeId\", \"providerPaymentId\", \"status\", \"reason\"],\n `${eventName} dispute`,\n );\n requireNonEmptyString(dispute.providerDisputeId, `${eventName} dispute.providerDisputeId`);\n requireNonEmptyString(dispute.providerPaymentId, `${eventName} dispute.providerPaymentId`);\n requireOneOf(dispute.status, DISPUTE_STATUSES, `${eventName} dispute.status`);\n requireOptionalString(dispute.reason, `${eventName} dispute.reason`);\n } else if (eventName.startsWith(\"dispute.\")) {\n throw new TypeError(`${eventName} requires dispute data`);\n }\n}\n\nexport type BillingEventHandler = (event: BillingEvent, accountId: string) => Promise<void>;\n\nexport interface BillingEventResult {\n handled: boolean;\n action?: string | null;\n error?: string | null;\n subscriptionId?: string | null;\n}\n\nexport type BillingEventClaim =\n | { status: \"claimed\"; claimToken: string; billingEventId: string }\n | { status: \"duplicate\" }\n | { status: \"busy\" }\n | { status: \"invalid_request\" }\n | { status: \"idempotency_conflict\"; billingEventId: string }\n | { status: \"max_retries_exceeded\"; billingEventId: string }\n | { status: \"retry\" };\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"subscriptions.d.ts","sourceRoot":"","sources":["../../../src/billing/types/subscriptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAErE,MAAM,MAAM,yBAAyB,GACjC,YAAY,GACZ,oBAAoB,GACpB,UAAU,GACV,QAAQ,GACR,UAAU,GACV,UAAU,GACV,QAAQ,GACR,QAAQ,GACR,SAAS,CAAC;AAEd,eAAO,MAAM,mBAAmB;;;;;;;;;;CAU8B,CAAC;AAE/D,MAAM,WAAW,uBAAuB;IACtC,sBAAsB,EAAE,MAAM,CAAC;IAC/B,MAAM,CAAC,EAAE,yBAAyB,GAAG,IAAI,CAAC;IAC1C,iBAAiB,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IACnC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,GA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M,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,cAAc,GAAG,cAAc,CAAC;IAC9C,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,oBAAoB,CAAC;IAC7B,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,SAAS,EAAE,MAAM,CAAC;CACnB"}
@@ -1 +1 @@
1
- {"version":3,"file":"subscriptions.js","sourceRoot":"","sources":["../../../src/billing/types/subscriptions.ts"],"names":[],"mappings":"AAaA,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;IACpB,QAAQ,EAAE,UAAU;IACpB,UAAU,EAAE,YAAY;IACxB,QAAQ,EAAE,UAAU;IACpB,kBAAkB,EAAE,oBAAoB;IACxC,MAAM,EAAE,QAAQ;IAChB,MAAM,EAAE,QAAQ;IAChB,OAAO,EAAE,SAAS;CAC0C,CAAC","sourcesContent":["import type { BillingOfferInterval, ProviderRef } from \"./common.js\";\n\nexport type BillingSubscriptionStatus =\n | \"incomplete\"\n | \"incomplete_expired\"\n | \"trialing\"\n | \"active\"\n | \"past_due\"\n | \"canceled\"\n | \"unpaid\"\n | \"paused\"\n | \"expired\";\n\nexport const SUBSCRIPTION_STATUS = {\n ACTIVE: \"active\",\n TRIALING: \"trialing\",\n CANCELED: \"canceled\",\n INCOMPLETE: \"incomplete\",\n PAST_DUE: \"past_due\",\n INCOMPLETE_EXPIRED: \"incomplete_expired\",\n UNPAID: \"unpaid\",\n PAUSED: \"paused\",\n EXPIRED: \"expired\",\n} as const satisfies Record<string, BillingSubscriptionStatus>;\n\nexport interface BillingSubscriptionInfo {\n providerSubscriptionId: string;\n status?: BillingSubscriptionStatus | null;\n cancelAtPeriodEnd?: boolean | null;\n periodStart?: string | null;\n periodEnd?: string | null;\n trialEnd?: string | null;\n cancelAt?: string | null;\n endedAt?: string | null;\n refs?: ProviderRef | null;\n interval?: string | null;\n intervalCount?: number | null;\n}\n\nexport interface BillingSubscriptionState {\n subscriptionId?: string | null;\n userId: string;\n provider: string;\n providerSubscriptionId: string;\n providerCustomerId?: string | null;\n offerId?: string | null;\n offerKey?: string | null;\n planId?: string | null;\n plan?: string | null;\n status: BillingSubscriptionStatus;\n currentPeriodStart?: string | null;\n currentPeriodEnd?: string | null;\n trialEnd?: string | null;\n cancelAt?: string | null;\n endedAt?: string | null;\n graceEndsAt?: string | null;\n graceExpiredAt?: string | null;\n providerUpdatedAt: string;\n cancelAtPeriodEnd: boolean;\n interval?: string | null;\n intervalCount?: number | null;\n metadata?: Record<string, unknown> | null;\n}\n\nexport type BillingSubscriptionChangeState =\n | \"awaiting_payment\"\n | \"scheduled\"\n | \"applied\"\n | \"failed\"\n | \"canceled\";\n\nexport interface BillingSubscriptionOfferContext {\n offerId: string;\n offerKey: string;\n planId: string;\n plan: string;\n interval: BillingOfferInterval;\n intervalCount: number;\n}\n\nexport interface BillingSubscriptionChange {\n id: string;\n subscriptionId: string;\n fromOfferId: string;\n toOfferId: string;\n fromOffer: BillingSubscriptionOfferContext;\n toOffer: BillingSubscriptionOfferContext;\n effectiveAt: string | null;\n effective: \"immediate\" | \"renewal\";\n state: BillingSubscriptionChangeState;\n prorationBehavior: \"provider_default\" | \"invoice_immediately\" | \"none\";\n idempotencyKey: string;\n providerOperationId?: string | null;\n errorMessage?: string | null;\n}\n\nexport interface BillingSubscriptionChangeInput {\n provider: string;\n providerSubscriptionId: string;\n toOfferId: string;\n effectiveAt: string;\n effective: \"immediate\" | \"renewal\";\n idempotencyKey: string;\n prorationBehavior?: \"provider_default\" | \"invoice_immediately\" | \"none\";\n}\n\nexport type CheckoutIntentStatus = \"open\" | \"completed\" | \"failed\" | \"expired\";\n\nexport interface CheckoutIntent {\n id: string;\n subjectId: string;\n provider: string;\n checkoutKind: \"subscription\" | \"credit_topup\";\n productKey: string;\n requestDigest: string;\n status: CheckoutIntentStatus;\n providerSessionId?: string | null;\n checkoutUrl?: string | null;\n expiresAt: string;\n}\n"]}
1
+ {"version":3,"file":"subscriptions.js","sourceRoot":"","sources":["../../../src/billing/types/subscriptions.ts"],"names":[],"mappings":"AAaA,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;IACpB,QAAQ,EAAE,UAAU;IACpB,UAAU,EAAE,YAAY;IACxB,QAAQ,EAAE,UAAU;IACpB,kBAAkB,EAAE,oBAAoB;IACxC,MAAM,EAAE,QAAQ;IAChB,MAAM,EAAE,QAAQ;IAChB,OAAO,EAAE,SAAS;CAC0C,CAAC","sourcesContent":["import type { BillingOfferInterval, ProviderRef } from \"./common.js\";\n\nexport type BillingSubscriptionStatus =\n | \"incomplete\"\n | \"incomplete_expired\"\n | \"trialing\"\n | \"active\"\n | \"past_due\"\n | \"canceled\"\n | \"unpaid\"\n | \"paused\"\n | \"expired\";\n\nexport const SUBSCRIPTION_STATUS = {\n ACTIVE: \"active\",\n TRIALING: \"trialing\",\n CANCELED: \"canceled\",\n INCOMPLETE: \"incomplete\",\n PAST_DUE: \"past_due\",\n INCOMPLETE_EXPIRED: \"incomplete_expired\",\n UNPAID: \"unpaid\",\n PAUSED: \"paused\",\n EXPIRED: \"expired\",\n} as const satisfies Record<string, BillingSubscriptionStatus>;\n\nexport interface BillingSubscriptionInfo {\n providerSubscriptionId: string;\n status?: BillingSubscriptionStatus | null;\n cancelAtPeriodEnd?: boolean | null;\n periodStart?: string | null;\n periodEnd?: string | null;\n trialEnd?: string | null;\n cancelAt?: string | null;\n endedAt?: string | null;\n refs?: ProviderRef | null;\n interval?: string | null;\n intervalCount?: number | null;\n}\n\nexport interface BillingSubscriptionState {\n subscriptionId?: string | null;\n userId: string;\n provider: string;\n providerSubscriptionId: string;\n providerCustomerId?: string | null;\n offerId?: string | null;\n offerKey?: string | null;\n planId?: string | null;\n plan?: string | null;\n status: BillingSubscriptionStatus;\n currentPeriodStart?: string | null;\n currentPeriodEnd?: string | null;\n trialEnd?: string | null;\n cancelAt?: string | null;\n endedAt?: string | null;\n graceEndsAt?: string | null;\n graceExpiredAt?: string | null;\n providerUpdatedAt: string;\n cancelAtPeriodEnd: boolean;\n interval?: string | null;\n intervalCount?: number | null;\n metadata?: Record<string, unknown> | null;\n}\n\nexport type BillingSubscriptionChangeState =\n \"awaiting_payment\" | \"scheduled\" | \"applied\" | \"failed\" | \"canceled\";\n\nexport interface BillingSubscriptionOfferContext {\n offerId: string;\n offerKey: string;\n planId: string;\n plan: string;\n interval: BillingOfferInterval;\n intervalCount: number;\n}\n\nexport interface BillingSubscriptionChange {\n id: string;\n subscriptionId: string;\n fromOfferId: string;\n toOfferId: string;\n fromOffer: BillingSubscriptionOfferContext;\n toOffer: BillingSubscriptionOfferContext;\n effectiveAt: string | null;\n effective: \"immediate\" | \"renewal\";\n state: BillingSubscriptionChangeState;\n prorationBehavior: \"provider_default\" | \"invoice_immediately\" | \"none\";\n idempotencyKey: string;\n providerOperationId?: string | null;\n errorMessage?: string | null;\n}\n\nexport interface BillingSubscriptionChangeInput {\n provider: string;\n providerSubscriptionId: string;\n toOfferId: string;\n effectiveAt: string;\n effective: \"immediate\" | \"renewal\";\n idempotencyKey: string;\n prorationBehavior?: \"provider_default\" | \"invoice_immediately\" | \"none\";\n}\n\nexport type CheckoutIntentStatus = \"open\" | \"completed\" | \"failed\" | \"expired\";\n\nexport interface CheckoutIntent {\n id: string;\n subjectId: string;\n provider: string;\n checkoutKind: \"subscription\" | \"credit_topup\";\n productKey: string;\n requestDigest: string;\n status: CheckoutIntentStatus;\n providerSessionId?: string | null;\n checkoutUrl?: string | null;\n expiresAt: string;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
2
  /**
3
3
  * Granular credit cost report for a usage event.
4
4
  *
@@ -1 +1 @@
1
- {"version":3,"file":"breakdown.d.ts","sourceRoot":"","sources":["../src/breakdown.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAGjC;;;;;;;GAOG;AACH,MAAM,WAAW,aAAa;IAC5B,YAAY,EAAE,OAAO,CAAC;IACtB,WAAW,EAAE,OAAO,CAAC;IACrB,aAAa,EAAE,OAAO,CAAC;IACvB,YAAY,EAAE,OAAO,CAAC;IACtB,YAAY,EAAE,OAAO,CAAC;IACtB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,KAAK,EAAE,OAAO,CAAC;IACf,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,wBAAgB,iBAAiB,CAAC,OAAO,CAAC,EAAE;IAC1C,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACrC,GAAG,aAAa,CA4BhB"}
1
+ {"version":3,"file":"breakdown.d.ts","sourceRoot":"","sources":["../src/breakdown.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGrC;;;;;;;GAOG;AACH,MAAM,WAAW,aAAa;IAC5B,YAAY,EAAE,OAAO,CAAC;IACtB,WAAW,EAAE,OAAO,CAAC;IACrB,aAAa,EAAE,OAAO,CAAC;IACvB,YAAY,EAAE,OAAO,CAAC;IACtB,YAAY,EAAE,OAAO,CAAC;IACtB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,KAAK,EAAE,OAAO,CAAC;IACf,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,wBAAgB,iBAAiB,CAAC,OAAO,CAAC,EAAE;IAC1C,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACrC,GAAG,aAAa,CA4BhB"}
package/dist/breakdown.js CHANGED
@@ -1,4 +1,4 @@
1
- import Decimal from "decimal.js";
1
+ import { Decimal } from "decimal.js";
2
2
  import { quantizeMoney } from "./expr.js";
3
3
  export function makeCostBreakdown(partial) {
4
4
  const modelCredits = quantizeMoney(partial?.modelCredits ?? new Decimal(0));
@@ -1 +1 @@
1
- {"version":3,"file":"breakdown.js","sourceRoot":"","sources":["../src/breakdown.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAqB1C,MAAM,UAAU,iBAAiB,CAAC,OAQjC;IACC,MAAM,YAAY,GAAG,aAAa,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,WAAW,GAAG,aAAa,CAAC,OAAO,EAAE,WAAW,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1E,MAAM,aAAa,GAAG,aAAa,CAAC,OAAO,EAAE,aAAa,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9E,MAAM,YAAY,GAAG,aAAa,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,YAAY,GAAG,aAAa,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,gBAAgB,GAAG,aAAa,CAAC,OAAO,EAAE,gBAAgB,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAEpF,yEAAyE;IACzE,4BAA4B;IAC5B,MAAM,QAAQ,GAAG,YAAY;SAC1B,IAAI,CAAC,WAAW,CAAC;SACjB,IAAI,CAAC,aAAa,CAAC;SACnB,IAAI,CAAC,YAAY,CAAC;SAClB,IAAI,CAAC,gBAAgB,CAAC;SACtB,IAAI,CAAC,YAAY,CAAC,CAAC;IACtB,MAAM,KAAK,GAAG,aAAa,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;IAEnE,OAAO;QACL,YAAY;QACZ,WAAW;QACX,aAAa;QACb,YAAY;QACZ,YAAY;QACZ,gBAAgB;QAChB,KAAK;QACL,SAAS,EAAE,OAAO,EAAE,SAAS,IAAI,EAAE;KACpC,CAAC;AACJ,CAAC","sourcesContent":["import Decimal from \"decimal.js\";\nimport { quantizeMoney } from \"./expr.js\";\n\n/**\n * Granular credit cost report for a usage event.\n *\n * All money fields are `Decimal` (never binary `number`) and are quantized to\n * 6dp ROUND_HALF_UP. `total` is the single source of truth: it is recomputed\n * from the components (clamped at 0) and quantized — there is NO implicit\n * integer truncation of the total (that was the revenue-leak bug).\n */\nexport interface CostBreakdown {\n modelCredits: Decimal;\n toolCredits: Decimal;\n searchCredits: Decimal;\n cacheSavings: Decimal;\n fixedCredits: Decimal;\n operationCredits: Decimal;\n total: Decimal;\n breakdown: Record<string, unknown>;\n}\n\nexport function makeCostBreakdown(partial?: {\n modelCredits?: Decimal;\n toolCredits?: Decimal;\n searchCredits?: Decimal;\n cacheSavings?: Decimal;\n fixedCredits?: Decimal;\n operationCredits?: Decimal;\n breakdown?: Record<string, unknown>;\n}): CostBreakdown {\n const modelCredits = quantizeMoney(partial?.modelCredits ?? new Decimal(0));\n const toolCredits = quantizeMoney(partial?.toolCredits ?? new Decimal(0));\n const searchCredits = quantizeMoney(partial?.searchCredits ?? new Decimal(0));\n const cacheSavings = quantizeMoney(partial?.cacheSavings ?? new Decimal(0));\n const fixedCredits = quantizeMoney(partial?.fixedCredits ?? new Decimal(0));\n const operationCredits = quantizeMoney(partial?.operationCredits ?? new Decimal(0));\n\n // Single source of truth for the total: sum of components, clamped at 0,\n // quantized to 6dp HALF_UP.\n const rawTotal = modelCredits\n .plus(toolCredits)\n .plus(searchCredits)\n .plus(fixedCredits)\n .plus(operationCredits)\n .plus(cacheSavings);\n const total = quantizeMoney(Decimal.max(new Decimal(0), rawTotal));\n\n return {\n modelCredits,\n toolCredits,\n searchCredits,\n cacheSavings,\n fixedCredits,\n operationCredits,\n total,\n breakdown: partial?.breakdown ?? {},\n };\n}\n"]}
1
+ {"version":3,"file":"breakdown.js","sourceRoot":"","sources":["../src/breakdown.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAqB1C,MAAM,UAAU,iBAAiB,CAAC,OAQjC;IACC,MAAM,YAAY,GAAG,aAAa,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,WAAW,GAAG,aAAa,CAAC,OAAO,EAAE,WAAW,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1E,MAAM,aAAa,GAAG,aAAa,CAAC,OAAO,EAAE,aAAa,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9E,MAAM,YAAY,GAAG,aAAa,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,YAAY,GAAG,aAAa,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,gBAAgB,GAAG,aAAa,CAAC,OAAO,EAAE,gBAAgB,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;IAEpF,yEAAyE;IACzE,4BAA4B;IAC5B,MAAM,QAAQ,GAAG,YAAY;SAC1B,IAAI,CAAC,WAAW,CAAC;SACjB,IAAI,CAAC,aAAa,CAAC;SACnB,IAAI,CAAC,YAAY,CAAC;SAClB,IAAI,CAAC,gBAAgB,CAAC;SACtB,IAAI,CAAC,YAAY,CAAC,CAAC;IACtB,MAAM,KAAK,GAAG,aAAa,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;IAEnE,OAAO;QACL,YAAY;QACZ,WAAW;QACX,aAAa;QACb,YAAY;QACZ,YAAY;QACZ,gBAAgB;QAChB,KAAK;QACL,SAAS,EAAE,OAAO,EAAE,SAAS,IAAI,EAAE;KACpC,CAAC;AACJ,CAAC","sourcesContent":["import { Decimal } from \"decimal.js\";\nimport { quantizeMoney } from \"./expr.js\";\n\n/**\n * Granular credit cost report for a usage event.\n *\n * All money fields are `Decimal` (never binary `number`) and are quantized to\n * 6dp ROUND_HALF_UP. `total` is the single source of truth: it is recomputed\n * from the components (clamped at 0) and quantized — there is NO implicit\n * integer truncation of the total (that was the revenue-leak bug).\n */\nexport interface CostBreakdown {\n modelCredits: Decimal;\n toolCredits: Decimal;\n searchCredits: Decimal;\n cacheSavings: Decimal;\n fixedCredits: Decimal;\n operationCredits: Decimal;\n total: Decimal;\n breakdown: Record<string, unknown>;\n}\n\nexport function makeCostBreakdown(partial?: {\n modelCredits?: Decimal;\n toolCredits?: Decimal;\n searchCredits?: Decimal;\n cacheSavings?: Decimal;\n fixedCredits?: Decimal;\n operationCredits?: Decimal;\n breakdown?: Record<string, unknown>;\n}): CostBreakdown {\n const modelCredits = quantizeMoney(partial?.modelCredits ?? new Decimal(0));\n const toolCredits = quantizeMoney(partial?.toolCredits ?? new Decimal(0));\n const searchCredits = quantizeMoney(partial?.searchCredits ?? new Decimal(0));\n const cacheSavings = quantizeMoney(partial?.cacheSavings ?? new Decimal(0));\n const fixedCredits = quantizeMoney(partial?.fixedCredits ?? new Decimal(0));\n const operationCredits = quantizeMoney(partial?.operationCredits ?? new Decimal(0));\n\n // Single source of truth for the total: sum of components, clamped at 0,\n // quantized to 6dp HALF_UP.\n const rawTotal = modelCredits\n .plus(toolCredits)\n .plus(searchCredits)\n .plus(fixedCredits)\n .plus(operationCredits)\n .plus(cacheSavings);\n const total = quantizeMoney(Decimal.max(new Decimal(0), rawTotal));\n\n return {\n modelCredits,\n toolCredits,\n searchCredits,\n cacheSavings,\n fixedCredits,\n operationCredits,\n total,\n breakdown: partial?.breakdown ?? {},\n };\n}\n"]}
package/dist/bursar.d.ts CHANGED
@@ -7,7 +7,7 @@ import type { BillingEvent, BillingEventResult } from "./billing/types/index.js"
7
7
  import type { BillingCapability, BillingEventSink } from "./billing/contracts.js";
8
8
  import { CommerceService as CommerceServiceImpl } from "./commerce/service.js";
9
9
  import type { CommerceOptions } from "./commerce/types.js";
10
- import type { CatalogRollout, ParsedBursarConfig } from "./config/types.js";
10
+ import type { BursarConfigData, CatalogRollout, ParsedBursarConfig } from "./config/types.js";
11
11
  import { type PublicCatalog } from "./catalog.js";
12
12
  import type { CreditMetadata, GrantProgramAwardResult } from "./credits/types/index.js";
13
13
  export type { BillingCapability, BillingEventSink } from "./billing/contracts.js";
@@ -20,15 +20,25 @@ export type { CommerceOptions } from "./commerce/types.js";
20
20
  */
21
21
  export type CreditsService = Pick<CreditsServiceImpl, "getUserPlan" | "checkFeature" | "getQuotaState" | "listQuotaEvents" | "startPlanMigration" | "migratePlanBatch" | "revokeCreditsByEntryType" | "executeGrantProgram" | "getLedgerEntry" | "getAvailable" | "aggregateStats" | "spendByUser" | "spendByModel" | "listLedgerEntries" | "listUsageEntries" | "listUsageCharges" | "topUsers" | "dailySpend" | "setUserPlan" | "unsetUserPlan" | "getBalance" | "addCredits" | "deductCredits" | "grantSubscriptionCycle" | "reserve" | "settle" | "release" | "renew" | "canAfford" | "getBucketBalances" | "checkAllowance" | "runBilled" | "beginBilledOperation" | "deduct" | "recordUsage" | "deductFlatJob" | "refundCredits" | "deductTeam" | "sweepExpiredCredits">;
22
22
  type CatalogCreditsService = Pick<CreditsServiceImpl, "getActiveCatalog" | "loadCatalogFromStore" | "refreshCatalogIfStale" | "invalidateCatalog" | "publishAndActivateCatalog" | "publishCatalogDraft" | "activateCatalogRevision" | "pricingEngine" | "setPlanRevisionPin" | "applyDuePlanChanges">;
23
- /** Options for constructing the single application-facing Bursar service. */
24
- export interface BursarOptions {
23
+ interface BaseBursarOptions {
25
24
  creditStore: CreditStore;
26
- billingStore?: BillingStore | null;
27
- creditsOptions?: CreditsServiceOptions | null;
28
- billingOptions?: BillingServiceOptions | null;
29
- commerceOptions?: CommerceOptions | null;
30
- emitter?: CreditEventEmitter | null;
25
+ creditsOptions?: CreditsServiceOptions;
26
+ emitter?: CreditEventEmitter;
27
+ }
28
+ /** Credits-only construction rejects billing options that would otherwise be ignored. */
29
+ export interface CreditsOnlyBursarOptions extends BaseBursarOptions {
30
+ billingStore?: undefined;
31
+ billingOptions?: never;
32
+ commerceOptions?: never;
31
33
  }
34
+ /** Billing construction owns provisioning and may optionally enable commerce. */
35
+ export interface BillingBursarOptions extends BaseBursarOptions {
36
+ billingStore: BillingStore;
37
+ billingOptions?: Omit<BillingServiceOptions, "provisioning">;
38
+ commerceOptions?: CommerceOptions;
39
+ }
40
+ /** Options for constructing the single application-facing Bursar service. */
41
+ export type BursarOptions = CreditsOnlyBursarOptions | BillingBursarOptions;
32
42
  /** Catalog operations. Configuration writes live here, never in BillingService. */
33
43
  export declare class CatalogService {
34
44
  private readonly credits;
@@ -45,9 +55,9 @@ export declare class CatalogService {
45
55
  invalidate(): void;
46
56
  getConfig(): Promise<ParsedBursarConfig>;
47
57
  publicView(): Promise<PublicCatalog>;
48
- publishDraft(config: Record<string, unknown>, label?: string | null): Promise<string>;
49
- activate(version: number, rollout?: CatalogRollout | Record<string, unknown> | null): Promise<string>;
50
- publishAndActivate(config: Record<string, unknown>, label?: string | null, rollout?: CatalogRollout | Record<string, unknown> | null): Promise<string>;
58
+ publishDraft(config: BursarConfigData, label?: string | null): Promise<string>;
59
+ activate(version: number, rollout?: CatalogRollout | null): Promise<string>;
60
+ publishAndActivate(config: BursarConfigData, label?: string | null, rollout?: CatalogRollout | null): Promise<string>;
51
61
  /** Pin or unpin one current assignment from automatic catalog rollout. */
52
62
  setRevisionPin(userId: string, pinned: boolean): Promise<boolean>;
53
63
  /** Apply one bounded batch of renewal-effective plan changes. */
@@ -1 +1 @@
1
- {"version":3,"file":"bursar.d.ts","sourceRoot":"","sources":["../src/bursar.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,qBAAqB,EAC3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EACL,cAAc,IAAI,kBAAkB,EACpC,KAAK,qBAAqB,EAC3B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACjF,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAClF,OAAO,EAAE,eAAe,IAAI,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE/E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE3D,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAE5E,OAAO,EAAwB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gBADP,OAAO,EAAE,cAAc,EACvB,OAAO,EAAE,cAAc;IAGpC,gBAAgB,CAAC,KAAK,EAAE,mBAAmB,GAAG,OAAO,CAAC,oBAAoB,CAAC;CA0ClF;AAED;;;;;;;GAOG;AACH,qBAAa,MAAO,YAAW,gBAAgB;IAC7C,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAC;IACjC,QAAQ,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI,CAAC;IAC3C,QAAQ,CAAC,QAAQ,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAC9C,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAC;IACjC,QAAQ,CAAC,QAAQ,EAAE,cAAc,CAAC;gBAEtB,OAAO,EAAE,aAAa;IAiElC,uDAAuD;IACjD,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAIlC,mEAAmE;IACnE,cAAc,IAAI,iBAAiB;IAOnC,oEAAoE;IACpE,eAAe,IAAI,mBAAmB;IAOtC;;;OAGG;IACG,kBAAkB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,kBAAkB,CAAC;CAG3E"}
package/dist/bursar.js CHANGED
@@ -68,11 +68,14 @@ export class AccountService {
68
68
  this.catalog = catalog;
69
69
  }
70
70
  async onAccountCreated(input) {
71
- if (!input.eventKey.trim())
72
- throw new ConfigError("eventKey must not be empty");
71
+ if (typeof input.accountId !== "string" || !input.accountId.trim()) {
72
+ throw new TypeError("accountId must be a non-empty string");
73
+ }
74
+ if (typeof input.eventKey !== "string" || !input.eventKey.trim()) {
75
+ throw new TypeError("eventKey must be a non-empty string");
76
+ }
73
77
  const config = await retryBursarOperation(() => this.catalog.getConfig());
74
- const fallback = Object.entries(config.plans).sort(([aKey, a], [bKey, b]) => a.rank - b.rank || aKey.localeCompare(bKey))[0]?.[0];
75
- const planKey = config.catalog.defaultPlan ?? fallback;
78
+ const planKey = config.catalog.defaultPlan;
76
79
  if (!planKey)
77
80
  throw new ConfigError("The active catalog has no default account plan");
78
81
  const current = await retryBursarOperation(() => this.credits.getUserPlan(input.accountId));
@@ -116,6 +119,39 @@ export class Bursar {
116
119
  catalog;
117
120
  accounts;
118
121
  constructor(options) {
122
+ if (typeof options !== "object" || options === null) {
123
+ throw new TypeError("Bursar options are required");
124
+ }
125
+ if (options.billingStore === null) {
126
+ throw new TypeError("billingStore must be a BillingStore when provided");
127
+ }
128
+ for (const optionName of [
129
+ "creditsOptions",
130
+ "billingOptions",
131
+ "commerceOptions",
132
+ "emitter",
133
+ ]) {
134
+ if (options[optionName] === null) {
135
+ throw new TypeError(`${optionName} must not be null`);
136
+ }
137
+ }
138
+ if (options.billingStore === undefined &&
139
+ (options.billingOptions !== undefined || options.commerceOptions !== undefined)) {
140
+ throw new TypeError("billingOptions and commerceOptions require billingStore");
141
+ }
142
+ if (options.billingOptions && "provisioning" in options.billingOptions) {
143
+ throw new TypeError("billingOptions.provisioning is owned by Bursar");
144
+ }
145
+ const environments = [
146
+ ["creditStore", options.creditStore.providerEnvironment],
147
+ ["billingStore", options.billingStore?.providerEnvironment],
148
+ ["commerceOptions", options.commerceOptions?.providerEnvironment],
149
+ ].filter((entry) => entry[1] !== undefined);
150
+ if (new Set(environments.map(([, environment]) => environment)).size > 1) {
151
+ throw new TypeError(`Bursar provider environments must match: ${environments
152
+ .map(([name, environment]) => `${name}=${environment}`)
153
+ .join(", ")}`);
154
+ }
119
155
  const credits = new CreditsServiceImpl(options.creditStore, undefined, options.emitter ?? undefined, options.creditsOptions ?? undefined);
120
156
  this.credits = credits;
121
157
  this.catalog = new CatalogService(credits);
@@ -1 +1 @@
1
- {"version":3,"file":"bursar.js","sourceRoot":"","sources":["../src/bursar.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,IAAI,mBAAmB,GAEtC,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,cAAc,IAAI,kBAAkB,GAErC,MAAM,sBAAsB,CAAC;AAK9B,OAAO,EAAE,eAAe,IAAI,mBAAmB,EAAE,MAA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IAAI,EAAE,OAAO,CAAC,eAAe,CAAC;gBAC/E,CAAC,CAAC,IAAI,CAAC;QACX,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClB,OAAO,CAAC,oBAAoB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE;gBAChD,MAAM,IAAI,CAAC,QAAS,CAAC,YAAY,CAAC,eAAe,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;YAC3E,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,uDAAuD;IACvD,KAAK,CAAC,WAAW;QACf,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;IAC5B,CAAC;IAED,mEAAmE;IACnE,cAAc;QACZ,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,MAAM,IAAI,4BAA4B,CAAC,SAAS,CAAC,CAAC;QACpD,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED,oEAAoE;IACpE,eAAe;QACb,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACnB,MAAM,IAAI,0BAA0B,CAAC,8CAA8C,CAAC,CAAC;QACvF,CAAC;QACD,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,kBAAkB,CAAC,KAAmB;QAC1C,OAAO,IAAI,CAAC,cAAc,EAAE,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IACzD,CAAC;CACF","sourcesContent":["import {\n BillingService as BillingEventService,\n type BillingServiceOptions,\n} from \"./billing/billing-service.js\";\nimport type { BillingStore } from \"./billing/billing-store.js\";\nimport {\n CreditsService as CreditsServiceImpl,\n type CreditsServiceOptions,\n} from \"./credits/service.js\";\nimport type { CreditStore } from \"./credits/store.js\";\nimport type { CreditEventEmitter } from \"./credits/events.js\";\nimport type { BillingEvent, BillingEventResult } from \"./billing/types/index.js\";\nimport type { BillingCapability, BillingEventSink } from \"./billing/contracts.js\";\nimport { CommerceService as CommerceServiceImpl } from \"./commerce/service.js\";\nimport { CommerceNotConfiguredError } from \"./commerce/errors.js\";\nimport type { CommerceOptions } from \"./commerce/types.js\";\nimport { loadConfigFromDict } from \"./config.js\";\nimport type { CatalogRollout, ParsedBursarConfig } from \"./config/types.js\";\nimport { CapabilityNotConfiguredError, ConfigError, CatalogNotLoadedError } from \"./errors.js\";\nimport { projectPublicCatalog, type PublicCatalog } from \"./catalog.js\";\nimport type { CreditMetadata, GrantProgramAwardResult } from \"./credits/types/index.js\";\nimport { retryBursarOperation } from \"./retry.js\";\nexport type { BillingCapability, BillingEventSink } from \"./billing/contracts.js\";\nexport type { CommerceOptions } from \"./commerce/types.js\";\n\n/**\n * Stable public credit capability exposed by {@link Bursar}.\n *\n * The explicit method list prevents implementation helpers added to\n * `CreditsServiceImpl` from silently becoming public API.\n */\nexport type CreditsService = Pick<\n CreditsServiceImpl,\n | \"getUserPlan\"\n | \"checkFeature\"\n | \"getQuotaState\"\n | \"listQuotaEvents\"\n | \"startPlanMigration\"\n | \"migratePlanBatch\"\n | \"revokeCreditsByEntryType\"\n | \"executeGrantProgram\"\n | \"getLedgerEntry\"\n | \"getAvailable\"\n | \"aggregateStats\"\n | \"spendByUser\"\n | \"spendByModel\"\n | \"listLedgerEntries\"\n | \"listUsageEntries\"\n | \"listUsageCharges\"\n | \"topUsers\"\n | \"dailySpend\"\n | \"setUserPlan\"\n | \"unsetUserPlan\"\n | \"getBalance\"\n | \"addCredits\"\n | \"deductCredits\"\n | \"grantSubscriptionCycle\"\n | \"reserve\"\n | \"settle\"\n | \"release\"\n | \"renew\"\n | \"canAfford\"\n | \"getBucketBalances\"\n | \"checkAllowance\"\n | \"runBilled\"\n | \"beginBilledOperation\"\n | \"deduct\"\n | \"recordUsage\"\n | \"deductFlatJob\"\n | \"refundCredits\"\n | \"deductTeam\"\n | \"sweepExpiredCredits\"\n>;\n\ntype CatalogCreditsService = Pick<\n CreditsServiceImpl,\n | \"getActiveCatalog\"\n | \"loadCatalogFromStore\"\n | \"refreshCatalogIfStale\"\n | \"invalidateCatalog\"\n | \"publishAndActivateCatalog\"\n | \"publishCatalogDraft\"\n | \"activateCatalogRevision\"\n | \"pricingEngine\"\n | \"setPlanRevisionPin\"\n | \"applyDuePlanChanges\"\n>;\n\n/** Options for constructing the single application-facing Bursar service. */\nexport interface BursarOptions {\n creditStore: CreditStore;\n billingStore?: BillingStore | null;\n creditsOptions?: CreditsServiceOptions | null;\n billingOptions?: BillingServiceOptions | null;\n commerceOptions?: CommerceOptions | null;\n emitter?: CreditEventEmitter | null;\n}\n\n/** Catalog operations. Configuration writes live here, never in BillingService. */\nexport class CatalogService {\n constructor(private readonly credits: CatalogCreditsService) {}\n\n /** Return the active persisted catalog revision, if one exists. */\n getActive() {\n return this.credits.getActiveCatalog();\n }\n\n /** Whether this process currently has a pricing engine loaded. */\n get isLoaded(): boolean {\n return this.credits.pricingEngine !== null;\n }\n\n /** Load the active persisted catalog into this process. */\n load(): Promise<void> {\n return this.credits.loadCatalogFromStore();\n }\n\n /** Block until a stale in-process catalog has been refreshed. */\n refresh(): Promise<void> {\n return this.credits.refreshCatalogIfStale();\n }\n\n /** Force the next refresh to reload the active catalog. */\n invalidate(): void {\n this.credits.invalidateCatalog();\n }\n\n async getConfig(): Promise<ParsedBursarConfig> {\n const active = await this.getActive();\n if (!active) throw new CatalogNotLoadedError(\"No active Bursar catalog is available\");\n return loadConfigFromDict(active.config);\n }\n\n async publicView(): Promise<PublicCatalog> {\n return projectPublicCatalog(await this.getConfig());\n }\n\n publishDraft(config: Record<string, unknown>, label?: string | null): Promise<string> {\n return this.credits.publishCatalogDraft(config, label);\n }\n\n activate(\n version: number,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string> {\n return this.credits.activateCatalogRevision(version, rollout);\n }\n\n publishAndActivate(\n config: Record<string, unknown>,\n label?: string | null,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string> {\n return this.credits.publishAndActivateCatalog(config, label, rollout);\n }\n\n /** Pin or unpin one current assignment from automatic catalog rollout. */\n setRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.credits.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n applyDueChanges(limit = 100): Promise<number> {\n return this.credits.applyDuePlanChanges(limit);\n }\n}\n\nexport interface AccountCreatedInput {\n accountId: string;\n eventKey: string;\n region?: string | null;\n metadata?: CreditMetadata | null;\n}\n\nexport interface AccountCreatedResult {\n accountId: string;\n planKey: string;\n planAssigned: boolean;\n grants: GrantProgramAwardResult[];\n}\n\n/** Generic financial lifecycle operations for SaaS accounts. */\nexport class AccountService {\n constructor(\n private readonly credits: CreditsService,\n private readonly catalog: CatalogService,\n ) {}\n\n async onAccountCreated(input: AccountCreatedInput): Promise<AccountCreatedResult> {\n if (!input.eventKey.trim()) throw new ConfigError(\"eventKey must not be empty\");\n const config = await retryBursarOperation(() => this.catalog.getConfig());\n const fallback = Object.entries(config.plans).sort(\n ([aKey, a], [bKey, b]) => a.rank - b.rank || aKey.localeCompare(bKey),\n )[0]?.[0];\n const planKey = config.catalog.defaultPlan ?? fallback;\n if (!planKey) throw new ConfigError(\"The active catalog has no default account plan\");\n\n const current = await retryBursarOperation(() => this.credits.getUserPlan(input.accountId));\n const planAssigned = current.planKey == null;\n if (planAssigned) {\n await retryBursarOperation(() => this.credits.setUserPlan(input.accountId, planKey));\n }\n\n const grants: GrantProgramAwardResult[] = [];\n for (const [programKey, program] of Object.entries(config.credits.grantPrograms).sort(\n ([a], [b]) => a.localeCompare(b),\n )) {\n if (program.trigger !== \"account_created\") continue;\n grants.push(\n ...(await retryBursarOperation(() =>\n this.credits.executeGrantProgram({\n trigger: \"account_created\",\n programKey,\n subjectId: input.accountId,\n eventKey: input.eventKey,\n region: input.region,\n metadata: input.metadata,\n }),\n )),\n );\n }\n return {\n accountId: input.accountId,\n planKey: current.planKey ?? planKey,\n planAssigned,\n grants,\n };\n }\n}\n\n/**\n * The application-facing Bursar boundary.\n *\n * Credit and billing services are deliberately created together so consumers\n * cannot accidentally construct unrelated services for the same account\n * lifecycle. Provider and application integrations use this facade rather\n * than constructing lifecycle services independently.\n */\nexport class Bursar implements BillingEventSink {\n readonly credits: CreditsService;\n readonly billing: BillingCapability | null;\n readonly commerce: CommerceServiceImpl | null;\n readonly catalog: CatalogService;\n readonly accounts: AccountService;\n\n constructor(options: BursarOptions) {\n const credits = new CreditsServiceImpl(\n options.creditStore,\n undefined,\n options.emitter ?? undefined,\n options.creditsOptions ?? undefined,\n );\n this.credits = credits;\n this.catalog = new CatalogService(credits);\n this.accounts = new AccountService(credits, this.catalog);\n\n this.billing = options.billingStore\n ? new BillingEventService(options.billingStore, {\n ...(options.billingOptions ?? {}),\n provisioning: credits,\n })\n : null;\n this.commerce =\n this.billing && options.commerceOptions\n ? new CommerceServiceImpl(this.billing, credits, this, options.commerceOptions)\n : null;\n if (this.commerce) {\n credits.addPostDeductionHook(async ({ userId }) => {\n await this.commerce!.autoRecharge.processIfNeeded({ accountId: userId });\n });\n }\n }\n\n /** Load the active catalog into the pricing engine. */\n async loadCatalog(): Promise<void> {\n await this.catalog.load();\n }\n\n /** Return billing or raise the SDK's typed configuration error. */\n requireBilling(): BillingCapability {\n if (!this.billing) {\n throw new CapabilityNotConfiguredError(\"billing\");\n }\n return this.billing;\n }\n\n /** Return commerce or raise the SDK's typed configuration error. */\n requireCommerce(): CommerceServiceImpl {\n if (!this.commerce) {\n throw new CommerceNotConfiguredError(\"Bursar commerce capability is not configured\");\n }\n return this.commerce;\n }\n\n /**\n * Ingest a normalized provider event through the facade-owned billing\n * lifecycle. Providers must not depend on BillingService directly.\n */\n async ingestBillingEvent(event: BillingEvent): Promise<BillingEventResult> {\n return this.requireBilling().ingestBillingEvent(event);\n }\n}\n"]}
1
+ {"version":3,"file":"bursar.js","sourceRoot":"","sources":["../src/bursar.ts"],"names":[],"mappings":"AAAA,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KAAmB;QAC1C,OAAO,IAAI,CAAC,cAAc,EAAE,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IACzD,CAAC;CACF","sourcesContent":["import {\n BillingService as BillingEventService,\n type BillingServiceOptions,\n} from \"./billing/billing-service.js\";\nimport type { BillingStore } from \"./billing/billing-store.js\";\nimport {\n CreditsService as CreditsServiceImpl,\n type CreditsServiceOptions,\n} from \"./credits/service.js\";\nimport type { CreditStore } from \"./credits/store.js\";\nimport type { CreditEventEmitter } from \"./credits/events.js\";\nimport type { BillingEvent, BillingEventResult } from \"./billing/types/index.js\";\nimport type { BillingCapability, BillingEventSink } from \"./billing/contracts.js\";\nimport { CommerceService as CommerceServiceImpl } from \"./commerce/service.js\";\nimport { CommerceNotConfiguredError } from \"./commerce/errors.js\";\nimport type { CommerceOptions } from \"./commerce/types.js\";\nimport { loadConfigFromDict } from \"./config.js\";\nimport type { BursarConfigData, CatalogRollout, ParsedBursarConfig } from \"./config/types.js\";\nimport { CapabilityNotConfiguredError, ConfigError, CatalogNotLoadedError } from \"./errors.js\";\nimport { projectPublicCatalog, type PublicCatalog } from \"./catalog.js\";\nimport type { CreditMetadata, GrantProgramAwardResult } from \"./credits/types/index.js\";\nimport { retryBursarOperation } from \"./retry.js\";\nexport type { BillingCapability, BillingEventSink } from \"./billing/contracts.js\";\nexport type { CommerceOptions } from \"./commerce/types.js\";\n\n/**\n * Stable public credit capability exposed by {@link Bursar}.\n *\n * The explicit method list prevents implementation helpers added to\n * `CreditsServiceImpl` from silently becoming public API.\n */\nexport type CreditsService = Pick<\n CreditsServiceImpl,\n | \"getUserPlan\"\n | \"checkFeature\"\n | \"getQuotaState\"\n | \"listQuotaEvents\"\n | \"startPlanMigration\"\n | \"migratePlanBatch\"\n | \"revokeCreditsByEntryType\"\n | \"executeGrantProgram\"\n | \"getLedgerEntry\"\n | \"getAvailable\"\n | \"aggregateStats\"\n | \"spendByUser\"\n | \"spendByModel\"\n | \"listLedgerEntries\"\n | \"listUsageEntries\"\n | \"listUsageCharges\"\n | \"topUsers\"\n | \"dailySpend\"\n | \"setUserPlan\"\n | \"unsetUserPlan\"\n | \"getBalance\"\n | \"addCredits\"\n | \"deductCredits\"\n | \"grantSubscriptionCycle\"\n | \"reserve\"\n | \"settle\"\n | \"release\"\n | \"renew\"\n | \"canAfford\"\n | \"getBucketBalances\"\n | \"checkAllowance\"\n | \"runBilled\"\n | \"beginBilledOperation\"\n | \"deduct\"\n | \"recordUsage\"\n | \"deductFlatJob\"\n | \"refundCredits\"\n | \"deductTeam\"\n | \"sweepExpiredCredits\"\n>;\n\ntype CatalogCreditsService = Pick<\n CreditsServiceImpl,\n | \"getActiveCatalog\"\n | \"loadCatalogFromStore\"\n | \"refreshCatalogIfStale\"\n | \"invalidateCatalog\"\n | \"publishAndActivateCatalog\"\n | \"publishCatalogDraft\"\n | \"activateCatalogRevision\"\n | \"pricingEngine\"\n | \"setPlanRevisionPin\"\n | \"applyDuePlanChanges\"\n>;\n\ninterface BaseBursarOptions {\n creditStore: CreditStore;\n creditsOptions?: CreditsServiceOptions;\n emitter?: CreditEventEmitter;\n}\n\n/** Credits-only construction rejects billing options that would otherwise be ignored. */\nexport interface CreditsOnlyBursarOptions extends BaseBursarOptions {\n billingStore?: undefined;\n billingOptions?: never;\n commerceOptions?: never;\n}\n\n/** Billing construction owns provisioning and may optionally enable commerce. */\nexport interface BillingBursarOptions extends BaseBursarOptions {\n billingStore: BillingStore;\n billingOptions?: Omit<BillingServiceOptions, \"provisioning\">;\n commerceOptions?: CommerceOptions;\n}\n\n/** Options for constructing the single application-facing Bursar service. */\nexport type BursarOptions = CreditsOnlyBursarOptions | BillingBursarOptions;\n\n/** Catalog operations. Configuration writes live here, never in BillingService. */\nexport class CatalogService {\n constructor(private readonly credits: CatalogCreditsService) {}\n\n /** Return the active persisted catalog revision, if one exists. */\n getActive() {\n return this.credits.getActiveCatalog();\n }\n\n /** Whether this process currently has a pricing engine loaded. */\n get isLoaded(): boolean {\n return this.credits.pricingEngine !== null;\n }\n\n /** Load the active persisted catalog into this process. */\n load(): Promise<void> {\n return this.credits.loadCatalogFromStore();\n }\n\n /** Block until a stale in-process catalog has been refreshed. */\n refresh(): Promise<void> {\n return this.credits.refreshCatalogIfStale();\n }\n\n /** Force the next refresh to reload the active catalog. */\n invalidate(): void {\n this.credits.invalidateCatalog();\n }\n\n async getConfig(): Promise<ParsedBursarConfig> {\n const active = await this.getActive();\n if (!active) throw new CatalogNotLoadedError(\"No active Bursar catalog is available\");\n return loadConfigFromDict(active.config);\n }\n\n async publicView(): Promise<PublicCatalog> {\n return projectPublicCatalog(await this.getConfig());\n }\n\n publishDraft(config: BursarConfigData, label?: string | null): Promise<string> {\n return this.credits.publishCatalogDraft(config, label);\n }\n\n activate(version: number, rollout?: CatalogRollout | null): Promise<string> {\n return this.credits.activateCatalogRevision(version, rollout);\n }\n\n publishAndActivate(\n config: BursarConfigData,\n label?: string | null,\n rollout?: CatalogRollout | null,\n ): Promise<string> {\n return this.credits.publishAndActivateCatalog(config, label, rollout);\n }\n\n /** Pin or unpin one current assignment from automatic catalog rollout. */\n setRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.credits.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n applyDueChanges(limit = 100): Promise<number> {\n return this.credits.applyDuePlanChanges(limit);\n }\n}\n\nexport interface AccountCreatedInput {\n accountId: string;\n eventKey: string;\n region?: string | null;\n metadata?: CreditMetadata | null;\n}\n\nexport interface AccountCreatedResult {\n accountId: string;\n planKey: string;\n planAssigned: boolean;\n grants: GrantProgramAwardResult[];\n}\n\n/** Generic financial lifecycle operations for SaaS accounts. */\nexport class AccountService {\n constructor(\n private readonly credits: CreditsService,\n private readonly catalog: CatalogService,\n ) {}\n\n async onAccountCreated(input: AccountCreatedInput): Promise<AccountCreatedResult> {\n if (typeof input.accountId !== \"string\" || !input.accountId.trim()) {\n throw new TypeError(\"accountId must be a non-empty string\");\n }\n if (typeof input.eventKey !== \"string\" || !input.eventKey.trim()) {\n throw new TypeError(\"eventKey must be a non-empty string\");\n }\n const config = await retryBursarOperation(() => this.catalog.getConfig());\n const planKey = config.catalog.defaultPlan;\n if (!planKey) throw new ConfigError(\"The active catalog has no default account plan\");\n\n const current = await retryBursarOperation(() => this.credits.getUserPlan(input.accountId));\n const planAssigned = current.planKey == null;\n if (planAssigned) {\n await retryBursarOperation(() => this.credits.setUserPlan(input.accountId, planKey));\n }\n\n const grants: GrantProgramAwardResult[] = [];\n for (const [programKey, program] of Object.entries(config.credits.grantPrograms).sort(\n ([a], [b]) => a.localeCompare(b),\n )) {\n if (program.trigger !== \"account_created\") continue;\n grants.push(\n ...(await retryBursarOperation(() =>\n this.credits.executeGrantProgram({\n trigger: \"account_created\",\n programKey,\n subjectId: input.accountId,\n eventKey: input.eventKey,\n region: input.region,\n metadata: input.metadata,\n }),\n )),\n );\n }\n return {\n accountId: input.accountId,\n planKey: current.planKey ?? planKey,\n planAssigned,\n grants,\n };\n }\n}\n\n/**\n * The application-facing Bursar boundary.\n *\n * Credit and billing services are deliberately created together so consumers\n * cannot accidentally construct unrelated services for the same account\n * lifecycle. Provider and application integrations use this facade rather\n * than constructing lifecycle services independently.\n */\nexport class Bursar implements BillingEventSink {\n readonly credits: CreditsService;\n readonly billing: BillingCapability | null;\n readonly commerce: CommerceServiceImpl | null;\n readonly catalog: CatalogService;\n readonly accounts: AccountService;\n\n constructor(options: BursarOptions) {\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"Bursar options are required\");\n }\n if (options.billingStore === null) {\n throw new TypeError(\"billingStore must be a BillingStore when provided\");\n }\n for (const optionName of [\n \"creditsOptions\",\n \"billingOptions\",\n \"commerceOptions\",\n \"emitter\",\n ] as const) {\n if (options[optionName] === null) {\n throw new TypeError(`${optionName} must not be null`);\n }\n }\n if (\n options.billingStore === undefined &&\n (options.billingOptions !== undefined || options.commerceOptions !== undefined)\n ) {\n throw new TypeError(\"billingOptions and commerceOptions require billingStore\");\n }\n if (options.billingOptions && \"provisioning\" in options.billingOptions) {\n throw new TypeError(\"billingOptions.provisioning is owned by Bursar\");\n }\n const environments = [\n [\"creditStore\", options.creditStore.providerEnvironment],\n [\"billingStore\", options.billingStore?.providerEnvironment],\n [\"commerceOptions\", options.commerceOptions?.providerEnvironment],\n ].filter((entry): entry is [string, NonNullable<(typeof entry)[1]>] => entry[1] !== undefined);\n if (new Set(environments.map(([, environment]) => environment)).size > 1) {\n throw new TypeError(\n `Bursar provider environments must match: ${environments\n .map(([name, environment]) => `${name}=${environment}`)\n .join(\", \")}`,\n );\n }\n const credits = new CreditsServiceImpl(\n options.creditStore,\n undefined,\n options.emitter ?? undefined,\n options.creditsOptions ?? undefined,\n );\n this.credits = credits;\n this.catalog = new CatalogService(credits);\n this.accounts = new AccountService(credits, this.catalog);\n\n this.billing = options.billingStore\n ? new BillingEventService(options.billingStore, {\n ...(options.billingOptions ?? {}),\n provisioning: credits,\n })\n : null;\n this.commerce =\n this.billing && options.commerceOptions\n ? new CommerceServiceImpl(this.billing, credits, this, options.commerceOptions)\n : null;\n if (this.commerce) {\n credits.addPostDeductionHook(async ({ userId }) => {\n await this.commerce!.autoRecharge.processIfNeeded({ accountId: userId });\n });\n }\n }\n\n /** Load the active catalog into the pricing engine. */\n async loadCatalog(): Promise<void> {\n await this.catalog.load();\n }\n\n /** Return billing or raise the SDK's typed configuration error. */\n requireBilling(): BillingCapability {\n if (!this.billing) {\n throw new CapabilityNotConfiguredError(\"billing\");\n }\n return this.billing;\n }\n\n /** Return commerce or raise the SDK's typed configuration error. */\n requireCommerce(): CommerceServiceImpl {\n if (!this.commerce) {\n throw new CommerceNotConfiguredError(\"Bursar commerce capability is not configured\");\n }\n return this.commerce;\n }\n\n /**\n * Ingest a normalized provider event through the facade-owned billing\n * lifecycle. Providers must not depend on BillingService directly.\n */\n async ingestBillingEvent(event: BillingEvent): Promise<BillingEventResult> {\n return this.requireBilling().ingestBillingEvent(event);\n }\n}\n"]}
@@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