@fantastic.dev/better-stripe 0.66.0 → 0.67.1

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 (90) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +17 -20
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +126 -12
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +79 -22
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +158 -44
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +63 -6
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +1 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js.map +1 -1
  14. package/dist/client/recoveryWorkflow/provider.fixture.d.ts +21 -0
  15. package/dist/client/recoveryWorkflow/provider.fixture.d.ts.map +1 -0
  16. package/dist/client/recoveryWorkflow/provider.fixture.js +125 -0
  17. package/dist/client/recoveryWorkflow/provider.fixture.js.map +1 -0
  18. package/dist/client/settlement/authorization.d.ts.map +1 -1
  19. package/dist/client/settlement/authorization.fixture.d.ts +10 -0
  20. package/dist/client/settlement/authorization.fixture.d.ts.map +1 -1
  21. package/dist/client/settlement/authorization.js +1 -0
  22. package/dist/client/settlement/authorization.js.map +1 -1
  23. package/dist/client/settlement/execution.d.ts +2 -0
  24. package/dist/client/settlement/execution.d.ts.map +1 -1
  25. package/dist/client/settlement/execution.js +3 -0
  26. package/dist/client/settlement/execution.js.map +1 -1
  27. package/dist/client/settlement/settleSale.d.ts +2 -0
  28. package/dist/client/settlement/settleSale.d.ts.map +1 -1
  29. package/dist/client/settlement/settleSale.js +4 -0
  30. package/dist/client/settlement/settleSale.js.map +1 -1
  31. package/dist/client/usage/observationClient.d.ts +2 -2
  32. package/dist/client/usage/observationClient.d.ts.map +1 -1
  33. package/dist/component/_generated/component.d.ts +25 -0
  34. package/dist/component/_generated/component.d.ts.map +1 -1
  35. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  36. package/dist/component/balanceFunding/queries.d.ts +1 -1
  37. package/dist/component/earnings/triggers.d.ts +36 -6
  38. package/dist/component/earnings/triggers.d.ts.map +1 -1
  39. package/dist/component/payoutRelease/queries.d.ts +2 -2
  40. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  41. package/dist/component/recoveryWorkflow/helpers.d.ts +5 -0
  42. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -1
  43. package/dist/component/recoveryWorkflow/mutations.d.ts +5 -0
  44. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -1
  45. package/dist/component/recoveryWorkflow/mutations.js +2 -0
  46. package/dist/component/recoveryWorkflow/mutations.js.map +1 -1
  47. package/dist/component/recoveryWorkflow/queries.d.ts +10 -0
  48. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -1
  49. package/dist/component/recoveryWorkflow/schema.d.ts +114 -10
  50. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -1
  51. package/dist/component/schema.d.ts +63 -6
  52. package/dist/component/settlement/mutations.d.ts +10 -0
  53. package/dist/component/settlement/mutations.d.ts.map +1 -1
  54. package/dist/component/settlement/mutations.js +3 -0
  55. package/dist/component/settlement/mutations.js.map +1 -1
  56. package/dist/component/settlement/queries.d.ts +5 -0
  57. package/dist/component/settlement/queries.d.ts.map +1 -1
  58. package/dist/component/settlement/schema.d.ts +24 -1
  59. package/dist/component/settlement/schema.d.ts.map +1 -1
  60. package/dist/component/settlement/schema.js +5 -0
  61. package/dist/component/settlement/schema.js.map +1 -1
  62. package/dist/component/usage/allowance.fixtures.d.ts +79 -22
  63. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  64. package/dist/component/usageCredits/accounting.fixtures.d.ts +63 -6
  65. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  66. package/dist/shared/settlementPolicyContext.d.ts +10 -0
  67. package/dist/shared/settlementPolicyContext.d.ts.map +1 -0
  68. package/dist/shared/settlementPolicyContext.js +40 -0
  69. package/dist/shared/settlementPolicyContext.js.map +1 -0
  70. package/docs/README.md +2 -1
  71. package/docs/metered-usage.md +174 -356
  72. package/docs/metering-setup.md +175 -168
  73. package/docs/settlement.md +38 -0
  74. package/docs/usage-catalog.md +1 -1
  75. package/docs/usage-ledger.md +9 -8
  76. package/docs/usage-rollout.md +147 -0
  77. package/package.json +3 -2
  78. package/src/client/index.ts +1 -0
  79. package/src/client/recoveryWorkflow/provider.fixture.ts +143 -0
  80. package/src/client/recoveryWorkflow/provider.test.ts +83 -140
  81. package/src/client/settlement/authorization.ts +1 -0
  82. package/src/client/settlement/execution.ts +7 -0
  83. package/src/client/settlement/policy-context.test.ts +277 -0
  84. package/src/client/settlement/settleSale.ts +12 -0
  85. package/src/component/_generated/component.ts +25 -0
  86. package/src/component/recoveryWorkflow/mutations.ts +2 -0
  87. package/src/component/settlement/mutations.ts +6 -0
  88. package/src/component/settlement/schema.ts +7 -0
  89. package/src/component/tsconfig.json +5 -0
  90. package/src/shared/settlementPolicyContext.ts +62 -0
@@ -1,192 +1,199 @@
1
- # Set up native Stripe metering
2
-
3
- BetterStripe's default metering path uses your existing Stripe sandbox. You do not
4
- need a Metronome account or token. Stripe recommends Metronome for new usage-based
5
- integrations, but Billing Meters APIs remain available. This project is building
6
- native Stripe integration into the existing BetterStripe Convex component.
7
-
8
- Current status: shared configuration/quantity helpers and repository sandbox probes
9
- are implemented. Atomic recording and bounded local history are available through the
10
- [usage ledger](usage-ledger.md). [Durable provider delivery](usage-delivery.md),
11
- [scoped observations](usage-observations.md) and [managed metered subscriptions](usage-subscriptions.md)
12
- are available. Allowance/credit
13
- accounting and the three example UI flows are still under development. The probes
14
- below verify provider behavior directly; they are not public BetterStripe billing
15
- workflows. See [metered usage contracts and evidence](metered-usage.md).
16
-
17
- ## Prerequisites
18
-
19
- Use Node 20 or later and the repository's pinned pnpm version. Start with an
20
- existing Stripe sandbox and a secret key for that sandbox, plus a Convex development
21
- deployment for the example. Keep the sandbox separate from production resources.
22
- Use the existing [Accounts v2 setup](accounts-v2-preview.md) for your account mode;
23
- Connect GA and customer-only public preview have different enrollment/version
24
- requirements. The probes pin `2026-09-30.endive`, as the package does by default.
25
- They do not prove a non-Connect preview configuration.
1
+ # Set up native Stripe metered billing
26
2
 
27
- From the repository root:
28
-
29
- ```sh
30
- pnpm install --frozen-lockfile
31
- pnpm run build
32
- ```
33
-
34
- If the example is not linked to a development deployment, follow the repository's
35
- example setup first. Run Convex deployment commands from `example/`, and check its
36
- `.env.local` deployment selection before setting credentials. Do not use `--prod`
37
- for these steps. A Stripe sandbox key and a Convex deployment credential are
38
- different credentials; one cannot replace the other.
39
-
40
- ## Supply the existing Stripe sandbox key
3
+ Use your existing Stripe sandbox and a Convex development deployment. BetterStripe
4
+ supports all three billing models through native Stripe APIs; no Metronome account,
5
+ token or signup is required. Start with the [model recipes](metered-usage.md) and
6
+ [example walkthrough](usage-example.md). Existing applications should also read
7
+ [opt-in adoption and rollback](usage-rollout.md).
41
8
 
42
- The required variable is `STRIPE_SECRET_KEY`. Use a server-only value, never a
43
- `VITE_`/browser variable. A `sk_test_` key is accepted by the probes; live keys are
44
- rejected before requests. An access failure with a restricted key does not prove
45
- that a billing model is unsupported.
9
+ ## Prerequisites and account selection
46
10
 
47
- To configure the example deployment, use the Convex dashboard's environment-variable
48
- editor or pipe a secret from your secret manager into the CLI. For example, from
49
- `example/`, replacing the reference with your own 1Password item:
11
+ The package supports Node 20 or newer. Use Node 24 for the repository and example
12
+ toolchain, as CI does, and the pinned `pnpm@10.32.1`. Use the actual reviewed
13
+ package candidate; source acceptance does not by itself prove npm publication.
50
14
 
51
- ```sh
52
- op read 'op://YourVault/YourStripeSandbox/secret-key' |
53
- pnpm exec convex env set STRIPE_SECRET_KEY
54
- ```
15
+ The default pinned Stripe API is `2026-09-30.endive`. The configured key must own
16
+ the original issuer realm and test/live mode. Accounts v2 payer subscriptions use
17
+ the provider-owned mapped Customer for meter payloads. The example verified the
18
+ platform issuer, issuer-only customer billing and eligible connected recipients.
19
+ Billing under connected-account headers is unsupported. A separate non-Connect
20
+ customer-only preview account requires its own enrollment/version verification;
21
+ see [Accounts v2 setup](accounts-v2-preview.md). Do not work around a mismatch by
22
+ creating a second payer or switching realms.
55
23
 
56
- The value travels through stdin instead of shell history or a command argument.
57
- Do not run `convex env get` or `op read` by itself in a recorded session. If the
58
- variable is already configured correctly, leave it in place.
59
-
60
- For repository-local probes, create an ignored `.env.metering` file containing a
61
- secret reference, not a copied secret value:
62
-
63
- ```dotenv
64
- STRIPE_SECRET_KEY=op://YourVault/YourStripeSandbox/secret-key
65
- ```
66
-
67
- Use one authorized interactive terminal for subsequent `op` commands. On macOS,
68
- 1Password CLI authorization is per terminal/account and expires after ten minutes
69
- of inactivity or when the app locks. Do not use keepalives or plaintext caches.
70
- Developers using another secret manager can inject the same process environment
71
- without 1Password.
72
-
73
- ## Run the read-only access check
24
+ ## Run the repository example
74
25
 
75
26
  From the repository root:
76
27
 
77
28
  ```sh
78
- op run --env-file=.env.metering -- node scripts/metering-feasibility.mjs
29
+ pnpm install --frozen-lockfile
30
+ pnpm run build
31
+ cd example
32
+ pnpm exec convex dev --once
79
33
  ```
80
34
 
81
- Expected result: `status: 200` and `accessible: true`. Other verification flags
82
- remain `unverified`, because this command only reads the meter endpoint. It does
83
- not create customers, catalogs, events, invoices or charges. On 401/403, check the
84
- sandbox, key permissions and deployment selection before changing code.
85
-
86
- ## Run all three native-provider scenarios
35
+ If the project is not configured, select the intended existing development
36
+ project. Confirm its deployment selection in `example/.env.local`; inspect only
37
+ `CONVEX_DEPLOYMENT` and the public `VITE_CONVEX_URL`, not an entire secret file.
38
+ Keep every Convex command below in `example/`. These commands do not use `--prod`.
39
+ Before invoking them, remove ambient `CONVEX_DEPLOY_KEY`,
40
+ `CONVEX_DEPLOYMENT_TOKEN`, `CONVEX_SELF_HOSTED_URL` and
41
+ `CONVEX_SELF_HOSTED_ADMIN_KEY` overrides from this terminal. Confirm that
42
+ `example/.env.local` and `example/.env` do not define those overrides and that
43
+ any ambient `CONVEX_DEPLOYMENT` matches the selected `dev:` deployment.
44
+ Deployment keys can override the selection even when you omit `--prod`.
45
+ If initial deployment stops for a missing required environment value, configure
46
+ that value on the selected development deployment, then repeat the deploy.
47
+
48
+ The required server variable is `STRIPE_SECRET_KEY`. If the existing deployment
49
+ already has the correct sandbox key, reuse it. Otherwise use its Convex dashboard
50
+ environment editor, or pipe from a secret manager. For 1Password, replace this
51
+ reference with your own item. Create an ignored, untracked `../.env.stripe-sandbox`
52
+ containing only `STRIPE_SECRET_KEY=op://YourVault/YourStripeSandbox/secret-key`.
53
+ It stores a reference, never a copied secret. Run in one authorized interactive terminal:
87
54
 
88
55
  ```sh
89
- op run --env-file=.env.metering -- node scripts/metering-sandbox.mjs
56
+ op run --env-file=../.env.stripe-sandbox -- node --input-type=module -e '
57
+ import { spawnSync } from "node:child_process";
58
+ const key = process.env.STRIPE_SECRET_KEY;
59
+ if (!/^sk_test_[A-Za-z0-9]+$/.test(key ?? "")) {
60
+ console.error("A nonempty Stripe sandbox secret is required"); process.exit(1);
61
+ }
62
+ const result = spawnSync("pnpm", ["exec", "convex", "env", "set", "STRIPE_SECRET_KEY"], {
63
+ input: key, stdio: ["pipe", "ignore", "ignore"],
64
+ });
65
+ if (result.status !== 0) {
66
+ console.error("Sandbox environment update failed"); process.exit(1);
67
+ }
68
+ '
69
+ pnpm exec convex dev --once
70
+ pnpm dev
90
71
  ```
91
72
 
92
- This creates synthetic test resources. The same provider-owned Accounts v2 payer
93
- mapping is used for subscriptions and meter events; it does not create an
94
- independent v1 payer to work around identity mismatches. Each model has its own
95
- meter and subscription. The default prepaid fixture is promotional credit, which
96
- is not proof of a paid purchase.
97
-
98
- | Scenario | Fixture | Expected aggregate | Expected preview total |
99
- | ---------------------------- | ------------------------------------------------- | ------------------ | ---------------------- |
100
- | Pay-as-you-go | 15 units at 2 US cents/unit | 15 | 30 cents |
101
- | Included usage plus overages | First 10 units free, then 2 cents/unit | 15 | 10 cents |
102
- | Prepaid | 100-cent credit applied to the same 15-unit usage | 15 | 0 cents |
103
-
104
- The runner retries the identical event with the same idempotency identity. Bounded
105
- polling allows aggregation to catch up. An accepted event alone is insufficient;
106
- look for `aggregationVerified` and `invoiceIdentityVerified` for every model and
107
- compare preview totals with the table. A zero aggregate or preview while delivery
108
- is delayed is not a successful free-usage result. Do not rerun with new source IDs
109
- to repair delayed aggregation, because that can double bill.
110
-
111
- The optional purchase check is explicit:
73
+ The omitted CLI value reads stdin, keeping the secret out of command arguments
74
+ and shell history. Do not run `convex env get`, print all environment values, or
75
+ paste secrets into screenshots, source or browser storage. Never prefix the
76
+ secret with `VITE_`. Other example payment screens can use a public publishable
77
+ key; that key cannot replace the server key. 1Password CLI authorization on macOS
78
+ is per terminal/account and expires after ten idle minutes or app lock. Reuse
79
+ one terminal; do not use keepalives or plaintext caches. Other secret managers
80
+ can supply the same stdin/process environment without 1Password.
81
+
82
+ Use the local URL printed by Vite, then `/demo/metered-usage`. If this is a new,
83
+ empty development example, use `/admin/setup` to seed the required demo personas.
84
+ Existing seeded deployments need no reset or re-seed. Do not run destructive setup
85
+ or mutate another application's database to make this flow work.
86
+
87
+ The persona switcher is test-only, not production authentication. In an application,
88
+ authenticate callers and resolve/authorize original payer, product, price, activity
89
+ and recipient policy on the server. See [usage security](usage-security.md).
90
+
91
+ ## Verify each model
92
+
93
+ Choose one model, then Set up sandbox. Setup retains its original resource IDs
94
+ across retries. Defaults below are this example's USD 1 per whole-call fixture;
95
+ applications choose their own units, precision and policies.
96
+
97
+ | Model | Exercise | Expected result |
98
+ | ---------------------- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
99
+ | Pay as you go | Three five-call jobs, replay one, observe, close/resume period | Effective/native 15, original usage invoice USD 15; replay adds no work or usage |
100
+ | Included monthly usage | Ten included calls, then another five | 15 consumed, 10 included, 5 overage; original usage invoice USD 5 |
101
+ | Paid prepaid | Try work unpaid, buy/confirm ten units, consume twice, try more | Unpaid work held, verified grant 10, consumed 10, excess denied; original purchase USD 10, usage invoice USD 0 |
102
+
103
+ Follow [the complete walkthrough](usage-example.md) for correction, delivery,
104
+ original payment/fee/transfer proof and cleanup. Aggregation may lag; refresh an
105
+ original request rather than inventing another event ID. Close/resume waits for
106
+ complete local/native equality, zero reservations and resolved correction/purchase
107
+ intents before advancing only that fixture's test clock. Future renewal allowance
108
+ is `not_active_yet` until its period is active on the real server. Do not forge
109
+ future timestamps or show a fake zero balance.
110
+
111
+ Archive/resume cleanup only after original paid invoice, cash and settlement
112
+ verification. Cleanup rechecks fresh original financial evidence; unresolved
113
+ payments, refunds, disputes, reservations, unknown sends and credit liabilities
114
+ remain retained. Only owned test resources are stopped. Payers, clocks and all
115
+ financial history remain. Unspent paid credits require original-source recovery;
116
+ reset does not delete them. After successful archive, configure a new isolated run.
117
+
118
+ ## Install in your own Convex application
119
+
120
+ Install the reviewed published package, or your actual reviewed tarball, plus
121
+ `convex`. For a published release:
112
122
 
113
123
  ```sh
114
- op run --env-file=.env.metering -- node scripts/metering-sandbox.mjs --verify-test-payment
124
+ pnpm add @fantastic.dev/better-stripe convex
115
125
  ```
116
126
 
117
- It creates a sandbox PaymentIntent with Stripe's test card, verifies succeeded
118
- status, payer, currency and received amount, then grants paid credits. Pending or
119
- mismatched payments must not grant credits. It requests a refund during cleanup.
120
- No live payments are authorized by this guide. This is a provider feasibility
121
- probe, not the component's future production credit purchase API.
122
-
123
- On this API version PaymentIntent filtering uses `allowed_payment_method_types`.
124
- The older `payment_method_types` parameter is rejected. The runner uses the current
125
- parameter. See the source for the exact pinned request contract.
126
-
127
- ## Cleanup and evidence
128
-
129
- The runner expires its grant, requests a refund for a verified test purchase,
130
- cancels its subscriptions without invoicing/proration, archives its prices and
131
- products, and deactivates its meters. Payer records and provider history remain.
132
- Check every cleanup result. API acceptance does not mean an asynchronous refund
133
- has settled. A failed run can require manual cleanup; do not delete unresolved
134
- financial evidence or touch another application's resources.
135
-
136
- Save sanitized result JSON and current test/CI links in PR evidence. Exclude API
137
- keys, client secrets, personal emails and raw provider payloads. Record which model,
138
- account mode, API version and stage actually ran. These tests do not by themselves
139
- prove finalized invoices, seller settlement, affiliate economics, corrections,
140
- shared-meter subscription boundaries or strict real-time prepaid access limits.
141
-
142
- Run repository verification before handing off changes:
143
-
144
- ```sh
145
- pnpm exec vitest run scripts/metering-feasibility.test.mjs scripts/metering-sandbox.test.mjs
146
- pnpm exec vitest run src/client/usage/contracts.test.ts scripts/usage-contracts-packed.test.mjs
147
- pnpm run check:all
127
+ Candidate reviewers should install the produced `.tgz` instead of assuming a
128
+ source commit has been published. Keep the original component instance name
129
+ when upgrading:
130
+
131
+ ```ts
132
+ // convex/convex.config.ts
133
+ import { defineApp } from "convex/server";
134
+ import { v } from "convex/values";
135
+ import betterStripe from "@fantastic.dev/better-stripe/convex.config";
136
+ const app = defineApp({ env: { STRIPE_SECRET_KEY: v.string() } });
137
+ app.use(betterStripe, {
138
+ env: { STRIPE_SECRET_KEY: app.env.STRIPE_SECRET_KEY },
139
+ });
140
+ export default app;
148
141
  ```
149
142
 
150
- ## Instructions for AI agents
143
+ Generate bindings through the supported Convex CLI in your chosen development
144
+ application. Configure the SDK key as well as the component environment:
151
145
 
152
- Read this guide, the linked usage contracts and repository `AGENTS.md` first.
153
- Confirm the selected development deployment and the secret source without printing
154
- values. Use the existing sandbox and credentials. Do not create a Metronome account
155
- as a prerequisite or provision an alternative customer identity to hide a mismatch.
146
+ ```ts
147
+ // convex/stripe.ts
148
+ import { BetterStripe } from "@fantastic.dev/better-stripe";
149
+ import { components } from "./_generated/api";
156
150
 
157
- Keep source-event IDs stable and distinguish transport acceptance, aggregation,
158
- invoice previews and paid invoices. Configuration validation does not authorize a
159
- payer or enable billing. Hosts authorize tenants and billable activity. Component
160
- mutations and durable workers must own accounting and delivery once implemented.
161
-
162
- When a check fails, record its stage and sanitized classification. Fix request or
163
- fixture errors before retrying, keep financial operation identities stable, and
164
- report unverified behavior explicitly. Check the source and current primary docs
165
- when provider parameter names change. Do not weaken repository gates or replace
166
- provider proof with mocked output.
167
-
168
- ## Optional Metronome evaluation
169
-
170
- Metronome is a separate service with its own signup, token and Stripe connection.
171
- Its signup asks for work email, name, company, country and employee range. Those
172
- are Metronome onboarding fields, not native Stripe metering requirements.
173
-
174
- If a host independently chooses Metronome, use its sandbox token and connect the
175
- intended Stripe test environment. Verify identity and invoice provenance against
176
- BetterStripe before claiming support. This repository currently has no Metronome
177
- adapter or verified Metronome sandbox setup. Native Stripe users can ignore this
178
- optional path.
179
-
180
- Primary references:
181
-
182
- - [Stripe usage recording](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage)
183
- - [Accounts v2 customer interoperability](https://docs.stripe.com/accounts-v2/use-accounts-as-customers)
184
- - [Stripe meter event API](https://docs.stripe.com/api/billing/meter-event/create)
185
- - [Stripe billing credits](https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits)
186
- - [Metronome quickstart](https://docs.metronome.com/guides/get-started/api-quickstart)
187
-
188
- Use the [native catalog guide](usage-catalog.md) to provision versioned meters and prices through BetterStripe.
189
-
190
- Use the [usage observation guide](usage-observations.md) for bounded local reads, native aggregate refreshes and honest invoice/credit availability.
151
+ export const stripe = new BetterStripe(components.betterStripe, {
152
+ STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
153
+ });
154
+ ```
191
155
 
192
- For managed package enrollment, mixed fixed/metered items, Checkout, period-end cancellation and test-clock invoice verification, follow [usage subscriptions](usage-subscriptions.md).
156
+ The catalog's meter/price provisioning uses this server SDK key. Keep it in the
157
+ same original sandbox realm as the component's key. Do not hand edit generated APIs. The component installs its nested
158
+ Workflow/Workpool runtime; do not add a second sibling worker. Start with one
159
+ original managed binding and the [per-model recipes](metered-usage.md), then wire
160
+ [internal delivery/callbacks](usage-delivery.md), [scoped observations](usage-observations.md)
161
+ and [React views](usage-react.md). Configuration-only validation does not authorize
162
+ usage or enable a paid credit grant.
163
+
164
+ ## Troubleshooting and AI-agent runbook
165
+
166
+ | Symptom | Next action |
167
+ | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
168
+ | 401/403 or `provider_unavailable` | Verify the selected development project, sandbox/key permissions and pinned API access. Do not print the key or assume the model is unsupported. |
169
+ | Realm or mapped-customer mismatch | Resolve original native issuer/payer/Customer provenance. Keep original IDs; do not provision an alternative payer. |
170
+ | Accepted event, stale/zero summary | Keep transport acceptance separate from aggregation. Refresh complete original period evidence; missing or lagging data is not free usage. |
171
+ | Unknown provider outcome | Retain the original source/operation IDs and inspect scoped delivery/history. Resume only a supported verified recovery path; never blind resend or move work to a new scope. |
172
+ | Prepaid balance held | Reconcile original payment, grant, native transactions and invoice applications; resolve refunds/disputes or pending finalization. Never grant locally because a UI says paid. |
173
+ | Paid invoice but no transfer | Inspect original cash, actual processing fee and recipient eligibility. A paid invoice does not establish settlement. |
174
+ | Cleanup refuses reset | Resolve retained usage, reservations, purchase/correction intents and original financial liabilities. Do not delete rows, clocks or payer evidence. |
175
+
176
+ AI agents should read repository `AGENTS.md`, this guide, the model recipes and
177
+ verification limits first. Confirm only non-secret development selection and the
178
+ secret source. Use existing sandbox credentials, stable business IDs and normal
179
+ codegen. Reuse the server's authorization boundary and package controllers rather
180
+ than building another ledger in the example. Report the exact failed stage and
181
+ sanitized classification. Preserve unknown outcomes and original timestamps.
182
+
183
+ From the repository root, run the checks and evidence auditor listed in
184
+ [verification](usage-verification.md), including `pnpm run check:all`. Retain
185
+ sanitized proof and current CI links directly in the PR. The release handoff does
186
+ not authorize publication, production migration or live billing.
187
+
188
+ Repository-only feasibility probes remain available as
189
+ `scripts/metering-feasibility.mjs` and `scripts/metering-sandbox.mjs`. Inject a test
190
+ key with a secret manager, for example `op run --env-file=.env.metering -- node
191
+ scripts/metering-feasibility.mjs`, where the ignored file contains an `op://`
192
+ reference rather than a copied secret. The default sandbox probe's promotional
193
+ credit is not paid-prepaid proof; its explicit `--verify-test-payment` probe has
194
+ separate refund/cleanup results. Prefer the actual package example and retained
195
+ paid-source evidence for integration acceptance.
196
+
197
+ Primary provider contracts: [meter event identity/windows](https://docs.stripe.com/api/billing/meter-event/create),
198
+ [Accounts v2 customer mapping](https://docs.stripe.com/accounts-v2/use-accounts-as-customers),
199
+ and [native billing credits](https://docs.stripe.com/billing/subscriptions/usage-based/billing-credits).
@@ -1045,3 +1045,41 @@ format; never clear unresolved financial claims to bypass validation.
1045
1045
  ## Native metered and prepaid sales
1046
1046
 
1047
1047
  Use the [usage settlement guide](usage-settlement.md) for original metered-invoice provenance and issuer-service paid-credit purchases. The usage facade reuses the existing allocation, transfer and recovery ledgers and keeps usage consumption separate from cash settlement.
1048
+
1049
+ ## Immutable host policy context
1050
+
1051
+ `settleSale` accepts optional `allocation.policyContext`:
1052
+
1053
+ ```ts
1054
+ const policyContext = {
1055
+ namespace: "my-app.sale-policy",
1056
+ version: 1 as const,
1057
+ fields: { originalSale: saleId, planVersion: verifiedPlanVersion },
1058
+ };
1059
+ ```
1060
+
1061
+ This nonsecret envelope is stored on the first component allocation and returned
1062
+ by allocation reads and settlement results. It is opaque provenance, never SDK
1063
+ permission or browser-supplied authority. The host must validate its original sale,
1064
+ current roles, recipients and exact economics in `authorize` before money writes.
1065
+ Namespace is 1–80 characters; at most 32 string fields have 1–64-character keys and
1066
+ values of at most 512 characters. Keys also follow Convex object-field rules:
1067
+ non-control ASCII, without a leading `$`. Canonical JSON is limited to 8 KiB UTF-8. Reordered
1068
+ map keys replay identically. Changed context, including absent versus present,
1069
+ rejects without replacing the saved allocation. Existing context-free callers
1070
+ remain supported; a legacy allocation cannot acquire context on retry.
1071
+
1072
+ Resolve the current paid-tier policy only after verified positive cash is ready,
1073
+ at the first reservation for that sale. Checkout creation, a trial or a zero invoice
1074
+ does not freeze a future cash fee. On retry, authorize the original saved context
1075
+ and immutable allocation rather than interpreting today's policy as historical
1076
+ terms. This does not define recurring affiliate terms or supply a host money ledger.
1077
+
1078
+ The initial `reserve` callback receives the validated proposal before it is saved.
1079
+ Resume admission receives the saved allocation; every new `transfer` callback
1080
+ receives its actual saved context and effective leg, including legitimate affiliate
1081
+ release reductions. Snapshots are detached, including nested context fields.
1082
+ Recovery keeps its earlier group admission and runtime transfer-only callback;
1083
+ operation/allocation context mismatch prevents a new transfer POST. No new recovery
1084
+ admission callback or distributed atomicity is promised. Prior successful transfers
1085
+ and reconciliation are retained when later authorization rejects.
@@ -38,7 +38,7 @@ a graduated free first tier and an infinite paid tier. Use `model: "prepaid"` an
38
38
  `insufficientBalance: "reject"` for the prepaid catalog. Its recurring price charges
39
39
  the configured rate, and payment-backed Billing Credit Grants offset eligible
40
40
  charges. Provisioning this price does not fund credits or enforce a balance.
41
- See the [implementation status](metered-usage.md) before enabling consumption.
41
+ Use the [model recipes](metered-usage.md) and [opt-in rollout](usage-rollout.md) before enabling consumption.
42
42
 
43
43
  Rates are decimal minor currency units per whole billable unit. With precision 2,
44
44
  a rate of `"2"` becomes `"0.02"` per scaled provider unit. The adapter rejects more
@@ -49,13 +49,13 @@ Replays do not consume quota. Export and reconcile bounded pages before planning
49
49
  future archival; this implementation has no financial-history deletion API.
50
50
  Do not clear the tables to reset a quota or repair unresolved usage.
51
51
 
52
- Prepaid recording requires a matching component-owned reservation and atomically
53
- commits it with the event. The scope, source ID, exact quantity and immutable plan
54
- must match. No arbitrary reservation-creation API exists. Payment-backed grant and
55
- reservation provisioning is implemented in the credit-accounting ticket; until
56
- then the facade rejects prepaid events without such a reservation. Included-usage
57
- snapshots use the same ledger; strict allowance reservations can use the same
58
- atomic commit seam when allowance accounting is enabled.
52
+ Prepaid recording requires a matching component-owned payment-backed reservation
53
+ and atomically commits it with the event. The scope, source ID, exact quantity and
54
+ immutable plan must match. Use `usage.purchaseCredits` / `observeCreditPurchase`
55
+ for verified funding and `reserveCredits` before work. See [paid credits](usage-credits.md).
56
+ For configured pay-as-you-go or included scopes, use `reserveAllowance`; recording
57
+ atomically commits that same reservation. See [limits](usage-limits.md). Unknown
58
+ provider outcomes never release committed capacity automatically.
59
59
 
60
60
  `get(ctx, {scope, eventId})` returns null for a foreign scope or absent event.
61
61
  `read(ctx, {scope, page: {period: {start, end}, limit, cursor}})` returns `events`,
@@ -64,6 +64,7 @@ The acceptance receipt always records initial queued intent; the view's separate
64
64
  `delivery` field reports current outbox state. Reauthorize every page. A complete
65
65
  local page history does not establish complete provider aggregation or invoices.
66
66
 
67
- This layer implements acceptance/history, not provider delivery or credit funding.
67
+ Recording itself performs no provider delivery or credit funding; the package supplies
68
+ those separate workflows.
68
69
  See [native setup](metering-setup.md), [shared contracts](metered-usage.md) and
69
70
  [Stripe's native event windows](https://docs.stripe.com/api/billing/meter-event/create).
@@ -0,0 +1,147 @@
1
+ # Adopt, roll out and roll back usage billing
2
+
3
+ Metered billing is opt-in. Installing a package does not convert existing fixed
4
+ subscriptions, import historical usage, mint credits or authorize new billing.
5
+ Keep the original component instance name and all existing financial records.
6
+ Start with [setup](metering-setup.md) and the [model recipes](metered-usage.md).
7
+ This guide describes a controlled host cutover, not an automatic migration.
8
+
9
+ ## Inventory original ownership and obligations
10
+
11
+ Record the original issuer realm, mode, Accounts v2 payer/mapped Customer,
12
+ subscription/item/price IDs, meter/event name, plan/version, currency, period,
13
+ source-event namespace and provider/API/worker versions. Keep a mapping from each
14
+ business activity to its original immutable binding. Inventory outstanding sends,
15
+ reservations, correction attempts, invoice adjustments, payments, grants, refunds,
16
+ disputes, transfer/recovery operations and affiliate policy.
17
+
18
+ Read bounded pages to completion; truncated or legacy-unknown coverage is not an
19
+ empty history. Compare local effective usage, accepted delivery, native aggregates
20
+ and original finalized invoices separately. Preserve all unknowns and original
21
+ occurrence times. Confirm host authentication and server-owned authorization
22
+ before exposing any new catalog, activity, billing reader or action.
23
+
24
+ ## Add usage to fixed-price billing
25
+
26
+ Choose whether the existing fixed subscription remains an intentional base fee
27
+ or is replaced at an authorized future boundary. A new usage-only enrollment can
28
+ use `fixedPriceIds: []`; a new mixed enrollment can include the chosen monthly
29
+ fixed price. Do not charge a duplicate fixed base accidentally while the original
30
+ subscription remains active. Existing fixed-price APIs and original invoices keep
31
+ their behavior and provenance.
32
+
33
+ Select a model, immutable unit/rate/version, authorized future start/period and
34
+ stable signup ID. Provision the native catalog and managed subscription only for
35
+ the intended new work. Observe its native accepting status and period, configure
36
+ allowance or verify a paid prepaid grant, then admit activity. A successful setup
37
+ screen or Checkout redirect is not proof of payment or entitlement.
38
+
39
+ ## Existing usage systems and catalog adoption
40
+
41
+ There is no general public importer for an arbitrary existing subscription,
42
+ provider event, historical invoice, payment or credit balance. `adoptUsageMeter`
43
+ verifies an exact native catalog resource; it does not adopt past financial
44
+ activity or release another enrollment's locks. Follow [catalog adoption](usage-catalog.md)
45
+ for its exact identity requirements. Preserve original prices and their immutable
46
+ terms for every previously accepted activity.
47
+
48
+ For a new managed enrollment, first stop the old writer at an explicit boundary,
49
+ drain/reconcile its original work and close its native billing obligations. Keep
50
+ the old subscription/item/price IDs in history. Retire a managed enrollment only
51
+ with its complete original final invoice proof. Native overlapping customer/meter
52
+ subscriptions block new enrollment; do not bypass that guard with a payer alias,
53
+ second component instance or changed event ID. Independent Dashboard/API writers
54
+ must also be controlled by the host.
55
+
56
+ An unbilled, provably unsent activity may be admitted only under its authorized
57
+ original identity, native binding and valid original period/time window. Do not
58
+ backfill already billed, delivered or ambiguous historical activity through
59
+ `record`. Older or unprovable history needs a separately reviewed import or native
60
+ adjustment procedure. Do not make it eligible by replacing occurrence time,
61
+ creating another source ID or reclassifying it as new work.
62
+
63
+ ## Change a billing model or price
64
+
65
+ Use a future billing boundary and a new immutable version/event name/price lookup
66
+ key for changed terms. Never rewrite the original plan, price, subscription
67
+ snapshot, quantity or payer of an accepted event. Keep old readers and workers
68
+ available until the old scope is fully reconciled and retired. The new model only
69
+ admits genuinely new business activity.
70
+
71
+ Included quantities reset in a separately verified active monthly period; old
72
+ consumption and reservations remain auditable. Native test-clock renewal ahead
73
+ of the real server is read-only, with `not_active_yet` allowance rather than an
74
+ invented reset. A hard cap is enforced by reservations, not an aggregate preview.
75
+
76
+ Paid prepaid grants remain attached to their original issuer, price, purchase and
77
+ terms. A new model, price or UI balance does not move or convert those credits.
78
+ Resolve unspent/consumed backing, refunds, disputes and affiliate recovery through
79
+ the original purchase contracts. Do not treat consumption as another sale, create
80
+ an offsetting fake grant, or pay a seller from credit redemption. See
81
+ [credits](usage-credits.md), [corrections](usage-corrections.md) and
82
+ [original-source settlement](usage-settlement.md).
83
+
84
+ ## Rollout and drain
85
+
86
+ 1. Exercise the three-model sandbox paths and the packed/native verification
87
+ matrix with the intended account configuration. Record unsupported modes.
88
+ 2. Keep new billing admissions off while validating authenticated adapters,
89
+ persisted business completion markers, internal delivery handles and callback
90
+ authorization. Shadow observations must not send a second copy of real usage.
91
+ 3. Enable a bounded opt-in cohort and record its original binding/version. Observe
92
+ queue state, native lag, exact quantities, credit backing and invoice outcomes.
93
+ 4. Before closing or replacing a scope, fence new work and new purchase/correction
94
+ intents. Drain queued work with its original IDs; reconcile every unknown or
95
+ pending provider effect instead of blindly resending it.
96
+ 5. Require complete native/local equality, resolved corrections and purchases,
97
+ zero outstanding reservations, and fresh original financial evidence. Then
98
+ complete cancellation/final invoicing and supported retirement/credit closure.
99
+ 6. Preserve payer, original resources, ledger, delivery/history, payments, grant
100
+ backing and recovery liabilities. Deactivate only owned resources whose
101
+ obligations are resolved. Cleanup is not deletion or debt forgiveness.
102
+
103
+ Bounded readers, retained-event and audit quotas deliberately stop rather than
104
+ silently truncate. Plan retention/export before hitting those bounds. No quota
105
+ reset, financial-history deletion or automated production backfill is provided.
106
+
107
+ ## Rollback
108
+
109
+ Disable new admissions to the affected cohort. Keep the original deployment
110
+ handlers, internal action handles, API/definition versions and component instance
111
+ available for existing workers and callbacks. Finish or explicitly hold original
112
+ operations; inspect their retained status before retrying. A credential outage
113
+ cannot turn an uncertain send into an unsent event.
114
+
115
+ Do not restore an old database snapshot over newer payments, grants, usage,
116
+ transfers or revision authority. Do not deploy a legacy-only writer that cannot
117
+ interpret retained operations. Preserve any separately activated payout revision
118
+ journal according to [its migration contract](payout-revision-migration.md).
119
+ Code rollback does not cancel invoices, restore credits, reverse transfers or
120
+ refund a customer. Use the original financial recovery APIs and verify outcomes.
121
+
122
+ After reconciliation, a new explicit enrollment/version can resume future work.
123
+ Do not replay the old cohort into another scope to repair the rollout.
124
+
125
+ ## Release handoff
126
+
127
+ Use the existing automated Release Please/changelog workflow. Preserve generated
128
+ release descriptions and standalone notes delimiters; put current review evidence
129
+ in comments. Follow [release policy](releasing.md) and
130
+ [component handoff](release-handoff.md). Do not hand edit a version or changelog to
131
+ claim publication. A workflow with publication skipped is not a published package.
132
+
133
+ Before handoff, build and pack the reviewed candidate, compile/load public root,
134
+ `/usage`, `/react` and `/testing` exports, and validate the `/convex.config` wiring
135
+ through the supported Convex bundler/codegen. The config's upstream runtime is not
136
+ a standalone Node ESM smoke-test target. Check that every linked Markdown guide
137
+ is in the actual tarball. Run the unchanged `pnpm run check:all` and current-head
138
+ CI, with independent acceptance and sanitized evidence directly in the PR.
139
+
140
+ The [verification matrix](usage-verification.md) contains native six-fixture proof,
141
+ actual invoice/fee/transfer economics, deterministic SDK failures, packed
142
+ consumers and explicit account/clock/throughput limits. The
143
+ [example walkthrough](usage-example.md) is the developer exercise. This handoff
144
+ covers reviewed source and a packed candidate. It does not authorize npm
145
+ publication, merging a release PR, production deployment/migration or live billing.
146
+
147
+ The [packed component handoff evidence](https://github.com/FantasticDevHQ/better-stripe/tree/main/docs/evidence/usage-handoff) records the extracted-candidate native bundler/codegen check and its reproduction command.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.66.0",
3
+ "version": "0.67.1",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -116,7 +116,8 @@
116
116
  "docs/usage-configuration.md",
117
117
  "docs/usage-example.md",
118
118
  "docs/payout-revision-migration.md",
119
- "docs/usage-verification.md"
119
+ "docs/usage-verification.md",
120
+ "docs/usage-rollout.md"
120
121
  ],
121
122
  "scripts": {
122
123
  "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
@@ -1,3 +1,4 @@
1
+ export type { SettlementPolicyContext } from "../shared/settlementPolicyContext.js";
1
2
  export { UsageSubscriptionError } from "./usage/subscriptionErrors.js";
2
3
  export { UsageCatalogError } from "./usage/catalogTypes.js";
3
4
  export type {