@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
@@ -1,200 +0,0 @@
1
- import { Missing } from './billing-gateway.js';
2
- import { managedBy } from './gateway.js';
3
- import { all, guarded, refOf } from './sdk-common.js';
4
- import { gone, stateOf } from './sdk-customer.js';
5
- const profileParams = (profile) => ({
6
- ...(profile.email != null && { email: profile.email }),
7
- ...(profile.name != null && { name: profile.name }),
8
- ...(profile.locale != null && { preferred_locales: [profile.locale] }),
9
- });
10
- /** The customer an object belongs to, read from Stripe. */
11
- export async function ownerOf(client, type, id) {
12
- switch (type) {
13
- case 'customer':
14
- return id;
15
- case 'checkout.session':
16
- return (await client.checkout.sessions.retrieve(id)).customer;
17
- case 'subscription':
18
- return (await client.subscriptions.retrieve(id)).customer;
19
- case 'subscription_schedule':
20
- return (await client.subscriptionSchedules.retrieve(id)).customer;
21
- case 'invoice':
22
- return (await client.invoices.retrieve(id)).customer;
23
- case 'payment_intent':
24
- return (await client.paymentIntents.retrieve(id)).customer;
25
- case 'charge':
26
- return (await client.charges.retrieve(id)).customer;
27
- case 'dispute': {
28
- const { charge } = await client.disputes.retrieve(id);
29
- const chargeId = refOf(charge);
30
- return chargeId === null
31
- ? null
32
- : (await client.charges.retrieve(chargeId)).customer;
33
- }
34
- default:
35
- return null;
36
- }
37
- }
38
- /** The active price of a lookup key, or a bug: the catalog was not applied. */
39
- async function priceId(client, lookupKey) {
40
- const listed = await client.prices.list({
41
- lookup_keys: [lookupKey],
42
- active: true,
43
- limit: 1,
44
- });
45
- const [price] = listed.data;
46
- if (price === undefined) {
47
- throw new Error(`Stripe holds no active price ${lookupKey}: apply the catalog.`);
48
- }
49
- return price.id;
50
- }
51
- async function flowOf(client, flow, returnUrl) {
52
- const after = {
53
- type: 'redirect',
54
- redirect: { return_url: returnUrl },
55
- };
56
- if (flow.kind === 'cancel') {
57
- return {
58
- type: 'subscription_cancel',
59
- subscription_cancel: { subscription: flow.subscriptionId },
60
- after_completion: after,
61
- };
62
- }
63
- if (flow.kind === 'home')
64
- return undefined;
65
- const subscription = await client.subscriptions.retrieve(flow.subscriptionId);
66
- const [item] = subscription.items.data;
67
- if (item === undefined)
68
- throw new Error('The subscription has no item.');
69
- // The quantity is kept (D-373 point 8).
70
- const price = await priceId(client, flow.lookupKey);
71
- return {
72
- type: 'subscription_update_confirm',
73
- subscription_update_confirm: {
74
- subscription: flow.subscriptionId,
75
- items: [{ id: item.id, price, quantity: item.quantity ?? 1 }],
76
- },
77
- after_completion: after,
78
- };
79
- }
80
- /** The billing gateway over Stripe's API. */
81
- export const sdkBilling = (client) => ({
82
- createCustomer: async (profile, idempotencyKey) => guarded('customer', async () => {
83
- const params = { ...profileParams(profile), metadata: { managedBy } };
84
- const created = await client.customers.create(params, {
85
- idempotencyKey,
86
- });
87
- return created.id;
88
- }),
89
- updateCustomer: async (id, profile) => guarded(id, async () => {
90
- await client.customers.update(id, profileParams(profile));
91
- }),
92
- deleteCustomer: async (id) => {
93
- try {
94
- await guarded(id, async () => client.customers.del(id));
95
- }
96
- catch (error) {
97
- if (!(error instanceof Missing))
98
- throw error;
99
- }
100
- },
101
- readCustomer: async (id, options) => {
102
- try {
103
- const asked = {
104
- invoices: options?.invoices ?? false,
105
- free: options?.free ?? false,
106
- };
107
- return await guarded(id, async () => stateOf(client, id, asked));
108
- }
109
- catch (error) {
110
- if (error instanceof Missing)
111
- return gone;
112
- throw error;
113
- }
114
- },
115
- customerOf: async (type, id) => {
116
- try {
117
- return refOf(await guarded(id, async () => ownerOf(client, type, id)));
118
- }
119
- catch (error) {
120
- if (error instanceof Missing)
121
- return null;
122
- throw error;
123
- }
124
- },
125
- openCheckout: async (checkout) => guarded(checkout.customerId, async () => {
126
- const price = await priceId(client, checkout.lookupKey);
127
- const metadata = {
128
- ...checkout.metadata,
129
- managedBy,
130
- product: checkout.product,
131
- // A purchase keeps its quantity: its credits are so many times.
132
- ...(checkout.mode === 'payment' && {
133
- quantity: String(checkout.quantity),
134
- }),
135
- };
136
- const session = await client.checkout.sessions.create({
137
- mode: checkout.mode,
138
- customer: checkout.customerId,
139
- client_reference_id: checkout.reference,
140
- line_items: [{ price, quantity: checkout.quantity }],
141
- success_url: checkout.successUrl,
142
- cancel_url: checkout.cancelUrl,
143
- metadata,
144
- ...(checkout.terms && {
145
- consent_collection: { terms_of_service: 'required' },
146
- }),
147
- ...(checkout.promotionCodes && { allow_promotion_codes: true }),
148
- ...(checkout.mode === 'subscription'
149
- ? {
150
- subscription_data: {
151
- metadata,
152
- ...(checkout.trialDays !== null && {
153
- trial_period_days: checkout.trialDays,
154
- }),
155
- },
156
- }
157
- : { payment_intent_data: { metadata } }),
158
- });
159
- if (session.url === null)
160
- throw new Error('Checkout gave no URL.');
161
- return session.url;
162
- }),
163
- expireCheckouts: async (customerId) => guarded(customerId, async () => {
164
- const open = await all(client.checkout.sessions.list({
165
- customer: customerId,
166
- status: 'open',
167
- limit: 100,
168
- }));
169
- for (const { id } of open)
170
- await client.checkout.sessions.expire(id);
171
- }),
172
- checkoutCustomer: async (id) => {
173
- try {
174
- const session = await guarded(id, async () => client.checkout.sessions.retrieve(id));
175
- return refOf(session.customer);
176
- }
177
- catch (error) {
178
- if (error instanceof Missing)
179
- return null;
180
- throw error;
181
- }
182
- },
183
- openPortal: async ({ customerId, configuration, returnUrl, flow }) => guarded(customerId, async () => {
184
- const flowData = await flowOf(client, flow, returnUrl);
185
- const session = await client.billingPortal.sessions.create({
186
- customer: customerId,
187
- return_url: returnUrl,
188
- ...(configuration !== null && { configuration }),
189
- ...(flowData !== undefined && { flow_data: flowData }),
190
- });
191
- return session.url;
192
- }),
193
- // The customer first: a failure between the two leaves both cards set.
194
- moveCard: async ({ id, customerId, card }) => guarded(id, async () => {
195
- await client.customers.update(customerId, {
196
- invoice_settings: { default_payment_method: card },
197
- });
198
- await client.subscriptions.update(id, { default_payment_method: '' });
199
- }),
200
- });
@@ -1,13 +0,0 @@
1
- import { Stripe } from 'stripe';
2
- import type { PriceKeys } from './billing-gateway.ts';
3
- export declare const guarded: <T>(id: string, run: () => Promise<T>) => Promise<T>;
4
- /** Every item of a list, past its pages: no cap drops one. */
5
- export declare const all: <T>(list: AsyncIterable<T>) => Promise<T[]>;
6
- export type Ref = string | {
7
- readonly id: string;
8
- } | null;
9
- export declare const refOf: (value: Ref) => string | null;
10
- export declare const dateOf: (seconds: number) => Date;
11
- export declare const maybeDate: (seconds: number | null) => Date | null;
12
- export declare const keysOf: (price: Stripe.Price | Stripe.DeletedPrice) => PriceKeys;
13
- //# sourceMappingURL=sdk-common.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sdk-common.d.ts","sourceRoot":"","sources":["../src/sdk-common.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAC/B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAA;AAqBrD,eAAO,MAAM,OAAO,GAAU,CAAC,MAC1B,MAAM,OACL,MAAM,OAAO,CAAC,CAAC,CAAC,KACnB,OAAO,CAAC,CAAC,CAMX,CAAA;AAED,8DAA8D;AAC9D,eAAO,MAAM,GAAG,GAAU,CAAC,QAAQ,aAAa,CAAC,CAAC,CAAC,KAAG,OAAO,CAAC,CAAC,EAAE,CAIhE,CAAA;AAED,MAAM,MAAM,GAAG,GAAG,MAAM,GAAG;IAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAA;AACzD,eAAO,MAAM,KAAK,UAAW,GAAG,KAAG,MAAM,GAAG,IACmB,CAAA;AAE/D,eAAO,MAAM,MAAM,YAAa,MAAM,KAAG,IAAgC,CAAA;AACzE,eAAO,MAAM,SAAS,YAAa,MAAM,GAAG,IAAI,KAAG,IAAI,GAAG,IAChB,CAAA;AAE1C,eAAO,MAAM,MAAM,UAAW,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,YAAY,KAAG,SAMjC,CAAA"}
@@ -1,41 +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 { Missing, unavailable } from './billing-gateway.js';
5
- /** Stripe's errors, as the plugin's: unavailable, missing, or a bug. */
6
- const translated = (error, id) => {
7
- if (error instanceof Stripe.errors.StripeConnectionError ||
8
- error instanceof Stripe.errors.StripeAPIError ||
9
- error instanceof Stripe.errors.StripeRateLimitError) {
10
- return unavailable(error);
11
- }
12
- if (error instanceof Stripe.errors.StripeInvalidRequestError &&
13
- error.code === 'resource_missing') {
14
- return new Missing(id);
15
- }
16
- return error;
17
- };
18
- export const guarded = async (id, run) => {
19
- try {
20
- return await run();
21
- }
22
- catch (error) {
23
- throw translated(error, id);
24
- }
25
- };
26
- /** Every item of a list, past its pages: no cap drops one. */
27
- export const all = async (list) => {
28
- const items = [];
29
- for await (const item of list)
30
- items.push(item);
31
- return items;
32
- };
33
- export const refOf = (value) => value === null || typeof value === 'string' ? value : value.id;
34
- export const dateOf = (seconds) => new Date(seconds * 1000);
35
- export const maybeDate = (seconds) => seconds === null ? null : dateOf(seconds);
36
- export const keysOf = (price) => 'metadata' in price
37
- ? {
38
- product: price.metadata['product'] ?? null,
39
- price: price.metadata['price'] ?? null,
40
- }
41
- : { product: null, price: null };
@@ -1,9 +0,0 @@
1
- import type { Stripe } from 'stripe';
2
- import type { CustomerState } from './billing-gateway.ts';
3
- export declare const gone: CustomerState;
4
- /** What a customer holds; its invoices and free Checkouts, if asked. */
5
- export declare function stateOf(client: Stripe, id: string, asked: {
6
- readonly invoices: boolean;
7
- readonly free: boolean;
8
- }): Promise<CustomerState>;
9
- //# sourceMappingURL=sdk-customer.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sdk-customer.d.ts","sourceRoot":"","sources":["../src/sdk-customer.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AACpC,OAAO,KAAK,EACX,aAAa,EAGb,MAAM,sBAAsB,CAAA;AAgH7B,eAAO,MAAM,IAAI,EAAE,aAKlB,CAAA;AAID,wEAAwE;AACxE,wBAAsB,OAAO,CAC5B,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,MAAM,EACV,KAAK,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GAC3D,OAAO,CAAC,aAAa,CAAC,CAoExB"}
@@ -1,149 +0,0 @@
1
- import { managedBy } from './gateway.js';
2
- import { all, dateOf, keysOf, maybeDate, refOf } from './sdk-common.js';
3
- import { invoicesOf } from './sdk-invoices.js';
4
- /** A subscription's next phase, when its schedule holds one. */
5
- async function scheduledOf(client, schedule) {
6
- if (schedule === null || typeof schedule === 'string')
7
- return null;
8
- const now = Date.now() / 1000;
9
- const next = schedule.phases.find(({ start_date }) => start_date > now);
10
- const item = next?.items[0];
11
- if (next === undefined || item === undefined)
12
- return null;
13
- const price = typeof item.price === 'string'
14
- ? await client.prices.retrieve(item.price)
15
- : item.price;
16
- return { ...keysOf(price), at: dateOf(next.start_date) };
17
- }
18
- async function subscriptionOf(client, subscription) {
19
- const item = subscription.items.data[0];
20
- const quantity = item?.quantity ?? 1;
21
- const recurring = item?.price.recurring;
22
- const cancelAt = subscription.cancel_at ??
23
- (subscription.cancel_at_period_end
24
- ? (item?.current_period_end ?? null)
25
- : null);
26
- return {
27
- id: subscription.id,
28
- customerId: refOf(subscription.customer) ?? '',
29
- ...(item === undefined
30
- ? { product: null, price: null }
31
- : keysOf(item.price)),
32
- status: subscription.status,
33
- quantity,
34
- amount: (item?.price.unit_amount ?? 0) * quantity,
35
- every: recurring?.interval ?? 'month',
36
- everyCount: recurring?.interval_count ?? 1,
37
- currentPeriodEnd: dateOf(item?.current_period_end ?? subscription.start_date),
38
- cancelAt: maybeDate(cancelAt),
39
- canceledAt: maybeDate(subscription.canceled_at),
40
- trialEnd: maybeDate(subscription.trial_end),
41
- startedAt: dateOf(subscription.start_date),
42
- scheduled: await scheduledOf(client, subscription.schedule),
43
- card: subscription.metadata['managedBy'] === managedBy
44
- ? refOf(subscription.default_payment_method)
45
- : null,
46
- };
47
- }
48
- /** The quantity a Checkout wrote to its payment, one when it wrote none. */
49
- const quantityOf = (value) => {
50
- const quantity = Number(value);
51
- return Number.isSafeInteger(quantity) && quantity > 0 ? quantity : 1;
52
- };
53
- async function paymentOf(client, intent) {
54
- const charge = intent.latest_charge === null || typeof intent.latest_charge === 'string'
55
- ? null
56
- : intent.latest_charge;
57
- const disputes = charge?.disputed === true
58
- ? await all(client.disputes.list({ payment_intent: intent.id }))
59
- : [];
60
- return {
61
- id: intent.id,
62
- customerId: refOf(intent.customer) ?? '',
63
- product: intent.metadata['product'] ?? null,
64
- quantity: quantityOf(intent.metadata['quantity']),
65
- amount: intent.amount_received,
66
- refunded: charge?.amount_refunded ?? 0,
67
- disputeLost: disputes.some(({ status }) => status === 'lost'),
68
- paidAt: dateOf(intent.created),
69
- receiptUrl: charge?.receipt_url ?? null,
70
- };
71
- }
72
- /**
73
- * A Checkout of the plugin's that a full discount made free: Stripe makes
74
- * no payment for it, so it stands for one.
75
- */
76
- const freeOf = (session) => ({
77
- id: session.id,
78
- customerId: refOf(session.customer) ?? '',
79
- product: session.metadata?.['product'] ?? null,
80
- quantity: quantityOf(session.metadata?.['quantity']),
81
- amount: 0,
82
- refunded: 0,
83
- disputeLost: false,
84
- paidAt: dateOf(session.created),
85
- receiptUrl: null,
86
- });
87
- const isFree = (session) => session.mode === 'payment' &&
88
- session.payment_intent === null &&
89
- session.metadata?.['managedBy'] === managedBy;
90
- export const gone = {
91
- deleted: true,
92
- subscriptions: [],
93
- payments: [],
94
- invoices: [],
95
- };
96
- const day = 24 * 60 * 60;
97
- /** What a customer holds; its invoices and free Checkouts, if asked. */
98
- export async function stateOf(client, id, asked) {
99
- const customer = await client.customers.retrieve(id);
100
- if (customer.deleted === true)
101
- return gone;
102
- // A refund comes within the year; a paid period, within its own.
103
- const created = { gte: Math.floor(Date.now() / 1000) - 400 * day };
104
- const [subscriptions, intents, invoices, sessions] = await Promise.all([
105
- all(client.subscriptions.list({
106
- customer: id,
107
- status: 'all',
108
- limit: 100,
109
- expand: ['data.schedule'],
110
- })),
111
- all(client.paymentIntents.list({
112
- customer: id,
113
- limit: 100,
114
- expand: ['data.latest_charge'],
115
- })),
116
- asked.invoices
117
- ? all(client.invoices.list({
118
- customer: id,
119
- status: 'paid',
120
- created,
121
- limit: 100,
122
- expand: ['data.payments'],
123
- }))
124
- : [],
125
- asked.free
126
- ? all(client.checkout.sessions.list({
127
- customer: id,
128
- status: 'complete',
129
- created,
130
- limit: 100,
131
- }))
132
- : [],
133
- ]);
134
- const succeeded = intents.filter(({ status }) => status === 'succeeded');
135
- const paid = await Promise.all(succeeded.map(async (one) => paymentOf(client, one)));
136
- // The plugin's one-time payments; the others paid invoices.
137
- const opened = new Set(succeeded
138
- .filter(({ metadata }) => metadata['managedBy'] === managedBy)
139
- .map(({ id: intent }) => intent));
140
- return {
141
- deleted: false,
142
- subscriptions: await Promise.all(subscriptions.map(async (one) => subscriptionOf(client, one))),
143
- payments: [
144
- ...paid.filter((one) => opened.has(one.id)),
145
- ...sessions.filter(isFree).map(freeOf),
146
- ],
147
- invoices: await invoicesOf(client, invoices, new Map(paid.map((one) => [one.id, one]))),
148
- };
149
- }
@@ -1,10 +0,0 @@
1
- import type { Stripe } from 'stripe';
2
- import type { StripeInvoice, StripePayment } from './billing-gateway.ts';
3
- /**
4
- * The paid invoices, with the periods they bill and the refunds and
5
- * disputes of the payments that paid them, from the customer's `payments`
6
- * by id. An invoice whose periods ended is kept: its refund takes back what
7
- * it gave.
8
- */
9
- export declare function invoicesOf(client: Stripe, invoices: readonly Stripe.Invoice[], payments: ReadonlyMap<string, StripePayment>): Promise<StripeInvoice[]>;
10
- //# sourceMappingURL=sdk-invoices.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sdk-invoices.d.ts","sourceRoot":"","sources":["../src/sdk-invoices.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AACpC,OAAO,KAAK,EAEX,aAAa,EACb,aAAa,EACb,MAAM,sBAAsB,CAAA;AAyC7B;;;;;GAKG;AACH,wBAAsB,UAAU,CAC/B,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,SAAS,MAAM,CAAC,OAAO,EAAE,EACnC,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,aAAa,CAAC,GAC1C,OAAO,CAAC,aAAa,EAAE,CAAC,CAqB1B"}
@@ -1,53 +0,0 @@
1
- import { all, dateOf, keysOf, refOf } from './sdk-common.js';
2
- /** A price's keys, each price read once. */
3
- function priceKeys(client) {
4
- const read = new Map();
5
- return async (price) => {
6
- if (typeof price !== 'string')
7
- return keysOf(price);
8
- const held = read.get(price) ?? client.prices.retrieve(price).then(keysOf);
9
- read.set(price, held);
10
- return held;
11
- };
12
- }
13
- /** Whether a line bills a whole period above zero: no proration, no trial. */
14
- const billsPeriod = (line) => line.amount > 0 && line.parent?.subscription_item_details?.proration === false;
15
- async function periodsOf(client, invoice, keys) {
16
- const lines = invoice.lines.has_more && invoice.id !== undefined
17
- ? await all(client.invoices.listLineItems(invoice.id, { limit: 100 }))
18
- : invoice.lines.data;
19
- return Promise.all(lines.filter(billsPeriod).flatMap((line) => {
20
- const price = line.pricing?.price_details?.price;
21
- if (price === undefined)
22
- return [];
23
- const quantity = line.quantity ?? 1;
24
- const end = dateOf(line.period.end);
25
- return [keys(price).then((held) => ({ ...held, quantity, end }))];
26
- }));
27
- }
28
- /**
29
- * The paid invoices, with the periods they bill and the refunds and
30
- * disputes of the payments that paid them, from the customer's `payments`
31
- * by id. An invoice whose periods ended is kept: its refund takes back what
32
- * it gave.
33
- */
34
- export async function invoicesOf(client, invoices, payments) {
35
- const keys = priceKeys(client);
36
- return Promise.all(invoices.map(async (invoice) => {
37
- const paidBy = (invoice.payments?.data ?? [])
38
- .filter(({ status }) => status === 'paid')
39
- .flatMap(({ payment }) => {
40
- const intent = refOf(payment.payment_intent ?? null);
41
- const held = intent === null ? undefined : payments.get(intent);
42
- return held === undefined ? [] : [held];
43
- });
44
- return {
45
- id: invoice.id ?? '',
46
- customerId: refOf(invoice.customer) ?? '',
47
- periods: await periodsOf(client, invoice, keys),
48
- amount: invoice.amount_paid,
49
- refunded: paidBy.reduce((sum, one) => sum + one.refunded, 0),
50
- disputeLost: paidBy.some(({ disputeLost }) => disputeLost),
51
- };
52
- }));
53
- }
@@ -1,5 +0,0 @@
1
- import { Stripe } from 'stripe';
2
- import type { RecoveryGateway } from './billing-gateway.ts';
3
- /** The recovery gateway over Stripe's API. */
4
- export declare const sdkRecovery: (client: Stripe) => RecoveryGateway;
5
- //# sourceMappingURL=sdk-recovery.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sdk-recovery.d.ts","sourceRoot":"","sources":["../src/sdk-recovery.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAC/B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA;AAiF3D,8CAA8C;AAC9C,eAAO,MAAM,WAAW,WAAY,MAAM,KAAG,eAK3C,CAAA"}
@@ -1,81 +0,0 @@
1
- // What the plugin asks Stripe's API to set right what went wrong (D-375):
2
- // a payer's second subscription ended and refunded, and the customers that
3
- // Stripe's events changed, for the hourly job to find what a lost webhook
4
- // missed.
5
- import { Stripe } from 'stripe';
6
- import { ownerOf } from './sdk-billing.js';
7
- import { all, guarded, refOf } from './sdk-common.js';
8
- /** The statuses Stripe no longer changes. */
9
- const ended = new Set(['canceled', 'incomplete_expired']);
10
- /** Whether Stripe refused a refund the payment no longer needs. */
11
- const refundedAlready = (error) => error instanceof Stripe.errors.StripeInvalidRequestError &&
12
- (error.code === 'charge_already_refunded' || error.code === 'charge_disputed');
13
- async function cancelAndRefund(client, id) {
14
- const subscription = await client.subscriptions.retrieve(id);
15
- if (!ended.has(subscription.status)) {
16
- await client.subscriptions.cancel(id, { prorate: false });
17
- }
18
- const invoice = refOf(subscription.latest_invoice);
19
- if (invoice === null)
20
- return;
21
- const paid = await all(client.invoicePayments.list({ invoice, status: 'paid', limit: 100 }));
22
- for (const { payment } of paid) {
23
- const intent = refOf(payment.payment_intent ?? null);
24
- const charge = refOf(payment.charge ?? null);
25
- const target = intent === null
26
- ? charge === null
27
- ? undefined
28
- : { charge }
29
- : { payment_intent: intent };
30
- if (target === undefined)
31
- continue;
32
- try {
33
- // The key makes a retried job refund once.
34
- await client.refunds.create(target, {
35
- idempotencyKey: `refund-${intent ?? charge ?? ''}`,
36
- });
37
- }
38
- catch (error) {
39
- if (!refundedAlready(error))
40
- throw error;
41
- }
42
- }
43
- }
44
- /** The customer an event's object belongs to, from the event alone. */
45
- async function ownerOfEvent(client, event) {
46
- const object = event.data.object;
47
- const kind = Reflect.get(Object(object), 'object');
48
- const id = Reflect.get(Object(object), 'id');
49
- if (kind === 'customer' && typeof id === 'string')
50
- return id;
51
- const customer = Reflect.get(Object(object), 'customer');
52
- if (typeof customer === 'string')
53
- return customer;
54
- const nested = Reflect.get(Object(customer), 'id');
55
- if (typeof nested === 'string')
56
- return nested;
57
- // A dispute names its charge only.
58
- if (kind === 'dispute' && typeof id === 'string') {
59
- return refOf(await ownerOf(client, 'dispute', id));
60
- }
61
- return null;
62
- }
63
- async function changedSince(client, since) {
64
- const changed = new Map();
65
- const created = { gt: Math.floor(since.getTime() / 1000) };
66
- // Stripe lists its events for 30 days, the newest first.
67
- for await (const event of client.events.list({ created, limit: 100 })) {
68
- const customer = await ownerOfEvent(client, event);
69
- const at = new Date(event.created * 1000);
70
- const known = customer === null ? undefined : changed.get(customer);
71
- if (customer !== null && (known === undefined || known < at)) {
72
- changed.set(customer, at);
73
- }
74
- }
75
- return changed;
76
- }
77
- /** The recovery gateway over Stripe's API. */
78
- export const sdkRecovery = (client) => ({
79
- cancelAndRefund: async (id) => guarded(id, async () => cancelAndRefund(client, id)),
80
- changedSince: async (since) => guarded('events', async () => changedSince(client, since)),
81
- });
package/dist/sync.d.ts DELETED
@@ -1,8 +0,0 @@
1
- /**
2
- * Writes what Stripe holds of the customer of row `id`. The sync takes the
3
- * next number of the customer's syncs, reads Stripe, then writes only when
4
- * no sync begun after it wrote first. A change at Stripe sends an event
5
- * whose sync begins after it, so no sync begun before overwrites it.
6
- */
7
- export declare function syncCustomer(id: string): Promise<void>;
8
- //# sourceMappingURL=sync.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AA6MA;;;;;GAKG;AACH,wBAAsB,YAAY,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAkC5D"}