@fantastic.dev/better-stripe 0.56.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +5 -1
  3. package/dist/client/billing/setup-intent-read.d.ts +12 -1
  4. package/dist/client/billing/setup-intent-read.d.ts.map +1 -1
  5. package/dist/client/billing/setup-intent-read.js +13 -8
  6. package/dist/client/billing/setup-intent-read.js.map +1 -1
  7. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +366 -2
  8. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +183 -1
  10. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  11. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +366 -2
  12. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutSyncTestHelpers.d.ts +183 -1
  14. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  15. package/dist/client/index.d.ts +2 -12
  16. package/dist/client/index.d.ts.map +1 -1
  17. package/dist/client/index.js +3 -20
  18. package/dist/client/index.js.map +1 -1
  19. package/dist/client/types/triggers.d.ts +3 -1
  20. package/dist/client/types/triggers.d.ts.map +1 -1
  21. package/dist/client/usage/allowanceClient.d.ts +51 -0
  22. package/dist/client/usage/allowanceClient.d.ts.map +1 -0
  23. package/dist/client/usage/allowanceClient.js +64 -0
  24. package/dist/client/usage/allowanceClient.js.map +1 -0
  25. package/dist/client/usage/allowanceTerms.d.ts +64 -0
  26. package/dist/client/usage/allowanceTerms.d.ts.map +1 -0
  27. package/dist/client/usage/allowanceTerms.js +101 -0
  28. package/dist/client/usage/allowanceTerms.js.map +1 -0
  29. package/dist/client/usage/client.d.ts +2 -2
  30. package/dist/client/usage/client.d.ts.map +1 -1
  31. package/dist/client/usage/client.js +4 -4
  32. package/dist/client/usage/client.js.map +1 -1
  33. package/dist/client/usage/creditCapacity.d.ts +5 -0
  34. package/dist/client/usage/creditCapacity.d.ts.map +1 -0
  35. package/dist/client/usage/creditCapacity.js +47 -0
  36. package/dist/client/usage/creditCapacity.js.map +1 -0
  37. package/dist/client/usage/creditClient.d.ts +104 -0
  38. package/dist/client/usage/creditClient.d.ts.map +1 -0
  39. package/dist/client/usage/creditClient.js +111 -0
  40. package/dist/client/usage/creditClient.js.map +1 -0
  41. package/dist/client/usage/creditDelivery.d.ts +6 -0
  42. package/dist/client/usage/creditDelivery.d.ts.map +1 -0
  43. package/dist/client/usage/creditDelivery.js +71 -0
  44. package/dist/client/usage/creditDelivery.js.map +1 -0
  45. package/dist/client/usage/creditInvoice.d.ts +6 -0
  46. package/dist/client/usage/creditInvoice.d.ts.map +1 -0
  47. package/dist/client/usage/creditInvoice.js +63 -0
  48. package/dist/client/usage/creditInvoice.js.map +1 -0
  49. package/dist/client/usage/creditLifecycle.d.ts +14 -0
  50. package/dist/client/usage/creditLifecycle.d.ts.map +1 -0
  51. package/dist/client/usage/creditLifecycle.js +90 -0
  52. package/dist/client/usage/creditLifecycle.js.map +1 -0
  53. package/dist/client/usage/creditNative.d.ts +20 -0
  54. package/dist/client/usage/creditNative.d.ts.map +1 -0
  55. package/dist/client/usage/creditNative.js +100 -0
  56. package/dist/client/usage/creditNative.js.map +1 -0
  57. package/dist/client/usage/creditObservation.d.ts +23 -0
  58. package/dist/client/usage/creditObservation.d.ts.map +1 -0
  59. package/dist/client/usage/creditObservation.js +54 -0
  60. package/dist/client/usage/creditObservation.js.map +1 -0
  61. package/dist/client/usage/creditProofs.d.ts +50 -0
  62. package/dist/client/usage/creditProofs.d.ts.map +1 -0
  63. package/dist/client/usage/creditProofs.js +58 -0
  64. package/dist/client/usage/creditProofs.js.map +1 -0
  65. package/dist/client/usage/creditProvider.d.ts +11 -0
  66. package/dist/client/usage/creditProvider.d.ts.map +1 -0
  67. package/dist/client/usage/creditProvider.js +195 -0
  68. package/dist/client/usage/creditProvider.js.map +1 -0
  69. package/dist/client/usage/creditRead.d.ts +47 -0
  70. package/dist/client/usage/creditRead.d.ts.map +1 -0
  71. package/dist/client/usage/creditRead.js +18 -0
  72. package/dist/client/usage/creditRead.js.map +1 -0
  73. package/dist/client/usage/creditReconciliation.d.ts +20 -0
  74. package/dist/client/usage/creditReconciliation.d.ts.map +1 -0
  75. package/dist/client/usage/creditReconciliation.js +157 -0
  76. package/dist/client/usage/creditReconciliation.js.map +1 -0
  77. package/dist/client/usage/creditTerms.d.ts +89 -0
  78. package/dist/client/usage/creditTerms.d.ts.map +1 -0
  79. package/dist/client/usage/creditTerms.js +76 -0
  80. package/dist/client/usage/creditTerms.js.map +1 -0
  81. package/dist/client/usage/creditTransport.fixtures.d.ts +101 -0
  82. package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -0
  83. package/dist/client/usage/creditTransport.fixtures.js +271 -0
  84. package/dist/client/usage/creditTransport.fixtures.js.map +1 -0
  85. package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
  86. package/dist/client/usage/deliveryProvider.js +2 -0
  87. package/dist/client/usage/deliveryProvider.js.map +1 -1
  88. package/dist/client/usage/index.d.ts +4 -0
  89. package/dist/client/usage/index.d.ts.map +1 -1
  90. package/dist/client/usage/index.js +1 -0
  91. package/dist/client/usage/index.js.map +1 -1
  92. package/dist/client/usage/records.d.ts +2 -0
  93. package/dist/client/usage/records.d.ts.map +1 -1
  94. package/dist/client/usage/records.js +22 -0
  95. package/dist/client/usage/records.js.map +1 -1
  96. package/dist/client/usage/subscriptionTransport.fixtures.d.ts +1 -1
  97. package/dist/client/usage/subscriptionTransport.fixtures.d.ts.map +1 -1
  98. package/dist/client/usage/subscriptionTransport.fixtures.js +4 -1
  99. package/dist/client/usage/subscriptionTransport.fixtures.js.map +1 -1
  100. package/dist/client/usage/summary.js +2 -2
  101. package/dist/client/usage/summary.js.map +1 -1
  102. package/dist/client/usageExports.d.ts +16 -0
  103. package/dist/client/usageExports.d.ts.map +1 -0
  104. package/dist/client/usageExports.js +3 -0
  105. package/dist/client/usageExports.js.map +1 -0
  106. package/dist/client/webhooks/subscriptionDeleted.d.ts +5 -0
  107. package/dist/client/webhooks/subscriptionDeleted.d.ts.map +1 -0
  108. package/dist/client/webhooks/subscriptionDeleted.js +34 -0
  109. package/dist/client/webhooks/subscriptionDeleted.js.map +1 -0
  110. package/dist/component/_generated/api.d.ts +18 -0
  111. package/dist/component/_generated/api.d.ts.map +1 -1
  112. package/dist/component/_generated/api.js.map +1 -1
  113. package/dist/component/_generated/component.d.ts +360 -0
  114. package/dist/component/_generated/component.d.ts.map +1 -1
  115. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  116. package/dist/component/accountClosure/mutations.js +10 -0
  117. package/dist/component/accountClosure/mutations.js.map +1 -1
  118. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  119. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  120. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  121. package/dist/component/balanceFunding/queries.d.ts +1 -1
  122. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  123. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  124. package/dist/component/earnings/triggers.d.ts +352 -18
  125. package/dist/component/earnings/triggers.d.ts.map +1 -1
  126. package/dist/component/payoutRelease/queries.d.ts +2 -2
  127. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  128. package/dist/component/schema.d.ts +183 -1
  129. package/dist/component/schema.js +8 -0
  130. package/dist/component/schema.js.map +1 -1
  131. package/dist/component/usage/mutations.d.ts.map +1 -1
  132. package/dist/component/usage/mutations.js +7 -0
  133. package/dist/component/usage/mutations.js.map +1 -1
  134. package/dist/component/usage/schema.d.ts +15 -1
  135. package/dist/component/usage/schema.d.ts.map +1 -1
  136. package/dist/component/usage/schema.js +12 -0
  137. package/dist/component/usage/schema.js.map +1 -1
  138. package/dist/component/usageAllowance/helpers.d.ts +78 -0
  139. package/dist/component/usageAllowance/helpers.d.ts.map +1 -0
  140. package/dist/component/usageAllowance/helpers.js +99 -0
  141. package/dist/component/usageAllowance/helpers.js.map +1 -0
  142. package/dist/component/usageAllowance/mutations.d.ts +37 -0
  143. package/dist/component/usageAllowance/mutations.d.ts.map +1 -0
  144. package/dist/component/usageAllowance/mutations.js +99 -0
  145. package/dist/component/usageAllowance/mutations.js.map +1 -0
  146. package/dist/component/usageAllowance/queries.d.ts +36 -0
  147. package/dist/component/usageAllowance/queries.d.ts.map +1 -0
  148. package/dist/component/usageAllowance/queries.js +113 -0
  149. package/dist/component/usageAllowance/queries.js.map +1 -0
  150. package/dist/component/usageAllowance/reservations.d.ts +25 -0
  151. package/dist/component/usageAllowance/reservations.d.ts.map +1 -0
  152. package/dist/component/usageAllowance/reservations.js +150 -0
  153. package/dist/component/usageAllowance/reservations.js.map +1 -0
  154. package/dist/component/usageAllowance/schema.d.ts +77 -0
  155. package/dist/component/usageAllowance/schema.d.ts.map +1 -0
  156. package/dist/component/usageAllowance/schema.js +32 -0
  157. package/dist/component/usageAllowance/schema.js.map +1 -0
  158. package/dist/component/usageCredits/helpers.d.ts +205 -0
  159. package/dist/component/usageCredits/helpers.d.ts.map +1 -0
  160. package/dist/component/usageCredits/helpers.js +129 -0
  161. package/dist/component/usageCredits/helpers.js.map +1 -0
  162. package/dist/component/usageCredits/mutations.d.ts +80 -0
  163. package/dist/component/usageCredits/mutations.d.ts.map +1 -0
  164. package/dist/component/usageCredits/mutations.js +344 -0
  165. package/dist/component/usageCredits/mutations.js.map +1 -0
  166. package/dist/component/usageCredits/purchase.d.ts +23 -0
  167. package/dist/component/usageCredits/purchase.d.ts.map +1 -0
  168. package/dist/component/usageCredits/purchase.js +166 -0
  169. package/dist/component/usageCredits/purchase.js.map +1 -0
  170. package/dist/component/usageCredits/queries.d.ts +184 -0
  171. package/dist/component/usageCredits/queries.d.ts.map +1 -0
  172. package/dist/component/usageCredits/queries.js +243 -0
  173. package/dist/component/usageCredits/queries.js.map +1 -0
  174. package/dist/component/usageCredits/reservations.d.ts +16 -0
  175. package/dist/component/usageCredits/reservations.d.ts.map +1 -0
  176. package/dist/component/usageCredits/reservations.js +161 -0
  177. package/dist/component/usageCredits/reservations.js.map +1 -0
  178. package/dist/component/usageCredits/schema.d.ts +282 -0
  179. package/dist/component/usageCredits/schema.d.ts.map +1 -0
  180. package/dist/component/usageCredits/schema.js +92 -0
  181. package/dist/component/usageCredits/schema.js.map +1 -0
  182. package/docs/README.md +4 -0
  183. package/docs/setup-intent-recovery.md +7 -0
  184. package/docs/usage-credits.md +255 -0
  185. package/docs/usage-ledger.md +7 -0
  186. package/docs/usage-limits.md +217 -0
  187. package/docs/webhooks.md +15 -1
  188. package/package.json +3 -1
  189. package/src/client/billing/setup-intent-read.test.ts +40 -0
  190. package/src/client/billing/setup-intent-read.ts +23 -9
  191. package/src/client/index.ts +9 -67
  192. package/src/client/types/triggers.ts +2 -0
  193. package/src/client/usage/allowanceClient.test.ts +93 -0
  194. package/src/client/usage/allowanceClient.ts +134 -0
  195. package/src/client/usage/allowanceTerms.test.ts +131 -0
  196. package/src/client/usage/allowanceTerms.ts +172 -0
  197. package/src/client/usage/client.ts +4 -4
  198. package/src/client/usage/creditCapacity.test.ts +83 -0
  199. package/src/client/usage/creditCapacity.ts +76 -0
  200. package/src/client/usage/creditClient.test.ts +221 -0
  201. package/src/client/usage/creditClient.ts +246 -0
  202. package/src/client/usage/creditDelivery.ts +105 -0
  203. package/src/client/usage/creditInvoice.test.ts +149 -0
  204. package/src/client/usage/creditInvoice.ts +87 -0
  205. package/src/client/usage/creditLifecycle.ts +175 -0
  206. package/src/client/usage/creditNative.ts +148 -0
  207. package/src/client/usage/creditObservation.test.ts +150 -0
  208. package/src/client/usage/creditObservation.ts +82 -0
  209. package/src/client/usage/creditProofs.ts +61 -0
  210. package/src/client/usage/creditProvider.test.ts +202 -0
  211. package/src/client/usage/creditProvider.ts +304 -0
  212. package/src/client/usage/creditRead.ts +32 -0
  213. package/src/client/usage/creditReconciliation.ts +213 -0
  214. package/src/client/usage/creditTerms.test.ts +48 -0
  215. package/src/client/usage/creditTerms.ts +140 -0
  216. package/src/client/usage/creditTransport.fixtures.ts +282 -0
  217. package/src/client/usage/deliveryProvider.ts +2 -0
  218. package/src/client/usage/index.ts +16 -0
  219. package/src/client/usage/record-composition.test.ts +195 -0
  220. package/src/client/usage/records.ts +26 -0
  221. package/src/client/usage/subscriptionTransport.fixtures.ts +6 -0
  222. package/src/client/usage/summary.test.ts +1 -1
  223. package/src/client/usage/summary.ts +2 -2
  224. package/src/client/usageExports.ts +56 -0
  225. package/src/client/webhook-handlers.test.ts +0 -34
  226. package/src/client/webhooks/subscription-deleted-dispatch.test.ts +61 -0
  227. package/src/client/webhooks/subscription-deleted.integration.test.ts +313 -0
  228. package/src/client/webhooks/subscriptionDeleted.ts +56 -0
  229. package/src/component/_generated/api.ts +18 -0
  230. package/src/component/_generated/component.ts +486 -0
  231. package/src/component/accountClosure/mutations.ts +14 -0
  232. package/src/component/schema.ts +16 -0
  233. package/src/component/usage/allowance.test.ts +435 -0
  234. package/src/component/usage/ledger.test.ts +8 -15
  235. package/src/component/usage/mutations.ts +22 -0
  236. package/src/component/usage/schema.ts +14 -0
  237. package/src/component/usageAllowance/helpers.ts +137 -0
  238. package/src/component/usageAllowance/mutations.ts +139 -0
  239. package/src/component/usageAllowance/queries.ts +133 -0
  240. package/src/component/usageAllowance/reservations.ts +220 -0
  241. package/src/component/usageAllowance/schema.ts +36 -0
  242. package/src/component/usageCredits/accounting.test.ts +389 -0
  243. package/src/component/usageCredits/helpers.ts +160 -0
  244. package/src/component/usageCredits/mutations.ts +451 -0
  245. package/src/component/usageCredits/purchase.ts +219 -0
  246. package/src/component/usageCredits/queries.ts +300 -0
  247. package/src/component/usageCredits/reservations.ts +214 -0
  248. package/src/component/usageCredits/schema.ts +106 -0
@@ -12,6 +12,7 @@ export type { RecordUsageOptions } from "./usage/client.js";
12
12
  export type {
13
13
  SetupIntentReadOptions,
14
14
  SetupIntentObservation,
15
+ SetupIntentObservationStatus,
15
16
  } from "./billing/setup-intent-read.js";
16
17
  import * as subscriptionPaymentMethod from "./billing/subscription-payment-method.js";
17
18
  import type {
@@ -193,6 +194,7 @@ import type {
193
194
  V2AccountUpdateParams,
194
195
  } from "./stripe-types.js";
195
196
  import { componentRef, DISPATCHER_UPSERT_PATHS } from "./webhooks/helpers.js";
197
+ import { upsertDeletedSubscriptionAndTrigger } from "./webhooks/subscriptionDeleted.js";
196
198
  import type {
197
199
  AccountLinkWithStatus,
198
200
  AsyncHookCtx,
@@ -1653,34 +1655,13 @@ export class BetterStripe extends PaymentSourceClient {
1653
1655
  ),
1654
1656
  record,
1655
1657
  ),
1656
- // Special case: marks the subscription canceled via upsert, then fires
1657
- // onDelete with the resulting doc. No pre-upsert read is needed.
1658
- subscriptionDeleted: async (ctx, record) => {
1659
- const id = record.stripeSubscriptionId;
1660
- if (typeof id !== "string") {
1661
- throw new Error(
1662
- "[better-stripe] subscriptionDeleted: missing stripeSubscriptionId in data",
1663
- );
1664
- }
1665
- await ctx.runMutation(
1666
- componentRef(component, DISPATCHER_UPSERT_PATHS.subscriptionDeleted),
1658
+ subscriptionDeleted: (ctx, record) =>
1659
+ upsertDeletedSubscriptionAndTrigger(
1660
+ component,
1661
+ ctx,
1667
1662
  record,
1668
- );
1669
- if (!onSubscriptionDeleted) return;
1670
- const doc = (await ctx.runQuery(
1671
- componentRef(component, "billing/queries/getSubscriptionByStripeId"),
1672
- { stripeSubscriptionId: id },
1673
- )) as StripeComponentSubscription | null;
1674
- if (doc === null) {
1675
- // Mutations read their own writes, so this cannot happen;
1676
- // fail loudly if it ever does.
1677
- throw new Error(
1678
- "[better-stripe] subscriptionDeleted: doc not found after " +
1679
- `upsert (stripeSubscriptionId=${id})`,
1680
- );
1681
- }
1682
- await onSubscriptionDeleted(ctx, doc);
1683
- },
1663
+ onSubscriptionDeleted,
1664
+ ),
1684
1665
  checkoutSessionUpserted: (ctx, record) =>
1685
1666
  runUpsertAndTrigger<StripeComponentCheckoutSession>(
1686
1667
  ctx,
@@ -1829,43 +1810,4 @@ export type {
1829
1810
  SubscriptionPaymentMethodResult,
1830
1811
  } from "./billing/subscription-payment-method.js";
1831
1812
 
1832
- export type {
1833
- UsageDeliveryRequest,
1834
- UsageDeliveryOutcome,
1835
- UsageDeliveryProviderOptions,
1836
- } from "./usage/deliveryProvider.js";
1837
- export type {
1838
- UsageDeliveryRef,
1839
- UsageDeliveryStatus,
1840
- UsageDeliveryStartOptions,
1841
- } from "./usage/deliveryClient.js";
1842
-
1843
- export {
1844
- usageDeliveryArgs,
1845
- usageDeliveryResult,
1846
- } from "./usage/deliveryProtocol.js";
1847
-
1848
- export type {
1849
- UsageObservationOptions,
1850
- UsageAggregateValue,
1851
- UsageAggregateObservation,
1852
- } from "./usage/observationTypes.js";
1853
- export type {
1854
- UsageLocalSummary,
1855
- UsageLocalGroup,
1856
- UsageCreditSummary,
1857
- } from "./usage/summary.js";
1858
- export type { UsageComparison } from "./usage/reconciliation.js";
1859
- export type { UsageReconciliationOptions } from "./usage/observationClient.js";
1860
-
1861
- export type {
1862
- UsageInvoiceObservation,
1863
- UsageInvoiceLine,
1864
- } from "./usage/invoiceObservation.js";
1865
-
1866
- export type {
1867
- UsageSubscriptionOptions,
1868
- UsageSubscriptionView,
1869
- } from "./usage/subscriptionTerms.js";
1870
- export type { UsageSubscriptionRef } from "./usage/subscriptionLifecycle.js";
1871
- export type { UsageSubscriptionInvoice } from "./usage/subscriptionInvoiceSchema.js";
1813
+ export * from "./usageExports.js";
@@ -47,6 +47,8 @@ export interface SyncTriggers {
47
47
  onDelete?: (
48
48
  ctx: SyncTriggerCtx,
49
49
  doc: StripeComponentSubscription,
50
+ /** Exact pre-upsert identity; null means absent, undefined supports legacy callers. */
51
+ oldDoc?: StripeComponentSubscription | null,
50
52
  ) => Promise<void>;
51
53
  };
52
54
  checkoutSession?: {
@@ -0,0 +1,93 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { BetterStripe } from "../index.js";
3
+ import type { RunCtx } from "../helpers.js";
4
+ import { fixture } from "./subscriptionTransport.fixtures.js";
5
+ import { request } from "./subscription.fixtures.js";
6
+ import { ensureManagedSubscription } from "./subscriptionProvider.js";
7
+ afterEach(() => vi.useRealTimers());
8
+ it("configures, reserves, reads and releases through the public component facade", async () => {
9
+ vi.useFakeTimers();
10
+ vi.setSystemTime(700000);
11
+ const f = fixture(),
12
+ client = new BetterStripe(f.component);
13
+ const view = await f.t.action((ctx) =>
14
+ ensureManagedSubscription(f.stripe, f.component, ctx as RunCtx, request),
15
+ );
16
+ const original = view.bindings[0];
17
+ const policy = {
18
+ reset: "billing_period",
19
+ rollover: "none",
20
+ entitled: true,
21
+ overage: "reject",
22
+ limit: { mode: "none" },
23
+ } as const;
24
+ expect(
25
+ await f.t.action((ctx) =>
26
+ client.usage.configureAllowance(ctx as RunCtx, {
27
+ ...original,
28
+ policy,
29
+ expectedRevision: 0,
30
+ }),
31
+ ),
32
+ ).toEqual({ revision: 1 });
33
+ const event = {
34
+ scope: original.scope,
35
+ binding: original.binding,
36
+ sourceEventId: "work1",
37
+ quantity: "6",
38
+ occurredAt: 700,
39
+ };
40
+ const reservation = await f.t.action((ctx) =>
41
+ client.usage.reserveAllowance(ctx as RunCtx, {
42
+ event,
43
+ subscription: original.subscription,
44
+ }),
45
+ );
46
+ expect(reservation.state).toBe("reserved");
47
+ expect(
48
+ await f.t.query((ctx) =>
49
+ client.usage.getAllowanceStatus(ctx as RunCtx, original),
50
+ ),
51
+ ).toMatchObject({
52
+ consumedQuantity: "0",
53
+ reservedQuantity: "6",
54
+ hardLimitRemainingQuantity: "4",
55
+ });
56
+ const denied = await f.t.action((ctx) =>
57
+ client.usage.reserveAllowance(ctx as RunCtx, {
58
+ event: { ...event, sourceEventId: "work2" },
59
+ subscription: original.subscription,
60
+ }),
61
+ );
62
+ expect(denied).toMatchObject({ state: "denied", reason: "hard_limit" });
63
+ if (reservation.state === "denied") throw new Error("Unexpected denial");
64
+ await f.t.action((ctx) =>
65
+ client.usage.releaseAllowance(ctx as RunCtx, {
66
+ scope: original.scope,
67
+ reservationId: reservation.reservationId,
68
+ reason: "work_failed",
69
+ }),
70
+ );
71
+ expect(
72
+ await f.t.query((ctx) =>
73
+ client.usage.reconcileAllowance(ctx as RunCtx, original),
74
+ ),
75
+ ).toMatchObject({ status: "matched", repaired: false });
76
+ const page = await f.t.query((ctx) =>
77
+ client.usage.readAllowanceHistory(ctx as RunCtx, {
78
+ ...original,
79
+ limit: 1,
80
+ cursor: null,
81
+ }),
82
+ );
83
+ expect(page.records).toHaveLength(1);
84
+ expect(page.cursor).not.toBeNull();
85
+ expect(
86
+ await f.t.query((ctx) =>
87
+ client.usage.getAllowanceStatus(ctx as RunCtx, {
88
+ ...original,
89
+ scope: { ...original.scope, customerAccount: "acct_other" },
90
+ }),
91
+ ),
92
+ ).toBeNull();
93
+ });
@@ -0,0 +1,134 @@
1
+ import { z } from "zod";
2
+ import type { RunCtx } from "../helpers.js";
3
+ import { runMutationOrThrow } from "../helpers.js";
4
+ import { componentRef } from "../webhooks/helpers.js";
5
+ import { UsageCreditClient } from "./creditClient.js";
6
+ import { prepareUsageRecord, scopeSchema, type UsageScope } from "./records.js";
7
+ import {
8
+ allowanceBinding,
9
+ limitPolicy,
10
+ type UsageAllowanceBinding,
11
+ type UsageAllowanceStatus,
12
+ type UsageAllowanceReconciliation,
13
+ type UsageLimitPolicy,
14
+ } from "./allowanceTerms.js";
15
+ import type { UsageSubscriptionBinding } from "./boundaries.js";
16
+ import type { Doc, Id } from "../../component/_generated/dataModel.js";
17
+ export type UsageAllowanceReservation =
18
+ | { state: "denied"; reason: "not_entitled" | "hard_limit"; revision: number }
19
+ | {
20
+ state: "reserved" | "committed" | "released";
21
+ reservationId: Id<"usageReservations">;
22
+ revision: number;
23
+ };
24
+ const bindingJson = (input: UsageAllowanceBinding) =>
25
+ JSON.stringify(
26
+ allowanceBinding({
27
+ scope: input.scope,
28
+ binding: input.binding,
29
+ subscription: input.subscription,
30
+ }),
31
+ );
32
+ /** Trusted host authorizes policy management and the exact billable activity. */
33
+ export class UsageAllowanceClient extends UsageCreditClient {
34
+ configureAllowance(
35
+ ctx: RunCtx,
36
+ input: UsageAllowanceBinding & {
37
+ policy: UsageLimitPolicy;
38
+ expectedRevision: number;
39
+ },
40
+ ): Promise<{ revision: number }> {
41
+ const binding = allowanceBinding({
42
+ scope: input.scope,
43
+ binding: input.binding,
44
+ subscription: input.subscription,
45
+ });
46
+ return runMutationOrThrow(
47
+ ctx,
48
+ componentRef(this.component, "usageAllowance/mutations/configure"),
49
+ {
50
+ bindingJson: JSON.stringify(binding),
51
+ policyJson: JSON.stringify(limitPolicy(input.policy, binding)),
52
+ expectedRevision: input.expectedRevision,
53
+ },
54
+ );
55
+ }
56
+ async getAllowanceStatus(
57
+ ctx: RunCtx,
58
+ input: UsageAllowanceBinding,
59
+ ): Promise<UsageAllowanceStatus | null> {
60
+ const result = (await ctx.runQuery(
61
+ componentRef(this.component, "usageAllowance/queries/status"),
62
+ { bindingJson: bindingJson(input) },
63
+ )) as string | null;
64
+ return result === null
65
+ ? null
66
+ : (JSON.parse(result) as UsageAllowanceStatus);
67
+ }
68
+ reconcileAllowance(
69
+ ctx: RunCtx,
70
+ input: UsageAllowanceBinding,
71
+ ): Promise<UsageAllowanceReconciliation> {
72
+ return ctx.runQuery(
73
+ componentRef(this.component, "usageAllowance/queries/reconciliation"),
74
+ { bindingJson: bindingJson(input) },
75
+ );
76
+ }
77
+ reserveAllowance(
78
+ ctx: RunCtx,
79
+ input: { event: unknown; subscription: UsageSubscriptionBinding },
80
+ ): Promise<UsageAllowanceReservation> {
81
+ const event = prepareUsageRecord(input.event);
82
+ return runMutationOrThrow(
83
+ ctx,
84
+ componentRef(this.component, "usageAllowance/mutations/reserve"),
85
+ {
86
+ inputJson: JSON.stringify({
87
+ scope: event.scope,
88
+ binding: event.binding,
89
+ sourceEventId: event.sourceEventId,
90
+ occurredAt: event.occurredAt,
91
+ quantity: event.quantity,
92
+ }),
93
+ subscriptionJson: JSON.stringify(input.subscription),
94
+ },
95
+ );
96
+ }
97
+ releaseAllowance(
98
+ ctx: RunCtx,
99
+ input: {
100
+ scope: UsageScope;
101
+ reservationId: Id<"usageReservations">;
102
+ reason: "work_failed" | "abandoned_before_work";
103
+ },
104
+ ) {
105
+ return runMutationOrThrow(
106
+ ctx,
107
+ componentRef(this.component, "usageAllowance/mutations/release"),
108
+ { ...input, scope: scopeSchema.parse(input.scope) },
109
+ );
110
+ }
111
+ async readAllowanceHistory(
112
+ ctx: RunCtx,
113
+ input: UsageAllowanceBinding & { limit: number; cursor: string | null },
114
+ ) {
115
+ const limit = z.number().int().min(1).max(100).parse(input.limit),
116
+ cursor = z.string().min(1).max(2048).nullable().parse(input.cursor);
117
+ const result = (await ctx.runQuery(
118
+ componentRef(this.component, "usageAllowance/queries/readHistory"),
119
+ {
120
+ bindingJson: bindingJson(input),
121
+ paginationOpts: { numItems: limit, cursor },
122
+ },
123
+ )) as {
124
+ page: Doc<"usageAllowanceHistory">[];
125
+ continueCursor: string;
126
+ isDone: boolean;
127
+ };
128
+ return {
129
+ records: result.page,
130
+ cursor: result.isDone ? null : result.continueCursor,
131
+ isDone: result.isDone,
132
+ };
133
+ }
134
+ }
@@ -0,0 +1,131 @@
1
+ import { expect, it } from "vitest";
2
+ import {
3
+ allowanceBinding,
4
+ allowanceStatus,
5
+ limitPolicy,
6
+ } from "./allowanceTerms.js";
7
+ import { request } from "./subscription.fixtures.js";
8
+ const original = {
9
+ ...request.meters[0],
10
+ subscription: {
11
+ subscriptionId: "sub_calls",
12
+ subscriptionItemId: "si_calls",
13
+ stripePriceId: "price_calls",
14
+ period: { start: 600, end: 1200 },
15
+ interval: "month",
16
+ },
17
+ };
18
+ it("calculates fractional units and decimal minor-currency estimates without rounding", () => {
19
+ const binding = allowanceBinding({
20
+ ...original,
21
+ binding: {
22
+ ...original.binding,
23
+ plan: {
24
+ ...original.binding.plan,
25
+ unit: { name: "call", precision: 2 },
26
+ includedQuantity: "1.25",
27
+ rate: { currency: "usd", unitAmountDecimal: "0.025" },
28
+ },
29
+ },
30
+ });
31
+ const policy = limitPolicy(
32
+ {
33
+ reset: "billing_period",
34
+ rollover: "none",
35
+ entitled: true,
36
+ overage: "allow",
37
+ limit: { mode: "soft", quantity: "1.30" },
38
+ },
39
+ binding,
40
+ );
41
+ expect(
42
+ allowanceStatus(
43
+ binding,
44
+ policy,
45
+ { consumed: "130", reserved: "1", revision: 1 },
46
+ 700,
47
+ ),
48
+ ).toMatchObject({
49
+ consumedQuantity: "1.3",
50
+ reservedQuantity: "0.01",
51
+ billableOverageQuantity: "0.05",
52
+ softLimitReached: true,
53
+ committedEstimate: { amountDecimal: "0.00125", currency: "usd" },
54
+ projectedEstimate: { amountDecimal: "0.0015", currency: "usd" },
55
+ });
56
+ });
57
+ it("rejects unsupported rollover/reset, invalid precision and prepaid instead of minting allowance credit", () => {
58
+ const binding = allowanceBinding(original),
59
+ policy = {
60
+ reset: "billing_period",
61
+ rollover: "none",
62
+ entitled: true,
63
+ overage: "allow",
64
+ limit: { mode: "none" },
65
+ };
66
+ for (const changed of [
67
+ { ...policy, reset: "calendar_month" },
68
+ { ...policy, rollover: "carry" },
69
+ { ...policy, limit: { mode: "hard", quantity: "0.1" } },
70
+ { ...policy, limit: { mode: "hard", quantity: "1000000000000000000" } },
71
+ ])
72
+ expect(() => limitPolicy(changed, binding)).toThrow();
73
+ expect(() =>
74
+ allowanceBinding({
75
+ ...original,
76
+ binding: {
77
+ ...original.binding,
78
+ plan: {
79
+ key: "calls",
80
+ version: "v1",
81
+ model: "prepaid",
82
+ unit: { name: "call", precision: 0 },
83
+ rate: { currency: "usd", unitAmountDecimal: "2" },
84
+ insufficientBalance: "reject",
85
+ },
86
+ },
87
+ }),
88
+ ).toThrow(/payment-backed/i);
89
+ });
90
+ it("supports optional pay-as-you-go hard caps without inventing included units", () => {
91
+ const binding = allowanceBinding({
92
+ ...original,
93
+ binding: {
94
+ ...original.binding,
95
+ plan: {
96
+ key: "calls",
97
+ version: "v1",
98
+ model: "pay_as_you_go",
99
+ unit: { name: "call", precision: 0 },
100
+ rate: { currency: "usd", unitAmountDecimal: "2" },
101
+ },
102
+ },
103
+ });
104
+ const policy = limitPolicy(
105
+ {
106
+ reset: "billing_period",
107
+ rollover: "none",
108
+ entitled: true,
109
+ overage: "allow",
110
+ limit: { mode: "hard", quantity: "12" },
111
+ },
112
+ binding,
113
+ );
114
+ expect(
115
+ allowanceStatus(
116
+ binding,
117
+ policy,
118
+ { consumed: "6", reserved: "6", revision: 1 },
119
+ 700,
120
+ ),
121
+ ).toMatchObject({
122
+ includedQuantity: "0",
123
+ hardLimitRemainingQuantity: "0",
124
+ accepting: false,
125
+ committedEstimate: { amountDecimal: "12", currency: "usd" },
126
+ projectedEstimate: { amountDecimal: "24", currency: "usd" },
127
+ });
128
+ expect(() => limitPolicy({ ...policy, overage: "reject" }, binding)).toThrow(
129
+ /explicit usage cap/i,
130
+ );
131
+ });
@@ -0,0 +1,172 @@
1
+ import { z } from "zod";
2
+ import { prepareUsageRecord, type PreparedUsageRecord } from "./records.js";
3
+ import { parseUsageQuantity } from "./contracts.js";
4
+ import { decimalFromScaled } from "./summary.js";
5
+ import type { UsageSubscriptionBinding } from "./boundaries.js";
6
+ export type UsageAllowanceBinding = Pick<
7
+ PreparedUsageRecord,
8
+ "scope" | "binding"
9
+ > & {
10
+ subscription: UsageSubscriptionBinding;
11
+ };
12
+ const seconds = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
13
+ const subscriptionSchema = z.strictObject({
14
+ subscriptionId: z.string().regex(/^sub_[a-zA-Z0-9]+$/),
15
+ subscriptionItemId: z.string().regex(/^si_[a-zA-Z0-9]+$/),
16
+ stripePriceId: z.string().regex(/^price_[a-zA-Z0-9]+$/),
17
+ period: z.strictObject({ start: seconds, end: seconds }),
18
+ interval: z.literal("month"),
19
+ });
20
+ export const usageLimitPolicySchema = z.strictObject({
21
+ reset: z.literal("billing_period"),
22
+ rollover: z.literal("none"),
23
+ entitled: z.boolean(),
24
+ overage: z.enum(["allow", "reject"]),
25
+ limit: z.discriminatedUnion("mode", [
26
+ z.strictObject({ mode: z.literal("none") }),
27
+ z.strictObject({ mode: z.enum(["soft", "hard"]), quantity: z.string() }),
28
+ ]),
29
+ });
30
+ export type UsageLimitPolicy = z.infer<typeof usageLimitPolicySchema>;
31
+ export type UsageAllowanceStatus = {
32
+ revision: number;
33
+ observedAt: number;
34
+ period: UsageSubscriptionBinding["period"];
35
+ accepting: boolean;
36
+ policy: UsageLimitPolicy;
37
+ consumedQuantity: string;
38
+ reservedQuantity: string;
39
+ includedQuantity: string;
40
+ remainingIncludedQuantity: string;
41
+ billableOverageQuantity: string;
42
+ softLimitReached: boolean;
43
+ hardLimitRemainingQuantity: string | null;
44
+ committedEstimate: { amountDecimal: string; currency: string };
45
+ projectedEstimate: { amountDecimal: string; currency: string };
46
+ cashCollection: "none";
47
+ };
48
+ export function allowanceBinding(input: unknown): UsageAllowanceBinding {
49
+ const raw = z
50
+ .strictObject({
51
+ scope: z.unknown(),
52
+ binding: z.unknown(),
53
+ subscription: subscriptionSchema,
54
+ })
55
+ .parse(input);
56
+ const event = prepareUsageRecord({
57
+ scope: raw.scope,
58
+ binding: raw.binding,
59
+ sourceEventId: "validation",
60
+ quantity: "0",
61
+ occurredAt: 0,
62
+ });
63
+ if (event.binding.plan.model === "prepaid")
64
+ throw new Error("Use payment-backed prepaid credit accounting");
65
+ if (
66
+ raw.subscription.period.end <= raw.subscription.period.start ||
67
+ raw.subscription.stripePriceId !== event.binding.stripePriceId
68
+ )
69
+ throw new Error("Allowance subscription period/price mismatch");
70
+ return {
71
+ scope: event.scope,
72
+ binding: event.binding,
73
+ subscription: raw.subscription,
74
+ };
75
+ }
76
+ export function limitPolicy(
77
+ input: unknown,
78
+ binding: UsageAllowanceBinding,
79
+ ): UsageLimitPolicy {
80
+ const policy = usageLimitPolicySchema.parse(input),
81
+ precision = binding.binding.plan.unit.precision;
82
+ if (policy.limit.mode !== "none")
83
+ policy.limit.quantity = parseUsageQuantity(
84
+ policy.limit.quantity,
85
+ precision,
86
+ ).quantity;
87
+ if (
88
+ binding.binding.plan.model === "pay_as_you_go" &&
89
+ policy.overage === "reject"
90
+ )
91
+ throw new Error(
92
+ "Pay-as-you-go requires an explicit usage cap instead of an included allowance",
93
+ );
94
+ return policy;
95
+ }
96
+ export function allowanceStatus(
97
+ binding: UsageAllowanceBinding,
98
+ policy: UsageLimitPolicy,
99
+ row: { consumed: string; reserved: string; revision: number },
100
+ observedAt: number,
101
+ ): UsageAllowanceStatus {
102
+ const plan = binding.binding.plan,
103
+ precision = plan.unit.precision;
104
+ const consumed = BigInt(row.consumed),
105
+ reserved = BigInt(row.reserved),
106
+ total = consumed + reserved;
107
+ const included =
108
+ plan.model === "included_overage"
109
+ ? BigInt(
110
+ parseUsageQuantity(plan.includedQuantity, precision).scaledQuantity,
111
+ )
112
+ : 0n;
113
+ const overage = (quantity: bigint) =>
114
+ quantity > included ? quantity - included : 0n;
115
+ const quantity = (value: bigint) => decimalFromScaled(value, precision);
116
+ const cost = (value: bigint) => {
117
+ const [whole, fraction = ""] = plan.rate.unitAmountDecimal.split(".");
118
+ return {
119
+ amountDecimal: decimalFromScaled(
120
+ overage(value) * BigInt(whole + fraction),
121
+ precision + fraction.length,
122
+ ),
123
+ currency: plan.rate.currency,
124
+ };
125
+ };
126
+ let hard: bigint | null =
127
+ policy.limit.mode === "hard"
128
+ ? BigInt(
129
+ parseUsageQuantity(policy.limit.quantity, precision).scaledQuantity,
130
+ )
131
+ : null;
132
+ if (policy.overage === "reject")
133
+ hard = hard === null || included < hard ? included : hard;
134
+ return {
135
+ revision: row.revision,
136
+ observedAt,
137
+ period: binding.subscription.period,
138
+ accepting:
139
+ policy.entitled &&
140
+ observedAt >= binding.subscription.period.start &&
141
+ observedAt < binding.subscription.period.end - 60 &&
142
+ (hard === null || total < hard),
143
+ policy,
144
+ consumedQuantity: quantity(consumed),
145
+ reservedQuantity: quantity(reserved),
146
+ includedQuantity: quantity(included),
147
+ remainingIncludedQuantity: quantity(
148
+ included > total ? included - total : 0n,
149
+ ),
150
+ billableOverageQuantity: quantity(overage(consumed)),
151
+ softLimitReached:
152
+ policy.limit.mode === "soft" &&
153
+ total >=
154
+ BigInt(
155
+ parseUsageQuantity(policy.limit.quantity, precision).scaledQuantity,
156
+ ),
157
+ hardLimitRemainingQuantity:
158
+ hard === null ? null : quantity(hard > total ? hard - total : 0n),
159
+ committedEstimate: cost(consumed),
160
+ projectedEstimate: cost(total),
161
+ cashCollection: "none",
162
+ };
163
+ }
164
+
165
+ export type UsageAllowanceReconciliation = {
166
+ status: "matched" | "held";
167
+ reason: string;
168
+ consumedScaledQuantity: string;
169
+ reservedScaledQuantity: string;
170
+ acceptedScaledQuantity: string;
171
+ repaired: false;
172
+ };
@@ -1,9 +1,9 @@
1
- import { UsageSubscriptionClient } from "./subscriptionClient.js";
1
+ import { UsageAllowanceClient } from "./allowanceClient.js";
2
2
  import type { Component, RunCtx } from "../helpers.js";
3
3
  import { runMutationOrThrow } from "../helpers.js";
4
4
  import { componentRef } from "../webhooks/helpers.js";
5
5
  import {
6
- prepareUsageRecord,
6
+ validateUsageRecordInput,
7
7
  type PreparedUsageRecord,
8
8
  type UsageScope,
9
9
  type UsageDeliveryState,
@@ -46,12 +46,12 @@ function decode({ event, delivery }: StoredView): UsageEventView {
46
46
  };
47
47
  }
48
48
  /** Trusted host facade. Authenticate and authorize each exact scope first. */
49
- export class UsageLedgerClient extends UsageSubscriptionClient {
49
+ export class UsageLedgerClient extends UsageAllowanceClient {
50
50
  constructor(component: Component) {
51
51
  super(component);
52
52
  }
53
53
  async record(ctx: RunCtx, opts: RecordUsageOptions): Promise<UsageReceipt> {
54
- const event = prepareUsageRecord(opts.event);
54
+ const event = validateUsageRecordInput(opts.event);
55
55
  const input = {
56
56
  scope: event.scope,
57
57
  binding: event.binding,