@tenthbilling/paywall 0.0.0-stage → 0.1.1

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.
Files changed (67) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/components/Badge.d.ts +8 -0
  4. package/dist/components/Badge.js +14 -0
  5. package/dist/components/Button.d.ts +17 -0
  6. package/dist/components/Button.js +60 -0
  7. package/dist/components/Card.d.ts +13 -0
  8. package/dist/components/Card.js +29 -0
  9. package/dist/components/CloseButton.d.ts +10 -0
  10. package/dist/components/CloseButton.js +21 -0
  11. package/dist/components/ComparisonTable.d.ts +20 -0
  12. package/dist/components/ComparisonTable.js +43 -0
  13. package/dist/components/CreditPackOption.d.ts +16 -0
  14. package/dist/components/CreditPackOption.js +38 -0
  15. package/dist/components/FeatureList.d.ts +14 -0
  16. package/dist/components/FeatureList.js +15 -0
  17. package/dist/components/PaywallFooter.d.ts +17 -0
  18. package/dist/components/PaywallFooter.js +46 -0
  19. package/dist/components/PaywallOption.d.ts +26 -0
  20. package/dist/components/PaywallOption.js +41 -0
  21. package/dist/components/Radio.d.ts +8 -0
  22. package/dist/components/Radio.js +21 -0
  23. package/dist/components/RadioGroup.d.ts +23 -0
  24. package/dist/components/RadioGroup.js +42 -0
  25. package/dist/components/Text.d.ts +10 -0
  26. package/dist/components/Text.js +8 -0
  27. package/dist/components/TextField.d.ts +19 -0
  28. package/dist/components/TextField.js +38 -0
  29. package/dist/components/dimensions.d.ts +29 -0
  30. package/dist/components/dimensions.js +21 -0
  31. package/dist/components/icons.d.ts +7 -0
  32. package/dist/components/icons.js +15 -0
  33. package/dist/controller.d.ts +97 -0
  34. package/dist/controller.js +1 -0
  35. package/dist/format.d.ts +5 -0
  36. package/dist/format.js +3 -0
  37. package/dist/index.d.ts +28 -0
  38. package/dist/index.js +26 -0
  39. package/dist/paywall/PaywallScaffold.d.ts +52 -0
  40. package/dist/paywall/PaywallScaffold.js +42 -0
  41. package/dist/paywall/PaywallView.d.ts +38 -0
  42. package/dist/paywall/PaywallView.js +219 -0
  43. package/dist/paywall/copy.d.ts +36 -0
  44. package/dist/paywall/copy.js +90 -0
  45. package/dist/paywall/price.d.ts +38 -0
  46. package/dist/paywall/price.js +124 -0
  47. package/dist/paywall/selection.d.ts +17 -0
  48. package/dist/paywall/selection.js +13 -0
  49. package/dist/paywall/slots.d.ts +46 -0
  50. package/dist/paywall/slots.js +1 -0
  51. package/dist/paywall/strings.d.ts +13 -0
  52. package/dist/paywall/strings.js +10 -0
  53. package/dist/paywall/templates.d.ts +31 -0
  54. package/dist/paywall/templates.js +60 -0
  55. package/dist/paywall/theme.d.ts +41 -0
  56. package/dist/paywall/theme.js +104 -0
  57. package/dist/paywall/url.d.ts +22 -0
  58. package/dist/paywall/url.js +48 -0
  59. package/dist/schema/config.d.ts +264 -0
  60. package/dist/schema/config.js +149 -0
  61. package/dist/schema/defaults.d.ts +2 -0
  62. package/dist/schema/defaults.js +20 -0
  63. package/dist/schema/index.d.ts +2 -0
  64. package/dist/schema/index.js +2 -0
  65. package/dist/theme.d.ts +14 -0
  66. package/dist/theme.js +14 -0
  67. package/package.json +66 -3
@@ -0,0 +1,219 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { themes } from '@tenthbilling/design';
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
+ import { AccessibilityInfo, ActivityIndicator, Animated, Easing, Modal, Platform, Pressable, ScrollView, StyleSheet, View, useColorScheme, useWindowDimensions, } from 'react-native';
5
+ import { Banner } from '../components/Card';
6
+ import { SHEET_DURATION_MS, SHEET_MAX_WIDTH } from '../components/dimensions';
7
+ import { Text } from '../components/Text';
8
+ import { ThemeProvider, useTheme } from '../theme';
9
+ import { resolveCopy } from './copy';
10
+ import { CloseRow, EnvironmentBanner } from './PaywallScaffold';
11
+ import { safeLocale } from './price';
12
+ import { selectedProduct } from './selection';
13
+ import { EMPTY_MESSAGE, LOAD_ERROR_MESSAGE, LOADING_LABEL, NOTHING_TO_RESTORE_MESSAGE, PENDING_MESSAGE, PURCHASE_FAILED_MESSAGE, RESTORE_FAILED_MESSAGE, RESTORED_MESSAGE, } from './strings';
14
+ import { PAYWALL_TEMPLATES, TiersTemplate, visibleProducts } from './templates';
15
+ import { resolveColorScheme, resolvePaywallTheme } from './theme';
16
+ function useReduceMotion() {
17
+ const [reduce, setReduce] = useState(null);
18
+ useEffect(() => {
19
+ let alive = true;
20
+ AccessibilityInfo.isReduceMotionEnabled()
21
+ .then((value) => alive && setReduce(value))
22
+ .catch(() => alive && setReduce(false));
23
+ const subscription = AccessibilityInfo.addEventListener('reduceMotionChanged', (value) => setReduce(value));
24
+ return () => {
25
+ alive = false;
26
+ subscription?.remove();
27
+ };
28
+ }, []);
29
+ return reduce;
30
+ }
31
+ function Sheet({ onClose, children }) {
32
+ const { colors, space, radius, shadows, name } = useTheme();
33
+ const { height } = useWindowDimensions();
34
+ const reduceMotion = useReduceMotion();
35
+ const progress = useRef(new Animated.Value(0)).current;
36
+ const web = Platform.OS === 'web';
37
+ const fade = web || reduceMotion === true;
38
+ useEffect(() => {
39
+ if (reduceMotion === null)
40
+ return;
41
+ const animation = Animated.timing(progress, {
42
+ toValue: 1,
43
+ duration: SHEET_DURATION_MS,
44
+ easing: Easing.out(Easing.cubic),
45
+ useNativeDriver: !web,
46
+ });
47
+ animation.start();
48
+ return () => animation.stop();
49
+ }, [progress, reduceMotion, web]);
50
+ const motion = fade
51
+ ? { opacity: progress }
52
+ : {
53
+ transform: [
54
+ { translateY: progress.interpolate({ inputRange: [0, 1], outputRange: [height, 0] }) },
55
+ ],
56
+ };
57
+ const card = web
58
+ ? {
59
+ width: '100%',
60
+ maxWidth: SHEET_MAX_WIDTH,
61
+ maxHeight: '90%',
62
+ borderRadius: radius.lg,
63
+ }
64
+ : {
65
+ width: '100%',
66
+ maxHeight: '90%',
67
+ borderTopLeftRadius: radius.xl,
68
+ borderTopRightRadius: radius.xl,
69
+ };
70
+ return (_jsxs(View, { style: {
71
+ flex: 1,
72
+ justifyContent: web ? 'center' : 'flex-end',
73
+ alignItems: 'center',
74
+ padding: web ? space[4] : undefined,
75
+ }, children: [_jsx(Pressable, { accessible: false, importantForAccessibility: "no", onPress: onClose, style: [
76
+ StyleSheet.absoluteFill,
77
+ {
78
+ backgroundColor: name === 'light' ? colors.ink : colors.surfaceSunken,
79
+ opacity: SCRIM_OPACITY,
80
+ },
81
+ ] }), _jsx(Animated.View, { accessibilityViewIsModal: true, style: [
82
+ card,
83
+ {
84
+ backgroundColor: colors.surfaceRaised,
85
+ boxShadow: shadows.shadowOverlay,
86
+ overflow: 'hidden',
87
+ },
88
+ motion,
89
+ ], children: _jsx(ScrollView, { contentContainerStyle: { padding: web ? space[5] : space[4] }, children: children }) })] }));
90
+ }
91
+ const PHONE_MAX_WIDTH = 640;
92
+ const SCRIM_OPACITY = 0.5;
93
+ function StatusState({ controller, slots, onClose, }) {
94
+ const { colors, space } = useTheme();
95
+ let body;
96
+ if (controller.status === 'loading') {
97
+ body = (_jsx(View, { style: { alignItems: 'center', paddingVertical: space[6] }, children: _jsx(ActivityIndicator, { size: "large", color: colors.brand, accessibilityLabel: LOADING_LABEL }) }));
98
+ }
99
+ else if (controller.status === 'error') {
100
+ body = _jsx(Banner, { kind: "danger", children: controller.error?.message || LOAD_ERROR_MESSAGE });
101
+ }
102
+ else {
103
+ body = (_jsx(Text, { variant: "body", color: "inkMuted", style: { textAlign: 'center' }, children: EMPTY_MESSAGE }));
104
+ }
105
+ return (_jsxs(View, { style: { gap: space[4] }, children: [_jsx(CloseRow, { onClose: onClose, slots: slots }), _jsx(EnvironmentBanner, { controller: controller }), body] }));
106
+ }
107
+ export function PaywallView({ controller, presentation = 'inline', slots, theme: themeOverrides, locale: localeProp, onDismiss, onPurchased, previewAssets, }) {
108
+ const config = controller.config;
109
+ const host = useColorScheme();
110
+ const scheme = resolveColorScheme(config.theme, themeOverrides, host);
111
+ const theme = useMemo(() => resolvePaywallTheme(themes[scheme], config.theme, themeOverrides), [scheme, config.theme, themeOverrides]);
112
+ const rawLocale = localeProp ?? controller.locale;
113
+ const locale = safeLocale(rawLocale);
114
+ const copy = resolveCopy(config.copy, rawLocale ?? locale);
115
+ const template = config.template;
116
+ const products = visibleProducts(template, controller.products);
117
+ const selected = selectedProduct(products, controller.selectedKey);
118
+ const [visible, setVisible] = useState(true);
119
+ const [notice, setNotice] = useState(null);
120
+ const mounted = useRef(true);
121
+ useEffect(() => {
122
+ mounted.current = true;
123
+ return () => {
124
+ mounted.current = false;
125
+ };
126
+ }, []);
127
+ const selectedKey = selected?.key ?? null;
128
+ useEffect(() => {
129
+ if (selectedKey !== null && controller.selectedKey !== selectedKey) {
130
+ controller.select(selectedKey);
131
+ }
132
+ }, [controller, selectedKey]);
133
+ const close = useCallback(() => {
134
+ setVisible(false);
135
+ onDismiss?.();
136
+ }, [onDismiss]);
137
+ const select = useCallback((key) => {
138
+ setNotice(null);
139
+ controller.select(key);
140
+ }, [controller]);
141
+ const purchase = useCallback(async () => {
142
+ if (!selected || controller.purchasing)
143
+ return;
144
+ setNotice(null);
145
+ let result;
146
+ try {
147
+ result = await controller.purchase(selected.key);
148
+ }
149
+ catch {
150
+ result = { status: 'failed', error: { code: 'unknown', message: PURCHASE_FAILED_MESSAGE } };
151
+ }
152
+ if (!mounted.current)
153
+ return;
154
+ if (result.status === 'purchased')
155
+ onPurchased?.(selected);
156
+ else if (result.status === 'pending')
157
+ setNotice({ kind: 'info', message: PENDING_MESSAGE });
158
+ else if (result.status === 'failed') {
159
+ setNotice({ kind: 'danger', message: result.error?.message || PURCHASE_FAILED_MESSAGE });
160
+ }
161
+ }, [controller, selected, onPurchased]);
162
+ const restore = useCallback(async () => {
163
+ if (controller.restoring)
164
+ return;
165
+ setNotice(null);
166
+ let result;
167
+ try {
168
+ result = await controller.restore();
169
+ }
170
+ catch {
171
+ result = { status: 'failed' };
172
+ }
173
+ if (!mounted.current)
174
+ return;
175
+ if (result.status === 'restored')
176
+ setNotice({ kind: 'success', message: RESTORED_MESSAGE });
177
+ else if (result.status === 'nothing_to_restore') {
178
+ setNotice({ kind: 'info', message: NOTHING_TO_RESTORE_MESSAGE });
179
+ }
180
+ else {
181
+ setNotice({ kind: 'danger', message: result.error?.message || RESTORE_FAILED_MESSAGE });
182
+ }
183
+ }, [controller]);
184
+ const onClose = presentation === 'inline'
185
+ ? onDismiss && config.layout.close_button !== false
186
+ ? close
187
+ : null
188
+ : close;
189
+ const onRestore = config.layout.restore_button === false ? null : () => void restore();
190
+ const Template = PAYWALL_TEMPLATES[template] ?? TiersTemplate;
191
+ const ready = controller.status === 'ready' && products.length > 0;
192
+ const content = ready ? (_jsx(Template, { controller: controller, copy: copy, locale: locale, products: products, selected: selected, select: select, slots: slots, onPurchase: () => void purchase(), onRestore: onRestore, onClose: onClose, notice: notice, previewAssets: previewAssets })) : (_jsx(StatusState, { controller: controller, slots: slots, onClose: onClose }));
193
+ return (_jsx(ThemeProvider, { theme: theme, children: _jsx(Presentation, { presentation: presentation, visible: visible, onClose: close, children: content }) }));
194
+ }
195
+ function Presentation({ presentation, visible, onClose, children, }) {
196
+ const { colors, space } = useTheme();
197
+ const { width } = useWindowDimensions();
198
+ const web = Platform.OS === 'web';
199
+ const reduceMotion = useReduceMotion();
200
+ const padding = width < PHONE_MAX_WIDTH ? space[4] : space[5];
201
+ if (presentation === 'sheet') {
202
+ return (_jsx(Modal, { visible: visible, transparent: true, animationType: "none", onRequestClose: onClose, children: _jsx(Sheet, { onClose: onClose, children: children }) }));
203
+ }
204
+ if (presentation === 'modal') {
205
+ return (_jsx(Modal, { visible: visible, animationType: reduceMotion === false ? 'slide' : 'fade', presentationStyle: "pageSheet", onRequestClose: onClose, children: _jsx(View, { style: { flex: 1, backgroundColor: colors.surfaceRaised }, children: _jsx(ScrollView, { contentContainerStyle: {
206
+ padding,
207
+ width: '100%',
208
+ maxWidth: web ? SHEET_MAX_WIDTH : undefined,
209
+ alignSelf: 'center',
210
+ }, children: children }) }) }));
211
+ }
212
+ return (_jsx(View, { style: {
213
+ backgroundColor: colors.surfaceRaised,
214
+ padding,
215
+ width: '100%',
216
+ maxWidth: web ? SHEET_MAX_WIDTH : undefined,
217
+ alignSelf: 'center',
218
+ }, children: children }));
219
+ }
@@ -0,0 +1,36 @@
1
+ import type { PaywallProduct } from '../controller';
2
+ import type { PaywallCopy, PaywallLocalizedCopy } from '../schema/config';
3
+ /**
4
+ * Picks the copy for `locale`: the exact tag (case-insensitive, `_` treated as `-`), then the bare
5
+ * language (`pt` for `pt-PT`), then another region of the same language (`pt-BR`), then
6
+ * `default_locale`. Never reads inherited properties, so a locale like `constructor` can't reach
7
+ * Object.prototype.
8
+ */
9
+ export declare function resolveCopy(copy: PaywallCopy, locale: string): PaywallLocalizedCopy;
10
+ /**
11
+ * The purchase button label, naming what happens (design system "Button", "PaywallOption"):
12
+ * - free trial: `Start 7-day free trial`
13
+ * - paid intro offer: `Subscribe for $0.99/month` (pay as you go) or `Subscribe for $1.99 for 3 months`
14
+ * - subscription: `Subscribe for $59.99/year`
15
+ * - credit pack: `Buy 500 credits for $4.99`
16
+ * - other one-time purchase: `Buy for $4.99`
17
+ *
18
+ * A tenant override (`copy.cta`) wins, with `{price}` and `{period}` replaced by the selected
19
+ * product's store price and period (`/{period}` is dropped for one-time purchases).
20
+ */
21
+ export declare function ctaLabel(product: PaywallProduct | null, options?: {
22
+ override?: string | null;
23
+ locale?: string;
24
+ }): string;
25
+ /**
26
+ * The detail line under an option's name (design system "PaywallOption": the per-month
27
+ * equivalent for long periods, or the trial):
28
+ * - free trial: `7-day free trial, then $59.99/year`
29
+ * - paid intro: `$0.99/month for 3 months, then $9.99/month`
30
+ * - long period: `$5.00/month`
31
+ * - credit pack: `500 credits`
32
+ * Null when there's nothing to add.
33
+ */
34
+ export declare function optionDetail(product: PaywallProduct, locale: string): string | null;
35
+ /** The price shown on an option, period price first: `$59.99/year`, or `$4.99`. */
36
+ export declare function optionPrice(product: PaywallProduct): string;
@@ -0,0 +1,90 @@
1
+ import { creditsLabel, durationAdjective, durationPhrase, formatCount, perMonthLabel, periodLabel, priceWithPeriod, } from './price';
2
+ const FALLBACK_COPY = { title: 'Upgrade' };
3
+ function normalizeTag(tag) {
4
+ return tag.replace(/_/g, '-').toLowerCase();
5
+ }
6
+ export function resolveCopy(copy, locale) {
7
+ const byTag = new Map();
8
+ for (const [tag, value] of Object.entries(copy.locales))
9
+ byTag.set(normalizeTag(tag), value);
10
+ const wanted = normalizeTag(locale ?? '');
11
+ const language = wanted.split('-')[0] ?? '';
12
+ const exact = byTag.get(wanted);
13
+ if (exact)
14
+ return exact;
15
+ const bare = byTag.get(language);
16
+ if (bare)
17
+ return bare;
18
+ if (language) {
19
+ for (const [tag, value] of byTag)
20
+ if (tag.split('-')[0] === language)
21
+ return value;
22
+ }
23
+ return (byTag.get(normalizeTag(copy.default_locale)) ?? byTag.values().next().value ?? FALLBACK_COPY);
24
+ }
25
+ function substitute(template, product) {
26
+ const price = product?.price.formatted ?? '';
27
+ const period = product?.period ? periodLabel(product.period) : '';
28
+ let out = template;
29
+ if (!period)
30
+ out = out.split('/{period}').join('');
31
+ return out
32
+ .split('{price}')
33
+ .join(price)
34
+ .split('{period}')
35
+ .join(period)
36
+ .replace(/\s+/g, ' ')
37
+ .trim();
38
+ }
39
+ export function ctaLabel(product, options = {}) {
40
+ const { override, locale = 'en' } = options;
41
+ if (override) {
42
+ const label = substitute(override, product);
43
+ if (label && (product || !/\{(price|period)\}/.test(override)))
44
+ return label;
45
+ }
46
+ if (!product)
47
+ return 'Continue';
48
+ const intro = product.intro;
49
+ if (product.type === 'subscription' && intro) {
50
+ if (intro.kind === 'free_trial') {
51
+ return `Start ${durationAdjective(intro.period, intro.periods)} free trial`;
52
+ }
53
+ if (intro.price) {
54
+ return intro.kind === 'pay_up_front'
55
+ ? `Subscribe for ${intro.price.formatted} for ${durationPhrase(intro.period, intro.periods)}`
56
+ : `Subscribe for ${priceWithPeriod(intro.price, intro.period)}`;
57
+ }
58
+ }
59
+ if (product.type === 'subscription') {
60
+ return `Subscribe for ${priceWithPeriod(product.price, product.period)}`;
61
+ }
62
+ const grant = product.credits[0];
63
+ if (product.type === 'consumable' && grant && Number.isFinite(grant.amount)) {
64
+ const noun = grant.amount === 1 ? 'credit' : 'credits';
65
+ return `Buy ${formatCount(grant.amount, locale)} ${noun} for ${product.price.formatted}`;
66
+ }
67
+ return `Buy for ${product.price.formatted}`;
68
+ }
69
+ export function optionDetail(product, locale) {
70
+ const intro = product.intro;
71
+ if (product.type === 'subscription' && intro) {
72
+ const then = `then ${priceWithPeriod(product.price, product.period)}`;
73
+ if (intro.kind === 'free_trial') {
74
+ return `${durationAdjective(intro.period, intro.periods)} free trial, ${then}`;
75
+ }
76
+ if (intro.price) {
77
+ const offer = intro.kind === 'pay_up_front'
78
+ ? intro.price.formatted
79
+ : priceWithPeriod(intro.price, intro.period);
80
+ return `${offer} for ${durationPhrase(intro.period, intro.periods)}, ${then}`;
81
+ }
82
+ }
83
+ if (product.type === 'subscription') {
84
+ return perMonthLabel(product.price, product.period, locale);
85
+ }
86
+ return creditsLabel(product, locale);
87
+ }
88
+ export function optionPrice(product) {
89
+ return priceWithPeriod(product.price, product.type === 'subscription' ? product.period : null);
90
+ }
@@ -0,0 +1,38 @@
1
+ import type { DisplayPrice, Period, PaywallProduct } from '../controller';
2
+ /**
3
+ * A locale Intl accepts. `controller.locale` comes from the device; a malformed tag would make
4
+ * Intl throw a RangeError, which must never crash a paywall, so it falls back to `en`.
5
+ */
6
+ export declare function safeLocale(locale: string | null | undefined): string;
7
+ /**
8
+ * The number of minor-unit digits for an ISO 4217 currency (2 for USD, 0 for JPY, 3 for KWD), or
9
+ * null when Intl doesn't know the code.
10
+ */
11
+ export declare function currencyDigits(currency: string): number | null;
12
+ /**
13
+ * Formats an amount in micros in `currency`, rounded half up to the currency's minor unit, such
14
+ * as `$5.00`, `¥1,200` or `KWD 1.250`. Null when the currency is unknown.
15
+ */
16
+ export declare function formatMicros(micros: bigint, currency: string, locale: string): string | null;
17
+ /** Whole months in a period, or null for day and week periods (and malformed counts). */
18
+ export declare function monthsIn(period: Period): number | null;
19
+ /**
20
+ * The per-month equivalent of a price, in micros rounded half up to the currency's minor unit.
21
+ * Only for periods longer than a month (design system: "the per-month equivalent for longer
22
+ * periods"); null otherwise, or when the currency is unknown.
23
+ */
24
+ export declare function perMonthMicros(price: DisplayPrice, period: Period): bigint | null;
25
+ /** The per-month equivalent as text: `$5.00/month`. Null when there isn't one. */
26
+ export declare function perMonthLabel(price: DisplayPrice, period: Period | null, locale: string): string | null;
27
+ /** A period as words: `year`, `month`, `3 months`, `2 weeks`. */
28
+ export declare function periodLabel(period: Period): string;
29
+ /** A period price: `$59.99/year`, `$29.99 every 3 months`, or just `$4.99` for one-time purchases. */
30
+ export declare function priceWithPeriod(price: DisplayPrice, period: Period | null): string;
31
+ /** A length as an adjective: `7-day`, `1-month`, `2-week`. */
32
+ export declare function durationAdjective(period: Period, periods?: number): string;
33
+ /** A length as a phrase: `3 months`, `1 week`. */
34
+ export declare function durationPhrase(period: Period, periods?: number): string;
35
+ /** Formats a whole count with grouping for `locale`: `1,000`. */
36
+ export declare function formatCount(value: number, locale: string): string;
37
+ /** Credits a product grants per purchase (or per period), from its first credit grant. */
38
+ export declare function creditsLabel(product: PaywallProduct, locale: string): string | null;
@@ -0,0 +1,124 @@
1
+ export function safeLocale(locale) {
2
+ if (!locale)
3
+ return 'en';
4
+ try {
5
+ return Intl.getCanonicalLocales(locale.replace(/_/g, '-'))[0] ?? 'en';
6
+ }
7
+ catch {
8
+ return 'en';
9
+ }
10
+ }
11
+ export function currencyDigits(currency) {
12
+ try {
13
+ const digits = new Intl.NumberFormat('en', {
14
+ style: 'currency',
15
+ currency,
16
+ }).resolvedOptions().maximumFractionDigits;
17
+ if (digits === undefined || !Number.isInteger(digits) || digits < 0 || digits > 6)
18
+ return null;
19
+ return digits;
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ function divRound(n, d) {
26
+ if (n < 0n)
27
+ return -divRound(-n, d);
28
+ return (n * 2n + d) / (2n * d);
29
+ }
30
+ export function formatMicros(micros, currency, locale) {
31
+ const digits = currencyDigits(currency);
32
+ if (digits === null)
33
+ return null;
34
+ const minor = divRound(micros < 0n ? -micros : micros, 10n ** BigInt(6 - digits));
35
+ const scale = 10n ** BigInt(digits);
36
+ const whole = (minor / scale).toString();
37
+ const decimal = digits === 0 ? whole : `${whole}.${(minor % scale).toString().padStart(digits, '0')}`;
38
+ try {
39
+ return new Intl.NumberFormat(safeLocale(locale), {
40
+ style: 'currency',
41
+ currency,
42
+ minimumFractionDigits: digits,
43
+ maximumFractionDigits: digits,
44
+ }).format(`${micros < 0n ? '-' : ''}${decimal}`);
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ export function monthsIn(period) {
51
+ if (!Number.isSafeInteger(period.count) || period.count < 1)
52
+ return null;
53
+ if (period.unit === 'year')
54
+ return period.count * 12;
55
+ if (period.unit === 'month')
56
+ return period.count;
57
+ return null;
58
+ }
59
+ export function perMonthMicros(price, period) {
60
+ const months = monthsIn(period);
61
+ if (months === null || months <= 1)
62
+ return null;
63
+ const digits = currencyDigits(price.currency);
64
+ if (digits === null)
65
+ return null;
66
+ const minorUnit = 10n ** BigInt(6 - digits);
67
+ return divRound(price.amountMicros, BigInt(months) * minorUnit) * minorUnit;
68
+ }
69
+ export function perMonthLabel(price, period, locale) {
70
+ if (!period)
71
+ return null;
72
+ const micros = perMonthMicros(price, period);
73
+ if (micros === null)
74
+ return null;
75
+ const formatted = formatMicros(micros, price.currency, locale);
76
+ return formatted === null ? null : `${formatted}/month`;
77
+ }
78
+ function unitWord(unit, count) {
79
+ return count === 1 ? unit : `${unit}s`;
80
+ }
81
+ function safeCount(count) {
82
+ return Number.isSafeInteger(count) && count > 0 ? count : 1;
83
+ }
84
+ export function periodLabel(period) {
85
+ const count = safeCount(period.count);
86
+ return count === 1 ? period.unit : `${count} ${unitWord(period.unit, count)}`;
87
+ }
88
+ export function priceWithPeriod(price, period) {
89
+ if (!period)
90
+ return price.formatted;
91
+ const count = safeCount(period.count);
92
+ return count === 1
93
+ ? `${price.formatted}/${period.unit}`
94
+ : `${price.formatted} every ${periodLabel(period)}`;
95
+ }
96
+ function total(period, periods) {
97
+ return { unit: period.unit, count: safeCount(period.count) * safeCount(periods) };
98
+ }
99
+ export function durationAdjective(period, periods = 1) {
100
+ const t = total(period, periods);
101
+ return `${t.count}-${t.unit}`;
102
+ }
103
+ export function durationPhrase(period, periods = 1) {
104
+ const t = total(period, periods);
105
+ return `${t.count} ${unitWord(t.unit, t.count)}`;
106
+ }
107
+ export function formatCount(value, locale) {
108
+ try {
109
+ return new Intl.NumberFormat(safeLocale(locale), { maximumFractionDigits: 0 }).format(value);
110
+ }
111
+ catch {
112
+ return String(value);
113
+ }
114
+ }
115
+ export function creditsLabel(product, locale) {
116
+ const grant = product.credits[0];
117
+ if (!grant || !Number.isFinite(grant.amount))
118
+ return null;
119
+ const amount = formatCount(grant.amount, locale);
120
+ const noun = grant.amount === 1 ? 'credit' : 'credits';
121
+ return grant.per === 'period' && product.period
122
+ ? `${amount} ${noun} every ${periodLabel(product.period)}`
123
+ : `${amount} ${noun}`;
124
+ }
@@ -0,0 +1,17 @@
1
+ import type { PaywallProduct } from '../controller';
2
+ /**
3
+ * The product selected when the paywall opens: the offering's highlighted product, else the
4
+ * first. Null when there are no products.
5
+ */
6
+ export declare function defaultProductKey(products: readonly PaywallProduct[]): string | null;
7
+ /**
8
+ * The selected product: the controller's selection when it names a product on offer, else the
9
+ * default. So exactly one option is selected whenever there are products.
10
+ */
11
+ export declare function selectedProduct(products: readonly PaywallProduct[], selectedKey: string | null): PaywallProduct | null;
12
+ /**
13
+ * The one product whose badge is shown. The badge is the paywall's single stamp element (design
14
+ * system: "One optional badge per paywall"), so only the highlighted product's badge shows, or the
15
+ * first badge when the highlighted product has none.
16
+ */
17
+ export declare function badgedProductKey(products: readonly PaywallProduct[]): string | null;
@@ -0,0 +1,13 @@
1
+ export function defaultProductKey(products) {
2
+ return (products.find((p) => p.highlighted) ?? products[0])?.key ?? null;
3
+ }
4
+ export function selectedProduct(products, selectedKey) {
5
+ const key = products.some((p) => p.key === selectedKey)
6
+ ? selectedKey
7
+ : defaultProductKey(products);
8
+ return products.find((p) => p.key === key) ?? null;
9
+ }
10
+ export function badgedProductKey(products) {
11
+ const highlighted = products.find((p) => p.highlighted && p.badge);
12
+ return (highlighted ?? products.find((p) => p.badge))?.key ?? null;
13
+ }
@@ -0,0 +1,46 @@
1
+ import type { ComponentType } from 'react';
2
+ import type { PaywallFeature } from '../components/FeatureList';
3
+ import type { PaywallProduct } from '../controller';
4
+ /** `header`: replaces the hero image, title and subtitle. */
5
+ export interface PaywallHeaderSlotProps {
6
+ title: string;
7
+ subtitle: string | null;
8
+ /**
9
+ * The hero image URL (https, from `controller.assets`), when the template shows one. In the
10
+ * editor's preview it can also be a `blob:` object URL from `previewAssets`.
11
+ */
12
+ heroImageUrl: string | null;
13
+ }
14
+ /**
15
+ * `productCard`: replaces each option row (design system "PaywallOption": a tenant "receives
16
+ * `{ product, selected, select }`"). It sits inside the paywall's radiogroup, so give it
17
+ * `accessibilityRole="radio"` and `accessibilityState={{ checked: selected }}`.
18
+ */
19
+ export interface PaywallProductCardSlotProps {
20
+ product: PaywallProduct;
21
+ selected: boolean;
22
+ select: () => void;
23
+ }
24
+ /** `featureList`: replaces the feature rows. Receives the localized features (possibly empty). */
25
+ export interface PaywallFeatureListSlotProps {
26
+ features: readonly PaywallFeature[];
27
+ }
28
+ /** `footer`: replaces Restore purchases and the legal links. URLs are already checked to be https. */
29
+ export interface PaywallFooterSlotProps {
30
+ /** Null when the config hides Restore purchases. */
31
+ restore: (() => void) | null;
32
+ restoring: boolean;
33
+ termsUrl: string | null;
34
+ privacyUrl: string | null;
35
+ }
36
+ /** `closeButton`: replaces the close button. Call `close` to dismiss. */
37
+ export interface PaywallCloseButtonSlotProps {
38
+ close: () => void;
39
+ }
40
+ export interface PaywallSlots {
41
+ header?: ComponentType<PaywallHeaderSlotProps>;
42
+ productCard?: ComponentType<PaywallProductCardSlotProps>;
43
+ featureList?: ComponentType<PaywallFeatureListSlotProps>;
44
+ footer?: ComponentType<PaywallFooterSlotProps>;
45
+ closeButton?: ComponentType<PaywallCloseButtonSlotProps>;
46
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ /** Design system "States and focus": the test-mode banner copy. */
2
+ export declare const TEST_MODE_MESSAGE = "Test mode. Purchases here use Apple Sandbox, Google license testers and Stripe test cards. Nothing is charged.";
3
+ /** Preview mode (Expo Go, or no native store). */
4
+ export declare const PREVIEW_MESSAGE = "Preview mode. Purchases are simulated on this device and nothing is charged.";
5
+ /** A purchase that's paid but whose access hasn't appeared yet. */
6
+ export declare const PENDING_MESSAGE = "Payment received. Your access will appear shortly.";
7
+ export declare const EMPTY_MESSAGE = "No products are available right now.";
8
+ export declare const LOAD_ERROR_MESSAGE = "This paywall couldn't load. Check your connection, then close it and try again.";
9
+ export declare const PURCHASE_FAILED_MESSAGE = "The purchase didn't go through and you weren't charged. Try again, or choose another option.";
10
+ export declare const RESTORED_MESSAGE = "Your purchases are restored.";
11
+ export declare const NOTHING_TO_RESTORE_MESSAGE = "There are no previous purchases to restore for this account. Restore on the account you bought with.";
12
+ export declare const RESTORE_FAILED_MESSAGE = "Purchases couldn't be restored. Check your connection and try again.";
13
+ export declare const LOADING_LABEL = "Loading";
@@ -0,0 +1,10 @@
1
+ export const TEST_MODE_MESSAGE = 'Test mode. Purchases here use Apple Sandbox, Google license testers and Stripe test cards. Nothing is charged.';
2
+ export const PREVIEW_MESSAGE = 'Preview mode. Purchases are simulated on this device and nothing is charged.';
3
+ export const PENDING_MESSAGE = 'Payment received. Your access will appear shortly.';
4
+ export const EMPTY_MESSAGE = 'No products are available right now.';
5
+ export const LOAD_ERROR_MESSAGE = "This paywall couldn't load. Check your connection, then close it and try again.";
6
+ export const PURCHASE_FAILED_MESSAGE = "The purchase didn't go through and you weren't charged. Try again, or choose another option.";
7
+ export const RESTORED_MESSAGE = 'Your purchases are restored.';
8
+ export const NOTHING_TO_RESTORE_MESSAGE = 'There are no previous purchases to restore for this account. Restore on the account you bought with.';
9
+ export const RESTORE_FAILED_MESSAGE = "Purchases couldn't be restored. Check your connection and try again.";
10
+ export const LOADING_LABEL = 'Loading';
@@ -0,0 +1,31 @@
1
+ import type { ComponentType } from 'react';
2
+ import type { PaywallProduct } from '../controller';
3
+ import type { PaywallTemplate } from '../schema/config';
4
+ import { type PaywallTemplateProps } from './PaywallScaffold';
5
+ /**
6
+ * The products a template shows. The hero template is a single-product paywall, so it shows the
7
+ * offering's highlighted product (else the first); the others show every product.
8
+ */
9
+ export declare function visibleProducts(template: PaywallTemplate, products: readonly PaywallProduct[]): readonly PaywallProduct[];
10
+ /**
11
+ * Multi-tier cards (the default template): the products as PaywallOption radio rows.
12
+ */
13
+ export declare function TiersTemplate(props: PaywallTemplateProps): import("react").JSX.Element;
14
+ /**
15
+ * Single-product hero: an optional hero image above the title, then the one product's price
16
+ * (period price in `figure-lg`, the trial or per-month equivalent in `body-sm` `ink-muted`).
17
+ * Render it with `visibleProducts('hero', …)` so the product shown is the one purchased.
18
+ */
19
+ export declare function HeroTemplate(props: PaywallTemplateProps): import("react").JSX.Element;
20
+ /**
21
+ * Comparison table: `copy.comparison` rows × the products, then the products as PaywallOption
22
+ * rows to choose from.
23
+ */
24
+ export declare function ComparisonTemplate(props: PaywallTemplateProps): import("react").JSX.Element;
25
+ /**
26
+ * Credit-pack grid: an optional hero image, then the packs as a two-column grid of tiles showing
27
+ * the credit amount and the store price.
28
+ */
29
+ export declare function CreditsTemplate(props: PaywallTemplateProps): import("react").JSX.Element;
30
+ /** Template components by config name. */
31
+ export declare const PAYWALL_TEMPLATES: Readonly<Record<PaywallTemplate, ComponentType<PaywallTemplateProps>>>;