@fantastic.dev/better-stripe 0.50.2 → 0.51.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.
- package/CHANGELOG.md +26 -0
- package/README.md +39 -1748
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.js +12 -1
- package/dist/client/connect/payoutAdoptionTestHelpers.js.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.js +12 -1
- package/dist/client/connect/payoutExecutionTestHelpers.js.map +1 -1
- package/dist/client/usage/boundaries.d.ts +132 -0
- package/dist/client/usage/boundaries.d.ts.map +1 -0
- package/dist/client/usage/boundaries.js +43 -0
- package/dist/client/usage/boundaries.js.map +1 -0
- package/dist/client/usage/contracts.d.ts +59 -0
- package/dist/client/usage/contracts.d.ts.map +1 -0
- package/dist/client/usage/contracts.js +63 -0
- package/dist/client/usage/contracts.js.map +1 -0
- package/dist/client/usage/index.d.ts +7 -0
- package/dist/client/usage/index.d.ts.map +1 -0
- package/dist/client/usage/index.js +4 -0
- package/dist/client/usage/index.js.map +1 -0
- package/dist/client/usage/records.d.ts +50 -0
- package/dist/client/usage/records.d.ts.map +1 -0
- package/dist/client/usage/records.js +54 -0
- package/dist/client/usage/records.js.map +1 -0
- package/docs/README.md +58 -0
- package/docs/architecture.md +80 -0
- package/docs/client-api.md +586 -0
- package/docs/configuration.md +51 -0
- package/docs/development.md +114 -0
- package/docs/marketplace.md +165 -0
- package/docs/metered-usage.md +289 -37
- package/docs/metering-setup.md +183 -0
- package/docs/overview.md +140 -0
- package/docs/react-api.md +284 -0
- package/docs/releasing.md +19 -0
- package/docs/testing.md +52 -0
- package/docs/webhooks.md +259 -0
- package/package.json +17 -2
- package/src/client/connect/payoutAdoptionTestHelpers.ts +17 -1
- package/src/client/connect/payoutExecutionTestHelpers.ts +17 -1
- package/src/client/transferContinuation.test.ts +2 -6
- package/src/client/usage/boundaries.test.ts +136 -0
- package/src/client/usage/boundaries.ts +182 -0
- package/src/client/usage/contracts.test.ts +145 -0
- package/src/client/usage/contracts.ts +79 -0
- package/src/client/usage/index.ts +34 -0
- package/src/client/usage/records.ts +76 -0
- package/src/test.ts +17 -1
- package/src/vite-env.d.ts +5 -1
package/docs/webhooks.md
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
# Webhooks and triggers
|
|
2
|
+
|
|
3
|
+
## Webhook API
|
|
4
|
+
|
|
5
|
+
### registerRoutes
|
|
6
|
+
|
|
7
|
+
Register the webhook endpoint on your Convex HTTP router:
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
import { registerRoutes } from "@fantastic.dev/better-stripe";
|
|
11
|
+
|
|
12
|
+
registerRoutes(http, components.betterStripe, {
|
|
13
|
+
webhookPath: "/stripe/webhook", // Default path
|
|
14
|
+
stripeSecretKey: process.env.STRIPE_SECRET_KEY,
|
|
15
|
+
webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
|
|
16
|
+
webhookSecretV2: process.env.STRIPE_WEBHOOK_SECRET_V2, // For V2 thin events
|
|
17
|
+
webhooks: internal.stripe, // The { syncWebhook, asyncWebhook } pair from webhookHandlers()
|
|
18
|
+
events: { ... }, // Optional per-event handlers (advanced)
|
|
19
|
+
onEvent: (ctx, event) => { ... }, // Optional catch-all handler (advanced)
|
|
20
|
+
});
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### Webhook Setup
|
|
24
|
+
|
|
25
|
+
Stripe event destinations come in two flavors that cannot be mixed:
|
|
26
|
+
|
|
27
|
+
- **Snapshot** (`event_payload: 'snapshot'`) — V1 events include the full object in the payload. Used for payments, subscriptions, invoices, products, and payouts.
|
|
28
|
+
- **Thin** (`event_payload: 'thin'`) — V2 events include only the event type and object reference. The handler fetches the full object from the Stripe API. Used for Connect account lifecycle events.
|
|
29
|
+
|
|
30
|
+
You need **two** event destinations pointing to the same webhook URL, each with its own signing secret.
|
|
31
|
+
|
|
32
|
+
#### Programmatic setup
|
|
33
|
+
|
|
34
|
+
Use `setupEventDestination()` to create or update destinations:
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
// Create V1 snapshot destination
|
|
38
|
+
const v1 = await stripe.setupEventDestination(ctx, {
|
|
39
|
+
url: webhookUrl,
|
|
40
|
+
eventPayload: "snapshot",
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// Create V2 thin destination
|
|
44
|
+
const v2 = await stripe.setupEventDestination(ctx, {
|
|
45
|
+
url: webhookUrl,
|
|
46
|
+
eventPayload: "thin",
|
|
47
|
+
});
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The method is idempotent — it finds an existing destination matching the URL and payload type, updates its events, or creates a new one.
|
|
51
|
+
|
|
52
|
+
#### Admin UI setup
|
|
53
|
+
|
|
54
|
+
The example app includes an `/admin/setup` page that handles webhook creation, env var verification, demo data seeding, and Stripe data syncing — all from the browser.
|
|
55
|
+
|
|
56
|
+
#### Event constants
|
|
57
|
+
|
|
58
|
+
```typescript
|
|
59
|
+
import {
|
|
60
|
+
BETTER_STRIPE_WEBHOOK_EVENTS, // V1 snapshot events (20 events)
|
|
61
|
+
BETTER_STRIPE_V2_WEBHOOK_EVENTS, // V2 thin events (12 events)
|
|
62
|
+
ALL_BETTER_STRIPE_EVENTS, // Combined (32 events)
|
|
63
|
+
} from "@fantastic.dev/better-stripe";
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Event Processing
|
|
67
|
+
|
|
68
|
+
Records synced from Stripe objects without `userId` metadata are stored unattributed (`userId: ""`) and are not returned by user-scoped queries.
|
|
69
|
+
|
|
70
|
+
The webhook handler processes events through these steps:
|
|
71
|
+
|
|
72
|
+
1. Verify Stripe signature
|
|
73
|
+
2. Record the event in the `webhookEvents` ledger by `stripeEventId`. If the event was already seen and is `processing`, `processed`, or `ignored`, return 200 immediately. If the previous delivery `failed` (its writes rolled back), the ledger row is reset and the event is reprocessed on Stripe's retry.
|
|
74
|
+
3. Upsert the component-owned domain table. When `webhooks` is configured, the upsert runs through `syncWebhook` — an internal mutation that performs the upsert **and** the sync trigger in the same transaction.
|
|
75
|
+
4. On failure, mark the ledger row `failed` and return 500 so Stripe retries; otherwise mark it `processed`
|
|
76
|
+
5. Schedule the matching `after*` async hook via `ctx.scheduler` (separate action)
|
|
77
|
+
|
|
78
|
+
### Ledger-Based Deduplication
|
|
79
|
+
|
|
80
|
+
The component maintains a `webhookEvents` table that tracks every event by its Stripe event ID. This provides:
|
|
81
|
+
|
|
82
|
+
- **Replay protection** -- duplicate events are detected and skipped
|
|
83
|
+
- **Retry recovery** -- events whose processing failed (and rolled back) are reprocessed when Stripe retries, instead of deduplicating forever
|
|
84
|
+
- **Crash recovery** -- if a delivery dies mid-processing (timeout, restart), the `processing` row goes stale after 10 minutes and the event is reprocessed on Stripe's next retry instead of deduplicating forever
|
|
85
|
+
- **Failure tracking** -- failed events are marked with status and error message
|
|
86
|
+
- **Observability** -- all events (including unsupported types) are logged with `ignored` status
|
|
87
|
+
|
|
88
|
+
### Supported Events
|
|
89
|
+
|
|
90
|
+
**Accounts V2 (thin events -- component fetches latest state, requires V2 event destination):**
|
|
91
|
+
|
|
92
|
+
- `v2.core.account.created`, `.updated`
|
|
93
|
+
- `v2.core.account[identity].updated`
|
|
94
|
+
- `v2.core.account[requirements].updated`
|
|
95
|
+
- `v2.core.account[configuration.merchant].updated`, `.capability_status_updated`
|
|
96
|
+
- `v2.core.account[configuration.customer].updated`
|
|
97
|
+
- `v2.core.account[configuration.recipient].updated`
|
|
98
|
+
- `v2.core.account[defaults].updated`
|
|
99
|
+
- `v2.core.account_person.created`, `.updated`
|
|
100
|
+
- `v2.core.account_link.returned`
|
|
101
|
+
|
|
102
|
+
**Billing (snapshot events -- payload contains full state):**
|
|
103
|
+
|
|
104
|
+
- `checkout.session.completed`
|
|
105
|
+
- `customer.subscription.created`, `.updated`, `.deleted`, `.trial_will_end`
|
|
106
|
+
- `invoice.created`, `.finalized`, `.paid`, `.payment_failed`
|
|
107
|
+
- `payment_intent.succeeded`, `.payment_failed`, `.canceled`
|
|
108
|
+
- `payout.created`, `.updated`, `.paid`, `.failed`, `.canceled`
|
|
109
|
+
|
|
110
|
+
- `refund.created`, `.updated`, `.failed`
|
|
111
|
+
- `application_fee.refunded` -- keeps `feeCollectedAmount`/`feeRefundedAmount` accurate on the linked payment
|
|
112
|
+
- `charge.dispute.created`, `.updated`, `.closed`, `.funds_withdrawn`, `.funds_reinstated`
|
|
113
|
+
- `product.created`, `.updated`
|
|
114
|
+
- `price.created`, `.updated`
|
|
115
|
+
|
|
116
|
+
Note: Subscription and invoice events use v1 Billing API event names even when the billing entity is a V2 account referenced via `customer_account`.
|
|
117
|
+
|
|
118
|
+
Dedicated payout cancellations use the same signed V1 endpoint, payout record
|
|
119
|
+
and connected-account association as other payout events. Generic `onEvent`
|
|
120
|
+
and `events["payout.canceled"]` callbacks run after reconciliation. Cancellation
|
|
121
|
+
does not invoke the paid/completed convenience hook. Normal verified replay is
|
|
122
|
+
deduplicated by the existing event ledger.
|
|
123
|
+
|
|
124
|
+
When upgrading from 0.11.0 or earlier, add `payout.canceled` to the existing V1
|
|
125
|
+
endpoint's selected events. New endpoints created with the corrected package's
|
|
126
|
+
defaults include it. Updating the library alone does not edit an existing provider
|
|
127
|
+
endpoint or recover already missed events. Consumers must adopt a published
|
|
128
|
+
version containing this correction; a merged source fix is not a package release.
|
|
129
|
+
|
|
130
|
+
## Trigger API
|
|
131
|
+
|
|
132
|
+
The trigger system follows the BetterAuth pattern: define callbacks at client init time, export the `syncWebhook`/`asyncWebhook` pair via `webhookHandlers()`, and pass their function references to `registerRoutes` via `webhooks`.
|
|
133
|
+
|
|
134
|
+
### SyncTriggers
|
|
135
|
+
|
|
136
|
+
Sync triggers run in the same transaction as the component's database write. They must be DB-only and idempotent. Throwing from a sync trigger rolls back the entire transaction (including the component upsert), causing Stripe to retry the webhook.
|
|
137
|
+
|
|
138
|
+
```typescript
|
|
139
|
+
interface SyncTriggers {
|
|
140
|
+
account?: {
|
|
141
|
+
onCreate?: (ctx, doc) => Promise<void>;
|
|
142
|
+
onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
|
|
143
|
+
};
|
|
144
|
+
subscription?: {
|
|
145
|
+
onCreate?: (ctx, doc) => Promise<void>;
|
|
146
|
+
onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
|
|
147
|
+
onDelete?: (ctx, doc) => Promise<void>;
|
|
148
|
+
};
|
|
149
|
+
checkoutSession?: {
|
|
150
|
+
onCompleted?: (ctx, doc) => Promise<void>;
|
|
151
|
+
};
|
|
152
|
+
product?: {
|
|
153
|
+
onCreate?: (ctx, doc) => Promise<void>;
|
|
154
|
+
onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
|
|
155
|
+
};
|
|
156
|
+
price?: {
|
|
157
|
+
onCreate?: (ctx, doc) => Promise<void>;
|
|
158
|
+
onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
|
|
159
|
+
};
|
|
160
|
+
invoice?: {
|
|
161
|
+
onCreate?: (ctx, doc) => Promise<void>;
|
|
162
|
+
onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
|
|
163
|
+
};
|
|
164
|
+
payment?: {
|
|
165
|
+
onCreate?: (ctx, doc) => Promise<void>;
|
|
166
|
+
};
|
|
167
|
+
payout?: {
|
|
168
|
+
onCreate?: (ctx, doc) => Promise<void>;
|
|
169
|
+
onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
|
|
170
|
+
};
|
|
171
|
+
refund?: {
|
|
172
|
+
onCreate?: (ctx, doc) => Promise<void>;
|
|
173
|
+
onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
|
|
174
|
+
};
|
|
175
|
+
dispute?: {
|
|
176
|
+
onCreate?: (ctx, doc) => Promise<void>;
|
|
177
|
+
onUpdate?: (ctx, newDoc, oldDoc) => Promise<void>;
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
### AsyncHooks
|
|
183
|
+
|
|
184
|
+
Async hooks run after the component's database write commits, in a separate scheduled action. Use these for external API calls (email, Slack, analytics). Failures do not roll back the component write.
|
|
185
|
+
|
|
186
|
+
```typescript
|
|
187
|
+
interface AsyncHooks {
|
|
188
|
+
onAccountUpdated?: (ctx, account) => Promise<void>;
|
|
189
|
+
onCheckoutCompleted?: (ctx, session) => Promise<void>;
|
|
190
|
+
onSubscriptionUpdated?: (ctx, subscription) => Promise<void>;
|
|
191
|
+
onSubscriptionCanceled?: (ctx, subscription) => Promise<void>;
|
|
192
|
+
onTrialEnding?: (ctx, subscription) => Promise<void>;
|
|
193
|
+
onInvoicePaid?: (ctx, invoice) => Promise<void>;
|
|
194
|
+
onInvoicePaymentFailed?: (ctx, invoice) => Promise<void>;
|
|
195
|
+
onPaymentSucceeded?: (ctx, payment) => Promise<void>;
|
|
196
|
+
onPaymentFailed?: (ctx, payment) => Promise<void>;
|
|
197
|
+
onPayoutCompleted?: (ctx, payout) => Promise<void>;
|
|
198
|
+
onRefundCreated?: (ctx, refund) => Promise<void>;
|
|
199
|
+
onDisputeCreated?: (ctx, dispute) => Promise<void>;
|
|
200
|
+
onDisputeClosed?: (ctx, dispute) => Promise<void>;
|
|
201
|
+
}
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### webhookHandlers()
|
|
205
|
+
|
|
206
|
+
Returns the `{ syncWebhook, asyncWebhook }` pair that bridges your app callbacks into the webhook processing pipeline. Export them from a Convex module (e.g. `convex/stripe.ts`) so they get function references the webhook handler can call:
|
|
207
|
+
|
|
208
|
+
```typescript
|
|
209
|
+
export const { syncWebhook, asyncWebhook } = stripe.webhookHandlers();
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
Then pass the module to `registerRoutes` as `webhooks: internal.stripe`.
|
|
213
|
+
|
|
214
|
+
**How `syncWebhook` works.** It is a single internal mutation that routes by a `dispatcher` discriminator to perform the component table upsert **and** your configured sync trigger inside one transaction. It reads the existing doc (to decide `onCreate` vs `onUpdate` and supply `oldDoc`), runs the upsert, re-reads the doc, and invokes your trigger. If the trigger throws, the whole mutation — including the component write — rolls back, the webhook handler marks the ledger row `failed`, and returns 500 so Stripe retries. On retry, failed ledger rows are reset and the event is reprocessed.
|
|
215
|
+
|
|
216
|
+
**How `asyncWebhook` works.** It is a single internal action that routes by a `hook` discriminator. After the `syncWebhook` transaction commits and the ledger marks the event `processed`, the webhook handler schedules `asyncWebhook` via `ctx.scheduler` with the committed doc. Hook failures never roll back the component write.
|
|
217
|
+
|
|
218
|
+
Exactly one hook (at most) is scheduled per event:
|
|
219
|
+
|
|
220
|
+
| Stripe event | Scheduled hook |
|
|
221
|
+
| ------------------------------------------------- | --------------------------- |
|
|
222
|
+
| `v2.core.account*` (all account lifecycle events) | `afterAccountUpdated` |
|
|
223
|
+
| `checkout.session.completed` | `afterCheckoutCompleted` |
|
|
224
|
+
| `customer.subscription.created` / `.updated` | `afterSubscriptionUpdated` |
|
|
225
|
+
| `customer.subscription.deleted` | `afterSubscriptionCanceled` |
|
|
226
|
+
| `customer.subscription.trial_will_end` | `afterTrialEnding` |
|
|
227
|
+
| `invoice.paid` | `afterInvoicePaid` |
|
|
228
|
+
| `invoice.payment_failed` | `afterInvoicePaymentFailed` |
|
|
229
|
+
| `payment_intent.succeeded` | `afterPaymentSucceeded` |
|
|
230
|
+
| `payment_intent.payment_failed` | `afterPaymentFailed` |
|
|
231
|
+
| `payout.paid` | `afterPayoutCompleted` |
|
|
232
|
+
| `refund.created` | `afterRefundCreated` |
|
|
233
|
+
| `charge.dispute.created` | `afterDisputeCreated` |
|
|
234
|
+
| `charge.dispute.closed` | `afterDisputeClosed` |
|
|
235
|
+
|
|
236
|
+
All other processed events (e.g. `payment_intent.canceled`, `payout.failed`, `invoice.created`, `refund.updated`, `charge.dispute.funds_withdrawn`) update the component tables but schedule no hook.
|
|
237
|
+
|
|
238
|
+
> **Note:** async hooks should be idempotent. Duplicate delivery is possible in rare ledger-failure cases (e.g. the event is processed and the hook scheduled, but the ledger update fails and Stripe redelivers).
|
|
239
|
+
|
|
240
|
+
The raw callbacks you pass to `triggers` and `hooks` on the `BetterStripe` constructor are the source of truth for app behavior. The exported `syncWebhook`/`asyncWebhook` pair is the bridge that makes them callable from the Convex runtime — events whose triggers you did not configure simply run the upsert (no sync trigger) and schedule no hook.
|
|
241
|
+
|
|
242
|
+
### Dunning & smart retries
|
|
243
|
+
|
|
244
|
+
Failed recurring payments are recovered by **Stripe Smart Retries**, not by any retry loop in this library. The component never re-attempts a charge itself — it tracks the delinquency and fires hooks so your app can notify the customer. Retry _timing and count_ are owned entirely by Stripe.
|
|
245
|
+
|
|
246
|
+
**Required Dashboard settings** (Stripe controls the schedule; enable these once):
|
|
247
|
+
|
|
248
|
+
- **Subscriptions:** Dashboard → **Billing → Revenue recovery → Retries** — turn on **Smart Retries** (Stripe's recommended, ML-timed schedule). Also set what happens when retries are exhausted (leave `past_due`, mark `unpaid`, or cancel).
|
|
249
|
+
- **One-time invoices:** Dashboard → **Settings → Billing → Invoices** — configure retry behavior for invoices not tied to a subscription.
|
|
250
|
+
- Ensure the `invoice.payment_failed` and `customer.subscription.updated` events are delivered to your webhook endpoint.
|
|
251
|
+
|
|
252
|
+
**What the component surfaces:**
|
|
253
|
+
|
|
254
|
+
- The subscription row tracks Stripe's delinquency states — `past_due` (first failed charge) and `unpaid` (retries exhausted) — arriving via `customer.subscription.updated`, which fires **`onSubscriptionUpdated`**.
|
|
255
|
+
- Each `invoice.payment_failed` fires **`onInvoicePaymentFailed`** with the committed invoice. Under Smart Retries the invoice carries `nextPaymentAttempt` (ISO time of Stripe's next retry) and `attemptCount`, so a dunning email can tell the buyer exactly when Stripe will try again. Both clear once the invoice is paid or retries stop.
|
|
256
|
+
|
|
257
|
+
`onInvoicePaymentFailed` is the **invoice-level** (subscription-cycle) failure — distinct from `onPaymentFailed`, which fires on a one-time **PaymentIntent** failure (`payment_intent.payment_failed`) and receives a payment, not an invoice.
|
|
258
|
+
|
|
259
|
+
> **Limitation:** `nextPaymentAttempt` is captured from the `invoice.payment_failed` payload, which is correct for Smart Retries. If you instead use a **custom retry _automation_**, Stripe sets `next_payment_attempt` on `invoice.updated` (not `invoice.payment_failed`); the component does not currently process `invoice.updated`, so the retry timestamp may lag until the next handled invoice event.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fantastic.dev/better-stripe",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.51.0",
|
|
4
4
|
"description": "A Convex component for Stripe V2 Accounts API integration.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"stripe",
|
|
@@ -46,6 +46,10 @@
|
|
|
46
46
|
"./_generated/component.js": {
|
|
47
47
|
"types": "./dist/component/_generated/component.d.ts",
|
|
48
48
|
"default": "./dist/component/_generated/component.js"
|
|
49
|
+
},
|
|
50
|
+
"./usage": {
|
|
51
|
+
"types": "./dist/client/usage/index.d.ts",
|
|
52
|
+
"default": "./dist/client/usage/index.js"
|
|
49
53
|
}
|
|
50
54
|
},
|
|
51
55
|
"main": "./dist/client/index.js",
|
|
@@ -85,7 +89,18 @@
|
|
|
85
89
|
"docs/releasing.md",
|
|
86
90
|
"docs/release-handoff.md",
|
|
87
91
|
"docs/setup-intent-recovery.md",
|
|
88
|
-
"docs/metered-usage.md"
|
|
92
|
+
"docs/metered-usage.md",
|
|
93
|
+
"docs/metering-setup.md",
|
|
94
|
+
"docs/README.md",
|
|
95
|
+
"docs/overview.md",
|
|
96
|
+
"docs/client-api.md",
|
|
97
|
+
"docs/webhooks.md",
|
|
98
|
+
"docs/marketplace.md",
|
|
99
|
+
"docs/react-api.md",
|
|
100
|
+
"docs/testing.md",
|
|
101
|
+
"docs/configuration.md",
|
|
102
|
+
"docs/architecture.md",
|
|
103
|
+
"docs/development.md"
|
|
89
104
|
],
|
|
90
105
|
"scripts": {
|
|
91
106
|
"build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
|
|
@@ -7,7 +7,23 @@ import schema from "../../component/schema.js";
|
|
|
7
7
|
import type { Component, RunCtx } from "../helpers.js";
|
|
8
8
|
import { releaseRecipientPayout } from "./payoutExecution.js";
|
|
9
9
|
import { adoptRecipientPayouts } from "./payoutAdoption.js";
|
|
10
|
-
|
|
10
|
+
// Load Convex functions during fixture import so the first action does not
|
|
11
|
+
// spend its execution timeout compiling the function graph.
|
|
12
|
+
const functionModules = import.meta.glob(
|
|
13
|
+
[
|
|
14
|
+
"../../component/**/*.*s",
|
|
15
|
+
"!../../component/**/*.test.*",
|
|
16
|
+
"!../../component/**/*.fixtures.ts",
|
|
17
|
+
"!../../component/**/convex.config.*",
|
|
18
|
+
],
|
|
19
|
+
{ eager: true },
|
|
20
|
+
);
|
|
21
|
+
const modules = Object.fromEntries(
|
|
22
|
+
Object.entries(functionModules).map(([path, module]) => [
|
|
23
|
+
path,
|
|
24
|
+
() => Promise.resolve(module),
|
|
25
|
+
]),
|
|
26
|
+
);
|
|
11
27
|
const symbol = Symbol.for("toReferencePath");
|
|
12
28
|
export const component = {
|
|
13
29
|
payoutPolicy: {
|
|
@@ -6,7 +6,23 @@ import type Stripe from "stripe";
|
|
|
6
6
|
import schema from "../../component/schema.js";
|
|
7
7
|
import type { Component, RunCtx } from "../helpers.js";
|
|
8
8
|
import { releaseRecipientPayout } from "./payoutExecution.js";
|
|
9
|
-
|
|
9
|
+
// Load Convex functions during fixture import so the first action does not
|
|
10
|
+
// spend its execution timeout compiling the function graph.
|
|
11
|
+
const functionModules = import.meta.glob(
|
|
12
|
+
[
|
|
13
|
+
"../../component/**/*.*s",
|
|
14
|
+
"!../../component/**/*.test.*",
|
|
15
|
+
"!../../component/**/*.fixtures.ts",
|
|
16
|
+
"!../../component/**/convex.config.*",
|
|
17
|
+
],
|
|
18
|
+
{ eager: true },
|
|
19
|
+
);
|
|
20
|
+
const modules = Object.fromEntries(
|
|
21
|
+
Object.entries(functionModules).map(([path, module]) => [
|
|
22
|
+
path,
|
|
23
|
+
() => Promise.resolve(module),
|
|
24
|
+
]),
|
|
25
|
+
);
|
|
10
26
|
const symbol = Symbol.for("toReferencePath");
|
|
11
27
|
export const component = {
|
|
12
28
|
payoutPolicy: {
|
|
@@ -1,17 +1,13 @@
|
|
|
1
1
|
// @vitest-environment edge-runtime
|
|
2
2
|
import { expect, it, vi } from "vitest";
|
|
3
|
-
import schema from "../
|
|
3
|
+
import { schema, modules } from "../test.js";
|
|
4
4
|
import { BetterStripe } from "./index.js";
|
|
5
5
|
import type { RunCtx } from "./helpers.js";
|
|
6
6
|
import { components, initConvexTest } from "./setup.test.js";
|
|
7
7
|
import { componentRef } from "./webhooks/helpers.js";
|
|
8
8
|
it("drains every original reference through the actual public SDK and component", async () => {
|
|
9
9
|
const t = initConvexTest();
|
|
10
|
-
t.registerComponent(
|
|
11
|
-
"betterStripe",
|
|
12
|
-
schema,
|
|
13
|
-
import.meta.glob("../component/**/*.ts"),
|
|
14
|
-
);
|
|
10
|
+
t.registerComponent("betterStripe", schema, modules);
|
|
15
11
|
const client = new BetterStripe(components.betterStripe);
|
|
16
12
|
const ctx = { runQuery: t.query, runMutation: t.mutation } as RunCtx;
|
|
17
13
|
for (let i = 0; i < 101; i++)
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { expect, it } from "vitest";
|
|
2
|
+
import { assertUsageReplay, validateUsagePageRequest } from "./boundaries.js";
|
|
3
|
+
import { prepareUsageRecord } from "./records.js";
|
|
4
|
+
import { authorizeUsageRecord, type UsageAuthorization } from "./boundaries.js";
|
|
5
|
+
|
|
6
|
+
const event = {
|
|
7
|
+
scope: {
|
|
8
|
+
stripeAccountId: "acct_platform",
|
|
9
|
+
customerAccount: "acct_buyer",
|
|
10
|
+
meterId: "mtr_calls",
|
|
11
|
+
livemode: false,
|
|
12
|
+
},
|
|
13
|
+
binding: {
|
|
14
|
+
stripeCustomerId: "cus_buyer",
|
|
15
|
+
stripePriceId: "price_calls",
|
|
16
|
+
eventName: "calls",
|
|
17
|
+
plan: {
|
|
18
|
+
key: "calls",
|
|
19
|
+
version: "v1",
|
|
20
|
+
model: "pay_as_you_go",
|
|
21
|
+
unit: { name: "call", precision: 2 },
|
|
22
|
+
rate: { currency: "usd", unitAmountDecimal: "2" },
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
sourceEventId: "request_1",
|
|
26
|
+
quantity: "1.20",
|
|
27
|
+
occurredAt: 100,
|
|
28
|
+
};
|
|
29
|
+
it("bounds page requests and uses half-open explicit periods", () => {
|
|
30
|
+
expect(
|
|
31
|
+
validateUsagePageRequest({
|
|
32
|
+
period: { start: 0, end: 100 },
|
|
33
|
+
limit: 100,
|
|
34
|
+
cursor: null,
|
|
35
|
+
}),
|
|
36
|
+
).toEqual({ period: { start: 0, end: 100 }, limit: 100, cursor: null });
|
|
37
|
+
for (const input of [
|
|
38
|
+
{ period: { start: 0, end: 0 }, limit: 10, cursor: null },
|
|
39
|
+
{ period: { start: 10, end: 9 }, limit: 10, cursor: null },
|
|
40
|
+
{ period: { start: 0, end: 1.1 }, limit: 10, cursor: null },
|
|
41
|
+
{ period: { start: 0, end: 100 }, limit: 101, cursor: null },
|
|
42
|
+
{ period: { start: 0, end: 100 }, limit: 0, cursor: null },
|
|
43
|
+
{ period: { start: 0, end: 100 }, limit: 10, cursor: "x".repeat(2049) },
|
|
44
|
+
])
|
|
45
|
+
expect(() => validateUsagePageRequest(input)).toThrow();
|
|
46
|
+
});
|
|
47
|
+
it("accepts an exact replay after normalizing quantities", () => {
|
|
48
|
+
expect(() =>
|
|
49
|
+
assertUsageReplay(
|
|
50
|
+
prepareUsageRecord(event),
|
|
51
|
+
prepareUsageRecord({ ...event, quantity: "1.2" }),
|
|
52
|
+
),
|
|
53
|
+
).not.toThrow();
|
|
54
|
+
});
|
|
55
|
+
it("rejects replay changes to historical terms, routing, time or quantity", () => {
|
|
56
|
+
const original = prepareUsageRecord(event);
|
|
57
|
+
for (const changed of [
|
|
58
|
+
{ ...event, quantity: "1.21" },
|
|
59
|
+
{ ...event, occurredAt: 101 },
|
|
60
|
+
{ ...event, binding: { ...event.binding, stripeCustomerId: "cus_other" } },
|
|
61
|
+
{
|
|
62
|
+
...event,
|
|
63
|
+
binding: {
|
|
64
|
+
...event.binding,
|
|
65
|
+
plan: { ...event.binding.plan, version: "v2" },
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
...event,
|
|
70
|
+
binding: {
|
|
71
|
+
...event.binding,
|
|
72
|
+
plan: {
|
|
73
|
+
...event.binding.plan,
|
|
74
|
+
rate: { currency: "eur", unitAmountDecimal: "2" },
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
])
|
|
79
|
+
expect(() =>
|
|
80
|
+
assertUsageReplay(original, prepareUsageRecord(changed)),
|
|
81
|
+
).toThrow("Conflicting usage replay");
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("runs host authorization and activity policy before accepting any model", async () => {
|
|
85
|
+
const order: string[] = [];
|
|
86
|
+
const policy: UsageAuthorization<{ userId: string }> = {
|
|
87
|
+
async authorize(ctx, request) {
|
|
88
|
+
expect(ctx.userId).toBe("user_1");
|
|
89
|
+
expect(request.operation).toBe("record");
|
|
90
|
+
order.push("authorize");
|
|
91
|
+
},
|
|
92
|
+
async authorizeActivity() {
|
|
93
|
+
order.push("activity");
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
for (const plan of [
|
|
97
|
+
event.binding.plan,
|
|
98
|
+
{
|
|
99
|
+
...event.binding.plan,
|
|
100
|
+
model: "included_overage",
|
|
101
|
+
includedQuantity: "10",
|
|
102
|
+
reset: "billing_period",
|
|
103
|
+
},
|
|
104
|
+
{ ...event.binding.plan, model: "prepaid", insufficientBalance: "reject" },
|
|
105
|
+
]) {
|
|
106
|
+
await authorizeUsageRecord(
|
|
107
|
+
{ userId: "user_1" },
|
|
108
|
+
policy,
|
|
109
|
+
{ ...event, binding: { ...event.binding, plan } },
|
|
110
|
+
async (record) => {
|
|
111
|
+
order.push("accept");
|
|
112
|
+
return record.identity;
|
|
113
|
+
},
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
expect(order).toEqual(
|
|
117
|
+
Array(3).fill(["authorize", "activity", "accept"]).flat(),
|
|
118
|
+
);
|
|
119
|
+
order.length = 0;
|
|
120
|
+
await expect(
|
|
121
|
+
authorizeUsageRecord(
|
|
122
|
+
{ userId: "user_1" },
|
|
123
|
+
{
|
|
124
|
+
...policy,
|
|
125
|
+
async authorizeActivity() {
|
|
126
|
+
throw new Error("Not billable");
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
event,
|
|
130
|
+
async () => {
|
|
131
|
+
order.push("accept");
|
|
132
|
+
},
|
|
133
|
+
),
|
|
134
|
+
).rejects.toThrow("Not billable");
|
|
135
|
+
expect(order).toEqual(["authorize"]);
|
|
136
|
+
});
|