diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9941feb..061847e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,23 @@
# Changelog
+## [Unreleased]
+
+Needs `@nebulr-group/bridge-auth-core` 1.0.0-alpha.11, which has plan limits, entitlements and the billing lock.
+
+### Added
+
+- **`QuotaGate`, `Entitled` and `useEntitlements`.** `` disables the actions inside once a metric is at its hard limit and shows an upgrade line; `` shows its content when the plan has a feature; `useEntitlements().can(key)` reads the same, from the flag `bridge:billing.entitlement.`, fail-closed until Bridge has answered (`ready`).
+- **`useQuota(metric)` gives `loading`, `unlimited`, `used`, `limit`, `remaining`, `warningLevel`, `kind` and `snapshot`** (with `policy`), and still `ratio` and `state`.
+- **The billing lock.** ` ` blocks the page while the workspace is locked for payment; the lock shows to every person and at once when your API answers a change with its 402 through `bridgeFetch`. `useBillingGate()` and `useBillingLocked()` give it as hooks.
+- **`onBridgeQuotaExceeded(handler)`** runs for each limit your API refuses through `bridgeFetch`, for an app with its own dialog.
+- `BridgeBillingNotice`, `BridgeQuotaBanner` and `BridgeUpgradeDialog` are other names for `BillingNotice`, `QuotaBanner` and `UpgradeDialog`. `dismissQuotaRefusal()` is another name for `closeUpgrade()`. `useBridgeBilling()` gives `quota(metric)`, `quotas`, `entitlements`, `handle`, `isLocked()`, `gateState()` and `assertNotLocked()` without a hook, as in 0.9; it has no `subscription` (use `useBilling()`).
+
+### Changed
+
+- **`QuotaBanner` and `useQuota` read Bridge's quota numbers** and follow quota and plan changes live, instead of the period's usage read once. The banner shows from 80%, says "limit reached" at the limit, and shows a metered limit's overage. `onActionClick` receives the quota snapshot.
+- **`useQuota` always returns an object** (`loading` is true until Bridge has answered) instead of `null` while loading and for a metric without a limit.
+- The type `QuotaState` is now what `useQuota` returns; the former `'ok' | 'near' | 'over'` is `QuotaLevel`, and `Quota` is gone.
+
## [1.0.0-alpha.1] - unreleased
Needs `@nebulr-group/bridge-auth-core` 1.0.0-alpha.8. A new major line, for the new Bridge: the React counterpart of `@nebulr-group/bridge-svelte` 1.0.0-alpha.8, with the same pages, settings and wording, so the guides of either package map to the other. `latest` stays on 0.x.
diff --git a/README.md b/README.md
index 6c3f0c7..5a0cb80 100644
--- a/README.md
+++ b/README.md
@@ -67,7 +67,7 @@ In your app's settings in Bridge, add your app's address as a browser address an
|---|---|
| Sign-in | `BridgeAuthRoutes` (sign-in, sign-up, verify-email, forgot-password, set-password, invite, workspaces, magic-link, passkey-setup, handoff, callback), `SignInForm`, `SignUpForm`, `VerifyEmail`, `ForgotPassword`, `SetPassword`, `InviteLanding`, `MagicLinkLanding`, `PasskeySetupLanding`, `PasskeyManager`, `WorkspaceChooser`, `SignOutButton`, `ProfileName` |
| Gates | route `rules`, `FeatureFlag`, `useFlag`, `requireFlag`, the paywall: all on flag results, never a role or the plan |
-| Billing | `BridgeBillingRoutes`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `QuotaBanner`, `CheckoutNotice`, `UpgradeDialog`, `useQuota`, `bridgeFetch` |
+| Billing | `BridgeBillingRoutes`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `QuotaBanner`, `QuotaGate`, `Entitled`, `CheckoutNotice`, `UpgradeDialog`, `useQuota`, `useEntitlements`, `bridgeFetch` |
| Team | `TeamPanel`, `MemberList`, `InviteDialog`, `InviteList`, `EditMemberDialog`, `ConfirmDialog`, `WorkspaceForm`, `ProfileForm` |
| State | `useSession`, `useUser`, `useWorkspace`, `useWorkspaces`, `useMe`, `useFlags`, `useBilling`, `usePlans`, `useUsage`, `useLiveStatus`, `getBridge()` |
| Hand-off | `HandoffSignIn`, `readHandoff`, `handoffSignIn`: a sign-in page for a command-line tool |
diff --git a/bridge-react/README.md b/bridge-react/README.md
index f0b581d..5aec420 100644
--- a/bridge-react/README.md
+++ b/bridge-react/README.md
@@ -67,7 +67,7 @@ In your app's settings in Bridge, add your app's address as a browser address an
|---|---|
| Sign-in | `BridgeAuthRoutes` (sign-in, sign-up, verify-email, forgot-password, set-password, invite, workspaces, magic-link, passkey-setup, handoff, callback), `SignInForm`, `SignUpForm`, `VerifyEmail`, `ForgotPassword`, `SetPassword`, `InviteLanding`, `MagicLinkLanding`, `PasskeySetupLanding`, `PasskeyManager`, `WorkspaceChooser`, `SignOutButton`, `ProfileName` |
| Gates | route `rules`, `FeatureFlag`, `useFlag`, `requireFlag`, the paywall: all on flag results, never a role or the plan |
-| Billing | `BridgeBillingRoutes`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `QuotaBanner`, `CheckoutNotice`, `UpgradeDialog`, `useQuota`, `bridgeFetch` |
+| Billing | `BridgeBillingRoutes`, `PlanPicker`, `BillingPortalButton`, `SubscriptionStatus`, `BillingNotice`, `QuotaBanner`, `QuotaGate`, `Entitled`, `CheckoutNotice`, `UpgradeDialog`, `useQuota`, `useEntitlements`, `bridgeFetch` |
| Team | `TeamPanel`, `MemberList`, `InviteDialog`, `InviteList`, `EditMemberDialog`, `ConfirmDialog`, `WorkspaceForm`, `ProfileForm` |
| State | `useSession`, `useUser`, `useWorkspace`, `useWorkspaces`, `useMe`, `useFlags`, `useBilling`, `usePlans`, `useUsage`, `useLiveStatus`, `getBridge()` |
| Hand-off | `HandoffSignIn`, `readHandoff`, `handoffSignIn`: a sign-in page for a command-line tool |
diff --git a/bridge-react/package.json b/bridge-react/package.json
index 0015c32..6754cf8 100644
--- a/bridge-react/package.json
+++ b/bridge-react/package.json
@@ -50,7 +50,7 @@
"react-dom": "^18.0.0 || ^19.0.0"
},
"dependencies": {
- "@nebulr-group/bridge-auth-core": "1.0.0-alpha.8"
+ "@nebulr-group/bridge-auth-core": "1.0.0-alpha.11"
},
"devDependencies": {
"@testing-library/react": "^16.3.0",
diff --git a/bridge-react/src/components/billing/BillingNotice.tsx b/bridge-react/src/components/billing/BillingNotice.tsx
index d7c7c69..95a7742 100644
--- a/bridge-react/src/components/billing/BillingNotice.tsx
+++ b/bridge-react/src/components/billing/BillingNotice.tsx
@@ -4,9 +4,15 @@
* change waiting. Renders nothing when all is well. A person with the
* `billingManage` flag gets a link to the billing pages; anyone else is told
* to ask the workspace owner. Not dismissible: it goes when the facts change.
+ *
+ * A workspace locked for payment shows to every person, from the lock Bridge
+ * keeps (`useBillingGate`), and at once when your API refuses a write with the
+ * lock's 402 through `bridgeFetch`. With `mode="hard"` the lock covers the page
+ * as a blocking screen; every other notice stays a banner.
*/
import { billingNotice, type BillingFacts, type BillingNotice as Notice, type Plan } from '@nebulr-group/bridge-auth-core';
import type { HTMLAttributes, MouseEvent } from 'react';
+import { useBillingGate } from '../../react/billing-gate.js';
import { useBilling, useBridgeConfig, useCanManageBilling, usePlans } from '../../react/hooks.js';
import { Link } from '../shared/Link.js';
import { formatDate } from './plan-format.js';
@@ -17,6 +23,8 @@ type Severity = 'info' | 'warn' | 'critical' | 'locked';
export interface BillingNoticeProps extends HTMLAttributes {
/** The notice's shape: a full-width bar, a rail with a left edge, or a card. @default 'rail' */
readonly chassis?: Chassis;
+ /** `hard` covers the page with a blocking screen while the workspace is locked for payment; other notices stay banners. @default 'soft' */
+ readonly mode?: 'soft' | 'hard';
/** Where the action link goes. @default the plan page for no plan, else the subscription page */
readonly actionHref?: string;
/** Replaces the action link's navigation. */
@@ -33,6 +41,7 @@ const SEVERITY: Record = {
};
const OWNER = 'Please contact your workspace owner.';
+const BLOCKED: Notice = { kind: 'blocked' };
function daysLeft(days: number): string {
if (days <= 0) return 'The trial ends today.';
@@ -72,14 +81,16 @@ function copyFor(n: Notice, admin: boolean, facts: BillingFacts | null, plans: r
}
}
-export function BillingNotice({ chassis = 'rail', actionHref, onActionClick, className, ...rest }: BillingNoticeProps) {
+export function BillingNotice({ chassis = 'rail', mode = 'soft', actionHref, onActionClick, className, ...rest }: BillingNoticeProps) {
const config = useBridgeConfig();
const base = config?.billingBase ?? '/subscription';
const canManage = useCanManageBilling();
const billing = useBilling();
const plans = usePlans();
+ const gate = useBillingGate();
- const notice = billing.value ? billingNotice(billing.value) : null;
+ // The lock is shown from the gate as well as the billing facts: the gate is read by every person, and a refusal shows it at once.
+ const notice: Notice | null = gate.locked ? BLOCKED : billing.value ? billingNotice(billing.value) : null;
if (!notice) return null;
const severity = SEVERITY[notice.kind];
const urgent = severity === 'critical' || severity === 'locked';
@@ -92,6 +103,32 @@ export function BillingNotice({ chassis = 'rail', actionHref, onActionClick, cla
onActionClick(notice);
}
+ if (mode === 'hard' && notice.kind === 'blocked') {
+ return (
+
+
+
+ {copy.title}
+
+ {copy.body}
+ {copy.cta && canManage && (
+
+ {copy.cta}
+
+ )}
+
+
+ );
+ }
+
return (
`: the children render when the plan has the feature,
+ * `fallback` when it does not.
+ *
+ * ```tsx
+ *
Upgrade for analytics}>
+ *
+ *
+ * ```
+ *
+ * Until Bridge has answered (`useEntitlements().ready`) it renders neither, only
+ * the optional `loading` node, so a cold start never flashes the upgrade prompt
+ * at a paying workspace, nor the paid feature at a free one.
+ *
+ * It reads the flag `bridge:billing.entitlement.
`, as
+ * `useEntitlements().can('analytics')` does. To show something for a flag in
+ * general, with its reason, use ``.
+ */
+import type { ReactNode } from 'react';
+import { useEntitlements } from '../../react/entitlements.js';
+
+export interface EntitledProps {
+ /** The plan feature's key, such as `analytics`. */
+ readonly to: string;
+ /** Rendered when the plan has `to`. */
+ readonly children?: ReactNode;
+ /** Rendered when Bridge has answered and the plan does not have `to`. */
+ readonly fallback?: ReactNode;
+ /** Rendered until Bridge has answered. Nothing by default. */
+ readonly loading?: ReactNode;
+}
+
+export function Entitled({ to, children, fallback = null, loading = null }: EntitledProps) {
+ const entitlements = useEntitlements();
+ if (!entitlements.ready) return <>{loading}>;
+ return <>{entitlements.can(to) ? children : fallback}>;
+}
+
+export default Entitled;
diff --git a/bridge-react/src/components/billing/QuotaBanner.tsx b/bridge-react/src/components/billing/QuotaBanner.tsx
index 45b2a49..c75f428 100644
--- a/bridge-react/src/components/billing/QuotaBanner.tsx
+++ b/bridge-react/src/components/billing/QuotaBanner.tsx
@@ -5,64 +5,47 @@
*
* ```
*
- * Renders nothing below 80% of the limit, or for a metric with no limit. It
- * shows numbers only and blocks nothing: whether something is allowed is a
- * flag. A person with the `billingManage` flag gets an Upgrade link; anyone
- * else is told to contact the workspace owner.
+ * Renders nothing while the metric has no limit or is below 80% of it. It moves
+ * by itself: Bridge's quota notices read the numbers again. It shows numbers
+ * only and blocks nothing: whether something is allowed is a flag. A person with
+ * the `billingManage` flag gets an Upgrade link; anyone else is told to contact
+ * the workspace owner. A metered limit shows the overage instead of a warning.
*/
+import type { QuotaSnapshot } from '@nebulr-group/bridge-auth-core';
import type { HTMLAttributes, MouseEvent } from 'react';
-import { useBridgeConfig, useCanManageBilling, useUsage } from '../../react/hooks.js';
+import { useBridgeConfig, useCanManageBilling } from '../../react/hooks.js';
+import { useQuota } from '../../react/quota.js';
import { Link } from '../shared/Link.js';
-import { quotaFor, type Quota } from './quota.js';
+import { quotaBannerCopy, quotaBannerState } from './quota-copy.js';
export interface QuotaBannerProps extends HTMLAttributes {
/** The metric to watch, such as `projects`. */
readonly metric: string;
- /** The metric's name in the copy. @default the metric key */
+ /** The metric's name in the copy. @default the metric's label from Bridge, else its key */
readonly label?: string;
/** Where Upgrade goes. @default the subscription page */
readonly actionHref?: string;
/** Replaces Upgrade's navigation. */
- readonly onActionClick?: (quota: Quota) => void;
-}
-
-const OWNER = 'Contact your workspace owner.';
-
-function copyFor(q: Quota, admin: boolean, what: string): { title: string; body: string } {
- const used = q.used.toLocaleString();
- const limit = q.limit.toLocaleString();
- if (q.used > q.limit) {
- return admin
- ? { title: `${what} over cap`, body: `You've used ${used} of ${limit}. Upgrade your plan to add headroom.` }
- : { title: `${what} over cap`, body: `Your workspace is over its ${what} cap. ${OWNER}` };
- }
- if (q.state === 'over') {
- return admin
- ? { title: `${what} limit reached`, body: `You've used all ${limit} on your plan. Upgrade your plan to add more.` }
- : { title: `${what} limit reached`, body: `Your workspace has reached its ${what} limit. ${OWNER}` };
- }
- const left = Math.max(0, q.limit - q.used).toLocaleString();
- return admin
- ? { title: `${what} approaching cap`, body: `You've used ${used} of ${limit} (${left} left).` }
- : { title: `${what} approaching cap`, body: `Your workspace is approaching its ${what} cap.` };
+ readonly onActionClick?: (snapshot: QuotaSnapshot) => void;
}
export function QuotaBanner({ metric, label, actionHref, onActionClick, className, ...rest }: QuotaBannerProps) {
const base = useBridgeConfig()?.billingBase ?? '/subscription';
const canManage = useCanManageBilling();
- const usage = useUsage();
+ const { snapshot } = useQuota(metric);
- const quota = quotaFor(usage.value, metric);
- if (quota === null || quota.state === 'ok') return null;
- const name = label ?? metric;
- const percent = Math.min(100, Math.round(quota.ratio * 100));
+ const state = quotaBannerState(snapshot);
+ if (state === 'hidden' || snapshot === null) return null;
+ const critical = state === 'critical' || state === 'reached' || state === 'over';
+ const name = label ?? snapshot.label ?? metric;
+ const percent = snapshot.limit > 0 ? Math.min(100, Math.round((snapshot.used / snapshot.limit) * 100)) : 0;
const href = actionHref ?? (base || '/');
- const copy = copyFor(quota, canManage, name);
+ const copy = quotaBannerCopy(snapshot, canManage, name);
function handleAction(event: MouseEvent) {
- if (!onActionClick || !quota) return;
+ if (!onActionClick || snapshot === null) return;
event.preventDefault();
- onActionClick(quota);
+ onActionClick(snapshot);
}
return (
@@ -70,24 +53,25 @@ export function QuotaBanner({ metric, label, actionHref, onActionClick, classNam
className={['bridge-quota-banner', className].filter(Boolean).join(' ')}
data-bridge-quota-banner=""
data-metric={metric}
- data-state={quota.state}
- role={quota.state === 'over' ? 'alert' : 'status'}
- aria-live={quota.state === 'over' ? 'assertive' : 'polite'}
+ data-state={state}
+ data-severity={critical ? 'critical' : 'warn'}
+ role={critical ? 'alert' : 'status'}
+ aria-live={critical ? 'assertive' : 'polite'}
aria-label={`${name} quota ${percent}% used`}
{...rest}
>
{copy.title}
{copy.body}
- {quota.limit > 0 && (
+ {snapshot.limit > 0 && (
)}
- {canManage && (
+ {copy.cta && canManage && (
- Upgrade
+ {copy.cta}
)}
diff --git a/bridge-react/src/components/billing/QuotaGate.tsx b/bridge-react/src/components/billing/QuotaGate.tsx
new file mode 100644
index 0000000..8e4bff2
--- /dev/null
+++ b/bridge-react/src/components/billing/QuotaGate.tsx
@@ -0,0 +1,82 @@
+/**
+ * ``: the action inside is disabled once the workspace
+ * is at its plan's hard limit, and an upgrade prompt shows beside it.
+ *
+ * ```tsx
+ *
+ * New ticket
+ *
+ *
+ * <>{q.used} of {q.limit} used. Upgrade >}>
+ * …
+ *
+ * ```
+ *
+ * Disabling is a `` around the children, so every button,
+ * input, select and textarea inside is disabled natively and announced as such,
+ * with no props to thread through your markup. Links are not form controls: put
+ * a link's action behind a button.
+ *
+ * Never disables on "don't know yet": while the quota is loading, the plan sets
+ * no limit on the metric, or the limit is metered (it bills the overage instead
+ * of blocking), the children are enabled. Only a known hard limit with nothing
+ * left disables them.
+ *
+ * Decoration only. Your server refuses the write; this saves the person a click
+ * that would be refused.
+ */
+import type { ReactNode } from 'react';
+import type { QuotaState } from '../../core/quota.js';
+import { useBridgeConfig } from '../../react/hooks.js';
+import { useQuota } from '../../react/quota.js';
+
+export interface QuotaGateProps {
+ /** The metric's key, such as `tickets`. */
+ readonly metric: string;
+ /** The action or actions to disable at the limit. */
+ readonly children: ReactNode;
+ /** What to show at the limit instead of the default line. Receives the live quota. */
+ readonly atLimit?: (quota: QuotaState) => ReactNode;
+ /** Class on the wrapper. */
+ readonly className?: string;
+}
+
+/** Where the gate stands for a metric. */
+export type QuotaGateState = 'loading' | 'unlimited' | 'metered' | 'available' | 'at-limit';
+
+/** The gate's decision for a quota. Exported for tests and custom gates. */
+export function quotaGateState(quota: QuotaState): QuotaGateState {
+ if (quota.loading) return 'loading';
+ if (quota.unlimited) return 'unlimited';
+ if (quota.snapshot?.policy === 'metered') return 'metered';
+ const atCap = (quota.remaining !== null && quota.remaining <= 0) || (quota.used !== null && quota.limit !== null && quota.used >= quota.limit);
+ return atCap ? 'at-limit' : 'available';
+}
+
+export function QuotaGate({ metric, children, atLimit, className }: QuotaGateProps) {
+ const quota = useQuota(metric);
+ const base = useBridgeConfig()?.billingBase ?? '/subscription';
+ const state = quotaGateState(quota);
+ const blocked = state === 'at-limit';
+
+ return (
+
+
+ {children}
+
+ {blocked && (
+
+ {atLimit ? (
+ atLimit(quota)
+ ) : (
+ <>
+ You've used all {quota.limit?.toLocaleString()} {metric} on your plan.
Upgrade
+ >
+ )}
+
+ )}
+
+ );
+}
+
+export default QuotaGate;
diff --git a/bridge-react/src/components/billing/billing-ui.test.tsx b/bridge-react/src/components/billing/billing-ui.test.tsx
new file mode 100644
index 0000000..b898162
--- /dev/null
+++ b/bridge-react/src/components/billing/billing-ui.test.tsx
@@ -0,0 +1,395 @@
+// @vitest-environment jsdom
+/**
+ * Plan limits and plan features, end to end against auth-core's fake issuer: `useQuota`, `useEntitlements`,
+ * `QuotaGate`, `Entitled`, `QuotaBanner`, the lock and the 402s.
+ */
+import { memoryStorage } from '@nebulr-group/bridge-auth-core';
+import { createFakeIssuer } from '@nebulr-group/bridge-auth-core/testing';
+import { act, cleanup, render, renderHook, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it } from 'vitest';
+import { resetClient, startClient } from '../../core/client.js';
+import { resolveConfig } from '../../core/config.js';
+import { bridgeFetch } from '../../core/fetch.js';
+import { warningOf } from '../../core/quota.js';
+import { closeUpgrade, onBridgeQuotaExceeded, parseQuotaRefusal, upgradeRequest, type BridgeQuotaRefusal } from '../../core/upgrade.js';
+import { useBillingGate } from '../../react/billing-gate.js';
+import { useEntitlements } from '../../react/entitlements.js';
+import { useQuota } from '../../react/quota.js';
+import { BillingNotice } from './BillingNotice.js';
+import { Entitled } from './Entitled.js';
+import { QuotaBanner } from './QuotaBanner.js';
+import { QuotaGate, quotaGateState } from './QuotaGate.js';
+import { quotaBannerCopy, quotaBannerState } from './quota-copy.js';
+
+const PASSWORD = 'correct horse battery';
+const API = 'https://api.example.test';
+const read = (used: number, limit: number, extra: object = {}) => ({ used, limit, remaining: Math.max(0, limit - used), policy: 'hard', ...extra });
+
+async function signedIn(options: { flags?: Record; facts?: Record; api?: (url: string) => Response } = {}) {
+ const fake = createFakeIssuer();
+ fake.addPerson({ email: 'alice@acme.test', password: PASSWORD, workspaces: [{ id: 'ws-acme', name: 'Acme', role: 'OWNER' }] });
+ fake.setFlags({ 'bridge-app-active': true, 'bridge-billing-manage': true, ...options.flags });
+ fake.setFacts({ plan: { key: 'free', name: 'Free' }, status: 'active', access: 'ok', ...options.facts });
+ const fetchFn = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = new Request(input, init).url;
+ return options.api !== undefined && url.startsWith(API) ? options.api(url) : fake.fetch(input, init);
+ }) as typeof fetch;
+ const client = startClient(resolveConfig({ issuer: fake.issuer, tokenOrigins: [API] }), {
+ fetch: fetchFn,
+ storage: memoryStorage(),
+ autoRefresh: false,
+ locks: null,
+ tabChannel: null,
+ live: false,
+ });
+ await client.signIn.start({ email: 'alice@acme.test', password: PASSWORD });
+ await client.flags.load();
+ return { fake, client };
+}
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 20));
+
+afterEach(() => {
+ cleanup();
+ resetClient();
+ closeUpgrade();
+});
+
+describe('useQuota', () => {
+ it('is loading, then the numbers, and moves when the quota is read again', async () => {
+ const { fake, client } = await signedIn();
+ fake.setQuota('tickets', read(8, 10));
+ const { result } = renderHook(() => useQuota('tickets'));
+ expect(result.current).toMatchObject({ loading: true, used: null, limit: null });
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(result.current).toMatchObject({ unlimited: false, used: 8, limit: 10, remaining: 2, kind: 'counter', warningLevel: 'approaching', ratio: 0.8, state: 'near' });
+ expect(result.current.snapshot?.policy).toBe('hard');
+ fake.setQuota('tickets', read(10, 10, { kind: 'gauge' }));
+ await act(() => client.quotas.refresh());
+ expect(result.current).toMatchObject({ used: 10, kind: 'gauge', ratio: 1, state: 'over' });
+ });
+
+ it('says unlimited for a metric the plan sets no limit on, and asks once', async () => {
+ const { fake } = await signedIn();
+ fake.setQuota('seats', null);
+ const { result, rerender } = renderHook(() => useQuota('seats'));
+ expect(result.current.loading).toBe(true);
+ await waitFor(() => expect(result.current).toMatchObject({ loading: false, unlimited: true, used: null, limit: null, ratio: null, state: null }));
+ rerender();
+ renderHook(() => useQuota('seats'));
+ await flush();
+ expect(fake.quotaReads.filter((m) => m === 'seats')).toHaveLength(1);
+ });
+
+ it('asks again once a person has signed in again, whatever it was before', async () => {
+ const { fake, client } = await signedIn();
+ fake.setQuota('seats', null);
+ const { result } = renderHook(() => useQuota('seats'));
+ await waitFor(() => expect(result.current.unlimited).toBe(true));
+ await act(() => client.signOut());
+ fake.setQuota('seats', read(2, 5));
+ await act(() => client.signIn.start({ email: 'alice@acme.test', password: PASSWORD }));
+ await waitFor(() => expect(result.current).toMatchObject({ unlimited: false, used: 2, limit: 5 }));
+ });
+
+ it('is loading before there is a client, never a zero', () => {
+ const { result } = renderHook(() => useQuota('tickets'));
+ expect(result.current).toMatchObject({ loading: true, unlimited: false, used: null, limit: null });
+ });
+});
+
+describe('useEntitlements', () => {
+ it('reads the entitlement flags, fail-closed, and says when it is ready', async () => {
+ const before = renderHook(() => useEntitlements());
+ expect(before.result.current).toMatchObject({ ready: false, all: {} });
+ expect(before.result.current.can('analytics')).toBe(false);
+ before.unmount();
+ await signedIn({ flags: { 'bridge:billing.entitlement.analytics': true, 'bridge:billing.entitlement.sso': false, analytics: true } });
+ const { result } = renderHook(() => useEntitlements());
+ expect(result.current.ready).toBe(true);
+ expect(result.current.can('analytics')).toBe(true);
+ expect(result.current.can('sso')).toBe(false);
+ expect(result.current.can('unknown')).toBe(false);
+ expect(result.current.all).toEqual({ analytics: true, sso: false });
+ });
+
+ it('follows a plan change', async () => {
+ const { fake, client } = await signedIn({ flags: { 'bridge:billing.entitlement.sso': false } });
+ const { result } = renderHook(() => useEntitlements());
+ expect(result.current.can('sso')).toBe(false);
+ fake.setFlags({ 'bridge-app-active': true, 'bridge:billing.entitlement.sso': true });
+ await act(() => client.flags.load());
+ expect(result.current.can('sso')).toBe(true);
+ });
+});
+
+describe('QuotaGate', () => {
+ // A button in a disabled fieldset is disabled by the browser: it matches `:disabled`, though its own property stays false.
+ const button = () => screen.getByRole('button', { name: 'New ticket' });
+ const gate = () => document.querySelector('[data-bridge-quota-gate]');
+
+ it('disables its children at a hard limit and offers the upgrade', async () => {
+ const { fake, client } = await signedIn();
+ fake.setQuota('tickets', read(3, 3));
+ await client.quotas.read('tickets');
+ const { unmount } = render(
+
+ New ticket
+ ,
+ );
+ expect(button().matches(':disabled')).toBe(true);
+ expect(gate()?.getAttribute('data-state')).toBe('at-limit');
+ expect(document.querySelector('[data-bridge-quota-gate-limit]')?.textContent).toContain('all 3 tickets on your plan.');
+ expect(document.querySelector('[data-bridge-quota-gate-limit] a')?.getAttribute('href')).toBe('/subscription');
+ unmount();
+ render(
+ <>{q.used} of {q.limit} used>}>
+ New ticket
+ ,
+ );
+ expect(document.querySelector('[data-bridge-quota-gate-limit]')?.textContent).toBe('3 of 3 used');
+ });
+
+ it('never disables on "do not know yet", no limit, a metered limit, or room left', async () => {
+ const { fake, client } = await signedIn();
+ fake.setQuota('tickets', read(1, 3));
+ fake.setQuota('seats', null);
+ fake.setQuota('exports', read(9, 5, { policy: 'metered' }));
+ const states: Record = {};
+ for (const metric of ['tickets', 'seats', 'exports']) {
+ const { unmount } = render(
+
+ New ticket
+ ,
+ );
+ expect(button().matches(':disabled')).toBe(false);
+ if (metric === 'tickets') expect(gate()?.getAttribute('data-state')).toBe('loading');
+ unmount();
+ }
+ await Promise.all(['tickets', 'seats', 'exports'].map((m) => client.quotas.read(m)));
+ for (const metric of ['tickets', 'seats', 'exports']) {
+ const { unmount } = render(
+
+ New ticket
+ ,
+ );
+ await waitFor(() => expect(gate()?.getAttribute('data-state')).not.toBe('loading'));
+ states[metric] = gate()?.getAttribute('data-state');
+ expect(button().matches(':disabled')).toBe(false);
+ unmount();
+ }
+ expect(states).toEqual({ tickets: 'available', seats: 'unlimited', exports: 'metered' });
+ });
+
+ it('decides from the quota alone', () => {
+ const loaded = { loading: false, unlimited: false, used: 3, limit: 3, remaining: 0, warningLevel: null, kind: 'counter', snapshot: null, ratio: 1, state: 'over' } as const;
+ expect(quotaGateState(loaded)).toBe('at-limit');
+ expect(quotaGateState({ ...loaded, remaining: 1, used: 2, ratio: 0.6, state: 'ok' })).toBe('available');
+ });
+});
+
+describe('Entitled', () => {
+ it('renders neither branch until Bridge has answered, then the one that applies', async () => {
+ const wait = render(
+ no
} loading={wait
}>
+ yes
+ ,
+ );
+ expect(screen.queryByText('wait')).not.toBeNull();
+ wait.unmount();
+ await signedIn({ flags: { 'bridge:billing.entitlement.analytics': true } });
+ const on = render(
+ no}>
+ yes
+ ,
+ );
+ expect(screen.queryByText('yes')).not.toBeNull();
+ expect(screen.queryByText('no')).toBeNull();
+ on.unmount();
+ render(
+ no}>
+ yes
+ ,
+ );
+ expect(screen.queryByText('no')).not.toBeNull();
+ expect(screen.queryByText('yes')).toBeNull();
+ });
+});
+
+describe('QuotaBanner', () => {
+ const banner = () => document.querySelector('[data-bridge-quota-banner]');
+
+ it('shows from 80%, the limit reached, and the overage of a metered limit; nothing below', async () => {
+ const { fake, client } = await signedIn();
+ fake.setQuota('low', read(1, 10));
+ fake.setQuota('near', read(8, 10));
+ fake.setQuota('edge', read(10, 10));
+ fake.setQuota('over', read(12, 10));
+ fake.setQuota('metered', read(12, 10, { policy: 'metered', overageEstimate: 2, currency: 'usd' }));
+ await Promise.all(['low', 'near', 'edge', 'over', 'metered'].map((m) => client.quotas.read(m)));
+ const shows = async (metric: string, label?: string) => {
+ const { unmount } = render( );
+ await flush();
+ const found = banner();
+ const state = found?.getAttribute('data-state') ?? null;
+ const text = found?.textContent ?? '';
+ const cta = found?.querySelector('[data-bridge-quota-banner-cta]')?.textContent ?? null;
+ unmount();
+ return { state, text, cta };
+ };
+ expect((await shows('low')).state).toBeNull();
+ expect((await shows('unasked')).state).toBeNull();
+ const near = await shows('near', 'Tickets');
+ expect(near).toMatchObject({ state: 'approaching', cta: 'Upgrade' });
+ expect(near.text).toContain('Tickets approaching cap');
+ expect((await shows('edge')).state).toBe('reached');
+ expect((await shows('over')).state).toBe('over');
+ const metered = await shows('metered');
+ expect(metered.state).toBe('metered');
+ expect(metered.text).toContain('2 over your 10 included');
+ });
+
+ it('moves by itself when the quota is read again, and is the 0.9 name too', async () => {
+ const { fake, client } = await signedIn();
+ fake.setQuota('tickets', read(1, 10));
+ render( );
+ await flush();
+ expect(banner()).toBeNull();
+ fake.setQuota('tickets', read(10, 10));
+ await act(() => client.quotas.refresh());
+ expect(banner()?.getAttribute('data-state')).toBe('reached');
+ expect(banner()?.getAttribute('role')).toBe('alert');
+ const { BridgeQuotaBanner, QuotaBanner: Same } = await import('../../index.js');
+ expect(BridgeQuotaBanner).toBe(Same);
+ });
+
+ it('tells a person who may not manage billing to ask the owner, without an upgrade link', async () => {
+ const { fake, client } = await signedIn({ flags: { 'bridge-billing-manage': false } });
+ fake.setQuota('edge', read(10, 10));
+ await client.quotas.read('edge');
+ render( );
+ await waitFor(() => expect(banner()).not.toBeNull());
+ expect(banner()?.textContent).toContain('Contact your workspace owner.');
+ expect(banner()?.querySelector('[data-bridge-quota-banner-cta]')).toBeNull();
+ });
+
+ it('decides from the numbers when the server sent no warning level', () => {
+ const snap = (used: number) => ({ metric: 'm', used, limit: 100, remaining: 100 - used, percent_used: used / 100, policy: 'hard' as const, warningLevel: null, label: 'm' });
+ expect(quotaBannerState(snap(79))).toBe('hidden');
+ expect(quotaBannerState(snap(80))).toBe('approaching');
+ expect(quotaBannerState(snap(95))).toBe('critical');
+ expect(quotaBannerState(snap(100))).toBe('reached');
+ expect(quotaBannerState(snap(101))).toBe('over');
+ expect(warningOf(snap(96))).toBe('critical');
+ expect(quotaBannerCopy(snap(96), false, 'Seats').body).toBe('Your workspace is approaching its Seats cap. Contact your workspace owner.');
+ expect(quotaBannerState(undefined)).toBe('hidden');
+ });
+});
+
+describe('the billing lock', () => {
+ const locked = { status: 'past_due', access: 'blocked', locked: true };
+
+ it('shows to the person, as a banner or a blocking screen', async () => {
+ await signedIn({ facts: locked });
+ const gate = renderHook(() => useBillingGate());
+ await waitFor(() => expect(gate.result.current).toMatchObject({ locked: true, severity: 'locked' }));
+ const soft = render( );
+ expect(document.querySelector('[data-bridge-billing-notice][data-kind="blocked"]')?.textContent).toContain('Access locked');
+ expect(document.querySelector('[data-bridge-billing-lockscreen]')).toBeNull();
+ soft.unmount();
+ render( );
+ expect(document.querySelector('[data-bridge-billing-lockscreen]')?.getAttribute('role')).toBe('alertdialog');
+ });
+
+ it('shows at once when your API refuses a write because of the lock, and opens no dialog', async () => {
+ const { client } = await signedIn({
+ api: () => Response.json({ code: 'BILLING_GATE_ENGAGED', reason: 'billing_locked', billing: { status: 'past_due', gateEngaged: true } }, { status: 402 }),
+ });
+ await flush();
+ const gate = renderHook(() => useBillingGate());
+ expect(gate.result.current.locked).toBe(false);
+ render( );
+ expect(document.querySelector('[data-bridge-billing-lockscreen]')).toBeNull();
+ const response = await act(() => bridgeFetch(`${API}/tickets`, { method: 'POST' }));
+ expect(response.status).toBe(402);
+ expect(client.isLocked()).toBe(true);
+ await waitFor(() => expect(gate.result.current).toMatchObject({ locked: true, recoveryUrl: '/subscription' }));
+ expect(upgradeRequest.get()).toBeNull();
+ await waitFor(() => expect(document.querySelector('[data-bridge-billing-lockscreen]')).not.toBeNull());
+ });
+});
+
+describe('a 402 at a plan limit', () => {
+ const limit = { statusCode: 402, code: 'QUOTA_EXCEEDED', message: 'Over', metric: 'tickets', used: 3, limit: 3, fix: '/subscription' };
+
+ it('opens the upgrade dialog and tells the listeners, who can stop listening', async () => {
+ await signedIn({ api: () => Response.json(limit, { status: 402 }) });
+ const heard: BridgeQuotaRefusal[] = [];
+ const stop = onBridgeQuotaExceeded((refusal) => heard.push(refusal));
+ onBridgeQuotaExceeded(() => {
+ throw new Error('a broken listener');
+ });
+ await bridgeFetch(`${API}/tickets`, { method: 'POST' });
+ expect(upgradeRequest.get()).toMatchObject({ kind: 'limit', metric: 'tickets', used: 3, limit: 3, upgradeHref: '/subscription' });
+ expect(heard).toEqual([{ metric: 'tickets', used: 3, limit: 3, fix: '/subscription', message: 'Over', url: `${API}/tickets` }]);
+ stop();
+ await bridgeFetch(`${API}/tickets`, { method: 'POST' });
+ expect(heard).toHaveLength(1);
+ });
+
+ it('is not a refusal when it is a missing plan feature, a declined card or not a 402 body', () => {
+ expect(parseQuotaRefusal({ code: 'FEATURE_NOT_IN_PLAN', flag: 'reports' })).toBeNull();
+ expect(parseQuotaRefusal({ code: 'CARD_DECLINED' })).toBeNull();
+ expect(parseQuotaRefusal('nope')).toBeNull();
+ expect(parseQuotaRefusal({ type: 'urn:bridge:problem:limit-reached', metric: 'seats', limit: 5, used: 5 })).toMatchObject({ metric: 'seats', fix: null });
+ });
+});
+
+describe('the 0.9 names', () => {
+ it('BridgeBillingNotice, BridgeQuotaBanner and BridgeUpgradeDialog are the 1.0 components', async () => {
+ const lib = await import('../../index.js');
+ expect(lib.BridgeBillingNotice).toBe(lib.BillingNotice);
+ expect(lib.BridgeQuotaBanner).toBe(lib.QuotaBanner);
+ expect(lib.BridgeUpgradeDialog).toBe(lib.UpgradeDialog);
+ });
+
+ it('dismissQuotaRefusal closes the upgrade dialog a refusal opened', async () => {
+ const { dismissQuotaRefusal } = await import('../../index.js');
+ await signedIn({ api: () => new Response(JSON.stringify({ statusCode: 402, code: 'QUOTA_EXCEEDED', metric: 'tickets', used: 3, limit: 3, fix: '/subscription', message: 'Over' }), { status: 402, headers: { 'content-type': 'application/json' } }) });
+ await bridgeFetch(`${API}/tickets`, { method: 'POST' });
+ expect(upgradeRequest.get()).not.toBeNull();
+ dismissQuotaRefusal();
+ expect(upgradeRequest.get()).toBeNull();
+ });
+
+ it('useBridgeBilling answers before there is a client: nothing locked, no quota, no feature', async () => {
+ const { useBridgeBilling } = await import('../../index.js');
+ const billing = useBridgeBilling();
+ expect(billing.isLocked()).toBe(false);
+ expect(billing.gateState()).toEqual({ locked: false, severity: 'info', noticeState: 'active' });
+ expect(billing.quota('tickets')).toBeUndefined();
+ expect(billing.entitlements.can('analytics')).toBe(false);
+ expect(billing.entitlements.all()).toEqual({});
+ expect(() => billing.assertNotLocked()).not.toThrow();
+ expect(() => billing.quotas).toThrow();
+ });
+
+ it('useBridgeBilling follows the page\'s client: quota, plan features, the lock and the quota.updated handler', async () => {
+ const { useBridgeBilling } = await import('../../index.js');
+ const billing = useBridgeBilling();
+ const heard: string[] = [];
+ const stop = billing.handle({ 'quota.updated': (message) => heard.push(message.metric) });
+ const { fake } = await signedIn({ flags: { 'bridge:billing.entitlement.analytics': true }, facts: { status: 'past_due', access: 'blocked' } });
+ fake.setQuota('tickets', read(2, 5));
+ expect(billing.quota('tickets')).toBeUndefined();
+ await waitFor(() => expect(billing.quota('tickets')).toMatchObject({ used: 2, limit: 5 }));
+ expect(billing.quotas.get('tickets')).toMatchObject({ used: 2 });
+ expect(billing.entitlements.can('analytics')).toBe(true);
+ expect(billing.entitlements.all()).toMatchObject({ analytics: true });
+ await waitFor(() => expect(billing.isLocked()).toBe(true));
+ expect(billing.gateState()).toMatchObject({ locked: true, severity: 'locked' });
+ expect(() => billing.assertNotLocked()).toThrow();
+ stop();
+ expect(heard).toEqual([]);
+ });
+});
diff --git a/bridge-react/src/components/billing/quota-copy.ts b/bridge-react/src/components/billing/quota-copy.ts
new file mode 100644
index 0000000..3ab5bbd
--- /dev/null
+++ b/bridge-react/src/components/billing/quota-copy.ts
@@ -0,0 +1,89 @@
+/** What `QuotaBanner` says, as a pure decision: where a quota sits, and the words for it. */
+import type { QuotaSnapshot } from '@nebulr-group/bridge-auth-core';
+import { warningOf } from '../../core/quota.js';
+
+export type QuotaBannerState = 'hidden' | 'approaching' | 'critical' | 'reached' | 'over' | 'metered';
+
+export interface QuotaBannerCopy {
+ readonly title: string;
+ readonly body: string;
+ readonly cta?: string;
+}
+
+const OWNER = 'Contact your workspace owner.';
+
+/** Where a snapshot sits. A metered quota bills instead of blocking and keeps its own words; exactly at a hard limit is `reached`, not "approaching". */
+export function quotaBannerState(snapshot: QuotaSnapshot | undefined | null): QuotaBannerState {
+ if (snapshot === undefined || snapshot === null) return 'hidden';
+ const level = warningOf(snapshot);
+ if (snapshot.policy === 'metered') return level !== null || (snapshot.overcap ?? snapshot.used > snapshot.limit) ? 'metered' : 'hidden';
+ if (snapshot.limit > 0 && snapshot.used > snapshot.limit) return 'over';
+ if (snapshot.limit > 0 && snapshot.used >= snapshot.limit) return 'reached';
+ return level === 'critical' ? 'critical' : level === 'approaching' ? 'approaching' : 'hidden';
+}
+
+/** An amount of money as `$1.00` or `1.00 SEK`. */
+export function formatCost(amount: number | undefined, currency: string | undefined): string {
+ if (amount === undefined) return '';
+ const code = (currency ?? '').toUpperCase();
+ try {
+ return new Intl.NumberFormat(undefined, { style: 'currency', currency: code || 'USD' }).format(amount);
+ } catch {
+ return `${amount.toFixed(2)}${code ? ` ${code}` : ''}`;
+ }
+}
+
+function memberBody(label: string, state: 'over' | 'reached' | 'critical' | 'approaching'): string {
+ switch (state) {
+ case 'over':
+ return `Your workspace is over its ${label} cap. ${OWNER}`;
+ case 'reached':
+ return `Your workspace has reached its ${label} limit. ${OWNER}`;
+ case 'critical':
+ return `Your workspace is approaching its ${label} cap. ${OWNER}`;
+ case 'approaching':
+ return `Your workspace is approaching its ${label} cap.`;
+ }
+}
+
+export function quotaBannerCopy(snapshot: QuotaSnapshot | undefined | null, admin: boolean, label: string): QuotaBannerCopy {
+ const state = quotaBannerState(snapshot);
+ if (snapshot === undefined || snapshot === null || state === 'hidden') return { title: '', body: '' };
+
+ if (state === 'metered') {
+ const over = snapshot.limit > 0 ? Math.max(0, snapshot.used - snapshot.limit) : snapshot.used;
+ const cost = formatCost(snapshot.overageEstimate, snapshot.currency);
+ const estimate = cost ? ` · ~${cost} estimated this period` : '';
+ if (snapshot.limit > 0) {
+ if (over > 0) return { title: `${label} overage`, body: `${over.toLocaleString()} over your ${snapshot.limit.toLocaleString()} included${estimate}.` };
+ const unit = formatCost(snapshot.unitAmount, snapshot.currency);
+ return {
+ title: `${label} approaching included limit`,
+ body: `You've used ${snapshot.used.toLocaleString()} of ${snapshot.limit.toLocaleString()} included${unit ? ` — extra usage is billed at ${unit}/unit` : ''}.`,
+ };
+ }
+ return { title: `${label} usage`, body: `${snapshot.used.toLocaleString()} ${label}${estimate}.` };
+ }
+
+ const used = snapshot.used.toLocaleString();
+ const limit = snapshot.limit.toLocaleString();
+ const left = Math.max(0, snapshot.remaining).toLocaleString();
+ switch (state) {
+ case 'over':
+ return admin
+ ? { title: `${label} over cap`, body: `You've used ${used} of ${limit}. Upgrade your plan to add headroom.`, cta: 'Upgrade' }
+ : { title: `${label} over cap`, body: memberBody(label, 'over') };
+ case 'reached':
+ return admin
+ ? { title: `${label} limit reached`, body: `You've used all ${limit} on your plan. Upgrade your plan to add more.`, cta: 'Upgrade' }
+ : { title: `${label} limit reached`, body: memberBody(label, 'reached') };
+ case 'critical':
+ return admin
+ ? { title: `${label} near cap`, body: `You've used ${used} of ${limit} (${left} left). Upgrade to avoid hitting the cap.`, cta: 'Upgrade' }
+ : { title: `${label} near cap`, body: memberBody(label, 'critical') };
+ default:
+ return admin
+ ? { title: `${label} approaching cap`, body: `You've used ${used} of ${limit} (${left} left).`, cta: 'Upgrade' }
+ : { title: `${label} approaching cap`, body: memberBody(label, 'approaching') };
+ }
+}
diff --git a/bridge-react/src/components/billing/quota.ts b/bridge-react/src/components/billing/quota.ts
deleted file mode 100644
index 8f7732d..0000000
--- a/bridge-react/src/components/billing/quota.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * One metric's usage against its plan limit, for your own UI:
- *
- * ```tsx
- * const projects = useQuota('projects');
- * return projects ? {projects.used} of {projects.limit} projects : null;
- * ```
- *
- * Numbers only, never a gate: whether something is allowed is a flag.
- */
-import type { UsageNumbers } from '@nebulr-group/bridge-auth-core';
-import { useMemo } from 'react';
-import { useUsage } from '../../react/hooks.js';
-
-export type QuotaState = 'ok' | 'near' | 'over';
-
-export interface Quota {
- readonly used: number;
- readonly limit: number;
- /** `used / limit`; 1 for a limit of 0. */
- readonly ratio: number;
- /** `near` from 80% of the limit, `over` once the limit is reached. */
- readonly state: QuotaState;
-}
-
-/** From this share of the limit, a metric is `near` it. */
-export const NEAR_LIMIT = 0.8;
-
-/** A metric's quota from the usage numbers, or null when it has no limit or is not loaded. */
-export function quotaFor(numbers: UsageNumbers | null | undefined, metric: string): Quota | null {
- const row = numbers?.metrics.find((m) => m.metric === metric);
- if (!row || row.limit === null) return null;
- const { used, limit } = row;
- const ratio = limit > 0 ? used / limit : 1;
- const state: QuotaState = used >= limit ? 'over' : ratio >= NEAR_LIMIT ? 'near' : 'ok';
- return { used, limit, ratio, state };
-}
-
-/** A metric's quota: null while loading and for a metric without a limit. */
-export function useQuota(metric: string): Quota | null {
- const numbers = useUsage().value;
- return useMemo(() => quotaFor(numbers, metric), [numbers, metric]);
-}
diff --git a/bridge-react/src/core/fetch.ts b/bridge-react/src/core/fetch.ts
index df04392..8ddf097 100644
--- a/bridge-react/src/core/fetch.ts
+++ b/bridge-react/src/core/fetch.ts
@@ -8,14 +8,16 @@
* is sent.
* - A 402 that is a plan limit or a missing plan feature opens the upgrade
* dialog, when it came straight from your page's origin, your
- * `tokenOrigins` or Bridge (never after a redirect). The response is
- * returned as it came, either way.
+ * `tokenOrigins` or Bridge (never after a redirect), and tells
+ * `onBridgeQuotaExceeded` listeners of a limit. The response is
+ * returned as it came, either way. A 402 for a workspace locked for
+ * payment shows the lock (`BillingNotice`) and opens no dialog.
*
* There is no global fetch patch: only calls made through this carry a token.
*/
import type { Bridge } from '@nebulr-group/bridge-auth-core';
import { getBridge, peekConfig } from './client.js';
-import { openUpgrade, readPaymentRequired } from './upgrade.js';
+import { openUpgrade, parseQuotaRefusal, readPaymentRequired, reportQuotaRefusal } from './upgrade.js';
function originOf(url: string): string | null {
try {
@@ -51,8 +53,11 @@ export async function bridgeFetch(input: RequestInfo | URL, init?: RequestInit):
const requested = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
if (response.status === 402 && mayExplain(bridge, requested, response)) {
try {
- const request = readPaymentRequired(await response.clone().json());
+ const body: unknown = await response.clone().json();
+ const request = readPaymentRequired(body);
if (request !== null) openUpgrade(request);
+ const refusal = parseQuotaRefusal(body, response.url !== '' ? response.url : requested);
+ if (refusal !== null) reportQuotaRefusal(refusal);
} catch {
// Not JSON: not a refusal the dialog can explain.
}
diff --git a/bridge-react/src/core/quota.ts b/bridge-react/src/core/quota.ts
new file mode 100644
index 0000000..5c24d0e
--- /dev/null
+++ b/bridge-react/src/core/quota.ts
@@ -0,0 +1,120 @@
+/**
+ * One metric's quota against the plan, as plain values: the numbers `useQuota` gives, the level a banner shows, and
+ * what the page remembers of Bridge's "no limit on this plan" answers. The numbers themselves are auth-core's quota
+ * store: one read when first asked for, then again when Bridge says a quota or the plan changed.
+ */
+import type { Bridge, QuotaSnapshot } from '@nebulr-group/bridge-auth-core';
+
+/** How near a metric is to its limit: `near` from 80%, `over` once the limit is reached. */
+export type QuotaLevel = 'ok' | 'near' | 'over';
+
+/** What `useQuota(metric)` gives. */
+export interface QuotaState {
+ /** True until Bridge has answered for this metric. The numbers are `null` meanwhile, never 0. */
+ readonly loading: boolean;
+ /** True once Bridge has answered that the plan puts no limit on the metric. */
+ readonly unlimited: boolean;
+ /** `counter`: this period's total. `gauge`: how many exist now. `null` while loading or unlimited. */
+ readonly used: number | null;
+ /** The plan's limit. `null` while loading or unlimited. */
+ readonly limit: number | null;
+ /** What is left before the limit. `null` while loading or unlimited. */
+ readonly remaining: number | null;
+ /** `approaching` from 80%, `critical` from 95%; `null` below that, while loading or unlimited. */
+ readonly warningLevel: 'approaching' | 'critical' | null;
+ /** `counter` counts up from your server's usage reports and resets each period; `gauge` is the level your server sets. */
+ readonly kind: 'counter' | 'gauge' | null;
+ /** The whole snapshot (policy, overage), or `null` while loading or unlimited. */
+ readonly snapshot: QuotaSnapshot | null;
+ /** `used / limit`; 1 for a limit of 0. `null` while loading or unlimited. */
+ readonly ratio: number | null;
+ /** `near` from 80% of the limit, `over` once it is reached. `null` while loading or unlimited. */
+ readonly state: QuotaLevel | null;
+}
+
+/** From this share of the limit, a metric is `near` it. */
+export const NEAR_LIMIT = 0.8;
+const CRITICAL = 0.95;
+
+/**
+ * How near a hard limit a snapshot is: the server's level, or from the numbers when it sent none. The same 80% and 95%
+ * the server uses.
+ */
+export function warningOf(snapshot: QuotaSnapshot): 'approaching' | 'critical' | null {
+ if (snapshot.warningLevel !== null) return snapshot.warningLevel;
+ if (snapshot.limit <= 0) return null;
+ const ratio = snapshot.used / snapshot.limit;
+ return ratio >= CRITICAL ? 'critical' : ratio >= NEAR_LIMIT ? 'approaching' : null;
+}
+
+const LOADING: QuotaState = Object.freeze({ loading: true, unlimited: false, used: null, limit: null, remaining: null, warningLevel: null, kind: null, snapshot: null, ratio: null, state: null });
+const UNLIMITED: QuotaState = Object.freeze({ ...LOADING, loading: false, unlimited: true });
+
+// One state object per snapshot object, so a reader sees the same value until the store changes it.
+const states = new WeakMap();
+
+function stateOf(snapshot: QuotaSnapshot): QuotaState {
+ let state = states.get(snapshot);
+ if (state === undefined) {
+ const { used, limit } = snapshot;
+ const ratio = limit > 0 ? used / limit : 1;
+ state = Object.freeze({
+ loading: false,
+ unlimited: false,
+ used,
+ limit,
+ remaining: snapshot.remaining,
+ warningLevel: warningOf(snapshot),
+ kind: snapshot.kind === 'gauge' ? 'gauge' : 'counter',
+ snapshot,
+ ratio,
+ state: used >= limit ? 'over' : ratio >= NEAR_LIMIT ? 'near' : 'ok',
+ } as const) as QuotaState;
+ states.set(snapshot, state);
+ }
+ return state;
+}
+
+// The quota store answers "no limit on this plan" by deleting the metric and telling `undefined`, and keeps no record
+// of it: a reader that read again on that would ask again for as long as the page is open. The answers are remembered
+// here, once per client, and a remembered metric is not asked for again until the person or workspace changes.
+interface Tracking {
+ readonly unlimited: Set;
+ who: string | null | undefined;
+}
+const tracked = new WeakMap();
+
+export function trackingOf(client: Bridge): Tracking {
+ let t = tracked.get(client);
+ if (t === undefined) {
+ const made: Tracking = { unlimited: new Set(), who: undefined };
+ t = made;
+ tracked.set(client, made);
+ client.quotas.subscribe((metric, snapshot) => {
+ if (snapshot === undefined) made.unlimited.add(metric);
+ else made.unlimited.delete(metric);
+ });
+ }
+ return t;
+}
+
+/** Tells the tracking who is signed in (null: nobody). Another person or workspace has another plan: what was "unlimited" no longer holds. */
+export function noteSession(client: Bridge, who: string | null): void {
+ const t = trackingOf(client);
+ if (t.who !== undefined && who !== t.who) t.unlimited.clear();
+ t.who = who;
+}
+
+/** What the page knows of a metric now, with no side effects. */
+export function readQuotaState(client: Bridge, metric: string): QuotaState {
+ const snapshot = client.quotas.get(metric);
+ if (snapshot !== undefined) return stateOf(snapshot);
+ return trackingOf(client).unlimited.has(metric) ? UNLIMITED : LOADING;
+}
+
+/** Starts the read of a metric, unless it is held or Bridge already answered that it has no limit. The store dedupes one in flight. */
+export function askForQuota(client: Bridge, metric: string): void {
+ if (client.quotas.get(metric) === undefined && !trackingOf(client).unlimited.has(metric)) client.quota(metric);
+}
+
+export const LOADING_QUOTA = LOADING;
diff --git a/bridge-react/src/core/upgrade.ts b/bridge-react/src/core/upgrade.ts
index 2449cf3..257b7cb 100644
--- a/bridge-react/src/core/upgrade.ts
+++ b/bridge-react/src/core/upgrade.ts
@@ -79,3 +79,51 @@ export function readPaymentRequired(body: unknown): UpgradeRequest | null {
}
return null;
}
+
+/** A plan limit your API refused: the 402 `QUOTA_EXCEEDED` answer, for code that wants to show something other than the dialog. */
+export interface BridgeQuotaRefusal {
+ /** The metric the plan ran out of, such as `tickets`. */
+ readonly metric: string;
+ /** How much was used when the request was refused, if the API said. */
+ readonly used: number | null;
+ /** The plan's limit, if the API said. */
+ readonly limit: number | null;
+ /** Where the refusal said to upgrade, when it named a page of this app; else null. */
+ readonly fix: string | null;
+ /** The API's own words, if it sent some. */
+ readonly message: string | null;
+ /** The address of the request that was refused. */
+ readonly url: string;
+}
+
+/** The refusal in a 402 body, or null when the body is not a plan limit (a declined card, a missing plan feature). */
+export function parseQuotaRefusal(body: unknown, url = ''): BridgeQuotaRefusal | null {
+ const request = readPaymentRequired(body);
+ if (request === null || request.kind !== 'limit' || request.metric === null || request.metric === undefined) return null;
+ return { metric: request.metric, used: request.used ?? null, limit: request.limit ?? null, fix: request.upgradeHref ?? null, message: request.message ?? null, url };
+}
+
+type QuotaListener = (refusal: BridgeQuotaRefusal) => void;
+const listeners = new Set();
+
+/**
+ * Runs `handler` each time your API refuses a request at a plan limit, through `bridgeFetch`: for an app that turned the
+ * dialog off (`billing.upgradeDialog: false`) and shows its own. Returns how to stop.
+ */
+export function onBridgeQuotaExceeded(handler: QuotaListener): () => void {
+ listeners.add(handler);
+ return () => {
+ listeners.delete(handler);
+ };
+}
+
+/** Tells the listeners of one refusal. A broken listener stops neither the others nor the dialog. */
+export function reportQuotaRefusal(refusal: BridgeQuotaRefusal): void {
+ for (const listener of [...listeners]) {
+ try {
+ listener(refusal);
+ } catch {
+ // One listener's mistake is its own.
+ }
+ }
+}
diff --git a/bridge-react/src/index.ts b/bridge-react/src/index.ts
index 9be9ac7..61b3336 100644
--- a/bridge-react/src/index.ts
+++ b/bridge-react/src/index.ts
@@ -47,14 +47,21 @@ export {
export type { CurrentWorkspace, ResourceState } from './react/hooks.js';
export { billing, me, plans, resource, usage, workspaces } from './core/resources.js';
export type { Resource, ResourceStore } from './core/resources.js';
+export { useEntitlements } from './react/entitlements.js';
+export type { EntitlementsState } from './react/entitlements.js';
+export { useBillingGate, useBillingLocked } from './react/billing-gate.js';
+export { useBridgeBilling } from './react/bridge-billing.js';
+export type { BridgeBillingApi } from './react/bridge-billing.js';
+export { useQuota } from './react/quota.js';
+export type { QuotaLevel, QuotaState } from './core/quota.js';
// Flags
export { canManageBilling, canManageTeam, requireFlag } from './core/flags.js';
// Calling your API
export { bridgeFetch } from './core/fetch.js';
-export { closeUpgrade, openUpgrade, readPaymentRequired, upgradeRequest } from './core/upgrade.js';
-export type { UpgradeDialogProps, UpgradeRequest } from './core/upgrade.js';
+export { closeUpgrade, closeUpgrade as dismissQuotaRefusal, onBridgeQuotaExceeded, openUpgrade, parseQuotaRefusal, readPaymentRequired, upgradeRequest } from './core/upgrade.js';
+export type { BridgeQuotaRefusal, UpgradeDialogProps, UpgradeRequest } from './core/upgrade.js';
// Hand-off mode
export { handoffSignIn, readHandoff, returnToProgram } from './core/handoff.js';
@@ -67,7 +74,7 @@ export type { PluginMessageKey } from './core/messages.js';
// The few auth-core names app code needs to use this package
export { BridgeError, isBridgeError, STANDARD_FLAGS } from '@nebulr-group/bridge-auth-core';
-export type { Bridge, BridgeErrorKind, SessionState, SessionUser, SessionWorkspace } from '@nebulr-group/bridge-auth-core';
+export type { BillingGateState, Bridge, BridgeErrorKind, QuotaSnapshot, SessionState, SessionUser, SessionWorkspace } from '@nebulr-group/bridge-auth-core';
// Components
export { Link } from './components/shared/Link.js';
@@ -106,6 +113,7 @@ export { ProfileName } from './components/auth/ProfileName.js';
export { FeatureFlag } from './components/flags/FeatureFlag.js';
export type { FeatureFlagOffInfo, FeatureFlagProps } from './components/flags/FeatureFlag.js';
export { UpgradeDialog } from './components/billing/UpgradeDialog.js';
+export { UpgradeDialog as BridgeUpgradeDialog } from './components/billing/UpgradeDialog.js';
export { LiveStatusBadge } from './components/live/LiveStatusBadge.js';
export { TeamPanel } from './components/team/TeamPanel.js';
export type { TeamPanelProps, TeamTab, TeamTabId } from './components/team/TeamPanel.js';
@@ -132,10 +140,14 @@ export type { BillingPortalButtonProps } from './components/billing/BillingPorta
export { SubscriptionStatus } from './components/billing/SubscriptionStatus.js';
export type { SubscriptionStatusProps } from './components/billing/SubscriptionStatus.js';
export { BillingNotice } from './components/billing/BillingNotice.js';
-export type { BillingNoticeProps } from './components/billing/BillingNotice.js';
+export { BillingNotice as BridgeBillingNotice } from './components/billing/BillingNotice.js';
+export type { BillingNoticeProps, BillingNoticeProps as BridgeBillingNoticeProps } from './components/billing/BillingNotice.js';
export { QuotaBanner } from './components/billing/QuotaBanner.js';
+export { QuotaBanner as BridgeQuotaBanner } from './components/billing/QuotaBanner.js';
export type { QuotaBannerProps } from './components/billing/QuotaBanner.js';
+export { QuotaGate, quotaGateState } from './components/billing/QuotaGate.js';
+export type { QuotaGateProps, QuotaGateState } from './components/billing/QuotaGate.js';
+export { Entitled } from './components/billing/Entitled.js';
+export type { EntitledProps } from './components/billing/Entitled.js';
export { CheckoutNotice } from './components/billing/CheckoutNotice.js';
export type { CheckoutNoticeProps, CheckoutOutcome } from './components/billing/CheckoutNotice.js';
-export { useQuota } from './components/billing/quota.js';
-export type { Quota, QuotaState } from './components/billing/quota.js';
diff --git a/bridge-react/src/react/billing-gate.ts b/bridge-react/src/react/billing-gate.ts
new file mode 100644
index 0000000..057ae05
--- /dev/null
+++ b/bridge-react/src/react/billing-gate.ts
@@ -0,0 +1,34 @@
+/**
+ * Whether the workspace is locked for payment. The lock is Bridge's: a locked workspace can be read but not changed.
+ * It is read when the page starts and again when Bridge says access changed, and a 402 for the lock that your own API
+ * answers through `bridgeFetch` shows it at once.
+ */
+import type { BillingGateState } from '@nebulr-group/bridge-auth-core';
+import { useCallback, useSyncExternalStore } from 'react';
+import { useBridge } from './hooks.js';
+
+const OPEN: BillingGateState = Object.freeze({ locked: false, severity: 'info', noticeState: 'active' });
+const noop = () => undefined;
+
+// `gateState()` builds a new object on each call: the last one is kept while its values are the same.
+const last = new WeakMap();
+
+/** The lock: `{ locked, severity, noticeState, recoveryUrl }`. Not locked until Bridge says so. */
+export function useBillingGate(): BillingGateState {
+ const client = useBridge();
+ const subscribe = useCallback((onChange: () => void) => (client === null ? noop : client.on('gate-changed', onChange)), [client]);
+ const read = useCallback((): BillingGateState => {
+ if (client === null) return OPEN;
+ const now = client.gateState();
+ const before = last.get(client);
+ if (before !== undefined && before.locked === now.locked && before.severity === now.severity && before.noticeState === now.noticeState && before.recoveryUrl === now.recoveryUrl) return before;
+ last.set(client, now);
+ return now;
+ }, [client]);
+ return useSyncExternalStore(subscribe, read, read);
+}
+
+/** Whether the workspace is locked for payment. */
+export function useBillingLocked(): boolean {
+ return useBillingGate().locked;
+}
diff --git a/bridge-react/src/react/bridge-billing.ts b/bridge-react/src/react/bridge-billing.ts
new file mode 100644
index 0000000..b023fff
--- /dev/null
+++ b/bridge-react/src/react/bridge-billing.ts
@@ -0,0 +1,72 @@
+/**
+ * `useBridgeBilling()`: the 0.9 name for the billing handle. It is not a React hook: it reads nothing during render, so
+ * call it anywhere (a component, an event handler, a module). It always answers, and it follows the page's client: before
+ * `` has made one, nothing is locked, no quota is known, no plan feature is on.
+ *
+ * What it gives is what 0.9 gave for the numbers and the lock: `quota(metric)`, `quotas`, `entitlements`, `handle`,
+ * `isLocked()`, `gateState()` and `assertNotLocked()`. In a component, `useQuota`, `useEntitlements` and
+ * `useBillingGate` redraw on a change; this handle does not.
+ */
+import type { BillingEventHandlers, BillingGateState, Bridge, QuotaSnapshot, QuotaStore } from '@nebulr-group/bridge-auth-core';
+import { bridgeClient } from '../core/client.js';
+
+const OPEN: BillingGateState = Object.freeze({ locked: false, severity: 'info', noticeState: 'active' });
+const NO_FEATURES: Readonly> = Object.freeze({});
+
+export interface BridgeBillingApi {
+ /** The metric's numbers, or `undefined` until Bridge has answered (the read starts at the first call). */
+ quota(metric: string): QuotaSnapshot | undefined;
+ /** Every metric asked for, with `subscribe` to hear a change. Throws before `` has made the client. */
+ readonly quotas: QuotaStore;
+ readonly entitlements: {
+ /** Whether the plan has the feature: `false` until Bridge has answered. */
+ can(key: string): boolean;
+ all(): Readonly>;
+ };
+ /** Runs `handlers['quota.updated']` when a metric's numbers changed. Returns how to remove the handlers. */
+ handle(handlers: BillingEventHandlers): () => void;
+ /** True when the workspace is locked for payment; false until that is known. */
+ isLocked(): boolean;
+ gateState(): BillingGateState;
+ /** Throws a `BillingLockedError` when the workspace is locked for payment. */
+ assertNotLocked(): void;
+}
+
+const api: BridgeBillingApi = {
+ quota: (metric) => bridgeClient.get()?.quota(metric),
+ get quotas(): QuotaStore {
+ const client: Bridge | null = bridgeClient.get();
+ if (client === null) throw new Error('useBridgeBilling().quotas needs to have started.');
+ return client.quotas;
+ },
+ entitlements: {
+ can: (key) => bridgeClient.get()?.entitlements.can(key) ?? false,
+ all: () => bridgeClient.get()?.entitlements.all() ?? NO_FEATURES,
+ },
+ handle(handlers) {
+ // Handlers given before the client exists are attached when it does, and move to a client that replaces it.
+ let removeFromClient: (() => void) | null = null;
+ let current: Bridge | null = null;
+ const attach = (client: Bridge | null) => {
+ if (client === current) return;
+ removeFromClient?.();
+ removeFromClient = client === null ? null : client.handle(handlers);
+ current = client;
+ };
+ attach(bridgeClient.get());
+ const stopWatching = bridgeClient.subscribe(attach);
+ return () => {
+ stopWatching();
+ removeFromClient?.();
+ removeFromClient = null;
+ };
+ },
+ isLocked: () => bridgeClient.get()?.isLocked() ?? false,
+ gateState: () => bridgeClient.get()?.gateState() ?? OPEN,
+ assertNotLocked: () => bridgeClient.get()?.assertNotLocked(),
+};
+
+/** The billing handle of the page's client (see the file's comment). */
+export function useBridgeBilling(): BridgeBillingApi {
+ return api;
+}
diff --git a/bridge-react/src/react/entitlements.ts b/bridge-react/src/react/entitlements.ts
new file mode 100644
index 0000000..7e701bc
--- /dev/null
+++ b/bridge-react/src/react/entitlements.ts
@@ -0,0 +1,39 @@
+/**
+ * `useEntitlements()`: which plan features the workspace has.
+ *
+ * ```tsx
+ * const entitlements = useEntitlements();
+ * if (!entitlements.ready) return ;
+ * return entitlements.can('analytics') ? : ;
+ * ```
+ *
+ * A plan feature is the flag `bridge:billing.entitlement.`: `can('analytics')` reads that flag, never the plan, so
+ * a rule on the flag (a rollout, a privilege) is honoured. It is fail-closed: `false` until Bridge has answered and for
+ * a feature the plan does not have, and `ready` tells those two apart. It moves when the flags do.
+ */
+import { useMemo } from 'react';
+import { useBridge, useFlags, useFlagsStatus } from './hooks.js';
+
+export interface EntitlementsState {
+ /** True once Bridge has answered. Before that every `can()` is `false`. */
+ readonly ready: boolean;
+ /** `true` only when the plan has the feature `key` on. */
+ can(key: string): boolean;
+ /** Every plan feature Bridge gave a result for, `{ key: on }`. */
+ readonly all: Readonly>;
+}
+
+const NOT_READY: EntitlementsState = Object.freeze({ ready: false, all: Object.freeze({}), can: () => false });
+
+/** The workspace's plan features, live. */
+export function useEntitlements(): EntitlementsState {
+ const client = useBridge();
+ const flags = useFlags();
+ const status = useFlagsStatus();
+ return useMemo((): EntitlementsState => {
+ if (client === null || status !== 'ready') return NOT_READY;
+ const all = Object.freeze(client.entitlements.all());
+ return Object.freeze({ ready: true, all, can: (key: string) => client.entitlements.can(key) });
+ // `flags` changes whenever a result does.
+ }, [client, flags, status]);
+}
diff --git a/bridge-react/src/react/quota.ts b/bridge-react/src/react/quota.ts
new file mode 100644
index 0000000..3ea9675
--- /dev/null
+++ b/bridge-react/src/react/quota.ts
@@ -0,0 +1,46 @@
+/**
+ * One metric's quota against the plan, for your own UI. The numbers are auth-core's quota store: one read when first
+ * asked for, then again when Bridge says a quota or the plan changed.
+ *
+ * ```tsx
+ * const projects = useQuota('projects');
+ * if (projects.loading) return ;
+ * if (projects.unlimited) return <>Unlimited projects>;
+ * return <>{projects.used} of {projects.limit} projects>;
+ * ```
+ *
+ * Numbers only, never a gate: whether something is allowed is a flag, and your server refuses the write.
+ */
+import { useCallback, useEffect, useSyncExternalStore } from 'react';
+import { LOADING_QUOTA, askForQuota, noteSession, readQuotaState, type QuotaState } from '../core/quota.js';
+import { useBridge, useSession } from './hooks.js';
+
+const noop = () => undefined;
+
+/**
+ * Live numbers for one metric. `loading` is true until Bridge has answered, and the numbers are `null` meanwhile,
+ * never a made-up 0.
+ *
+ * @param metric The metric's key, such as `projects`.
+ */
+export function useQuota(metric: string): QuotaState {
+ const client = useBridge();
+ const session = useSession();
+ const who = session.status === 'signed-in' ? `${session.user.id}|${session.workspace?.id ?? ''}` : null;
+ // Before the read below: a person or workspace that changed has another plan.
+ if (client !== null) noteSession(client, who);
+
+ const subscribe = useCallback(
+ (onChange: () => void) => (client === null ? noop : client.quotas.subscribe((m) => (m === metric ? onChange() : undefined))),
+ [client, metric],
+ );
+ const read = useCallback(() => (client === null ? LOADING_QUOTA : readQuotaState(client, metric)), [client, metric]);
+ const state = useSyncExternalStore(subscribe, read, read);
+
+ // The first read, and the first after a person signs in: the store cannot read for nobody.
+ useEffect(() => {
+ if (client !== null) askForQuota(client, metric);
+ }, [client, metric, who]);
+
+ return state;
+}
diff --git a/bridge-react/src/styles.css b/bridge-react/src/styles.css
index 8f85813..8fad302 100644
--- a/bridge-react/src/styles.css
+++ b/bridge-react/src/styles.css
@@ -1755,6 +1755,62 @@
color: var(--bridge-foreground, #111827);
}
+ /* A locked workspace in hard mode: a blocking screen over the page. */
+ .bridge-billing-lockscreen {
+ position: fixed;
+ inset: 0;
+ z-index: 9999;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 1rem;
+ background: var(--bridge-paywall-bg, rgba(15, 23, 42, 0.72));
+ backdrop-filter: blur(2px);
+ }
+
+ .bbl-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+ max-width: 28rem;
+ width: 100%;
+ padding: 1.5rem;
+ border-radius: 0.75rem;
+ background: var(--bridge-foreground, #111827);
+ color: var(--bridge-bg, #ffffff);
+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.35);
+ text-align: center;
+ }
+
+ .bbl-title {
+ font-size: calc(1.125 * var(--bridge-text-base, 1rem));
+ font-weight: var(--bridge-font-weight-heading, 600);
+ }
+
+ .bbl-body {
+ font-size: calc(0.9375 * var(--bridge-text-base, 1rem));
+ opacity: 0.85;
+ }
+
+ .bbl-cta {
+ align-self: center;
+ margin-top: 0.5rem;
+ padding: 0.625rem 1.25rem;
+ border-radius: 0.5rem;
+ border: 1px solid currentColor;
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ font-weight: var(--bridge-font-weight-button, 500);
+ text-decoration: none;
+ cursor: pointer;
+ }
+
+ .bbl-cta:hover {
+ background: var(--bridge-bg, #ffffff);
+ color: var(--bridge-foreground, #111827);
+ }
+
/* ─── QuotaBanner ─────────────────────────────────────────────────────── */
[data-bridge-quota-banner] {
@@ -1769,12 +1825,12 @@
transition: opacity 280ms ease, transform 320ms ease;
}
- [data-bridge-quota-banner][data-state="near"] {
+ [data-bridge-quota-banner][data-severity="warn"] {
background: var(--bridge-alert-warning-bg, #fffbeb);
color: var(--bridge-alert-warning-fg, #92400e);
}
- [data-bridge-quota-banner][data-state="over"] {
+ [data-bridge-quota-banner][data-severity="critical"] {
background: var(--bridge-alert-error-bg, #fef2f2);
color: var(--bridge-alert-error-fg, #991b1b);
}
diff --git a/demo/src/pages/Tickets.tsx b/demo/src/pages/Tickets.tsx
index fc221b8..c99b555 100644
--- a/demo/src/pages/Tickets.tsx
+++ b/demo/src/pages/Tickets.tsx
@@ -1,10 +1,15 @@
// Calling the app's own API with the person's token, and what the browser does when the API refuses at a plan limit.
-import { bridgeFetch, FeatureFlag, QuotaBanner } from '@nebulr-group/bridge-react';
+import { bridgeFetch, Entitled, FeatureFlag, QuotaBanner, QuotaGate } from '@nebulr-group/bridge-react';
import { useState } from 'react';
export function Tickets() {
const [result, setResult] = useState(null);
+ async function createTicket() {
+ const response = await bridgeFetch('/api/tickets', { method: 'POST' });
+ setResult(response.ok ? 'Ticket created.' : `Refused: ${response.status}`);
+ }
+
async function exportTickets() {
// The API answers 402 at the plan's limit; bridgeFetch opens the upgrade dialog.
const response = await bridgeFetch('/api/exports', { method: 'POST' });
@@ -16,6 +21,11 @@ export function Tickets() {
Tickets
+
+ void createTicket()}>
+ New ticket
+
+
void exportTickets()}>
Export
@@ -26,6 +36,9 @@ export function Tickets() {
Export as PDF
+ Reports are not on your plan.
}>
+ Reports are on your plan.
+
>
);
}
diff --git a/demo/vite.config.ts b/demo/vite.config.ts
index 1fad22b..55ba357 100644
--- a/demo/vite.config.ts
+++ b/demo/vite.config.ts
@@ -6,7 +6,8 @@ const plugin = (path: string) => fileURLToPath(new URL(`../bridge-react/src/${pa
/**
* A stand-in for the app's own API, so the demo needs no server: it refuses
- * an export at a plan limit with the 402 a server plugin answers at the cap.
+ * an export at a plan limit with the 402 a server plugin answers at the cap,
+ * and creates a ticket.
* The browser's side (the upgrade dialog) is what the demo shows.
*/
function demoApi(): Plugin {
@@ -14,6 +15,11 @@ function demoApi(): Plugin {
return {
name: 'demo-api',
configureServer(server) {
+ server.middlewares.use('/api/tickets', (request, response) => {
+ response.statusCode = request.method === 'POST' ? 201 : 405;
+ response.setHeader('content-type', 'application/json');
+ response.end('{}');
+ });
server.middlewares.use('/api/exports', (request, response) => {
response.statusCode = request.method === 'POST' ? 402 : 405;
response.setHeader('content-type', 'application/json');
diff --git a/e2e/harness/fake-issuer.ts b/e2e/harness/fake-issuer.ts
index 2ae89fc..1408b2a 100644
--- a/e2e/harness/fake-issuer.ts
+++ b/e2e/harness/fake-issuer.ts
@@ -31,6 +31,7 @@ function fresh(): FakeIssuer {
made.setFlags(STANDARD_FLAGS);
made.setPlans(PLANS);
made.setFacts({ plan: { key: 'free', name: 'Free' }, status: 'active', access: 'ok', limits: { tickets: 3 }, usage: { tickets: 1 } });
+ made.setQuota('tickets', { used: 1, limit: 3, remaining: 2, policy: 'hard' });
return made;
}
@@ -77,6 +78,9 @@ async function control(path: string, request: Request, url: URL): Promise, visitor?: Record): Promise;
setFacts(facts: Record): Promise;
+ /** What the quota read answers for a metric (`null`: no limit on it). The local issuer only. */
+ setQuota(metric: string, read: Record | null): Promise;
/** Ends every session of a person, as Bridge does after a password reset or a removal. */
endSessions(email: string): Promise;
}
@@ -71,6 +73,9 @@ class LocalIssuer implements TestIssuer {
async setFacts(facts: Record) {
await this.call('/facts', facts);
}
+ async setQuota(metric: string, read: Record | null) {
+ await this.call('/quota', { metric, read });
+ }
async endSessions(email: string) {
await this.call('/end-sessions', { email });
}
@@ -101,6 +106,9 @@ class RealIssuer implements TestIssuer {
async setFacts(): Promise {
this.missing('set billing facts');
}
+ async setQuota(): Promise {
+ this.missing('set a quota');
+ }
async endSessions(): Promise {
this.missing('end sessions');
}
diff --git a/e2e/playwright/tests/billing/limits.spec.ts b/e2e/playwright/tests/billing/limits.spec.ts
new file mode 100644
index 0000000..05a1af9
--- /dev/null
+++ b/e2e/playwright/tests/billing/limits.spec.ts
@@ -0,0 +1,38 @@
+import { expect, signIn, test } from '../../support/fixtures';
+
+test.describe('plan limits and plan features', () => {
+ test.beforeEach(({ issuer }) => {
+ test.skip(issuer.kind === 'real', 'The quota read is the plan\'s own on a real server: the local issuer sets the numbers.');
+ });
+
+ test('a metric at its hard limit shows the banner and disables the action, and room left does neither', async ({ page, issuer, person }) => {
+ await signIn(page, person.email);
+ await page.goto('/tickets');
+ await expect(page.getByRole('heading', { name: 'Tickets' })).toBeVisible();
+ await expect(page.locator('[data-bridge-quota-banner]')).toHaveCount(0);
+ await expect(page.getByTestId('new-ticket')).toBeEnabled();
+
+ await issuer.setQuota('tickets', { used: 3, limit: 3, remaining: 0, policy: 'hard' });
+ await page.reload();
+ await expect(page.locator('[data-bridge-quota-banner]')).toHaveAttribute('data-state', 'reached');
+ await expect(page.locator('[data-bridge-quota-gate]')).toHaveAttribute('data-state', 'at-limit');
+ await expect(page.getByTestId('new-ticket')).toBeDisabled();
+ await expect(page.locator('[data-bridge-quota-gate-limit] a')).toHaveAttribute('href', '/subscription');
+ });
+
+ test('a plan feature that is on shows its content, one that is off shows the fallback', async ({ page, issuer, person }) => {
+ await issuer.setFlags({ 'bridge:billing.entitlement.reports': false });
+ await signIn(page, person.email);
+ await page.goto('/tickets');
+ await expect(page.getByTestId('reports-not-entitled')).toBeVisible();
+ await issuer.setFlags({ 'bridge:billing.entitlement.reports': true });
+ await page.reload();
+ await expect(page.getByTestId('reports-entitled')).toBeVisible();
+ });
+
+ test('a workspace locked for payment shows the lock', async ({ page, issuer, person }) => {
+ await issuer.setFacts({ status: 'past_due', access: 'blocked', locked: true });
+ await signIn(page, person.email);
+ await expect(page.locator('[data-bridge-billing-notice][data-kind="blocked"]')).toBeVisible();
+ });
+});
diff --git a/learning/billing/billing.md b/learning/billing/billing.md
index 70b86c5..6410ecd 100644
--- a/learning/billing/billing.md
+++ b/learning/billing/billing.md
@@ -29,11 +29,35 @@ Choosing a paid plan without a card on file sends the person to Stripe's checkou
| `PlanPicker` | The plans on offer, with prices per interval and the current plan marked. Choosing needs `bridge-billing-manage`; others see who to ask |
| `BillingPortalButton` | Opens Stripe's billing portal. Shown only with `bridge-billing-manage` |
| `SubscriptionStatus` | The plan's name and its status |
-| `BillingNotice` | The one notice worth showing now: blocked, payment due, needs a plan, trial ending, ending, or a change waiting |
-| `QuotaBanner` | A limit nearing or reached, for one metric (` `) |
+| `BillingNotice` | The one notice worth showing now: blocked, payment due, needs a plan, trial ending, ending, or a change waiting. `mode="hard"` covers the page while the workspace is locked for payment |
+| `QuotaBanner` | A limit nearing (from 80%) or reached, for one metric (` `); a metered limit shows its overage |
+| `QuotaGate` | Disables the actions inside once a metric is at its hard limit, with an upgrade line beside them |
+| `Entitled` | Shows its content when the plan has a feature, a fallback when it does not |
| `CheckoutNotice` | The outcome of a checkout the person came back from |
-`useBilling()`, `usePlans()` and `useUsage()` are the hooks behind them, as `{ value, loading, error, refresh }`. `useQuota('tickets')` gives `{ used, limit, ratio, state }`, or `null`, for your own display.
+`useBilling()`, `usePlans()` and `useUsage()` are the hooks behind them, as `{ value, loading, error, refresh }`.
+
+### Your own display
+
+`useQuota('tickets')` gives one metric's numbers, live: they move by themselves when usage or the plan changes.
+
+```tsx
+const tickets = useQuota('tickets');
+if (tickets.loading) return null;
+return tickets.unlimited ? <>Unlimited> : <>{tickets.used} of {tickets.limit}>;
+```
+
+It has `loading`, `unlimited`, `used`, `limit`, `remaining`, `warningLevel` (`approaching` from 80%, `critical` from 95%), `kind` (`counter` or `gauge`), the whole `snapshot` (with `policy`, `hard` or `metered`), and `ratio` and `state` (`ok`, `near` or `over`). There is never a made-up 0: while loading the numbers are `null`.
+
+`useEntitlements().can('analytics')` tells whether the plan has a feature; it reads the flag `bridge:billing.entitlement.analytics`, is `false` until Bridge has answered, and `ready` tells those two apart. `` is the markup form. To gate a page or a button with a reason, use a flag with that rule and ``.
+
+```tsx
+ <>{quota.used} of {quota.limit} used. Upgrade >}>
+ New ticket
+
+```
+
+The gate and the banner only decorate: your server refuses the write. They never disable on "not known yet", for a metric without a limit, or for a metered limit, which bills the overage instead of blocking.
## Plan limits
@@ -45,10 +69,16 @@ import { bridgeFetch } from '@nebulr-group/bridge-react';
const response = await bridgeFetch('/api/tickets', { method: 'POST' });
```
-The dialog opens for a 402 that says a limit was reached (`{ code: 'QUOTA_EXCEEDED', metric, used, limit }`, or problem details of type `quota-exceeded`) or a plan feature is missing (`plan-required`, with `entitlement`). Any other 402, such as a declined card, leaves it shut, and so does a 402 that came through a redirect or from a host other than your page, your `tokenOrigins` or Bridge. A link in the refusal is followed only when it is a path on your site. Open it yourself with `openUpgrade({ kind: 'feature', entitlement })`, replace it with `billing: { upgradeDialog: MyDialog }` (a component taking `request`, `upgradeHref`, `canUpgrade` and `onClose`), or turn it off with `false`.
+The dialog opens for a 402 that says a limit was reached (`{ code: 'QUOTA_EXCEEDED', metric, used, limit }`, or problem details of type `quota-exceeded`) or a plan feature is missing (`plan-required`, with `entitlement`). Any other 402, such as a declined card, leaves it shut, and so does a 402 that came through a redirect or from a host other than your page, your `tokenOrigins` or Bridge. A link in the refusal is followed only when it is a path on your site. Run your own code for each refused limit with `onBridgeQuotaExceeded((refusal) => …)`. Open the dialog yourself with `openUpgrade({ kind: 'feature', entitlement })`, replace it with `billing: { upgradeDialog: MyDialog }` (a component taking `request`, `upgradeHref`, `canUpgrade` and `onClose`), or turn it off with `false`.
`bridgeFetch` adds the person's token and refreshes it once after a 401. It sends the token only to your page's own origin, Bridge, and the origins you list:
```ts
const config: BridgeConfig = { issuer, tokenOrigins: ['https://api.example.com'] };
```
+
+## A workspace locked for payment
+
+When the payment provider has given up collecting, the workspace is locked: people can read, nothing can be changed. ` ` shows it to every person, not only the owner, and ` ` covers the page with a blocking screen that the owner can leave through the billing page. `useBillingGate()` is the lock, `{ locked, severity, noticeState, recoveryUrl }`, and `useBillingLocked()` is its yes or no. It is read when the page starts and again when Bridge says billing access changed. When your API refuses a change with the lock's 402 (`BILLING_GATE_ENGAGED`) through `bridgeFetch`, the lock shows at once and the upgrade dialog stays shut: a locked workspace needs to pay, not to pick a plan.
+
+To run code when a metric's numbers change, use the client: `getBridge().handle({ 'quota.updated': (update) => … })` runs once for each metric whose numbers changed, and returns how to stop.
diff --git a/package.json b/package.json
index adb1628..6119e04 100644
--- a/package.json
+++ b/package.json
@@ -23,6 +23,6 @@
"@types/node": "^25.2.2"
},
"dependencies": {
- "@nebulr-group/bridge-auth-core": "1.0.0-alpha.8"
+ "@nebulr-group/bridge-auth-core": "1.0.0-alpha.11"
}
}