@rocapine/react-native-onboarding 1.60.0 → 1.62.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.
Files changed (173) hide show
  1. package/dist/OnboardingStudioClient.d.ts +23 -5
  2. package/dist/OnboardingStudioClient.d.ts.map +1 -1
  3. package/dist/OnboardingStudioClient.js +82 -6
  4. package/dist/OnboardingStudioClient.js.map +1 -1
  5. package/dist/index.d.ts +6 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +8 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/infra/provider/OnboardingProvider.d.ts +37 -1
  10. package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
  11. package/dist/infra/provider/OnboardingProvider.js +76 -2
  12. package/dist/infra/provider/OnboardingProvider.js.map +1 -1
  13. package/dist/infra/queries/cacheKey.d.ts +22 -4
  14. package/dist/infra/queries/cacheKey.d.ts.map +1 -1
  15. package/dist/infra/queries/cacheKey.js +26 -5
  16. package/dist/infra/queries/cacheKey.js.map +1 -1
  17. package/dist/paywalls/PaywallProvider.d.ts +66 -0
  18. package/dist/paywalls/PaywallProvider.d.ts.map +1 -0
  19. package/dist/paywalls/PaywallProvider.js +227 -0
  20. package/dist/paywalls/PaywallProvider.js.map +1 -0
  21. package/dist/paywalls/getPaywalls.query.d.ts +37 -0
  22. package/dist/paywalls/getPaywalls.query.d.ts.map +1 -0
  23. package/dist/paywalls/getPaywalls.query.js +114 -0
  24. package/dist/paywalls/getPaywalls.query.js.map +1 -0
  25. package/dist/paywalls/present.d.ts +100 -0
  26. package/dist/paywalls/present.d.ts.map +1 -0
  27. package/dist/paywalls/present.js +113 -0
  28. package/dist/paywalls/present.js.map +1 -0
  29. package/dist/paywalls/types.d.ts +95 -0
  30. package/dist/paywalls/types.d.ts.map +1 -0
  31. package/dist/paywalls/types.js +10 -0
  32. package/dist/paywalls/types.js.map +1 -0
  33. package/dist/paywalls/usePaywall.d.ts +29 -0
  34. package/dist/paywalls/usePaywall.d.ts.map +1 -0
  35. package/dist/paywalls/usePaywall.js +17 -0
  36. package/dist/paywalls/usePaywall.js.map +1 -0
  37. package/dist/products/ProductRuntimeContext.d.ts +15 -0
  38. package/dist/products/ProductRuntimeContext.d.ts.map +1 -0
  39. package/dist/products/ProductRuntimeContext.js +19 -0
  40. package/dist/products/ProductRuntimeContext.js.map +1 -0
  41. package/dist/products/adapters/expoIap.d.ts +4 -0
  42. package/dist/products/adapters/expoIap.d.ts.map +1 -0
  43. package/dist/products/adapters/expoIap.js +95 -0
  44. package/dist/products/adapters/expoIap.js.map +1 -0
  45. package/dist/products/adapters/revenueCat.d.ts +7 -0
  46. package/dist/products/adapters/revenueCat.d.ts.map +1 -0
  47. package/dist/products/adapters/revenueCat.js +116 -0
  48. package/dist/products/adapters/revenueCat.js.map +1 -0
  49. package/dist/products/adapters/stub.d.ts +8 -0
  50. package/dist/products/adapters/stub.d.ts.map +1 -0
  51. package/dist/products/adapters/stub.js +21 -0
  52. package/dist/products/adapters/stub.js.map +1 -0
  53. package/dist/products/derive.d.ts +19 -0
  54. package/dist/products/derive.d.ts.map +1 -0
  55. package/dist/products/derive.js +79 -0
  56. package/dist/products/derive.js.map +1 -0
  57. package/dist/products/duration.d.ts +3 -0
  58. package/dist/products/duration.d.ts.map +1 -0
  59. package/dist/products/duration.js +25 -0
  60. package/dist/products/duration.js.map +1 -0
  61. package/dist/products/index.d.ts +10 -0
  62. package/dist/products/index.d.ts.map +1 -0
  63. package/dist/products/index.js +23 -0
  64. package/dist/products/index.js.map +1 -0
  65. package/dist/products/mergeProductRuntimes.d.ts +55 -0
  66. package/dist/products/mergeProductRuntimes.d.ts.map +1 -0
  67. package/dist/products/mergeProductRuntimes.js +79 -0
  68. package/dist/products/mergeProductRuntimes.js.map +1 -0
  69. package/dist/products/toVariables.d.ts +18 -0
  70. package/dist/products/toVariables.d.ts.map +1 -0
  71. package/dist/products/toVariables.js +52 -0
  72. package/dist/products/toVariables.js.map +1 -0
  73. package/dist/products/types.d.ts +96 -0
  74. package/dist/products/types.d.ts.map +1 -0
  75. package/dist/products/types.js +3 -0
  76. package/dist/products/types.js.map +1 -0
  77. package/dist/products/useProducts.d.ts +12 -0
  78. package/dist/products/useProducts.d.ts.map +1 -0
  79. package/dist/products/useProducts.js +90 -0
  80. package/dist/products/useProducts.js.map +1 -0
  81. package/dist/screens/elements/AnimatedTextElement.d.ts +1 -24
  82. package/dist/screens/elements/AnimatedTextElement.d.ts.map +1 -1
  83. package/dist/screens/elements/BaseBoxProps.d.ts +1 -24
  84. package/dist/screens/elements/BaseBoxProps.d.ts.map +1 -1
  85. package/dist/screens/elements/ButtonElement.d.ts +6 -121
  86. package/dist/screens/elements/ButtonElement.d.ts.map +1 -1
  87. package/dist/screens/elements/CarouselElement.d.ts +1 -24
  88. package/dist/screens/elements/CarouselElement.d.ts.map +1 -1
  89. package/dist/screens/elements/CheckboxGroupElement.d.ts +1 -24
  90. package/dist/screens/elements/CheckboxGroupElement.d.ts.map +1 -1
  91. package/dist/screens/elements/DatePickerElement.d.ts +1 -24
  92. package/dist/screens/elements/DatePickerElement.d.ts.map +1 -1
  93. package/dist/screens/elements/DrawingPadElement.d.ts +1 -24
  94. package/dist/screens/elements/DrawingPadElement.d.ts.map +1 -1
  95. package/dist/screens/elements/IconElement.d.ts +1 -24
  96. package/dist/screens/elements/IconElement.d.ts.map +1 -1
  97. package/dist/screens/elements/ImageElement.d.ts +1 -24
  98. package/dist/screens/elements/ImageElement.d.ts.map +1 -1
  99. package/dist/screens/elements/InputElement.d.ts +1 -24
  100. package/dist/screens/elements/InputElement.d.ts.map +1 -1
  101. package/dist/screens/elements/KeyboardAvoidingViewElement.d.ts +1 -24
  102. package/dist/screens/elements/KeyboardAvoidingViewElement.d.ts.map +1 -1
  103. package/dist/screens/elements/LottieElement.d.ts +1 -24
  104. package/dist/screens/elements/LottieElement.d.ts.map +1 -1
  105. package/dist/screens/elements/ProgressIndicatorElement.d.ts +1 -24
  106. package/dist/screens/elements/ProgressIndicatorElement.d.ts.map +1 -1
  107. package/dist/screens/elements/ProgressiveBlurImageElement.d.ts +1 -24
  108. package/dist/screens/elements/ProgressiveBlurImageElement.d.ts.map +1 -1
  109. package/dist/screens/elements/RadioGroupElement.d.ts +1 -24
  110. package/dist/screens/elements/RadioGroupElement.d.ts.map +1 -1
  111. package/dist/screens/elements/RichTextElement.d.ts +1 -24
  112. package/dist/screens/elements/RichTextElement.d.ts.map +1 -1
  113. package/dist/screens/elements/RiveElement.d.ts +1 -24
  114. package/dist/screens/elements/RiveElement.d.ts.map +1 -1
  115. package/dist/screens/elements/SafeAreaViewElement.d.ts +1 -24
  116. package/dist/screens/elements/SafeAreaViewElement.d.ts.map +1 -1
  117. package/dist/screens/elements/ScrollViewElement.d.ts +1 -24
  118. package/dist/screens/elements/ScrollViewElement.d.ts.map +1 -1
  119. package/dist/screens/elements/SliderElement.d.ts +1 -24
  120. package/dist/screens/elements/SliderElement.d.ts.map +1 -1
  121. package/dist/screens/elements/StackElement.d.ts +1 -24
  122. package/dist/screens/elements/StackElement.d.ts.map +1 -1
  123. package/dist/screens/elements/TextElement.d.ts +1 -24
  124. package/dist/screens/elements/TextElement.d.ts.map +1 -1
  125. package/dist/screens/elements/TypewriterTextElement.d.ts +1 -24
  126. package/dist/screens/elements/TypewriterTextElement.d.ts.map +1 -1
  127. package/dist/screens/elements/VideoElement.d.ts +1 -24
  128. package/dist/screens/elements/VideoElement.d.ts.map +1 -1
  129. package/dist/screens/elements/WheelPickerElement.d.ts +1 -24
  130. package/dist/screens/elements/WheelPickerElement.d.ts.map +1 -1
  131. package/dist/screens/elements/ZStackElement.d.ts +1 -24
  132. package/dist/screens/elements/ZStackElement.d.ts.map +1 -1
  133. package/dist/steps/Carousel/types.d.ts +1 -1
  134. package/dist/steps/Commitment/types.d.ts +1 -1
  135. package/dist/steps/ComposableScreen/types.d.ts +1 -1
  136. package/dist/steps/Loader/types.d.ts +1 -1
  137. package/dist/steps/MediaContent/types.d.ts +1 -1
  138. package/dist/steps/Picker/types.d.ts +1 -1
  139. package/dist/steps/Question/types.d.ts +1 -1
  140. package/dist/steps/Ratings/types.d.ts +1 -1
  141. package/dist/steps/common.types.d.ts +44 -30
  142. package/dist/steps/common.types.d.ts.map +1 -1
  143. package/dist/steps/common.types.js +27 -3
  144. package/dist/steps/common.types.js.map +1 -1
  145. package/package.json +1 -1
  146. package/src/OnboardingStudioClient.ts +110 -7
  147. package/src/__tests__/mergeProductRuntimes.test.ts +172 -0
  148. package/src/__tests__/productAdapters.test.ts +58 -0
  149. package/src/__tests__/productDerive.test.ts +111 -0
  150. package/src/__tests__/productVariables.test.ts +109 -0
  151. package/src/__tests__/resolveLocalProductArgs.test.ts +41 -0
  152. package/src/index.ts +14 -0
  153. package/src/infra/provider/OnboardingProvider.tsx +101 -2
  154. package/src/infra/queries/cacheKey.ts +27 -4
  155. package/src/paywalls/PaywallProvider.tsx +342 -0
  156. package/src/paywalls/__tests__/getPaywalls.test.ts +334 -0
  157. package/src/paywalls/__tests__/present.test.ts +190 -0
  158. package/src/paywalls/getPaywalls.query.ts +123 -0
  159. package/src/paywalls/present.ts +141 -0
  160. package/src/paywalls/types.ts +99 -0
  161. package/src/paywalls/usePaywall.ts +35 -0
  162. package/src/products/ProductRuntimeContext.tsx +17 -0
  163. package/src/products/adapters/expoIap.ts +93 -0
  164. package/src/products/adapters/revenueCat.ts +108 -0
  165. package/src/products/adapters/stub.ts +20 -0
  166. package/src/products/derive.ts +93 -0
  167. package/src/products/duration.ts +21 -0
  168. package/src/products/index.ts +20 -0
  169. package/src/products/mergeProductRuntimes.ts +78 -0
  170. package/src/products/toVariables.ts +54 -0
  171. package/src/products/types.ts +88 -0
  172. package/src/products/useProducts.ts +106 -0
  173. package/src/steps/common.types.ts +83 -6
@@ -0,0 +1,93 @@
1
+ import { Platform } from "react-native";
2
+ import type { ProductProvider, ProductRef, ProductPeriod, ResolvedProduct } from "../types";
3
+
4
+ // Optional peer: expo-iap. Same dynamic-require pattern as elements/haptics.ts.
5
+ let IAP: any;
6
+ try {
7
+ IAP = require("expo-iap");
8
+ } catch {
9
+ IAP = null;
10
+ }
11
+
12
+ const toPeriod = (iso: string | null | undefined): { period: ProductPeriod | null; count: number } => {
13
+ if (!iso) return { period: null, count: 0 };
14
+ const m = /^P(\d+)([DWMY])$/.exec(iso);
15
+ if (!m) return { period: null, count: 0 };
16
+ const map: Record<string, ProductPeriod> = { D: "week", W: "week", M: "month", Y: "year" };
17
+ return { period: map[m[2]] ?? null, count: Number(m[1]) };
18
+ };
19
+
20
+ // expo-iap surfaces a user cancellation as a code rather than a typed error.
21
+ const isCancellation = (e: any): boolean =>
22
+ e?.code === "E_USER_CANCELLED" || e?.code === "USER_CANCELED" || e?.userCancelled === true;
23
+
24
+ const idFor = (ref: ProductRef): string | undefined =>
25
+ Platform.OS === "ios" ? ref.ios : ref.android;
26
+
27
+ /** Direct StoreKit / Play Billing provider, no vendor in the path. */
28
+ export const expoIapProductProvider = (Iap: any = IAP): ProductProvider => {
29
+ const required = () => {
30
+ if (!Iap) {
31
+ throw new Error(
32
+ "expoIapProductProvider: expo-iap is not installed. Install it, or pass a different ProductProvider."
33
+ );
34
+ }
35
+ return Iap;
36
+ };
37
+
38
+ return {
39
+ async getProducts(refs: ProductRef[]): Promise<ResolvedProduct[]> {
40
+ const M = required();
41
+ const wanted = refs.map((r) => ({ ref: r, id: idFor(r) })).filter((x) => !!x.id);
42
+ if (wanted.length === 0) return [];
43
+ const skus = wanted.map((w) => w.id as string);
44
+ const store = await M.getProducts(skus);
45
+ const byId = new Map<string, any>(store.map((s: any) => [s.id ?? s.productId, s]));
46
+ const out: ResolvedProduct[] = [];
47
+ for (const { ref, id } of wanted) {
48
+ const s = byId.get(id as string);
49
+ if (!s) continue;
50
+ const iso = s.subscriptionPeriodISO ?? s.subscriptionPeriod ?? null;
51
+ const { period, count } = toPeriod(iso);
52
+ out.push({
53
+ key: ref.key,
54
+ productId: s.id ?? s.productId,
55
+ store: Platform.OS === "ios" ? "app_store" : "play_store",
56
+ title: s.title ?? "",
57
+ description: s.description ?? "",
58
+ price: s.displayPrice ?? s.localizedPrice ?? "",
59
+ priceAmount: Number(s.price ?? 0),
60
+ currencyCode: s.currency ?? s.currencyCode ?? "",
61
+ period,
62
+ periodCount: count,
63
+ periodIso: iso,
64
+ });
65
+ }
66
+ return out;
67
+ },
68
+
69
+ async purchase(product) {
70
+ const M = required();
71
+ try {
72
+ await M.requestPurchase({ request: { sku: product.productId } });
73
+ return { status: "purchased", productKey: product.key };
74
+ } catch (e: any) {
75
+ if (isCancellation(e)) return { status: "cancelled" };
76
+ return { status: "error", error: e instanceof Error ? e : new Error(String(e)) };
77
+ }
78
+ },
79
+
80
+ async restore() {
81
+ const M = required();
82
+ try {
83
+ const purchases = await M.getAvailablePurchases();
84
+ const ids: string[] = (purchases ?? []).map((p: any) => p.id ?? p.productId).filter(Boolean);
85
+ return ids.length > 0
86
+ ? { status: "restored", entitlements: ids }
87
+ : { status: "nothing_to_restore" };
88
+ } catch (e) {
89
+ return { status: "error", error: e instanceof Error ? e : new Error(String(e)) };
90
+ }
91
+ },
92
+ };
93
+ };
@@ -0,0 +1,108 @@
1
+ import { Platform } from "react-native";
2
+ import type { ProductProvider, ProductRef, ProductPeriod, ResolvedProduct } from "../types";
3
+
4
+ // Optional peer: react-native-purchases. Same dynamic-require pattern as
5
+ // elements/haptics.ts — absent is not a crash, it is a clear error at call time.
6
+ let RC: any;
7
+ try {
8
+ RC = require("react-native-purchases");
9
+ } catch {
10
+ RC = null;
11
+ }
12
+
13
+ const PERIOD_UNIT: Record<string, ProductPeriod> = {
14
+ DAY: "week", WEEK: "week", MONTH: "month", YEAR: "year",
15
+ };
16
+
17
+ const toPeriod = (iso: string | null | undefined): { period: ProductPeriod | null; count: number } => {
18
+ if (!iso) return { period: null, count: 0 };
19
+ const m = /^P(\d+)([DWMY])$/.exec(iso);
20
+ if (!m) return { period: null, count: 0 };
21
+ const unit = { D: "DAY", W: "WEEK", M: "MONTH", Y: "YEAR" }[m[2]]!;
22
+ return { period: PERIOD_UNIT[unit] ?? null, count: Number(m[1]) };
23
+ };
24
+
25
+ const idFor = (ref: ProductRef): string | undefined =>
26
+ Platform.OS === "ios" ? ref.ios : ref.android;
27
+
28
+ /**
29
+ * RevenueCat-backed provider. Pass the `Purchases` module explicitly if you have
30
+ * a custom instance; otherwise the installed one is used.
31
+ */
32
+ export const revenueCatProductProvider = (Purchases: any = RC?.default ?? RC): ProductProvider => {
33
+ const required = () => {
34
+ if (!Purchases) {
35
+ throw new Error(
36
+ "revenueCatProductProvider: react-native-purchases is not installed. Install it, or pass a different ProductProvider."
37
+ );
38
+ }
39
+ return Purchases;
40
+ };
41
+
42
+ return {
43
+ async getProducts(refs: ProductRef[]): Promise<ResolvedProduct[]> {
44
+ const P = required();
45
+ const wanted = refs.map((r) => ({ ref: r, id: idFor(r) })).filter((x) => !!x.id);
46
+ if (wanted.length === 0) return [];
47
+ const store = await P.getProducts(wanted.map((w) => w.id as string));
48
+ const byId = new Map<string, any>(store.map((s: any) => [s.identifier, s]));
49
+ const out: ResolvedProduct[] = [];
50
+ for (const { ref, id } of wanted) {
51
+ const s = byId.get(id as string);
52
+ if (!s) continue;
53
+ const { period, count } = toPeriod(s.subscriptionPeriod);
54
+ out.push({
55
+ key: ref.key,
56
+ productId: s.identifier,
57
+ store: Platform.OS === "ios" ? "app_store" : "play_store",
58
+ title: s.title ?? "",
59
+ description: s.description ?? "",
60
+ price: s.priceString,
61
+ priceAmount: s.price,
62
+ currencyCode: s.currencyCode,
63
+ period,
64
+ periodCount: count,
65
+ periodIso: s.subscriptionPeriod ?? null,
66
+ trial: s.introPrice && s.introPrice.price === 0
67
+ ? {
68
+ period: toPeriod(s.introPrice.periodISO).period ?? "week",
69
+ periodCount: toPeriod(s.introPrice.periodISO).count,
70
+ days: 0,
71
+ }
72
+ : undefined,
73
+ });
74
+ }
75
+ return out;
76
+ },
77
+
78
+ async purchase(product) {
79
+ const P = required();
80
+ try {
81
+ const store = await P.getProducts([product.productId]);
82
+ if (!store[0]) return { status: "error", error: new Error(`Unknown product ${product.productId}`) };
83
+ const res = await P.purchaseStoreProduct(store[0]);
84
+ return {
85
+ status: "purchased",
86
+ productKey: product.key,
87
+ entitlements: Object.keys(res?.customerInfo?.entitlements?.active ?? {}),
88
+ };
89
+ } catch (e: any) {
90
+ if (e?.userCancelled) return { status: "cancelled" };
91
+ return { status: "error", error: e instanceof Error ? e : new Error(String(e)) };
92
+ }
93
+ },
94
+
95
+ async restore() {
96
+ const P = required();
97
+ try {
98
+ const info = await P.restorePurchases();
99
+ const ents = Object.keys(info?.entitlements?.active ?? {});
100
+ return ents.length > 0
101
+ ? { status: "restored", entitlements: ents }
102
+ : { status: "nothing_to_restore" };
103
+ } catch (e) {
104
+ return { status: "error", error: e instanceof Error ? e : new Error(String(e)) };
105
+ }
106
+ },
107
+ };
108
+ };
@@ -0,0 +1,20 @@
1
+ import type { ProductProvider, ProductRef, ResolvedProduct } from "../types";
2
+
3
+ /**
4
+ * In-memory provider for demos, tests, and studio previews. NEVER ship a paywall
5
+ * backed by this — its prices are invented, and App Review rejects a paywall
6
+ * whose displayed price does not match the store.
7
+ */
8
+ export const stubProductProvider = (
9
+ catalog: Record<string, Omit<ResolvedProduct, "key">>
10
+ ): ProductProvider => ({
11
+ async getProducts(refs: ProductRef[]): Promise<ResolvedProduct[]> {
12
+ return refs.filter((r) => catalog[r.key]).map((r) => ({ key: r.key, ...catalog[r.key] }));
13
+ },
14
+ async purchase(product) {
15
+ return { status: "purchased", productKey: product.key };
16
+ },
17
+ async restore() {
18
+ return { status: "nothing_to_restore" };
19
+ },
20
+ });
@@ -0,0 +1,93 @@
1
+ import { parseIsoDuration } from "./duration";
2
+ import type {
3
+ DerivedProductFields,
4
+ ProductRef,
5
+ ProductWithDerived,
6
+ ResolvedProduct,
7
+ } from "./types";
8
+
9
+ /**
10
+ * Format in the PRODUCT's currency, not the device's. Falls back to a plain
11
+ * `amount currencyCode` string if Intl rejects the code, so a bad code degrades
12
+ * to something readable instead of throwing mid-render.
13
+ */
14
+ export const formatCurrency = (
15
+ amount: number,
16
+ currencyCode: string,
17
+ locale?: string
18
+ ): string => {
19
+ try {
20
+ return new Intl.NumberFormat(locale, {
21
+ style: "currency",
22
+ currency: currencyCode,
23
+ }).format(amount);
24
+ } catch {
25
+ return `${amount.toFixed(2)} ${currencyCode}`;
26
+ }
27
+ };
28
+
29
+ const perDay = (p: ResolvedProduct): number | null => {
30
+ const days = parseIsoDuration(p.periodIso);
31
+ if (!days || days <= 0) return null;
32
+ return p.priceAmount / days;
33
+ };
34
+
35
+ /**
36
+ * Derived fields for one product. `compareTo` enables `savingsPct`, computed on
37
+ * a normalized per-day basis so a yearly plan can be compared to a monthly one.
38
+ * These are FRAMING values ("$1.15/week"), never presented as the charged amount.
39
+ */
40
+ export const deriveProductFields = (
41
+ p: ResolvedProduct,
42
+ opts: { compareTo?: ResolvedProduct; locale?: string } = {}
43
+ ): DerivedProductFields => {
44
+ const { compareTo, locale } = opts;
45
+ const out: DerivedProductFields = {};
46
+
47
+ const daily = perDay(p);
48
+ if (daily != null) {
49
+ const week = daily * 7;
50
+ const month = daily * 30;
51
+ const year = daily * 365;
52
+ out.pricePerWeekAmount = week;
53
+ out.pricePerWeek = formatCurrency(week, p.currencyCode, locale);
54
+ out.pricePerMonthAmount = month;
55
+ out.pricePerMonth = formatCurrency(month, p.currencyCode, locale);
56
+ out.pricePerYearAmount = year;
57
+ out.pricePerYear = formatCurrency(year, p.currencyCode, locale);
58
+ }
59
+
60
+ if (compareTo) {
61
+ const otherDaily = perDay(compareTo);
62
+ if (daily != null && otherDaily != null && otherDaily > 0 && daily < otherDaily) {
63
+ out.savingsPct = Math.round((1 - daily / otherDaily) * 100);
64
+ }
65
+ }
66
+
67
+ if (p.trial) {
68
+ const days =
69
+ p.trial.days > 0
70
+ ? p.trial.days
71
+ : (parseIsoDuration(`P${p.trial.periodCount}${p.trial.period === "week" ? "W" : p.trial.period === "month" ? "M" : p.trial.period === "year" ? "Y" : "D"}`) ?? 0);
72
+ if (days > 0) out.trialDays = days;
73
+ }
74
+
75
+ return out;
76
+ };
77
+
78
+ /** Derive every product, keyed by its ref key, resolving `compareTo` between them. */
79
+ export const deriveAll = (
80
+ products: ResolvedProduct[],
81
+ refs: ProductRef[],
82
+ locale?: string
83
+ ): Record<string, ProductWithDerived> => {
84
+ const byKey = new Map(products.map((p) => [p.key, p]));
85
+ const out: Record<string, ProductWithDerived> = {};
86
+ for (const ref of refs) {
87
+ const p = byKey.get(ref.key);
88
+ if (!p) continue;
89
+ const compareTo = ref.compareTo ? byKey.get(ref.compareTo) : undefined;
90
+ out[ref.key] = { ...p, ...deriveProductFields(p, { compareTo, locale }) };
91
+ }
92
+ return out;
93
+ };
@@ -0,0 +1,21 @@
1
+ // Store-standard ISO-8601 subscription periods only: P1W / P1M / P3M / P1Y / P7D.
2
+ // Time components (PT1H) are not subscription periods and are rejected rather
3
+ // than silently coerced — a wrong period would corrupt every per-period price.
4
+ const ISO_PERIOD = /^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?$/;
5
+
6
+ const DAYS_PER = { year: 365, month: 30, week: 7, day: 1 } as const;
7
+
8
+ /** ISO-8601 period → whole days. `null` when unparseable or empty (bare "P"). */
9
+ export const parseIsoDuration = (iso: string | null | undefined): number | null => {
10
+ if (!iso) return null;
11
+ const m = ISO_PERIOD.exec(iso);
12
+ if (!m) return null;
13
+ const [, y, mo, w, d] = m;
14
+ if (!y && !mo && !w && !d) return null;
15
+ return (
16
+ Number(y ?? 0) * DAYS_PER.year +
17
+ Number(mo ?? 0) * DAYS_PER.month +
18
+ Number(w ?? 0) * DAYS_PER.week +
19
+ Number(d ?? 0) * DAYS_PER.day
20
+ );
21
+ };
@@ -0,0 +1,20 @@
1
+ export type {
2
+ ProductRef,
3
+ ProductPeriod,
4
+ ResolvedProduct,
5
+ DerivedProductFields,
6
+ ProductWithDerived,
7
+ PurchaseResult,
8
+ RestoreResult,
9
+ ProductProvider,
10
+ ProductStatus,
11
+ ProductRuntime,
12
+ } from "./types";
13
+ export { parseIsoDuration } from "./duration";
14
+ export { formatCurrency, deriveProductFields, deriveAll } from "./derive";
15
+ export { productVariables } from "./toVariables";
16
+ export { useProducts } from "./useProducts";
17
+ export { ProductRuntimeContext, useProductRuntime } from "./ProductRuntimeContext";
18
+ export { stubProductProvider } from "./adapters/stub";
19
+ export { revenueCatProductProvider } from "./adapters/revenueCat";
20
+ export { expoIapProductProvider } from "./adapters/expoIap";
@@ -0,0 +1,78 @@
1
+ import type { ProductRuntime, ProductStatus } from "./types";
2
+
3
+ const mergeStatus = (a: ProductStatus, b: ProductStatus): ProductStatus => {
4
+ if (a === "error" || b === "error") return "error";
5
+ if (a === "ready" && b === "ready") return "ready";
6
+ if (a === "loading" || b === "loading") return "loading";
7
+ return "idle";
8
+ };
9
+
10
+ /**
11
+ * Publishes ONE `ProductRuntime` out of the shared context runtime (a
12
+ * `PaywallProvider` ancestor's catalog union) and this `OnboardingProvider`'s
13
+ * own local resolution of its `productRefs` prop.
14
+ *
15
+ * Finding 5, 2026-08-17 final review: `OnboardingProvider` used to zero the
16
+ * local ref set out entirely whenever a context runtime existed, on the
17
+ * assumption that the paywall catalog's product union is always a superset of
18
+ * whatever `productRefs` the host declares — an assumption about a
19
+ * host-supplied prop, not a property of the code. That silently broke a
20
+ * documented Phase 3 prop the moment a host added a `PaywallProvider` above
21
+ * an existing `OnboardingProvider`: `productRefs` keys absent from the
22
+ * catalog union resolved to nothing, with no error and nothing that
23
+ * type-checks. `productRefs` is therefore ALWAYS resolved locally now,
24
+ * regardless of whether a context runtime exists (see
25
+ * `resolveLocalProductArgs`) — this function unions the result back into the
26
+ * one `ProductRuntime` the rest of the app reads.
27
+ *
28
+ * **Callers MUST memoize this** (`OnboardingProvider.tsx` wraps it in
29
+ * `useMemo`, keyed on the four arguments) — round 2 of the final review (N1)
30
+ * found the object literal below allocated fresh, plus a fresh `purchase`
31
+ * closure, on every call, which breaks `ScreenHost.products`'s "referentially
32
+ * stable across variable writes" contract when called inline in a render
33
+ * body.
34
+ *
35
+ * Returns `contextRuntime` UNCHANGED when there is nothing local to add
36
+ * (`hasLocalRefs` false — the common case: no host-declared `productRefs`),
37
+ * so the well-established "one shared runtime, no local round trip" identity
38
+ * and behavior is untouched for every app that doesn't use this prop.
39
+ *
40
+ * `purchase` routes by key: a key resolved by the LOCAL runtime purchases
41
+ * through the local provider (it is the only one that resolved it); anything
42
+ * else — including an unknown key — goes through the context runtime, which
43
+ * already reports "No resolved product for key" for that case (`useProducts.
44
+ * purchase`), so no separate handling is needed here. `restore` delegates to
45
+ * the context runtime only: restoring is a whole store-account operation, not
46
+ * scoped to individual refs, so one call through the shared adapter is
47
+ * correct even with a local ref set also present — the same billing adapter
48
+ * type is the expected real-world setup for both `productProvider` props.
49
+ *
50
+ * `hasLocalProvider` (N3, round 2): a host can declare `productRefs` with NO
51
+ * local `productProvider` — nothing unusual, since the shared context runtime
52
+ * is normally expected to cover everything. `useProducts` then never leaves
53
+ * `"idle"` for the local runtime (it bails before ever calling a provider it
54
+ * doesn't have — `useProducts.ts`), and a naive `mergeStatus` would drag the
55
+ * context runtime's `"ready"` down to `"idle"` FOREVER, closing every
56
+ * `renderWhen: {"products.loaded": {eq:"true"}}` gate for good — the same
57
+ * "idle blocks readiness when there's nothing to actually wait for" trap
58
+ * `computeIsReady` (`present.ts`) already special-cases for an empty ref set.
59
+ * When there is no local provider, the local runtime has nothing pending, so
60
+ * the merged status is just the context runtime's.
61
+ */
62
+ export const mergeProductRuntimes = (
63
+ contextRuntime: ProductRuntime,
64
+ localRuntime: ProductRuntime,
65
+ hasLocalRefs: boolean,
66
+ hasLocalProvider: boolean
67
+ ): ProductRuntime => {
68
+ if (!hasLocalRefs) return contextRuntime;
69
+ return {
70
+ products: { ...contextRuntime.products, ...localRuntime.products },
71
+ status: hasLocalProvider ? mergeStatus(contextRuntime.status, localRuntime.status) : contextRuntime.status,
72
+ error: contextRuntime.error ?? localRuntime.error,
73
+ purchasing: contextRuntime.purchasing || localRuntime.purchasing,
74
+ purchase: (key: string) =>
75
+ key in localRuntime.products ? localRuntime.purchase(key) : contextRuntime.purchase(key),
76
+ restore: contextRuntime.restore,
77
+ };
78
+ };
@@ -0,0 +1,54 @@
1
+ import type { ComposableVariableEntry } from "../steps/ComposableScreen/types";
2
+ import type { ProductRuntime } from "./types";
3
+
4
+ /**
5
+ * Resolved products → the variable bag, as FLAT DOTTED KEYS
6
+ * (`product.yearly.pricePerWeek`). `interpolate()` resolves `{{key}}` with a
7
+ * flat `variables[key]` lookup and `evaluateCondition` reads `flatVariables`
8
+ * the same way, so this needs no engine change.
9
+ *
10
+ * Optional fields are OMITTED when absent rather than emitted empty: a missing
11
+ * key interpolates to "" anyway, but `evaluateCondition`'s `is_empty`/
12
+ * `is_not_empty` treat an empty string identically to a missing key, so that
13
+ * pair doesn't actually depend on this. It's `is_null`/`is_not_null` that do —
14
+ * they only treat null/undefined as null, so an emitted `""` would read as
15
+ * "not null" — so omitting is what makes
16
+ * `renderWhen: { "product.x.savingsPct": { is_not_null: true } }` behave.
17
+ */
18
+ export const productVariables = (
19
+ runtime: Pick<ProductRuntime, "products" | "status" | "error" | "purchasing">
20
+ ): Record<string, ComposableVariableEntry> => {
21
+ const out: Record<string, ComposableVariableEntry> = {};
22
+
23
+ const put = (key: string, value: string | number | undefined | null) => {
24
+ if (value === undefined || value === null) return;
25
+ out[key] = { value: String(value) };
26
+ };
27
+
28
+ for (const [key, p] of Object.entries(runtime.products)) {
29
+ const b = `product.${key}`;
30
+ put(`${b}.productId`, p.productId);
31
+ put(`${b}.title`, p.title);
32
+ put(`${b}.description`, p.description);
33
+ put(`${b}.price`, p.price);
34
+ put(`${b}.priceAmount`, p.priceAmount);
35
+ put(`${b}.currencyCode`, p.currencyCode);
36
+ put(`${b}.period`, p.period);
37
+ put(`${b}.periodCount`, p.periodCount);
38
+ put(`${b}.pricePerWeek`, p.pricePerWeek);
39
+ put(`${b}.pricePerWeekAmount`, p.pricePerWeekAmount);
40
+ put(`${b}.pricePerMonth`, p.pricePerMonth);
41
+ put(`${b}.pricePerMonthAmount`, p.pricePerMonthAmount);
42
+ put(`${b}.pricePerYear`, p.pricePerYear);
43
+ put(`${b}.pricePerYearAmount`, p.pricePerYearAmount);
44
+ put(`${b}.savingsPct`, p.savingsPct);
45
+ put(`${b}.trialDays`, p.trialDays);
46
+ put(`${b}.introPrice`, p.introOffer?.price);
47
+ }
48
+
49
+ out["products.loaded"] = { value: runtime.status === "ready" ? "true" : "false" };
50
+ out["products.purchasing"] = { value: runtime.purchasing ? "true" : "false" };
51
+ out["products.error"] = { value: runtime.error ?? "" };
52
+
53
+ return out;
54
+ };
@@ -0,0 +1,88 @@
1
+ /** A product slot declared by the author: a stable key plus per-store ids. */
2
+ export type ProductRef = {
3
+ /** Author-chosen slot name used in variables, e.g. "yearly" → product.yearly.price */
4
+ key: string;
5
+ /** App Store product identifier. */
6
+ ios?: string;
7
+ /** Play product identifier. `productId:basePlanId` — RevenueCat's convention. */
8
+ android?: string;
9
+ /** Another slot's key; savingsPct is computed against it. */
10
+ compareTo?: string;
11
+ };
12
+
13
+ export type ProductPeriod = "week" | "month" | "year" | "lifetime";
14
+
15
+ /** A product as the store reports it. Prices here are authoritative. */
16
+ export type ResolvedProduct = {
17
+ key: string;
18
+ /** The identifier resolved for THIS platform. */
19
+ productId: string;
20
+ store: "app_store" | "play_store";
21
+ title: string;
22
+ description: string;
23
+ /** Store-localized, pre-formatted, e.g. "$59.99". Display this. */
24
+ price: string;
25
+ priceAmount: number;
26
+ currencyCode: string;
27
+ period: ProductPeriod | null;
28
+ periodCount: number;
29
+ /** ISO-8601 duration, e.g. "P1Y". null for non-subscriptions. */
30
+ periodIso: string | null;
31
+ introOffer?: {
32
+ price: string;
33
+ priceAmount: number;
34
+ period: ProductPeriod;
35
+ periodCount: number;
36
+ cycles: number;
37
+ };
38
+ trial?: { period: ProductPeriod; periodCount: number; days: number };
39
+ };
40
+
41
+ /**
42
+ * Computed by the SDK, never by an adapter — so every provider produces
43
+ * identical semantics and formatting.
44
+ */
45
+ export type DerivedProductFields = {
46
+ pricePerWeek?: string;
47
+ pricePerWeekAmount?: number;
48
+ pricePerMonth?: string;
49
+ pricePerMonthAmount?: number;
50
+ pricePerYear?: string;
51
+ pricePerYearAmount?: number;
52
+ /** Whole percent cheaper than `compareTo`, normalized per day. Absent if not cheaper. */
53
+ savingsPct?: number;
54
+ trialDays?: number;
55
+ };
56
+
57
+ export type ProductWithDerived = ResolvedProduct & DerivedProductFields;
58
+
59
+ export type PurchaseResult =
60
+ | { status: "purchased"; productKey: string; entitlements?: string[] }
61
+ | { status: "cancelled" }
62
+ | { status: "pending" }
63
+ | { status: "error"; error: Error };
64
+
65
+ export type RestoreResult =
66
+ | { status: "restored"; entitlements: string[] }
67
+ | { status: "nothing_to_restore" }
68
+ | { status: "error"; error: Error };
69
+
70
+ /** The vendor seam. Implement this to back paywalls with any billing SDK. */
71
+ export interface ProductProvider {
72
+ getProducts(refs: ProductRef[]): Promise<ResolvedProduct[]>;
73
+ purchase(product: ResolvedProduct): Promise<PurchaseResult>;
74
+ restore(): Promise<RestoreResult>;
75
+ }
76
+
77
+ export type ProductStatus = "idle" | "loading" | "ready" | "error";
78
+
79
+ /** What a host puts on ScreenHost.products; what press actions dispatch through. */
80
+ export type ProductRuntime = {
81
+ products: Record<string, ProductWithDerived>;
82
+ status: ProductStatus;
83
+ error?: string;
84
+ /** In-flight purchase guard, surfaced as the `products.purchasing` variable. */
85
+ purchasing: boolean;
86
+ purchase: (key: string) => Promise<PurchaseResult>;
87
+ restore: () => Promise<RestoreResult>;
88
+ };