@fantastic.dev/better-stripe 0.52.0 → 0.53.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 (101) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +44 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +22 -0
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +44 -0
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +22 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +3 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +1 -0
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/products/catalogClient.d.ts +23 -0
  16. package/dist/client/products/catalogClient.d.ts.map +1 -1
  17. package/dist/client/products/catalogClient.js +32 -0
  18. package/dist/client/products/catalogClient.js.map +1 -1
  19. package/dist/client/products/fixedPrice.d.ts +4 -0
  20. package/dist/client/products/fixedPrice.d.ts.map +1 -0
  21. package/dist/client/products/fixedPrice.js +10 -0
  22. package/dist/client/products/fixedPrice.js.map +1 -0
  23. package/dist/client/products/products.d.ts.map +1 -1
  24. package/dist/client/products/products.js +3 -0
  25. package/dist/client/products/products.js.map +1 -1
  26. package/dist/client/usage/catalog.d.ts +7 -0
  27. package/dist/client/usage/catalog.d.ts.map +1 -0
  28. package/dist/client/usage/catalog.js +55 -0
  29. package/dist/client/usage/catalog.js.map +1 -0
  30. package/dist/client/usage/catalogLifecycle.d.ts +25 -0
  31. package/dist/client/usage/catalogLifecycle.d.ts.map +1 -0
  32. package/dist/client/usage/catalogLifecycle.js +64 -0
  33. package/dist/client/usage/catalogLifecycle.js.map +1 -0
  34. package/dist/client/usage/catalogMath.d.ts +3 -0
  35. package/dist/client/usage/catalogMath.d.ts.map +1 -0
  36. package/dist/client/usage/catalogMath.js +21 -0
  37. package/dist/client/usage/catalogMath.js.map +1 -0
  38. package/dist/client/usage/catalogPrices.d.ts +5 -0
  39. package/dist/client/usage/catalogPrices.d.ts.map +1 -0
  40. package/dist/client/usage/catalogPrices.js +178 -0
  41. package/dist/client/usage/catalogPrices.js.map +1 -0
  42. package/dist/client/usage/catalogRead.d.ts +25 -0
  43. package/dist/client/usage/catalogRead.d.ts.map +1 -0
  44. package/dist/client/usage/catalogRead.js +71 -0
  45. package/dist/client/usage/catalogRead.js.map +1 -0
  46. package/dist/client/usage/catalogTypes.d.ts +97 -0
  47. package/dist/client/usage/catalogTypes.d.ts.map +1 -0
  48. package/dist/client/usage/catalogTypes.js +106 -0
  49. package/dist/client/usage/catalogTypes.js.map +1 -0
  50. package/dist/client/webhooks/processors.d.ts.map +1 -1
  51. package/dist/client/webhooks/processors.js +3 -0
  52. package/dist/client/webhooks/processors.js.map +1 -1
  53. package/dist/component/_generated/api.d.ts +4 -0
  54. package/dist/component/_generated/api.d.ts.map +1 -1
  55. package/dist/component/_generated/api.js.map +1 -1
  56. package/dist/component/_generated/component.d.ts +62 -0
  57. package/dist/component/_generated/component.d.ts.map +1 -1
  58. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  59. package/dist/component/earnings/triggers.d.ts +46 -0
  60. package/dist/component/earnings/triggers.d.ts.map +1 -1
  61. package/dist/component/payoutRelease/queries.d.ts +2 -2
  62. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  63. package/dist/component/schema.d.ts +22 -0
  64. package/dist/component/schema.js +2 -0
  65. package/dist/component/schema.js.map +1 -1
  66. package/dist/component/usageCatalog/mutations.d.ts +25 -0
  67. package/dist/component/usageCatalog/mutations.d.ts.map +1 -0
  68. package/dist/component/usageCatalog/mutations.js +75 -0
  69. package/dist/component/usageCatalog/mutations.js.map +1 -0
  70. package/dist/component/usageCatalog/queries.d.ts +33 -0
  71. package/dist/component/usageCatalog/queries.d.ts.map +1 -0
  72. package/dist/component/usageCatalog/queries.js +26 -0
  73. package/dist/component/usageCatalog/queries.js.map +1 -0
  74. package/dist/component/usageCatalog/schema.d.ts +57 -0
  75. package/dist/component/usageCatalog/schema.d.ts.map +1 -0
  76. package/dist/component/usageCatalog/schema.js +22 -0
  77. package/dist/component/usageCatalog/schema.js.map +1 -0
  78. package/docs/README.md +3 -1
  79. package/docs/metering-setup.md +2 -0
  80. package/docs/usage-catalog.md +106 -0
  81. package/package.json +3 -2
  82. package/src/client/index.ts +7 -0
  83. package/src/client/products/catalogClient.ts +77 -0
  84. package/src/client/products/fixedPrice.test.ts +57 -0
  85. package/src/client/products/fixedPrice.ts +13 -0
  86. package/src/client/products/products.ts +2 -0
  87. package/src/client/usage/catalog.test.ts +464 -0
  88. package/src/client/usage/catalog.ts +117 -0
  89. package/src/client/usage/catalogLifecycle.ts +128 -0
  90. package/src/client/usage/catalogMath.test.ts +13 -0
  91. package/src/client/usage/catalogMath.ts +22 -0
  92. package/src/client/usage/catalogPrices.ts +251 -0
  93. package/src/client/usage/catalogRead.ts +98 -0
  94. package/src/client/usage/catalogTypes.ts +170 -0
  95. package/src/client/webhooks/processors.ts +2 -0
  96. package/src/component/_generated/api.ts +4 -0
  97. package/src/component/_generated/component.ts +78 -0
  98. package/src/component/schema.ts +2 -0
  99. package/src/component/usageCatalog/mutations.ts +79 -0
  100. package/src/component/usageCatalog/queries.ts +32 -0
  101. package/src/component/usageCatalog/schema.ts +21 -0
@@ -0,0 +1,106 @@
1
+ # Provision the native usage catalog
2
+
3
+ BetterStripe uses Stripe Billing Meters and recurring metered Prices. No
4
+ Metronome account is required. Follow [sandbox setup](metering-setup.md) first.
5
+ These methods run in authenticated host actions. Resolve the account, test/live
6
+ mode, plan and product on the server, and authorize the caller before provisioning.
7
+
8
+ ```ts
9
+ import { defineUsagePlan } from "@fantastic.dev/better-stripe/usage";
10
+
11
+ const plan = defineUsagePlan({
12
+ key: "api-calls",
13
+ version: "v1",
14
+ model: "pay_as_you_go",
15
+ unit: { name: "call", precision: 0 },
16
+ rate: { currency: "usd", unitAmountDecimal: "2" },
17
+ });
18
+ const scope = { stripeAccountId: verifiedPlatformAccountId, livemode: false };
19
+ const meter = await stripe.ensureUsageMeter(ctx, {
20
+ scope,
21
+ plan,
22
+ eventName: "api_calls_v1",
23
+ displayName: "API calls v1",
24
+ });
25
+ const price = await stripe.ensureUsagePrice(ctx, {
26
+ scope,
27
+ plan,
28
+ meterId: meter.id,
29
+ stripeProductId: verifiedProductId,
30
+ lookupKey: "api_calls_v1_usd",
31
+ });
32
+ // price is a Convex-safe UsagePriceBinding with exact string amounts.
33
+ ```
34
+
35
+ Use `model: "included_overage"`, `includedQuantity: "1000"` and
36
+ `reset: "billing_period"` for monthly included units with overages. Stripe receives
37
+ a graduated free first tier and an infinite paid tier. Use `model: "prepaid"` and
38
+ `insufficientBalance: "reject"` for the prepaid catalog. Its recurring price charges
39
+ the configured rate, and payment-backed Billing Credit Grants offset eligible
40
+ charges. Provisioning this price does not fund credits or enforce a balance.
41
+ See the [implementation status](metered-usage.md) before enabling consumption.
42
+
43
+ Rates are decimal minor currency units per whole billable unit. With precision 2,
44
+ a rate of `"2"` becomes `"0.02"` per scaled provider unit. The adapter rejects more
45
+ than 12 provider decimal places rather than rounding. Included tier boundaries
46
+ must be exact positive safe integers after scaling. Monthly intervals, sum
47
+ aggregation, `stripe_customer_id` and `value` mappings are supported. Other
48
+ intervals, transformations and provider terms require an explicit adapter change.
49
+
50
+ The configured Stripe key must own `scope.stripeAccountId`. The adapter verifies
51
+ that account and the key's mode before writes. Connected-account headers are not
52
+ supported by these APIs. Restricted keys that cannot perform this verification
53
+ return `provider_unavailable`. A mismatch returns `unsupported_scope`.
54
+
55
+ ## Immutable identities and recovery
56
+
57
+ A meter identity is scoped by account, mode, plan key and version. A price identity
58
+ uses the same account/mode plus its lookup key. Plan terms, event name, mappings,
59
+ product, price currency and rates cannot change under those identities. Use a new
60
+ version, event name and lookup key for changed terms. A provider resource cannot
61
+ be adopted into a second managed identity.
62
+
63
+ The component persists a creation intent before calling Stripe and uses a stable
64
+ idempotency key. Retries verify provider terms and repair a failed mirror write.
65
+ Pinned resources are retrieved by ID and never recreated when retrieval fails.
66
+ Unpinned meter discovery is bounded to 1,000 resources. Incomplete discovery,
67
+ ambiguous matches and conflicting terms stop provisioning.
68
+
69
+ Automatic creation stops 23 hours after the first intent. Stripe's idempotency
70
+ retention is finite. An absent result after that point returns
71
+ `unknown_create_outcome`; investigate the provider account and adopt the verified
72
+ existing meter rather than generating another event identity. Found matching
73
+ resources can still repair a mirror after this window. Do not delete intent rows
74
+ or change keys to retry an uncertain write.
75
+
76
+ ## Lifecycle and reads
77
+
78
+ `adoptUsageMeter` accepts an exact provider meter ID plus the same configuration
79
+ as `ensureUsageMeter`. `getUsageMeterFromStripe` retrieves one ID.
80
+ `listStripeUsageMeters` accepts a page limit of 1–100 and optional cursor, and
81
+ returns `data`, `hasMore` and `cursor`. These provider methods require the same
82
+ verified scope. `deactivateUsageMeter` and `reactivateUsageMeter` operate only on
83
+ managed IDs and refresh their local observation.
84
+
85
+ Deactivation stops new usage ingestion for that meter. It does not migrate or
86
+ cancel existing subscriptions, settle prior usage or change immutable prices.
87
+ Review active subscriptions and queued delivery before deactivation. Explicitly
88
+ create and bind a new version when changing billing terms.
89
+
90
+ `getUsagePrice(ctx, { scope, lookupKey })` is a local query-compatible reader.
91
+ Its `available` result contains `observedAt` and a discriminated
92
+ `pricingMode: "metered"` binding, exact string amounts and explicit tiers. Missing,
93
+ pending and invalid observations return typed `unavailable` states. Reauthorize
94
+ every read. Cached observations do not prove fresh provider state or invoicing.
95
+
96
+ The legacy fixed-price mirror and its readers only represent fixed integer prices.
97
+ Webhook and bulk sync omit metered, tiered, transformed and decimal-only prices
98
+ instead of converting a null amount into zero. Use the scoped usage reader for
99
+ managed metered prices. Historical mirrors written by earlier package versions
100
+ are not automatically migrated; audit those records before relying on old data.
101
+ Existing fixed-price creation, adoption and readers retain their contracts.
102
+
103
+ Authoritative references: [Stripe meters](https://docs.stripe.com/api/billing/meter),
104
+ [usage-based prices](https://docs.stripe.com/billing/subscriptions/usage-based/implementation-guide),
105
+ [idempotency retention](https://docs.stripe.com/api/idempotent_requests), and
106
+ [Billing Credit Grant eligibility](https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.52.0",
3
+ "version": "0.53.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -101,7 +101,8 @@
101
101
  "docs/configuration.md",
102
102
  "docs/architecture.md",
103
103
  "docs/development.md",
104
- "docs/usage-ledger.md"
104
+ "docs/usage-ledger.md",
105
+ "docs/usage-catalog.md"
105
106
  ],
106
107
  "scripts": {
107
108
  "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
@@ -1,3 +1,10 @@
1
+ export { UsageCatalogError } from "./usage/catalogTypes.js";
2
+ export type {
3
+ UsageCatalogScope,
4
+ UsageMeterOptions,
5
+ UsagePriceOptions,
6
+ } from "./usage/catalogTypes.js";
7
+ export type { UsagePriceBinding } from "./usage/catalogRead.js";
1
8
  import * as setupIntentRead from "./billing/setup-intent-read.js";
2
9
  import { UsageLedgerClient } from "./usage/client.js";
3
10
  export type { RecordUsageOptions } from "./usage/client.js";
@@ -1,3 +1,7 @@
1
+ import { UsageCatalogError } from "../usage/catalogTypes.js";
2
+ import * as usageCatalog from "../usage/catalog.js";
3
+ import * as usageLifecycle from "../usage/catalogLifecycle.js";
4
+ import { getUsagePriceBinding } from "../usage/catalogRead.js";
1
5
  import type Stripe from "stripe";
2
6
  import { BillingPortalClient } from "../core/billingPortalClient.js";
3
7
  import type { RunCtx } from "../helpers.js";
@@ -9,6 +13,79 @@ import * as catalog from "./catalog.js";
9
13
  /** Catalog APIs inherited by BetterStripe. Host authorization remains required. */
10
14
  export abstract class CatalogClient extends BillingPortalClient {
11
15
  abstract get statementDescriptorSuffix(): string | undefined;
16
+ ensureUsageMeter(ctx: RunCtx, opts: usageCatalog.UsageMeterOptions) {
17
+ return usageCatalog.ensureUsageMeter(
18
+ this.stripe(),
19
+ this.component,
20
+ ctx,
21
+ opts,
22
+ );
23
+ }
24
+ async ensureUsagePrice(ctx: RunCtx, opts: usageCatalog.UsagePriceOptions) {
25
+ await usageCatalog.ensureUsagePrice(
26
+ this.stripe(),
27
+ this.component,
28
+ ctx,
29
+ opts,
30
+ );
31
+ const binding = await getUsagePriceBinding(this.component, ctx, opts);
32
+ if (binding.status !== "available")
33
+ throw new UsageCatalogError(
34
+ "provider_unavailable",
35
+ "Native usage price mirror is unavailable",
36
+ );
37
+ return binding.value;
38
+ }
39
+
40
+ adoptUsageMeter(
41
+ ctx: RunCtx,
42
+ opts: usageCatalog.UsageMeterOptions & { meterId: string },
43
+ ) {
44
+ return usageLifecycle.adoptUsageMeter(
45
+ this.stripe(),
46
+ this.component,
47
+ ctx,
48
+ opts,
49
+ );
50
+ }
51
+ getUsageMeterFromStripe(
52
+ _ctx: RunCtx,
53
+ opts: Parameters<typeof usageLifecycle.getUsageMeterFromStripe>[1],
54
+ ) {
55
+ return usageLifecycle.getUsageMeterFromStripe(this.stripe(), opts);
56
+ }
57
+ listStripeUsageMeters(
58
+ _ctx: RunCtx,
59
+ opts: Parameters<typeof usageLifecycle.listStripeUsageMeters>[1],
60
+ ) {
61
+ return usageLifecycle.listStripeUsageMeters(this.stripe(), opts);
62
+ }
63
+ deactivateUsageMeter(
64
+ ctx: RunCtx,
65
+ opts: { scope: usageCatalog.UsageCatalogScope; meterId: string },
66
+ ) {
67
+ return usageLifecycle.setUsageMeterActive(
68
+ this.stripe(),
69
+ this.component,
70
+ ctx,
71
+ { ...opts, active: false },
72
+ );
73
+ }
74
+ reactivateUsageMeter(
75
+ ctx: RunCtx,
76
+ opts: { scope: usageCatalog.UsageCatalogScope; meterId: string },
77
+ ) {
78
+ return usageLifecycle.setUsageMeterActive(
79
+ this.stripe(),
80
+ this.component,
81
+ ctx,
82
+ { ...opts, active: true },
83
+ );
84
+ }
85
+ getUsagePrice(ctx: RunCtx, opts: Parameters<typeof getUsagePriceBinding>[2]) {
86
+ return getUsagePriceBinding(this.component, ctx, opts);
87
+ }
88
+
12
89
  async getStripePriceByLookupKey(
13
90
  _ctx: RunCtx,
14
91
  opts: { lookupKey: string },
@@ -0,0 +1,57 @@
1
+ import { expect, it, vi } from "vitest";
2
+ import type Stripe from "stripe";
3
+ import { syncAllProducts } from "./products.js";
4
+ import { processEvent } from "../webhooks/processors.js";
5
+ import type { Component, RunCtx } from "../helpers.js";
6
+ import type { WebhookContext } from "../webhooks/helpers.js";
7
+
8
+ it("does not project metered, tiered or decimal-only provider prices into fixed prices", async () => {
9
+ const runMutation = vi.fn();
10
+ const runQuery = vi.fn().mockResolvedValue({ _id: "product" });
11
+ const component = {
12
+ products: {
13
+ queries: {
14
+ getProductByStripeId: {
15
+ [Symbol.for("toReferencePath")]:
16
+ "betterStripe/products/queries/getProductByStripeId",
17
+ },
18
+ },
19
+ mutations: {
20
+ upsertPrice: {
21
+ [Symbol.for("toReferencePath")]:
22
+ "betterStripe/products/mutations/upsertPrice",
23
+ },
24
+ },
25
+ },
26
+ } as unknown as Component;
27
+ const ctx = { runMutation, runQuery } as unknown as RunCtx;
28
+ const prices = [
29
+ {
30
+ id: "price_metered",
31
+ unit_amount: 2,
32
+ recurring: { usage_type: "metered" },
33
+ },
34
+ { id: "price_tiered", unit_amount: null, billing_scheme: "tiered" },
35
+ { id: "price_decimal", unit_amount: null, unit_amount_decimal: "0.02" },
36
+ ].map((price) => ({ product: "prod_1", ...price }));
37
+ const stripe = {
38
+ products: { list: () => (async function* () {})() },
39
+ prices: {
40
+ list: () =>
41
+ (async function* () {
42
+ yield* prices;
43
+ })(),
44
+ },
45
+ } as unknown as Stripe;
46
+ for (const price of prices) {
47
+ await processEvent(
48
+ { stripe, component, ctx } as WebhookContext,
49
+ {
50
+ type: "price.created",
51
+ data: { object: price },
52
+ } as unknown as Stripe.Event,
53
+ );
54
+ }
55
+ await syncAllProducts(stripe, component, ctx);
56
+ expect(runMutation).not.toHaveBeenCalled();
57
+ });
@@ -0,0 +1,13 @@
1
+ import type Stripe from "stripe";
2
+
3
+ /** The legacy fixed-price mirror cannot express metered or tiered amounts. */
4
+ export function isFixedPrice(price: Stripe.Price): boolean {
5
+ return (
6
+ price.recurring?.usage_type !== "metered" &&
7
+ price.billing_scheme !== "tiered" &&
8
+ price.transform_quantity == null &&
9
+ typeof price.unit_amount === "number" &&
10
+ Number.isSafeInteger(price.unit_amount) &&
11
+ price.unit_amount >= 0
12
+ );
13
+ }
@@ -1,3 +1,4 @@
1
+ import { isFixedPrice } from "./fixedPrice.js";
1
2
  import type Stripe from "stripe";
2
3
  import { idempotencyOptions } from "../core/idempotency.js";
3
4
 
@@ -289,6 +290,7 @@ export async function syncAllProducts(
289
290
  let pricesSynced = 0;
290
291
  const productCache = new Map<string, { _id: string } | null>();
291
292
  for await (const price of stripe.prices.list({ limit: 100 })) {
293
+ if (!isFixedPrice(price)) continue;
292
294
  try {
293
295
  const stripeProductId =
294
296
  typeof price.product === "string" ? price.product : "";