@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/product.ts DELETED
@@ -1,203 +0,0 @@
1
- // `defineProduct` (D-372): what an application sells, either a subscription
2
- // with its recurring prices or a one-time product with the credits it gives.
3
- // The catalog writes it to Stripe; the product's key never changes.
4
- import { Refused } from 'ultimabase'
5
- import type { CreditAmount } from './credit.ts'
6
- import { checkKey, ownKeys, whereOf } from './keys.ts'
7
-
8
- /** How often a recurring price bills. */
9
- export type Every = 'day' | 'week' | 'month' | 'year'
10
-
11
- /** A subscription's price, billed every `everyCount` (1 by default) `every`. */
12
- export interface RecurringPrice {
13
- /** In the currency's smallest unit: `9_90` is 9.90 €. */
14
- readonly amount: number
15
- readonly every: Every
16
- readonly everyCount?: number
17
- /** The credits each paid period gives (D-377 point 4). */
18
- readonly gives?: readonly CreditAmount[]
19
- }
20
-
21
- /** A one-time product's price. */
22
- export interface OneTimePrice {
23
- /** In the currency's smallest unit. */
24
- readonly amount: number
25
- }
26
-
27
- /** A subscription, with its recurring prices by name. */
28
- export interface SubscriptionProduct<
29
- K extends string = string,
30
- P extends string = string,
31
- > {
32
- /** The product's name in the application, never changed. */
33
- readonly key: K
34
- /** What Checkout and the invoices show. */
35
- readonly name: string
36
- /** Its Stripe Tax code, `txcd_…`. */
37
- readonly taxCode?: string
38
- readonly prices: { readonly [N in P]: RecurringPrice }
39
- }
40
-
41
- /** A product paid once, and the credits it gives. */
42
- export interface OneTimeProduct<K extends string = string> {
43
- readonly key: K
44
- readonly name: string
45
- readonly taxCode?: string
46
- readonly price: OneTimePrice
47
- readonly gives: readonly CreditAmount[]
48
- }
49
-
50
- /** A product of the catalog. */
51
- export type Product = SubscriptionProduct | OneTimeProduct
52
-
53
- /** Stripe bills at most every three years. */
54
- const longest: Readonly<Record<Every, number>> = {
55
- day: 1095,
56
- week: 156,
57
- month: 36,
58
- year: 3,
59
- }
60
- const productKeys = ['key', 'name', 'taxCode', 'prices', 'price', 'gives']
61
-
62
- /** Refuses an amount that is not a positive integer. */
63
- function checkAmount(where: string, amount: unknown): void {
64
- if (!Number.isSafeInteger(amount) || Number(amount) <= 0) {
65
- throw new Refused(
66
- `${where}: the amount ${String(amount)} is not a positive integer, in the currency's smallest unit.`,
67
- )
68
- }
69
- }
70
-
71
- /** Refuses a recurring price Stripe would refuse; returns its interval. */
72
- function checkRecurring(where: string, price: unknown): string {
73
- ownKeys(where, price, ['amount', 'every', 'everyCount', 'gives'])
74
- checkAmount(where, Reflect.get(price, 'amount'))
75
- checkGives(where, Reflect.get(price, 'gives') ?? [])
76
- const every: unknown = Reflect.get(price, 'every')
77
- const most = Object.entries(longest).find(([name]) => name === every)?.[1]
78
- if (most === undefined) {
79
- throw new Refused(`${where}: every is 'day', 'week', 'month' or 'year'.`)
80
- }
81
- const count: unknown = Reflect.get(price, 'everyCount') ?? 1
82
- if (
83
- !Number.isSafeInteger(count) ||
84
- Number(count) < 1 ||
85
- Number(count) > most
86
- ) {
87
- throw new Refused(
88
- `${where}: everyCount is an integer from 1 to ${String(most)}.`,
89
- )
90
- }
91
- return `${String(count)} ${String(every)}`
92
- }
93
-
94
- /** Refuses a subscription's prices: none, a bad one, or two of one interval. */
95
- function checkPrices(where: string, prices: unknown): void {
96
- if (typeof prices !== 'object' || prices === null) {
97
- throw new Refused(`${where}: prices holds the recurring prices by name.`)
98
- }
99
- const names = Object.keys(prices)
100
- if (names.length === 0) {
101
- throw new Refused(`${where}: prices holds at least one price.`)
102
- }
103
- // The customer portal takes one price per interval of a product.
104
- const intervals = new Map<string, string>()
105
- for (const name of names) {
106
- checkKey(where, name)
107
- const price: unknown = Reflect.get(prices, name)
108
- const interval = checkRecurring(`${where}.${name}`, price)
109
- const other = intervals.get(interval)
110
- if (other !== undefined) {
111
- throw new Refused(
112
- `${where}: ${other} and ${name} both bill every ${interval}; a product has one price per interval.`,
113
- )
114
- }
115
- intervals.set(interval, name)
116
- }
117
- }
118
-
119
- /** Refuses what a one-time product gives: one credit twice, or a bad one. */
120
- function checkGives(where: string, gives: unknown): void {
121
- if (!Array.isArray(gives)) {
122
- throw new Refused(`${where}: gives lists credits, as [blueGems(500)].`)
123
- }
124
- const given = new Set<unknown>()
125
- for (const item of gives) {
126
- const credit: unknown =
127
- typeof item === 'object' && item !== null
128
- ? Reflect.get(item, 'credit')
129
- : undefined
130
- if (typeof credit !== 'string') {
131
- throw new Refused(`${where}: gives lists credits, as [blueGems(500)].`)
132
- }
133
- checkAmount(`${where} gives ${credit}`, Reflect.get(Object(item), 'amount'))
134
- if (given.has(credit)) {
135
- throw new Refused(`${where}: gives ${credit} twice.`)
136
- }
137
- given.add(credit)
138
- }
139
- }
140
-
141
- /** A subscription and its recurring prices (D-372). */
142
- export function defineProduct<
143
- const K extends string,
144
- const P extends string,
145
- >(definition: {
146
- readonly key: K
147
- readonly name: string
148
- readonly taxCode?: string
149
- readonly prices: { readonly [N in P]: RecurringPrice }
150
- }): SubscriptionProduct<K, P>
151
- /** A product paid once, and the credits it gives (D-372). */
152
- export function defineProduct<const K extends string>(definition: {
153
- readonly key: K
154
- readonly name: string
155
- readonly taxCode?: string
156
- readonly price: OneTimePrice
157
- readonly gives?: readonly CreditAmount[]
158
- }): OneTimeProduct<K>
159
- export function defineProduct(definition: {
160
- readonly key: string
161
- readonly name: string
162
- readonly taxCode?: string
163
- readonly prices?: Readonly<Record<string, RecurringPrice>>
164
- readonly price?: OneTimePrice
165
- readonly gives?: readonly CreditAmount[]
166
- }): Product {
167
- ownKeys('defineProduct', definition, productKeys)
168
- checkKey('defineProduct', definition.key)
169
- const where = whereOf('defineProduct', definition)
170
- const { key, name, taxCode, prices, price } = definition
171
- if (typeof name !== 'string' || name.trim() === '') {
172
- throw new Refused(`${where}: name is what Checkout and the invoices show.`)
173
- }
174
- if (taxCode !== undefined && typeof taxCode !== 'string') {
175
- throw new Refused(
176
- `${where}: taxCode is a Stripe Tax code, as txcd_10000000.`,
177
- )
178
- }
179
- const tax = taxCode === undefined ? {} : { taxCode }
180
- if ((prices === undefined) === (price === undefined)) {
181
- throw new Refused(
182
- `${where}: a product has either prices, recurring, or one price, paid once.`,
183
- )
184
- }
185
- if (price === undefined) {
186
- if (definition.gives !== undefined) {
187
- throw new Refused(`${where}: gives goes with a one-time price.`)
188
- }
189
- checkPrices(where, prices)
190
- return Object.freeze({ key, name, ...tax, prices: { ...prices } })
191
- }
192
- ownKeys(where, price, ['amount'])
193
- checkAmount(where, price.amount)
194
- const gives = definition.gives ?? []
195
- checkGives(where, gives)
196
- return Object.freeze({
197
- key,
198
- name,
199
- ...tax,
200
- price: { amount: price.amount },
201
- gives: [...gives],
202
- })
203
- }
package/src/running.ts DELETED
@@ -1,104 +0,0 @@
1
- // The running plugin's state, which its server calls and jobs read: one
2
- // application runs at a time in a realm.
3
- import type { Stripe } from 'stripe'
4
- import type { Logger, QueryOptions } from 'ultimabase'
5
- import type { Gateway } from './accounts.ts'
6
- import type { CustomerProfile } from './billing-gateway.ts'
7
- import { unavailable } from './billing-gateway.ts'
8
- import type { Catalog } from './catalog.ts'
9
- import type { Product } from './product.ts'
10
-
11
- /** A row as the plugin reads it, from a model it does not type. */
12
- export type Row = { readonly id: string; readonly [field: string]: unknown }
13
-
14
- /** The queries the plugin sends to the application's models. */
15
- export interface Rows {
16
- findUnique(args: object, options: QueryOptions): Promise<Row | null>
17
- findMany(args: object, options: QueryOptions): Promise<readonly Row[]>
18
- create(args: object, options: QueryOptions): Promise<Row>
19
- update(args: object, options: QueryOptions): Promise<Row>
20
- upsert(args: object, options: QueryOptions): Promise<Row>
21
- updateManyAndReturn(
22
- args: object,
23
- options: QueryOptions,
24
- ): Promise<readonly Row[]>
25
- groupBy(
26
- args: object,
27
- options: QueryOptions,
28
- ): Promise<readonly Readonly<Record<string, unknown>>[]>
29
- }
30
-
31
- const methods = [
32
- 'findUnique',
33
- 'findMany',
34
- 'create',
35
- 'update',
36
- 'upsert',
37
- 'updateManyAndReturn',
38
- 'groupBy',
39
- ]
40
-
41
- const isRows = (queries: object): queries is Rows =>
42
- methods.every((name) => typeof Reflect.get(queries, name) === 'function')
43
-
44
- /** A model's queries, as the plugin sends them. */
45
- export function rowsOf(queries: object): Rows {
46
- if (isRows(queries)) return queries
47
- throw new TypeError('A model’s queries were expected.')
48
- }
49
-
50
- /** A model the plugin writes, with its payer's model. */
51
- export interface Billing {
52
- readonly name: string
53
- readonly queries: Rows
54
- /** The payer's or owner's model: its name and queries. */
55
- readonly payer: { readonly name: string; readonly queries: Rows }
56
- }
57
-
58
- /** What the plugin holds while the application runs. */
59
- export interface Running {
60
- /** `undefined` without keys: every call throws `PAYMENT_UNAVAILABLE`. */
61
- readonly stripe:
62
- | {
63
- readonly gateway: Gateway
64
- /** Verifies the webhook's events; it reaches no network. */
65
- readonly client: Stripe
66
- readonly webhook: string
67
- readonly live: boolean
68
- }
69
- | undefined
70
- readonly catalog: Catalog
71
- readonly products: ReadonlyMap<string, Product>
72
- readonly customer: ((payer: never) => CustomerProfile) | undefined
73
- readonly oneSubscription: boolean
74
- readonly subscription: Billing | undefined
75
- readonly purchase: Billing | undefined
76
- readonly balance: Billing | undefined
77
- readonly history: Billing | undefined
78
- readonly logger: Logger
79
- /** The managed portal configuration's id, once read. */
80
- portal: string | null | undefined
81
- }
82
-
83
- let running: Running | undefined
84
-
85
- export const useRunning = (state: Running | undefined): void => {
86
- running = state
87
- }
88
-
89
- /** The running plugin; a call before the application starts is a bug. */
90
- export function runningOf(entry: string): Running {
91
- if (running === undefined) {
92
- throw new Error(
93
- `${entry} runs while an application with stripePlugin() runs.`,
94
- )
95
- }
96
- return running
97
- }
98
-
99
- /** The gateway, or `PAYMENT_UNAVAILABLE` without keys (D-371). */
100
- export function stripeOf(entry: string): NonNullable<Running['stripe']> {
101
- const { stripe } = runningOf(entry)
102
- if (stripe === undefined) throw unavailable()
103
- return stripe
104
- }
@@ -1,220 +0,0 @@
1
- // The billing gateway over Stripe's API: what `gatewayOf` gives a real
2
- // secret key. Stripe's errors become the plugin's: `PAYMENT_UNAVAILABLE`
3
- // when Stripe cannot answer, `Missing` for an object it does not hold.
4
- import type { Stripe } from 'stripe'
5
- import type {
6
- BillingGateway,
7
- CustomerProfile,
8
- PortalFlow,
9
- } from './billing-gateway.ts'
10
- import { Missing } from './billing-gateway.ts'
11
- import { managedBy } from './gateway.ts'
12
- import type { Ref } from './sdk-common.ts'
13
- import { all, guarded, refOf } from './sdk-common.ts'
14
- import { gone, stateOf } from './sdk-customer.ts'
15
- const profileParams = (profile: CustomerProfile) => ({
16
- ...(profile.email != null && { email: profile.email }),
17
- ...(profile.name != null && { name: profile.name }),
18
- ...(profile.locale != null && { preferred_locales: [profile.locale] }),
19
- })
20
- /** The customer an object belongs to, read from Stripe. */
21
- export async function ownerOf(
22
- client: Stripe,
23
- type: string,
24
- id: string,
25
- ): Promise<Ref> {
26
- switch (type) {
27
- case 'customer':
28
- return id
29
- case 'checkout.session':
30
- return (await client.checkout.sessions.retrieve(id)).customer
31
- case 'subscription':
32
- return (await client.subscriptions.retrieve(id)).customer
33
- case 'subscription_schedule':
34
- return (await client.subscriptionSchedules.retrieve(id)).customer
35
- case 'invoice':
36
- return (await client.invoices.retrieve(id)).customer
37
- case 'payment_intent':
38
- return (await client.paymentIntents.retrieve(id)).customer
39
- case 'charge':
40
- return (await client.charges.retrieve(id)).customer
41
- case 'dispute': {
42
- const { charge } = await client.disputes.retrieve(id)
43
- const chargeId = refOf(charge)
44
- return chargeId === null
45
- ? null
46
- : (await client.charges.retrieve(chargeId)).customer
47
- }
48
- default:
49
- return null
50
- }
51
- }
52
-
53
- /** The active price of a lookup key, or a bug: the catalog was not applied. */
54
- async function priceId(client: Stripe, lookupKey: string): Promise<string> {
55
- const listed = await client.prices.list({
56
- lookup_keys: [lookupKey],
57
- active: true,
58
- limit: 1,
59
- })
60
- const [price] = listed.data
61
- if (price === undefined) {
62
- throw new Error(
63
- `Stripe holds no active price ${lookupKey}: apply the catalog.`,
64
- )
65
- }
66
- return price.id
67
- }
68
-
69
- async function flowOf(
70
- client: Stripe,
71
- flow: PortalFlow,
72
- returnUrl: string,
73
- ): Promise<Stripe.BillingPortal.SessionCreateParams.FlowData | undefined> {
74
- const after = {
75
- type: 'redirect' as const,
76
- redirect: { return_url: returnUrl },
77
- }
78
- if (flow.kind === 'cancel') {
79
- return {
80
- type: 'subscription_cancel',
81
- subscription_cancel: { subscription: flow.subscriptionId },
82
- after_completion: after,
83
- }
84
- }
85
- if (flow.kind === 'home') return undefined
86
- const subscription = await client.subscriptions.retrieve(flow.subscriptionId)
87
- const [item] = subscription.items.data
88
- if (item === undefined) throw new Error('The subscription has no item.')
89
- // The quantity is kept (D-373 point 8).
90
- const price = await priceId(client, flow.lookupKey)
91
- return {
92
- type: 'subscription_update_confirm',
93
- subscription_update_confirm: {
94
- subscription: flow.subscriptionId,
95
- items: [{ id: item.id, price, quantity: item.quantity ?? 1 }],
96
- },
97
- after_completion: after,
98
- }
99
- }
100
- /** The billing gateway over Stripe's API. */
101
- export const sdkBilling = (client: Stripe): BillingGateway => ({
102
- createCustomer: async (profile, idempotencyKey) =>
103
- guarded('customer', async () => {
104
- const params = { ...profileParams(profile), metadata: { managedBy } }
105
- const created = await client.customers.create(params, {
106
- idempotencyKey,
107
- })
108
- return created.id
109
- }),
110
- updateCustomer: async (id, profile) =>
111
- guarded(id, async () => {
112
- await client.customers.update(id, profileParams(profile))
113
- }),
114
- deleteCustomer: async (id) => {
115
- try {
116
- await guarded(id, async () => client.customers.del(id))
117
- } catch (error) {
118
- if (!(error instanceof Missing)) throw error
119
- }
120
- },
121
- readCustomer: async (id, options) => {
122
- try {
123
- const asked = {
124
- invoices: options?.invoices ?? false,
125
- free: options?.free ?? false,
126
- }
127
- return await guarded(id, async () => stateOf(client, id, asked))
128
- } catch (error) {
129
- if (error instanceof Missing) return gone
130
- throw error
131
- }
132
- },
133
- customerOf: async (type, id) => {
134
- try {
135
- return refOf(await guarded(id, async () => ownerOf(client, type, id)))
136
- } catch (error) {
137
- if (error instanceof Missing) return null
138
- throw error
139
- }
140
- },
141
- openCheckout: async (checkout) =>
142
- guarded(checkout.customerId, async () => {
143
- const price = await priceId(client, checkout.lookupKey)
144
- const metadata = {
145
- ...checkout.metadata,
146
- managedBy,
147
- product: checkout.product,
148
- // A purchase keeps its quantity: its credits are so many times.
149
- ...(checkout.mode === 'payment' && {
150
- quantity: String(checkout.quantity),
151
- }),
152
- }
153
- const session = await client.checkout.sessions.create({
154
- mode: checkout.mode,
155
- customer: checkout.customerId,
156
- client_reference_id: checkout.reference,
157
- line_items: [{ price, quantity: checkout.quantity }],
158
- success_url: checkout.successUrl,
159
- cancel_url: checkout.cancelUrl,
160
- metadata,
161
- ...(checkout.terms && {
162
- consent_collection: { terms_of_service: 'required' },
163
- }),
164
- ...(checkout.promotionCodes && { allow_promotion_codes: true }),
165
- ...(checkout.mode === 'subscription'
166
- ? {
167
- subscription_data: {
168
- metadata,
169
- ...(checkout.trialDays !== null && {
170
- trial_period_days: checkout.trialDays,
171
- }),
172
- },
173
- }
174
- : { payment_intent_data: { metadata } }),
175
- })
176
- if (session.url === null) throw new Error('Checkout gave no URL.')
177
- return session.url
178
- }),
179
- expireCheckouts: async (customerId) =>
180
- guarded(customerId, async () => {
181
- const open = await all(
182
- client.checkout.sessions.list({
183
- customer: customerId,
184
- status: 'open',
185
- limit: 100,
186
- }),
187
- )
188
- for (const { id } of open) await client.checkout.sessions.expire(id)
189
- }),
190
- checkoutCustomer: async (id) => {
191
- try {
192
- const session = await guarded(id, async () =>
193
- client.checkout.sessions.retrieve(id),
194
- )
195
- return refOf(session.customer)
196
- } catch (error) {
197
- if (error instanceof Missing) return null
198
- throw error
199
- }
200
- },
201
- openPortal: async ({ customerId, configuration, returnUrl, flow }) =>
202
- guarded(customerId, async () => {
203
- const flowData = await flowOf(client, flow, returnUrl)
204
- const session = await client.billingPortal.sessions.create({
205
- customer: customerId,
206
- return_url: returnUrl,
207
- ...(configuration !== null && { configuration }),
208
- ...(flowData !== undefined && { flow_data: flowData }),
209
- })
210
- return session.url
211
- }),
212
- // The customer first: a failure between the two leaves both cards set.
213
- moveCard: async ({ id, customerId, card }) =>
214
- guarded(id, async () => {
215
- await client.customers.update(customerId, {
216
- invoice_settings: { default_payment_method: card },
217
- })
218
- await client.subscriptions.update(id, { default_payment_method: '' })
219
- }),
220
- })
package/src/sdk-common.ts DELETED
@@ -1,57 +0,0 @@
1
- // What the gateways over Stripe's API share: Stripe's errors as the
2
- // plugin's, lists read whole, and the keys a price's metadata holds.
3
- import { Stripe } from 'stripe'
4
- import type { PriceKeys } from './billing-gateway.ts'
5
- import { Missing, unavailable } from './billing-gateway.ts'
6
-
7
- /** Stripe's errors, as the plugin's: unavailable, missing, or a bug. */
8
- const translated = (error: unknown, id: string): unknown => {
9
- if (
10
- error instanceof Stripe.errors.StripeConnectionError ||
11
- error instanceof Stripe.errors.StripeAPIError ||
12
- error instanceof Stripe.errors.StripeRateLimitError
13
- ) {
14
- return unavailable(error)
15
- }
16
- if (
17
- error instanceof Stripe.errors.StripeInvalidRequestError &&
18
- error.code === 'resource_missing'
19
- ) {
20
- return new Missing(id)
21
- }
22
- return error
23
- }
24
-
25
- export const guarded = async <T>(
26
- id: string,
27
- run: () => Promise<T>,
28
- ): Promise<T> => {
29
- try {
30
- return await run()
31
- } catch (error) {
32
- throw translated(error, id)
33
- }
34
- }
35
-
36
- /** Every item of a list, past its pages: no cap drops one. */
37
- export const all = async <T>(list: AsyncIterable<T>): Promise<T[]> => {
38
- const items: T[] = []
39
- for await (const item of list) items.push(item)
40
- return items
41
- }
42
-
43
- export type Ref = string | { readonly id: string } | null
44
- export const refOf = (value: Ref): string | null =>
45
- value === null || typeof value === 'string' ? value : value.id
46
-
47
- export const dateOf = (seconds: number): Date => new Date(seconds * 1000)
48
- export const maybeDate = (seconds: number | null): Date | null =>
49
- seconds === null ? null : dateOf(seconds)
50
-
51
- export const keysOf = (price: Stripe.Price | Stripe.DeletedPrice): PriceKeys =>
52
- 'metadata' in price
53
- ? {
54
- product: price.metadata['product'] ?? null,
55
- price: price.metadata['price'] ?? null,
56
- }
57
- : { product: null, price: null }