@inferencebureau/apps-sdk 0.16.12 → 0.16.13
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/dist/stripe.d.ts +85 -2
- package/dist/stripe.js +128 -2
- package/package.json +1 -1
package/dist/stripe.d.ts
CHANGED
|
@@ -7,10 +7,16 @@
|
|
|
7
7
|
* Its calls go through `fetch`, so inside an action each one is a `stripe` call in the run's trace in Logs. It uses the
|
|
8
8
|
* API version of the `stripe` package the app installs (`npm install stripe`), so the types match what Stripe answers.
|
|
9
9
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
10
|
+
* The common path has helpers over the synced `stripeCustomer` and `stripeSubscription` models (Inference Bureau keeps
|
|
11
|
+
* them from Stripe's webhooks): `checkout(user, …)` for a Checkout URL, `billingPortal(user, …)` for the customer
|
|
12
|
+
* portal, `subscriptionOf(user)` and `requireSubscription(user, …)` for access checks.
|
|
13
|
+
*
|
|
14
|
+
* import { checkout, requireSubscription } from "@inferencebureau/apps-sdk/stripe";
|
|
15
|
+
* const url = await checkout(user, { price: "pro_monthly", successUrl, cancelUrl });
|
|
16
|
+
* await requireSubscription(user, { prices: ["pro_monthly"] });
|
|
12
17
|
*/
|
|
13
18
|
import Stripe from "stripe";
|
|
19
|
+
import { type Api } from "./index.js";
|
|
14
20
|
/**
|
|
15
21
|
* The Stripe client for the environment's key, made once per key. `apiKey` overrides STRIPE_SECRET_KEY (a connected
|
|
16
22
|
* account's, say). Throws when there's no key: connect Stripe in Settings → Integrations.
|
|
@@ -19,3 +25,80 @@ export declare function stripe(o?: {
|
|
|
19
25
|
apiKey?: string;
|
|
20
26
|
}): Stripe;
|
|
21
27
|
export type { Stripe };
|
|
28
|
+
/** Who's paying: the app's `user` record, or anything with its id (and email, for Stripe's receipts). */
|
|
29
|
+
export interface StripeUser {
|
|
30
|
+
id: string;
|
|
31
|
+
email?: unknown;
|
|
32
|
+
}
|
|
33
|
+
interface Via {
|
|
34
|
+
api?: Api | undefined;
|
|
35
|
+
stripe?: Stripe | undefined;
|
|
36
|
+
}
|
|
37
|
+
/** The user's Stripe customer id, from the synced stripeCustomer; null when they have none yet or the app doesn't sync it. */
|
|
38
|
+
export declare function customerOf(user: StripeUser, o?: Pick<Via, "api">): Promise<string | null>;
|
|
39
|
+
export interface CheckoutOptions extends Via {
|
|
40
|
+
/** A price's id (`price_…`) or its lookup key (`pro_monthly`), which survives changing the price in Stripe. */
|
|
41
|
+
price: string;
|
|
42
|
+
/** `subscription` (the default) for a recurring price, `payment` for a one-time one. */
|
|
43
|
+
mode?: "subscription" | "payment";
|
|
44
|
+
/** Where Stripe sends them after paying. `{CHECKOUT_SESSION_ID}` in it is replaced with the session's id. */
|
|
45
|
+
successUrl: string;
|
|
46
|
+
/** Where Stripe sends them when they go back without paying. */
|
|
47
|
+
cancelUrl: string;
|
|
48
|
+
quantity?: number;
|
|
49
|
+
/** A subscription's free trial, in days. */
|
|
50
|
+
trialDays?: number;
|
|
51
|
+
allowPromotionCodes?: boolean;
|
|
52
|
+
/** Kept on the session (and the subscription or payment), for the app's own `stripe<Type>` actions to read. */
|
|
53
|
+
metadata?: Record<string, string>;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A Stripe Checkout URL for the user: redirect to it. Their Stripe customer is found (the synced stripeCustomer) or
|
|
57
|
+
* made with `metadata.ib_user`, so every payment of theirs is the same customer and the sync links it back to them.
|
|
58
|
+
* Access follows the webhook, not the redirect back: check `requireSubscription` on the page they return to.
|
|
59
|
+
*/
|
|
60
|
+
export declare function checkout(user: StripeUser, o: CheckoutOptions): Promise<string>;
|
|
61
|
+
/** A Stripe customer portal URL for the user, to manage their subscription, payment methods and invoices: redirect to it. */
|
|
62
|
+
export declare function billingPortal(user: StripeUser, o: Via & {
|
|
63
|
+
returnUrl: string;
|
|
64
|
+
}): Promise<string>;
|
|
65
|
+
/** A user's subscription as the synced stripeSubscription has it. */
|
|
66
|
+
export interface StripeSubscription {
|
|
67
|
+
/** Stripe's `sub_…` id. */
|
|
68
|
+
id: string;
|
|
69
|
+
status: string;
|
|
70
|
+
price: string | null;
|
|
71
|
+
lookupKey: string | null;
|
|
72
|
+
quantity: number | null;
|
|
73
|
+
currentPeriodEnd: string | null;
|
|
74
|
+
cancelAtPeriodEnd: boolean;
|
|
75
|
+
trialEnd: string | null;
|
|
76
|
+
inTrial: boolean;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The user's subscription: their live one (active, trialing or past due) with the latest period end, else their most
|
|
80
|
+
* recent; null when they've never subscribed or the app doesn't sync subscriptions.
|
|
81
|
+
*/
|
|
82
|
+
export declare function subscriptionOf(user: StripeUser, o?: Pick<Via, "api"> & {
|
|
83
|
+
now?: number;
|
|
84
|
+
}): Promise<StripeSubscription | null>;
|
|
85
|
+
/** A user without the subscription a page, route or action needs. `status` is 402; `toResponse()` answers it as JSON. */
|
|
86
|
+
export declare class SubscriptionRequiredError extends Error {
|
|
87
|
+
readonly prices: string[];
|
|
88
|
+
readonly current: StripeSubscription | null;
|
|
89
|
+
readonly status = 402;
|
|
90
|
+
constructor(message: string, prices: string[], current: StripeSubscription | null);
|
|
91
|
+
toResponse(): Response;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The user's subscription when it's active (or trialing, unless `allowTrial: false`) and, with `prices`, on one of them
|
|
95
|
+
* (price ids or lookup keys); else throws SubscriptionRequiredError. A past-due subscription doesn't pass: Stripe is
|
|
96
|
+
* still trying to take the payment.
|
|
97
|
+
*
|
|
98
|
+
* const sub = await requireSubscription(user, { prices: ["pro_monthly", "pro_yearly"] });
|
|
99
|
+
*/
|
|
100
|
+
export declare function requireSubscription(user: StripeUser | null, o?: Pick<Via, "api"> & {
|
|
101
|
+
prices?: string[];
|
|
102
|
+
allowTrial?: boolean;
|
|
103
|
+
now?: number;
|
|
104
|
+
}): Promise<StripeSubscription>;
|
package/dist/stripe.js
CHANGED
|
@@ -7,10 +7,16 @@
|
|
|
7
7
|
* Its calls go through `fetch`, so inside an action each one is a `stripe` call in the run's trace in Logs. It uses the
|
|
8
8
|
* API version of the `stripe` package the app installs (`npm install stripe`), so the types match what Stripe answers.
|
|
9
9
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
10
|
+
* The common path has helpers over the synced `stripeCustomer` and `stripeSubscription` models (Inference Bureau keeps
|
|
11
|
+
* them from Stripe's webhooks): `checkout(user, …)` for a Checkout URL, `billingPortal(user, …)` for the customer
|
|
12
|
+
* portal, `subscriptionOf(user)` and `requireSubscription(user, …)` for access checks.
|
|
13
|
+
*
|
|
14
|
+
* import { checkout, requireSubscription } from "@inferencebureau/apps-sdk/stripe";
|
|
15
|
+
* const url = await checkout(user, { price: "pro_monthly", successUrl, cancelUrl });
|
|
16
|
+
* await requireSubscription(user, { prices: ["pro_monthly"] });
|
|
12
17
|
*/
|
|
13
18
|
import Stripe from "stripe";
|
|
19
|
+
import { ApiError, createClient } from "./index.js";
|
|
14
20
|
const envVar = (name) => globalThis.process?.env?.[name];
|
|
15
21
|
const clients = new Map();
|
|
16
22
|
/**
|
|
@@ -33,3 +39,123 @@ export function stripe(o = {}) {
|
|
|
33
39
|
}
|
|
34
40
|
return client;
|
|
35
41
|
}
|
|
42
|
+
/** A synced model by name: the app's generated types may not have it. */
|
|
43
|
+
function model(api, name) {
|
|
44
|
+
return typeof api.$model === "function" ? api.$model(name) : api[name];
|
|
45
|
+
}
|
|
46
|
+
const notSynced = (e) => e instanceof ApiError && (e.status === 404 || e.code === "not_found");
|
|
47
|
+
/** The user's Stripe customer id, from the synced stripeCustomer; null when they have none yet or the app doesn't sync it. */
|
|
48
|
+
export async function customerOf(user, o = {}) {
|
|
49
|
+
try {
|
|
50
|
+
const r = await model(o.api ?? createClient(), "stripeCustomer").findFirst({ filter: { user: { equals: user.id } } });
|
|
51
|
+
return typeof r?.stripeId === "string" ? r.stripeId : null;
|
|
52
|
+
}
|
|
53
|
+
catch (e) {
|
|
54
|
+
if (notSynced(e))
|
|
55
|
+
return null;
|
|
56
|
+
throw e;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** A price id as given (`price_…`), or the id of the active price with that lookup key. */
|
|
60
|
+
async function priceId(s, price) {
|
|
61
|
+
if (price.startsWith("price_"))
|
|
62
|
+
return price;
|
|
63
|
+
const [found] = (await s.prices.list({ lookup_keys: [price], active: true, limit: 1 })).data;
|
|
64
|
+
if (!found)
|
|
65
|
+
throw new Error(`No active Stripe price has the lookup key ${price}. Set it on the price in Stripe (Product catalog → the price → Lookup key), or pass the price's id.`);
|
|
66
|
+
return found.id;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* A Stripe Checkout URL for the user: redirect to it. Their Stripe customer is found (the synced stripeCustomer) or
|
|
70
|
+
* made with `metadata.ib_user`, so every payment of theirs is the same customer and the sync links it back to them.
|
|
71
|
+
* Access follows the webhook, not the redirect back: check `requireSubscription` on the page they return to.
|
|
72
|
+
*/
|
|
73
|
+
export async function checkout(user, o) {
|
|
74
|
+
const s = o.stripe ?? stripe();
|
|
75
|
+
const api = o.api ?? createClient();
|
|
76
|
+
let customer = await customerOf(user, { api });
|
|
77
|
+
if (!customer) {
|
|
78
|
+
const c = await s.customers.create({ ...(typeof user.email === "string" && user.email ? { email: user.email } : {}), metadata: { ib_user: user.id } });
|
|
79
|
+
customer = c.id;
|
|
80
|
+
// Recorded now so a second click before the webhook arrives reuses it; the sync fills in the rest.
|
|
81
|
+
await model(api, "stripeCustomer").create({ stripeId: c.id, email: c.email ?? null, user: user.id }).catch(() => undefined);
|
|
82
|
+
}
|
|
83
|
+
const mode = o.mode ?? "subscription";
|
|
84
|
+
const metadata = { ...o.metadata, ib_user: user.id };
|
|
85
|
+
const session = await s.checkout.sessions.create({
|
|
86
|
+
mode, customer, client_reference_id: user.id, metadata,
|
|
87
|
+
line_items: [{ price: await priceId(s, o.price), quantity: o.quantity ?? 1 }],
|
|
88
|
+
success_url: o.successUrl, cancel_url: o.cancelUrl,
|
|
89
|
+
...(o.allowPromotionCodes ? { allow_promotion_codes: true } : {}),
|
|
90
|
+
...(mode === "subscription" ? { subscription_data: { metadata, ...(o.trialDays ? { trial_period_days: o.trialDays } : {}) } } : { payment_intent_data: { metadata } }),
|
|
91
|
+
});
|
|
92
|
+
if (!session.url)
|
|
93
|
+
throw new Error("Stripe made the Checkout Session without a URL.");
|
|
94
|
+
return session.url;
|
|
95
|
+
}
|
|
96
|
+
/** A Stripe customer portal URL for the user, to manage their subscription, payment methods and invoices: redirect to it. */
|
|
97
|
+
export async function billingPortal(user, o) {
|
|
98
|
+
const customer = await customerOf(user, o);
|
|
99
|
+
if (!customer)
|
|
100
|
+
throw new Error("This user has no Stripe customer yet: they get one the first time they go through checkout().");
|
|
101
|
+
const session = await (o.stripe ?? stripe()).billingPortal.sessions.create({ customer, return_url: o.returnUrl });
|
|
102
|
+
return session.url;
|
|
103
|
+
}
|
|
104
|
+
const LIVE = ["active", "trialing", "past_due"];
|
|
105
|
+
/**
|
|
106
|
+
* The user's subscription: their live one (active, trialing or past due) with the latest period end, else their most
|
|
107
|
+
* recent; null when they've never subscribed or the app doesn't sync subscriptions.
|
|
108
|
+
*/
|
|
109
|
+
export async function subscriptionOf(user, o = {}) {
|
|
110
|
+
let rows;
|
|
111
|
+
try {
|
|
112
|
+
rows = (await model(o.api ?? createClient(), "stripeSubscription").findMany({ filter: { user: { equals: user.id } }, sort: { currentPeriodEnd: "Descending" }, first: 20 })).records;
|
|
113
|
+
}
|
|
114
|
+
catch (e) {
|
|
115
|
+
if (notSynced(e))
|
|
116
|
+
return null;
|
|
117
|
+
throw e;
|
|
118
|
+
}
|
|
119
|
+
const r = rows.find((x) => LIVE.includes(String(x.status))) ?? rows[0];
|
|
120
|
+
if (!r)
|
|
121
|
+
return null;
|
|
122
|
+
const trialEnd = typeof r.trialEnd === "string" ? r.trialEnd : null;
|
|
123
|
+
return {
|
|
124
|
+
id: String(r.stripeId), status: String(r.status ?? ""), price: r.price ?? null, lookupKey: r.lookupKey ?? null,
|
|
125
|
+
quantity: typeof r.quantity === "number" ? r.quantity : null, currentPeriodEnd: r.currentPeriodEnd ?? null,
|
|
126
|
+
cancelAtPeriodEnd: r.cancelAtPeriodEnd === true, trialEnd, inTrial: r.status === "trialing" && !!trialEnd && Date.parse(trialEnd) > (o.now ?? Date.now()),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
/** A user without the subscription a page, route or action needs. `status` is 402; `toResponse()` answers it as JSON. */
|
|
130
|
+
export class SubscriptionRequiredError extends Error {
|
|
131
|
+
prices;
|
|
132
|
+
current;
|
|
133
|
+
status = 402;
|
|
134
|
+
constructor(message, prices, current) {
|
|
135
|
+
super(message);
|
|
136
|
+
this.prices = prices;
|
|
137
|
+
this.current = current;
|
|
138
|
+
}
|
|
139
|
+
toResponse() {
|
|
140
|
+
return Response.json({ error: { code: "subscription_required", message: this.message, prices: this.prices, current: this.current?.status ?? null } }, { status: 402 });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The user's subscription when it's active (or trialing, unless `allowTrial: false`) and, with `prices`, on one of them
|
|
145
|
+
* (price ids or lookup keys); else throws SubscriptionRequiredError. A past-due subscription doesn't pass: Stripe is
|
|
146
|
+
* still trying to take the payment.
|
|
147
|
+
*
|
|
148
|
+
* const sub = await requireSubscription(user, { prices: ["pro_monthly", "pro_yearly"] });
|
|
149
|
+
*/
|
|
150
|
+
export async function requireSubscription(user, o = {}) {
|
|
151
|
+
const want = (o.prices ?? []).filter(Boolean);
|
|
152
|
+
if (!user)
|
|
153
|
+
throw new SubscriptionRequiredError("Sign in to subscribe.", want, null);
|
|
154
|
+
const sub = await subscriptionOf(user, o);
|
|
155
|
+
const ok = sub && (sub.status === "active" || (sub.status === "trialing" && o.allowTrial !== false));
|
|
156
|
+
if (!sub || !ok)
|
|
157
|
+
throw new SubscriptionRequiredError(sub ? `The subscription is ${sub.status.replace(/_/g, " ")}; this needs an active one.` : "This needs a subscription.", want, sub);
|
|
158
|
+
if (want.length && !want.some((p) => p === sub.price || p === sub.lookupKey))
|
|
159
|
+
throw new SubscriptionRequiredError(`This needs ${want.join(" or ")}.`, want, sub);
|
|
160
|
+
return sub;
|
|
161
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inferencebureau/apps-sdk",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.13",
|
|
4
4
|
"description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types, the records API client, React hooks with AutoTable and AutoForm, and a test harness for its actions.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"keywords": [
|