@apexara/stripe 1.0.5 → 1.1.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 (57) hide show
  1. package/README.md +450 -28
  2. package/dist/apex-stripe.d.ts.map +1 -1
  3. package/dist/apex-stripe.js +10 -8
  4. package/dist/errors/http-error.d.ts +2 -1
  5. package/dist/errors/http-error.d.ts.map +1 -1
  6. package/dist/errors/http-error.js +3 -1
  7. package/dist/errors/stripe-error-status.d.ts +16 -0
  8. package/dist/errors/stripe-error-status.d.ts.map +1 -0
  9. package/dist/errors/stripe-error-status.js +60 -0
  10. package/dist/models/config.model.d.ts +2 -0
  11. package/dist/models/config.model.d.ts.map +1 -1
  12. package/dist/models/stripe.model.d.ts +12 -0
  13. package/dist/models/stripe.model.d.ts.map +1 -1
  14. package/dist/models/subscription.model.d.ts +1 -0
  15. package/dist/models/subscription.model.d.ts.map +1 -1
  16. package/dist/models/webhook.model.d.ts +16 -0
  17. package/dist/models/webhook.model.d.ts.map +1 -1
  18. package/dist/services/checkout/checkout.service.d.ts +8 -5
  19. package/dist/services/checkout/checkout.service.d.ts.map +1 -1
  20. package/dist/services/checkout/checkout.service.js +26 -13
  21. package/dist/services/connected-account/connected-account.service.d.ts +2 -1
  22. package/dist/services/connected-account/connected-account.service.d.ts.map +1 -1
  23. package/dist/services/connected-account/connected-account.service.js +4 -3
  24. package/dist/services/customer/customer.service.d.ts +2 -1
  25. package/dist/services/customer/customer.service.d.ts.map +1 -1
  26. package/dist/services/customer/customer.service.js +3 -2
  27. package/dist/services/invoice/invoice.service.d.ts +27 -3
  28. package/dist/services/invoice/invoice.service.d.ts.map +1 -1
  29. package/dist/services/invoice/invoice.service.js +108 -12
  30. package/dist/services/payment-link/payment-link.service.d.ts +2 -2
  31. package/dist/services/payment-link/payment-link.service.d.ts.map +1 -1
  32. package/dist/services/payment-link/payment-link.service.js +5 -4
  33. package/dist/services/payment-method/payment-method.service.d.ts +5 -4
  34. package/dist/services/payment-method/payment-method.service.d.ts.map +1 -1
  35. package/dist/services/payment-method/payment-method.service.js +35 -9
  36. package/dist/services/price/price.service.d.ts +2 -2
  37. package/dist/services/price/price.service.d.ts.map +1 -1
  38. package/dist/services/price/price.service.js +4 -3
  39. package/dist/services/subscription/subscription.service.d.ts +79 -12
  40. package/dist/services/subscription/subscription.service.d.ts.map +1 -1
  41. package/dist/services/subscription/subscription.service.js +337 -49
  42. package/dist/utils/idempotency.d.ts +29 -0
  43. package/dist/utils/idempotency.d.ts.map +1 -0
  44. package/dist/utils/idempotency.js +62 -0
  45. package/dist/webhooks/report-error.d.ts +7 -0
  46. package/dist/webhooks/report-error.d.ts.map +1 -0
  47. package/dist/webhooks/report-error.js +15 -0
  48. package/dist/webhooks/webhook.dispatcher.d.ts +15 -2
  49. package/dist/webhooks/webhook.dispatcher.d.ts.map +1 -1
  50. package/dist/webhooks/webhook.dispatcher.js +52 -9
  51. package/dist/webhooks/webhook.handler.d.ts +20 -1
  52. package/dist/webhooks/webhook.handler.d.ts.map +1 -1
  53. package/dist/webhooks/webhook.handler.js +94 -18
  54. package/package.json +5 -4
  55. package/dist/tests/helpers.d.ts +0 -5
  56. package/dist/tests/helpers.d.ts.map +0 -1
  57. package/dist/tests/helpers.js +0 -96
package/README.md CHANGED
@@ -4,10 +4,13 @@ A typed Stripe service layer for Node.js. Wraps the official Stripe SDK into foc
4
4
 
5
5
  ## Contents
6
6
 
7
+ - [Changes since 1.0.5](#changes-since-105)
7
8
  - [Installation](#installation)
8
9
  - [Quick Start](#quick-start)
9
10
  - [Configuration](#configuration)
10
11
  - [Services](#services)
12
+ - [Repeated writes](#repeated-writes)
13
+ - [Errors](#errors)
11
14
  - [CheckoutService](#checkoutservice)
12
15
  - [CustomerService](#customerservice)
13
16
  - [InvoiceService](#invoiceservice)
@@ -23,6 +26,88 @@ A typed Stripe service layer for Node.js. Wraps the official Stripe SDK into foc
23
26
 
24
27
  ---
25
28
 
29
+ ## Changes since 1.0.5
30
+
31
+ These changes ship as 1.1.0, and some change what an existing call does (see "Behaves differently"). An app on a `^1`
32
+ version range takes them on its next fresh install. An app pinned to an exact version sees none of this until it moves
33
+ to 1.1.0.
34
+
35
+ ### Behaves differently
36
+
37
+ - **An ended subscription's unpaid bills are voided.** When Stripe ends a subscription, the webhook handler voids its
38
+ open and uncollectible invoices after `onSubscriptionDeleted` runs, so a plan that has ended is never charged. On by
39
+ default; `voidUnpaidInvoicesOnEnd: false` turns it off. A `WebhookDispatcher` built on its own does the same, and
40
+ takes the setting as its fourth constructor argument. See [Ended subscriptions](#ended-subscriptions).
41
+ - **A blank webhook signing secret refuses every event** with a 500 before the signature check, at the main and the
42
+ connected endpoints. Stripe's own check accepts an event signed with an empty key. Stripe retries the refused events
43
+ once the secret is set.
44
+ - **A declined card carries 402** with the bank's reason and asks for no alert email. Every other Stripe error passes
45
+ through as before. See [Errors](#errors).
46
+ - **A declined plan switch fails.** `switchSubscriptionPlan` throws 402 with the decline reason and voids the switch's
47
+ open bill, where it answered as a success and left the bill open. A booked downgrade stays in place after a decline
48
+ or a refusal.
49
+ - **A booked plan change is released when it is in the way.** Cancel and resume release it first, so they no longer
50
+ fail on such a plan. A switch releases it only once the switch has gone through.
51
+ - **A booked downgrade keeps what the member has now.** The current period keeps its discounts, a running free trial,
52
+ its card and its payout and billing settings, and the new price keeps the same discounts until each one ends.
53
+ - **Removing a card checks its owner.** `removePaymentMethod` answers 404 for a card that belongs to another customer
54
+ or to none, and for an id Stripe does not know.
55
+ - **Webhook errors answer plainly.** In standalone mode a hook or store error answers 500 with the message
56
+ `Webhook processing error`, and the error goes to `onError`. A `stripe-signature` header that is missing, a list or
57
+ not text is refused as a bad signature. In Express mode a failed signature check reaches `next` with status 400 and
58
+ no alert.
59
+ - **`createInvoiceBasedSubscription` finalizes the first bill before it sends it,** and its answer carries the bill's
60
+ payment link.
61
+ - **`SubscriptionSyncFields` gains `cancelAt` and `isEnding`, both required.** An app that builds that type itself, such
62
+ as a test fixture, adds the two fields.
63
+
64
+ ### New
65
+
66
+ - **Idempotency keys.** Twelve writes take a last, optional `{ idempotencyKey }`, sent to Stripe with each write's step
67
+ name added. See [Repeated writes](#repeated-writes).
68
+ - **`invoices.findConfirmPaymentUrl(subscription)`** gives the page where the customer confirms a renewal their bank
69
+ holds for its security check.
70
+ - **`invoices.payPastDueInvoice(subscription, idempotency?)`** charges the open bill of a past due plan at once, for
71
+ right after the customer sets a new default card.
72
+ - **`invoices.voidUnpaidInvoices(subscription)`** is public, so an app can retry the void from a nightly job.
73
+ - **The event store takes optional `release` and `markDone`,** so an event that failed is given back and Stripe's
74
+ retry runs it again. See [Retrying an event that failed](#retrying-an-event-that-failed).
75
+ - **`markRefusalsDone`** in the webhook config, off by default, marks an event done when its hook refuses it with a
76
+ 4xx status, except one that asks for a later try. See [Marking a refusal done](#marking-a-refusal-done).
77
+ - **`HttpError` takes a third argument, `shouldTryLater`,** for a 4xx that asks for a later try, as the library's 409
78
+ for an idempotency key still in use does. `markRefusalsDone` gives such an event back.
79
+ - **`onOtherEvent` and `onRefused`** in the webhook hooks, both optional. `onOtherEvent(event)` runs an event the
80
+ package has no hook for inside the same claim as its own, so an app hands every Stripe event to the handler.
81
+ `onRefused(event, error)` is called when a refusal is marked done, so the app can tell its team. See
82
+ [Events dispatched](#events-dispatched) and [Marking a refusal done](#marking-a-refusal-done).
83
+ - **`scheduleDowngrade` takes an optional `discounts`** for the new price. Left out, the current discounts carry on;
84
+ `[]` sets none. See [Downgrades (scheduled)](#downgrades-scheduled).
85
+ - **`WebhookDispatcher.isVoidUndone(err)`** is public: true for an error thrown from `onSubscriptionDeleted` while the
86
+ void after it failed too, which the handler gives back even under `markRefusalsDone`.
87
+ - **Discounts.** `getSubscriptionWithDiscounts`, `getSubscriptionDiscount`, `getCostWithDiscount` and the
88
+ `SubscriptionDiscount` type. See [Discounts](#discounts).
89
+ - **`buildSubscriptionSyncFields` returns `cancelAt` and `isEnding`,** so a plan given an end date in the Stripe
90
+ dashboard shows as ending.
91
+
92
+ ### Fixed
93
+
94
+ - Cancel and resume work on a trial.
95
+ - Removing the default card makes another card on file the default first.
96
+ - Lists read every page, up to 1000 items.
97
+ - Hosted checkout works: `createCheckoutSession` returns the address of Stripe's page in place of an empty
98
+ `client_secret`, and sends its return address as `success_url`. An automatically charged invoice is finalized with
99
+ automatic collection on.
100
+ - `expireCheckoutSession` returns quietly when the checkout is already expired or complete.
101
+ - A throw or a rejection from `onError` is dropped: it never changes a webhook's answer or stops the process.
102
+
103
+ ### Release and tooling
104
+
105
+ - The release pipeline runs the type check and the tests before the build, and a failure stops the publish.
106
+ - `qs` moves to 6.17.1 and `npm audit` reports nothing. The Stripe range stays `^18.5.0`.
107
+ - The tests run on Vitest 4. Nothing an app installs changes, and the package leaves its tests out.
108
+
109
+ ---
110
+
26
111
  ## Installation
27
112
 
28
113
  ```bash
@@ -142,6 +227,75 @@ All services are available as properties on the `ApexStripe` instance. They can
142
227
 
143
228
  ---
144
229
 
230
+ ### Repeated writes
231
+
232
+ A second press or a retry after a slow answer calls a write again, and Stripe makes a new object for each call: a
233
+ second plan, bill, credit, customer or charge. The SDK's own network retries already reuse one key, so only a repeat by
234
+ the app is open. The writes below take a last, optional `{ idempotencyKey }` (`IdempotencyOptions`). With a key,
235
+ Stripe answers a repeat within 24 hours with the first call's result instead of running it again. Without one a call
236
+ works as before.
237
+
238
+ | Method | Stripe writes, by step name |
239
+ |---|---|
240
+ | `checkout.createCheckoutSession(params, idempotency?)` | `checkout` |
241
+ | `checkout.createSetupIntentSession(customerId, idempotency?)` | `setup-intent` |
242
+ | `customers.createCustomer(firstName, lastName, email, idempotency?)` | `customer` |
243
+ | `invoices.createInvoice(params, idempotency?)` | `invoice`, `invoice-line`, then `invoice-send` or `invoice-finalize` |
244
+ | `invoices.payPastDueInvoice(subscription, idempotency?)` | `invoice-pay` |
245
+ | `paymentLinks.createPaymentLink(params, idempotency?)` | `payment-link-price`, `payment-link` |
246
+ | `prices.createCustomSubscriptionPrice(params, idempotency?)` | `price` |
247
+ | `connectedAccounts.createConnectedAccount(metadata?, idempotency?)` | `connected-account` |
248
+ | `subscriptions.applyPlanCredit(customerId, subscriptionId, amount, currency, description?, metadata?, idempotency?)` | `plan-credit` |
249
+ | `subscriptions.switchSubscriptionPlan(subscriptionId, itemId, newPriceId, options?, idempotency?)` | `plan-switch` |
250
+ | `subscriptions.createInvoiceBasedSubscription(customerId, priceId, options?, idempotency?)` | `invoice-subscription`, `invoice-subscription-finalize`, `invoice-subscription-send` |
251
+ | `subscriptions.updateSubscription(subscriptionId, params, idempotency?)` | `subscription-update` |
252
+
253
+ Each Stripe write gets the key with its step name added (`<key>:invoice-line`). A repeated write of several steps so
254
+ makes one bill with one line, emailed once, and one key can cover every library call of one user action.
255
+
256
+ - Make one key per user action, such as a form's submit, and send it again only for a repeat of that action. A UUID
257
+ the browser makes when the form opens, sent as an `Idempotency-Key` header, does this.
258
+ - Call each method once per key: a second call of the same method with the same key gets the first one's result.
259
+ - A repeat gets the first answer, a Stripe error included: a declined card stays declined for that key, also after the
260
+ card is changed. A new attempt needs a new key.
261
+ - A key has at most 200 characters, all visible ASCII (letters, digits and symbols, no spaces), so a UUID fits. Any
262
+ other key is refused with `HttpError` 400 before Stripe is called.
263
+ - The same key with other details is refused with `HttpError` 422, and a repeat while the first call still runs with
264
+ `HttpError` 409, to try again a moment later (`shouldTryLater` is true). Neither asks for an alert email
265
+ (`shouldSendEmail` is false).
266
+
267
+ ```typescript
268
+ const idempotency = { idempotencyKey: req.header('Idempotency-Key') }; // the form's key, made when the form opens
269
+
270
+ const customer = await stripe.customers.createCustomer('Jane', 'Doe', 'jane@example.com', idempotency);
271
+ const { invoiceUrl } = await stripe.subscriptions.createInvoiceBasedSubscription(customer.id, 'price_xxx', { metadata }, idempotency);
272
+ ```
273
+
274
+ Writes that are safe to repeat as they are take no key: the fixed updates (a card, the cancel flag), cancels, voids,
275
+ deletes, attaches, detaches and archives. Neither do a downgrade's schedule, which Stripe allows once per subscription,
276
+ and the short lived account and login links. `updateSubscription` passes its params on as they are, so a change that
277
+ can bill (a new price, `billing_cycle_anchor: 'now'`) should carry a key.
278
+
279
+ ---
280
+
281
+ ### Errors
282
+
283
+ A declined card thrown through a service of `ApexStripe` (Stripe's `StripeCardError`) carries `status` 402 and asks for
284
+ no alert email (`shouldSendEmail` is false), as the library's own `HttpError` refusals do. Its `message` is the bank's
285
+ reason, written by Stripe for the customer ("Your card has insufficient funds."), so an app can show it. The error
286
+ stays Stripe's, with its class, `type` and `code`.
287
+
288
+ Every other Stripe error passes through as Stripe threw it, with no `status`: a missing object, a bad request, a wrong
289
+ or restricted key, too many requests, a failure at Stripe or no connection. An app's error middleware answers it 500
290
+ (`err.status || 500`) and sends its alert, and Stripe's own words never reach a member. Two methods answer a missing
291
+ object themselves: `removePaymentMethod` throws `HttpError` 404 for a card Stripe does not know, and
292
+ `expireCheckoutSession` returns quietly for a checkout Stripe does not know.
293
+
294
+ Services made on their own (see [Advanced Usage](#advanced-usage)) and calls through `client` throw Stripe's errors as
295
+ they are.
296
+
297
+ ---
298
+
145
299
  ### CheckoutService
146
300
 
147
301
  `stripe.checkout`
@@ -150,9 +304,11 @@ Handles Stripe Checkout sessions, Setup Intents, and affiliate payout calculatio
150
304
 
151
305
  ---
152
306
 
153
- #### `createCheckoutSession(params)`
307
+ #### `createCheckoutSession(params, idempotency?)`
154
308
 
155
- Creates a payment or subscription checkout session. Returns the `client_secret` for use with Stripe.js.
309
+ Creates a payment or subscription checkout session. Returns the `client_secret` for use with Stripe.js or, when
310
+ `checkoutUiMode` is `'hosted'`, the address of Stripe's page to send the customer to. On Stripe's page `returnUrl` is
311
+ where Stripe sends the customer once they have paid (`success_url`).
156
312
 
157
313
  **Payment mode:**
158
314
 
@@ -193,7 +349,7 @@ const clientSecret = await stripe.checkout.createCheckoutSession({
193
349
 
194
350
  ---
195
351
 
196
- #### `createSetupIntentSession(customerId)`
352
+ #### `createSetupIntentSession(customerId, idempotency?)`
197
353
 
198
354
  Creates a Setup Intent for saving a payment method without charging. Returns the `client_secret`.
199
355
 
@@ -205,7 +361,7 @@ const clientSecret = await stripe.checkout.createSetupIntentSession('cus_xxx');
205
361
 
206
362
  #### `expireCheckoutSession(sessionId)`
207
363
 
208
- Expires an open checkout session. Silently ignores sessions that are already expired — safe to call unconditionally.
364
+ Expires an open checkout session. Returns quietly when Stripe has no such session or the session is no longer open (already expired, or complete because it was paid), so it is safe to call unconditionally. Any other error, a 500 or 429 included, also counts as done when the session then reads back expired or complete; the call throws it when the session reads back open or cannot be read.
209
365
 
210
366
  ```typescript
211
367
  await stripe.checkout.expireCheckoutSession('cs_xxx');
@@ -241,7 +397,7 @@ const intent = await stripe.checkout.getPaymentIntent('pi_xxx');
241
397
 
242
398
  ---
243
399
 
244
- #### `createCustomer(firstName, lastName, email)`
400
+ #### `createCustomer(firstName, lastName, email, idempotency?)`
245
401
 
246
402
  Creates a Stripe customer. The full name is stored as `${firstName} ${lastName}`.
247
403
 
@@ -268,12 +424,14 @@ await stripe.customers.updateCustomerDefaultPaymentMethod('cus_xxx', 'pm_xxx');
268
424
 
269
425
  ---
270
426
 
271
- #### `createInvoice(params)`
427
+ #### `createInvoice(params, idempotency?)`
272
428
 
273
429
  Creates an invoice with a single line item and either sends it or finalizes it, depending on `invoiceCollectionMethod`.
274
430
 
275
431
  - `send_invoice` — creates, adds line item, sends — customer receives an email with payment link
276
- - `charge_automatically` — creates, adds line item, finalizes — Stripe charges the default payment method
432
+ - `charge_automatically` — creates, adds line item, finalizes with automatic collection on — Stripe charges the
433
+ customer's default payment method about an hour later. The invoice has no due date, so `invoiceDaysUntilDue` is not
434
+ used.
277
435
 
278
436
  ```typescript
279
437
  const invoice = await stripe.invoices.createInvoice({
@@ -300,7 +458,7 @@ const payments = await stripe.invoices.listInvoicePayments('in_xxx');
300
458
 
301
459
  #### `findPendingActivationInvoice(customerId)`
302
460
 
303
- Checks whether a customer has an open invoice from a `subscription_create` event whose subscription is still active or incomplete. Returns the invoice data or `null`.
461
+ Checks whether any of a customer's open invoices is from a `subscription_create` event whose subscription is still active or incomplete. Returns the invoice data or `null`.
304
462
 
305
463
  Use this to prompt the user to pay their pending subscription invoice after an admin-created invoice-based subscription.
306
464
 
@@ -320,13 +478,74 @@ Returns `null` when:
320
478
 
321
479
  ---
322
480
 
481
+ #### `payPastDueInvoice(subscription, idempotency?)`
482
+
483
+ Charges a `past_due` subscription's latest invoice now, with the card the subscription charges. Stripe's retries keep
484
+ their own schedule after the customer saves a new card, so call this right after setting the new default card, the way
485
+ app stores charge at once on a card update. Returns the invoice once it is paid, also when a retry paid it meanwhile
486
+ and the subscription reads `active` again. Returns `null` for a subscription in any other status, one with no invoice,
487
+ a draft or void invoice, and an `active` subscription's open invoice, which are never charged here. A declined card throws `HttpError` 402 with the card's reason, and a payment that waits for the
488
+ customer's bank check (3D Secure) throws 402 "Your bank needs you to confirm this payment.". After a decline Stripe
489
+ keeps retrying as before; a payment that waits for the bank check waits for the customer to confirm it
490
+ (`findConfirmPaymentUrl`). Any other refusal from Stripe is thrown as it is.
491
+
492
+ ```typescript
493
+ await stripe.paymentMethods.setDefaultPaymentMethod(subscriptionId, paymentMethodId);
494
+ const subscription = await stripe.subscriptions.getSubscriptionById(subscriptionId);
495
+ try {
496
+ const paid = await stripe.invoices.payPastDueInvoice(subscription);
497
+ // → the paid invoice, or null when there was nothing to pay
498
+ } catch (err) {
499
+ // err.status === 402: err.message is the reason to show the customer
500
+ }
501
+ ```
502
+
503
+ ---
504
+
505
+ #### `voidUnpaidInvoices(subscription)`
506
+
507
+ Voids the `open` and `uncollectible` invoices of a `canceled` subscription, so nobody can pay for a plan that has
508
+ ended. Stripe keeps those invoices payable after a cancel, and an uncollectible invoice still takes a payment; only a
509
+ void one is refused. A subscription in any other status is left alone, because voiding a live subscription's latest
510
+ invoice changes its status. An invoice paid or voided in the meantime is left as it is, so calling it again changes
511
+ nothing. Any other refusal from Stripe is thrown. Returns how many invoices it voided.
512
+
513
+ The webhook handler calls this for every `customer.subscription.deleted` (see [Webhooks](#webhooks)). Call it
514
+ yourself to retry later, for example from a nightly job over the subscriptions that ended in the last few days.
515
+
516
+ ```typescript
517
+ const subscription = await stripe.subscriptions.getSubscriptionById('sub_xxx');
518
+ const voided = await stripe.invoices.voidUnpaidInvoices(subscription);
519
+ // → 1
520
+ ```
521
+
522
+ ---
523
+
524
+ #### `findConfirmPaymentUrl(subscription)`
525
+
526
+ Returns Stripe's hosted page for a `past_due` subscription's latest invoice when its payment waits for the customer's
527
+ bank check (3D Secure, a PaymentIntent in `requires_action`). Stripe never retries such a payment on its own, so the
528
+ customer has to confirm it on that page. Returns `null` for a declined card or any other failure, an invoice that is
529
+ no longer `open`, and a subscription in any other status. Reads the latest invoice once; a refusal from Stripe is
530
+ thrown.
531
+
532
+ Show the link on the billing page next to the plan, so a renewal held by the bank is one click from being paid.
533
+
534
+ ```typescript
535
+ const subscription = await stripe.subscriptions.getSubscriptionById('sub_xxx');
536
+ const confirmUrl = await stripe.invoices.findConfirmPaymentUrl(subscription);
537
+ // → 'https://invoice.stripe.com/i/...' or null
538
+ ```
539
+
540
+ ---
541
+
323
542
  ### PaymentLinkService
324
543
 
325
544
  `stripe.paymentLinks`
326
545
 
327
546
  ---
328
547
 
329
- #### `createPaymentLink(params)`
548
+ #### `createPaymentLink(params, idempotency?)`
330
549
 
331
550
  Creates a Stripe Price and Payment Link in one call. Returns the link ID, URL, and the underlying price/product IDs needed to archive later.
332
551
 
@@ -376,7 +595,7 @@ const pm = await stripe.paymentMethods.getPaymentMethod('pm_xxx');
376
595
 
377
596
  #### `listPaymentMethods(customerId)`
378
597
 
379
- Returns the customer's saved payment methods as a flat array.
598
+ Returns all the customer's saved payment methods as a flat array, reading every page Stripe returns.
380
599
 
381
600
  ```typescript
382
601
  const methods = await stripe.paymentMethods.listPaymentMethods('cus_xxx');
@@ -421,7 +640,10 @@ const { changed } = await stripe.paymentMethods.setDefaultPaymentMethodIfMissing
421
640
 
422
641
  #### `removePaymentMethod(customerId, subscriptionId, paymentMethodId)`
423
642
 
424
- Removes a payment method safely. If it is the subscription's default, another payment method is assigned first. Throws if it is the only payment method on the customer.
643
+ Removes a payment method safely. If it is the subscription's default or the customer's default, another card on file
644
+ takes its place first, so a plan is not left without a card to charge. Throws if it is the only payment method on the
645
+ customer, and `HttpError` 404 when the card is not this customer's, also for an id Stripe does not know.
646
+ `newDefaultId` is the subscription's new default, or `null` when the subscription's default did not change.
425
647
 
426
648
  ```typescript
427
649
  const { newDefaultId } = await stripe.paymentMethods.removePaymentMethod(
@@ -439,7 +661,7 @@ const { newDefaultId } = await stripe.paymentMethods.removePaymentMethod(
439
661
 
440
662
  ---
441
663
 
442
- #### `createCustomSubscriptionPrice(params)`
664
+ #### `createCustomSubscriptionPrice(params, idempotency?)`
443
665
 
444
666
  Creates a recurring price on an existing Stripe product.
445
667
 
@@ -477,7 +699,7 @@ Handles Stripe Connect for marketplace and affiliate payout scenarios.
477
699
 
478
700
  ---
479
701
 
480
- #### `createConnectedAccount(metadata?)`
702
+ #### `createConnectedAccount(metadata?, idempotency?)`
481
703
 
482
704
  Creates a new connected account (type from config, defaults to `'express'`). Returns the account ID.
483
705
 
@@ -541,7 +763,7 @@ The most comprehensive service. Covers the full subscription lifecycle including
541
763
  // Get a subscription (expands items.data.price)
542
764
  const sub = await stripe.subscriptions.getSubscriptionById('sub_xxx');
543
765
 
544
- // Get all subscriptions for a customer (status: 'all', expands default_payment_method)
766
+ // Get all subscriptions for a customer, every page (status: 'all', expands default_payment_method)
545
767
  const subs = await stripe.subscriptions.getAllUserSubscriptions('cus_xxx');
546
768
  // → Stripe.Subscription[] (empty array if customerId is falsy)
547
769
 
@@ -559,15 +781,21 @@ const cancelled = await stripe.subscriptions.cancelSubscription('sub_xxx');
559
781
  #### Lifecycle — cancel at period end / resume
560
782
 
561
783
  ```typescript
562
- // Schedule cancellation at end of billing period.
563
- // Throws if status is not 'active' or 'past_due'.
784
+ // Schedule cancellation at end of billing period (for a free trial, the trial's end).
785
+ // Throws if status is not 'active', 'past_due' or 'trialing'.
564
786
  const sub = await stripe.subscriptions.cancelSubscriptionAtPeriodEnd('sub_xxx');
565
787
 
566
788
  // Undo a scheduled cancellation.
567
- // Throws if cancel_at_period_end is false or status is not resumable.
789
+ // Throws if the plan is not set to end (cancel_at_period_end, or a schedule that ends it) or status is not resumable.
568
790
  const sub = await stripe.subscriptions.resumeSubscription('sub_xxx');
569
791
  ```
570
792
 
793
+ Stripe refuses to change a plan's cancellation while a schedule is attached to it, such as a booked downgrade. Both
794
+ methods therefore release an attached schedule first: the plan stays on its current price and the schedule's later
795
+ phases are dropped. A plan that an attached schedule ends shows `cancel_at` with `cancel_at_period_end` false;
796
+ `resumeSubscription` resumes it too. A schedule another call has just released is passed over. Neither method
797
+ releases anything when it refuses the call.
798
+
571
799
  ---
572
800
 
573
801
  #### Plan switching and credits
@@ -599,11 +827,22 @@ const updated = await stripe.subscriptions.switchSubscriptionPlan(
599
827
  );
600
828
  ```
601
829
 
830
+ An attached schedule, such as a booked downgrade, is released once the switch has gone through; left attached, its next
831
+ phase would move the plan back when the current one ends. A declined charge or a switch Stripe refuses leaves it
832
+ attached, so the member keeps what they booked. A repeat with the key releases only the schedule the first call found,
833
+ so a downgrade booked since then stays. The answer names no schedule even then, so read the subscription again before
834
+ acting on its schedule. If the release fails, the call throws although the plan has switched and been charged; a repeat
835
+ with the key releases it without switching again, while a repeat without a key switches and charges again. A key the
836
+ library refuses stops the call before anything changes.
837
+
602
838
  ---
603
839
 
604
840
  #### Downgrades (scheduled)
605
841
 
606
842
  Downgrades are scheduled to take effect at the end of the current billing period using Stripe Subscription Schedules.
843
+ The current period keeps everything it already has: its discounts, a running free trial, its own card and affiliate
844
+ payout. The new price keeps the same discounts (each runs on to its own end date, so one that ends before the change
845
+ is not carried), unless `discounts` says otherwise. A failed call releases a schedule it made itself.
607
846
 
608
847
  ```typescript
609
848
  // Schedule a downgrade to a lower price at period end.
@@ -615,6 +854,7 @@ const schedule = await stripe.subscriptions.scheduleDowngrade(
615
854
  transferData: { destination: 'acct_xxx', amount_percent: 19 }, // Optional
616
855
  phaseMetadata: { affiliateId: 'aff_xxx' }, // Optional
617
856
  scheduleMetadata: { initiatedBy: 'user' }, // Optional
857
+ discounts: [], // Optional: none on the new price
618
858
  },
619
859
  );
620
860
 
@@ -640,7 +880,7 @@ const schedule = await stripe.subscriptions.getOrCreateSubscriptionSchedule(subs
640
880
 
641
881
  #### Invoice-based subscriptions (admin-created)
642
882
 
643
- Creates a subscription using `send_invoice` collection and immediately emails the invoice to the customer. Use this for admin-created subscriptions where the customer pays via an emailed link rather than through a checkout session.
883
+ Creates a subscription using `send_invoice` collection, finalizes its first invoice and emails it to the customer at once, and answers with the invoice's payment link. Use this for admin-created subscriptions where the customer pays via an emailed link rather than through a checkout session.
644
884
 
645
885
  ```typescript
646
886
  const { subscription, invoiceId, invoiceUrl } =
@@ -672,7 +912,9 @@ const fields = stripe.subscriptions.buildSubscriptionSyncFields(subscription, {
672
912
  currentPeriodEnd: existingDoc.currentPeriodEnd,
673
913
  itemId: existingDoc.itemId,
674
914
  });
675
- // → { status, cancelAtPeriodEnd, currentPeriodStart, currentPeriodEnd, itemId }
915
+ // → { status, cancelAtPeriodEnd, cancelAt, isEnding, currentPeriodStart, currentPeriodEnd, itemId }
916
+ // cancelAt is the day Stripe ends the plan: the period's end, or a date picked in the dashboard, which can fall
917
+ // after the period's end. isEnding is true when it is set to end either way; cancelAtPeriodEnd stays Stripe's flag.
676
918
 
677
919
  // Get the primary subscription item, preferring a known item ID.
678
920
  const item = stripe.subscriptions.getPrimarySubscriptionItem(subscription, 'si_xxx');
@@ -681,6 +923,39 @@ const item = stripe.subscriptions.getPrimarySubscriptionItem(subscription, 'si_x
681
923
 
682
924
  ---
683
925
 
926
+ #### Discounts
927
+
928
+ These read the discount a customer's subscription carries, such as a promotion code they entered at checkout, and
929
+ work out what a charge comes to once it is taken off, for example to show the next charge on a billing page.
930
+
931
+ ```typescript
932
+ // Get the subscription with its discounts and the promotion codes behind them expanded.
933
+ // Other fields to expand go in the second argument; each is added once.
934
+ const subscription = await stripe.subscriptions.getSubscriptionWithDiscounts('sub_xxx', ['latest_invoice']);
935
+
936
+ // Read its discount.
937
+ const discount = stripe.subscriptions.getSubscriptionDiscount(subscription);
938
+ // → { code: 'FOUNDERS25', name: 'Founders', percentOff: 25, amountOff: null, endsAt: null }, or null without one
939
+
940
+ // What a $49.00 charge on nextChargeAt comes to with it off, in cents. nextChargeAt is the next charge's date,
941
+ // e.g. currentPeriodEnd from buildSubscriptionSyncFields (the trial's end during a trial).
942
+ const next = stripe.subscriptions.getCostWithDiscount(4900, discount, nextChargeAt);
943
+ // → 3675
944
+ ```
945
+
946
+ - `getSubscriptionDiscount` reads the first discount Stripe expanded. `code` is the promotion code the customer
947
+ entered, `null` without one; `amountOff` is in cents; `endsAt` is `null` for a discount that lasts as long as the
948
+ subscription, and also for a once coupon, which Stripe takes off one bill and then removes: it gives the price of
949
+ the next charge, not of the ones after it. Pass a subscription from `getSubscriptionWithDiscounts`: from
950
+ `getSubscriptionById` the discounts are ids, so it returns `null`.
951
+ - `getCostWithDiscount` takes off the percent rounded to the cent (12.5% of $49.00 is $6.125, so $6.13 comes off
952
+ and $42.87 is charged), or the amount off, never going below 0. A discount that ends on or before `nextChargeAt`
953
+ takes nothing off; a `nextChargeAt` of `null` keeps it.
954
+ - For a subscription with one price and one discount and no tax, the result is the total of Stripe's own preview of
955
+ that bill.
956
+
957
+ ---
958
+
684
959
  ## Affiliate Payout Helpers
685
960
 
686
961
  Two standalone functions are exported for calculating affiliate payouts after deducting Stripe processing fees. Both require a `processingFees` object (`{ flat: number, percent: number }`).
@@ -700,11 +975,11 @@ const fees = { flat: 30, percent: 0.029 }; // Standard Stripe rates
700
975
  const amount = calculateAffiliatePaymentPayoutAmount(10000, 20, fees);
701
976
  // → 1936
702
977
 
703
- // Subscription payout — returns percentage to pass to transfer_data.amount_percent
704
- // subscriptionCost = 10000, payoutPercent = 0.20
705
- // result = ((10000 - 320) * 0.20) / 10000 ≈ 0.19
706
- const percent = calculateAffiliateSubscriptionPayoutPercent(10000, 0.20, fees);
707
- // → 0.19
978
+ // Subscription payout — returns the percent to pass to transfer_data.amount_percent (20 for 20%)
979
+ // subscriptionCost = 10000, payoutPercent = 20
980
+ // result = ((10000 - 320) * 20) / 10000 = 19.36
981
+ const percent = calculateAffiliateSubscriptionPayoutPercent(10000, 20, fees);
982
+ // → 19.36
708
983
  ```
709
984
 
710
985
  ---
@@ -713,6 +988,10 @@ const percent = calculateAffiliateSubscriptionPayoutPercent(10000, 0.20, fees);
713
988
 
714
989
  `StripeWebhookHandler` handles the main Stripe webhook and the connected account webhook. It performs signature verification, idempotency checks, and event dispatch.
715
990
 
991
+ While a secret is blank or missing, its endpoint refuses every event with a 500 (passed to `next` in Express mode),
992
+ since an event signed with an empty key would pass the signature check. Stripe retries those events, so they run once
993
+ the secret is set.
994
+
716
995
  ### Setup
717
996
 
718
997
  ```typescript
@@ -721,6 +1000,8 @@ import { StripeWebhookHandler, WebhookHooks, WebhookHandlerConfig } from '@apexa
721
1000
  const config: WebhookHandlerConfig = {
722
1001
  webhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
723
1002
  connectedWebhookSecret: process.env.STRIPE_WEBHOOK_CONNECTED_SECRET, // Optional
1003
+ voidUnpaidInvoicesOnEnd: true, // Optional, defaults to true: see "Ended subscriptions" below
1004
+ markRefusalsDone: false, // Optional, defaults to false: see "Marking a refusal done" below
724
1005
  };
725
1006
 
726
1007
  const hooks: WebhookHooks = {
@@ -732,6 +1013,8 @@ const hooks: WebhookHooks = {
732
1013
  // Use a unique index to make this atomic.
733
1014
  return db.stripeEvents.tryInsert({ eventId, type });
734
1015
  },
1016
+ // Optional: release, so Stripe's retry runs a failed event again, and markDone
1017
+ // (see "Retrying an event that failed")
735
1018
  },
736
1019
 
737
1020
  // Optional: implement only the events you care about
@@ -758,7 +1041,22 @@ const hooks: WebhookHooks = {
758
1041
  await syncAffiliateStatus(account);
759
1042
  },
760
1043
 
761
- // Optional: called when a non-critical internal error occurs (e.g. fail reason extraction)
1044
+ // Optional: every other event on the main endpoint, run in the same claim as the hooks above, so the event store
1045
+ // treats it as it treats them (see "Events dispatched")
1046
+ onOtherEvent: async (event) => {
1047
+ if (event.type === 'charge.refunded') {
1048
+ await recordRefund(event.data.object);
1049
+ }
1050
+ },
1051
+
1052
+ // Optional: called when markRefusalsDone marks a refused event done (see "Marking a refusal done")
1053
+ onRefused: (event, error) => {
1054
+ alertTeam(`Stripe event ${event.id} (${event.type}) was refused`, error);
1055
+ },
1056
+
1057
+ // Optional: gets the errors the package does not pass on, such as a failed fail reason extraction, and in
1058
+ // standalone mode the error behind each 500 (see "Express routes"). A throw or a rejection from it is dropped,
1059
+ // and no answer waits for it.
762
1060
  onError: (context, error) => {
763
1061
  logger.error(`Webhook error in ${context}`, error);
764
1062
  },
@@ -789,6 +1087,34 @@ app.post('/stripe/webhook/connected', (req, res, next) => handler.handleConnecte
789
1087
  app.post('/stripe/webhook', (req, res) => handler.handle(req, res));
790
1088
  ```
791
1089
 
1090
+ In standalone mode the handler answers errors itself:
1091
+
1092
+ - A bad signature gets a 400 with Stripe's reason. That covers a forged request and a `stripe-signature` header that
1093
+ is missing, a list or not text.
1094
+ - Anything else gets a 500 with `{ "error": "Webhook processing error" }`, so no internal error text leaves the app.
1095
+ The error itself goes to `onError('handle' | 'handleConnected', error)` once the answer is sent; without `onError`
1096
+ it is not seen anywhere. A throw or a rejection from `onError` there is dropped, since the answer has already gone.
1097
+
1098
+ In Express mode both go to `next`. A bad signature goes as Stripe's `StripeSignatureVerificationError` with `status`
1099
+ 400 and `shouldSendEmail` false, as the library's own `HttpError` refusals carry, so an error middleware that answers
1100
+ `err.status || 500` answers it 400 without an alert. Anything else goes to `next` as it is.
1101
+
1102
+ #### Noticing a wrong signing secret
1103
+
1104
+ A bad signature raises no alert in either mode, since anyone can send one. But a wrong signing secret on the endpoint
1105
+ (another endpoint's, or another Stripe account's) refuses every event Stripe sends it the same way, so no event runs
1106
+ until it is fixed. To notice it, an app checks the signature itself before it calls the handler:
1107
+
1108
+ - Check with `stripeClient.webhooks.constructEvent`, on the same raw body and secret the handler uses. When it throws,
1109
+ answer 400 and do not call the handler.
1110
+ - Email the team when a refused request carries a `stripe-signature` header. Stripe sends one with every event, so
1111
+ such a request most likely comes from Stripe, signed with a secret the app does not hold.
1112
+ - A forger can send the header too, so cap these emails at a few an hour, under an alert source of their own so they
1113
+ cannot use up the alerts the rest of the app needs.
1114
+
1115
+ In live mode Stripe retries a refused event for up to three days, so the events refused meanwhile still run once the
1116
+ secret is fixed.
1117
+
792
1118
  ### Idempotency
793
1119
 
794
1120
  Every incoming event is checked against the event store before being dispatched. If `tryInsert` returns `false`, the event is acknowledged with HTTP 200 and skipped — no hook is called. This prevents duplicate processing when Stripe retries delivery.
@@ -811,6 +1137,76 @@ eventStore: {
811
1137
  },
812
1138
  ```
813
1139
 
1140
+ #### Retrying an event that failed
1141
+
1142
+ `tryInsert` records an event before its hooks run. With `tryInsert` alone the package never gives the event back, so
1143
+ when a hook throws, Stripe's retry finds it recorded and gets a 200. Two optional store methods change that:
1144
+
1145
+ - `release(eventId)` is called when handling the event throws (a hook, or the package's own Stripe call around it),
1146
+ before the error goes on (to `next`, or the 500). Give the event back there, for example by deleting its record,
1147
+ and Stripe's retry runs it again. Add it only once every hook is safe to run again after failing part way, since the
1148
+ retry runs the whole hook again. `onSubscriptionDeleted` must also be safe to run again after it finished: when
1149
+ Stripe refuses the void that follows it, the event is given back too (see "Ended subscriptions"). With
1150
+ `markRefusalsDone`, a refusal is marked done instead (see "Marking a refusal done").
1151
+ - `markDone(eventId)` is called once the hooks have finished, before the 200. It suits a store that claims an event
1152
+ before it runs and records it as done after.
1153
+ - A `release` or `markDone` that fails goes to `onError('release' | 'markDone', error)`: the hook's error still goes on,
1154
+ and finished work is still answered 200.
1155
+ - Neither is called for a repeat, when `tryInsert` throws, or for an event refused before `tryInsert` (a blank
1156
+ webhook secret or a failed signature check).
1157
+
1158
+ ```typescript
1159
+ eventStore: {
1160
+ tryInsert: async (eventId, type) => { /* as above */ },
1161
+ release: async (eventId) => {
1162
+ await StripeEventModel.deleteOne({ eventId }); // Stripe's retry inserts it again
1163
+ },
1164
+ },
1165
+ ```
1166
+
1167
+ The store above loses an event when a second delivery of it arrives while the first is still running: `tryInsert`
1168
+ finds the record, so the second delivery gets a 200 and Stripe takes the event as delivered. When the first run then
1169
+ fails and gives the event back, no retry comes. A store that claims an event first and marks it done after closes that
1170
+ gap:
1171
+
1172
+ - `tryInsert` claims a new event as being handled. It returns `false` only for an event marked done, and throws for
1173
+ one still being handled, so that delivery is answered with an error and Stripe sends it again later. The package
1174
+ calls neither `release` nor `markDone` for it, so the first run keeps its claim.
1175
+ - `markDone` marks the claim done, and `release` deletes it.
1176
+ - A run cut off part way (a restart, a crash) leaves its claim behind, so `tryInsert` also takes over a claim older
1177
+ than a time limit far longer than any hook runs.
1178
+ - `release` and `markDone` get the event id only, so they act on the event's claim as it is now: a run that outlasts
1179
+ the time limit and then ends would release or mark done the claim of the delivery that took it over. The long time
1180
+ limit keeps that out of reach.
1181
+
1182
+ #### Marking a refusal done
1183
+
1184
+ This setting stops Stripe sending an event again and again when your hook refuses it on purpose, for example an
1185
+ event about a customer your app has deleted, which would otherwise come back for up to three days.
1186
+
1187
+ With `release`, Stripe's retry runs every failed event again, also one that fails the same way every time, such as a
1188
+ hook that refuses an event with a 4xx status (an `HttpError`, or the app's own error with `status` 404). Set
1189
+ `markRefusalsDone: true` in `WebhookHandlerConfig` and such an event is marked done with `markDone` instead:
1190
+
1191
+ - An error whose `status` is a number from 400 to 499 is a refusal, except 408, 429 and any error with
1192
+ `shouldTryLater: true` (`new HttpError(409, message, true)` makes one, as the library's 409 for an idempotency key
1193
+ still in use does), which ask for a later try. Every other error gives the event back as before: a 5xx, a later try,
1194
+ an error with no `status`, and a Stripe error that has only a `statusCode`, since its 429 or 409 passes on Stripe's
1195
+ retry.
1196
+ - A refusal from `onSubscriptionDeleted` while the void after it failed too gives the event back, so Stripe's retry
1197
+ voids the unpaid invoices again (see "Ended subscriptions"). That mark sits on the error object, so a hook throws a
1198
+ new error for each event rather than one shared object.
1199
+ - The answer does not change: the error still goes to `next`, or the 500, and a failed `markDone` goes to
1200
+ `onError('markDone', error)`.
1201
+ - `onRefused(event, error)`, when given, is called once for each refusal marked done, with the hook's error, after
1202
+ `markDone` and also when `markDone` failed. It is not called for finished work, for an error that gives the event
1203
+ back (a 5xx, a later try, no `status`, the ended subscription whose void failed), with the setting off, for a
1204
+ repeat, when `tryInsert` throws, or for a bad signature. No answer waits for it, and a throw or a rejection from it
1205
+ goes to `onError('onRefused', error)` and changes neither the answer nor the store call. A failed `markDone` lets
1206
+ the claim expire, so Stripe's retry can run the event again and call `onRefused` once more.
1207
+ - It is off by default. A store without `markDone` is not called, so the event stays as `tryInsert` recorded it;
1208
+ `onRefused` is still called.
1209
+
814
1210
  ### Events dispatched
815
1211
 
816
1212
  | Stripe event | Hook called | Notes |
@@ -818,9 +1214,28 @@ eventStore: {
818
1214
  | `checkout.session.completed` | `onCheckoutCompleted` | Session re-fetched and expanded with `payment_intent.latest_charge` and `invoice` before the hook is called |
819
1215
  | `invoice.paid` | `onInvoicePaid` | Raw invoice from event data |
820
1216
  | `invoice.payment_failed` | `onInvoicePaymentFailed` | Raw invoice + `failReason` pre-extracted from the payment intent (`decline_code` or `code`) |
821
- | `customer.subscription.deleted` | `onSubscriptionDeleted` | Raw subscription from event data |
1217
+ | `customer.subscription.deleted` | `onSubscriptionDeleted` | Raw subscription from event data; then the subscription's unpaid invoices are voided (see below) |
822
1218
  | `account.updated` (connected) | `onConnectedAccountUpdated` | Raw account from event data |
823
- | All other event types | — | Silently ignored — HTTP 200 returned. Throwing for unknown events would cause Stripe to retry for up to 72 hours. |
1219
+ | All other event types | `onOtherEvent` | Raw event, run in the same claim as the hooks above, so `release`, `markDone` and `markRefusalsDone` apply to it as to them. Without `onOtherEvent`, silently ignored — HTTP 200 returned. |
1220
+
1221
+ `onOtherEvent` gets the main endpoint's events only. On the connected endpoint every event but `account.updated` is
1222
+ ignored and answered 200. The four main endpoint events in the table never reach `onOtherEvent`, also when their own
1223
+ hook is left out.
1224
+
1225
+ ### Ended subscriptions
1226
+
1227
+ When Stripe ends a subscription, its unpaid invoices stay payable: a cancel leaves them open, and when payment retries
1228
+ run out Stripe can mark the last one uncollectible, which still takes a payment. So after `onSubscriptionDeleted` the
1229
+ handler calls `invoices.voidUnpaidInvoices(subscription)`. Set `voidUnpaidInvoicesOnEnd: false` to turn this off.
1230
+
1231
+ - The hook runs first, so the app ends access even when Stripe refuses a void. The void runs even when the hook
1232
+ throws.
1233
+ - A refused void fails the event when the hook succeeded. The event is retried only if the app's event store lets
1234
+ Stripe deliver it again, for example with `release` (see "Retrying an event that failed"), and that retry runs
1235
+ `onSubscriptionDeleted` again although it had finished. With a store that keeps every event it has seen, a nightly
1236
+ job calling `voidUnpaidInvoices` is the only retry.
1237
+ - When both fail, the hook's error is thrown and the refused void goes to `onError('voidUnpaidInvoices', error)`. The
1238
+ event is given back even when the hook's error is a refusal under `markRefusalsDone`, so the retry voids again.
824
1239
 
825
1240
  ---
826
1241
 
@@ -892,6 +1307,12 @@ import {
892
1307
  } from '@apexara/stripe';
893
1308
  ```
894
1309
 
1310
+ ### Idempotency keys
1311
+
1312
+ ```typescript
1313
+ import { IdempotencyOptions } from '@apexara/stripe';
1314
+ ```
1315
+
895
1316
  ### Checkout
896
1317
 
897
1318
  ```typescript
@@ -913,6 +1334,7 @@ import {
913
1334
  CreateInvoiceSubscriptionOptions,
914
1335
  CreateInvoiceSubscriptionResult,
915
1336
  SubscriptionSyncFields,
1337
+ SubscriptionDiscount,
916
1338
  } from '@apexara/stripe';
917
1339
  ```
918
1340
 
@@ -992,7 +1414,7 @@ npm test
992
1414
  npm run test:coverage
993
1415
  ```
994
1416
 
995
- **Test stack:** Vitest with v8 coverage. Tests live in `src/tests/` and are excluded from the build output.
1417
+ **Test stack:** Vitest 4 with v8 coverage. Tests live in `src/tests/` and are excluded from the build output. Running them needs Node 20.19 or later; the library itself still runs on Node 18 (`engines`).
996
1418
 
997
1419
  **Stripe API version:** `2025-08-27.basil` — pinned in `src/client.ts`. To use a different version, pass `apiVersion` in `StripeClientConfig`.
998
1420