@meterbox/react 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Meterbox Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,187 @@
1
+ # @meterbox/react
2
+
3
+ Drop-in React components for Meterbox: pricing tables, plan comparison,
4
+ subscription preview, credit balance + grants + utilization, and usage
5
+ charts. Depends on [`@meterbox/node`](https://www.npmjs.com/package/@meterbox/node)
6
+ for the typed API client.
7
+
8
+ Each component supports two modes:
9
+
10
+ - **Presentational**: your backend fetches via `@meterbox/node` and
11
+ passes the body in as props. Default behavior. No API key in the
12
+ browser.
13
+ - **Self-fetching**: `<SubscriptionPreview>`, `<PlanChangeCard>`,
14
+ `<CreditBalance>`, `<CreditGrantsTable>`, and `<CreditUtilization>` can
15
+ fetch their own data from the `/v1/customer-portal/*` endpoints using a
16
+ short-lived customer-scoped JWT minted server-side
17
+ (`POST /v1/tokens/:id`). Pass `baseUrl` + `customerId` +
18
+ `customerToken` instead of the data prop.
19
+
20
+ For a complete hosted-feel portal in one component, see
21
+ [`@meterbox/customer-portal`](https://www.npmjs.com/package/@meterbox/customer-portal).
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ npm install @meterbox/react react react-dom
27
+ ```
28
+
29
+ `react` and `react-dom` are peer deps (≥17).
30
+
31
+ ## Components
32
+
33
+ ```jsx
34
+ import {
35
+ PricingTable,
36
+ PlanComparison,
37
+ SubscriptionPreview,
38
+ PlanChangeCard,
39
+ CreditBalance,
40
+ CreditGrantsTable,
41
+ CreditUtilization,
42
+ UsageChart,
43
+ CheckoutButton,
44
+ } from "@meterbox/react";
45
+ ```
46
+
47
+ ### `<PricingTable plans currentPlanId? currency? onSelect? />`
48
+
49
+ Renders the plan catalog as a comparison grid. Highlights `currentPlanId`
50
+ if supplied, picks a localized price when `currency` matches a row in
51
+ `plan.localized_prices`. A monthly/annual toggle renders automatically
52
+ when at least one plan has `annual_free_months` set. Selecting "Annual"
53
+ shows the one-time prepaid total, not that total divided back into a
54
+ misleading "$X/mo" figure. `onSelect(plan, billingInterval)` receives
55
+ whichever interval was selected, ready to hand straight to
56
+ `<CheckoutButton billingInterval>`. `PricingTable.annualPriceUsd(plan)` is
57
+ exposed as a static if you need the same total outside the grid.
58
+
59
+ ### `<PlanComparison from to onSwitch? />`
60
+
61
+ Side-by-side comparison of two plan records with added / removed feature
62
+ deltas. Pair with `<SubscriptionPreview>` for the prorated math.
63
+
64
+ ### `<CheckoutButton planId successUrl cancelUrl baseUrl customerId customerToken billingInterval? label? onSession? onError? />`
65
+
66
+ One-tap Stripe Checkout for a plan change. POSTs to
67
+ `/v1/customer-portal/:id/checkout` (customer JWT, no API key in the
68
+ browser) and redirects to the returned Stripe URL. `billingInterval`
69
+ ("monthly", the default, or "annual") only takes effect for a plan with
70
+ `annual_free_months` configured; requesting "annual" on a plan that
71
+ doesn't offer it surfaces a 400 via `onError` rather than redirecting.
72
+
73
+ ### `<SubscriptionPreview preview? | baseUrl customerId customerToken planId planVersion? />`
74
+
75
+ Renders the response of `POST /v1/customers/:id/subscription/preview` (admin)
76
+ or `POST /v1/customer-portal/:id/subscription/preview` (customer JWT):
77
+ prorated charge, MRR delta, effective date.
78
+
79
+ ### `<PlanChangeCard preview? scheduledChange? allowSchedule? | baseUrl customerId customerToken planId planVersion? fetch? onConfirm? onCancelScheduled? onChanged? />`
80
+
81
+ Composes `<SubscriptionPreview>` with the actions it doesn't have: actually
82
+ applying or scheduling the change, and cancelling a pending scheduled one.
83
+ Two modes:
84
+
85
+ - **Presentational**: pass `preview` (already fetched) plus
86
+ `onConfirm(effective)` / `onCancelScheduled()` callbacks that return
87
+ promises; you own how the request is actually made (e.g. proxied through
88
+ your own backend, session-authenticated, holding no customer JWT).
89
+ - **Self-fetching**: `baseUrl` + `customerId` + `customerToken` + `planId`,
90
+ no `onConfirm`/`onCancelScheduled` supplied: fetches its own preview AND
91
+ posts confirm/cancel directly to `POST /v1/customer-portal/:id/subscription/change`
92
+ and `DELETE /v1/customer-portal/:id/subscription/scheduled`.
93
+
94
+ `scheduledChange` (e.g. from `GET /v1/customer-portal/:id/me`'s
95
+ `scheduled_change` field) renders a banner with its own Cancel action ahead
96
+ of the preview. `allowSchedule` (default `true`) hides "Schedule for end of
97
+ period". Set `false` if nothing on your side reconciles a change applied
98
+ later, on its own schedule, back into wherever you cache plan state.
99
+ `onChanged(result)` fires after either action succeeds, for refreshing your
100
+ own cached plan/schedule state. It does not control whether the card stays
101
+ mounted; keep whatever render condition shows the card independent of the
102
+ plan id it just changed to, or the card (and the confirmation message it's
103
+ showing) unmounts the instant your own state catches up.
104
+
105
+ ### `<CreditBalance balance? | baseUrl customerId customerToken; threshold? onTopUp? />`
106
+
107
+ Compact balance widget. If `balance_usd < threshold`, shows a top-up CTA
108
+ wired to `onTopUp`. Self-fetches `GET /v1/customer-portal/:id/credits` in
109
+ self-fetch mode.
110
+
111
+ ### `<CreditGrantsTable grants? balance_usd? | baseUrl customerId customerToken; filter? />`
112
+
113
+ Table of active grants: source, amount, remaining, expiry, status. Pass
114
+ `filter={(g) => ...}` to slice the rows.
115
+
116
+ ### `<CreditUtilization series? | baseUrl customerId customerToken from? to? granularity?; height? />`
117
+
118
+ Inline SVG line + area chart of credit balance over time, fed by
119
+ `GET /v1/customer-portal/:id/credits/timeseries`.
120
+
121
+ ### `<UsageChart series valueKey? height? label? />`
122
+
123
+ Tiny inline SVG bar chart of a time series, typically the day-grain rollup
124
+ from `GET /v1/ledger/:id?grain=day`. `valueKey` picks the dimension
125
+ (`amount_usd` default, `api_calls`, `input_tokens`, `output_tokens`).
126
+
127
+ ## End-to-end shapes
128
+
129
+ **Presentational** (server fetches, client renders):
130
+
131
+ ```jsx
132
+ // app/server.tsx (Next.js Server Component, or any backend handler)
133
+ import { getV1Plans, MeterboxClient } from "@meterbox/node";
134
+
135
+ new MeterboxClient({
136
+ baseUrl: process.env.METERBOX_BASE_URL, // e.g. https://meterbox.ai
137
+ apiKey: process.env.METERBOX_API_KEY,
138
+ });
139
+
140
+ export default async function PricingPage() {
141
+ const { data } = await getV1Plans();
142
+ return <PricingTableClient plans={data.plans} />;
143
+ }
144
+ ```
145
+
146
+ ```jsx
147
+ // app/PricingTableClient.tsx
148
+ "use client";
149
+ import { PricingTable } from "@meterbox/react";
150
+
151
+ export function PricingTableClient({ plans }) {
152
+ function handleSelect(plan, billingInterval) {
153
+ // route to checkout, e.g. via <CheckoutButton planId={plan.id} billingInterval={billingInterval} ...>
154
+ }
155
+ return <PricingTable plans={plans} currency="USD" onSelect={handleSelect} />;
156
+ }
157
+ ```
158
+
159
+ **Self-fetching** (browser-safe, customer JWT):
160
+
161
+ ```jsx
162
+ 'use client';
163
+ import { SubscriptionPreview, CreditBalance } from '@meterbox/react';
164
+
165
+ // The customer JWT is minted server-side via POST /v1/tokens/:id
166
+ // and handed to the client (e.g. as a cookie / SSR prop). It is scoped to
167
+ // one customer (claim `sub === customerId`) and short-lived.
168
+ export function PortalBits({ customerJwt }) {
169
+ return (
170
+ <>
171
+ <SubscriptionPreview
172
+ baseUrl="https://meterbox.ai"
173
+ customerId="cus_42"
174
+ customerToken={customerJwt}
175
+ planId="pro"
176
+ />
177
+ <CreditBalance
178
+ baseUrl="https://meterbox.ai"
179
+ customerId="cus_42"
180
+ customerToken={customerJwt}
181
+ threshold={10}
182
+ onTopUp={(b) => /* mint a top-up session */}
183
+ />
184
+ </>
185
+ );
186
+ }
187
+ ```
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@meterbox/react",
3
+ "version": "0.1.0",
4
+ "description": "Embeddable React components for Meterbox: pricing tables, subscription preview, credit balance and usage charts. Presentational by default, with data fetched by your backend via @meterbox/node.",
5
+ "license": "MIT",
6
+ "homepage": "https://meterbox.ai",
7
+ "main": "src/index.js",
8
+ "files": [
9
+ "src/",
10
+ "README.md",
11
+ "LICENSE"
12
+ ],
13
+ "engines": {
14
+ "node": ">=18"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "dependencies": {
20
+ "@meterbox/node": "0.1.0"
21
+ },
22
+ "peerDependencies": {
23
+ "react": ">=17",
24
+ "react-dom": ">=17"
25
+ },
26
+ "keywords": [
27
+ "meterbox",
28
+ "react",
29
+ "components",
30
+ "pricing-table",
31
+ "subscription-preview"
32
+ ]
33
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * <CheckoutButton planId="pro" successUrl="..." cancelUrl="..."
3
+ * customerId customerToken baseUrl billingInterval? />
4
+ *
5
+ * One-tap Stripe Checkout for a plan change. POSTs to
6
+ * `/v1/customer-portal/:id/checkout` and redirects the browser to the
7
+ * returned Stripe URL. Pass `onSession({ id, url })` to intercept the
8
+ * redirect (e.g. to track an analytics event first).
9
+ *
10
+ * `billingInterval` ("monthly", the default, or "annual") only works for a
11
+ * plan with `annual_free_months` configured — the tenant sets that up the
12
+ * same way as any other plan field (Settings -> Plans, or the catalog API),
13
+ * not something specific to this component. Requesting "annual" for a plan
14
+ * that doesn't offer it fails with a 400 (`onError` receives it).
15
+ *
16
+ * Requires the tenant to have enabled `checkout_via_meterbox` in billing
17
+ * settings — otherwise the endpoint returns 409 and the button surfaces the
18
+ * error via `onError`.
19
+ */
20
+
21
+ const React = require("react");
22
+
23
+ const styles = {
24
+ btn: {
25
+ padding: "10px 18px",
26
+ border: "none",
27
+ borderRadius: 8,
28
+ background: "#5045e8",
29
+ color: "#fff",
30
+ fontWeight: 600,
31
+ cursor: "pointer",
32
+ fontFamily: "system-ui, -apple-system, sans-serif",
33
+ },
34
+ disabled: { opacity: 0.6, cursor: "default" },
35
+ };
36
+
37
+ async function startCheckout({
38
+ baseUrl,
39
+ customerId,
40
+ customerToken,
41
+ planId,
42
+ successUrl,
43
+ cancelUrl,
44
+ billingInterval,
45
+ fetchImpl,
46
+ }) {
47
+ const url = `${baseUrl.replace(/\/+$/, "")}/v1/customer-portal/${encodeURIComponent(
48
+ customerId,
49
+ )}/checkout`;
50
+ const res = await fetchImpl(url, {
51
+ method: "POST",
52
+ headers: {
53
+ Authorization: `Bearer ${customerToken}`,
54
+ "Content-Type": "application/json",
55
+ },
56
+ body: JSON.stringify({
57
+ plan_id: planId,
58
+ success_url: successUrl,
59
+ cancel_url: cancelUrl,
60
+ billing_interval: billingInterval,
61
+ }),
62
+ });
63
+ const body = await res.json().catch(() => ({}));
64
+ if (!res.ok) {
65
+ const err = new Error(body.error || `checkout: ${res.status}`);
66
+ err.status = res.status;
67
+ throw err;
68
+ }
69
+ return body;
70
+ }
71
+
72
+ function CheckoutButton({
73
+ planId,
74
+ successUrl,
75
+ cancelUrl,
76
+ billingInterval,
77
+ label,
78
+ baseUrl,
79
+ customerId,
80
+ customerToken,
81
+ fetch: fetchImpl,
82
+ onSession,
83
+ onError,
84
+ }) {
85
+ const [busy, setBusy] = React.useState(false);
86
+
87
+ const onClick = React.useCallback(async () => {
88
+ setBusy(true);
89
+ try {
90
+ const session = await startCheckout({
91
+ baseUrl,
92
+ customerId,
93
+ customerToken,
94
+ planId,
95
+ successUrl,
96
+ cancelUrl,
97
+ billingInterval,
98
+ fetchImpl: fetchImpl || globalThis.fetch,
99
+ });
100
+ if (onSession) onSession(session);
101
+ if (session.url && typeof globalThis !== "undefined" && globalThis.window) {
102
+ globalThis.window.location.href = session.url;
103
+ }
104
+ } catch (err) {
105
+ if (onError) onError(err);
106
+ } finally {
107
+ setBusy(false);
108
+ }
109
+ }, [
110
+ baseUrl,
111
+ customerId,
112
+ customerToken,
113
+ planId,
114
+ successUrl,
115
+ cancelUrl,
116
+ billingInterval,
117
+ fetchImpl,
118
+ onSession,
119
+ onError,
120
+ ]);
121
+
122
+ const ready = baseUrl && customerId && customerToken && planId && successUrl && cancelUrl;
123
+ return React.createElement(
124
+ "button",
125
+ {
126
+ type: "button",
127
+ className: "meterbox-checkout-button",
128
+ style: !ready || busy ? { ...styles.btn, ...styles.disabled } : styles.btn,
129
+ disabled: !ready || busy,
130
+ onClick,
131
+ "aria-label": label || `Subscribe to ${planId}`,
132
+ },
133
+ busy ? "Redirecting…" : label || "Subscribe",
134
+ );
135
+ }
136
+
137
+ module.exports = CheckoutButton;
@@ -0,0 +1,165 @@
1
+ /**
2
+ * <CreditBalance ... />
3
+ *
4
+ * Two modes:
5
+ *
6
+ * 1. **Presentational**:
7
+ * <CreditBalance balance={...} threshold? onTopUp? />
8
+ * `balance` is the shape returned by `GET /v1/customers/:id/credits`
9
+ * — `{balance_usd, grants}`.
10
+ *
11
+ * 2. **Self-fetching** (browser-safe):
12
+ * <CreditBalance baseUrl="https://meterbox.ai"
13
+ * customerId="cus_42"
14
+ * customerToken={jwt}
15
+ * threshold={10} onTopUp={...} />
16
+ * Fetches `GET /v1/customer-portal/:id/credits` with the customer JWT.
17
+ *
18
+ * If `threshold` is provided and `balance_usd` falls below it, the widget
19
+ * surfaces an inline "Top up" CTA wired to `onTopUp`.
20
+ */
21
+
22
+ const React = require("react");
23
+
24
+ async function fetchBalance({ baseUrl, customerId, customerToken, fetchImpl }) {
25
+ const url = `${String(baseUrl).replace(/\/+$/, "")}/v1/customer-portal/${encodeURIComponent(
26
+ customerId,
27
+ )}/credits`;
28
+ const res = await fetchImpl(url, {
29
+ method: "GET",
30
+ headers: { Authorization: `Bearer ${customerToken}` },
31
+ });
32
+ const json = await res.json();
33
+ if (!res.ok) {
34
+ const err = new Error(json?.error || `HTTP ${res.status}`);
35
+ err.status = res.status;
36
+ throw err;
37
+ }
38
+ return json;
39
+ }
40
+
41
+ const styles = {
42
+ card: {
43
+ fontFamily: "system-ui, -apple-system, sans-serif",
44
+ color: "#111",
45
+ border: "1px solid #e5e7eb",
46
+ borderRadius: 12,
47
+ padding: 16,
48
+ background: "#fff",
49
+ display: "grid",
50
+ gap: 8,
51
+ maxWidth: 320,
52
+ },
53
+ label: { fontSize: 12, opacity: 0.6, textTransform: "uppercase", letterSpacing: 0.4 },
54
+ amount: { fontSize: 32, fontWeight: 700 },
55
+ low: { color: "#dc2626" },
56
+ hint: { fontSize: 12, opacity: 0.65 },
57
+ topUp: {
58
+ padding: "8px 12px",
59
+ border: "1px solid #5045e8",
60
+ borderRadius: 8,
61
+ background: "#fff",
62
+ color: "#5045e8",
63
+ fontWeight: 600,
64
+ cursor: "pointer",
65
+ width: "fit-content",
66
+ },
67
+ };
68
+
69
+ function dollars(n) {
70
+ if (n == null) return "—";
71
+ return `$${Number(n).toLocaleString(undefined, { maximumFractionDigits: 2 })}`;
72
+ }
73
+
74
+ function CreditBalance({
75
+ balance,
76
+ threshold,
77
+ onTopUp,
78
+ baseUrl,
79
+ customerId,
80
+ customerToken,
81
+ fetch: fetchImpl,
82
+ }) {
83
+ const selfFetch = !balance && baseUrl && customerId && customerToken;
84
+ const [fetched, setFetched] = React.useState(null);
85
+ const [error, setError] = React.useState(null);
86
+ const [loading, setLoading] = React.useState(false);
87
+
88
+ React.useEffect(() => {
89
+ if (!selfFetch) return undefined;
90
+ let cancelled = false;
91
+ setLoading(true);
92
+ setError(null);
93
+ fetchBalance({
94
+ baseUrl,
95
+ customerId,
96
+ customerToken,
97
+ fetchImpl: fetchImpl || globalThis.fetch,
98
+ })
99
+ .then((body) => {
100
+ if (!cancelled) {
101
+ setFetched(body);
102
+ setLoading(false);
103
+ }
104
+ })
105
+ .catch((err) => {
106
+ if (!cancelled) {
107
+ setError(err.message || "Could not load credit balance.");
108
+ setLoading(false);
109
+ }
110
+ });
111
+ return () => {
112
+ cancelled = true;
113
+ };
114
+ }, [selfFetch, baseUrl, customerId, customerToken, fetchImpl]);
115
+
116
+ if (loading) {
117
+ return React.createElement(
118
+ "div",
119
+ { style: { opacity: 0.6, fontFamily: styles.card.fontFamily } },
120
+ "Loading credit balance…",
121
+ );
122
+ }
123
+ if (error) {
124
+ return React.createElement(
125
+ "div",
126
+ { style: { color: "#dc2626", fontFamily: styles.card.fontFamily } },
127
+ error,
128
+ );
129
+ }
130
+ const data = balance || fetched;
131
+ if (!data) {
132
+ return React.createElement(
133
+ "div",
134
+ { style: { opacity: 0.6, fontFamily: styles.card.fontFamily } },
135
+ "Loading credit balance…",
136
+ );
137
+ }
138
+ const value = data.balance_usd ?? data.balance ?? null;
139
+ const grants = Array.isArray(data.grants) ? data.grants : [];
140
+ const low = threshold != null && value != null && value < threshold;
141
+ return React.createElement(
142
+ "div",
143
+ { className: "meterbox-credit-balance", style: styles.card },
144
+ React.createElement("div", { style: styles.label }, "Credit balance"),
145
+ React.createElement(
146
+ "div",
147
+ { style: low ? { ...styles.amount, ...styles.low } : styles.amount },
148
+ dollars(value),
149
+ ),
150
+ React.createElement(
151
+ "div",
152
+ { style: styles.hint },
153
+ `${grants.length} active grant${grants.length === 1 ? "" : "s"}`,
154
+ ),
155
+ onTopUp &&
156
+ low &&
157
+ React.createElement(
158
+ "button",
159
+ { type: "button", style: styles.topUp, onClick: () => onTopUp(data) },
160
+ "Top up credits",
161
+ ),
162
+ );
163
+ }
164
+
165
+ module.exports = CreditBalance;