@rocapine/react-native-onboarding 1.73.0 → 1.74.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +164 -3
  2. package/dist/OnboardingStudio.d.ts +82 -0
  3. package/dist/OnboardingStudio.d.ts.map +1 -0
  4. package/dist/OnboardingStudio.js +91 -0
  5. package/dist/OnboardingStudio.js.map +1 -0
  6. package/dist/OnboardingStudioClient.d.ts +14 -5
  7. package/dist/OnboardingStudioClient.d.ts.map +1 -1
  8. package/dist/OnboardingStudioClient.js +24 -9
  9. package/dist/OnboardingStudioClient.js.map +1 -1
  10. package/dist/index.d.ts +7 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +40 -4
  13. package/dist/index.js.map +1 -1
  14. package/dist/infra/provider/OnboardingProvider.d.ts +15 -2
  15. package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
  16. package/dist/infra/provider/OnboardingProvider.js +66 -6
  17. package/dist/infra/provider/OnboardingProvider.js.map +1 -1
  18. package/dist/infra/queries/cacheKey.d.ts +41 -3
  19. package/dist/infra/queries/cacheKey.d.ts.map +1 -1
  20. package/dist/infra/queries/cacheKey.js +44 -8
  21. package/dist/infra/queries/cacheKey.js.map +1 -1
  22. package/dist/infra/queries/getOnboarding.query.d.ts.map +1 -1
  23. package/dist/infra/queries/getOnboarding.query.js +6 -1
  24. package/dist/infra/queries/getOnboarding.query.js.map +1 -1
  25. package/dist/paywalls/PaywallProvider.d.ts +52 -4
  26. package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
  27. package/dist/paywalls/PaywallProvider.js +105 -7
  28. package/dist/paywalls/PaywallProvider.js.map +1 -1
  29. package/dist/paywalls/catalogSettleWaiter.d.ts +31 -0
  30. package/dist/paywalls/catalogSettleWaiter.d.ts.map +1 -0
  31. package/dist/paywalls/catalogSettleWaiter.js +58 -0
  32. package/dist/paywalls/catalogSettleWaiter.js.map +1 -0
  33. package/dist/paywalls/getPaywalls.query.d.ts.map +1 -1
  34. package/dist/paywalls/getPaywalls.query.js +6 -1
  35. package/dist/paywalls/getPaywalls.query.js.map +1 -1
  36. package/dist/paywalls/register.d.ts +105 -0
  37. package/dist/paywalls/register.d.ts.map +1 -0
  38. package/dist/paywalls/register.js +112 -0
  39. package/dist/paywalls/register.js.map +1 -0
  40. package/dist/paywalls/usePaywall.d.ts +29 -0
  41. package/dist/paywalls/usePaywall.d.ts.map +1 -1
  42. package/dist/paywalls/usePaywall.js +2 -1
  43. package/dist/paywalls/usePaywall.js.map +1 -1
  44. package/dist/userProperties/applyPatch.d.ts +18 -0
  45. package/dist/userProperties/applyPatch.d.ts.map +1 -0
  46. package/dist/userProperties/applyPatch.js +57 -0
  47. package/dist/userProperties/applyPatch.js.map +1 -0
  48. package/dist/userProperties/effectiveParams.d.ts +29 -0
  49. package/dist/userProperties/effectiveParams.d.ts.map +1 -0
  50. package/dist/userProperties/effectiveParams.js +56 -0
  51. package/dist/userProperties/effectiveParams.js.map +1 -0
  52. package/dist/userProperties/index.d.ts +9 -0
  53. package/dist/userProperties/index.d.ts.map +1 -0
  54. package/dist/userProperties/index.js +21 -0
  55. package/dist/userProperties/index.js.map +1 -0
  56. package/dist/userProperties/reserved.d.ts +33 -0
  57. package/dist/userProperties/reserved.d.ts.map +1 -0
  58. package/dist/userProperties/reserved.js +45 -0
  59. package/dist/userProperties/reserved.js.map +1 -0
  60. package/dist/userProperties/serialize.d.ts +38 -0
  61. package/dist/userProperties/serialize.d.ts.map +1 -0
  62. package/dist/userProperties/serialize.js +67 -0
  63. package/dist/userProperties/serialize.js.map +1 -0
  64. package/dist/userProperties/store.d.ts +65 -0
  65. package/dist/userProperties/store.d.ts.map +1 -0
  66. package/dist/userProperties/store.js +155 -0
  67. package/dist/userProperties/store.js.map +1 -0
  68. package/dist/userProperties/types.d.ts +21 -0
  69. package/dist/userProperties/types.d.ts.map +1 -0
  70. package/dist/userProperties/types.js +3 -0
  71. package/dist/userProperties/types.js.map +1 -0
  72. package/dist/userProperties/useUserProperties.d.ts +20 -0
  73. package/dist/userProperties/useUserProperties.d.ts.map +1 -0
  74. package/dist/userProperties/useUserProperties.js +30 -0
  75. package/dist/userProperties/useUserProperties.js.map +1 -0
  76. package/package.json +5 -1
  77. package/src/OnboardingStudio.ts +147 -0
  78. package/src/OnboardingStudioClient.ts +27 -11
  79. package/src/__tests__/OnboardingDataGate.test.tsx +445 -0
  80. package/src/__tests__/OnboardingStudio.test.ts +208 -0
  81. package/src/__tests__/cacheKey.test.ts +71 -0
  82. package/src/__tests__/getOnboarding.query.test.ts +47 -8
  83. package/src/index.ts +43 -0
  84. package/src/infra/provider/OnboardingProvider.tsx +98 -10
  85. package/src/infra/queries/cacheKey.ts +54 -9
  86. package/src/infra/queries/getOnboarding.query.ts +9 -1
  87. package/src/paywalls/PaywallProvider.tsx +162 -6
  88. package/src/paywalls/__tests__/catalogSettleWaiter.test.ts +134 -0
  89. package/src/paywalls/__tests__/getPaywalls.test.ts +29 -11
  90. package/src/paywalls/__tests__/register.test.ts +266 -0
  91. package/src/paywalls/catalogSettleWaiter.ts +72 -0
  92. package/src/paywalls/getPaywalls.query.ts +9 -1
  93. package/src/paywalls/register.ts +169 -0
  94. package/src/paywalls/usePaywall.ts +40 -2
  95. package/src/userProperties/__tests__/effectiveParams.test.ts +51 -0
  96. package/src/userProperties/__tests__/primitives.test.ts +96 -0
  97. package/src/userProperties/__tests__/store.test.ts +181 -0
  98. package/src/userProperties/applyPatch.ts +68 -0
  99. package/src/userProperties/effectiveParams.ts +60 -0
  100. package/src/userProperties/index.ts +11 -0
  101. package/src/userProperties/reserved.ts +44 -0
  102. package/src/userProperties/serialize.ts +61 -0
  103. package/src/userProperties/store.ts +179 -0
  104. package/src/userProperties/types.ts +22 -0
  105. package/src/userProperties/useUserProperties.ts +26 -0
@@ -0,0 +1,71 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import {
3
+ getOnboardingCacheKey,
4
+ getPaywallsCacheKey,
5
+ DEFAULT_ONBOARDING_CACHE_KEY,
6
+ DEFAULT_PAYWALLS_CACHE_KEY,
7
+ ONBOARDING_CACHE_KEY_PREFIX,
8
+ PAYWALLS_CACHE_KEY_PREFIX,
9
+ } from "../infra/queries/cacheKey";
10
+ import { paramsHash } from "../userProperties/serialize";
11
+ import { USER_PROPERTIES_STORAGE_KEY } from "../userProperties/store";
12
+
13
+ describe("cache keys", () => {
14
+ it("is byte-identical to the legacy key when there are no params", () => {
15
+ expect(getOnboardingCacheKey()).toBe(DEFAULT_ONBOARDING_CACHE_KEY);
16
+ expect(getOnboardingCacheKey(undefined, "")).toBe(DEFAULT_ONBOARDING_CACHE_KEY);
17
+ expect(getPaywallsCacheKey()).toBe(DEFAULT_PAYWALLS_CACHE_KEY);
18
+ expect(getPaywallsCacheKey(undefined, "")).toBe(DEFAULT_PAYWALLS_CACHE_KEY);
19
+ expect(getPaywallsCacheKey("v2")).toBe("rocapine-paywalls-sdk-v2");
20
+ expect(getOnboardingCacheKey("v2")).toBe("rocapine-onboarding-sdk-v2");
21
+ });
22
+
23
+ it("appends the hash when params are present", () => {
24
+ const hash = paramsHash({ plan: "free" });
25
+ expect(getPaywallsCacheKey(undefined, hash)).toBe(`${DEFAULT_PAYWALLS_CACHE_KEY}-${hash}`);
26
+ expect(getPaywallsCacheKey("v2", hash)).toBe(`rocapine-paywalls-sdk-v2-${hash}`);
27
+ });
28
+
29
+ it("gives different params different keys", () => {
30
+ const a = getPaywallsCacheKey(undefined, paramsHash({ plan: "free" }));
31
+ const b = getPaywallsCacheKey(undefined, paramsHash({ plan: "pro" }));
32
+ expect(a).not.toBe(b);
33
+ });
34
+
35
+ it("gives the same params the same key regardless of insertion order", () => {
36
+ const a = getPaywallsCacheKey(undefined, paramsHash({ plan: "free", days: "3" }));
37
+ const b = getPaywallsCacheKey(undefined, paramsHash({ days: "3", plan: "free" }));
38
+ expect(a).toBe(b);
39
+ });
40
+
41
+ it("keeps the two domains on separate prefixes", () => {
42
+ const hash = paramsHash({ plan: "free" });
43
+ expect(getOnboardingCacheKey(undefined, hash).startsWith(ONBOARDING_CACHE_KEY_PREFIX)).toBe(true);
44
+ expect(getPaywallsCacheKey(undefined, hash).startsWith(PAYWALLS_CACHE_KEY_PREFIX)).toBe(true);
45
+ });
46
+
47
+ it("every key a helper can produce starts with its prefix, so clearCache finds it", () => {
48
+ const hash = paramsHash({ plan: "free" });
49
+ for (const key of [
50
+ getPaywallsCacheKey(),
51
+ getPaywallsCacheKey("v2"),
52
+ getPaywallsCacheKey(undefined, hash),
53
+ getPaywallsCacheKey("v2", hash),
54
+ ]) {
55
+ expect(key.startsWith(PAYWALLS_CACHE_KEY_PREFIX)).toBe(true);
56
+ }
57
+ for (const key of [
58
+ getOnboardingCacheKey(),
59
+ getOnboardingCacheKey("v2"),
60
+ getOnboardingCacheKey(undefined, hash),
61
+ getOnboardingCacheKey("v2", hash),
62
+ ]) {
63
+ expect(key.startsWith(ONBOARDING_CACHE_KEY_PREFIX)).toBe(true);
64
+ }
65
+ });
66
+
67
+ it("does not match the user-property key, which clearCache must never wipe", () => {
68
+ expect(USER_PROPERTIES_STORAGE_KEY.startsWith(ONBOARDING_CACHE_KEY_PREFIX)).toBe(false);
69
+ expect(USER_PROPERTIES_STORAGE_KEY.startsWith(PAYWALLS_CACHE_KEY_PREFIX)).toBe(false);
70
+ });
71
+ });
@@ -1,13 +1,17 @@
1
1
  import { describe, it, expect, vi, beforeEach } from "vitest";
2
2
 
3
3
  // AsyncStorage is mocked — the query reads/writes the production cache through it.
4
- const { getItem, setItem, removeItem } = vi.hoisted(() => ({
4
+ const { getItem, setItem, removeItem, getAllKeys, multiRemove } = vi.hoisted(() => ({
5
5
  getItem: vi.fn<(key: string) => Promise<string | null>>(),
6
6
  setItem: vi.fn<(key: string, value: string) => Promise<void>>(),
7
7
  removeItem: vi.fn<(key: string) => Promise<void>>(),
8
+ // `clearCache` scans by prefix now, because the keys are scoped by a hash of
9
+ // the resolved audience params and are no longer predictable one-by-one.
10
+ getAllKeys: vi.fn<() => Promise<string[]>>(),
11
+ multiRemove: vi.fn<(keys: string[]) => Promise<void>>(),
8
12
  }));
9
13
  vi.mock("@react-native-async-storage/async-storage", () => ({
10
- default: { getItem, setItem, removeItem },
14
+ default: { getItem, setItem, removeItem, getAllKeys, multiRemove },
11
15
  }));
12
16
  // OnboardingStudioClient (used by the clearCache test) imports `react-native`
13
17
  // for `Platform`; stub it so the class loads under Node.
@@ -156,17 +160,52 @@ describe("getOnboardingCacheKey", () => {
156
160
  });
157
161
 
158
162
  describe("OnboardingStudioClient.clearCache", () => {
159
- beforeEach(() => removeItem.mockReset());
163
+ beforeEach(() => {
164
+ multiRemove.mockReset();
165
+ multiRemove.mockResolvedValue(undefined);
166
+ getAllKeys.mockReset();
167
+ });
168
+
169
+ it("clears every param variant of both domains, plus any legacy unscoped key", async () => {
170
+ getAllKeys.mockResolvedValue([
171
+ CACHE_KEY,
172
+ `${CACHE_KEY}-7f3a1c92`,
173
+ CUSTOM_CACHE_KEY,
174
+ "rocapine-paywalls-studio",
175
+ "rocapine-paywalls-sdk-v2-deadbeef",
176
+ "unrelated-app-key",
177
+ ]);
178
+ const client = new OnboardingStudioClient("p1", {});
179
+ await client.clearCache();
180
+ expect(multiRemove).toHaveBeenCalledWith([
181
+ CACHE_KEY,
182
+ `${CACHE_KEY}-7f3a1c92`,
183
+ CUSTOM_CACHE_KEY,
184
+ "rocapine-paywalls-studio",
185
+ "rocapine-paywalls-sdk-v2-deadbeef",
186
+ ]);
187
+ });
160
188
 
161
- it("removes the default key when no custom key is configured", async () => {
189
+ it("leaves user properties alone — clearing a cache must not forget who the user is", async () => {
190
+ getAllKeys.mockResolvedValue(["rocapine-user-properties"]);
162
191
  const client = new OnboardingStudioClient("p1", {});
163
192
  await client.clearCache();
164
- expect(removeItem).toHaveBeenCalledWith(CACHE_KEY);
193
+ expect(multiRemove).not.toHaveBeenCalled();
165
194
  });
166
195
 
167
- it("removes the namespaced key when a custom key is configured", async () => {
168
- const client = new OnboardingStudioClient("p1", { cacheKey: CUSTOM_KEY });
196
+ it("does nothing when there is nothing of ours to clear", async () => {
197
+ getAllKeys.mockResolvedValue(["unrelated-app-key"]);
198
+ const client = new OnboardingStudioClient("p1", {});
169
199
  await client.clearCache();
170
- expect(removeItem).toHaveBeenCalledWith(CUSTOM_CACHE_KEY);
200
+ expect(multiRemove).not.toHaveBeenCalled();
201
+ });
202
+
203
+ it("does not throw when storage enumeration fails", async () => {
204
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
205
+ getAllKeys.mockRejectedValue(new Error("storage unavailable"));
206
+ const client = new OnboardingStudioClient("p1", {});
207
+ await expect(client.clearCache()).resolves.toBeUndefined();
208
+ expect(warn).toHaveBeenCalled();
209
+ warn.mockRestore();
171
210
  });
172
211
  });
package/src/index.ts CHANGED
@@ -47,6 +47,49 @@ export {
47
47
  generateWheelPickerRangeItems,
48
48
  resolveWheelPickerItems,
49
49
  } from "./steps/ComposableScreen/types";
50
+ // The SDK's front door: configuration (`init`) and user identity
51
+ // (`setUserProperty`, `reset`), in the shape of the SDKs it sits alongside —
52
+ // `Superwall.configure`, `Purchases.configure`, `amplitude.init`.
53
+ //
54
+ // User properties feed audience resolution for BOTH onboardings and paywalls.
55
+ // This is a module-level object rather than a provider so non-React code — a
56
+ // login handler, an analytics service — can write to it; see
57
+ // `userProperties/store.ts` for why that one departure from the package's
58
+ // provider+context pattern is the point rather than an oversight.
59
+ //
60
+ // `register`/`present` are NOT here: presenting needs the mounted provider's
61
+ // state, so they stay on `usePaywall()`.
62
+ export { OnboardingStudio } from "./OnboardingStudio";
63
+ export type { OnboardingStudioConfig, OnboardingStudioFacade } from "./OnboardingStudio";
64
+ // `useUserProperties()` is the React READ path; the write path is the facade.
65
+ //
66
+ // The internal helpers (`toQueryParams`, `paramsHash`, `applyUserPropertyPatch`,
67
+ // `resolveEffectiveParams`, `userPropertyStore`) are deliberately NOT exported:
68
+ // they are implementation detail, and `paramsHash` in particular is a cache-key
69
+ // concern a host reproducing it would only drift from.
70
+ export {
71
+ useUserProperties,
72
+ createUserPropertyStore,
73
+ USER_PROPERTIES_STORAGE_KEY,
74
+ RESERVED_USER_PROPERTY_KEYS,
75
+ isReservedUserPropertyKey,
76
+ } from "./userProperties";
77
+ export type {
78
+ UserProperties,
79
+ UserPropertyPatch,
80
+ UserPropertyValue,
81
+ UserPropertySnapshot,
82
+ UserPropertyStorage,
83
+ UserPropertyStore,
84
+ } from "./userProperties";
85
+ // `register(moment, feature)` — gate a feature on a moment. The decision helpers
86
+ // are exported because they are pure: a host building its own gating on top of
87
+ // `catalog` can reuse the SDK's exact rules rather than reimplement them slightly
88
+ // differently. `runRegister` and `RegisterDeps` stay internal — that seam exists
89
+ // for its own test.
90
+ export { resolveRegisterDecision, shouldRunFeature } from "./paywalls/register";
91
+ export type { RegisterDecision, RegisterFeature, RegisterResult } from "./paywalls/register";
92
+ export { DEFAULT_REGISTER_TIMEOUT_MS } from "./paywalls/PaywallProvider";
50
93
  // A step that IS a paywall: `payload.moment` names a moment, and the audience
51
94
  // waterfall behind it picks which paywall renders.
52
95
  export type { PaywallStepType } from "./steps/Paywall/types";
@@ -10,6 +10,13 @@ import { extractAssetUrls } from "../preload/extractAssetUrls";
10
10
  import { preloadAssets } from "../preload/preloadAssets";
11
11
  import { collectUnknownKeysInSteps, formatUnknownElementKeys } from "../../screens/unknownKeys";
12
12
  import { OnboardingNavigationAdapter } from "../navigation/types";
13
+ import { useUserProperties } from "../../userProperties/useUserProperties";
14
+ import { resolveEffectiveParams } from "../../userProperties/effectiveParams";
15
+ import {
16
+ OnboardingStudio,
17
+ resolveProviderClient,
18
+ MISSING_CLIENT_MESSAGE,
19
+ } from "../../OnboardingStudio";
13
20
  import { expoRouterAdapter } from "../navigation/expoRouterAdapter";
14
21
  import { useProducts } from "../../products/useProducts";
15
22
  import { ProductProvider, ProductRef, ProductRuntime } from "../../products/types";
@@ -103,8 +110,21 @@ export type OnboardingCompleteHandler = (
103
110
 
104
111
  interface OnboardingProviderProps {
105
112
  children: React.ReactNode;
106
- client: OnboardingStudioClient;
113
+ /**
114
+ * The studio client. Optional: omit it and the provider uses the client
115
+ * `OnboardingStudio.init({ projectId })` built. Passing one explicitly still
116
+ * wins, so an existing host is unaffected.
117
+ *
118
+ * With neither, this provider THROWS — an onboarding with no client has
119
+ * nothing to render, and a host `ErrorBoundary` gets a message naming both
120
+ * fixes.
121
+ */
122
+ client?: OnboardingStudioClient;
107
123
  locale?: string;
124
+ /**
125
+ * Static audience params (build-time facts). Merged under the user-property
126
+ * store and read once, when the onboarding is served — see `useAudienceParams`.
127
+ */
108
128
  customAudienceParams?: Record<string, any>;
109
129
  /**
110
130
  * Map of named handlers invokable from ComposableScreen Button `actions`
@@ -146,26 +166,71 @@ interface OnboardingProviderProps {
146
166
  productRefs?: ProductRef[];
147
167
  }
148
168
 
169
+ /**
170
+ * The audience params this onboarding is served with: the `customAudienceParams`
171
+ * prop merged with the user-property store, resolved ONCE when the store is
172
+ * ready and then pinned for the life of the provider. `null` while hydrating.
173
+ *
174
+ * Audience resolution happens at serve time and a served onboarding is frozen:
175
+ * a `setUserProperty` during the flow does not change these, so it cannot
176
+ * re-key the query, refetch, or swap the onboarding under the user. It applies
177
+ * to the next serve (next mount / launch). `PaywallProvider` deliberately keeps
178
+ * following the store — a paywall is served later, at `register(moment)`.
179
+ *
180
+ * So the two CAN resolve against different properties for the same user: a
181
+ * property written mid-flow reaches a paywall served afterwards (including a
182
+ * paywall step later in this same onboarding) but not the onboarding around it.
183
+ * That is intended, not a gap — it is the "set the property, then register the
184
+ * moment" model — and both still read ONE store; they differ only in when they
185
+ * read it.
186
+ */
187
+ const useAudienceParams = (
188
+ customAudienceParams: Record<string, any>
189
+ ): Record<string, string> | null => {
190
+ const { properties, status } = useUserProperties();
191
+ // State rather than a ref: a pin taken in a render React later discards is
192
+ // discarded with it, so the served params always come from a committed render.
193
+ const [pinned, setPinned] = useState<Record<string, string> | null>(null);
194
+ if (pinned === null && status === "ready") {
195
+ const resolved = resolveEffectiveParams(customAudienceParams, properties);
196
+ setPinned(resolved);
197
+ return resolved;
198
+ }
199
+ return pinned;
200
+ };
201
+
149
202
  interface OnboardingDataGateProps {
150
203
  client: OnboardingStudioClient;
151
204
  locale: string;
152
- customAudienceParams: Record<string, any>;
205
+ /** From `useAudienceParams`; `null` disables the query until the store is ready. */
206
+ audienceParams: Record<string, string> | null;
153
207
  setOnboarding: (onboarding: Onboarding<OnboardingStepType>) => void;
154
208
  fontsFallback?: React.ReactNode;
155
209
  children: React.ReactNode;
156
210
  }
157
211
 
212
+ /**
213
+ * Fetches the onboarding and holds the subtree until it is there. The query is
214
+ * disabled while `audienceParams` is `null` (store still hydrating); the gate
215
+ * shows `fontsFallback` meanwhile, as it already does while the payload loads.
216
+ */
158
217
  const OnboardingDataGate = ({
159
218
  client,
160
219
  locale,
161
- customAudienceParams,
220
+ audienceParams,
162
221
  setOnboarding,
163
222
  fontsFallback,
164
223
  children,
165
224
  }: OnboardingDataGateProps) => {
166
- const { data, error } = useQuery<Onboarding<OnboardingStepType>>(
167
- getOnboardingQuery<OnboardingStepType>(client, locale, customAudienceParams, setOnboarding)
168
- );
225
+ const { data, error } = useQuery<Onboarding<OnboardingStepType>>({
226
+ ...getOnboardingQuery<OnboardingStepType>(
227
+ client,
228
+ locale,
229
+ audienceParams ?? {},
230
+ setOnboarding
231
+ ),
232
+ enabled: audienceParams !== null,
233
+ });
169
234
 
170
235
  // Background asset preload: once the payload is available, warm every remote
171
236
  // image/video/Lottie/Rive asset so later screens render without a load flash.
@@ -190,7 +255,11 @@ const OnboardingDataGate = ({
190
255
  }, [data]);
191
256
 
192
257
  if (error) throw error;
193
- if (!data) return <>{fontsFallback ?? null}</>;
258
+ // Both checks, not just `!data`: a disabled query still returns cached data for
259
+ // its key, and the unpinned key (`{}`) is also a legitimate pinned one. Holding
260
+ // on `audienceParams` makes "children mount only once the params are pinned"
261
+ // structural, so nothing below can ever fetch under un-pinned params.
262
+ if (audienceParams === null || !data) return <>{fontsFallback ?? null}</>;
194
263
 
195
264
  return (
196
265
  <FontLoaderGate fonts={data.fonts} fallback={fontsFallback}>
@@ -201,7 +270,7 @@ const OnboardingDataGate = ({
201
270
 
202
271
  export const OnboardingProvider = ({
203
272
  children,
204
- client,
273
+ client: clientProp,
205
274
  locale = "en",
206
275
  customAudienceParams = {},
207
276
  customActions = EMPTY_CUSTOM_ACTIONS,
@@ -211,6 +280,23 @@ export const OnboardingProvider = ({
211
280
  productProvider,
212
281
  productRefs,
213
282
  }: OnboardingProviderProps) => {
283
+ // An explicit prop wins; otherwise use whatever `OnboardingStudio.init()`
284
+ // built. THROWN rather than degraded, unlike `PaywallProvider`: this provider
285
+ // wraps an onboarding, so a host `ErrorBoundary` catches it and the rest of the
286
+ // app survives — and an onboarding with no client has nothing at all to render,
287
+ // where a paywall-less app is merely un-monetised.
288
+ //
289
+ // Read during render, so `init()` must run BEFORE the first render — at module
290
+ // scope, which is where the warning tells a host to put it.
291
+ const client = resolveProviderClient(clientProp, OnboardingStudio.getClient());
292
+ if (!client) throw new Error(MISSING_CLIENT_MESSAGE);
293
+
294
+ // Resolved here, once, and handed to BOTH the context (read by the step hooks)
295
+ // and the data gate — so they build the same query. Resolving in the gate
296
+ // alone, as before, left the hooks with the raw prop: a second fetch under a
297
+ // different key, resolved without the user's properties, was what rendered.
298
+ const audienceParams = useAudienceParams(customAudienceParams);
299
+
214
300
  const [activeStep, setActiveStep] = useState({
215
301
  number: 0,
216
302
  displayProgressHeader: false,
@@ -299,7 +385,9 @@ export const OnboardingProvider = ({
299
385
  setHeaderHeight,
300
386
  client,
301
387
  locale,
302
- customAudienceParams,
388
+ // The raw prop is never observed: the data gate holds `children` until
389
+ // the params are pinned, and everything reading this context is a child.
390
+ customAudienceParams: audienceParams ?? customAudienceParams,
303
391
  onboarding,
304
392
  setOnboarding,
305
393
  variables,
@@ -314,7 +402,7 @@ export const OnboardingProvider = ({
314
402
  <OnboardingDataGate
315
403
  client={client}
316
404
  locale={locale}
317
- customAudienceParams={customAudienceParams}
405
+ audienceParams={audienceParams}
318
406
  setOnboarding={setOnboarding}
319
407
  fontsFallback={fontsFallback}
320
408
  >
@@ -5,9 +5,46 @@
5
5
  * Lives in its own module so `getOnboarding.query.ts`, `getPaywalls.query.ts`
6
6
  * and `OnboardingStudioClient` can all use these as values without a circular
7
7
  * import (the query modules import `OnboardingStudioClient` for typing) —
8
- * this module itself has no imports.
8
+ * this module itself has no imports, and must keep none that reach
9
+ * `OnboardingStudioClient`.
10
+ *
11
+ * ## Why the key is scoped by params
12
+ *
13
+ * The react-query key has always been scoped by `customAudienceParams`; this
14
+ * disk key was a bare constant. So a cache-first read could serve a payload
15
+ * resolved under DIFFERENT params — non-null, and therefore indistinguishable
16
+ * from a correct one — with a fresh fetch in flight behind it.
17
+ *
18
+ * Observed in production: an audience gated on `hoursSinceOnboardingPaywall >= 44`
19
+ * was served the pre-threshold catalog on the launch where the user first became
20
+ * eligible, so the arm under test lost exactly the launch that mattered.
21
+ *
22
+ * That needed volatile params to trigger, which was rare while params were a
23
+ * static prop. The user-property store makes volatile params normal, so the key
24
+ * carries a hash of the resolved params (`userProperties/serialize.ts`'s
25
+ * `paramsHash`). An EMPTY hash yields the legacy key byte-for-byte, so shipping
26
+ * this does not invalidate existing installs.
27
+ *
28
+ * Every key these helpers can produce starts with one of the two prefixes below,
29
+ * which is what lets `OnboardingStudioClient.clearCache` find them all by
30
+ * scanning rather than by naming a key it can no longer predict.
9
31
  */
10
32
 
33
+ /**
34
+ * Every onboarding cache key starts with this — `clearCache` scans on it.
35
+ *
36
+ * Deliberately NOT a bare `rocapine-`: `USER_PROPERTIES_STORAGE_KEY` is
37
+ * `rocapine-user-properties`, and clearing a payload cache must not forget who
38
+ * the user is.
39
+ */
40
+ export const ONBOARDING_CACHE_KEY_PREFIX = "rocapine-onboarding";
41
+
42
+ /** Every paywall cache key starts with this — `clearCache` scans on it. */
43
+ export const PAYWALLS_CACHE_KEY_PREFIX = "rocapine-paywalls";
44
+
45
+ /** Appends the params fingerprint, or nothing at all when there are no params. */
46
+ const withHash = (base: string, hash?: string): string => (hash ? `${base}-${hash}` : base);
47
+
11
48
  /** Default cache key used when the host does not provide a custom one. */
12
49
  export const DEFAULT_ONBOARDING_CACHE_KEY = "rocapine-onboarding-studio";
13
50
 
@@ -19,11 +56,15 @@ export const DEFAULT_ONBOARDING_CACHE_KEY = "rocapine-onboarding-studio";
19
56
  * - Custom key → `"rocapine-onboarding-sdk-{customKey}"`, which the SDK
20
57
  * persists cache-first with **no** background revalidation, so the host owns
21
58
  * when to refetch (see `OnboardingStudioClient.clearCache`).
59
+ *
60
+ * `paramsHash` scopes the key to the resolved audience params — see the module
61
+ * doc. Omit it (or pass `""`) for the legacy, unscoped key.
22
62
  */
23
- export const getOnboardingCacheKey = (customKey?: string): string =>
24
- customKey
25
- ? `rocapine-onboarding-sdk-${customKey}`
26
- : DEFAULT_ONBOARDING_CACHE_KEY;
63
+ export const getOnboardingCacheKey = (customKey?: string, paramsHash?: string): string =>
64
+ withHash(
65
+ customKey ? `rocapine-onboarding-sdk-${customKey}` : DEFAULT_ONBOARDING_CACHE_KEY,
66
+ paramsHash,
67
+ );
27
68
 
28
69
  /** Default cache key used when the host does not provide a custom one. */
29
70
  export const DEFAULT_PAYWALLS_CACHE_KEY = "rocapine-paywalls-studio";
@@ -40,8 +81,12 @@ export const DEFAULT_PAYWALLS_CACHE_KEY = "rocapine-paywalls-studio";
40
81
  * - Custom key → `"rocapine-paywalls-sdk-{customKey}"`, which the SDK persists
41
82
  * cache-first with **no** background revalidation, so the host owns when to
42
83
  * refetch (see `OnboardingStudioClient.clearCache`).
84
+ *
85
+ * `paramsHash` scopes the key to the resolved audience params — see the module
86
+ * doc. Omit it (or pass `""`) for the legacy, unscoped key.
43
87
  */
44
- export const getPaywallsCacheKey = (customKey?: string): string =>
45
- customKey
46
- ? `rocapine-paywalls-sdk-${customKey}`
47
- : DEFAULT_PAYWALLS_CACHE_KEY;
88
+ export const getPaywallsCacheKey = (customKey?: string, paramsHash?: string): string =>
89
+ withHash(
90
+ customKey ? `rocapine-paywalls-sdk-${customKey}` : DEFAULT_PAYWALLS_CACHE_KEY,
91
+ paramsHash,
92
+ );
@@ -3,6 +3,7 @@ import { OnboardingStudioClient } from "../../OnboardingStudioClient";
3
3
  import { BaseStepType, Onboarding, OnboardingMetadata } from "../../types";
4
4
  import type { UseQueryOptions } from "@tanstack/react-query";
5
5
  import { getOnboardingCacheKey } from "./cacheKey";
6
+ import { paramsHash } from "../../userProperties/serialize";
6
7
 
7
8
  export const getOnboardingQuery = <StepType extends BaseStepType>(
8
9
  client: OnboardingStudioClient,
@@ -26,7 +27,14 @@ export const getOnboardingQuery = <StepType extends BaseStepType>(
26
27
  // with NO background revalidation, so a pinned version survives across
27
28
  // launches. The default key keeps stale-while-revalidate.
28
29
  const hasCustomKey = Boolean(client.options.cacheKey);
29
- const cacheKey = getOnboardingCacheKey(client.options.cacheKey);
30
+ // Scoped by the resolved audience params — see `cacheKey.ts`. The provider
31
+ // hands these over already serialized to strings
32
+ // (`userProperties/effectiveParams.ts`), so the hash sees the same bytes
33
+ // that go on the querystring.
34
+ const cacheKey = getOnboardingCacheKey(
35
+ client.options.cacheKey,
36
+ paramsHash(customAudienceParams as Record<string, string>),
37
+ );
30
38
 
31
39
  // Fetches the live payload, pushes it to the provider, and caches it —
32
40
  // but NEVER caches the offline fallback. Caching the fallback (with