@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/invoices.ts ADDED
@@ -0,0 +1,102 @@
1
+ import type { OneTimeInvoice, RecurringAddOn } from 'jsr:@yaks/host@0.2.36/payments'
2
+ import { ask, found, type Keyed, list } from './mod.js'
3
+
4
+ export let invoiceMethods = {
5
+ payment_method_types: ['card', 'us_bank_account'],
6
+ }
7
+
8
+ let product = 'prod_yaks_support_contract'
9
+
10
+ export let addOnPrice = async (at: Keyed, item: RecurringAddOn) => {
11
+ if (!await found(at, `/v1/products/${product}`)) {
12
+ await ask(
13
+ at,
14
+ '/v1/products',
15
+ { id: product, name: item.name },
16
+ undefined,
17
+ 'POST',
18
+ product,
19
+ )
20
+ }
21
+ return {
22
+ price_data: {
23
+ product,
24
+ currency: 'usd',
25
+ recurring: { interval: 'year' },
26
+ unit_amount: item.cents,
27
+ },
28
+ metadata: { yaks_add_on: item.key },
29
+ }
30
+ }
31
+
32
+ type Bill = {
33
+ id: string
34
+ status: string
35
+ metadata?: Record<string, string>
36
+ lines?: { data: { metadata?: Record<string, string> }[] }
37
+ }
38
+
39
+ /** A draft holds the line before Stripe finalizes and sends it. Each step
40
+ * can be replayed, including after Stripe has expired its idempotency keys. */
41
+ export let invoiceOnce = async (at: Keyed, item: OneTimeInvoice) => {
42
+ let invoice: Bill | undefined
43
+ for await (
44
+ let bill of list<Bill>(at, '/v1/invoices', { customer: item.payer })
45
+ ) {
46
+ if (bill.metadata?.yaks_once == item.key) {
47
+ invoice = bill
48
+ break
49
+ }
50
+ }
51
+ let key = `invoice-once|${item.key}`
52
+ if (!invoice) {
53
+ invoice = await ask(
54
+ at,
55
+ '/v1/invoices',
56
+ {
57
+ customer: item.payer,
58
+ collection_method: 'send_invoice',
59
+ days_until_due: item.due,
60
+ auto_advance: false,
61
+ pending_invoice_items_behavior: 'exclude',
62
+ payment_settings: invoiceMethods,
63
+ metadata: { ...item.tags, yaks_once: item.key },
64
+ },
65
+ undefined,
66
+ 'POST',
67
+ key,
68
+ ) as unknown as Bill
69
+ }
70
+ if (invoice.status == 'draft') {
71
+ if (
72
+ !invoice.lines?.data.some((line) => line.metadata?.yaks_once == item.key)
73
+ ) {
74
+ await ask(
75
+ at,
76
+ '/v1/invoiceitems',
77
+ {
78
+ customer: item.payer,
79
+ invoice: invoice.id,
80
+ amount: item.cents,
81
+ currency: 'usd',
82
+ description: item.name,
83
+ metadata: { yaks_once: item.key },
84
+ },
85
+ undefined,
86
+ 'POST',
87
+ `${key}|line`,
88
+ )
89
+ }
90
+ await ask(
91
+ at,
92
+ `/v1/invoices/${invoice.id}/finalize`,
93
+ {
94
+ auto_advance: true,
95
+ },
96
+ undefined,
97
+ 'POST',
98
+ `${key}|finalize`,
99
+ )
100
+ }
101
+ return invoice.id
102
+ }
package/mod.js ADDED
@@ -0,0 +1,118 @@
1
+ // One call to Stripe, over fetch: the whole Stripe client. It reads no
2
+ // environment; whoever calls it lends the key, and the clock its retries wait
3
+ // on.
4
+ //
5
+ // No SDK: the whole surface used is a few form-encoded POSTs and GETs, and an
6
+ // SDK would be a build step for less code than this.
7
+ import { sleep } from "@yaks/fp";
8
+ let API = 'https://api.stripe.com';
9
+ // Stripe's form encoding: nested keys are `a[b][c]`, and everything is a
10
+ // string. Undefined and null are left out rather than sent empty — an empty
11
+ // `customer` is not the same ask as no customer at all.
12
+ export let form = (fields, prefix = '')=>{
13
+ let out = [];
14
+ for (let [k, v] of Object.entries(fields)){
15
+ let at = prefix ? `${prefix}[${k}]` : k;
16
+ if (v == null) continue;
17
+ if (typeof v == 'object') {
18
+ out.push(...form(v, at));
19
+ } else out.push([
20
+ at,
21
+ String(v)
22
+ ]);
23
+ }
24
+ return out;
25
+ };
26
+ // A Stripe error as the sentence it gave us. Its own `message` is written for
27
+ // a person to read, so it is the one worth keeping; the code is what a log
28
+ // needs and rides beside it, and what a caller tells one refusal from another
29
+ // by (`code`).
30
+ export class StripeError extends Error {
31
+ code;
32
+ constructor(body, status){
33
+ let said = body;
34
+ // Connect's OAuth endpoints say it the OAuth way: the code in `error`,
35
+ // the sentence beside it.
36
+ let e = typeof said?.error == 'string' ? {
37
+ code: said.error,
38
+ message: said.error_description
39
+ } : said?.error;
40
+ super(e?.message ? `stripe: ${e.message}${e.code ? ` (${e.code})` : ''}` : `stripe: HTTP ${status}`);
41
+ this.code = e?.code;
42
+ }
43
+ }
44
+ /** The least Stripe charges in a currency, in its smallest unit; 0 where
45
+ * none is known here. */ export let minimum = (currency)=>currency.toUpperCase() == 'USD' ? 50 : 0;
46
+ /** The id of an object Stripe names by id or expanded whole. */ export let idOf = (v)=>typeof v == 'string' ? v : v?.id ?? '';
47
+ /** What Stripe holds at `path`, on account `on` where one is named; null
48
+ * where it holds nothing by that name, which Stripe says as a refusal. */ export let found = (at, path, on)=>ask(at, path, undefined, on).catch((e)=>{
49
+ if (e instanceof StripeError && e.code == 'resource_missing') return null;
50
+ throw e;
51
+ });
52
+ /** Rows from a Stripe list, including every page. */ export let list = async function*(at, path, fields) {
53
+ let next;
54
+ do {
55
+ let query = new URLSearchParams({
56
+ ...fields,
57
+ limit: '100',
58
+ ...next ? {
59
+ starting_after: next
60
+ } : {}
61
+ });
62
+ let page = await ask(at, `${path}?${query}`);
63
+ for (let row of page.data)yield row;
64
+ next = page.has_more ? page.data.at(-1)?.id : undefined;
65
+ }while (next)
66
+ };
67
+ // One call. A GET has no body; a POST is form-encoded, which is the only shape
68
+ // Stripe's v1 API takes. `path` is on the API's host unless it names another
69
+ // of Stripe's own, as Connect's OAuth endpoints do (connect.stripe.com).
70
+ //
71
+ // `on` is a connected account: the platform key acting on somebody
72
+ // else's account, which Stripe reads off the `Stripe-Account` header and
73
+ // nothing else — the same key, the same path, a different merchant. It is one
74
+ // header rather than a second client because it is one header: a direct charge
75
+ // differs from our own only in whose books it lands on.
76
+ //
77
+ // A call that did not get through — the connection lost on the way, or Stripe
78
+ // saying another request held the object (`Stripe-Should-Retry: true`) — is
79
+ // asked again, as Stripe's own libraries do, under one `Idempotency-Key`, so a
80
+ // write asked twice is one write. {@link TRIES} times in all, a half second
81
+ // and then a second apart on the lent clock: a person is waiting on the
82
+ // answer.
83
+ export let TRIES = 3;
84
+ export let ask = async (at, path, fields, on, method = fields ? 'POST' : 'GET', key)=>{
85
+ if (!at.key) throw new Error('stripe: no key was lent');
86
+ let body = fields ? new URLSearchParams(form(fields)).toString() : undefined;
87
+ let headers = {
88
+ authorization: `Bearer ${at.key}`,
89
+ ...on ? {
90
+ 'stripe-account': on
91
+ } : {},
92
+ ...method == 'POST' ? {
93
+ 'idempotency-key': key ?? crypto.randomUUID()
94
+ } : {},
95
+ ...body == null ? {} : {
96
+ 'content-type': 'application/x-www-form-urlencoded'
97
+ }
98
+ };
99
+ for(let n = 1;; n++){
100
+ let last = n == TRIES;
101
+ let r = await fetch(new URL(path, API), {
102
+ method,
103
+ headers,
104
+ body
105
+ }).catch((e)=>{
106
+ if (last) throw e;
107
+ return null;
108
+ });
109
+ if (r && (last || r.headers.get('stripe-should-retry') != 'true')) {
110
+ let out = await r.json().catch(()=>null);
111
+ if (!r.ok) throw new StripeError(out, r.status);
112
+ return out;
113
+ }
114
+ await r?.body?.cancel();
115
+ await sleep(500 * n, undefined, at.clock);
116
+ }
117
+ };
118
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,8EAA8E;AAC9E,MAAM;AACN,EAAE;AACF,8EAA8E;AAC9E,qDAAqD;AACrD,SAAqB,KAAK,wBAA6B;AAEvD,IAAI,MAAM;AAEV,yEAAyE;AACzE,4EAA4E;AAC5E,wDAAwD;AACxD,OAAO,IAAI,OAAO,CAChB,QACA,SAAS,EAAE;EAEX,IAAI,MAA0B,EAAE;EAChC,KAAK,IAAI,CAAC,GAAG,EAAE,IAAI,OAAO,O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7D,KAAK,CAAC,CAAC;MACN,IAAI,MAAM,MAAM;MAChB,OAAO;IACT;IACF,IAAI,KAAK,CAAC,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,0BAA0B,MAAM,GAAG;MACjE,IAAI,MAAM,MAAM,EAAE,IAAI,GAAG,KAAK,CAAC,IAAM;MACrC,IAAI,CAAC,EAAE,EAAE,EAAE,MAAM,IAAI,YAAY,KAAK,EAAE,MAAM;MAC9C,OAAO;IACT;IACA,MAAM,GAAG,MAAM;IACf,MAAM,MAAM,MAAM,GAAG,WAAW,GAAG,KAAK;EAC1C;AACF,EAAC"}
package/mod.ts ADDED
@@ -0,0 +1,154 @@
1
+ // One call to Stripe, over fetch: the whole Stripe client. It reads no
2
+ // environment; whoever calls it lends the key, and the clock its retries wait
3
+ // on.
4
+ //
5
+ // No SDK: the whole surface used is a few form-encoded POSTs and GETs, and an
6
+ // SDK would be a build step for less code than this.
7
+ import { type Clock, sleep } from '@yaks/fp'
8
+
9
+ let API = 'https://api.stripe.com'
10
+
11
+ // Stripe's form encoding: nested keys are `a[b][c]`, and everything is a
12
+ // string. Undefined and null are left out rather than sent empty — an empty
13
+ // `customer` is not the same ask as no customer at all.
14
+ export let form = (
15
+ fields: Record<string, unknown>,
16
+ prefix = '',
17
+ ): [string, string][] => {
18
+ let out: [string, string][] = []
19
+ for (let [k, v] of Object.entries(fields)) {
20
+ let at = prefix ? `${prefix}[${k}]` : k
21
+ if (v == null) continue
22
+ if (typeof v == 'object') {
23
+ out.push(...form(v as Record<string, unknown>, at))
24
+ } else out.push([at, String(v)])
25
+ }
26
+ return out
27
+ }
28
+
29
+ // A Stripe error as the sentence it gave us. Its own `message` is written for
30
+ // a person to read, so it is the one worth keeping; the code is what a log
31
+ // needs and rides beside it, and what a caller tells one refusal from another
32
+ // by (`code`).
33
+ export class StripeError extends Error {
34
+ code?: string
35
+ constructor(body: unknown, status: number) {
36
+ let said = body as {
37
+ error?: string | { message?: string; code?: string }
38
+ error_description?: string
39
+ }
40
+ // Connect's OAuth endpoints say it the OAuth way: the code in `error`,
41
+ // the sentence beside it.
42
+ let e = typeof said?.error == 'string'
43
+ ? { code: said.error, message: said.error_description }
44
+ : said?.error
45
+ super(
46
+ e?.message
47
+ ? `stripe: ${e.message}${e.code ? ` (${e.code})` : ''}`
48
+ : `stripe: HTTP ${status}`,
49
+ )
50
+ this.code = e?.code
51
+ }
52
+ }
53
+
54
+ /** The least Stripe charges in a currency, in its smallest unit; 0 where
55
+ * none is known here. */
56
+ export let minimum = (currency: string): number =>
57
+ currency.toUpperCase() == 'USD' ? 50 : 0
58
+
59
+ /** The id of an object Stripe names by id or expanded whole. */
60
+ export let idOf = (
61
+ v: string | { id?: string } | null | undefined,
62
+ ): string => typeof v == 'string' ? v : v?.id ?? ''
63
+
64
+ /** What Stripe holds at `path`, on account `on` where one is named; null
65
+ * where it holds nothing by that name, which Stripe says as a refusal. */
66
+ export let found = (
67
+ at: Keyed,
68
+ path: string,
69
+ on?: string,
70
+ ): Promise<Record<string, unknown> | null> =>
71
+ ask(at, path, undefined, on).catch((e) => {
72
+ if (e instanceof StripeError && e.code == 'resource_missing') return null
73
+ throw e
74
+ })
75
+
76
+ /** Rows from a Stripe list, including every page. */
77
+ export let list = async function* <T extends { id: string }>(
78
+ at: Keyed,
79
+ path: string,
80
+ fields: Record<string, string>,
81
+ ): AsyncGenerator<T> {
82
+ let next: string | undefined
83
+ do {
84
+ let query = new URLSearchParams({
85
+ ...fields,
86
+ limit: '100',
87
+ ...next ? { starting_after: next } : {},
88
+ })
89
+ let page = await ask(at, `${path}?${query}`) as {
90
+ data: T[]
91
+ has_more: boolean
92
+ }
93
+ for (let row of page.data) yield row
94
+ next = page.has_more ? page.data.at(-1)?.id : undefined
95
+ } while (next)
96
+ }
97
+
98
+ // One call. A GET has no body; a POST is form-encoded, which is the only shape
99
+ // Stripe's v1 API takes. `path` is on the API's host unless it names another
100
+ // of Stripe's own, as Connect's OAuth endpoints do (connect.stripe.com).
101
+ //
102
+ // `on` is a connected account: the platform key acting on somebody
103
+ // else's account, which Stripe reads off the `Stripe-Account` header and
104
+ // nothing else — the same key, the same path, a different merchant. It is one
105
+ // header rather than a second client because it is one header: a direct charge
106
+ // differs from our own only in whose books it lands on.
107
+ //
108
+ // A call that did not get through — the connection lost on the way, or Stripe
109
+ // saying another request held the object (`Stripe-Should-Retry: true`) — is
110
+ // asked again, as Stripe's own libraries do, under one `Idempotency-Key`, so a
111
+ // write asked twice is one write. {@link TRIES} times in all, a half second
112
+ // and then a second apart on the lent clock: a person is waiting on the
113
+ // answer.
114
+ export let TRIES = 3
115
+
116
+ /** What a call is made with: the secret key, and the clock retries wait on. */
117
+ export type Keyed = { key?: string; clock?: Clock }
118
+
119
+ export let ask = async (
120
+ at: Keyed,
121
+ path: string,
122
+ fields?: Record<string, unknown>,
123
+ on?: string,
124
+ method = fields ? 'POST' : 'GET',
125
+ key?: string,
126
+ ): Promise<Record<string, unknown>> => {
127
+ if (!at.key) throw new Error('stripe: no key was lent')
128
+ let body = fields ? new URLSearchParams(form(fields)).toString() : undefined
129
+ let headers = {
130
+ authorization: `Bearer ${at.key}`,
131
+ ...(on ? { 'stripe-account': on } : {}),
132
+ ...(method == 'POST'
133
+ ? { 'idempotency-key': key ?? crypto.randomUUID() }
134
+ : {}),
135
+ ...(body == null
136
+ ? {}
137
+ : { 'content-type': 'application/x-www-form-urlencoded' }),
138
+ }
139
+ for (let n = 1;; n++) {
140
+ let last = n == TRIES
141
+ let r = await fetch(new URL(path, API), { method, headers, body })
142
+ .catch((e) => {
143
+ if (last) throw e
144
+ return null
145
+ })
146
+ if (r && (last || r.headers.get('stripe-should-retry') != 'true')) {
147
+ let out = await r.json().catch(() => null)
148
+ if (!r.ok) throw new StripeError(out, r.status)
149
+ return out as Record<string, unknown>
150
+ }
151
+ await r?.body?.cancel()
152
+ await sleep(500 * n, undefined, at.clock)
153
+ }
154
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@yaks/stripe",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/stripe",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./doors": {
12
+ "types": "./_dist/doors.d.ts",
13
+ "default": "./doors.js"
14
+ },
15
+ "./graph": {
16
+ "types": "./_dist/graph.d.ts",
17
+ "default": "./graph.js"
18
+ },
19
+ "./plans": {
20
+ "types": "./_dist/plans.d.ts",
21
+ "default": "./plans.js"
22
+ },
23
+ "./testing": {
24
+ "types": "./_dist/testing.d.ts",
25
+ "default": "./testing.js"
26
+ },
27
+ "./shops": {
28
+ "types": "./_dist/shops.d.ts",
29
+ "default": "./shops.js"
30
+ }
31
+ },
32
+ "license": "Apache-2.0",
33
+ "dependencies": {
34
+ "@yaks/fp": "0.2.36",
35
+ "@yaks/hook": "0.2.36",
36
+ "@yaks/host": "0.2.36"
37
+ },
38
+ "description": "Stripe's API over fetch, and the plans, shops and signed webhook doors it lends a host as a payment provider.",
39
+ "repository": "https://github.com/yak-sh/yak.git"
40
+ }