@molecule/app-billing-react 1.0.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,115 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,24 @@
1
+ /** Props for `<BillingStatusBadge />`. */
2
+ export interface BillingStatusBadgeProps {
3
+ /**
4
+ * Optional callback invoked after a successful cancel. Most apps will
5
+ * navigate the user back to settings or refresh the page from here.
6
+ */
7
+ onCanceled?: () => void;
8
+ /** Optional className applied to the outer wrapper. */
9
+ className?: string;
10
+ /**
11
+ * Whether to render the cancel-subscription button when the user is
12
+ * on a paid tier. Defaults to `true`.
13
+ */
14
+ showCancel?: boolean;
15
+ }
16
+ /**
17
+ * Compact billing-status display for the user's account/settings page.
18
+ * Shows the current tier name and offers a cancel button on paid tiers.
19
+ *
20
+ * @param props - Component props.
21
+ * @returns The rendered status badge.
22
+ */
23
+ export declare function BillingStatusBadge(props: BillingStatusBadgeProps): React.ReactElement | null;
24
+ //# sourceMappingURL=BillingStatusBadge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BillingStatusBadge.d.ts","sourceRoot":"","sources":["../src/BillingStatusBadge.tsx"],"names":[],"mappings":"AAKA,0CAA0C;AAC1C,MAAM,WAAW,uBAAuB;IACtC;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,IAAI,CAAA;IAEvB,uDAAuD;IACvD,SAAS,CAAC,EAAE,MAAM,CAAA;IAElB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;CACrB;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,uBAAuB,GAAG,KAAK,CAAC,YAAY,GAAG,IAAI,CAuD5F"}
@@ -0,0 +1,33 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useTranslation } from '@molecule/app-react';
3
+ import { getClassMap } from '@molecule/app-ui';
4
+ import { useBillingStatus, useCancelSubscription } from './hooks.js';
5
+ /**
6
+ * Compact billing-status display for the user's account/settings page.
7
+ * Shows the current tier name and offers a cancel button on paid tiers.
8
+ *
9
+ * @param props - Component props.
10
+ * @returns The rendered status badge.
11
+ */
12
+ export function BillingStatusBadge(props) {
13
+ const { onCanceled, className, showCancel = true } = props;
14
+ const cm = getClassMap();
15
+ const { t } = useTranslation();
16
+ const { data: status, loading, error } = useBillingStatus();
17
+ const { cancel, loading: canceling, error: cancelError } = useCancelSubscription();
18
+ if (loading) {
19
+ return (_jsx("span", { className: className, "data-mol-id": "billing-status-loading", children: t('billing.status.loading', undefined, { defaultValue: 'Loading…' }) }));
20
+ }
21
+ if (error || !status) {
22
+ return null;
23
+ }
24
+ const isFree = status.isFree;
25
+ const handleCancel = async () => {
26
+ const result = await cancel();
27
+ if (result?.canceled)
28
+ onCanceled?.();
29
+ };
30
+ return (_jsxs("div", { className: className, "data-mol-id": "billing-status", children: [_jsx("span", { className: cm.cardDescription, children: t('billing.status.currentPlan', { tierName: status.name }, { defaultValue: 'Current plan: {{tierName}}' }) }), showCancel && !isFree && (_jsx("button", { type: "button", className: cm.button({ variant: 'outline', size: 'sm' }), disabled: canceling, onClick: handleCancel, "data-mol-id": "billing-cancel-button", children: t('billing.status.cancelCta', undefined, { defaultValue: 'Cancel subscription' }) })), cancelError && (_jsx("p", { className: cm.formError, role: "alert", children: t('billing.status.cancelError', undefined, {
31
+ defaultValue: 'Could not cancel. Please try again.',
32
+ }) }))] }));
33
+ }
@@ -0,0 +1,114 @@
1
+ import type { ReactNode } from 'react';
2
+ import type { PricingTierPrice } from './types.js';
3
+ /**
4
+ * Container for a tier's feature list. Apps use this in their
5
+ * `renderLimits` prop with `<LimitsItem>` children to get the polished
6
+ * stacked-checklist layout (check icon prefix, muted/primary colors,
7
+ * spacing) that matches the rest of `<PricingPage />`.
8
+ *
9
+ * @example
10
+ * ```tsx
11
+ * <PricingPage
12
+ * renderLimits={(limits) => (
13
+ * <LimitsList>
14
+ * <LimitsItem>{t('pricing.blocks', { count: limits.maxBlocks })}</LimitsItem>
15
+ * <LimitsItem included={limits.canExport}>{t('pricing.dataExport')}</LimitsItem>
16
+ * </LimitsList>
17
+ * )}
18
+ * />
19
+ * ```
20
+ */
21
+ export declare function LimitsList({ children }: {
22
+ children: ReactNode;
23
+ }): React.ReactElement;
24
+ /** Props for `<LimitsItem>`. */
25
+ export interface LimitsItemProps {
26
+ /** Row content (typically a translated label + number). */
27
+ children: ReactNode;
28
+ /**
29
+ * Whether this feature is included in the tier. When `false`, the row
30
+ * renders with a muted line-through and a dash glyph instead of the
31
+ * check icon. Defaults to `true`.
32
+ */
33
+ included?: boolean;
34
+ }
35
+ /**
36
+ * Single row in a tier's feature list — a check (or em-dash) icon
37
+ * followed by the row label. Use inside `<LimitsList>`.
38
+ */
39
+ export declare function LimitsItem({ children, included }: LimitsItemProps): React.ReactElement;
40
+ /** Props for `<PricingPage />`. */
41
+ export interface PricingPageProps<TLimits = unknown> {
42
+ /**
43
+ * Optional billing-period selector. Defaults to `'month'`. Pass `'year'`
44
+ * to render the yearly column. The component falls back to whatever the
45
+ * tier provides when the requested period is missing.
46
+ */
47
+ period?: PricingTierPrice['period'];
48
+ /**
49
+ * Optional render function for the tier-specific limits column. Defaults
50
+ * to a stacked checklist rendering numeric / boolean values with a green
51
+ * check glyph. Apps with rich limit shapes can supply a custom renderer.
52
+ */
53
+ renderLimits?: (limits: TLimits) => React.ReactNode;
54
+ /**
55
+ * Optional override for the page-level heading translation key.
56
+ * Defaults to `'billing.pricing.heading'`.
57
+ */
58
+ headingKey?: string;
59
+ /** Optional English fallback for the heading. Defaults to `'Choose your plan'`. */
60
+ headingDefault?: string;
61
+ /**
62
+ * Optional sub-heading shown under the page heading. Pass `null` to
63
+ * suppress. Defaults to a translated "Pick the plan that fits…" line.
64
+ */
65
+ subheadingKey?: string | null;
66
+ /** English fallback for the sub-heading. */
67
+ subheadingDefault?: string;
68
+ /**
69
+ * Optional className applied to the outer wrapper, useful when embedding
70
+ * the page in an existing layout.
71
+ */
72
+ className?: string;
73
+ /**
74
+ * Path the browser is sent to when an anonymous visitor clicks a paid
75
+ * tier's upgrade CTA. Defaults to `/login`. Set to `null` to disable
76
+ * the redirect (e.g. when the app handles the auth gate at a higher
77
+ * level via routing guards).
78
+ */
79
+ unauthenticatedRedirect?: string | null;
80
+ /**
81
+ * Optional tier key to highlight as "most popular" — receives the
82
+ * elevated card variant, a popular-badge in the header, and a
83
+ * primary-tone CTA. When omitted (default), the highest-priced tier
84
+ * with a real stripePriceId for the selected period is auto-selected.
85
+ * Pass `null` to disable highlighting entirely.
86
+ */
87
+ popularTierKey?: string | null;
88
+ /**
89
+ * Optional font-family stack applied inline to the page heading,
90
+ * tier names, and hero price. Defaults to a system-serif cascade
91
+ * (Georgia, Iowan Old Style, …) matching the flagship-app
92
+ * convention. Pass `null` to disable inline font and inherit from
93
+ * the theme.
94
+ */
95
+ headlineFontFamily?: string | null;
96
+ }
97
+ /**
98
+ * Renders the public pricing page. Fetches `/api/billing/tiers` on mount
99
+ * and lays out one card per tier with the price for the selected period
100
+ * and a CTA that starts a Stripe Checkout session via
101
+ * `/api/billing/checkout`. Tiers without a Stripe priceId (e.g. the free
102
+ * tier or local-dev) render a disabled CTA so users still see the row.
103
+ *
104
+ * The highest-priced paid tier is highlighted as "most popular" by
105
+ * default — the card uses the elevated variant, the header carries a
106
+ * star badge, and its CTA renders in the primary color. Apps that want
107
+ * a different tier in the spotlight can pass `popularTierKey` (or
108
+ * `null` to suppress).
109
+ *
110
+ * @param props - Component props (see `PricingPageProps`).
111
+ * @returns The rendered pricing page.
112
+ */
113
+ export declare function PricingPage<TLimits = unknown>(props: PricingPageProps<TLimits>): React.ReactElement;
114
+ //# sourceMappingURL=PricingPage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PricingPage.d.ts","sourceRoot":"","sources":["../src/PricingPage.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AAOtC,OAAO,KAAK,EAAoB,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAEpE;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,UAAU,CAAC,EAAE,QAAQ,EAAE,EAAE;IAAE,QAAQ,EAAE,SAAS,CAAA;CAAE,GAAG,KAAK,CAAC,YAAY,CAOpF;AAED,gCAAgC;AAChC,MAAM,WAAW,eAAe;IAC9B,2DAA2D;IAC3D,QAAQ,EAAE,SAAS,CAAA;IACnB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,EAAE,QAAQ,EAAE,QAAe,EAAE,EAAE,eAAe,GAAG,KAAK,CAAC,YAAY,CAmB7F;AAwBD,mCAAmC;AACnC,MAAM,WAAW,gBAAgB,CAAC,OAAO,GAAG,OAAO;IACjD;;;;OAIG;IACH,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,CAAA;IAEnC;;;;OAIG;IACH,YAAY,CAAC,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,KAAK,CAAC,SAAS,CAAA;IAEnD;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;IAEnB,mFAAmF;IACnF,cAAc,CAAC,EAAE,MAAM,CAAA;IAEvB;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC7B,4CAA4C;IAC5C,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAE1B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;IAElB;;;;;OAKG;IACH,uBAAuB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAEvC;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAE9B;;;;;;OAMG;IACH,kBAAkB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CACnC;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,WAAW,CAAC,OAAO,GAAG,OAAO,EAC3C,KAAK,EAAE,gBAAgB,CAAC,OAAO,CAAC,GAC/B,KAAK,CAAC,YAAY,CAoJpB"}
@@ -0,0 +1,305 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useAuth, useTranslation } from '@molecule/app-react';
3
+ import { getClassMap } from '@molecule/app-ui';
4
+ import { Icon } from '@molecule/app-ui-react';
5
+ import { usePricingTiers, useStartCheckout } from './hooks.js';
6
+ /**
7
+ * Container for a tier's feature list. Apps use this in their
8
+ * `renderLimits` prop with `<LimitsItem>` children to get the polished
9
+ * stacked-checklist layout (check icon prefix, muted/primary colors,
10
+ * spacing) that matches the rest of `<PricingPage />`.
11
+ *
12
+ * @example
13
+ * ```tsx
14
+ * <PricingPage
15
+ * renderLimits={(limits) => (
16
+ * <LimitsList>
17
+ * <LimitsItem>{t('pricing.blocks', { count: limits.maxBlocks })}</LimitsItem>
18
+ * <LimitsItem included={limits.canExport}>{t('pricing.dataExport')}</LimitsItem>
19
+ * </LimitsList>
20
+ * )}
21
+ * />
22
+ * ```
23
+ */
24
+ export function LimitsList({ children }) {
25
+ const cm = getClassMap();
26
+ return (_jsx("ul", { className: cm.stack(3), "data-mol-id": "pricing-limits-list", children: children }));
27
+ }
28
+ /**
29
+ * Single row in a tier's feature list — a check (or em-dash) icon
30
+ * followed by the row label. Use inside `<LimitsList>`.
31
+ */
32
+ export function LimitsItem({ children, included = true }) {
33
+ const cm = getClassMap();
34
+ return (_jsxs("li", { className: cm.cn(cm.flex({ direction: 'row', align: 'start', gap: 'sm' }), cm.textSize('sm'), !included && cm.textMuted), children: [_jsx(Icon, { name: included ? 'check-circle' : 'minus', size: 18, "aria-hidden": "true", className: included ? cm.textPrimary : cm.textSubtle }), _jsx("span", { children: children })] }));
35
+ }
36
+ /**
37
+ * Default "anonymous → routes to" path used when a logged-out visitor
38
+ * clicks an upgrade CTA. Apps can override via the `unauthenticatedRedirect`
39
+ * prop. `/login` is the convention across flagship templates.
40
+ */
41
+ const DEFAULT_UNAUTHENTICATED_REDIRECT = '/login';
42
+ /**
43
+ * Headline font is sourced from the app's theme via the
44
+ * `--font-headline` CSS variable. Apps that want a serif/display
45
+ * treatment set this variable in their `theme.css`. Apps that don't
46
+ * set it inherit the body font (no special headline treatment), which
47
+ * is the safe default for a generic shared component — we never bake
48
+ * a specific font family into the shared package.
49
+ *
50
+ * The CSS variable fallback chain is intentionally just `inherit` so
51
+ * the headline picks up whatever the surrounding context uses; apps
52
+ * that want a custom stack pass `headlineFontFamily` to override
53
+ * either with a literal string or another `var(--something)` value.
54
+ */
55
+ const DEFAULT_HEADLINE_FONT = 'var(--font-headline, inherit)';
56
+ /**
57
+ * Renders the public pricing page. Fetches `/api/billing/tiers` on mount
58
+ * and lays out one card per tier with the price for the selected period
59
+ * and a CTA that starts a Stripe Checkout session via
60
+ * `/api/billing/checkout`. Tiers without a Stripe priceId (e.g. the free
61
+ * tier or local-dev) render a disabled CTA so users still see the row.
62
+ *
63
+ * The highest-priced paid tier is highlighted as "most popular" by
64
+ * default — the card uses the elevated variant, the header carries a
65
+ * star badge, and its CTA renders in the primary color. Apps that want
66
+ * a different tier in the spotlight can pass `popularTierKey` (or
67
+ * `null` to suppress).
68
+ *
69
+ * @param props - Component props (see `PricingPageProps`).
70
+ * @returns The rendered pricing page.
71
+ */
72
+ export function PricingPage(props) {
73
+ const { period = 'month', renderLimits, headingKey = 'billing.pricing.heading', headingDefault = 'Choose your plan', subheadingKey = 'billing.pricing.subheading', subheadingDefault = 'Pick the plan that fits how you work. Upgrade or downgrade any time.', className, unauthenticatedRedirect = DEFAULT_UNAUTHENTICATED_REDIRECT, popularTierKey, headlineFontFamily = DEFAULT_HEADLINE_FONT, } = props;
74
+ const headlineStyle = headlineFontFamily === null ? undefined : { fontFamily: headlineFontFamily };
75
+ const cm = getClassMap();
76
+ const { t } = useTranslation();
77
+ const auth = useAuth();
78
+ const { data, loading, error } = usePricingTiers();
79
+ const { start, loading: starting, error: startError } = useStartCheckout();
80
+ if (loading) {
81
+ return (_jsx("section", { className: cm.cn(cm.maxW('xl'), cm.mxAuto, cm.textCenter, cm.sp('py', 16), className), "data-mol-id": "pricing-page", children: _jsx("p", { className: cm.textMuted, children: t('billing.pricing.loading', undefined, { defaultValue: 'Loading plans…' }) }) }));
82
+ }
83
+ if (error || !data) {
84
+ return (_jsx("section", { className: cm.cn(cm.maxW('xl'), cm.mxAuto, cm.textCenter, cm.sp('py', 16), className), "data-mol-id": "pricing-page", children: _jsx("p", { className: cm.formError, children: t('billing.pricing.error', undefined, {
85
+ defaultValue: 'Could not load pricing. Try again later.',
86
+ }) }) }));
87
+ }
88
+ const rawTiers = data.data;
89
+ // Default-pick the popular tier: highest-priced paid tier that has a
90
+ // real Stripe price id for the active period. Honors `popularTierKey`
91
+ // override when set (string = use that key; null = disable highlight).
92
+ const resolvedPopularKey = popularTierKey === null ? null : (popularTierKey ?? autoSelectPopular(rawTiers, period));
93
+ // Move the popular tier to the visual center of the row. We keep the
94
+ // server's order otherwise — only the highlighted tier shifts. For odd
95
+ // tier counts this means index `Math.floor(N/2)`; for 2 tiers we leave
96
+ // the popular one second so it still flanks the free tier on the right.
97
+ const tiers = centerPopularTier(rawTiers, resolvedPopularKey);
98
+ const handleUpgrade = async (priceId) => {
99
+ if (!priceId)
100
+ return;
101
+ // Always fire the POST so the API is the source of truth for auth and
102
+ // entitlement gating. Short-circuiting on `auth.isAuthenticated` would
103
+ // produce a "silent button" for anonymous visitors (no network activity,
104
+ // no observable failure) and bypass the API's 401 contract that e2e
105
+ // suites rely on. Redirect anonymous visitors only AFTER the POST
106
+ // resolves (or fails), so the request is always observable.
107
+ const response = await start(priceId);
108
+ if (!response) {
109
+ if (!auth.isAuthenticated && unauthenticatedRedirect && typeof window !== 'undefined') {
110
+ window.location.assign(unauthenticatedRedirect);
111
+ }
112
+ return;
113
+ }
114
+ if (response.checkoutUrl) {
115
+ window.location.assign(response.checkoutUrl);
116
+ }
117
+ else if (response.updated) {
118
+ window.location.reload();
119
+ }
120
+ };
121
+ return (_jsxs("section", { className: cm.cn(cm.maxW('6xl'), cm.mxAuto, cm.sp('px', 6), cm.sp('py', 12), className), "data-mol-id": "pricing-page", children: [_jsxs("header", { className: cm.cn(cm.textCenter, cm.sp('mb', 10)), children: [_jsx("h1", { className: cm.cn(cm.textSize('4xl'), cm.fontWeight('bold'), cm.sp('mb', 3)), style: headlineStyle, "data-mol-id": "pricing-page-heading", children: t(headingKey, undefined, { defaultValue: headingDefault }) }), subheadingKey !== null && (_jsx("p", { className: cm.cn(cm.textSize('lg'), cm.textMuted, cm.maxW('2xl'), cm.mxAuto), "data-mol-id": "pricing-page-subheading", children: t(subheadingKey, undefined, { defaultValue: subheadingDefault }) }))] }), _jsx("div", { className: cm.flex({
122
+ direction: 'row',
123
+ wrap: 'wrap',
124
+ gap: 'lg',
125
+ justify: 'center',
126
+ align: 'stretch',
127
+ }), children: tiers.map((tier) => (_jsx(TierCard, { tier: tier, period: period, cm: cm, t: t, renderLimits: renderLimits, onUpgrade: handleUpgrade, starting: starting, popular: tier.key === resolvedPopularKey, headlineStyle: headlineStyle }, tier.key))) }), startError && (_jsx("p", { className: cm.cn(cm.formError, cm.sp('mt', 6), cm.textCenter), role: "alert", children: t('billing.pricing.checkoutError', undefined, {
128
+ defaultValue: 'Could not start checkout. Please try again.',
129
+ }) })), _jsx("p", { className: cm.cn(cm.sp('mt', 10), cm.textCenter, cm.textSize('xs'), cm.textSubtle), "data-mol-id": "pricing-page-reassurance", children: t('billing.pricing.reassurance', undefined, {
130
+ defaultValue: 'Cancel anytime · No credit card required to start',
131
+ }) })] }));
132
+ }
133
+ /**
134
+ * Renders a single pricing tier card with its price, limits, and upgrade CTA.
135
+ */
136
+ function TierCard({ tier, period, cm, t, renderLimits, onUpgrade, starting, popular, headlineStyle, }) {
137
+ const price = tier.prices.find((p) => p.period === period) ?? tier.prices[0];
138
+ const periodLabel = price?.period
139
+ ? t(`billing.pricing.period.${price.period}`, undefined, {
140
+ defaultValue: price.period === 'year' ? 'per year' : 'per month',
141
+ })
142
+ : '';
143
+ void periodLabel;
144
+ return (_jsx("div", {
145
+ // Outer wrapper keeps the popular tier physically larger (taller
146
+ // + wider) than its neighbors. The "Most popular" tag sits
147
+ // INSIDE the card at the top-right, matching the Stitch
148
+ // reference — not floating above the top edge.
149
+ style: {
150
+ position: 'relative',
151
+ width: popular ? '24rem' : '19rem',
152
+ marginTop: popular ? '-1.5rem' : 0,
153
+ marginBottom: popular ? '-1.5rem' : 0,
154
+ }, children: _jsxs("article", { className: cm.cn(
155
+ // `elevated` removes the default 1px all-sides border so the
156
+ // popular tier's `borderTPrimary` accent shows ONLY as a top
157
+ // edge instead of bleeding into a 4-sided primary ring.
158
+ // Keeps the theme's `bg-surface` card color so cards still
159
+ // contrast with the page background — `bg-white` blended
160
+ // away on themes whose page bg is also white.
161
+ cm.card({ variant: 'elevated' }), cm.flex({ direction: 'col' }), popular && cm.borderTPrimary), style: {
162
+ position: 'relative',
163
+ height: '100%',
164
+ // Generous internal padding matches the Stitch reference's
165
+ // editorial whitespace — content should never crowd edges.
166
+ padding: popular ? '3rem 2.5rem 2.5rem' : '2.5rem 2rem',
167
+ // Strong soft shadow lifts cards off any same-colored page
168
+ // background. Heavier on the popular tier for emphasis.
169
+ boxShadow: popular
170
+ ? '0 24px 48px -12px rgba(15, 23, 42, 0.18), 0 8px 16px -8px rgba(15, 23, 42, 0.08)'
171
+ : '0 12px 24px -8px rgba(15, 23, 42, 0.10), 0 4px 8px -4px rgba(15, 23, 42, 0.06)',
172
+ }, "data-mol-id": `pricing-tier-${tier.key}`, "data-popular": popular ? 'true' : undefined, children: [popular && (_jsx("span", { className: cm.cn(cm.uppercase, cm.trackingWide, cm.fontWeight('bold'), cm.textSize('xs')), style: {
173
+ position: 'absolute',
174
+ top: '1rem',
175
+ right: '1rem',
176
+ backgroundColor: 'var(--color-accent-soft, #ffdf99)',
177
+ color: 'var(--color-on-accent-soft, #5a4300)',
178
+ padding: '0.25rem 0.6rem',
179
+ borderRadius: '999px',
180
+ lineHeight: 1.2,
181
+ zIndex: 1,
182
+ }, "data-mol-id": `pricing-tier-${tier.key}-popular-badge`, children: t('billing.pricing.mostPopular', undefined, { defaultValue: 'Most popular' }) })), _jsxs("header", { className: cm.cardHeader, children: [!popular && (_jsx("p", { className: cm.cn(cm.textSize('xs'), cm.textSubtle, cm.fontWeight('semibold'), cm.uppercase, cm.trackingWide, cm.sp('mb', 2)), "data-mol-id": `pricing-tier-${tier.key}-eyebrow`, children: t('billing.pricing.tierEyebrow', undefined, { defaultValue: 'Tier' }) })), _jsx("h2", { className: cm.cn(cm.textSize('2xl'), cm.italic, cm.fontWeight('semibold'), cm.sp('mb', 4)), style: headlineStyle, children: tier.name }), _jsxs("p", { children: [_jsx("span", { className: cm.cn(cm.textSize('5xl'), cm.fontWeight('bold'), popular && cm.textPrimary), style: headlineStyle, children: price?.price ?? '—' }), tier.perSeat && (_jsxs("span", { className: cm.cn(cm.textSize('sm'), cm.textMuted, cm.fontWeight('normal')), children: [' ', t('billing.pricing.perSeat', undefined, { defaultValue: 'per seat' })] }))] }), _jsxs("p", { className: cm.cn(cm.textSize('xs'), cm.textSubtle, cm.fontWeight('semibold'), cm.uppercase, cm.trackingWide, cm.sp('mt', 2)), children: [t(`billing.pricing.billed.${price?.period ?? 'month'}`, undefined, {
183
+ defaultValue: price?.period === 'year' ? 'Billed annually' : 'Billed monthly',
184
+ }), price?.savings && (_jsxs(_Fragment, { children: [' · ', _jsx("span", { className: cm.textSuccess, children: price.savings.toUpperCase() })] }))] })] }), _jsx("div", { className: cm.cn(cm.cardContent, cm.flex1), children: renderLimits ? (renderLimits(tier.limits)) : (_jsx(DefaultLimits, { limits: tier.limits, cm: cm })) }), _jsx("footer", { className: cm.cardFooter, children: _jsx("button", { type: "button", className: cm.cn(cm.button({
185
+ variant: popular ? 'solid' : 'outline',
186
+ size: 'md',
187
+ fullWidth: true,
188
+ }), popular && cm.gradientPrimary, cm.uppercase, cm.trackingWide, cm.fontWeight('semibold'), cm.textSize('sm')),
189
+ // Override the cramped default size — `cm.button({size: 'md'})`
190
+ // gives `h-[30px] px-2.5` which feels like a tag, not a CTA.
191
+ // Real button padding: ~14px vertical, ~20px horizontal.
192
+ style: {
193
+ height: 'auto',
194
+ paddingTop: '0.875rem',
195
+ paddingBottom: '0.875rem',
196
+ paddingLeft: '1.25rem',
197
+ paddingRight: '1.25rem',
198
+ }, disabled: !price?.stripePriceId || starting, onClick: () => onUpgrade(price?.stripePriceId ?? null), "data-mol-id": `pricing-cta-${tier.key}`, children: price?.stripePriceId
199
+ ? t('billing.pricing.upgradeCta', { tierName: tier.name }, { defaultValue: 'Upgrade to {{tierName}}' })
200
+ : t('billing.pricing.currentCta', undefined, { defaultValue: 'Current plan' }) }) })] }) }));
201
+ }
202
+ /**
203
+ * Default render for a tier's `limits` object — a stacked checklist
204
+ * with a green check glyph per row. Numbers and booleans render
205
+ * directly; objects/arrays JSON-stringify. Apps with richer limit
206
+ * shapes should pass their own `renderLimits` prop to `<PricingPage />`.
207
+ *
208
+ * @param props - The component props.
209
+ * @param props.limits - Tier-specific limits to render.
210
+ * @param props.cm - Active ClassMap instance.
211
+ * @returns A `<ul>` of check-prefixed limit rows.
212
+ */
213
+ function DefaultLimits({ limits, cm }) {
214
+ if (limits == null || typeof limits !== 'object') {
215
+ return _jsx(_Fragment, {});
216
+ }
217
+ const entries = Object.entries(limits);
218
+ return (_jsx("ul", { className: cm.stack(2), children: entries.map(([key, value]) => (_jsxs("li", { className: cm.cn(cm.flex({ direction: 'row', align: 'start', gap: 'sm' }), cm.textSize('sm')), children: [_jsx(Icon, { name: "check-circle", size: 16, className: cm.textSuccess, "aria-hidden": "true" }), _jsxs("span", { children: [_jsxs("span", { className: cm.textMuted, children: [humanizeKey(key), ": "] }), _jsx("span", { className: cm.fontWeight('medium'), children: formatLimitValue(value) })] })] }, key))) }));
219
+ }
220
+ /**
221
+ * Converts a camelCase or snake_case key into a human-readable label (e.g. `maxBlocks` → `Max blocks`).
222
+ */
223
+ function humanizeKey(key) {
224
+ // 'maxBlocks' → 'Max blocks'; 'canExport' → 'Can export';
225
+ // 'max_blocks' → 'Max blocks'. The PricingPage caller can always
226
+ // override with renderLimits for fully custom labels.
227
+ const spaced = key
228
+ .replace(/_/g, ' ')
229
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
230
+ .toLowerCase();
231
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
232
+ }
233
+ /**
234
+ * Formats a raw limit value (boolean, number, string, or object) into a display string.
235
+ */
236
+ function formatLimitValue(value) {
237
+ if (typeof value === 'boolean')
238
+ return value ? '✓' : '—';
239
+ if (typeof value === 'number') {
240
+ if (value >= 999_999)
241
+ return 'Unlimited';
242
+ return value.toLocaleString();
243
+ }
244
+ if (value == null)
245
+ return '—';
246
+ if (typeof value === 'string')
247
+ return value;
248
+ try {
249
+ return JSON.stringify(value);
250
+ }
251
+ catch (_error) {
252
+ // JSON.stringify can throw on circular references; String() is always safe.
253
+ return String(value);
254
+ }
255
+ }
256
+ /**
257
+ * Pick the "most popular" tier when the caller hasn't specified one:
258
+ * the highest-priced paid tier that has a real stripePriceId for the
259
+ * active period. If nothing qualifies, returns null (no highlight).
260
+ */
261
+ function autoSelectPopular(tiers, period) {
262
+ let bestKey = null;
263
+ let bestCents = -1;
264
+ for (const tier of tiers) {
265
+ const price = tier.prices.find((p) => p.period === period) ?? tier.prices[0];
266
+ if (!price?.stripePriceId)
267
+ continue;
268
+ const cents = priceToCents(price.price);
269
+ if (cents > bestCents) {
270
+ bestCents = cents;
271
+ bestKey = tier.key;
272
+ }
273
+ }
274
+ return bestKey;
275
+ }
276
+ /**
277
+ * Parses a price label string (e.g. `"$12.99/mo"`) into an integer cent value for comparison.
278
+ */
279
+ function priceToCents(label) {
280
+ if (!label)
281
+ return 0;
282
+ // Accept "$12", "$12.99/mo", "€12,99" — strip currency + suffix, parse the number.
283
+ const match = label.match(/(\d+(?:[.,]\d+)?)/);
284
+ if (!match)
285
+ return 0;
286
+ return Math.round(Number(match[1].replace(',', '.')) * 100);
287
+ }
288
+ /**
289
+ * Move the popular tier to the visual center of the row so the
290
+ * highlighted card flanks the other tiers. Returns a new array with the
291
+ * popular tier at `Math.floor(N/2)`; if the popular key isn't found, or
292
+ * is already in that position, the array is returned unchanged.
293
+ */
294
+ function centerPopularTier(tiers, popularKey) {
295
+ if (!popularKey || tiers.length < 3)
296
+ return [...tiers];
297
+ const targetIdx = Math.floor(tiers.length / 2);
298
+ const currentIdx = tiers.findIndex((t) => t.key === popularKey);
299
+ if (currentIdx === -1 || currentIdx === targetIdx)
300
+ return [...tiers];
301
+ const next = [...tiers];
302
+ const [popular] = next.splice(currentIdx, 1);
303
+ next.splice(targetIdx, 0, popular);
304
+ return next;
305
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * React hooks for the standard `/billing/*` endpoints.
3
+ *
4
+ * These hooks wrap `@molecule/app-react`'s HTTP primitives so callers get
5
+ * familiar `{ data, loading, error }` ergonomics. The endpoints they hit
6
+ * are provided server-side by `@molecule/api-entitlements` +
7
+ * `@molecule/api-payments-stripe` (see
8
+ * `mlcl/templates/apps/<app>/api/routes/billing.ts` for the routes).
9
+ *
10
+ * NOTE on URLs: flagship apps do NOT bond an HTTP client baseURL — each
11
+ * page-level caller passes the full `/api/...` path explicitly. We match
12
+ * that convention here so the hooks work in any flagship app whether or
13
+ * not it later opts into a baseURL-bonded client.
14
+ *
15
+ * @module
16
+ */
17
+ import { type UseHttpResult } from '@molecule/app-react';
18
+ import type { BillingStatus, CancelResponse, CheckoutResponse, PricingTiersResponse } from './types.js';
19
+ /**
20
+ * Fetch the public pricing data once on mount. Useful inside a
21
+ * pricing/upgrade page where the tiers are needed before render.
22
+ *
23
+ * @template TLimits - Application-specific tier limits shape.
24
+ * @returns Async-state for the pricing tiers response.
25
+ */
26
+ export declare function usePricingTiers<TLimits = unknown>(): UseHttpResult<PricingTiersResponse<TLimits>>;
27
+ /**
28
+ * Fetch the signed-in user's current subscription state once on mount.
29
+ * Returns 401 from the API when the user is not authenticated; consumers
30
+ * should treat the absence of `data` as "anonymous → free tier".
31
+ *
32
+ * @template TLimits - Application-specific tier limits shape.
33
+ * @returns Async-state for the user's billing status.
34
+ */
35
+ export declare function useBillingStatus<TLimits = unknown>(): UseHttpResult<BillingStatus<TLimits>>;
36
+ /** Async-state shape returned by `useStartCheckout` / `useCancelSubscription`. */
37
+ export interface BillingActionState<T> {
38
+ /** The most recent response from the action, or `null` before the first call. */
39
+ data: T | null;
40
+ /** True while a request is in flight. */
41
+ loading: boolean;
42
+ /** Last error thrown by the action, or `null` on success. */
43
+ error: Error | null;
44
+ }
45
+ /**
46
+ * Start a Stripe Checkout session for a given Stripe price ID. The
47
+ * returned `start(priceId)` posts to `/api/billing/checkout`; the
48
+ * response is either `{ checkoutUrl }` (for new subscribers — redirect
49
+ * the browser) or `{ updated: true }` (for existing subscribers —
50
+ * refresh the page).
51
+ *
52
+ * @returns Async-state plus a `start` function.
53
+ */
54
+ export declare function useStartCheckout(): BillingActionState<CheckoutResponse> & {
55
+ start: (priceId: string) => Promise<CheckoutResponse | null>;
56
+ };
57
+ /**
58
+ * Cancel the user's active subscription at the end of the current
59
+ * billing period. Returns the response from the bonded payment provider.
60
+ *
61
+ * @returns Async-state plus a `cancel` function.
62
+ */
63
+ export declare function useCancelSubscription(): BillingActionState<CancelResponse> & {
64
+ cancel: () => Promise<CancelResponse | null>;
65
+ };
66
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAIH,OAAO,EAAyB,KAAK,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAE/E,OAAO,KAAK,EACV,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,oBAAoB,EACrB,MAAM,YAAY,CAAA;AAEnB;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAG,OAAO,KAAK,aAAa,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAEjG;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAG,OAAO,KAAK,aAAa,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAE3F;AAED,kFAAkF;AAClF,MAAM,WAAW,kBAAkB,CAAC,CAAC;IACnC,iFAAiF;IACjF,IAAI,EAAE,CAAC,GAAG,IAAI,CAAA;IAEd,yCAAyC;IACzC,OAAO,EAAE,OAAO,CAAA;IAEhB,6DAA6D;IAC7D,KAAK,EAAE,KAAK,GAAG,IAAI,CAAA;CACpB;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,IAAI,kBAAkB,CAAC,gBAAgB,CAAC,GAAG;IACzE,KAAK,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAAA;CAC7D,CAyBA;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,IAAI,kBAAkB,CAAC,cAAc,CAAC,GAAG;IAC5E,MAAM,EAAE,MAAM,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAAA;CAC7C,CAsBA"}
package/dist/hooks.js ADDED
@@ -0,0 +1,98 @@
1
+ /**
2
+ * React hooks for the standard `/billing/*` endpoints.
3
+ *
4
+ * These hooks wrap `@molecule/app-react`'s HTTP primitives so callers get
5
+ * familiar `{ data, loading, error }` ergonomics. The endpoints they hit
6
+ * are provided server-side by `@molecule/api-entitlements` +
7
+ * `@molecule/api-payments-stripe` (see
8
+ * `mlcl/templates/apps/<app>/api/routes/billing.ts` for the routes).
9
+ *
10
+ * NOTE on URLs: flagship apps do NOT bond an HTTP client baseURL — each
11
+ * page-level caller passes the full `/api/...` path explicitly. We match
12
+ * that convention here so the hooks work in any flagship app whether or
13
+ * not it later opts into a baseURL-bonded client.
14
+ *
15
+ * @module
16
+ */
17
+ import { useCallback, useState } from 'react';
18
+ import { useGet, useHttpClient } from '@molecule/app-react';
19
+ /**
20
+ * Fetch the public pricing data once on mount. Useful inside a
21
+ * pricing/upgrade page where the tiers are needed before render.
22
+ *
23
+ * @template TLimits - Application-specific tier limits shape.
24
+ * @returns Async-state for the pricing tiers response.
25
+ */
26
+ export function usePricingTiers() {
27
+ return useGet('/api/billing/tiers', { immediate: true });
28
+ }
29
+ /**
30
+ * Fetch the signed-in user's current subscription state once on mount.
31
+ * Returns 401 from the API when the user is not authenticated; consumers
32
+ * should treat the absence of `data` as "anonymous → free tier".
33
+ *
34
+ * @template TLimits - Application-specific tier limits shape.
35
+ * @returns Async-state for the user's billing status.
36
+ */
37
+ export function useBillingStatus() {
38
+ return useGet('/api/billing/status', { immediate: true });
39
+ }
40
+ /**
41
+ * Start a Stripe Checkout session for a given Stripe price ID. The
42
+ * returned `start(priceId)` posts to `/api/billing/checkout`; the
43
+ * response is either `{ checkoutUrl }` (for new subscribers — redirect
44
+ * the browser) or `{ updated: true }` (for existing subscribers —
45
+ * refresh the page).
46
+ *
47
+ * @returns Async-state plus a `start` function.
48
+ */
49
+ export function useStartCheckout() {
50
+ const client = useHttpClient();
51
+ const [state, setState] = useState({
52
+ data: null,
53
+ loading: false,
54
+ error: null,
55
+ });
56
+ const start = useCallback(async (priceId) => {
57
+ setState({ data: null, loading: true, error: null });
58
+ try {
59
+ const response = await client.post('/api/billing/checkout', { priceId });
60
+ setState({ data: response.data, loading: false, error: null });
61
+ return response.data;
62
+ }
63
+ catch (err) {
64
+ const error = err instanceof Error ? err : new Error(String(err));
65
+ setState({ data: null, loading: false, error });
66
+ return null;
67
+ }
68
+ }, [client]);
69
+ return { ...state, start };
70
+ }
71
+ /**
72
+ * Cancel the user's active subscription at the end of the current
73
+ * billing period. Returns the response from the bonded payment provider.
74
+ *
75
+ * @returns Async-state plus a `cancel` function.
76
+ */
77
+ export function useCancelSubscription() {
78
+ const client = useHttpClient();
79
+ const [state, setState] = useState({
80
+ data: null,
81
+ loading: false,
82
+ error: null,
83
+ });
84
+ const cancel = useCallback(async () => {
85
+ setState({ data: null, loading: true, error: null });
86
+ try {
87
+ const response = await client.post('/api/billing/cancel', {});
88
+ setState({ data: response.data, loading: false, error: null });
89
+ return response.data;
90
+ }
91
+ catch (err) {
92
+ const error = err instanceof Error ? err : new Error(String(err));
93
+ setState({ data: null, loading: false, error });
94
+ return null;
95
+ }
96
+ }, [client]);
97
+ return { ...state, cancel };
98
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * React pricing page + checkout flow for the molecule.dev billing kit.
3
+ *
4
+ * Components:
5
+ * `<PricingPage />` — public pricing table that fetches `/api/billing/tiers`
6
+ * and posts to `/api/billing/checkout` when the user clicks Upgrade.
7
+ *
8
+ * `<BillingStatusBadge />` — compact account-page status display that
9
+ * shows the current tier and offers a cancel-subscription button.
10
+ *
11
+ * `<LimitsList>` / `<LimitsItem>` — building blocks for the
12
+ * `renderLimits` prop: a stacked checklist row with check / dash icon,
13
+ * e.g. `renderLimits={(l) => (
14
+ * <LimitsList>
15
+ * <LimitsItem>{l.maxAccounts} accounts</LimitsItem>
16
+ * <LimitsItem included={l.canExport}>Data export</LimitsItem>
17
+ * </LimitsList>
18
+ * )}`
19
+ *
20
+ * Hooks:
21
+ * `usePricingTiers<TLimits>()` → `UseHttpResult<PricingTiersResponse<TLimits>>`
22
+ * `useBillingStatus<TLimits>()` → `UseHttpResult<BillingStatus<TLimits>>`
23
+ * `useStartCheckout()` → `{ data, loading, error, start(priceId) }`
24
+ * `useCancelSubscription()` → `{ data, loading, error, cancel() }`
25
+ *
26
+ * The API side of this kit lives in `@molecule/api-entitlements` +
27
+ * `@molecule/api-payments-stripe`. Wire those into your project (any
28
+ * mlcl flagship template that includes `@molecule/api-entitlements`
29
+ * already exposes the `/api/billing/*` routes), then drop `<PricingPage />`
30
+ * onto a `/pricing` route.
31
+ *
32
+ * @remarks
33
+ * **Name collision:** `PricingPage` is also exported by
34
+ * `@molecule/app-pricing-page-react` (a tier-card grid with a monthly/yearly
35
+ * toggle driven by `usePricingTiers()`). THIS package's `<PricingPage>` is the
36
+ * entitlements-kit table with a `renderLimits` prop + compound
37
+ * `<LimitsList>`/`<LimitsItem>` and a built-in `<BillingStatusBadge>` — import
38
+ * from `@molecule/app-billing-react` when you are wiring
39
+ * `@molecule/api-entitlements`. If you import both packages, alias one to avoid
40
+ * the clash.
41
+ *
42
+ * @example
43
+ * ```tsx
44
+ * import { PricingPage } from '@molecule/app-billing-react'
45
+ * import type { PersonalFinanceLimits } from '../tiers'
46
+ *
47
+ * const Pricing = () => (
48
+ * <PricingPage<PersonalFinanceLimits>
49
+ * period="month"
50
+ * renderLimits={(l) => (
51
+ * <ul>
52
+ * <li>{l.maxAccounts} accounts</li>
53
+ * <li>{l.maxTransactionsPerMonth} transactions / month</li>
54
+ * </ul>
55
+ * )}
56
+ * />
57
+ * )
58
+ * ```
59
+ *
60
+ * @e2e
61
+ * Integration checklist — drive the real UI (live preview, no mocks), adapt
62
+ * each item to this app's actual screens/flows, and check every box off one
63
+ * by one. A box you can't check is an integration bug to fix — not a skip:
64
+ * - [ ] The pricing route renders every tier from `/api/billing/tiers` with name,
65
+ * price, and per-tier limits — no empty table, no `undefined` cells.
66
+ * - [ ] The signed-in user's CURRENT tier is visibly marked (highlighted / "current
67
+ * plan") and its Upgrade button is disabled or absent.
68
+ * - [ ] Clicking Upgrade on another tier posts to `/api/billing/checkout` and the
69
+ * page follows the returned checkout handoff (button is not a dead click).
70
+ * - [ ] `<BillingStatusBadge />` on the account screen shows the live tier, and its
71
+ * cancel action updates the shown status after confirmation.
72
+ * - [ ] A signed-out visitor can still view the public pricing table.
73
+ * - [ ] If the tiers endpoint fails, the page shows a visible error state — not a
74
+ * blank page or spinner forever.
75
+ *
76
+ * @module
77
+ */
78
+ export * from './BillingStatusBadge.js';
79
+ export * from './hooks.js';
80
+ export * from './PricingPage.js';
81
+ export * from './types.js';
82
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4EG;AAEH,cAAc,yBAAyB,CAAA;AACvC,cAAc,YAAY,CAAA;AAC1B,cAAc,kBAAkB,CAAA;AAChC,cAAc,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,81 @@
1
+ /**
2
+ * React pricing page + checkout flow for the molecule.dev billing kit.
3
+ *
4
+ * Components:
5
+ * `<PricingPage />` — public pricing table that fetches `/api/billing/tiers`
6
+ * and posts to `/api/billing/checkout` when the user clicks Upgrade.
7
+ *
8
+ * `<BillingStatusBadge />` — compact account-page status display that
9
+ * shows the current tier and offers a cancel-subscription button.
10
+ *
11
+ * `<LimitsList>` / `<LimitsItem>` — building blocks for the
12
+ * `renderLimits` prop: a stacked checklist row with check / dash icon,
13
+ * e.g. `renderLimits={(l) => (
14
+ * <LimitsList>
15
+ * <LimitsItem>{l.maxAccounts} accounts</LimitsItem>
16
+ * <LimitsItem included={l.canExport}>Data export</LimitsItem>
17
+ * </LimitsList>
18
+ * )}`
19
+ *
20
+ * Hooks:
21
+ * `usePricingTiers<TLimits>()` → `UseHttpResult<PricingTiersResponse<TLimits>>`
22
+ * `useBillingStatus<TLimits>()` → `UseHttpResult<BillingStatus<TLimits>>`
23
+ * `useStartCheckout()` → `{ data, loading, error, start(priceId) }`
24
+ * `useCancelSubscription()` → `{ data, loading, error, cancel() }`
25
+ *
26
+ * The API side of this kit lives in `@molecule/api-entitlements` +
27
+ * `@molecule/api-payments-stripe`. Wire those into your project (any
28
+ * mlcl flagship template that includes `@molecule/api-entitlements`
29
+ * already exposes the `/api/billing/*` routes), then drop `<PricingPage />`
30
+ * onto a `/pricing` route.
31
+ *
32
+ * @remarks
33
+ * **Name collision:** `PricingPage` is also exported by
34
+ * `@molecule/app-pricing-page-react` (a tier-card grid with a monthly/yearly
35
+ * toggle driven by `usePricingTiers()`). THIS package's `<PricingPage>` is the
36
+ * entitlements-kit table with a `renderLimits` prop + compound
37
+ * `<LimitsList>`/`<LimitsItem>` and a built-in `<BillingStatusBadge>` — import
38
+ * from `@molecule/app-billing-react` when you are wiring
39
+ * `@molecule/api-entitlements`. If you import both packages, alias one to avoid
40
+ * the clash.
41
+ *
42
+ * @example
43
+ * ```tsx
44
+ * import { PricingPage } from '@molecule/app-billing-react'
45
+ * import type { PersonalFinanceLimits } from '../tiers'
46
+ *
47
+ * const Pricing = () => (
48
+ * <PricingPage<PersonalFinanceLimits>
49
+ * period="month"
50
+ * renderLimits={(l) => (
51
+ * <ul>
52
+ * <li>{l.maxAccounts} accounts</li>
53
+ * <li>{l.maxTransactionsPerMonth} transactions / month</li>
54
+ * </ul>
55
+ * )}
56
+ * />
57
+ * )
58
+ * ```
59
+ *
60
+ * @e2e
61
+ * Integration checklist — drive the real UI (live preview, no mocks), adapt
62
+ * each item to this app's actual screens/flows, and check every box off one
63
+ * by one. A box you can't check is an integration bug to fix — not a skip:
64
+ * - [ ] The pricing route renders every tier from `/api/billing/tiers` with name,
65
+ * price, and per-tier limits — no empty table, no `undefined` cells.
66
+ * - [ ] The signed-in user's CURRENT tier is visibly marked (highlighted / "current
67
+ * plan") and its Upgrade button is disabled or absent.
68
+ * - [ ] Clicking Upgrade on another tier posts to `/api/billing/checkout` and the
69
+ * page follows the returned checkout handoff (button is not a dead click).
70
+ * - [ ] `<BillingStatusBadge />` on the account screen shows the live tier, and its
71
+ * cancel action updates the shown status after confirmation.
72
+ * - [ ] A signed-out visitor can still view the public pricing table.
73
+ * - [ ] If the tiers endpoint fails, the page shows a visible error state — not a
74
+ * blank page or spinner forever.
75
+ *
76
+ * @module
77
+ */
78
+ export * from './BillingStatusBadge.js';
79
+ export * from './hooks.js';
80
+ export * from './PricingPage.js';
81
+ export * from './types.js';
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Type definitions mirroring the API-side billing endpoint contracts.
3
+ *
4
+ * These types match the JSON shapes returned by `@molecule/api-entitlements`
5
+ * + `@molecule/api-payments-stripe` when an app exposes the standard billing
6
+ * routes:
7
+ *
8
+ * - `GET /api/billing/tiers` → `{ data: PricingTierEntry[] }`
9
+ * - `GET /api/billing/status` → `BillingStatus`
10
+ * - `POST /api/billing/checkout` body: `{ priceId: string }`
11
+ * response: `{ checkoutUrl }` | `{ updated, subscription }`
12
+ * - `POST /api/billing/cancel` → `{ canceled: true }`
13
+ *
14
+ * @module
15
+ */
16
+ /**
17
+ * One billing period offered for a tier — typically `month` or `year` —
18
+ * with the human-readable price string and the Stripe price ID. The price
19
+ * ID may be `null` for the free tier (no Stripe product).
20
+ */
21
+ export interface PricingTierPrice {
22
+ /** Billing cadence. */
23
+ period: 'month' | 'year';
24
+ /** Display string (e.g. `'$19/mo'`, `'$190/yr'`, `'$0'`). */
25
+ price: string;
26
+ /**
27
+ * Stripe Price ID used as the line item when the user clicks Upgrade.
28
+ * `null` for free tiers and during local dev when env vars are unset.
29
+ */
30
+ stripePriceId: string | null;
31
+ /** Optional savings tag on yearly variants (e.g. `'2 months free'`). */
32
+ savings?: string;
33
+ }
34
+ /**
35
+ * One row of the public pricing table. Apps can declare any number of
36
+ * `period` variants per tier (typically a `month` and `year` pair).
37
+ */
38
+ export interface PricingTierEntry<TLimits = unknown> {
39
+ /** Stable slug used as a row key (`'free'`, `'pro'`, `'team'`). */
40
+ key: string;
41
+ /** Display name shown in the page heading and CTA. */
42
+ name: string;
43
+ /** Price variants for the tier. Order is presentation order. */
44
+ prices: PricingTierPrice[];
45
+ /** Tier-specific limits — render any/all of these on the comparison row. */
46
+ limits: TLimits;
47
+ /** Whether the tier is billed per seat (rendered as a footnote). */
48
+ perSeat?: boolean;
49
+ }
50
+ /** Response envelope for `GET /api/billing/tiers`. */
51
+ export interface PricingTiersResponse<TLimits = unknown> {
52
+ /** Tiers ordered as the API returns them (typically free → pro → team). */
53
+ data: PricingTierEntry<TLimits>[];
54
+ }
55
+ /**
56
+ * Snapshot of the signed-in user's current billing state. Returned by
57
+ * `GET /api/billing/status` once the user is authenticated.
58
+ */
59
+ export interface BillingStatus<TLimits = unknown> {
60
+ /** The user's `users.planKey` (`'free'`, `'stripeMonthly'`, etc.). */
61
+ planKey: string;
62
+ /** Tier category — `'free'`, `'pro'`, `'team'`, or any app-defined extension. */
63
+ category: string;
64
+ /** Display name (matches `PricingTierEntry.name` for the active tier). */
65
+ name: string;
66
+ /** Tier-specific limits the user is currently entitled to. */
67
+ limits: TLimits;
68
+ /** True when the user is on the registry default (free) tier. */
69
+ isFree: boolean;
70
+ }
71
+ /** Response from `POST /api/billing/checkout`. Either `checkoutUrl` or `updated` is set. */
72
+ export interface CheckoutResponse {
73
+ /** Stripe Checkout URL — set when the user has no active subscription yet. */
74
+ checkoutUrl?: string;
75
+ /** True when the user already had a subscription that was updated in place. */
76
+ updated?: boolean;
77
+ /** Updated subscription metadata (only when `updated === true`). */
78
+ subscription?: {
79
+ expiresAt?: string;
80
+ autoRenews?: boolean;
81
+ };
82
+ }
83
+ /** Response from `POST /api/billing/cancel`. */
84
+ export interface CancelResponse {
85
+ /** True when the cancellation request was accepted. */
86
+ canceled?: boolean;
87
+ /** Localized error message when cancellation failed. */
88
+ error?: string;
89
+ }
90
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,uBAAuB;IACvB,MAAM,EAAE,OAAO,GAAG,MAAM,CAAA;IAExB,6DAA6D;IAC7D,KAAK,EAAE,MAAM,CAAA;IAEb;;;OAGG;IACH,aAAa,EAAE,MAAM,GAAG,IAAI,CAAA;IAE5B,wEAAwE;IACxE,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB,CAAC,OAAO,GAAG,OAAO;IACjD,mEAAmE;IACnE,GAAG,EAAE,MAAM,CAAA;IAEX,sDAAsD;IACtD,IAAI,EAAE,MAAM,CAAA;IAEZ,gEAAgE;IAChE,MAAM,EAAE,gBAAgB,EAAE,CAAA;IAE1B,4EAA4E;IAC5E,MAAM,EAAE,OAAO,CAAA;IAEf,oEAAoE;IACpE,OAAO,CAAC,EAAE,OAAO,CAAA;CAClB;AAED,sDAAsD;AACtD,MAAM,WAAW,oBAAoB,CAAC,OAAO,GAAG,OAAO;IACrD,2EAA2E;IAC3E,IAAI,EAAE,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAA;CAClC;AAED;;;GAGG;AACH,MAAM,WAAW,aAAa,CAAC,OAAO,GAAG,OAAO;IAC9C,sEAAsE;IACtE,OAAO,EAAE,MAAM,CAAA;IAEf,iFAAiF;IACjF,QAAQ,EAAE,MAAM,CAAA;IAEhB,0EAA0E;IAC1E,IAAI,EAAE,MAAM,CAAA;IAEZ,8DAA8D;IAC9D,MAAM,EAAE,OAAO,CAAA;IAEf,iEAAiE;IACjE,MAAM,EAAE,OAAO,CAAA;CAChB;AAED,4FAA4F;AAC5F,MAAM,WAAW,gBAAgB;IAC/B,8EAA8E;IAC9E,WAAW,CAAC,EAAE,MAAM,CAAA;IAEpB,+EAA+E;IAC/E,OAAO,CAAC,EAAE,OAAO,CAAA;IAEjB,oEAAoE;IACpE,YAAY,CAAC,EAAE;QACb,SAAS,CAAC,EAAE,MAAM,CAAA;QAClB,UAAU,CAAC,EAAE,OAAO,CAAA;KACrB,CAAA;CACF;AAED,gDAAgD;AAChD,MAAM,WAAW,cAAc;IAC7B,uDAAuD;IACvD,QAAQ,CAAC,EAAE,OAAO,CAAA;IAElB,wDAAwD;IACxD,KAAK,CAAC,EAAE,MAAM,CAAA;CACf"}
package/dist/types.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Type definitions mirroring the API-side billing endpoint contracts.
3
+ *
4
+ * These types match the JSON shapes returned by `@molecule/api-entitlements`
5
+ * + `@molecule/api-payments-stripe` when an app exposes the standard billing
6
+ * routes:
7
+ *
8
+ * - `GET /api/billing/tiers` → `{ data: PricingTierEntry[] }`
9
+ * - `GET /api/billing/status` → `BillingStatus`
10
+ * - `POST /api/billing/checkout` body: `{ priceId: string }`
11
+ * response: `{ checkoutUrl }` | `{ updated, subscription }`
12
+ * - `POST /api/billing/cancel` → `{ canceled: true }`
13
+ *
14
+ * @module
15
+ */
16
+ export {};
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@molecule/app-billing-react",
3
+ "version": "1.0.0",
4
+ "description": "React pricing page + checkout flow that consumes /api/billing/* (provided by @molecule/api-entitlements + @molecule/api-payments-stripe)",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "molecule",
24
+ "billing",
25
+ "subscriptions",
26
+ "stripe",
27
+ "react"
28
+ ],
29
+ "license": "Apache-2.0",
30
+ "peerDependencies": {
31
+ "@molecule/app-http": "^1.0.0",
32
+ "@molecule/app-react": "^1.0.0",
33
+ "@molecule/app-ui": "^1.0.0",
34
+ "@molecule/app-ui-react": "^1.0.0",
35
+ "react": "^18.0.0 || ^19.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "@molecule/app-http": "1.0.0",
39
+ "@molecule/app-react": "1.0.0",
40
+ "@molecule/app-ui": "1.0.0",
41
+ "@molecule/app-ui-react": "1.0.0",
42
+ "@types/node": "26.1.2",
43
+ "@types/react": "19.2.17",
44
+ "react": "19.2.8",
45
+ "typescript": "6.0.3",
46
+ "vitest": "4.1.10"
47
+ }
48
+ }