@yaks/stripe 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/shops.js ADDED
@@ -0,0 +1,689 @@
1
+ // What Stripe lends a party selling on an account of its own, as @yaks/host's
2
+ // `Shops`: a Connect account opened once, finished through Stripe's hosted
3
+ // onboarding, Checkout Sessions on it that the platform takes an application
4
+ // fee from, in payment mode or in subscription mode, the subscriptions those
5
+ // start, read and cancelled at their period's end, and the events Stripe
6
+ // posts about it read into the host's words (`shopped`, which ./doors.ts
7
+ // hears them with).
8
+ //
9
+ // Direct charges throughout, the "charge merchants directly" model. The
10
+ // connected account is the merchant: the charge is on their books, Stripe's
11
+ // processing fee comes out of their money, the customer's statement says their
12
+ // name, and a refund or a dispute is theirs to answer and theirs to pay. The
13
+ // platform acts on their account with its own key, one `Stripe-Account` header
14
+ // (./mod.ts `ask`), and names an `application_fee_amount` Stripe moves to it
15
+ // out of the same payment.
16
+ //
17
+ // A seller who already has a Stripe account connects it instead, through
18
+ // Connect's OAuth for Standard accounts (docs.stripe.com/connect/oauth-standard-accounts):
19
+ // Stripe's page asks them to sign in and allow the platform, and hands them
20
+ // back with a code the platform trades for the account's id. Stripe calls
21
+ // OAuth not recommended for new platforms because Account Links onboard an
22
+ // account the platform makes; it remains the one way to connect an account
23
+ // that already exists. The account is theirs, not the platform's to
24
+ // control, so its details are changed in their own dashboard, and the same
25
+ // direct charges and application fee apply to it.
26
+ //
27
+ // The house sells on the platform's own account instead (@yaks/host/payments
28
+ // `Seller`), named '' wherever an account is: the same calls with no
29
+ // `Stripe-Account` header, so the charge is the platform's, Stripe's fees come
30
+ // out of the platform's balance (and its fee credit), and no application fee
31
+ // is named, since Stripe takes none from an account for itself. Managed
32
+ // Payments, on by default on the platform's account for its plans, is turned
33
+ // off for these: it sells digital goods as merchant of record, and the house
34
+ // sells printed books as itself. The card statement reads the platform's
35
+ // prefix and the seller's name after it (`YAKS.APP* PRINTBOUND`). Its events
36
+ // arrive at the platform's own endpoint, which `housed` tells from the
37
+ // platform's own plans.
38
+ //
39
+ // v1 throughout, deliberately: `POST /v1/accounts` with controller properties,
40
+ // and the v1 event names. There is a v2 Accounts API with its own thin
41
+ // `v2.core.*` events; mixing the two would mean a reader of one set of names
42
+ // and a dashboard ticking the other, which is a webhook that silently does
43
+ // nothing.
44
+ import { ask, found, idOf, minimum } from "./mod.js";
45
+ import { refund, refundedOf } from "./refunds.js";
46
+ import { shopPortal } from "./shop-portal.js";
47
+ import { cancelTerm, termAt } from "./shop-term.js";
48
+ /** Stripe's host for Connect's OAuth, and where a seller whose account the
49
+ * platform does not control changes its details: their own dashboard. */ export let CONNECT = 'https://connect.stripe.com';
50
+ export let DASHBOARD = 'https://dashboard.stripe.com/';
51
+ /// authorizeAt('ca_1', 's1', 'https://yaks.app/selling/callback') -> 'https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_1&scope=read_write&state=s1&redirect_uri=https%3A%2F%2Fyaks.app%2Fselling%2Fcallback'
52
+ /** The address of Stripe's page where a seller connects an account they
53
+ * already have. `read_write` is the only scope a platform may ask for, and
54
+ * `redirect_uri` must be one listed in the platform's OAuth settings. */ export let authorizeAt = (client, state, back)=>`${CONNECT}/oauth/authorize?${new URLSearchParams({
55
+ response_type: 'code',
56
+ client_id: client,
57
+ scope: 'read_write',
58
+ state,
59
+ redirect_uri: back
60
+ })}`;
61
+ /**
62
+ * The account asked for, as the form fields of `POST /v1/accounts`.
63
+ *
64
+ * The controller properties are the whole model. "Charge merchants directly"
65
+ * is these four answers, and each is a sentence about who is responsible for
66
+ * what. They are also, all four, Stripe's own defaults, the combination it
67
+ * documents as the Standard mapping
68
+ * (docs.stripe.com/connect/migrate-to-controller-properties). They are written
69
+ * out anyway, because a liability decision that four omitted parameters happen
70
+ * to make is a liability decision nobody can read, and a default Stripe moves
71
+ * one day would move it silently.
72
+ *
73
+ * `controller[fees][payer] = account`
74
+ * the connected account pays Stripe's processing fee, out of its own
75
+ * money, on its own charge. Not the platform: it is not reselling
76
+ * payments.
77
+ * `controller[losses][payments] = stripe`
78
+ * Stripe, not the platform, carries the negative balance when a dispute
79
+ * is lost. There is no `account` value here and the value is not a
80
+ * mistake: `stripe` is what "the platform is not liable" is called, and
81
+ * the merchant is still the one whose charge is reversed.
82
+ * `controller[stripe_dashboard][type] = full`
83
+ * the seller gets the whole Stripe Dashboard, their own account, where
84
+ * they read their payments, answer their disputes and manage their
85
+ * payouts. `express` is the cut-down one, and Stripe refuses it beside
86
+ * `fees.payer = account`: an Express dashboard is for a platform that
87
+ * pays the fees and carries the losses, which is the opposite of this.
88
+ * `controller[requirement_collection] = stripe`
89
+ * Stripe collects and re-collects the identity requirements, through the
90
+ * Account Link below. The platform never sees, stores or forwards a
91
+ * seller's identity documents, which is exactly the property that lets
92
+ * this integration exist without it becoming a KYC operator.
93
+ *
94
+ * No `capabilities`, deliberately. Stripe requires them only where the account
95
+ * has no Stripe-hosted dashboard; with `full` the payment capabilities are
96
+ * requested automatically for the account's country, and the seller manages
97
+ * them themselves. `transfers` in particular would be wrong: that is the
98
+ * capability a destination charge needs, and a direct charge never transfers.
99
+ *
100
+ * No `type` either. It is deprecated in favour of exactly these four
101
+ * properties, and the two ways of saying one thing are not passed together.
102
+ *
103
+ * `metadata` carries the tags, so an account read back out of Stripe's
104
+ * dashboard says whose it is without a lookup.
105
+ */ export let account = (who)=>({
106
+ controller: {
107
+ fees: {
108
+ payer: 'account'
109
+ },
110
+ losses: {
111
+ payments: 'stripe'
112
+ },
113
+ stripe_dashboard: {
114
+ type: 'full'
115
+ },
116
+ requirement_collection: 'stripe'
117
+ },
118
+ ...who.email ? {
119
+ email: who.email
120
+ } : {},
121
+ metadata: who.tags
122
+ });
123
+ /** The onboarding link, as the form fields of `POST /v1/account_links`.
124
+ *
125
+ * `account_onboarding` and never `account_update`: Stripe refuses an update
126
+ * link for an account that has its own dashboard, and these all do. A seller
127
+ * changing their details later does it in their own Stripe Dashboard, which is
128
+ * the whole point of giving them one.
129
+ *
130
+ * `return_url` is where Stripe sends them when they finish, and `refresh_url`
131
+ * where it sends them when the link is spent: an Account Link is single-use
132
+ * and expires in about five minutes, since it is an authenticated door into
133
+ * somebody's identity form. Stripe's own instruction for `refresh_url` is
134
+ * "generate a new account link with the same parameters, then redirect", which
135
+ * is asking for onboarding again, so both are `back`. */ export let link = (account, back)=>({
136
+ account,
137
+ type: 'account_onboarding',
138
+ return_url: back,
139
+ refresh_url: back
140
+ });
141
+ /** A Stripe account as a seller: `charges_enabled` is `ready` and
142
+ * `details_submitted` is `submitted`.
143
+ *
144
+ * A missing field reads false rather than "unchanged". Stripe sends the whole
145
+ * account object on every `account.updated`, so an absent flag is an absent
146
+ * capability, and a reader that treated it as unchanged would leave a seller
147
+ * marked ready after Stripe stopped them. */ export let sellerOf = (a)=>({
148
+ account: String(a.id ?? ''),
149
+ ready: !!a.charges_enabled,
150
+ submitted: !!a.details_submitted
151
+ });
152
+ /** What Stripe charges a seller in the United States, from its pricing page
153
+ * (stripe.com/pricing) and help pages, read 2026-11-23: 2.9% + 30¢ a
154
+ * domestic card payment, 1.5% more for an international card, a $15 dispute
155
+ * fee returned on a won dispute, processing fees kept on a refund
156
+ * (support.stripe.com/questions/understanding-fees-for-refunded-payments),
157
+ * and payouts on a two-day rolling schedule after a first payout about seven
158
+ * days after the first payment
159
+ * (support.stripe.com/questions/delay-for-first-payout-for-connected-accounts).
160
+ * The account pays them itself (`fees.payer = account`, {@link account}),
161
+ * so these are the seller's costs, as published, and change when Stripe's
162
+ * pricing does. */ export let COSTS = {
163
+ card: {
164
+ bps: 290,
165
+ cents: 30
166
+ },
167
+ bankDebit: {
168
+ bps: 80,
169
+ cap: 500
170
+ },
171
+ recurring: 70,
172
+ abroad: 150,
173
+ dispute: 1500,
174
+ refunded: false,
175
+ payout: {
176
+ days: 2,
177
+ first: 7
178
+ },
179
+ country: 'US',
180
+ pricing: 'https://stripe.com/pricing'
181
+ };
182
+ /** The longest metadata value Stripe keeps, in characters: the most one
183
+ * tag carries ({@link Shops.tag}). */ export let TAG = 500;
184
+ /** A return address as Stripe reads it. `{CHECKOUT_SESSION_ID}` is a literal
185
+ * Stripe substitutes the session id for on the way back, and the host hands
186
+ * over an address `URL` wrote, which percent-encodes braces in a query:
187
+ * `%7BCHECKOUT_SESSION_ID%7D` is a string Stripe does not recognise, so the
188
+ * buyer would land on a page that never learns which order it is about. The
189
+ * braces come back, and only those two characters. */ export let back = (url)=>url.replaceAll('%7B', '{').replaceAll('%7D', '}');
190
+ /// cut({ lines: [{ name: 'Tee', cents: 999, qty: 1 }], bps: 250 }) -> 24
191
+ /// cut({ lines: [{ name: 'Tee', cents: 100, qty: 1 }], bps: 20_000 }) -> 100
192
+ /** The platform's cut of a sale paid once, in its smallest unit: the rate of
193
+ * its whole total, shipping included, rounded down, and never more than the
194
+ * sale. */ export let cut = (sale)=>{
195
+ let total = sale.lines.reduce((n, l)=>n + l.cents * l.qty, 0) + (sale.shipping?.cents ?? 0);
196
+ return Math.min(total, Math.max(0, Math.floor(total * (sale.bps || 0) / 10_000)));
197
+ };
198
+ // The payment a sale paid once makes. `application_fee_amount` is the
199
+ // platform's cut, and this is the only place Stripe takes one for a payment
200
+ // Checkout Session: there is no top-level parameter. It is left out entirely
201
+ // when it is zero, since Stripe requires a positive amount, so a fee of
202
+ // nothing has to be no fee rather than a fee of 0.
203
+ //
204
+ // The tags are copied onto it, which is not redundancy: a refund arrives as a
205
+ // `charge.refunded`, whose object inherits the PaymentIntent's metadata and
206
+ // knows nothing of the session, so without them the refund of a sale could
207
+ // not be told whose it was.
208
+ let once = (sale, house)=>{
209
+ let fee = house ? 0 : cut(sale);
210
+ let suffix = descriptor(sale.statementSuffix ?? (house ? sale.descriptor ?? '' : ''));
211
+ return {
212
+ ...house ? {
213
+ managed_payments: {
214
+ enabled: false
215
+ }
216
+ } : {},
217
+ ...sale.shipping ? {
218
+ shipping_options: [
219
+ {
220
+ shipping_rate_data: {
221
+ type: 'fixed_amount',
222
+ display_name: sale.shipping.name,
223
+ fixed_amount: {
224
+ amount: sale.shipping.cents,
225
+ currency: sale.currency
226
+ }
227
+ }
228
+ }
229
+ ]
230
+ } : {},
231
+ payment_intent_data: {
232
+ ...fee > 0 ? {
233
+ application_fee_amount: fee
234
+ } : {},
235
+ ...suffix ? {
236
+ statement_descriptor_suffix: suffix
237
+ } : {},
238
+ ...sale.description ? {
239
+ description: sale.description
240
+ } : {},
241
+ metadata: house ? marked(sale.tags) : sale.tags,
242
+ ...sale.destination ? {
243
+ shipping: sale.destination
244
+ } : {}
245
+ }
246
+ };
247
+ };
248
+ // The subscription a renewing sale makes. Its fee is a percent of every
249
+ // invoice, since an amount would be taken from the first payment alone, and a
250
+ // rate in whole basis points is a percent with the two decimal places Stripe
251
+ // takes. The tags ride the subscription, which every `customer.subscription.*`
252
+ // event carries back, and which an invoice's payment does not inherit.
253
+ let renewing = (sale)=>({
254
+ subscription_data: {
255
+ ...sale.bps > 0 ? {
256
+ application_fee_percent: Math.min(100, sale.bps / 100)
257
+ } : {},
258
+ ...sale.description ? {
259
+ description: sale.description
260
+ } : {},
261
+ metadata: sale.tags
262
+ }
263
+ });
264
+ /// descriptor('PrintBound') -> 'PRINTBOUND'
265
+ /// descriptor('Crayon "Bloom" <Books>') -> 'CRAYON BLOOM BOOKS'
266
+ /// descriptor('1234') -> ''
267
+ /** A seller's name as a statement descriptor suffix: upper case, without the
268
+ * characters Stripe refuses there (`<>\'"*`), at most 22 characters, and ''
269
+ * where no letter is left, which Stripe requires one of. Stripe itself cuts
270
+ * the suffix to what fits after the account's prefix. */ export let descriptor = (name)=>{
271
+ let out = name.toUpperCase().replace(/[<>\\'"*]/g, '').replace(/\s+/g, ' ').trim().slice(0, 22).trim();
272
+ return /\p{L}/u.test(out) ? out : '';
273
+ };
274
+ /** The metadata key a house sale's objects carry, which tells its events on
275
+ * the platform's own account from the platform's plans (`housed`). */ export let HOUSE = 'house';
276
+ let marked = (tags)=>({
277
+ ...tags,
278
+ [HOUSE]: 'true'
279
+ });
280
+ /**
281
+ * The Checkout Session, as the form fields of `POST /v1/checkout/sessions`,
282
+ * made on the seller's account (the `Stripe-Account` header `checkout` adds),
283
+ * or on the platform's own for the house: in payment mode for a sale paid
284
+ * once, and in subscription mode for one that says how often it renews, where
285
+ * every line recurs at that interval.
286
+ *
287
+ * The tags ride `metadata`, and the payment or the subscription it makes as
288
+ * well, with the house's mark on a house sale. Lines go out as inline
289
+ * `price_data`, numbered as Stripe's form encoding numbers a list.
290
+ */ export let session = (sale, house = false, embedded = false)=>({
291
+ mode: sale.per ? 'subscription' : 'payment',
292
+ ...sale.bankDebit && embedded && !house ? {
293
+ payment_method_types: [
294
+ 'card',
295
+ 'link',
296
+ 'us_bank_account'
297
+ ],
298
+ payment_method_options: {
299
+ us_bank_account: {
300
+ verification_method: 'instant'
301
+ }
302
+ },
303
+ adaptive_pricing: {
304
+ enabled: false
305
+ }
306
+ } : sale.cardOnly ? {
307
+ payment_method_types: [
308
+ 'card'
309
+ ],
310
+ adaptive_pricing: {
311
+ enabled: false
312
+ }
313
+ } : {},
314
+ ...sale.expires ? {
315
+ expires_at: Math.floor(Date.parse(sale.expires) / 1000)
316
+ } : {},
317
+ line_items: Object.fromEntries(sale.lines.map((l, i)=>[
318
+ i,
319
+ {
320
+ price_data: {
321
+ currency: sale.currency,
322
+ product_data: {
323
+ name: l.name,
324
+ ...l.description ? {
325
+ description: l.description
326
+ } : {}
327
+ },
328
+ unit_amount: l.cents,
329
+ ...sale.per ? {
330
+ recurring: {
331
+ interval: sale.per
332
+ }
333
+ } : {}
334
+ },
335
+ quantity: l.qty
336
+ }
337
+ ])),
338
+ ...embedded ? {
339
+ ui_mode: 'elements',
340
+ return_url: back(sale.done),
341
+ name_collection: {
342
+ individual: {
343
+ enabled: true
344
+ }
345
+ }
346
+ } : {
347
+ success_url: back(sale.done),
348
+ cancel_url: back(sale.cancel)
349
+ },
350
+ ...sale.email ? {
351
+ customer_email: sale.email
352
+ } : {},
353
+ metadata: house ? marked(sale.tags) : sale.tags,
354
+ ...sale.per ? renewing(sale) : once(sale, house)
355
+ });
356
+ /** A completed session as the sale it made. The buyer's address is
357
+ * `customer_details.email` and only falls back to `customer_email`: the
358
+ * second is the prefill the checkout started with, and the person may have
359
+ * typed a different one on Stripe's page. `payment_status` is the gate and
360
+ * `status` is not: a session can be `complete` with a payment still
361
+ * processing (a bank debit, say), and `paid` is the word Stripe documents as
362
+ * "the funds are available". */ export let paidOf = (o)=>({
363
+ ...o.currency ? {
364
+ currency: o.currency
365
+ } : {},
366
+ paid: o.payment_status == 'paid',
367
+ ...o.status == 'expired' ? {
368
+ expired: true
369
+ } : {},
370
+ ...o.status == 'complete' && o.payment_status == 'unpaid' ? typeof o.payment_intent == 'object' && [
371
+ 'requires_payment_method',
372
+ 'canceled'
373
+ ].includes(o.payment_intent?.status ?? '') ? {
374
+ failed: true
375
+ } : {
376
+ processing: true
377
+ } : {},
378
+ status: String(o.payment_status ?? ''),
379
+ checkout: String(o.id ?? ''),
380
+ payment: idOf(o.payment_intent),
381
+ ...idOf(o.subscription) ? {
382
+ subscription: idOf(o.subscription)
383
+ } : {},
384
+ ...idOf(o.subscription) && idOf(o.customer) ? {
385
+ payer: idOf(o.customer)
386
+ } : {},
387
+ total: Math.max(0, Math.floor(Number(o.amount_total ?? 0))),
388
+ email: String(o.customer_details?.email || o.customer_email || ''),
389
+ ...o.customer_details?.name ? {
390
+ name: o.customer_details.name
391
+ } : {},
392
+ tags: {
393
+ ...o.metadata
394
+ }
395
+ });
396
+ // Where an event moves a payment. A refund is whole only once the whole charge
397
+ // is (Stripe's `refunded`). A dispute is open until it closes: `lost` means
398
+ // the buyer's bank took the money back, and `won` or an inquiry closed without
399
+ // one (`warning_closed`) restores it. A dispute's other events (updated, funds
400
+ // withdrawn or reinstated) move nothing.
401
+ let settledBy = (type, o)=>type == 'charge.refunded' ? o.refunded ? 'refunded' : 'partially_refunded' : type == 'charge.dispute.created' ? 'disputed' : type == 'charge.dispute.closed' ? o.status == 'lost' ? 'lost' : 'restored' : null;
402
+ /** Stripe's shops, every call made with `options` as they read at the
403
+ * time. */ export let shops = (options)=>{
404
+ let mode = ()=>/^(?:sk|rk)_test_/.test(options.key ?? '') ? 'test' : /^(?:sk|rk)_live_/.test(options.key ?? '') ? 'live' : undefined;
405
+ let elements = (account, row)=>{
406
+ let clientSecret = row.client_secret;
407
+ if (typeof clientSecret != 'string' || !clientSecret) return null;
408
+ return {
409
+ clientSecret,
410
+ publishableKey: options.publishableKey,
411
+ ...row.id ? {
412
+ id: String(row.id)
413
+ } : {},
414
+ ...account ? {
415
+ account
416
+ } : {}
417
+ };
418
+ };
419
+ let embedded = ()=>!!mode() && options.publishableKey?.startsWith(`pk_${mode()}_`) === true;
420
+ let domains = new Map();
421
+ let walletDomain = async (on, domain, key)=>{
422
+ let credentials = {
423
+ key,
424
+ clock: options.clock
425
+ };
426
+ let path = '/v1/payment_method_domains';
427
+ let listed = await ask(credentials, `${path}?${new URLSearchParams({
428
+ domain_name: domain
429
+ })}`, undefined, on);
430
+ let [held] = listed.data;
431
+ if (!held) {
432
+ await ask(credentials, path, {
433
+ domain_name: domain
434
+ }, on, 'POST', `wallet|${on}|${domain}`);
435
+ }
436
+ };
437
+ // The address of what one POST made, which Stripe always answers with.
438
+ let made = async (what, path, fields, on, key)=>{
439
+ let url = String((await ask(options, path, fields, on, 'POST', key)).url ?? '');
440
+ if (!url) throw new Error(`stripe made ${what} with no url`);
441
+ return url;
442
+ };
443
+ return {
444
+ on: ()=>!!options.key,
445
+ costs: COSTS,
446
+ minimum,
447
+ mode,
448
+ tag: TAG,
449
+ open: async (who)=>{
450
+ let a = await ask(options, '/v1/accounts', account(who));
451
+ if (!a.id) throw new Error('stripe made an account with no id');
452
+ return sellerOf(a);
453
+ },
454
+ // An account the seller brought is not ours to onboard: Stripe makes no
455
+ // Account Link for it, and its owner finishes in their own dashboard.
456
+ onboarding: async (id, back)=>{
457
+ let a = await ask(options, `/v1/accounts/${encodeURIComponent(id)}`);
458
+ return a.controller?.is_controller ? await made('an account link', '/v1/account_links', link(id, back)) : DASHBOARD;
459
+ },
460
+ authorize: (state, back)=>options.client ? authorizeAt(options.client, state, back) : null,
461
+ // The code is good once, so the trade is never retried under a new key.
462
+ authorized: async (code)=>{
463
+ let token = await ask(options, `${CONNECT}/oauth/token`, {
464
+ grant_type: 'authorization_code',
465
+ code
466
+ }, undefined, 'POST', `oauth:${code}`);
467
+ let id = String(token.stripe_user_id ?? '');
468
+ if (!id) throw new Error('stripe connected an account with no id');
469
+ return sellerOf(await ask(options, `/v1/accounts/${encodeURIComponent(id)}`));
470
+ },
471
+ // On the seller's account: that one header is the whole of what makes it
472
+ // their charge rather than the platform's. The house's has none, and
473
+ // sells nothing that renews: a subscription's events on the platform's
474
+ // own account are read as the platform's plans.
475
+ checkout: (on, sale)=>{
476
+ if (!on && sale.per) {
477
+ throw new Error('the house sells nothing that renews');
478
+ }
479
+ return made('a checkout session', '/v1/checkout/sessions', session(sale, !on), on, sale.key);
480
+ },
481
+ embedded: {
482
+ on: embedded,
483
+ checkout: async (on, sale)=>{
484
+ if (!embedded()) {
485
+ throw new Error('stripe checkout publishable key unavailable');
486
+ }
487
+ if (!on && sale.per) {
488
+ throw new Error('the house sells nothing that renews');
489
+ }
490
+ let made = await ask(options, '/v1/checkout/sessions', session(sale, !on, true), on, 'POST', sale.key ? `elements|${sale.key}` : undefined);
491
+ let payment = elements(on, made);
492
+ if (!payment) {
493
+ throw new Error('stripe made an in-page checkout without a client secret');
494
+ }
495
+ return payment;
496
+ },
497
+ resume: async (on, id)=>{
498
+ if (!embedded()) return null;
499
+ let held = await found(options, `/v1/checkout/sessions/${encodeURIComponent(id)}`, on);
500
+ return held?.status == 'open' ? elements(on, held) : null;
501
+ },
502
+ walletDomain: (on, domain)=>{
503
+ let credential = options.walletKey;
504
+ if (!credential) return Promise.resolve();
505
+ let key = JSON.stringify([
506
+ mode(),
507
+ on,
508
+ domain
509
+ ]);
510
+ let held = domains.get(key);
511
+ if (held) return held;
512
+ if (domains.size >= 256) domains.delete(domains.keys().next().value);
513
+ let registered = walletDomain(on, domain, credential).catch((error)=>{
514
+ domains.delete(key);
515
+ throw error;
516
+ });
517
+ domains.set(key, registered);
518
+ return registered;
519
+ }
520
+ },
521
+ paid: async (on, checkout)=>{
522
+ let o = await found(options, `/v1/checkout/sessions/${encodeURIComponent(checkout)}?expand[]=payment_intent`, on);
523
+ return o && paidOf(o);
524
+ },
525
+ term: (on, id)=>termAt(options, on, id),
526
+ // `cancel_at_period_end` and not a delete: the buyer keeps what they paid
527
+ // for, and Stripe ends it when the period does. Setting it twice is one
528
+ // setting, so no request key holds it: one would replay a stale answer
529
+ // to a cancel asked again after the seller undid the first.
530
+ cancel: (on, id)=>cancelTerm(options, on, id),
531
+ refund: (on, request)=>refund(options, on, request),
532
+ portal: (on, payer, subscription, back, purpose)=>shopPortal(options, on, payer, subscription, back, purpose),
533
+ refundFee: async (id, refunded, total)=>{
534
+ if (!total || !refunded) return;
535
+ let fee = await ask(options, `/v1/application_fees/${encodeURIComponent(id)}`);
536
+ let target = Math.floor(Number(fee.amount ?? 0) * Math.min(refunded, total) / total);
537
+ let amount = target - Number(fee.amount_refunded ?? 0);
538
+ if (amount <= 0) return;
539
+ await ask(options, `/v1/application_fees/${encodeURIComponent(id)}/refunds`, {
540
+ amount
541
+ }, undefined, 'POST', `fee:${id}:${refunded}:${total}`);
542
+ }
543
+ };
544
+ };
545
+ // A charge's payment and what it carries: a charge inherits its intent's
546
+ // metadata, and is read back on the seller's own account for a dispute, which
547
+ // carries none of its own.
548
+ let payment = (o)=>{
549
+ let id = idOf(o.payment_intent);
550
+ return id ? {
551
+ id,
552
+ tags: {
553
+ ...o.metadata
554
+ },
555
+ ...o.amount != null ? {
556
+ total: o.amount
557
+ } : {},
558
+ ...o.amount_refunded != null ? {
559
+ refunded: o.amount_refunded
560
+ } : {},
561
+ ...idOf(o.application_fee) ? {
562
+ fee: idOf(o.application_fee)
563
+ } : {}
564
+ } : null;
565
+ };
566
+ // The subscription an event moves the term of, '' where it names none, and
567
+ // null for an event about no subscription's term. A subscription's own events
568
+ // say it was made, renewed, cancelled or ended; an invoice paid is a period
569
+ // paid for, and names its subscription under `parent` since API
570
+ // 2025-03-31.basil and at its top level before (as ./plans.ts `changed`
571
+ // reads it). Every one is read again from Stripe when it is applied, so the
572
+ // order they arrive in leaves the latest word.
573
+ let subscribedBy = (type, o)=>{
574
+ if (type.startsWith('customer.subscription.')) {
575
+ return idOf(o.id);
576
+ }
577
+ if (type != 'invoice.paid' && type != 'invoice.payment_failed') return null;
578
+ let parent = o.parent;
579
+ return idOf(o.subscription ?? parent?.subscription_details?.subscription);
580
+ };
581
+ let invoiceTags = (o)=>o.parent?.subscription_details?.metadata ?? o.subscription_details?.metadata ?? {};
582
+ /// billedOf({ id: 'in_1', customer: 'cus_1', amount_paid: 2500, created: 0, parent: { subscription_details: { metadata: { a: 'b' } } } }, 'sub_1') -> { id: 'in_1', subscription: 'sub_1', payer: 'cus_1', total: 2500, at: '1970-01-01T00:00:00.000Z', email: '', tags: { a: 'b' } }
583
+ /** A paid invoice as the period it paid. The subscription's metadata rides
584
+ * the invoice under `parent` since API 2025-03-31.basil, and at its top
585
+ * level before; the time is when it was paid, else when it was made. */ export let billedOf = (o, subscription)=>({
586
+ id: String(o.id ?? ''),
587
+ subscription,
588
+ payer: idOf(o.customer),
589
+ total: Number(o.amount_paid ?? 0),
590
+ at: new Date((o.status_transitions?.paid_at ?? o.created ?? 0) * 1000).toISOString(),
591
+ email: o.customer_email ?? '',
592
+ ...o.customer_name ? {
593
+ name: o.customer_name
594
+ } : {},
595
+ tags: {
596
+ ...invoiceTags(o)
597
+ }
598
+ });
599
+ /** Whether a verified event Stripe posted about the platform's own account is
600
+ * about a house sale, which `shopped` reads, rather than about the platform's
601
+ * plans, which ./plans.ts `changed` reads: a checkout carrying the house's
602
+ * mark, or a payment refunded or disputed. The platform's plans read neither
603
+ * of the second, and a refund or dispute of one of theirs reads as a payment
604
+ * the shops know nothing of. */ export let housed = (event)=>{
605
+ let e = event ?? {};
606
+ let type = e.type ?? '';
607
+ return type == 'checkout.session.completed' ? e.data?.object?.metadata?.[HOUSE] == 'true' : type == 'charge.refunded' || type.startsWith('charge.dispute.') || type.startsWith('refund.');
608
+ };
609
+ /** A verified event Stripe posted to the Connect endpoint, read, with the
610
+ * account it happened on: '' for one about a house sale, posted to the
611
+ * platform's own endpoint. */ export let shopped = (options)=>(event)=>{
612
+ let e = event ?? {};
613
+ let type = e.type ?? '';
614
+ let account = e.account ?? '';
615
+ let o = e.data?.object ?? {};
616
+ if (type == 'account.updated') {
617
+ return {
618
+ account,
619
+ about: 'seller',
620
+ seller: sellerOf(o)
621
+ };
622
+ }
623
+ if (type == 'account.application.deauthorized') {
624
+ return {
625
+ account,
626
+ about: 'revoked'
627
+ };
628
+ }
629
+ if (type == 'checkout.session.completed' || type == 'checkout.session.async_payment_succeeded' || type == 'checkout.session.async_payment_failed' || type == 'checkout.session.expired' && o.metadata?.fundraiser) {
630
+ let sale = paidOf(o);
631
+ if (type == 'checkout.session.async_payment_failed') {
632
+ sale.failed = true;
633
+ delete sale.processing;
634
+ }
635
+ if (sale.tags.fund && e.created && typeof e.livemode == 'boolean') {
636
+ sale.gift = {
637
+ at: new Date(e.created * 1000).toISOString(),
638
+ live: e.livemode
639
+ };
640
+ }
641
+ return {
642
+ account,
643
+ about: 'sale',
644
+ sale
645
+ };
646
+ }
647
+ let renewed = subscribedBy(type, o);
648
+ if (renewed != null) {
649
+ let invoice = type == 'invoice.paid' && renewed && o.paid_out_of_band !== true ? {
650
+ ...billedOf(o, renewed),
651
+ live: e.livemode
652
+ } : undefined;
653
+ return {
654
+ account,
655
+ about: 'term',
656
+ subscription: renewed,
657
+ tags: type.startsWith('customer.subscription.') ? o.metadata ?? {} : invoiceTags(o),
658
+ term: async ()=>renewed ? await termAt(options, account, renewed) : null,
659
+ ...invoice ? {
660
+ invoice
661
+ } : {}
662
+ };
663
+ }
664
+ if (type == 'refund.created' || type == 'refund.updated' || type == 'refund.failed') {
665
+ return {
666
+ account,
667
+ about: 'refund',
668
+ refund: refundedOf(o)
669
+ };
670
+ }
671
+ let c = o;
672
+ let to = settledBy(type, c);
673
+ if (!to) return {
674
+ account,
675
+ about: 'other'
676
+ };
677
+ return {
678
+ account,
679
+ about: 'payment',
680
+ to,
681
+ payment: async ()=>{
682
+ if (type == 'charge.refunded') return payment(c);
683
+ let charge = idOf(c.charge);
684
+ if (!charge) return null;
685
+ return payment(await ask(options, `/v1/charges/${encodeURIComponent(charge)}`, undefined, account));
686
+ }
687
+ };
688
+ };
689
+ //# sourceMappingURL=shops.js.map