@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
@@ -21,6 +21,18 @@ import { ProductProvider, ProductStatus } from "../products/types";
21
21
  import { ProductRuntimeContext } from "../products/ProductRuntimeContext";
22
22
  import type { CustomActions } from "../infra/provider/OnboardingProvider";
23
23
  import type { CustomPaywallScreens } from "./customScreens";
24
+ import { useUserProperties } from "../userProperties/useUserProperties";
25
+ import { resolveEffectiveParams } from "../userProperties/effectiveParams";
26
+ import { runRegister, type RegisterFeature, type RegisterResult } from "./register";
27
+ import {
28
+ OnboardingStudio,
29
+ resolveProviderClient,
30
+ MISSING_CLIENT_MESSAGE,
31
+ } from "../OnboardingStudio";
32
+ import {
33
+ createCatalogSettleWaiter,
34
+ type CatalogSettleWaiter,
35
+ } from "./catalogSettleWaiter";
24
36
 
25
37
  // Module-scope, private to this file — mirrors `OnboardingProvider.tsx:17-23`.
26
38
  // `OnboardingProvider`'s QueryClient is not exported, so it cannot be reused
@@ -59,6 +71,20 @@ const EMPTY_CUSTOM_SCREENS: CustomPaywallScreens = Object.freeze({});
59
71
  */
60
72
  export type PaywallContextValue = {
61
73
  present: (moment: string) => Promise<PresentResult>;
74
+ /**
75
+ * Gate a feature on a moment: `register("unlock_stats", () => go())`.
76
+ *
77
+ * Runs the feature immediately when the moment has no paywall (it is not
78
+ * monetised, or not authored yet), otherwise presents the moment's paywall and
79
+ * runs the feature ONLY on a purchase. Gates on the moment alone — there is no
80
+ * entitlement check; exclude subscribers with an audience filter on a user
81
+ * property.
82
+ *
83
+ * Fails OPEN: when no catalog is reachable it runs the feature and warns, so an
84
+ * offline launch does not silently disable the app's features. The resolved
85
+ * `reason` reports which path was taken, so a host can measure that rate.
86
+ */
87
+ register: (moment: string, feature?: RegisterFeature) => Promise<RegisterResult>;
62
88
  isReady: boolean;
63
89
  catalog: PaywallCatalog | null;
64
90
  /**
@@ -126,6 +152,14 @@ const EMPTY_PAYWALL_CONTEXT: PaywallContextValue = {
126
152
  // No provider above: there is no catalog at all, which is the same answer
127
153
  // `resolvePresentDecision` gives for an unresolved one.
128
154
  present: async () => ({ status: "error", reason: "unknown-moment" }),
155
+ // No provider above: no verdict is reachable, which is exactly the fail-open
156
+ // case — consistent with how `register` treats an unavailable catalog. A host
157
+ // that forgot the provider gets a working app whose features are ungated,
158
+ // rather than an app whose gated features are all silently dead.
159
+ register: async (_moment, feature) => {
160
+ await feature?.();
161
+ return { ran: true, presented: false, reason: "catalog-unavailable" };
162
+ },
129
163
  isReady: false,
130
164
  catalog: null,
131
165
  // No provider above: nothing is loading and nothing will arrive.
@@ -149,6 +183,13 @@ const EMPTY_PAYWALL_CONTEXT: PaywallContextValue = {
149
183
  */
150
184
  const DEFAULT_PRESENT_ACK_TIMEOUT_MS = 5000;
151
185
 
186
+ /**
187
+ * How long `register()` waits for the catalog to settle before deciding without
188
+ * it. Generous enough that a cold network fetch usually lands, short enough that
189
+ * a tap does not feel stuck.
190
+ */
191
+ export const DEFAULT_REGISTER_TIMEOUT_MS = 3000;
192
+
152
193
  export const PaywallContext = createContext<PaywallContextValue>(EMPTY_PAYWALL_CONTEXT);
153
194
 
154
195
  /**
@@ -169,7 +210,15 @@ export const usePaywallHost = (): Pick<
169
210
 
170
211
  interface PaywallProviderProps {
171
212
  children: React.ReactNode;
172
- client: OnboardingStudioClient;
213
+ /**
214
+ * The studio client. Optional: omit it and the provider uses the client
215
+ * `OnboardingStudio.init({ projectId })` built. Passing one explicitly still
216
+ * wins, so an existing host is unaffected.
217
+ *
218
+ * With neither, this provider warns and renders `children` with paywalls inert
219
+ * — it does not throw, because it wraps the whole app.
220
+ */
221
+ client?: OnboardingStudioClient;
173
222
  locale?: string;
174
223
  customAudienceParams?: Record<string, any>;
175
224
  /**
@@ -223,6 +272,15 @@ interface PaywallProviderProps {
223
272
  * rest of the process. Only pass `null` if the host cannot acknowledge.
224
273
  */
225
274
  presentAckTimeoutMs?: number | null;
275
+ /**
276
+ * How long `register()` waits for the paywall catalog to settle before deciding
277
+ * without it. Defaults to 3000 ms.
278
+ *
279
+ * On timeout `register` fails OPEN — it runs the gated feature and warns. Lower
280
+ * it if a tap feels stuck on a slow network; raise it to give the catalog more
281
+ * chance to land before a feature is given away.
282
+ */
283
+ registerTimeoutMs?: number;
226
284
  }
227
285
 
228
286
  interface PaywallProviderInnerProps {
@@ -235,6 +293,7 @@ interface PaywallProviderInnerProps {
235
293
  customActions: CustomActions;
236
294
  customScreens: CustomPaywallScreens;
237
295
  presentAckTimeoutMs: number | null;
296
+ registerTimeoutMs: number;
238
297
  }
239
298
 
240
299
  const PaywallProviderInner = ({
@@ -247,6 +306,7 @@ const PaywallProviderInner = ({
247
306
  customActions,
248
307
  customScreens,
249
308
  presentAckTimeoutMs,
309
+ registerTimeoutMs,
250
310
  }: PaywallProviderInnerProps) => {
251
311
  // `data` straight off `useQuery` is the single source of truth (Finding 1,
252
312
  // 2026-08-17 final review) — react-query's own cache already gets both a
@@ -256,9 +316,28 @@ const PaywallProviderInner = ({
256
316
  // for why the query still needs `paywallQueryClient` for the ONE case
257
317
  // `data` alone can't cover: a background revalidation pushing a fresh
258
318
  // payload while this query call already resolved with the cached one.
259
- const { data, error, isFetching } = useQuery<PaywallCatalog>(
260
- getPaywallsQuery(client, locale, customAudienceParams, paywallQueryClient)
319
+ // The user-property store is the RUNTIME half of audience targeting; the
320
+ // `customAudienceParams` prop is the static half. Merged store-wins and
321
+ // serialized once, so the query key, the disk cache key's hash and the
322
+ // querystring all see the same bytes — see `resolveEffectiveParams`.
323
+ const { properties, status: propertiesStatus } = useUserProperties();
324
+ const params = useMemo(
325
+ () => resolveEffectiveParams(customAudienceParams, properties),
326
+ [customAudienceParams, properties]
261
327
  );
328
+
329
+ const { data, error, isFetching } = useQuery<PaywallCatalog>({
330
+ ...getPaywallsQuery(client, locale, params, paywallQueryClient),
331
+ // Held until the store has hydrated from disk. Without this the first fetch
332
+ // of a cold launch carries an EMPTY property map, matches the catch-all
333
+ // audience, and — because the catalog is cached with `staleTime: Infinity` —
334
+ // that wrong answer is what the whole session uses.
335
+ //
336
+ // A disabled query reports `data: undefined`, `error: null`,
337
+ // `isFetching: false`, which `computeCatalogStatus` reads as "loading" — the
338
+ // honest answer while the store hydrates, and the one `register()` waits on.
339
+ enabled: propertiesStatus === "ready",
340
+ });
262
341
  const catalog = data ?? null;
263
342
  // `isFetching` (not `isLoading`) on purpose: it is also true for a BACKGROUND
264
343
  // revalidation behind an already-served cached catalog, which is precisely the
@@ -388,6 +467,19 @@ const PaywallProviderInner = ({
388
467
  // `purchase`/`restore` callbacks.
389
468
  const catalogRef = useRef(catalog);
390
469
  catalogRef.current = catalog;
470
+ // `catalogStatus` as a ref for the same reason: `register` must read the
471
+ // CURRENT status without being re-created on every status change.
472
+ const catalogStatusRef = useRef(catalogStatus);
473
+ catalogStatusRef.current = catalogStatus;
474
+ // One waiter per provider instance, reading status through the ref above. See
475
+ // `catalogSettleWaiter.ts` for the two invariants that put it in its own
476
+ // module instead of inline here.
477
+ const settleWaiterRef = useRef<CatalogSettleWaiter | null>(null);
478
+ if (settleWaiterRef.current === null) {
479
+ settleWaiterRef.current = createCatalogSettleWaiter(
480
+ () => catalogStatusRef.current === "loading"
481
+ );
482
+ }
391
483
  // `activeMomentRef` is made AUTHORITATIVE below — assigned inside
392
484
  // `present()`'s start branch and inside `complete()`, not just here. Finding
393
485
  // 4, 2026-08-17 final review: this line alone only resyncs the ref from
@@ -433,6 +525,42 @@ const PaywallProviderInner = ({
433
525
  });
434
526
  }, []);
435
527
 
528
+ // Wakes anything parked in `register` as soon as the catalog stops loading.
529
+ useEffect(() => {
530
+ if (catalogStatus === "loading") return;
531
+ settleWaiterRef.current?.settle();
532
+ }, [catalogStatus]);
533
+
534
+ /**
535
+ * Superwall's `registerPlacement`, in this SDK's vocabulary: gate a feature on
536
+ * a moment.
537
+ *
538
+ * Gates on the MOMENT alone — there is deliberately no entitlement check.
539
+ * Exclude subscribers by authoring an audience filter against a user property
540
+ * the host sets (`plan: "pro"`), which is machinery that already exists.
541
+ *
542
+ * All of the decision logic — both fail-open paths, the wait-once rule, the
543
+ * Stripe warning — is `runRegister` in `register.ts`, where it is unit-tested.
544
+ * This callback only supplies the environment.
545
+ */
546
+ const register = useCallback(
547
+ (moment: string, feature?: RegisterFeature): Promise<RegisterResult> =>
548
+ runRegister(
549
+ {
550
+ getCatalog: () => catalogRef.current,
551
+ getCatalogStatus: () => catalogStatusRef.current,
552
+ waitForCatalogSettled: (ms) => settleWaiterRef.current!.wait(ms),
553
+ // The real `present`, so the wedge recovery, the purchase-generation
554
+ // race guard and outcome reconciliation all apply unchanged.
555
+ present,
556
+ timeoutMs: registerTimeoutMs,
557
+ },
558
+ moment,
559
+ feature
560
+ ),
561
+ [present, registerTimeoutMs]
562
+ );
563
+
436
564
  // Called by PaywallHost (Task 7) from the presented paywall's
437
565
  // `ScreenHost.complete`. Resolves whatever `present()` call is pending and
438
566
  // clears the active moment, hiding the Modal and allowing a new
@@ -515,6 +643,7 @@ const PaywallProviderInner = ({
515
643
  const contextValue = useMemo<PaywallContextValue>(
516
644
  () => ({
517
645
  present,
646
+ register,
518
647
  isReady,
519
648
  catalog,
520
649
  catalogStatus,
@@ -530,6 +659,7 @@ const PaywallProviderInner = ({
530
659
  }),
531
660
  [
532
661
  present,
662
+ register,
533
663
  isReady,
534
664
  catalog,
535
665
  catalogStatus,
@@ -555,15 +685,25 @@ const PaywallProviderInner = ({
555
685
  * only flows to descendants; two true siblings could not share one runtime).
556
686
  *
557
687
  * ```tsx
558
- * <PaywallProvider client={client} productProvider={revenueCatProductProvider(Purchases)}>
688
+ * OnboardingStudio.init({ projectId: "…" }); // at module scope
689
+ *
690
+ * <PaywallProvider productProvider={revenueCatProductProvider(Purchases)}>
559
691
  * <App />
560
- * <PaywallHost /> // Task 7: renders the active paywall in a fullScreen RN Modal
692
+ * <PaywallHost /> // renders the active paywall in a fullScreen RN Modal
561
693
  * </PaywallProvider>
562
694
  * ```
695
+ *
696
+ * With no client at all — neither a prop nor an `OnboardingStudio.init()` — this
697
+ * WARNS and renders `children` untouched, so paywalls are inert and the app
698
+ * still runs. It deliberately does not throw the way `OnboardingProvider` does:
699
+ * this provider wraps the whole app (see the query-error effect inside), so
700
+ * throwing would take down every screen over a missing paywall client. Consumers
701
+ * then read the default context, where `isProviderMounted` is `false` and both
702
+ * `present` and `register` resolve their fail-open answers.
563
703
  */
564
704
  export const PaywallProvider = ({
565
705
  children,
566
- client,
706
+ client: clientProp,
567
707
  locale = "en",
568
708
  customAudienceParams = {},
569
709
  productProvider,
@@ -571,7 +711,22 @@ export const PaywallProvider = ({
571
711
  customActions = EMPTY_CUSTOM_ACTIONS,
572
712
  customScreens = EMPTY_CUSTOM_SCREENS,
573
713
  presentAckTimeoutMs = DEFAULT_PRESENT_ACK_TIMEOUT_MS,
714
+ registerTimeoutMs = DEFAULT_REGISTER_TIMEOUT_MS,
574
715
  }: PaywallProviderProps) => {
716
+ // Prop wins, else whatever `OnboardingStudio.init()` built. Read during render,
717
+ // so `init()` must run before the first render — at module scope.
718
+ const client = resolveProviderClient(clientProp, OnboardingStudio.getClient());
719
+
720
+ // Effect, not an inline call, so a re-render does not re-log. Declared above
721
+ // the early return: hooks must run unconditionally.
722
+ useEffect(() => {
723
+ if (client) return;
724
+ console.warn(`${MISSING_CLIENT_MESSAGE} Paywalls are inert until then.`);
725
+ }, [client]);
726
+
727
+ // Degrade rather than throw — see the doc above.
728
+ if (!client) return <>{children}</>;
729
+
575
730
  return (
576
731
  <QueryClientProvider client={paywallQueryClient}>
577
732
  <PaywallProviderInner
@@ -583,6 +738,7 @@ export const PaywallProvider = ({
583
738
  customActions={customActions}
584
739
  customScreens={customScreens}
585
740
  presentAckTimeoutMs={presentAckTimeoutMs}
741
+ registerTimeoutMs={registerTimeoutMs}
586
742
  >
587
743
  {children}
588
744
  </PaywallProviderInner>
@@ -0,0 +1,134 @@
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import { createCatalogSettleWaiter } from "../catalogSettleWaiter";
3
+
4
+ // A controllable stand-in for setTimeout: records pending callbacks so a test can
5
+ // fire them deliberately instead of waiting on real time.
6
+ const makeScheduler = () => {
7
+ const pending: Array<{ fn: () => void; ms: number; cancelled: boolean }> = [];
8
+ const schedule = (fn: () => void, ms: number) => {
9
+ const entry = { fn, ms, cancelled: false };
10
+ pending.push(entry);
11
+ return () => {
12
+ entry.cancelled = true;
13
+ };
14
+ };
15
+ const fire = () => {
16
+ for (const entry of [...pending]) if (!entry.cancelled) entry.fn();
17
+ };
18
+ return { schedule, fire, pending };
19
+ };
20
+
21
+ describe("createCatalogSettleWaiter", () => {
22
+ it("resolves immediately when the catalog is not loading", async () => {
23
+ const { schedule, pending } = makeScheduler();
24
+ const waiter = createCatalogSettleWaiter(() => false, schedule);
25
+ await waiter.wait(1000);
26
+ // Nothing was scheduled: there was nothing to wait for.
27
+ expect(pending).toHaveLength(0);
28
+ });
29
+
30
+ it("parks while loading and resolves on settle()", async () => {
31
+ const { schedule } = makeScheduler();
32
+ let loading = true;
33
+ const waiter = createCatalogSettleWaiter(() => loading, schedule);
34
+
35
+ let resolved = false;
36
+ const promise = waiter.wait(1000).then(() => {
37
+ resolved = true;
38
+ });
39
+
40
+ await Promise.resolve();
41
+ expect(resolved).toBe(false);
42
+
43
+ loading = false;
44
+ waiter.settle();
45
+ await promise;
46
+ expect(resolved).toBe(true);
47
+ });
48
+
49
+ it("resolves on timeout even if settle() never comes", async () => {
50
+ const { schedule, fire } = makeScheduler();
51
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
52
+ const promise = waiter.wait(1000);
53
+ fire();
54
+ await expect(promise).resolves.toBeUndefined();
55
+ });
56
+
57
+ it("passes the requested timeout to the scheduler", async () => {
58
+ const { schedule, pending, fire } = makeScheduler();
59
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
60
+ const promise = waiter.wait(4321);
61
+ expect(pending[0].ms).toBe(4321);
62
+ fire();
63
+ await promise;
64
+ });
65
+
66
+ it("resolves each waiter exactly once when a timeout races a settle", async () => {
67
+ const { schedule, fire } = makeScheduler();
68
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
69
+ const onResolve = vi.fn();
70
+ const promise = waiter.wait(1000).then(onResolve);
71
+
72
+ waiter.settle();
73
+ fire(); // the timeout fires after the settle already resolved it
74
+ await promise;
75
+
76
+ expect(onResolve).toHaveBeenCalledTimes(1);
77
+ });
78
+
79
+ it("cancels a waiter's timer once it has settled, leaving nothing pending", async () => {
80
+ const { schedule, pending } = makeScheduler();
81
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
82
+ const promise = waiter.wait(1000);
83
+ waiter.settle();
84
+ await promise;
85
+ expect(pending.every((entry) => entry.cancelled)).toBe(true);
86
+ });
87
+
88
+ it("settles every parked waiter", async () => {
89
+ const { schedule } = makeScheduler();
90
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
91
+ const results: number[] = [];
92
+ const all = Promise.all([
93
+ waiter.wait(1000).then(() => results.push(1)),
94
+ waiter.wait(1000).then(() => results.push(2)),
95
+ waiter.wait(1000).then(() => results.push(3)),
96
+ ]);
97
+ waiter.settle();
98
+ await all;
99
+ expect(results.sort()).toEqual([1, 2, 3]);
100
+ });
101
+
102
+ it("does not skip a waiter that re-parks from another waiter's continuation", async () => {
103
+ const { schedule } = makeScheduler();
104
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
105
+ const second = vi.fn();
106
+
107
+ // The first waiter's continuation parks a NEW waiter — which must not be
108
+ // dropped by the drain that woke the first one.
109
+ const first = waiter.wait(1000).then(() => {
110
+ void waiter.wait(1000).then(second);
111
+ });
112
+
113
+ waiter.settle();
114
+ await first;
115
+ await Promise.resolve();
116
+ expect(second).not.toHaveBeenCalled(); // still parked, correctly
117
+
118
+ waiter.settle();
119
+ await Promise.resolve();
120
+ await Promise.resolve();
121
+ expect(second).toHaveBeenCalledTimes(1);
122
+ });
123
+
124
+ it("settle() with nothing parked is a no-op", () => {
125
+ const { schedule } = makeScheduler();
126
+ const waiter = createCatalogSettleWaiter(() => true, schedule);
127
+ expect(() => waiter.settle()).not.toThrow();
128
+ });
129
+
130
+ it("defaults to real timers when no scheduler is injected", async () => {
131
+ const waiter = createCatalogSettleWaiter(() => true);
132
+ await expect(waiter.wait(1)).resolves.toBeUndefined();
133
+ });
134
+ });
@@ -5,13 +5,17 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
5
5
  vi.mock("react-native", () => ({ Platform: { OS: "ios" } }));
6
6
 
7
7
  // AsyncStorage is mocked — the query reads/writes the paywall cache through it.
8
- const { getItem, setItem, removeItem } = vi.hoisted(() => ({
8
+ const { getItem, setItem, removeItem, getAllKeys, multiRemove } = vi.hoisted(() => ({
9
9
  getItem: vi.fn<(key: string) => Promise<string | null>>(),
10
10
  setItem: vi.fn<(key: string, value: string) => Promise<void>>(),
11
11
  removeItem: vi.fn<(key: string) => Promise<void>>(),
12
+ // `clearCache` scans by prefix now — the keys are scoped by a hash of the
13
+ // resolved audience params, so it can no longer name them one by one.
14
+ getAllKeys: vi.fn<() => Promise<string[]>>(),
15
+ multiRemove: vi.fn<(keys: string[]) => Promise<void>>(),
12
16
  }));
13
17
  vi.mock("@react-native-async-storage/async-storage", () => ({
14
- default: { getItem, setItem, removeItem },
18
+ default: { getItem, setItem, removeItem, getAllKeys, multiRemove },
15
19
  }));
16
20
 
17
21
  import { OnboardingStudioClient } from "../../OnboardingStudioClient";
@@ -315,23 +319,37 @@ describe("getPaywallsQuery", () => {
315
319
  });
316
320
 
317
321
  describe("OnboardingStudioClient.clearCache", () => {
318
- beforeEach(() => removeItem.mockReset());
322
+ beforeEach(() => {
323
+ multiRemove.mockReset();
324
+ multiRemove.mockResolvedValue(undefined);
325
+ getAllKeys.mockReset();
326
+ });
319
327
 
320
- it("removes both the default onboarding key and the default paywalls key", async () => {
328
+ it("clears both domains' default keys", async () => {
329
+ getAllKeys.mockResolvedValue([DEFAULT_ONBOARDING_CACHE_KEY, CACHE_KEY]);
321
330
  const client = new OnboardingStudioClient("p1", {});
322
331
  await client.clearCache();
323
332
 
324
- expect(removeItem).toHaveBeenCalledWith(DEFAULT_ONBOARDING_CACHE_KEY);
325
- expect(removeItem).toHaveBeenCalledWith(CACHE_KEY);
326
- expect(removeItem).toHaveBeenCalledTimes(2);
333
+ expect(multiRemove).toHaveBeenCalledWith([DEFAULT_ONBOARDING_CACHE_KEY, CACHE_KEY]);
327
334
  });
328
335
 
329
- it("removes both namespaced keys when a custom key is configured", async () => {
336
+ it("clears both namespaced keys when a custom key is configured", async () => {
337
+ getAllKeys.mockResolvedValue([`rocapine-onboarding-sdk-${CUSTOM_KEY}`, CUSTOM_CACHE_KEY]);
330
338
  const client = new OnboardingStudioClient("p1", { cacheKey: CUSTOM_KEY });
331
339
  await client.clearCache();
332
340
 
333
- expect(removeItem).toHaveBeenCalledWith(`rocapine-onboarding-sdk-${CUSTOM_KEY}`);
334
- expect(removeItem).toHaveBeenCalledWith(CUSTOM_CACHE_KEY);
335
- expect(removeItem).toHaveBeenCalledTimes(2);
341
+ expect(multiRemove).toHaveBeenCalledWith([
342
+ `rocapine-onboarding-sdk-${CUSTOM_KEY}`,
343
+ CUSTOM_CACHE_KEY,
344
+ ]);
345
+ });
346
+
347
+ it("clears a params-scoped paywall key it could not have named in advance", async () => {
348
+ const scoped = `${CACHE_KEY}-1b9a2624`;
349
+ getAllKeys.mockResolvedValue([scoped]);
350
+ const client = new OnboardingStudioClient("p1", {});
351
+ await client.clearCache();
352
+
353
+ expect(multiRemove).toHaveBeenCalledWith([scoped]);
336
354
  });
337
355
  });