@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.
@@ -0,0 +1,124 @@
1
+ /**
2
+ * <UsageProgress metric="input_tokens_per_month" customerId customerToken baseUrl />
3
+ *
4
+ * Real-time bar chart of consumption against the customer's current plan
5
+ * limit. Self-fetches from `GET /v1/customer-portal/:id/usage`, or accept
6
+ * `usage` + `limits` props for a presentational use.
7
+ *
8
+ * Props:
9
+ * - metric which limit field to render (e.g. `input_tokens_per_month`)
10
+ * - label override the rendered label (default: humanized metric)
11
+ * - warnAt fraction (0..1) to flip the bar to warning color (default 0.8)
12
+ * - dangerAt fraction at which to flip to danger color (default 1.0)
13
+ *
14
+ * Stale-while-error: on fetch failure we keep the previous data and show a
15
+ * small "stale" badge — same pattern as the entitlement-sidecar.
16
+ */
17
+
18
+ const React = require("react");
19
+
20
+ const styles = {
21
+ wrap: {
22
+ display: "grid",
23
+ gap: 6,
24
+ fontFamily: "system-ui, -apple-system, sans-serif",
25
+ color: "#111",
26
+ },
27
+ header: { display: "flex", justifyContent: "space-between", fontSize: 13 },
28
+ label: { fontWeight: 600 },
29
+ value: { opacity: 0.75, fontFamily: "monospace" },
30
+ track: { background: "#e5e7eb", borderRadius: 6, height: 8, overflow: "hidden" },
31
+ fill: { height: "100%", background: "#5045e8", transition: "width 200ms ease" },
32
+ warn: { background: "#d97706" },
33
+ danger: { background: "#dc2626" },
34
+ stale: { fontSize: 11, opacity: 0.55, alignSelf: "flex-end" },
35
+ };
36
+
37
+ function humanize(key) {
38
+ return key.replace(/_/g, " ");
39
+ }
40
+
41
+ async function fetchUsage({ baseUrl, customerId, customerToken, fetchImpl }) {
42
+ const url = `${baseUrl.replace(/\/+$/, "")}/v1/customer-portal/${encodeURIComponent(
43
+ customerId,
44
+ )}/usage`;
45
+ const res = await fetchImpl(url, {
46
+ method: "GET",
47
+ headers: { Authorization: `Bearer ${customerToken}` },
48
+ });
49
+ if (!res.ok) throw new Error(`usage-progress: ${res.status}`);
50
+ return res.json();
51
+ }
52
+
53
+ function UsageProgress({
54
+ metric,
55
+ label,
56
+ usage,
57
+ limits,
58
+ warnAt = 0.8,
59
+ dangerAt = 1.0,
60
+ baseUrl,
61
+ customerId,
62
+ customerToken,
63
+ fetch: fetchImpl,
64
+ }) {
65
+ const selfFetch = (!usage || !limits) && baseUrl && customerId && customerToken;
66
+ const [fetched, setFetched] = React.useState(null);
67
+ const [stale, setStale] = React.useState(false);
68
+
69
+ React.useEffect(() => {
70
+ if (!selfFetch) return undefined;
71
+ let alive = true;
72
+ fetchUsage({
73
+ baseUrl,
74
+ customerId,
75
+ customerToken,
76
+ fetchImpl: fetchImpl || globalThis.fetch,
77
+ })
78
+ .then((d) => {
79
+ if (alive) {
80
+ setFetched(d);
81
+ setStale(false);
82
+ }
83
+ })
84
+ .catch(() => {
85
+ if (alive) setStale(true);
86
+ });
87
+ return () => {
88
+ alive = false;
89
+ };
90
+ }, [selfFetch, baseUrl, customerId, customerToken, fetchImpl]);
91
+
92
+ const data = fetched || (usage && limits ? { usage, plan: { limits } } : null);
93
+ if (!data) return null;
94
+
95
+ const used = data.usage?.[metric] ?? 0;
96
+ const cap = data.plan?.limits?.[metric] ?? 0;
97
+ const fraction = cap > 0 ? Math.min(1, used / cap) : 0;
98
+ const fillStyle = { ...styles.fill, width: `${fraction * 100}%` };
99
+ if (fraction >= dangerAt) Object.assign(fillStyle, styles.danger);
100
+ else if (fraction >= warnAt) Object.assign(fillStyle, styles.warn);
101
+
102
+ return React.createElement(
103
+ "div",
104
+ { className: "meterbox-usage-progress", style: styles.wrap },
105
+ React.createElement(
106
+ "div",
107
+ { style: styles.header },
108
+ React.createElement("span", { style: styles.label }, label || humanize(metric)),
109
+ React.createElement(
110
+ "span",
111
+ { style: styles.value },
112
+ `${used.toLocaleString()}${cap > 0 ? ` / ${cap.toLocaleString()}` : ""}`,
113
+ ),
114
+ ),
115
+ React.createElement(
116
+ "div",
117
+ { style: styles.track, role: "progressbar", "aria-valuenow": Math.round(fraction * 100) },
118
+ React.createElement("div", { style: fillStyle }),
119
+ ),
120
+ stale && React.createElement("span", { style: styles.stale }, "stale"),
121
+ );
122
+ }
123
+
124
+ module.exports = UsageProgress;
package/src/index.js ADDED
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @meterbox/react — drop-in components for the tenant's product.
3
+ *
4
+ * Each component supports two modes:
5
+ * • **Presentational** — tenant fetches the body on their backend via
6
+ * `@meterbox/node` and passes it as props. No admin key in the
7
+ * browser bundle.
8
+ * • **Self-fetching** — `SubscriptionPreview`, `PlanChangeCard`,
9
+ * `CreditBalance`, `CreditGrantsTable`, `CreditUtilization`, and
10
+ * `OutcomeHistory` can fetch their own data from the
11
+ * `/v1/customer-portal/*` endpoints using a short-lived customer-scoped
12
+ * JWT minted server-side (`POST /v1/tokens/:id`).
13
+ *
14
+ * Re-exports `@meterbox/node` for convenience: `import { plans } from
15
+ * '@meterbox/react'` works the same as importing the SDK directly.
16
+ */
17
+
18
+ // Re-export the Node SDK surface so tenants can grab everything from one
19
+ // package if they want a single dependency.
20
+ const sdk = require("@meterbox/node");
21
+ const PricingTable = require("./PricingTable");
22
+ const PlanComparison = require("./PlanComparison");
23
+ const SubscriptionPreview = require("./SubscriptionPreview");
24
+ const PlanChangeCard = require("./PlanChangeCard");
25
+ const CreditBalance = require("./CreditBalance");
26
+ const CreditGrantsTable = require("./CreditGrantsTable");
27
+ const CreditUtilization = require("./CreditUtilization");
28
+ const OutcomeHistory = require("./OutcomeHistory");
29
+ const UsageChart = require("./UsageChart");
30
+ const Paywall = require("./Paywall");
31
+ const UsageProgress = require("./UsageProgress");
32
+ const TrialBanner = require("./TrialBanner");
33
+ const CheckoutButton = require("./CheckoutButton");
34
+
35
+ module.exports = {
36
+ PricingTable,
37
+ PlanComparison,
38
+ SubscriptionPreview,
39
+ PlanChangeCard,
40
+ CreditBalance,
41
+ CreditGrantsTable,
42
+ CreditUtilization,
43
+ OutcomeHistory,
44
+ UsageChart,
45
+ Paywall,
46
+ UsageProgress,
47
+ TrialBanner,
48
+ CheckoutButton,
49
+ sdk,
50
+ MeterboxClient: sdk.MeterboxClient,
51
+ };