@rocapine/react-native-onboarding 1.60.0 → 1.61.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 (124) hide show
  1. package/dist/index.d.ts +1 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +2 -0
  4. package/dist/index.js.map +1 -1
  5. package/dist/infra/provider/OnboardingProvider.d.ts +12 -1
  6. package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
  7. package/dist/infra/provider/OnboardingProvider.js +15 -1
  8. package/dist/infra/provider/OnboardingProvider.js.map +1 -1
  9. package/dist/products/adapters/expoIap.d.ts +4 -0
  10. package/dist/products/adapters/expoIap.d.ts.map +1 -0
  11. package/dist/products/adapters/expoIap.js +95 -0
  12. package/dist/products/adapters/expoIap.js.map +1 -0
  13. package/dist/products/adapters/revenueCat.d.ts +7 -0
  14. package/dist/products/adapters/revenueCat.d.ts.map +1 -0
  15. package/dist/products/adapters/revenueCat.js +116 -0
  16. package/dist/products/adapters/revenueCat.js.map +1 -0
  17. package/dist/products/adapters/stub.d.ts +8 -0
  18. package/dist/products/adapters/stub.d.ts.map +1 -0
  19. package/dist/products/adapters/stub.js +21 -0
  20. package/dist/products/adapters/stub.js.map +1 -0
  21. package/dist/products/derive.d.ts +19 -0
  22. package/dist/products/derive.d.ts.map +1 -0
  23. package/dist/products/derive.js +79 -0
  24. package/dist/products/derive.js.map +1 -0
  25. package/dist/products/duration.d.ts +3 -0
  26. package/dist/products/duration.d.ts.map +1 -0
  27. package/dist/products/duration.js +25 -0
  28. package/dist/products/duration.js.map +1 -0
  29. package/dist/products/index.d.ts +9 -0
  30. package/dist/products/index.d.ts.map +1 -0
  31. package/dist/products/index.js +20 -0
  32. package/dist/products/index.js.map +1 -0
  33. package/dist/products/toVariables.d.ts +18 -0
  34. package/dist/products/toVariables.d.ts.map +1 -0
  35. package/dist/products/toVariables.js +52 -0
  36. package/dist/products/toVariables.js.map +1 -0
  37. package/dist/products/types.d.ts +96 -0
  38. package/dist/products/types.d.ts.map +1 -0
  39. package/dist/products/types.js +3 -0
  40. package/dist/products/types.js.map +1 -0
  41. package/dist/products/useProducts.d.ts +12 -0
  42. package/dist/products/useProducts.d.ts.map +1 -0
  43. package/dist/products/useProducts.js +90 -0
  44. package/dist/products/useProducts.js.map +1 -0
  45. package/dist/screens/elements/AnimatedTextElement.d.ts +1 -24
  46. package/dist/screens/elements/AnimatedTextElement.d.ts.map +1 -1
  47. package/dist/screens/elements/BaseBoxProps.d.ts +1 -24
  48. package/dist/screens/elements/BaseBoxProps.d.ts.map +1 -1
  49. package/dist/screens/elements/ButtonElement.d.ts +6 -121
  50. package/dist/screens/elements/ButtonElement.d.ts.map +1 -1
  51. package/dist/screens/elements/CarouselElement.d.ts +1 -24
  52. package/dist/screens/elements/CarouselElement.d.ts.map +1 -1
  53. package/dist/screens/elements/CheckboxGroupElement.d.ts +1 -24
  54. package/dist/screens/elements/CheckboxGroupElement.d.ts.map +1 -1
  55. package/dist/screens/elements/DatePickerElement.d.ts +1 -24
  56. package/dist/screens/elements/DatePickerElement.d.ts.map +1 -1
  57. package/dist/screens/elements/DrawingPadElement.d.ts +1 -24
  58. package/dist/screens/elements/DrawingPadElement.d.ts.map +1 -1
  59. package/dist/screens/elements/IconElement.d.ts +1 -24
  60. package/dist/screens/elements/IconElement.d.ts.map +1 -1
  61. package/dist/screens/elements/ImageElement.d.ts +1 -24
  62. package/dist/screens/elements/ImageElement.d.ts.map +1 -1
  63. package/dist/screens/elements/InputElement.d.ts +1 -24
  64. package/dist/screens/elements/InputElement.d.ts.map +1 -1
  65. package/dist/screens/elements/KeyboardAvoidingViewElement.d.ts +1 -24
  66. package/dist/screens/elements/KeyboardAvoidingViewElement.d.ts.map +1 -1
  67. package/dist/screens/elements/LottieElement.d.ts +1 -24
  68. package/dist/screens/elements/LottieElement.d.ts.map +1 -1
  69. package/dist/screens/elements/ProgressIndicatorElement.d.ts +1 -24
  70. package/dist/screens/elements/ProgressIndicatorElement.d.ts.map +1 -1
  71. package/dist/screens/elements/ProgressiveBlurImageElement.d.ts +1 -24
  72. package/dist/screens/elements/ProgressiveBlurImageElement.d.ts.map +1 -1
  73. package/dist/screens/elements/RadioGroupElement.d.ts +1 -24
  74. package/dist/screens/elements/RadioGroupElement.d.ts.map +1 -1
  75. package/dist/screens/elements/RichTextElement.d.ts +1 -24
  76. package/dist/screens/elements/RichTextElement.d.ts.map +1 -1
  77. package/dist/screens/elements/RiveElement.d.ts +1 -24
  78. package/dist/screens/elements/RiveElement.d.ts.map +1 -1
  79. package/dist/screens/elements/SafeAreaViewElement.d.ts +1 -24
  80. package/dist/screens/elements/SafeAreaViewElement.d.ts.map +1 -1
  81. package/dist/screens/elements/ScrollViewElement.d.ts +1 -24
  82. package/dist/screens/elements/ScrollViewElement.d.ts.map +1 -1
  83. package/dist/screens/elements/SliderElement.d.ts +1 -24
  84. package/dist/screens/elements/SliderElement.d.ts.map +1 -1
  85. package/dist/screens/elements/StackElement.d.ts +1 -24
  86. package/dist/screens/elements/StackElement.d.ts.map +1 -1
  87. package/dist/screens/elements/TextElement.d.ts +1 -24
  88. package/dist/screens/elements/TextElement.d.ts.map +1 -1
  89. package/dist/screens/elements/TypewriterTextElement.d.ts +1 -24
  90. package/dist/screens/elements/TypewriterTextElement.d.ts.map +1 -1
  91. package/dist/screens/elements/VideoElement.d.ts +1 -24
  92. package/dist/screens/elements/VideoElement.d.ts.map +1 -1
  93. package/dist/screens/elements/WheelPickerElement.d.ts +1 -24
  94. package/dist/screens/elements/WheelPickerElement.d.ts.map +1 -1
  95. package/dist/screens/elements/ZStackElement.d.ts +1 -24
  96. package/dist/screens/elements/ZStackElement.d.ts.map +1 -1
  97. package/dist/steps/Carousel/types.d.ts +1 -1
  98. package/dist/steps/Commitment/types.d.ts +1 -1
  99. package/dist/steps/ComposableScreen/types.d.ts +1 -1
  100. package/dist/steps/Loader/types.d.ts +1 -1
  101. package/dist/steps/MediaContent/types.d.ts +1 -1
  102. package/dist/steps/Picker/types.d.ts +1 -1
  103. package/dist/steps/Question/types.d.ts +1 -1
  104. package/dist/steps/Ratings/types.d.ts +1 -1
  105. package/dist/steps/common.types.d.ts +23 -30
  106. package/dist/steps/common.types.d.ts.map +1 -1
  107. package/dist/steps/common.types.js +18 -3
  108. package/dist/steps/common.types.js.map +1 -1
  109. package/package.json +1 -1
  110. package/src/__tests__/productAdapters.test.ts +58 -0
  111. package/src/__tests__/productDerive.test.ts +111 -0
  112. package/src/__tests__/productVariables.test.ts +109 -0
  113. package/src/index.ts +2 -0
  114. package/src/infra/provider/OnboardingProvider.tsx +29 -0
  115. package/src/products/adapters/expoIap.ts +93 -0
  116. package/src/products/adapters/revenueCat.ts +108 -0
  117. package/src/products/adapters/stub.ts +20 -0
  118. package/src/products/derive.ts +93 -0
  119. package/src/products/duration.ts +21 -0
  120. package/src/products/index.ts +19 -0
  121. package/src/products/toVariables.ts +54 -0
  122. package/src/products/types.ts +88 -0
  123. package/src/products/useProducts.ts +106 -0
  124. package/src/steps/common.types.ts +50 -6
@@ -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,19 @@
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 { stubProductProvider } from "./adapters/stub";
18
+ export { revenueCatProductProvider } from "./adapters/revenueCat";
19
+ export { expoIapProductProvider } from "./adapters/expoIap";
@@ -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
+ };
@@ -0,0 +1,106 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { deriveAll } from "./derive";
3
+ import type {
4
+ ProductProvider,
5
+ ProductRef,
6
+ ProductRuntime,
7
+ ProductStatus,
8
+ ProductWithDerived,
9
+ PurchaseResult,
10
+ RestoreResult,
11
+ } from "./types";
12
+
13
+ const EMPTY_PRODUCTS: Record<string, ProductWithDerived> = {};
14
+
15
+ /**
16
+ * Resolves `refs` through `provider` once per (refs, provider) pair and exposes
17
+ * a referentially stable ProductRuntime.
18
+ *
19
+ * Stability matters: this object lands in RenderContext's dependency array, so
20
+ * an identity change on every render would re-render every memoized element on
21
+ * every variable write — undoing the Phase 1 memoization work. It is memoized on
22
+ * its actual contents, and purchase/restore are useCallback-stable.
23
+ */
24
+ export const useProducts = (
25
+ refs: ProductRef[] | undefined,
26
+ provider: ProductProvider | undefined,
27
+ locale?: string
28
+ ): ProductRuntime => {
29
+ const [products, setProducts] = useState<Record<string, ProductWithDerived>>(EMPTY_PRODUCTS);
30
+ const [status, setStatus] = useState<ProductStatus>("idle");
31
+ const [error, setError] = useState<string | undefined>(undefined);
32
+ const [purchasing, setPurchasing] = useState(false);
33
+
34
+ // Refs so the callbacks below never need to be re-created.
35
+ const productsRef = useRef(products);
36
+ productsRef.current = products;
37
+ const providerRef = useRef(provider);
38
+ providerRef.current = provider;
39
+
40
+ // Key the effect on the refs' identity CONTENT, not the array identity — a
41
+ // host passing an inline array literal would otherwise refetch every render.
42
+ const refsKey = useMemo(
43
+ () => (refs ?? []).map((r) => `${r.key}|${r.ios ?? ""}|${r.android ?? ""}|${r.compareTo ?? ""}`).join(","),
44
+ [refs]
45
+ );
46
+ const refsRef = useRef(refs);
47
+ refsRef.current = refs;
48
+
49
+ useEffect(() => {
50
+ const current = refsRef.current;
51
+ const prov = providerRef.current;
52
+ if (!prov || !current || current.length === 0) {
53
+ setStatus("idle");
54
+ return;
55
+ }
56
+ let cancelled = false;
57
+ setStatus("loading");
58
+ setError(undefined);
59
+ prov
60
+ .getProducts(current)
61
+ .then((resolved) => {
62
+ if (cancelled) return;
63
+ setProducts(deriveAll(resolved, current, locale));
64
+ setStatus("ready");
65
+ })
66
+ .catch((e: unknown) => {
67
+ if (cancelled) return;
68
+ setError(e instanceof Error ? e.message : String(e));
69
+ setStatus("error");
70
+ });
71
+ return () => {
72
+ cancelled = true;
73
+ };
74
+ }, [refsKey, locale]);
75
+
76
+ const purchase = useCallback(async (key: string): Promise<PurchaseResult> => {
77
+ const prov = providerRef.current;
78
+ const product = productsRef.current[key];
79
+ if (!prov || !product) {
80
+ return { status: "error", error: new Error(`No resolved product for key "${key}"`) };
81
+ }
82
+ setPurchasing(true);
83
+ try {
84
+ return await prov.purchase(product);
85
+ } catch (e) {
86
+ return { status: "error", error: e instanceof Error ? e : new Error(String(e)) };
87
+ } finally {
88
+ setPurchasing(false);
89
+ }
90
+ }, []);
91
+
92
+ const restore = useCallback(async (): Promise<RestoreResult> => {
93
+ const prov = providerRef.current;
94
+ if (!prov) return { status: "error", error: new Error("No ProductProvider") };
95
+ try {
96
+ return await prov.restore();
97
+ } catch (e) {
98
+ return { status: "error", error: e instanceof Error ? e : new Error(String(e)) };
99
+ }
100
+ }, []);
101
+
102
+ return useMemo(
103
+ () => ({ products, status, error, purchasing, purchase, restore }),
104
+ [products, status, error, purchasing, purchase, restore]
105
+ );
106
+ };
@@ -101,13 +101,57 @@ export const SetVariableButtonActionSchema = z.object({
101
101
  arrayOp: z.enum(["append", "remove", "toggle"]).optional(),
102
102
  });
103
103
 
104
- export type ButtonAction = "continue" | CustomButtonAction | SetVariableButtonAction;
104
+ export type PurchaseButtonAction = {
105
+ type: "purchase";
106
+ /** A product slot key, or an interpolable ref like "{{plan}}". */
107
+ product: string;
108
+ onSuccess?: ButtonAction[];
109
+ onCancel?: ButtonAction[];
110
+ onError?: ButtonAction[];
111
+ };
105
112
 
106
- export const ButtonActionSchema = z.union([
107
- z.literal("continue"),
108
- CustomButtonActionSchema,
109
- SetVariableButtonActionSchema,
110
- ]);
113
+ export type RestoreButtonAction = {
114
+ type: "restore";
115
+ onSuccess?: ButtonAction[];
116
+ onNothingToRestore?: ButtonAction[];
117
+ onError?: ButtonAction[];
118
+ };
119
+
120
+ export type ButtonAction =
121
+ | "continue"
122
+ | CustomButtonAction
123
+ | SetVariableButtonAction
124
+ | PurchaseButtonAction
125
+ | RestoreButtonAction;
126
+
127
+ export const PurchaseButtonActionSchema: z.ZodType<PurchaseButtonAction> = z.lazy(() =>
128
+ z.object({
129
+ type: z.literal("purchase"),
130
+ product: z.string().min(1, "product must not be empty"),
131
+ onSuccess: z.array(ButtonActionSchema).optional(),
132
+ onCancel: z.array(ButtonActionSchema).optional(),
133
+ onError: z.array(ButtonActionSchema).optional(),
134
+ })
135
+ );
136
+
137
+ export const RestoreButtonActionSchema: z.ZodType<RestoreButtonAction> = z.lazy(() =>
138
+ z.object({
139
+ type: z.literal("restore"),
140
+ onSuccess: z.array(ButtonActionSchema).optional(),
141
+ onNothingToRestore: z.array(ButtonActionSchema).optional(),
142
+ onError: z.array(ButtonActionSchema).optional(),
143
+ })
144
+ );
145
+
146
+ export const ButtonActionSchema: z.ZodType<ButtonAction> = z.lazy(() =>
147
+ z.union([
148
+ z.literal("continue"),
149
+ CustomButtonActionSchema,
150
+ SetVariableButtonActionSchema,
151
+ PurchaseButtonActionSchema,
152
+ RestoreButtonActionSchema,
153
+ ])
154
+ );
111
155
 
112
156
  // ── Branching / nextStep schemas ─────────────────────────────────────────────
113
157