@ultimabase/stripe 0.0.0-first.0 → 0.0.0-stage

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 (130) hide show
  1. package/README.md +2 -6
  2. package/package.json +3 -48
  3. package/dist/accounts.d.ts +0 -9
  4. package/dist/accounts.d.ts.map +0 -1
  5. package/dist/accounts.js +0 -20
  6. package/dist/apply.d.ts +0 -26
  7. package/dist/apply.d.ts.map +0 -1
  8. package/dist/apply.js +0 -73
  9. package/dist/audit.d.ts +0 -3
  10. package/dist/audit.d.ts.map +0 -1
  11. package/dist/audit.js +0 -123
  12. package/dist/billing-gateway.d.ts +0 -158
  13. package/dist/billing-gateway.d.ts.map +0 -1
  14. package/dist/billing-gateway.js +0 -23
  15. package/dist/billing.d.ts +0 -130
  16. package/dist/billing.d.ts.map +0 -1
  17. package/dist/billing.js +0 -128
  18. package/dist/calls.d.ts +0 -61
  19. package/dist/calls.d.ts.map +0 -1
  20. package/dist/calls.js +0 -172
  21. package/dist/catalog.d.ts +0 -54
  22. package/dist/catalog.d.ts.map +0 -1
  23. package/dist/catalog.js +0 -182
  24. package/dist/credit.d.ts +0 -16
  25. package/dist/credit.d.ts.map +0 -1
  26. package/dist/credit.js +0 -18
  27. package/dist/credits.d.ts +0 -38
  28. package/dist/credits.d.ts.map +0 -1
  29. package/dist/credits.js +0 -138
  30. package/dist/customer.d.ts +0 -25
  31. package/dist/customer.d.ts.map +0 -1
  32. package/dist/customer.js +0 -88
  33. package/dist/describe.d.ts +0 -4
  34. package/dist/describe.d.ts.map +0 -1
  35. package/dist/describe.js +0 -56
  36. package/dist/duplicates.d.ts +0 -12
  37. package/dist/duplicates.d.ts.map +0 -1
  38. package/dist/duplicates.js +0 -24
  39. package/dist/fake-billing.d.ts +0 -72
  40. package/dist/fake-billing.d.ts.map +0 -1
  41. package/dist/fake-billing.js +0 -290
  42. package/dist/gateway.d.ts +0 -108
  43. package/dist/gateway.d.ts.map +0 -1
  44. package/dist/gateway.js +0 -196
  45. package/dist/index.d.ts +0 -15
  46. package/dist/index.d.ts.map +0 -1
  47. package/dist/index.js +0 -6
  48. package/dist/job-input.d.ts +0 -6
  49. package/dist/job-input.d.ts.map +0 -1
  50. package/dist/job-input.js +0 -20
  51. package/dist/jobs.d.ts +0 -16
  52. package/dist/jobs.d.ts.map +0 -1
  53. package/dist/jobs.js +0 -189
  54. package/dist/keys.d.ts +0 -10
  55. package/dist/keys.d.ts.map +0 -1
  56. package/dist/keys.js +0 -30
  57. package/dist/kinds.d.ts +0 -11
  58. package/dist/kinds.d.ts.map +0 -1
  59. package/dist/kinds.js +0 -4
  60. package/dist/models.d.ts +0 -71
  61. package/dist/models.d.ts.map +0 -1
  62. package/dist/models.js +0 -41
  63. package/dist/plugin.d.ts +0 -41
  64. package/dist/plugin.d.ts.map +0 -1
  65. package/dist/plugin.js +0 -229
  66. package/dist/portal.d.ts +0 -23
  67. package/dist/portal.d.ts.map +0 -1
  68. package/dist/portal.js +0 -66
  69. package/dist/product.d.ts +0 -57
  70. package/dist/product.d.ts.map +0 -1
  71. package/dist/product.js +0 -113
  72. package/dist/running.d.ts +0 -61
  73. package/dist/running.d.ts.map +0 -1
  74. package/dist/running.js +0 -35
  75. package/dist/sdk-billing.d.ts +0 -8
  76. package/dist/sdk-billing.d.ts.map +0 -1
  77. package/dist/sdk-billing.js +0 -200
  78. package/dist/sdk-common.d.ts +0 -13
  79. package/dist/sdk-common.d.ts.map +0 -1
  80. package/dist/sdk-common.js +0 -41
  81. package/dist/sdk-customer.d.ts +0 -9
  82. package/dist/sdk-customer.d.ts.map +0 -1
  83. package/dist/sdk-customer.js +0 -149
  84. package/dist/sdk-invoices.d.ts +0 -10
  85. package/dist/sdk-invoices.d.ts.map +0 -1
  86. package/dist/sdk-invoices.js +0 -53
  87. package/dist/sdk-recovery.d.ts +0 -5
  88. package/dist/sdk-recovery.d.ts.map +0 -1
  89. package/dist/sdk-recovery.js +0 -81
  90. package/dist/sync.d.ts +0 -8
  91. package/dist/sync.d.ts.map +0 -1
  92. package/dist/sync.js +0 -196
  93. package/dist/testing.d.ts +0 -24
  94. package/dist/testing.d.ts.map +0 -1
  95. package/dist/testing.js +0 -100
  96. package/dist/webhook.d.ts +0 -4
  97. package/dist/webhook.d.ts.map +0 -1
  98. package/dist/webhook.js +0 -73
  99. package/src/accounts.ts +0 -30
  100. package/src/apply.ts +0 -99
  101. package/src/audit.ts +0 -171
  102. package/src/billing-gateway.ts +0 -188
  103. package/src/billing.ts +0 -361
  104. package/src/calls.ts +0 -280
  105. package/src/catalog.ts +0 -327
  106. package/src/credit.ts +0 -36
  107. package/src/credits.ts +0 -206
  108. package/src/customer.ts +0 -113
  109. package/src/describe.ts +0 -76
  110. package/src/duplicates.ts +0 -45
  111. package/src/fake-billing.ts +0 -388
  112. package/src/gateway.ts +0 -333
  113. package/src/index.ts +0 -35
  114. package/src/job-input.ts +0 -24
  115. package/src/jobs.ts +0 -230
  116. package/src/keys.ts +0 -40
  117. package/src/kinds.ts +0 -15
  118. package/src/models.ts +0 -107
  119. package/src/plugin.ts +0 -307
  120. package/src/portal.ts +0 -95
  121. package/src/product.ts +0 -203
  122. package/src/running.ts +0 -104
  123. package/src/sdk-billing.ts +0 -220
  124. package/src/sdk-common.ts +0 -57
  125. package/src/sdk-customer.ts +0 -203
  126. package/src/sdk-invoices.ts +0 -81
  127. package/src/sdk-recovery.ts +0 -93
  128. package/src/sync.ts +0 -246
  129. package/src/testing.ts +0 -135
  130. package/src/webhook.ts +0 -100
package/src/describe.ts DELETED
@@ -1,76 +0,0 @@
1
- // A catalog step in a line, as `applyStripeCatalog` prints its plan.
2
- import type { CatalogStep } from './catalog.ts'
3
- import type { Recurring, StripePrice } from './gateway.ts'
4
-
5
- /** An amount in the currency's smallest unit, as `9.90 EUR`. */
6
- const formatAmount = (amount: number, currency: string): string => {
7
- const digits = Number(
8
- new Intl.NumberFormat('en', {
9
- style: 'currency',
10
- currency,
11
- }).resolvedOptions().maximumFractionDigits,
12
- )
13
- return `${(amount / 10 ** digits).toFixed(digits)} ${currency.toUpperCase()}`
14
- }
15
-
16
- const often = (recurring: Recurring | null): string =>
17
- recurring === null
18
- ? 'once'
19
- : recurring.count === 1
20
- ? `every ${recurring.every}`
21
- : `every ${String(recurring.count)} ${recurring.every}s`
22
-
23
- const billing = (
24
- amount: number | null,
25
- currency: string,
26
- recurring: Recurring | null,
27
- ): string =>
28
- `${amount === null ? 'no amount' : formatAmount(amount, currency)} ${often(recurring)}`
29
-
30
- const priceName = (price: StripePrice): string =>
31
- price.lookupKey === null ? price.id : `${price.lookupKey} (${price.id})`
32
-
33
- /** What an update changes of a product. */
34
- const productChanges = (
35
- step: Extract<CatalogStep, { readonly kind: 'updateProduct' }>,
36
- ): string => {
37
- const { product, was } = step
38
- return [
39
- ...(was.active ? [] : ['restore it']),
40
- ...(was.name === product.name
41
- ? []
42
- : [`rename it from "${was.name}" to "${product.name}"`]),
43
- ...(was.taxCode === product.taxCode
44
- ? []
45
- : [`set its tax code to ${product.taxCode ?? 'none'}`]),
46
- ].join(', ')
47
- }
48
-
49
- /** The step in a line. */
50
- export const describeStep = (step: CatalogStep, currency: string): string => {
51
- if (step.kind === 'createProduct') {
52
- return `create the product ${step.product.key}: "${step.product.name}"`
53
- }
54
- if (step.kind === 'updateProduct') {
55
- return `update the product ${step.product.key}: ${productChanges(step)}`
56
- }
57
- if (step.kind === 'archiveProduct') {
58
- return `archive the product "${step.was.name}" (${step.was.id})`
59
- }
60
- if (step.kind === 'createPrice') {
61
- const { price, replaces } = step
62
- const line = `create the price ${price.lookupKey}: ${billing(price.amount, currency, price.recurring)}`
63
- return replaces === null
64
- ? line
65
- : `${line}, replacing ${replaces.id} (${billing(replaces.amount, replaces.currency, replaces.recurring)})`
66
- }
67
- if (step.kind === 'updatePrice') {
68
- return `update the nickname and metadata of the price ${priceName(step.was)}`
69
- }
70
- if (step.kind === 'archivePrice') {
71
- return `archive the price ${priceName(step.was)}`
72
- }
73
- return step.id === null
74
- ? 'create the customer portal configuration'
75
- : `update the customer portal configuration ${step.id}`
76
- }
package/src/duplicates.ts DELETED
@@ -1,45 +0,0 @@
1
- // A payer's second subscription, with `oneSubscription` (D-373 point 6): a
2
- // sync finds it, and a job ends it at once and refunds it. Its events then
3
- // sync the payer again.
4
- import type { Job } from '@ultimabase/jobs'
5
- import { defineJob } from '@ultimabase/jobs'
6
- import type { StripeSubscription } from './billing-gateway.ts'
7
- import { liveStatuses } from './billing-gateway.ts'
8
- import { strings } from './job-input.ts'
9
- import { stripeOf } from './running.ts'
10
-
11
- /**
12
- * The live subscriptions beyond the first: the oldest stays. One still
13
- * `incomplete` is not paid, and Stripe expires it within a day.
14
- */
15
- export const duplicatesOf = (
16
- subscriptions: readonly StripeSubscription[],
17
- ): readonly StripeSubscription[] =>
18
- subscriptions
19
- .filter(({ status }) => liveStatuses.includes(status))
20
- .toSorted(
21
- (one, other) =>
22
- one.startedAt.getTime() - other.startedAt.getTime() ||
23
- one.id.localeCompare(other.id),
24
- )
25
- .slice(1)
26
-
27
- /** Ends a second subscription at once and refunds it: the payer paid twice. */
28
- export const duplicateJob: Job<
29
- 'stripe.duplicate',
30
- { readonly subscription: string }
31
- > = defineJob({
32
- name: 'stripe.duplicate',
33
- input: strings('subscription'),
34
- // Each sync until it ends finds it again: one run at a time.
35
- key: ({ subscription }) => subscription,
36
- run: async ({ input, logger }) => {
37
- await stripeOf('stripe.duplicate').gateway.cancelAndRefund(
38
- input.subscription,
39
- )
40
- logger.error(
41
- input,
42
- 'A payer’s second subscription was canceled and refunded.',
43
- )
44
- },
45
- })
@@ -1,388 +0,0 @@
1
- // The fake account's payers (D-371 point 8): customers, Checkouts a test
2
- // pays, subscriptions and payments, and the thin events each change sends
3
- // to the webhook, signed as Stripe signs them.
4
- import { Stripe } from 'stripe'
5
- import type {
6
- BillingGateway,
7
- CheckoutWrite,
8
- RecoveryGateway,
9
- CustomerProfile,
10
- PortalWrite,
11
- StripeInvoice,
12
- StripePayment,
13
- StripeSubscription,
14
- } from './billing-gateway.ts'
15
- import { Missing } from './billing-gateway.ts'
16
- import type { StripePrice } from './gateway.ts'
17
-
18
- /** A customer of the fake account. */
19
- export interface FakeCustomer {
20
- readonly id: string
21
- readonly profile: CustomerProfile
22
- readonly deleted: boolean
23
- /** Its default card: the one a renewal charges (D-380). */
24
- readonly card: string | null
25
- }
26
-
27
- /** A Checkout of the fake account. */
28
- export interface FakeCheckout extends CheckoutWrite {
29
- readonly id: string
30
- readonly url: string
31
- readonly status: 'open' | 'complete' | 'expired'
32
- }
33
-
34
- /** What the fake account holds of its payers, and what a test does at Stripe. */
35
- export interface FakeBilling {
36
- readonly webhookSecret: string
37
- readonly customers: Map<string, FakeCustomer>
38
- readonly checkouts: Map<string, FakeCheckout>
39
- readonly subscriptions: Map<string, StripeSubscription>
40
- readonly payments: Map<string, StripePayment>
41
- /** The paid invoices of subscriptions, each period's. */
42
- readonly invoices: Map<string, StripeInvoice>
43
- /** Each portal session opened, in order. */
44
- readonly portalSessions: PortalWrite[]
45
- /** The subscriptions whose latest payment the plugin refunded. */
46
- readonly subscriptionRefunds: Set<string>
47
- /**
48
- * Pays an open Checkout, by its URL, as its payer would; gives its id.
49
- * `free`: a promotion code took the whole price, and Stripe makes no
50
- * payment for a purchase.
51
- */
52
- readonly pay: (url: string, options?: { readonly free?: boolean }) => string
53
- /** Changes a subscription, as the portal or a renewal would. */
54
- readonly update: (
55
- id: string,
56
- changes: Partial<Omit<StripeSubscription, 'id'>>,
57
- ) => void
58
- /** Pays a subscription's next period, as Stripe renews it; gives its invoice. */
59
- readonly renew: (id: string) => string
60
- /** Refunds a payment or an invoice, all of it by default. */
61
- readonly refund: (id: string, amount?: number) => void
62
- readonly loseDispute: (id: string) => void
63
- /** Deletes a customer, as the dashboard would. */
64
- readonly deleteCustomer: (id: string) => void
65
- /** Posts each event sent since the last call to the application at `url`. */
66
- readonly deliver: (url: string, path?: string) => Promise<void>
67
- }
68
-
69
- /** A thin event's body, as Stripe sends it to an event destination. */
70
- export const thinEvent = (event: {
71
- readonly id?: string
72
- /** Its v1 type: `customer.subscription.updated`. */
73
- readonly type: string
74
- /** Its related object: `{ id: 'sub_1', type: 'subscription' }`. */
75
- readonly object: { readonly id: string; readonly type: string }
76
- readonly livemode?: boolean
77
- }): string =>
78
- JSON.stringify({
79
- id: event.id ?? `evt_${crypto.randomUUID().replaceAll('-', '')}`,
80
- object: 'v2.core.event',
81
- type: `v1.${event.type}`,
82
- livemode: event.livemode ?? false,
83
- created: new Date().toISOString(),
84
- related_object: { ...event.object, url: `/v1/${event.object.id}` },
85
- })
86
-
87
- /** Posts `payload` to the webhook of the application at `url`, signed. */
88
- export const postEvent = async (
89
- url: string,
90
- payload: string,
91
- options: { readonly secret: string; readonly path?: string | undefined },
92
- ): Promise<Response> =>
93
- fetch(`${url}${options.path ?? '/webhooks/stripe'}`, {
94
- method: 'POST',
95
- headers: {
96
- 'content-type': 'application/json',
97
- 'stripe-signature': Stripe.webhooks.generateTestHeaderString({
98
- payload,
99
- secret: options.secret,
100
- }),
101
- },
102
- body: payload,
103
- })
104
-
105
- const found = <T>(map: ReadonlyMap<string, T>, id: string): T => {
106
- const record = map.get(id)
107
- if (record === undefined) throw new Missing(id)
108
- return record
109
- }
110
-
111
- const day = 24 * 60 * 60 * 1000
112
- const days: Readonly<Record<string, number>> = {
113
- day: 1,
114
- week: 7,
115
- month: 30,
116
- year: 365,
117
- }
118
- const periodOf = ({ every, everyCount }: StripeSubscription): number =>
119
- (days[every] ?? 30) * everyCount * day
120
-
121
- /** The fake's billing, over its catalog's prices. */
122
- export function fakeBilling(
123
- prices: ReadonlyMap<string, StripePrice>,
124
- newId: (prefix: string) => string,
125
- ): {
126
- readonly gateway: BillingGateway & RecoveryGateway
127
- readonly fake: FakeBilling
128
- } {
129
- const customers = new Map<string, FakeCustomer>()
130
- const keys = new Map<string, string>()
131
- const checkouts = new Map<string, FakeCheckout>()
132
- const subscriptions = new Map<string, StripeSubscription>()
133
- const payments = new Map<string, StripePayment>()
134
- const invoices = new Map<string, StripeInvoice>()
135
- const portalSessions: PortalWrite[] = []
136
- const subscriptionRefunds = new Set<string>()
137
- const sent: string[] = []
138
- /** Each event's object and time, which Stripe lists for 30 days. */
139
- const listed: { readonly id: string; readonly type: string; at: Date }[] = []
140
- const send = (type: string, id: string, object: string) => {
141
- sent.push(thinEvent({ type, object: { id, type: object } }))
142
- listed.push({ id, type: object, at: new Date() })
143
- }
144
- const ownerOf = (type: string, id: string): string | null => {
145
- const maps: Record<string, ReadonlyMap<string, { customerId: string }>> = {
146
- 'checkout.session': checkouts,
147
- subscription: subscriptions,
148
- payment_intent: payments,
149
- invoice: invoices,
150
- }
151
- if (type === 'customer') return customers.has(id) ? id : null
152
- return maps[type]?.get(id)?.customerId ?? null
153
- }
154
- const priceOf = (lookupKey: string): StripePrice => {
155
- const held = [...prices.values()].find(
156
- (one) => one.active && one.lookupKey === lookupKey,
157
- )
158
- if (held === undefined) throw new Error(`No price is ${lookupKey}.`)
159
- return held
160
- }
161
- const live = (id: string): FakeCustomer => {
162
- const customer = found(customers, id)
163
- if (customer.deleted) throw new Missing(id)
164
- return customer
165
- }
166
- /** Bills a subscription's period, which ends at `end`. */
167
- const bill = (subscription: StripeSubscription, end: Date): string => {
168
- const id = newId('in')
169
- const { product, price, quantity, amount, customerId } = subscription
170
- const periods = [{ product, price, quantity, end }]
171
- const refunds = { refunded: 0, disputeLost: false }
172
- invoices.set(id, { id, customerId, periods, amount, ...refunds })
173
- send('invoice.paid', id, 'invoice')
174
- return id
175
- }
176
- const subscribe = (checkout: FakeCheckout, price: StripePrice): string => {
177
- const id = newId('sub')
178
- const now = Date.now()
179
- const { every = 'month', count = 1 } = price.recurring ?? {}
180
- const trialEnd =
181
- checkout.trialDays === null
182
- ? null
183
- : new Date(now + checkout.trialDays * day)
184
- const [product = '', name = ''] = checkout.lookupKey.split('.')
185
- subscriptions.set(id, {
186
- id,
187
- customerId: checkout.customerId,
188
- product,
189
- price: name,
190
- status: trialEnd === null ? 'active' : 'trialing',
191
- quantity: checkout.quantity,
192
- amount: (price.amount ?? 0) * checkout.quantity,
193
- every,
194
- everyCount: count,
195
- currentPeriodEnd:
196
- trialEnd ?? new Date(now + (days[every] ?? 30) * count * day),
197
- cancelAt: null,
198
- canceledAt: null,
199
- trialEnd,
200
- startedAt: new Date(now),
201
- scheduled: null,
202
- card: newId('pm'),
203
- })
204
- send('customer.subscription.created', id, 'subscription')
205
- const created = found(subscriptions, id)
206
- if (trialEnd === null) bill(created, created.currentPeriodEnd)
207
- return id
208
- }
209
- const charge = (
210
- checkout: FakeCheckout,
211
- price: StripePrice,
212
- free: boolean,
213
- ): string => {
214
- // A free Checkout stands for its payment, which Stripe does not make.
215
- const id = free ? checkout.id : newId('pi')
216
- payments.set(id, {
217
- id,
218
- customerId: checkout.customerId,
219
- product: checkout.product,
220
- quantity: checkout.quantity,
221
- amount: free ? 0 : (price.amount ?? 0) * checkout.quantity,
222
- refunded: 0,
223
- disputeLost: false,
224
- paidAt: new Date(),
225
- receiptUrl: free ? null : `https://pay.stripe.test/receipts/${id}`,
226
- })
227
- if (!free) send('payment_intent.succeeded', id, 'payment_intent')
228
- return id
229
- }
230
- const gateway: BillingGateway & RecoveryGateway = {
231
- createCustomer: async (profile, idempotencyKey) => {
232
- const held = keys.get(idempotencyKey)
233
- if (held !== undefined) return held
234
- const id = newId('cus')
235
- customers.set(id, { id, profile, deleted: false, card: null })
236
- keys.set(idempotencyKey, id)
237
- return id
238
- },
239
- updateCustomer: async (id, profile) => {
240
- customers.set(id, { ...live(id), profile })
241
- },
242
- deleteCustomer: async (id) => {
243
- fake.deleteCustomer(id)
244
- },
245
- readCustomer: async (id, options) => {
246
- const customer = customers.get(id)
247
- if (customer === undefined || customer.deleted) {
248
- return { deleted: true, subscriptions: [], payments: [], invoices: [] }
249
- }
250
- const own = <T extends { readonly customerId: string }>(
251
- map: ReadonlyMap<string, T>,
252
- ) => [...map.values()].filter((one) => one.customerId === id)
253
- return {
254
- deleted: false,
255
- subscriptions: own(subscriptions),
256
- // Stripe lists a free Checkout only when asked to.
257
- payments: own(payments).filter(
258
- (one) => options?.free === true || !one.id.startsWith('cs_'),
259
- ),
260
- invoices: options?.invoices === true ? own(invoices) : [],
261
- }
262
- },
263
- customerOf: async (type, id) => ownerOf(type, id),
264
- openCheckout: async (checkout) => {
265
- live(checkout.customerId)
266
- priceOf(checkout.lookupKey)
267
- const id = newId('cs')
268
- const url = `https://checkout.stripe.test/${id}`
269
- checkouts.set(id, { ...checkout, id, url, status: 'open' })
270
- return url
271
- },
272
- expireCheckouts: async (customerId) => {
273
- live(customerId)
274
- for (const checkout of checkouts.values()) {
275
- if (checkout.customerId === customerId && checkout.status === 'open') {
276
- checkouts.set(checkout.id, { ...checkout, status: 'expired' })
277
- }
278
- }
279
- },
280
- checkoutCustomer: async (id) => checkouts.get(id)?.customerId ?? null,
281
- openPortal: async (portal) => {
282
- live(portal.customerId)
283
- portalSessions.push(portal)
284
- return `https://billing.stripe.test/${newId('bps')}`
285
- },
286
- moveCard: async ({ id, customerId, card }) => {
287
- customers.set(customerId, { ...live(customerId), card })
288
- fake.update(id, { card: null })
289
- },
290
- cancelAndRefund: async (id) => {
291
- const held = found(subscriptions, id)
292
- if (held.status !== 'canceled') {
293
- const ended = { status: 'canceled', canceledAt: new Date() }
294
- subscriptions.set(id, { ...held, ...ended })
295
- send('customer.subscription.deleted', id, 'subscription')
296
- }
297
- subscriptionRefunds.add(id)
298
- },
299
- changedSince: async (since) => {
300
- const changed = new Map<string, Date>()
301
- for (const { id, type, at } of listed) {
302
- const customer = ownerOf(type, id)
303
- if (customer !== null && at > since) changed.set(customer, at)
304
- }
305
- return changed
306
- },
307
- }
308
- const fake: FakeBilling = {
309
- webhookSecret: `whsec_fake_${crypto.randomUUID()}`,
310
- customers,
311
- checkouts,
312
- subscriptions,
313
- payments,
314
- invoices,
315
- portalSessions,
316
- subscriptionRefunds,
317
- pay: (url, options) => {
318
- const checkout = [...checkouts.values()].find((one) => one.url === url)
319
- if (checkout?.status !== 'open') throw new Error(`${url} is not open.`)
320
- const price = priceOf(checkout.lookupKey)
321
- checkouts.set(checkout.id, { ...checkout, status: 'complete' })
322
- const id =
323
- checkout.mode === 'subscription'
324
- ? subscribe(checkout, price)
325
- : charge(checkout, price, options?.free ?? false)
326
- send('checkout.session.completed', checkout.id, 'checkout.session')
327
- return id
328
- },
329
- update: (id, changes) => {
330
- subscriptions.set(id, { ...found(subscriptions, id), ...changes })
331
- send('customer.subscription.updated', id, 'subscription')
332
- },
333
- renew: (id) => {
334
- const held = found(subscriptions, id)
335
- const start = Math.max(held.currentPeriodEnd.getTime(), Date.now())
336
- const end = new Date(start + periodOf(held))
337
- const renewed = { ...held, status: 'active', currentPeriodEnd: end }
338
- subscriptions.set(id, renewed)
339
- send('customer.subscription.updated', id, 'subscription')
340
- return bill(renewed, end)
341
- },
342
- refund: (id, amount) => {
343
- const map: Map<string, StripePayment | StripeInvoice> = invoices.has(id)
344
- ? invoices
345
- : payments
346
- const paid = found(map, id)
347
- const refunded = paid.refunded + (amount ?? paid.amount)
348
- map.set(id, { ...paid, refunded })
349
- send(
350
- 'charge.refunded',
351
- id,
352
- invoices.has(id) ? 'invoice' : 'payment_intent',
353
- )
354
- },
355
- loseDispute: (id) => {
356
- const map: Map<string, StripePayment | StripeInvoice> = invoices.has(id)
357
- ? invoices
358
- : payments
359
- map.set(id, { ...found(map, id), disputeLost: true })
360
- send(
361
- 'charge.dispute.closed',
362
- id,
363
- invoices.has(id) ? 'invoice' : 'payment_intent',
364
- )
365
- },
366
- deleteCustomer: (id) => {
367
- const customer = customers.get(id)
368
- if (customer === undefined || customer.deleted) return
369
- customers.set(id, { ...customer, deleted: true })
370
- for (const one of subscriptions.values()) {
371
- if (one.customerId === id && one.status !== 'canceled') {
372
- subscriptions.set(one.id, { ...one, status: 'canceled' })
373
- }
374
- }
375
- send('customer.deleted', id, 'customer')
376
- },
377
- deliver: async (url, path) => {
378
- for (const payload of sent.splice(0)) {
379
- const secret = fake.webhookSecret
380
- const response = await postEvent(url, payload, { secret, path })
381
- if (!response.ok) {
382
- throw new Error(`The webhook answered ${String(response.status)}.`)
383
- }
384
- }
385
- },
386
- }
387
- return { gateway, fake }
388
- }