@rocapine/react-native-onboarding 1.72.0 → 1.74.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 (117) hide show
  1. package/README.md +136 -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 +10 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +43 -4
  13. package/dist/index.js.map +1 -1
  14. package/dist/infra/provider/OnboardingProvider.d.ts +11 -2
  15. package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
  16. package/dist/infra/provider/OnboardingProvider.js +26 -2
  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 +95 -5
  26. package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
  27. package/dist/paywalls/PaywallProvider.js +121 -9
  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/customScreens.d.ts +83 -0
  34. package/dist/paywalls/customScreens.d.ts.map +1 -0
  35. package/dist/paywalls/customScreens.js +3 -0
  36. package/dist/paywalls/customScreens.js.map +1 -0
  37. package/dist/paywalls/getPaywalls.query.d.ts.map +1 -1
  38. package/dist/paywalls/getPaywalls.query.js +6 -1
  39. package/dist/paywalls/getPaywalls.query.js.map +1 -1
  40. package/dist/paywalls/register.d.ts +105 -0
  41. package/dist/paywalls/register.d.ts.map +1 -0
  42. package/dist/paywalls/register.js +112 -0
  43. package/dist/paywalls/register.js.map +1 -0
  44. package/dist/paywalls/usePaywall.d.ts +43 -0
  45. package/dist/paywalls/usePaywall.d.ts.map +1 -1
  46. package/dist/paywalls/usePaywall.js +11 -2
  47. package/dist/paywalls/usePaywall.js.map +1 -1
  48. package/dist/steps/Paywall/types.d.ts +63 -0
  49. package/dist/steps/Paywall/types.d.ts.map +1 -0
  50. package/dist/steps/Paywall/types.js +29 -0
  51. package/dist/steps/Paywall/types.js.map +1 -0
  52. package/dist/steps/types.d.ts +2 -1
  53. package/dist/steps/types.d.ts.map +1 -1
  54. package/dist/userProperties/applyPatch.d.ts +18 -0
  55. package/dist/userProperties/applyPatch.d.ts.map +1 -0
  56. package/dist/userProperties/applyPatch.js +57 -0
  57. package/dist/userProperties/applyPatch.js.map +1 -0
  58. package/dist/userProperties/effectiveParams.d.ts +29 -0
  59. package/dist/userProperties/effectiveParams.d.ts.map +1 -0
  60. package/dist/userProperties/effectiveParams.js +56 -0
  61. package/dist/userProperties/effectiveParams.js.map +1 -0
  62. package/dist/userProperties/index.d.ts +9 -0
  63. package/dist/userProperties/index.d.ts.map +1 -0
  64. package/dist/userProperties/index.js +21 -0
  65. package/dist/userProperties/index.js.map +1 -0
  66. package/dist/userProperties/reserved.d.ts +33 -0
  67. package/dist/userProperties/reserved.d.ts.map +1 -0
  68. package/dist/userProperties/reserved.js +45 -0
  69. package/dist/userProperties/reserved.js.map +1 -0
  70. package/dist/userProperties/serialize.d.ts +38 -0
  71. package/dist/userProperties/serialize.d.ts.map +1 -0
  72. package/dist/userProperties/serialize.js +67 -0
  73. package/dist/userProperties/serialize.js.map +1 -0
  74. package/dist/userProperties/store.d.ts +63 -0
  75. package/dist/userProperties/store.d.ts.map +1 -0
  76. package/dist/userProperties/store.js +153 -0
  77. package/dist/userProperties/store.js.map +1 -0
  78. package/dist/userProperties/types.d.ts +21 -0
  79. package/dist/userProperties/types.d.ts.map +1 -0
  80. package/dist/userProperties/types.js +3 -0
  81. package/dist/userProperties/types.js.map +1 -0
  82. package/dist/userProperties/useUserProperties.d.ts +20 -0
  83. package/dist/userProperties/useUserProperties.d.ts.map +1 -0
  84. package/dist/userProperties/useUserProperties.js +30 -0
  85. package/dist/userProperties/useUserProperties.js.map +1 -0
  86. package/package.json +1 -1
  87. package/src/OnboardingStudio.ts +147 -0
  88. package/src/OnboardingStudioClient.ts +27 -11
  89. package/src/__tests__/OnboardingStudio.test.ts +208 -0
  90. package/src/__tests__/cacheKey.test.ts +71 -0
  91. package/src/__tests__/getOnboarding.query.test.ts +47 -8
  92. package/src/index.ts +51 -0
  93. package/src/infra/provider/OnboardingProvider.tsx +45 -4
  94. package/src/infra/queries/cacheKey.ts +54 -9
  95. package/src/infra/queries/getOnboarding.query.ts +9 -1
  96. package/src/paywalls/PaywallProvider.tsx +226 -9
  97. package/src/paywalls/__tests__/catalogSettleWaiter.test.ts +134 -0
  98. package/src/paywalls/__tests__/getPaywalls.test.ts +29 -11
  99. package/src/paywalls/__tests__/register.test.ts +266 -0
  100. package/src/paywalls/catalogSettleWaiter.ts +72 -0
  101. package/src/paywalls/customScreens.ts +82 -0
  102. package/src/paywalls/getPaywalls.query.ts +9 -1
  103. package/src/paywalls/register.ts +169 -0
  104. package/src/paywalls/usePaywall.ts +63 -3
  105. package/src/steps/Paywall/types.ts +29 -0
  106. package/src/steps/types.ts +2 -0
  107. package/src/userProperties/__tests__/effectiveParams.test.ts +51 -0
  108. package/src/userProperties/__tests__/primitives.test.ts +96 -0
  109. package/src/userProperties/__tests__/store.test.ts +181 -0
  110. package/src/userProperties/applyPatch.ts +68 -0
  111. package/src/userProperties/effectiveParams.ts +60 -0
  112. package/src/userProperties/index.ts +11 -0
  113. package/src/userProperties/reserved.ts +44 -0
  114. package/src/userProperties/serialize.ts +61 -0
  115. package/src/userProperties/store.ts +177 -0
  116. package/src/userProperties/types.ts +22 -0
  117. package/src/userProperties/useUserProperties.ts +26 -0
@@ -9,8 +9,8 @@ import {
9
9
  BaseStepType,
10
10
  } from "./types";
11
11
  import {
12
- getOnboardingCacheKey,
13
- getPaywallsCacheKey,
12
+ ONBOARDING_CACHE_KEY_PREFIX,
13
+ PAYWALLS_CACHE_KEY_PREFIX,
14
14
  } from "./infra/queries/cacheKey";
15
15
  import {
16
16
  PaywallCatalog,
@@ -35,18 +35,34 @@ export class OnboardingStudioClient {
35
35
  }
36
36
 
37
37
  /**
38
- * Removes this client's cached onboarding payload AND cached paywall catalog
39
- * from AsyncStorage (the keys derived from `options.cacheKey`, or the
40
- * default keys). The next query mount or app launch is then a cache miss
41
- * and refetches both. To force an in-session refetch as well, also
42
- * invalidate the React Query keys `["onboardingQuestions", ...]` and
38
+ * Removes EVERY cached onboarding payload and paywall catalog this SDK wrote,
39
+ * across all audience-param variants. The next query mount or app launch is
40
+ * then a cache miss and refetches. To force an in-session refetch as well,
41
+ * also invalidate the React Query keys `["onboardingQuestions", ...]` and
43
42
  * `["paywallCatalog", ...]`.
43
+ *
44
+ * Scans `getAllKeys()` by prefix rather than naming two keys, because the keys
45
+ * are now scoped by a hash of the resolved audience params (see
46
+ * `infra/queries/cacheKey.ts`) — so there is no longer one key per domain to
47
+ * name. This also picks up entries written before that scoping existed, which
48
+ * would otherwise be orphaned forever.
49
+ *
50
+ * It does NOT clear user properties: `USER_PROPERTIES_STORAGE_KEY` matches
51
+ * neither prefix, deliberately. Clearing a payload cache must not forget who
52
+ * the user is — that is what `OnboardingStudio.reset()` is for.
44
53
  */
45
54
  async clearCache(): Promise<void> {
46
- await Promise.all([
47
- AsyncStorage.removeItem(getOnboardingCacheKey(this.options.cacheKey)),
48
- AsyncStorage.removeItem(getPaywallsCacheKey(this.options.cacheKey)),
49
- ]);
55
+ try {
56
+ const keys = await AsyncStorage.getAllKeys();
57
+ const ours = keys.filter(
58
+ (key) =>
59
+ key.startsWith(ONBOARDING_CACHE_KEY_PREFIX) ||
60
+ key.startsWith(PAYWALLS_CACHE_KEY_PREFIX),
61
+ );
62
+ if (ours.length > 0) await AsyncStorage.multiRemove(ours);
63
+ } catch (error) {
64
+ console.warn("Failed to clear SDK caches:", error);
65
+ }
50
66
  }
51
67
 
52
68
  async getSteps<StepType extends BaseStepType = OnboardingStepType>(
@@ -0,0 +1,208 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+
3
+ // `OnboardingStudioClient` reads `Platform.OS`; stub it so the class loads under
4
+ // Node — the same stub the other client-touching suites use.
5
+ vi.mock("react-native", () => ({ Platform: { OS: "ios" } }));
6
+ // `userProperties/store.ts` constructs the real singleton at module scope from
7
+ // AsyncStorage. The facade under test is built over an INJECTED store, so this
8
+ // mock only has to let the import resolve.
9
+ const { getItem, setItem, removeItem } = vi.hoisted(() => ({
10
+ getItem: vi.fn(async () => null),
11
+ setItem: vi.fn(async () => {}),
12
+ removeItem: vi.fn(async () => {}),
13
+ }));
14
+ vi.mock("@react-native-async-storage/async-storage", () => ({
15
+ default: { getItem, setItem, removeItem },
16
+ }));
17
+
18
+ import {
19
+ createOnboardingStudio,
20
+ resolveProviderClient,
21
+ MISSING_CLIENT_MESSAGE,
22
+ } from "../OnboardingStudio";
23
+ import { createUserPropertyStore } from "../userProperties/store";
24
+ import { OnboardingStudioClient } from "../OnboardingStudioClient";
25
+
26
+ const makeStorage = () => {
27
+ const map = new Map<string, string>();
28
+ return {
29
+ getItem: vi.fn(async (k: string) => map.get(k) ?? null),
30
+ setItem: vi.fn(async (k: string, v: string) => void map.set(k, v)),
31
+ removeItem: vi.fn(async (k: string) => void map.delete(k)),
32
+ };
33
+ };
34
+
35
+ /** A fresh facade over a fresh store, so no test can leak into another. */
36
+ const makeStudio = () => {
37
+ const storage = makeStorage();
38
+ const store = createUserPropertyStore(storage);
39
+ return { studio: createOnboardingStudio(store), store, storage };
40
+ };
41
+
42
+ beforeEach(() => {
43
+ vi.restoreAllMocks();
44
+ vi.spyOn(console, "warn").mockImplementation(() => {});
45
+ });
46
+
47
+ describe("OnboardingStudio.init", () => {
48
+ it("is not initialized before init", () => {
49
+ const { studio } = makeStudio();
50
+ expect(studio.isInitialized()).toBe(false);
51
+ expect(studio.getClient()).toBeNull();
52
+ });
53
+
54
+ it("builds a client from the config and returns it", () => {
55
+ const { studio } = makeStudio();
56
+ const client = studio.init({ projectId: "abc", appVersion: "1.0.0" });
57
+
58
+ expect(client).toBeInstanceOf(OnboardingStudioClient);
59
+ expect(client.projectId).toBe("abc");
60
+ expect(client.options.appVersion).toBe("1.0.0");
61
+ expect(studio.isInitialized()).toBe(true);
62
+ expect(studio.getClient()).toBe(client);
63
+ });
64
+
65
+ it("does not leak `userProperties` into the client options", () => {
66
+ const { studio } = makeStudio();
67
+ const client = studio.init({ projectId: "abc", userProperties: { plan: "free" } });
68
+ expect("userProperties" in client.options).toBe(false);
69
+ });
70
+
71
+ it("seeds initial user properties, so targeting is right on a first-ever launch", () => {
72
+ const { studio } = makeStudio();
73
+ studio.init({ projectId: "abc", userProperties: { plan: "free", days: 3 } });
74
+ expect(studio.getUserProperties()).toEqual({ plan: "free", days: 3 });
75
+ });
76
+
77
+ it("is a silent no-op when called twice with the same config", () => {
78
+ const { studio } = makeStudio();
79
+ const first = studio.init({ projectId: "abc", appVersion: "1.0.0" });
80
+ const second = studio.init({ projectId: "abc", appVersion: "1.0.0" });
81
+
82
+ // Same client instance: Fast Refresh re-running module scope must not
83
+ // rebuild the client and orphan the one the providers already hold.
84
+ expect(second).toBe(first);
85
+ expect(console.warn).not.toHaveBeenCalled();
86
+ });
87
+
88
+ it("replaces the client and warns when called again with a different config", () => {
89
+ const { studio } = makeStudio();
90
+ const first = studio.init({ projectId: "abc" });
91
+ const second = studio.init({ projectId: "different" });
92
+
93
+ expect(second).not.toBe(first);
94
+ expect(studio.getClient()).toBe(second);
95
+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining("different"));
96
+ });
97
+
98
+ it("starts hydrating persisted properties without waiting for a provider", () => {
99
+ const { studio, storage } = makeStudio();
100
+ studio.init({ projectId: "abc" });
101
+ expect(storage.getItem).toHaveBeenCalled();
102
+ });
103
+
104
+ it("lets an init-time property win over a persisted one", async () => {
105
+ const storage = makeStorage();
106
+ await storage.setItem("rocapine-user-properties", JSON.stringify({ plan: "pro", days: 9 }));
107
+ const store = createUserPropertyStore(storage);
108
+ const studio = createOnboardingStudio(store);
109
+
110
+ studio.init({ projectId: "abc", userProperties: { plan: "free" } });
111
+ await store.ensureHydrated();
112
+
113
+ // The host's current knowledge beats last launch's; disk fills the gap.
114
+ expect(studio.getUserProperties()).toEqual({ plan: "free", days: 9 });
115
+ });
116
+ });
117
+
118
+ describe("OnboardingStudio user properties", () => {
119
+ it("sets a single property", () => {
120
+ const { studio } = makeStudio();
121
+ studio.setUserProperty("plan", "free");
122
+ expect(studio.getUserProperties()).toEqual({ plan: "free" });
123
+ });
124
+
125
+ it("deletes a property when the value is null", () => {
126
+ const { studio } = makeStudio();
127
+ studio.setUserProperty("plan", "free");
128
+ studio.setUserProperty("plan", null);
129
+ expect(studio.getUserProperties()).toEqual({});
130
+ });
131
+
132
+ it("merges a batch rather than replacing", () => {
133
+ const { studio } = makeStudio();
134
+ studio.setUserProperty("plan", "free");
135
+ studio.setUserProperties({ days: 3 });
136
+ expect(studio.getUserProperties()).toEqual({ plan: "free", days: 3 });
137
+ });
138
+
139
+ it("removes a property by name", () => {
140
+ const { studio } = makeStudio();
141
+ studio.setUserProperties({ plan: "free", days: 3 });
142
+ studio.removeUserProperty("plan");
143
+ expect(studio.getUserProperties()).toEqual({ days: 3 });
144
+ });
145
+
146
+ it("refuses a reserved name and warns", () => {
147
+ const { studio } = makeStudio();
148
+ studio.setUserProperty("projectId", "sneaky");
149
+ expect(studio.getUserProperties()).toEqual({});
150
+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining("projectId"));
151
+ });
152
+
153
+ it("works before init — properties are not gated on configuration", () => {
154
+ const { studio } = makeStudio();
155
+ studio.setUserProperty("plan", "free");
156
+ expect(studio.getUserProperties()).toEqual({ plan: "free" });
157
+ expect(studio.isInitialized()).toBe(false);
158
+ });
159
+ });
160
+
161
+ describe("OnboardingStudio.reset", () => {
162
+ it("clears user properties", () => {
163
+ const { studio } = makeStudio();
164
+ studio.setUserProperties({ plan: "free", days: 3 });
165
+ studio.reset();
166
+ expect(studio.getUserProperties()).toEqual({});
167
+ });
168
+
169
+ it("keeps the client — reset forgets the user, not the configuration", () => {
170
+ const { studio } = makeStudio();
171
+ const client = studio.init({ projectId: "abc" });
172
+ studio.reset();
173
+ expect(studio.getClient()).toBe(client);
174
+ expect(studio.isInitialized()).toBe(true);
175
+ });
176
+
177
+ it("does not clear the payload cache", () => {
178
+ // Logging out should forget who you are, not force a refetch of content that
179
+ // has not changed. `getClient()?.clearCache()` is there if both are wanted.
180
+ const { studio } = makeStudio();
181
+ const client = studio.init({ projectId: "abc" });
182
+ const clearCache = vi.spyOn(client, "clearCache");
183
+ studio.reset();
184
+ expect(clearCache).not.toHaveBeenCalled();
185
+ });
186
+ });
187
+
188
+ describe("resolveProviderClient", () => {
189
+ const a = new OnboardingStudioClient("prop", {});
190
+ const b = new OnboardingStudioClient("studio", {});
191
+
192
+ it("prefers the prop, so an existing host is unaffected", () => {
193
+ expect(resolveProviderClient(a, b)).toBe(a);
194
+ });
195
+
196
+ it("falls back to the studio's client", () => {
197
+ expect(resolveProviderClient(undefined, b)).toBe(b);
198
+ });
199
+
200
+ it("is null when neither exists", () => {
201
+ expect(resolveProviderClient(undefined, null)).toBeNull();
202
+ });
203
+
204
+ it("names both fixes in the missing-client message", () => {
205
+ expect(MISSING_CLIENT_MESSAGE).toContain("OnboardingStudio.init");
206
+ expect(MISSING_CLIENT_MESSAGE).toContain("client");
207
+ });
208
+ });
@@ -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,53 @@ 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";
93
+ // A step that IS a paywall: `payload.moment` names a moment, and the audience
94
+ // waterfall behind it picks which paywall renders.
95
+ export type { PaywallStepType } from "./steps/Paywall/types";
96
+ export { PaywallStepTypeSchema, PaywallStepPayloadSchema } from "./steps/Paywall/types";
50
97
  // Payload diagnostics — non-fatal detection of keys placed at an element's top
51
98
  // level that the schema silently drops (e.g. `animation` outside `props`).
52
99
  export {
@@ -102,6 +149,10 @@ export type {
102
149
  PresentErrorReason,
103
150
  } from "./paywalls/types";
104
151
  export { PaywallProvider, usePaywallHost } from "./paywalls/PaywallProvider";
152
+ // The custom-screen registry lives on PaywallProvider now (two renderers read
153
+ // it: PaywallHost's Modal and the inline Paywall onboarding step), so its types
154
+ // live in the headless package. onboarding-ui re-exports both names.
155
+ export type { CustomPaywallScreenProps, CustomPaywallScreens } from "./paywalls/customScreens";
105
156
  export type { PaywallContextValue } from "./paywalls/PaywallProvider";
106
157
  export { usePaywall } from "./paywalls/usePaywall";
107
158
  // Exported so a host can switch exhaustively on what the catalog is doing
@@ -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,7 +110,16 @@ 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;
108
124
  customAudienceParams?: Record<string, any>;
109
125
  /**
@@ -163,10 +179,24 @@ const OnboardingDataGate = ({
163
179
  fontsFallback,
164
180
  children,
165
181
  }: OnboardingDataGateProps) => {
166
- const { data, error } = useQuery<Onboarding<OnboardingStepType>>(
167
- getOnboardingQuery<OnboardingStepType>(client, locale, customAudienceParams, setOnboarding)
182
+ // Same merge the paywall provider does, for the same reason: one store feeds
183
+ // both waterfalls, so an onboarding audience and a paywall audience can no
184
+ // longer disagree about the same user. See `resolveEffectiveParams`.
185
+ const { properties, status: propertiesStatus } = useUserProperties();
186
+ const params = useMemo(
187
+ () => resolveEffectiveParams(customAudienceParams, properties),
188
+ [customAudienceParams, properties]
168
189
  );
169
190
 
191
+ const { data, error } = useQuery<Onboarding<OnboardingStepType>>({
192
+ ...getOnboardingQuery<OnboardingStepType>(client, locale, params, setOnboarding),
193
+ // Held until the store hydrates — otherwise the first fetch of a cold launch
194
+ // is audience-matched against an empty property map. This gate renders
195
+ // `fontsFallback`, the state this gate already shows while the payload
196
+ // loads, so nothing new appears on screen.
197
+ enabled: propertiesStatus === "ready",
198
+ });
199
+
170
200
  // Background asset preload: once the payload is available, warm every remote
171
201
  // image/video/Lottie/Rive asset so later screens render without a load flash.
172
202
  // Fire-and-forget and non-blocking — does NOT gate the FontLoaderGate render.
@@ -201,7 +231,7 @@ const OnboardingDataGate = ({
201
231
 
202
232
  export const OnboardingProvider = ({
203
233
  children,
204
- client,
234
+ client: clientProp,
205
235
  locale = "en",
206
236
  customAudienceParams = {},
207
237
  customActions = EMPTY_CUSTOM_ACTIONS,
@@ -211,6 +241,17 @@ export const OnboardingProvider = ({
211
241
  productProvider,
212
242
  productRefs,
213
243
  }: OnboardingProviderProps) => {
244
+ // An explicit prop wins; otherwise use whatever `OnboardingStudio.init()`
245
+ // built. THROWN rather than degraded, unlike `PaywallProvider`: this provider
246
+ // wraps an onboarding, so a host `ErrorBoundary` catches it and the rest of the
247
+ // app survives — and an onboarding with no client has nothing at all to render,
248
+ // where a paywall-less app is merely un-monetised.
249
+ //
250
+ // Read during render, so `init()` must run BEFORE the first render — at module
251
+ // scope, which is where the warning tells a host to put it.
252
+ const client = resolveProviderClient(clientProp, OnboardingStudio.getClient());
253
+ if (!client) throw new Error(MISSING_CLIENT_MESSAGE);
254
+
214
255
  const [activeStep, setActiveStep] = useState({
215
256
  number: 0,
216
257
  displayProgressHeader: false,
@@ -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
+ );