@hjam91/billing 0.0.0-stage → 0.7.0

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.
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Optional React billing card: plan, next billing date, auto-renew toggle and
3
+ * a Manage billing button.
4
+ *
5
+ * BROWSER-SAFE: it calls the APP's own backend routes (billingRoutes() in
6
+ * '@hjam91/billing/hono', mounted at `basePath`), never the billing service,
7
+ * so the app secret stays on the server. It imports only types from the rest
8
+ * of the SDK.
9
+ *
10
+ * Written with createElement (no JSX) so it needs no build step. Unstyled:
11
+ * every element has a `bk-` class name for the app to style.
12
+ *
13
+ * import { BillingCard } from '@hjam91/billing/react';
14
+ * <BillingCard basePath="/api/billing" plan="pro" />
15
+ */
16
+ import { type ReactElement, type ReactNode } from 'react';
17
+ import type { AccountStatus, FeatureReason, FeatureType } from './types.js';
18
+ /** What the app's GET {basePath} returns: the service status + whether this viewer may manage it. */
19
+ export type BillingStatus = AccountStatus & {
20
+ viewer_can_manage?: boolean;
21
+ };
22
+ export interface UseBillingOptions {
23
+ /** Where billingRoutes() is mounted. Default "/api/billing". */
24
+ basePath?: string;
25
+ /** fetch to use (e.g. one that adds an auth header). Default: global fetch with credentials. */
26
+ fetch?: typeof fetch;
27
+ /** Skip the first fetch (server-rendered or tests). */
28
+ initialStatus?: BillingStatus;
29
+ /** Navigation for Checkout/portal URLs. Default: window.location.assign. */
30
+ navigate?: (url: string) => void;
31
+ }
32
+ export interface UseBilling {
33
+ status: BillingStatus | null;
34
+ /** True until the first load settles (one-shot: never flips back). */
35
+ booting: boolean;
36
+ /** An action is in flight. */
37
+ busy: boolean;
38
+ error: string | null;
39
+ refresh(): Promise<void>;
40
+ subscribe(plan: string, quantity?: number): Promise<void>;
41
+ openPortal(): Promise<void>;
42
+ setAutoRenew(on: boolean): Promise<void>;
43
+ }
44
+ export declare function useBilling(opts?: UseBillingOptions): UseBilling;
45
+ export interface BillingCardModel {
46
+ /** One-line headline, e.g. "Pro × 2" or "Free trial". */
47
+ title: string;
48
+ /** Short facts, in display order. */
49
+ lines: string[];
50
+ showSubscribe: boolean;
51
+ showManage: boolean;
52
+ showAutoRenew: boolean;
53
+ autoRenew: boolean;
54
+ }
55
+ /**
56
+ * Pure: what the card shows for a status. Exported so apps with their own UI
57
+ * can reuse the wording rules, and so they are testable without a DOM.
58
+ */
59
+ export declare function billingCardModel(s: BillingStatus, locale?: string): BillingCardModel;
60
+ export interface BillingCardProps extends UseBillingOptions {
61
+ /** Plan offered by the Subscribe button. */
62
+ plan?: string;
63
+ quantity?: number;
64
+ className?: string;
65
+ locale?: string;
66
+ }
67
+ export declare function BillingCard(props: BillingCardProps): ReactElement;
68
+ /** What the app's GET {basePath}/check answers (billingRoutes in '@hjam91/billing/hono'). */
69
+ export interface FeatureCheck {
70
+ feature_id: string;
71
+ allowed: boolean;
72
+ type: FeatureType | null;
73
+ balance: number | null;
74
+ included: number | null;
75
+ usage: number | null;
76
+ unlimited: boolean;
77
+ resets_at: string | null;
78
+ plan: string | null;
79
+ reason: FeatureReason;
80
+ /** Since 0.6.0, only when credits / grants / overage are in play. */
81
+ granted?: number;
82
+ credit_feature_id?: string;
83
+ credit_rate?: number;
84
+ }
85
+ export interface UseFeatureOptions {
86
+ /** Where billingRoutes() is mounted. Default "/api/billing". */
87
+ basePath?: string;
88
+ fetch?: typeof fetch;
89
+ /** How much the UI needs (default 1). */
90
+ requiredBalance?: number;
91
+ /** Skip the first fetch (server-rendered or tests). */
92
+ initial?: FeatureCheck;
93
+ }
94
+ export interface UseFeature {
95
+ /** null until the first answer (one-shot loading: never flips back). */
96
+ allowed: boolean | null;
97
+ /** What is left (credits for a feature drawing from a credit pool); null for on/off, unlimited, or before the first answer. Since 0.6.0. */
98
+ balance: number | null;
99
+ loading: boolean;
100
+ check: FeatureCheck | null;
101
+ refresh(): Promise<void>;
102
+ }
103
+ /**
104
+ * The browser side of a feature gate: asks the APP's backend (GET {basePath}/check), never the
105
+ * billing service. UX only — the server enforces with requireFeature / track. A failed request
106
+ * fails OPEN (allowed, reason 'unverified'), like every billing check: an outage never hides a
107
+ * feature someone paid for.
108
+ */
109
+ export declare function useFeature(featureId: string, opts?: UseFeatureOptions): UseFeature;
110
+ export interface GateProps extends UseFeatureOptions {
111
+ feature: string;
112
+ /** Shown when the feature is not allowed (an upgrade prompt). Default: nothing. */
113
+ fallback?: ReactNode | ((check: FeatureCheck) => ReactNode);
114
+ /** Shown until the first answer. Default: nothing. */
115
+ loading?: ReactNode;
116
+ children?: ReactNode;
117
+ }
118
+ /** <Gate feature="export" fallback={<Upgrade />}>…</Gate> — renders children only when the feature is allowed. */
119
+ export declare function Gate(props: GateProps): ReactElement | null;
package/dist/react.js ADDED
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Optional React billing card: plan, next billing date, auto-renew toggle and
3
+ * a Manage billing button.
4
+ *
5
+ * BROWSER-SAFE: it calls the APP's own backend routes (billingRoutes() in
6
+ * '@hjam91/billing/hono', mounted at `basePath`), never the billing service,
7
+ * so the app secret stays on the server. It imports only types from the rest
8
+ * of the SDK.
9
+ *
10
+ * Written with createElement (no JSX) so it needs no build step. Unstyled:
11
+ * every element has a `bk-` class name for the app to style.
12
+ *
13
+ * import { BillingCard } from '@hjam91/billing/react';
14
+ * <BillingCard basePath="/api/billing" plan="pro" />
15
+ */
16
+ import { Fragment, createElement as h, useCallback, useEffect, useRef, useState } from 'react';
17
+ export function useBilling(opts = {}) {
18
+ const base = (opts.basePath ?? '/api/billing').replace(/\/+$/, '');
19
+ const doFetch = opts.fetch ?? ((input, init) => fetch(input, { credentials: 'same-origin', ...init }));
20
+ const navigate = opts.navigate ?? ((url) => window.location.assign(url));
21
+ const [status, setStatus] = useState(opts.initialStatus ?? null);
22
+ const [booting, setBooting] = useState(!opts.initialStatus);
23
+ const [busy, setBusy] = useState(false);
24
+ const [error, setError] = useState(null);
25
+ const mounted = useRef(true);
26
+ const request = useCallback(async (method, path, body) => {
27
+ const res = await doFetch(`${base}${path}`, {
28
+ method,
29
+ headers: body !== undefined ? { 'Content-Type': 'application/json' } : undefined,
30
+ body: body !== undefined ? JSON.stringify(body) : undefined,
31
+ });
32
+ const data = await res.json().catch(() => null);
33
+ if (!res.ok)
34
+ throw new Error(data?.message ?? data?.error ?? `HTTP ${res.status}`);
35
+ return data;
36
+ },
37
+ // `fetch` is configuration: read on the first render only.
38
+ [base]);
39
+ const refresh = useCallback(async () => {
40
+ try {
41
+ const s = await request('GET', '');
42
+ if (mounted.current) {
43
+ setStatus(s);
44
+ setError(null);
45
+ }
46
+ }
47
+ catch (e) {
48
+ // A failed load is an error, never an empty billing page.
49
+ if (mounted.current)
50
+ setError(e.message);
51
+ }
52
+ finally {
53
+ if (mounted.current)
54
+ setBooting(false);
55
+ }
56
+ }, [request]);
57
+ useEffect(() => {
58
+ mounted.current = true;
59
+ if (!opts.initialStatus)
60
+ void refresh();
61
+ return () => {
62
+ mounted.current = false;
63
+ };
64
+ }, []); // load once on mount
65
+ const act = useCallback(async (fn) => {
66
+ setBusy(true);
67
+ setError(null);
68
+ try {
69
+ await fn();
70
+ }
71
+ catch (e) {
72
+ if (mounted.current)
73
+ setError(e.message);
74
+ }
75
+ finally {
76
+ if (mounted.current)
77
+ setBusy(false);
78
+ }
79
+ }, []);
80
+ return {
81
+ status,
82
+ booting,
83
+ busy,
84
+ error,
85
+ refresh,
86
+ subscribe: (plan, quantity) => act(async () => navigate((await request('POST', '/checkout', { plan, quantity })).url)),
87
+ openPortal: () => act(async () => navigate((await request('POST', '/portal', {})).url)),
88
+ setAutoRenew: (on) => act(async () => setStatus(await request('POST', '/autorenew', { auto_renew: on }))),
89
+ };
90
+ }
91
+ const fmtDate = (iso, locale) => iso ? new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone: 'UTC' }).format(new Date(iso)) : '';
92
+ /**
93
+ * Pure: what the card shows for a status. Exported so apps with their own UI
94
+ * can reuse the wording rules, and so they are testable without a DOM.
95
+ */
96
+ export function billingCardModel(s, locale) {
97
+ const ent = s.entitlement;
98
+ const canManage = s.viewer_can_manage !== false;
99
+ const sub = s.subscription;
100
+ const lines = [];
101
+ const model = { title: '', lines, showSubscribe: false, showManage: false, showAutoRenew: false, autoRenew: s.auto_renew };
102
+ if (s.exempt) {
103
+ model.title = 'Free account';
104
+ lines.push('This account is not billed.');
105
+ return model;
106
+ }
107
+ if (s.covered_by_account_id && !sub) {
108
+ model.title = ent.active ? 'Covered' : 'Not covered';
109
+ lines.push(`Billing is managed by ${s.covered_by_account_id}.`);
110
+ return model;
111
+ }
112
+ if (sub && s.has_subscription) {
113
+ model.title = `${sub.plan ?? 'Subscription'}${sub.quantity > 1 ? ` × ${sub.quantity}` : ''}`;
114
+ if (sub.status === 'past_due' || sub.status === 'unpaid')
115
+ lines.push('Payment failed — update your card to keep access.');
116
+ if (ent.reason === 'trial' && ent.trial_ends_at)
117
+ lines.push(`Free until ${fmtDate(ent.trial_ends_at, locale)}`);
118
+ lines.push(sub.auto_renew && sub.next_billing_date
119
+ ? `Next billing date: ${fmtDate(sub.next_billing_date, locale)}`
120
+ : `Ends on ${fmtDate(sub.current_period_end, locale)} (auto-renew is off)`);
121
+ model.showManage = canManage && s.can_manage;
122
+ model.showAutoRenew = canManage && s.can_manage;
123
+ if (s.subscriptions.length > 1)
124
+ lines.push(`${s.subscriptions.length} subscriptions on this account — see Manage billing.`);
125
+ return model;
126
+ }
127
+ // No live subscription: trial, grace or nothing.
128
+ if (ent.reason === 'trial') {
129
+ model.title = 'Free trial';
130
+ lines.push(`Free until ${fmtDate(ent.trial_ends_at, locale)}`);
131
+ }
132
+ else if (ent.reason === 'grace') {
133
+ model.title = 'Grace period';
134
+ lines.push(`Access ends on ${fmtDate(ent.grace_ends_at, locale)}`);
135
+ }
136
+ else if (ent.reason === 'paid') {
137
+ model.title = 'Canceled';
138
+ lines.push(`Access until ${fmtDate(sub?.paid_through ?? ent.current_period_end, locale)}`);
139
+ }
140
+ else {
141
+ model.title = 'No subscription';
142
+ }
143
+ model.showSubscribe = canManage;
144
+ model.showManage = canManage && s.can_manage; // past invoices remain in the portal
145
+ return model;
146
+ }
147
+ export function BillingCard(props) {
148
+ const b = useBilling(props);
149
+ const cls = ['bk-card', props.className].filter(Boolean).join(' ');
150
+ // First-paint rule: a loader until the first fetch settles, never an empty state.
151
+ if (b.booting)
152
+ return h('div', { className: cls }, h('div', { className: 'bk-loading' }, 'Loading…'));
153
+ if (!b.status)
154
+ return h('div', { className: cls }, h('div', { className: 'bk-error', role: 'alert' }, `Billing unavailable: ${b.error ?? 'unknown error'}`));
155
+ const m = billingCardModel(b.status, props.locale);
156
+ return h('div', { className: cls }, h('div', { className: 'bk-title' }, m.title), ...m.lines.map((line, i) => h('div', { key: i, className: 'bk-line' }, line)), m.showAutoRenew
157
+ ? h('label', { className: 'bk-autorenew' }, h('input', { type: 'checkbox', checked: m.autoRenew, disabled: b.busy, onChange: (e) => void b.setAutoRenew(e.target.checked) }), ' Auto-renew')
158
+ : null, h('div', { className: 'bk-actions' }, m.showSubscribe && props.plan
159
+ ? h('button', { type: 'button', className: 'bk-subscribe', disabled: b.busy, onClick: () => void b.subscribe(props.plan, props.quantity) }, 'Subscribe')
160
+ : null, m.showManage ? h('button', { type: 'button', className: 'bk-manage', disabled: b.busy, onClick: () => void b.openPortal() }, 'Manage billing') : null), b.error ? h('div', { className: 'bk-error', role: 'alert' }, b.error) : null);
161
+ }
162
+ /**
163
+ * The browser side of a feature gate: asks the APP's backend (GET {basePath}/check), never the
164
+ * billing service. UX only — the server enforces with requireFeature / track. A failed request
165
+ * fails OPEN (allowed, reason 'unverified'), like every billing check: an outage never hides a
166
+ * feature someone paid for.
167
+ */
168
+ export function useFeature(featureId, opts = {}) {
169
+ const base = (opts.basePath ?? '/api/billing').replace(/\/+$/, '');
170
+ const doFetch = opts.fetch ?? ((input, init) => fetch(input, { credentials: 'same-origin', ...init }));
171
+ const [check, setCheck] = useState(opts.initial ?? null);
172
+ const mounted = useRef(true);
173
+ const refresh = useCallback(async () => {
174
+ const q = new URLSearchParams({ feature_id: featureId });
175
+ if (opts.requiredBalance !== undefined)
176
+ q.set('required_balance', String(opts.requiredBalance));
177
+ let next;
178
+ try {
179
+ const res = await doFetch(`${base}/check?${q}`);
180
+ const data = (await res.json().catch(() => null));
181
+ if (!res.ok || !data)
182
+ throw new Error(`HTTP ${res.status}`);
183
+ next = data;
184
+ }
185
+ catch {
186
+ next = { feature_id: featureId, allowed: true, type: null, balance: null, included: null, usage: null, unlimited: false, resets_at: null, plan: null, reason: 'unverified' };
187
+ }
188
+ if (mounted.current)
189
+ setCheck(next);
190
+ // `fetch` is configuration: read on the first render only.
191
+ }, [base, featureId, opts.requiredBalance]);
192
+ useEffect(() => {
193
+ mounted.current = true;
194
+ if (!opts.initial)
195
+ void refresh();
196
+ return () => {
197
+ mounted.current = false;
198
+ };
199
+ }, [refresh]);
200
+ return { allowed: check ? check.allowed : null, balance: check?.balance ?? null, loading: check === null, check, refresh };
201
+ }
202
+ /** <Gate feature="export" fallback={<Upgrade />}>…</Gate> — renders children only when the feature is allowed. */
203
+ export function Gate(props) {
204
+ const { feature, fallback, loading, children, ...opts } = props;
205
+ const f = useFeature(feature, opts);
206
+ if (f.check === null)
207
+ return (loading ?? null);
208
+ if (f.check.allowed)
209
+ return h(Fragment, null, children);
210
+ return (typeof fallback === 'function' ? fallback(f.check) : (fallback ?? null));
211
+ }