@rocapine/react-native-onboarding 1.61.0 → 1.63.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 +7 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +12 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/infra/hooks/index.d.ts +1 -0
  10. package/dist/infra/hooks/index.d.ts.map +1 -1
  11. package/dist/infra/hooks/index.js +3 -1
  12. package/dist/infra/hooks/index.js.map +1 -1
  13. package/dist/infra/hooks/useProgressHeaderConfig.d.ts +14 -0
  14. package/dist/infra/hooks/useProgressHeaderConfig.d.ts.map +1 -0
  15. package/dist/infra/hooks/useProgressHeaderConfig.js +24 -0
  16. package/dist/infra/hooks/useProgressHeaderConfig.js.map +1 -0
  17. package/dist/infra/preload/extractAssetUrls.d.ts.map +1 -1
  18. package/dist/infra/preload/extractAssetUrls.js +67 -0
  19. package/dist/infra/preload/extractAssetUrls.js.map +1 -1
  20. package/dist/infra/provider/OnboardingProvider.d.ts +25 -0
  21. package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
  22. package/dist/infra/provider/OnboardingProvider.js +74 -3
  23. package/dist/infra/provider/OnboardingProvider.js.map +1 -1
  24. package/dist/infra/queries/cacheKey.d.ts +22 -4
  25. package/dist/infra/queries/cacheKey.d.ts.map +1 -1
  26. package/dist/infra/queries/cacheKey.js +26 -5
  27. package/dist/infra/queries/cacheKey.js.map +1 -1
  28. package/dist/onboarding-example.d.ts +1063 -60
  29. package/dist/onboarding-example.d.ts.map +1 -1
  30. package/dist/onboarding-example.js +140 -0
  31. package/dist/onboarding-example.js.map +1 -1
  32. package/dist/paywalls/PaywallProvider.d.ts +66 -0
  33. package/dist/paywalls/PaywallProvider.d.ts.map +1 -0
  34. package/dist/paywalls/PaywallProvider.js +227 -0
  35. package/dist/paywalls/PaywallProvider.js.map +1 -0
  36. package/dist/paywalls/getPaywalls.query.d.ts +37 -0
  37. package/dist/paywalls/getPaywalls.query.d.ts.map +1 -0
  38. package/dist/paywalls/getPaywalls.query.js +114 -0
  39. package/dist/paywalls/getPaywalls.query.js.map +1 -0
  40. package/dist/paywalls/present.d.ts +100 -0
  41. package/dist/paywalls/present.d.ts.map +1 -0
  42. package/dist/paywalls/present.js +113 -0
  43. package/dist/paywalls/present.js.map +1 -0
  44. package/dist/paywalls/types.d.ts +95 -0
  45. package/dist/paywalls/types.d.ts.map +1 -0
  46. package/dist/paywalls/types.js +10 -0
  47. package/dist/paywalls/types.js.map +1 -0
  48. package/dist/paywalls/usePaywall.d.ts +29 -0
  49. package/dist/paywalls/usePaywall.d.ts.map +1 -0
  50. package/dist/paywalls/usePaywall.js +17 -0
  51. package/dist/paywalls/usePaywall.js.map +1 -0
  52. package/dist/products/ProductRuntimeContext.d.ts +15 -0
  53. package/dist/products/ProductRuntimeContext.d.ts.map +1 -0
  54. package/dist/products/ProductRuntimeContext.js +19 -0
  55. package/dist/products/ProductRuntimeContext.js.map +1 -0
  56. package/dist/products/index.d.ts +1 -0
  57. package/dist/products/index.d.ts.map +1 -1
  58. package/dist/products/index.js +4 -1
  59. package/dist/products/index.js.map +1 -1
  60. package/dist/products/mergeProductRuntimes.d.ts +55 -0
  61. package/dist/products/mergeProductRuntimes.d.ts.map +1 -0
  62. package/dist/products/mergeProductRuntimes.js +79 -0
  63. package/dist/products/mergeProductRuntimes.js.map +1 -0
  64. package/dist/screens/elements/AnimatedTextElement.d.ts +7 -0
  65. package/dist/screens/elements/AnimatedTextElement.d.ts.map +1 -1
  66. package/dist/screens/elements/BaseBoxProps.d.ts +39 -0
  67. package/dist/screens/elements/BaseBoxProps.d.ts.map +1 -1
  68. package/dist/screens/elements/BaseBoxProps.js +9 -0
  69. package/dist/screens/elements/BaseBoxProps.js.map +1 -1
  70. package/dist/screens/elements/ButtonElement.d.ts +28 -0
  71. package/dist/screens/elements/ButtonElement.d.ts.map +1 -1
  72. package/dist/screens/elements/CarouselElement.d.ts +38 -0
  73. package/dist/screens/elements/CarouselElement.d.ts.map +1 -1
  74. package/dist/screens/elements/CarouselElement.js +1 -0
  75. package/dist/screens/elements/CarouselElement.js.map +1 -1
  76. package/dist/screens/elements/CheckboxGroupElement.d.ts +7 -0
  77. package/dist/screens/elements/CheckboxGroupElement.d.ts.map +1 -1
  78. package/dist/screens/elements/DatePickerElement.d.ts +7 -0
  79. package/dist/screens/elements/DatePickerElement.d.ts.map +1 -1
  80. package/dist/screens/elements/DrawingPadElement.d.ts +7 -0
  81. package/dist/screens/elements/DrawingPadElement.d.ts.map +1 -1
  82. package/dist/screens/elements/IconElement.d.ts +7 -0
  83. package/dist/screens/elements/IconElement.d.ts.map +1 -1
  84. package/dist/screens/elements/ImageElement.d.ts +26 -0
  85. package/dist/screens/elements/ImageElement.d.ts.map +1 -1
  86. package/dist/screens/elements/ImageElement.js +1 -0
  87. package/dist/screens/elements/ImageElement.js.map +1 -1
  88. package/dist/screens/elements/InputElement.d.ts +7 -0
  89. package/dist/screens/elements/InputElement.d.ts.map +1 -1
  90. package/dist/screens/elements/KeyboardAvoidingViewElement.d.ts +7 -0
  91. package/dist/screens/elements/KeyboardAvoidingViewElement.d.ts.map +1 -1
  92. package/dist/screens/elements/LottieElement.d.ts +7 -0
  93. package/dist/screens/elements/LottieElement.d.ts.map +1 -1
  94. package/dist/screens/elements/ProgressIndicatorElement.d.ts +7 -0
  95. package/dist/screens/elements/ProgressIndicatorElement.d.ts.map +1 -1
  96. package/dist/screens/elements/ProgressiveBlurImageElement.d.ts +7 -0
  97. package/dist/screens/elements/ProgressiveBlurImageElement.d.ts.map +1 -1
  98. package/dist/screens/elements/RadioGroupElement.d.ts +7 -0
  99. package/dist/screens/elements/RadioGroupElement.d.ts.map +1 -1
  100. package/dist/screens/elements/RepeatElement.d.ts +79 -0
  101. package/dist/screens/elements/RepeatElement.d.ts.map +1 -0
  102. package/dist/screens/elements/RepeatElement.js +10 -0
  103. package/dist/screens/elements/RepeatElement.js.map +1 -0
  104. package/dist/screens/elements/RichTextElement.d.ts +7 -0
  105. package/dist/screens/elements/RichTextElement.d.ts.map +1 -1
  106. package/dist/screens/elements/RiveElement.d.ts +7 -0
  107. package/dist/screens/elements/RiveElement.d.ts.map +1 -1
  108. package/dist/screens/elements/SafeAreaViewElement.d.ts +7 -0
  109. package/dist/screens/elements/SafeAreaViewElement.d.ts.map +1 -1
  110. package/dist/screens/elements/ScrollViewElement.d.ts +7 -0
  111. package/dist/screens/elements/ScrollViewElement.d.ts.map +1 -1
  112. package/dist/screens/elements/SliderElement.d.ts +7 -0
  113. package/dist/screens/elements/SliderElement.d.ts.map +1 -1
  114. package/dist/screens/elements/StackElement.d.ts +7 -0
  115. package/dist/screens/elements/StackElement.d.ts.map +1 -1
  116. package/dist/screens/elements/TextElement.d.ts +7 -0
  117. package/dist/screens/elements/TextElement.d.ts.map +1 -1
  118. package/dist/screens/elements/TypewriterTextElement.d.ts +26 -0
  119. package/dist/screens/elements/TypewriterTextElement.d.ts.map +1 -1
  120. package/dist/screens/elements/TypewriterTextElement.js +1 -0
  121. package/dist/screens/elements/TypewriterTextElement.js.map +1 -1
  122. package/dist/screens/elements/VideoElement.d.ts +7 -0
  123. package/dist/screens/elements/VideoElement.d.ts.map +1 -1
  124. package/dist/screens/elements/WheelPickerElement.d.ts +7 -0
  125. package/dist/screens/elements/WheelPickerElement.d.ts.map +1 -1
  126. package/dist/screens/elements/ZStackElement.d.ts +7 -0
  127. package/dist/screens/elements/ZStackElement.d.ts.map +1 -1
  128. package/dist/screens/types.d.ts +9 -0
  129. package/dist/screens/types.d.ts.map +1 -1
  130. package/dist/screens/types.js +9 -0
  131. package/dist/screens/types.js.map +1 -1
  132. package/dist/screens/unknownKeys.d.ts +67 -0
  133. package/dist/screens/unknownKeys.d.ts.map +1 -0
  134. package/dist/screens/unknownKeys.js +160 -0
  135. package/dist/screens/unknownKeys.js.map +1 -0
  136. package/dist/steps/common.types.d.ts +22 -1
  137. package/dist/steps/common.types.d.ts.map +1 -1
  138. package/dist/steps/common.types.js +10 -1
  139. package/dist/steps/common.types.js.map +1 -1
  140. package/dist/types.d.ts +73 -0
  141. package/dist/types.d.ts.map +1 -1
  142. package/package.json +1 -1
  143. package/src/OnboardingStudioClient.ts +110 -7
  144. package/src/__tests__/extractAssetUrls.test.ts +104 -0
  145. package/src/__tests__/mergeProductRuntimes.test.ts +172 -0
  146. package/src/__tests__/resolveLocalProductArgs.test.ts +41 -0
  147. package/src/__tests__/unknownKeys.test.ts +234 -0
  148. package/src/index.ts +20 -0
  149. package/src/infra/hooks/index.ts +1 -0
  150. package/src/infra/hooks/useProgressHeaderConfig.ts +21 -0
  151. package/src/infra/preload/extractAssetUrls.ts +72 -0
  152. package/src/infra/provider/OnboardingProvider.tsx +87 -3
  153. package/src/infra/queries/cacheKey.ts +27 -4
  154. package/src/onboarding-example.ts +140 -0
  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/index.ts +1 -0
  164. package/src/products/mergeProductRuntimes.ts +78 -0
  165. package/src/screens/elements/BaseBoxProps.ts +56 -0
  166. package/src/screens/elements/CarouselElement.ts +31 -0
  167. package/src/screens/elements/ImageElement.ts +16 -0
  168. package/src/screens/elements/RepeatElement.ts +80 -0
  169. package/src/screens/elements/TypewriterTextElement.ts +19 -0
  170. package/src/screens/types.ts +18 -0
  171. package/src/screens/unknownKeys.ts +211 -0
  172. package/src/steps/common.types.ts +34 -1
  173. package/src/types.ts +86 -0
@@ -341,6 +341,24 @@ export const onboardingExample = {
341
341
  marginVertical: 8,
342
342
  },
343
343
  },
344
+ {
345
+ // Cursor mode types characters in progressively, so the block would
346
+ // grow 1 -> 2 lines and shove everything below it down the screen.
347
+ // `reserveSpace` lays the finished string out invisibly first and
348
+ // overlays the animation, so the siblings never move. It measures
349
+ // the real resolved string, so it stays right in every locale.
350
+ id: "typewriter-reserved",
351
+ type: "TypewriterText",
352
+ props: {
353
+ content: "Meet your AI journal companion",
354
+ cursor: true,
355
+ reserveSpace: true,
356
+ stagger: 40,
357
+ fontSize: 16,
358
+ textAlign: "center",
359
+ marginVertical: 8,
360
+ },
361
+ },
344
362
  {
345
363
  id: "hero-video",
346
364
  type: "Video",
@@ -860,6 +878,10 @@ export const onboardingExample = {
860
878
  marginVertical: 8,
861
879
  defaultIndex: 0,
862
880
  variableName: "carouselPage",
881
+ // Snap-time variable (`carouselPage`) steps 0 -> 1 -> 2. This one
882
+ // tracks the finger continuously, so siblings can animate DURING
883
+ // the swipe instead of after it lands.
884
+ progressVariableName: "carouselProgress",
863
885
  },
864
886
  children: [
865
887
  {
@@ -891,6 +913,104 @@ export const onboardingExample = {
891
913
  },
892
914
  ],
893
915
  },
916
+ {
917
+ // Gated on the CONTINUOUS position: `eq` compares the rounded value,
918
+ // so this mounts (and fades in) once the swipe passes halfway to
919
+ // slide 2 -- not when it snaps. Because the published value is
920
+ // normalized to [0, childCount), it behaves identically on every lap
921
+ // even though `loop` is on.
922
+ id: "carousel-swipe-reveal",
923
+ type: "Text",
924
+ renderWhen: { variable: "carouselProgress", operator: "eq", value: 1 },
925
+ props: {
926
+ // `animation` is a BaseBoxProp -- inside `props`, not top level.
927
+ animation: { entering: { preset: "FadeInDown", duration: 300 } },
928
+ content: "Revealed mid-swipe on slide 2",
929
+ fontSize: 13,
930
+ textAlign: "center",
931
+ marginVertical: 2,
932
+ },
933
+ },
934
+ {
935
+ // Data-driven Image: ONE element instead of one duplicated subtree
936
+ // per case. The URL rebuilds as `carouselPage` changes, so paging
937
+ // the carousel swaps this image. `{{var}}` resolves to the
938
+ // variable's VALUE (not its label) — a URL segment is an identifier.
939
+ id: "carousel-derived-image",
940
+ type: "Image",
941
+ props: {
942
+ url: "https://picsum.photos/seed/{{carouselPage}}/120/120",
943
+ mode: "expression",
944
+ width: 120,
945
+ height: 120,
946
+ borderRadius: 12,
947
+ alignSelf: "center",
948
+ marginVertical: 4,
949
+ },
950
+ },
951
+ {
952
+ // `animation.replayWhen`: re-fires the entering animation each
953
+ // time `carouselPage` changes, WITHOUT the element disappearing.
954
+ // Previously the only way to replay was to toggle `renderWhen`,
955
+ // which couples "animate again" to "change visibility".
956
+ id: "carousel-replay-label",
957
+ type: "Text",
958
+ props: {
959
+ content: "Slide {{carouselPage}}",
960
+ mode: "expression",
961
+ fontSize: 14,
962
+ fontWeight: "600",
963
+ textAlign: "center",
964
+ marginVertical: 2,
965
+ animation: {
966
+ entering: { preset: "FadeInUp", duration: 260 },
967
+ replayWhen: "carouselPage",
968
+ },
969
+ },
970
+ },
971
+ {
972
+ // `Repeat`: ONE template materialized per row of payload-authored
973
+ // data, instead of three near-identical hand-written subtrees.
974
+ // Layout-transparent, so these rows become children of the
975
+ // enclosing YStack and its `gap` applies between them.
976
+ // Row fields are exposed as `{{item.*}}`; `item.index` is always
977
+ // available. A `renderWhen` on the template gates per row, which
978
+ // is how Repeat also covers the "switch" case without a separate
979
+ // Match element.
980
+ id: "feature-rows",
981
+ type: "Repeat",
982
+ props: {
983
+ keyField: "key",
984
+ data: [
985
+ { key: "track", label: "Track every workout" },
986
+ { key: "plan", label: "Plan your week" },
987
+ { key: "coach", label: "Coaching that adapts" },
988
+ ],
989
+ },
990
+ children: [
991
+ {
992
+ id: "feature-row",
993
+ type: "XStack",
994
+ props: { gap: 10, alignItems: "center", marginVertical: 2 },
995
+ children: [
996
+ {
997
+ // Static: `Icon.name` has no `mode`, so it does NOT
998
+ // interpolate — `{{item.icon}}` here would render as a
999
+ // literal, unmatched icon name. Only props documented as
1000
+ // supporting `expression` accept `{{var}}`.
1001
+ id: "feature-icon",
1002
+ type: "Icon",
1003
+ props: { name: "check", size: 18 },
1004
+ },
1005
+ {
1006
+ id: "feature-label",
1007
+ type: "Text",
1008
+ props: { content: "{{item.label}}", mode: "expression", fontSize: 15 },
1009
+ },
1010
+ ],
1011
+ },
1012
+ ],
1013
+ },
894
1014
  {
895
1015
  id: "carousel-page-label",
896
1016
  type: "Text",
@@ -985,6 +1105,26 @@ export const onboardingExample = {
985
1105
  },
986
1106
  ],
987
1107
  },
1108
+ {
1109
+ // `inset`: declarative off-anchor placement. Supplying one side
1110
+ // per axis leaves this content-sized and pinned by its top-left
1111
+ // corner, instead of doing the arithmetic with
1112
+ // transform.translateX/Y. Percentages keep it stable across
1113
+ // device widths. Honoured only on a ZStack child.
1114
+ id: "zstack-inset-badge",
1115
+ type: "Text",
1116
+ props: {
1117
+ inset: { top: "12%", left: "62%" },
1118
+ content: "NEW",
1119
+ fontSize: 12,
1120
+ fontWeight: "700",
1121
+ color: "#fff",
1122
+ backgroundColor: "#E76F51",
1123
+ paddingHorizontal: 8,
1124
+ paddingVertical: 4,
1125
+ borderRadius: 999,
1126
+ },
1127
+ },
988
1128
  ],
989
1129
  },
990
1130
  {
@@ -0,0 +1,342 @@
1
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
2
+ import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
3
+ import { OnboardingStudioClient } from "../OnboardingStudioClient";
4
+ import { getPaywallsQuery } from "./getPaywalls.query";
5
+ import { Paywall, PaywallCatalog, PresentResult } from "./types";
6
+ import {
7
+ collectProductRefs,
8
+ computeIsReady,
9
+ purchaseOutcomeFromResult,
10
+ resolvePresentDecision,
11
+ resolvePresentedOutcome,
12
+ shouldRecordPurchaseOutcome,
13
+ type PurchaseOutcomeDuringPresentation,
14
+ } from "./present";
15
+ import { useProducts } from "../products/useProducts";
16
+ import { ProductProvider } from "../products/types";
17
+ import { ProductRuntimeContext } from "../products/ProductRuntimeContext";
18
+ import type { CustomActions } from "../infra/provider/OnboardingProvider";
19
+
20
+ // Module-scope, private to this file — mirrors `OnboardingProvider.tsx:17-23`.
21
+ // `OnboardingProvider`'s QueryClient is not exported, so it cannot be reused
22
+ // here; a second, independent cache is intentional, not an oversight — the
23
+ // paywall catalog and the onboarding step payload are different resources
24
+ // with different lifetimes and different AsyncStorage namespaces
25
+ // (`rocapine-paywalls-*` vs `rocapine-onboarding-*`, see
26
+ // `infra/queries/cacheKey.ts`).
27
+ const paywallQueryClient = new QueryClient({
28
+ defaultOptions: {
29
+ queries: {
30
+ staleTime: Infinity,
31
+ },
32
+ },
33
+ });
34
+
35
+ // Frozen at module scope, not a default PARAMETER — a default parameter
36
+ // re-allocates on every render, and `customActions` sits in the published
37
+ // context value (read by `usePaywallHost()` to build the presented paywall's
38
+ // `ScreenHost`), so an unstable identity would defeat memoization the same
39
+ // way `EMPTY_CUSTOM_ACTIONS` in `OnboardingProvider.tsx` documents.
40
+ const EMPTY_CUSTOM_ACTIONS: CustomActions = Object.freeze({});
41
+
42
+ /**
43
+ * Everything a paywall consumer or a paywall HOST needs. Deliberately one
44
+ * context carrying both, mirroring how `OnboardingProgressContext` bundles
45
+ * far more than any single hook reads — `usePaywall()` and `usePaywallHost()`
46
+ * each slice out the fields they need, same pattern as the small hooks in
47
+ * `infra/hooks/` slicing `OnboardingProgressContext`.
48
+ */
49
+ export type PaywallContextValue = {
50
+ present: (placement: string) => Promise<PresentResult>;
51
+ isReady: boolean;
52
+ catalog: PaywallCatalog | null;
53
+ /** The paywall currently being presented, or null. Read by `usePaywallHost()` — not by `usePaywall()`. */
54
+ activePaywall: Paywall | null;
55
+ /**
56
+ * Resolve the pending `present()` call and clear the active placement.
57
+ * Call this from the presented paywall's `ScreenHost.complete` (Task 7's
58
+ * `PaywallHost`) — never from an ordinary consumer.
59
+ */
60
+ complete: (result: PresentResult) => void;
61
+ /** Forwarded into the presented paywall's `ScreenHost.customActions`. */
62
+ customActions: CustomActions;
63
+ };
64
+
65
+ const EMPTY_PAYWALL_CONTEXT: PaywallContextValue = {
66
+ present: async () => ({ status: "error" }),
67
+ isReady: false,
68
+ catalog: null,
69
+ activePaywall: null,
70
+ complete: () => {},
71
+ customActions: EMPTY_CUSTOM_ACTIONS,
72
+ };
73
+
74
+ export const PaywallContext = createContext<PaywallContextValue>(EMPTY_PAYWALL_CONTEXT);
75
+
76
+ /**
77
+ * The seam a paywall HOST (Task 7's `PaywallHost`) reads from — analogous to
78
+ * `ScreenHost` being the seam the rendering engine reads from. Kept out of
79
+ * `usePaywall()`'s return so an ordinary caller never sees presentation
80
+ * internals it has no reason to touch (which paywall is active, how to
81
+ * resolve it).
82
+ */
83
+ export const usePaywallHost = (): Pick<PaywallContextValue, "activePaywall" | "complete" | "customActions"> => {
84
+ const { activePaywall, complete, customActions } = useContext(PaywallContext);
85
+ return { activePaywall, complete, customActions };
86
+ };
87
+
88
+ interface PaywallProviderProps {
89
+ children: React.ReactNode;
90
+ client: OnboardingStudioClient;
91
+ locale?: string;
92
+ customAudienceParams?: Record<string, any>;
93
+ /**
94
+ * Billing adapter. Products are resolved once, over the union of every
95
+ * `paywall.products[]` in the catalog (deduplicated), and published via
96
+ * `ProductRuntimeContext` — an `OnboardingProvider` mounted anywhere inside
97
+ * this tree picks up the SAME runtime instead of resolving its own, so
98
+ * there is one store round-trip and one `purchasing` flag for both.
99
+ */
100
+ productProvider?: ProductProvider;
101
+ /** Handlers for `{ type: "custom" }` ButtonActions inside a paywall's elements. */
102
+ customActions?: CustomActions;
103
+ }
104
+
105
+ interface PaywallProviderInnerProps {
106
+ children: React.ReactNode;
107
+ client: OnboardingStudioClient;
108
+ locale: string;
109
+ customAudienceParams: Record<string, any>;
110
+ productProvider?: ProductProvider;
111
+ customActions: CustomActions;
112
+ }
113
+
114
+ const PaywallProviderInner = ({
115
+ children,
116
+ client,
117
+ locale,
118
+ customAudienceParams,
119
+ productProvider,
120
+ customActions,
121
+ }: PaywallProviderInnerProps) => {
122
+ // `data` straight off `useQuery` is the single source of truth (Finding 1,
123
+ // 2026-08-17 final review) — react-query's own cache already gets both a
124
+ // provider remount and a locale/customAudienceParams round-trip right; a
125
+ // mirrored `useState` populated from inside `queryFn` does not (it only
126
+ // gets written on a cache MISS). See `getPaywalls.query.ts`'s module doc
127
+ // for why the query still needs `paywallQueryClient` for the ONE case
128
+ // `data` alone can't cover: a background revalidation pushing a fresh
129
+ // payload while this query call already resolved with the cached one.
130
+ const { data, error } = useQuery<PaywallCatalog>(
131
+ getPaywallsQuery(client, locale, customAudienceParams, paywallQueryClient)
132
+ );
133
+ const catalog = data ?? null;
134
+
135
+ useEffect(() => {
136
+ if (!error) return;
137
+ // Deliberately NOT thrown. `OnboardingProvider` throws its query error so
138
+ // a host `ErrorBoundary` around a single onboarding screen catches it —
139
+ // but `PaywallProvider` wraps the WHOLE app (spec §7:
140
+ // `<PaywallProvider><App/><PaywallHost/></PaywallProvider>`), so throwing
141
+ // here would crash every screen over a paywall-catalog failure alone.
142
+ // Instead: `catalog` simply stays null, `present()` on any placement
143
+ // resolves "error" (see `resolvePresentDecision` — an unresolved catalog
144
+ // looks identical to an unknown placement), and `isReady` stays false.
145
+ console.warn("[paywalls] Failed to load paywall catalog:", error);
146
+ }, [error]);
147
+
148
+ // Union of every placement's products, deduplicated, resolved ONCE — never
149
+ // re-keyed per presented paywall. See `present.ts`'s `collectProductRefs`
150
+ // doc for why (spec §6.1's "render instantly on tap" requirement).
151
+ const productRefs = useMemo(() => collectProductRefs(catalog), [catalog]);
152
+ const productRuntime = useProducts(productRefs, productProvider, locale);
153
+
154
+ // Tracks what a purchase attempt resolved to during the CURRENT
155
+ // presentation — read by `complete()` to upgrade a generic "dismissed"
156
+ // outcome (see `resolvePresentedOutcome`), reset when a new presentation
157
+ // starts (`present()`'s "start" branch) so one presentation's purchase
158
+ // can never leak into the next.
159
+ const lastPurchaseOutcomeRef = useRef<PurchaseOutcomeDuringPresentation>(null);
160
+
161
+ // Monotonic, incremented every time a presentation actually starts (never
162
+ // on the "immediate" no-op branch). Resetting `lastPurchaseOutcomeRef` at
163
+ // that same moment is NOT enough to stop a stale write: paywall A's
164
+ // `purchase()` can still be in flight when the user dismisses A and
165
+ // paywall B is presented (which resets the ref); if A's promise settles
166
+ // AFTER that reset, an unconditional write would land "purchased" in what
167
+ // is now B's tracker. `purchase()` below captures the generation it
168
+ // started in and only writes if that generation is still current — see
169
+ // `shouldRecordPurchaseOutcome`. DO NOT remove the guard because the write
170
+ // "looks" unconditional; that is exactly the race it closes.
171
+ const presentationGenerationRef = useRef(0);
172
+
173
+ // Wraps `productRuntime.purchase` to record the outcome above (race-guarded
174
+ // — see `presentationGenerationRef`); every other field (and — critically —
175
+ // the object's change cadence, since `products.purchasing` flips must
176
+ // still propagate) is untouched. `productRuntime.purchase` is itself
177
+ // `useCallback(…, [])`-stable (`useProducts.ts`), so this wrapper never
178
+ // changes identity either.
179
+ const purchase = useCallback(
180
+ async (key: string) => {
181
+ const startedInGeneration = presentationGenerationRef.current;
182
+ const result = await productRuntime.purchase(key);
183
+ const outcome = purchaseOutcomeFromResult(result);
184
+ if (outcome && shouldRecordPurchaseOutcome(startedInGeneration, presentationGenerationRef.current)) {
185
+ lastPurchaseOutcomeRef.current = outcome;
186
+ }
187
+ return result;
188
+ },
189
+ [productRuntime.purchase]
190
+ );
191
+ const productRuntimeWithPurchaseTracking = useMemo(
192
+ () => ({ ...productRuntime, purchase }),
193
+ [productRuntime, purchase]
194
+ );
195
+
196
+ const [activePlacement, setActivePlacement] = useState<string | null>(null);
197
+ // Refs so `present`/`complete` stay referentially stable (empty deps) while
198
+ // still reading current state — same pattern `useProducts.ts` uses for its
199
+ // `purchase`/`restore` callbacks.
200
+ const catalogRef = useRef(catalog);
201
+ catalogRef.current = catalog;
202
+ // `activePlacementRef` is made AUTHORITATIVE below — assigned inside
203
+ // `present()`'s start branch and inside `complete()`, not just here. Finding
204
+ // 4, 2026-08-17 final review: this line alone only resyncs the ref from
205
+ // state AFTER React commits, so between a `present()` call and the next
206
+ // commit the ref still holds the PREVIOUS value. Two `present()` calls
207
+ // issued in the same tick (`Promise.all([present("a"), present("b")])`, or
208
+ // two `presentPaywall` actions in one action list) both read the stale ref,
209
+ // both take the "start" branch, and the second overwrites
210
+ // `pendingResolveRef` — the first promise then never settles, exactly the
211
+ // orphaning this whole ref/resolver scheme exists to prevent. Assigning
212
+ // synchronously inside `present`/`complete` closes that window; this
213
+ // render-body line stays only as a resync for the (rare) case something
214
+ // external changes `activePlacement` state without going through either
215
+ // callback.
216
+ const activePlacementRef = useRef(activePlacement);
217
+ activePlacementRef.current = activePlacement;
218
+ const pendingResolveRef = useRef<((result: PresentResult) => void) | null>(null);
219
+
220
+ // present() must not fetch anything — the catalog and products are already
221
+ // resolved (or resolving) from mount. It only decides, synchronously,
222
+ // whether to show the Modal.
223
+ const present = useCallback((placement: string): Promise<PresentResult> => {
224
+ const decision = resolvePresentDecision(catalogRef.current, activePlacementRef.current, placement);
225
+ if (decision.type === "immediate") {
226
+ return Promise.resolve(decision.result);
227
+ }
228
+ // Fresh presentation: no purchase has happened under it yet, and any
229
+ // still-in-flight purchase from a PREVIOUS presentation must not be
230
+ // allowed to write into this one — see `presentationGenerationRef`.
231
+ lastPurchaseOutcomeRef.current = null;
232
+ presentationGenerationRef.current += 1;
233
+ // Authoritative NOW, synchronously — see the ref's doc above. A second
234
+ // `present()` call before React commits reads this value, not the stale
235
+ // pre-commit state, and correctly takes the "already showing" branch.
236
+ activePlacementRef.current = placement;
237
+ return new Promise<PresentResult>((resolve) => {
238
+ pendingResolveRef.current = resolve;
239
+ setActivePlacement(placement);
240
+ });
241
+ }, []);
242
+
243
+ // Called by PaywallHost (Task 7) from the presented paywall's
244
+ // `ScreenHost.complete`. Resolves whatever `present()` call is pending and
245
+ // clears the active placement, hiding the Modal and allowing a new
246
+ // `present()` to start. Safe to call with nothing pending (no-ops).
247
+ //
248
+ // `resolvePresentedOutcome` upgrades a bare "dismissed" to "purchased" (or
249
+ // "cancelled") when the store actually did something during this
250
+ // presentation — see its doc for why `dismiss`'s own `{status:"dismissed"}`
251
+ // isn't treated as an unoverridable explicit answer.
252
+ const complete = useCallback((result: PresentResult) => {
253
+ const resolve = pendingResolveRef.current;
254
+ pendingResolveRef.current = null;
255
+ // Authoritative NOW, synchronously — same reasoning as `present()`'s
256
+ // assignment above: a `present()` issued from the resolution continuation
257
+ // (`const r = await present("a"); … present("downsell")` — a downsell
258
+ // opening from the previous paywall's resolution is a canonical pattern,
259
+ // spec §4.5) must see "nothing showing" immediately, not wait for the
260
+ // next commit.
261
+ activePlacementRef.current = null;
262
+ setActivePlacement(null);
263
+ resolve?.(resolvePresentedOutcome(result, lastPurchaseOutcomeRef.current));
264
+ }, []);
265
+
266
+ const activePaywall = activePlacement ? catalog?.paywalls[activePlacement] ?? null : null;
267
+
268
+ // Finding 6, 2026-08-17 final review, widened by N2 (round 2): a background
269
+ // catalog revalidation (see `getPaywalls.query.ts`) can push a fresh catalog
270
+ // that no longer contains the placement currently on screen (a studio
271
+ // publish renamed or removed it mid-session) — OR the query KEY itself can
272
+ // change while a paywall is showing (`locale`/`customAudienceParams`
273
+ // changed as a prop), which makes react-query report `data: undefined`
274
+ // while the new key is fetching (Finding 1's fix reads `catalog` straight
275
+ // from that `data`). Both collapse `activePaywall` to null the same way, so
276
+ // guarding on THAT — not on `catalog` being non-null — catches both: the
277
+ // original guard (`!catalog` check) missed the query-key case entirely,
278
+ // because a null `catalog` made it bail out before ever checking whether
279
+ // the placement was still present.
280
+ //
281
+ // Either way, the Modal closes itself WITHOUT going through `complete()`,
282
+ // so the pending `present()` promise would never settle and
283
+ // `activePlacement` would stay set forever, silently failing every later
284
+ // `present()` call with `"error"` for the rest of the app's life.
285
+ // `complete()` always clears `activePlacement` together with resolving the
286
+ // pending promise, so it cannot race with or double-resolve this branch.
287
+ useEffect(() => {
288
+ if (!activePlacement || activePaywall) return;
289
+ complete({ status: "error" });
290
+ }, [activePlacement, activePaywall, complete]);
291
+
292
+ const isReady = useMemo(
293
+ () => computeIsReady(catalog, productRefs, productRuntime.status),
294
+ [catalog, productRefs, productRuntime.status]
295
+ );
296
+
297
+ const contextValue = useMemo<PaywallContextValue>(
298
+ () => ({ present, isReady, catalog, activePaywall, complete, customActions }),
299
+ [present, isReady, catalog, activePaywall, complete, customActions]
300
+ );
301
+
302
+ return (
303
+ <ProductRuntimeContext.Provider value={productRuntimeWithPurchaseTracking}>
304
+ <PaywallContext.Provider value={contextValue}>{children}</PaywallContext.Provider>
305
+ </ProductRuntimeContext.Provider>
306
+ );
307
+ };
308
+
309
+ /**
310
+ * App-level ancestor. Renders ABOVE `OnboardingProvider`, not inside it —
311
+ * that is what lets both share one `ProductRuntimeContext` (React context
312
+ * only flows to descendants; two true siblings could not share one runtime).
313
+ *
314
+ * ```tsx
315
+ * <PaywallProvider client={client} productProvider={revenueCatProductProvider(Purchases)}>
316
+ * <App />
317
+ * <PaywallHost /> // Task 7: renders the active paywall in a fullScreen RN Modal
318
+ * </PaywallProvider>
319
+ * ```
320
+ */
321
+ export const PaywallProvider = ({
322
+ children,
323
+ client,
324
+ locale = "en",
325
+ customAudienceParams = {},
326
+ productProvider,
327
+ customActions = EMPTY_CUSTOM_ACTIONS,
328
+ }: PaywallProviderProps) => {
329
+ return (
330
+ <QueryClientProvider client={paywallQueryClient}>
331
+ <PaywallProviderInner
332
+ client={client}
333
+ locale={locale}
334
+ customAudienceParams={customAudienceParams}
335
+ productProvider={productProvider}
336
+ customActions={customActions}
337
+ >
338
+ {children}
339
+ </PaywallProviderInner>
340
+ </QueryClientProvider>
341
+ );
342
+ };