@rocapine/react-native-onboarding 1.75.0 → 1.76.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 (87) hide show
  1. package/dist/index.d.ts +5 -3
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +16 -2
  4. package/dist/index.js.map +1 -1
  5. package/dist/onboarding-example.d.ts +140 -0
  6. package/dist/onboarding-example.d.ts.map +1 -1
  7. package/dist/onboarding-example.js +41 -1
  8. package/dist/onboarding-example.js.map +1 -1
  9. package/dist/paywalls/PaywallProvider.d.ts +71 -5
  10. package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
  11. package/dist/paywalls/PaywallProvider.js +237 -57
  12. package/dist/paywalls/PaywallProvider.js.map +1 -1
  13. package/dist/paywalls/customScreens.d.ts +31 -0
  14. package/dist/paywalls/customScreens.d.ts.map +1 -1
  15. package/dist/paywalls/observer.d.ts +129 -0
  16. package/dist/paywalls/observer.d.ts.map +1 -0
  17. package/dist/paywalls/observer.js +211 -0
  18. package/dist/paywalls/observer.js.map +1 -0
  19. package/dist/paywalls/present.d.ts +19 -15
  20. package/dist/paywalls/present.d.ts.map +1 -1
  21. package/dist/paywalls/present.js +21 -17
  22. package/dist/paywalls/present.js.map +1 -1
  23. package/dist/paywalls/types.d.ts +3 -1
  24. package/dist/paywalls/types.d.ts.map +1 -1
  25. package/dist/products/adapters/expoIap.d.ts +38 -1
  26. package/dist/products/adapters/expoIap.d.ts.map +1 -1
  27. package/dist/products/adapters/expoIap.js +509 -75
  28. package/dist/products/adapters/expoIap.js.map +1 -1
  29. package/dist/products/index.d.ts +1 -0
  30. package/dist/products/index.d.ts.map +1 -1
  31. package/dist/products/index.js.map +1 -1
  32. package/dist/products/types.d.ts +13 -0
  33. package/dist/products/types.d.ts.map +1 -1
  34. package/dist/screens/completingActions.d.ts +55 -3
  35. package/dist/screens/completingActions.d.ts.map +1 -1
  36. package/dist/screens/completingActions.js +209 -15
  37. package/dist/screens/completingActions.js.map +1 -1
  38. package/dist/screens/elementTypeRegistry.d.ts +14 -0
  39. package/dist/screens/elementTypeRegistry.d.ts.map +1 -1
  40. package/dist/screens/elementTypeRegistry.js +38 -1
  41. package/dist/screens/elementTypeRegistry.js.map +1 -1
  42. package/dist/screens/elements/ButtonElement.d.ts +3 -2
  43. package/dist/screens/elements/ButtonElement.d.ts.map +1 -1
  44. package/dist/screens/elements/ButtonElement.js +5 -1
  45. package/dist/screens/elements/ButtonElement.js.map +1 -1
  46. package/dist/screens/types.d.ts +2 -2
  47. package/dist/screens/types.d.ts.map +1 -1
  48. package/dist/screens/types.js +5 -1
  49. package/dist/screens/types.js.map +1 -1
  50. package/dist/screens/unknownKeys.d.ts +25 -4
  51. package/dist/screens/unknownKeys.d.ts.map +1 -1
  52. package/dist/screens/unknownKeys.js +81 -2
  53. package/dist/screens/unknownKeys.js.map +1 -1
  54. package/dist/steps/common.types.d.ts +178 -6
  55. package/dist/steps/common.types.d.ts.map +1 -1
  56. package/dist/steps/common.types.js +64 -3
  57. package/dist/steps/common.types.js.map +1 -1
  58. package/package.json +1 -1
  59. package/src/__tests__/authoringDocEscapes.test.ts +59 -0
  60. package/src/__tests__/completingActions.test.ts +371 -1
  61. package/src/__tests__/customActionHooks.test.ts +224 -0
  62. package/src/__tests__/onboardingExampleElements.test.ts +47 -0
  63. package/src/__tests__/requestPermissionAction.test.ts +138 -0
  64. package/src/__tests__/retryIdempotencyDocs.test.ts +57 -0
  65. package/src/__tests__/unknownKeys.test.ts +110 -0
  66. package/src/index.ts +33 -1
  67. package/src/onboarding-example.ts +41 -1
  68. package/src/paywalls/PaywallProvider.tsx +370 -66
  69. package/src/paywalls/__tests__/PaywallProvider.observer.test.tsx +866 -0
  70. package/src/paywalls/__tests__/observer.test.ts +401 -0
  71. package/src/paywalls/__tests__/present.test.ts +0 -18
  72. package/src/paywalls/customScreens.ts +34 -1
  73. package/src/paywalls/observer.ts +308 -0
  74. package/src/paywalls/present.ts +24 -18
  75. package/src/paywalls/types.ts +3 -1
  76. package/src/products/adapters/__tests__/expoIap.contract.test.ts +648 -0
  77. package/src/products/adapters/__tests__/expoIap.test.ts +25 -11
  78. package/src/products/adapters/__tests__/expoIap5Fake.ts +288 -0
  79. package/src/products/adapters/expoIap.ts +609 -78
  80. package/src/products/index.ts +1 -0
  81. package/src/products/types.ts +13 -0
  82. package/src/screens/completingActions.ts +223 -15
  83. package/src/screens/elementTypeRegistry.ts +34 -0
  84. package/src/screens/elements/ButtonElement.ts +9 -1
  85. package/src/screens/types.ts +2 -2
  86. package/src/screens/unknownKeys.ts +113 -7
  87. package/src/steps/common.types.ts +213 -6
@@ -1,4 +1,5 @@
1
1
  import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
2
+ import { Platform } from "react-native";
2
3
  import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
3
4
  import { OnboardingStudioClient } from "../OnboardingStudioClient";
4
5
  import { getPaywallsQuery } from "./getPaywalls.query";
@@ -12,12 +13,12 @@ import {
12
13
  resolvePresentDecision,
13
14
  selectActiveProductRuntime,
14
15
  shouldBreakPresentationWedge,
15
- resolvePresentedOutcome,
16
- shouldRecordPurchaseOutcome,
16
+ resolveEndedOutcome,
17
+ LATE_PURCHASE_TIMEOUT_MS,
17
18
  type PurchaseOutcomeDuringPresentation,
18
19
  } from "./present";
19
20
  import { useProducts } from "../products/useProducts";
20
- import { ProductProvider, ProductStatus } from "../products/types";
21
+ import { ProductProvider, ProductStatus, type PurchaseResult } from "../products/types";
21
22
  import { ProductRuntimeContext } from "../products/ProductRuntimeContext";
22
23
  import type { CustomActions } from "../infra/provider/OnboardingProvider";
23
24
  import type { CustomPaywallScreens } from "./customScreens";
@@ -33,6 +34,14 @@ import {
33
34
  createCatalogSettleWaiter,
34
35
  type CatalogSettleWaiter,
35
36
  } from "./catalogSettleWaiter";
37
+ import {
38
+ NOOP_PAYWALL_PRESENTATION,
39
+ openPaywallPresentation,
40
+ type PaywallObserver,
41
+ type PaywallPresentation,
42
+ type PaywallPresentationSource,
43
+ type PaywallTransactionInfo,
44
+ } from "./observer";
36
45
 
37
46
  // Module-scope, private to this file — mirrors `OnboardingProvider.tsx:17-23`.
38
47
  // `OnboardingProvider`'s QueryClient is not exported, so it cannot be reused
@@ -122,15 +131,49 @@ export type PaywallContextValue = {
122
131
  * Resolve the pending `present()` call and clear the active moment.
123
132
  * Call this from the presented paywall's `ScreenHost.complete` (Task 7's
124
133
  * `PaywallHost`) — never from an ordinary consumer.
134
+ *
135
+ * BOUND to the presentation on screen when it was rendered: its identity
136
+ * changes once per presentation, and a stale copy (a previous paywall's
137
+ * action chain finishing late) is a no-op rather than closing whatever is on
138
+ * screen now. Call the `complete` from the CURRENT render; one stashed
139
+ * across presentations does nothing.
140
+ *
141
+ * `transaction` is what a custom paywall screen passed to its own
142
+ * `complete()` (#287): forwarded to the observer's `end()`, sanitized, and
143
+ * only when `result.status` is `"purchased"`. It never changes what
144
+ * `present()` resolves. Omit it and nothing changes.
125
145
  */
126
- complete: (result: PresentResult) => void;
146
+ complete: (result: PresentResult, transaction?: PaywallTransactionInfo) => void;
127
147
  /**
128
- * Called by the paywall HOST once the paywall is actually on screen (the UI
129
- * host wires this to its Modal's `onShow`) — never by an ordinary consumer.
148
+ * Called by the paywall HOST once the CURRENT presentation is actually on
149
+ * screen — never by an ordinary consumer. The provider never acknowledges a
150
+ * presentation on its own: only the host knows what it renders.
151
+ *
152
+ * The contract for a host of its own (the UI package's `PaywallHost` meets
153
+ * it already):
154
+ * - Call it from the Modal's `onShow`, which fires when the Modal appears
155
+ * and never when the platform refuses to present.
156
+ * - Call it again when a new presentation takes a Modal you kept mounted
157
+ * and `visible` (the previous one ended and the next started in the same
158
+ * commit, e.g. an `await present("a")` continuation): `onShow` does not
159
+ * fire twice, and without the call that paywall is abandoned after
160
+ * `presentAckTimeoutMs` as `host-never-presented`. Only do so if an
161
+ * `onShow` arrived while the Modal was visible, during its current
162
+ * visible stretch.
163
+ * - Ignore an `onShow` that arrives while your Modal is hidden. iOS emits it
164
+ * from the present completion with no visibility check, so a paywall that
165
+ * ended before its slide-in finished delivers it late. Acting on it (or
166
+ * counting it as confirmation) vouches for a presentation nobody saw.
167
+ * - Never call it for a presentation you will not render (a custom screen
168
+ * you do not have, elements that fail to parse): it would report a paywall
169
+ * nobody saw as shown, and disable the recovery below.
170
+ * - A Modal re-keyed per presentation needs none of the above: each one
171
+ * mounts afresh and fires its own `onShow`.
130
172
  *
131
173
  * Without it a presentation the platform silently refused is
132
174
  * indistinguishable from one the user is reading, and the refused case wedges
133
175
  * the surface permanently. See `shouldBreakPresentationWedge` in `present.ts`.
176
+ * Calling it twice for one presentation is harmless.
134
177
  */
135
178
  acknowledgePresentation: () => void;
136
179
  /** Forwarded into the presented paywall's `ScreenHost.customActions`. */
@@ -146,6 +189,16 @@ export type PaywallContextValue = {
146
189
  * already mounts. `PaywallHost`'s own prop still wins for that host.
147
190
  */
148
191
  customScreens: CustomPaywallScreens;
192
+ /**
193
+ * Opens one observed presentation for a surface OTHER than `present()` —
194
+ * today the inline `Paywall` onboarding step, reported as
195
+ * `surface: "paywall_step"`. Calls the provider's `observer.start` now and
196
+ * returns a handle whose `shown`/`end` never throw and reach the observer at
197
+ * most once / exactly once. A no-op handle when no observer was passed.
198
+ *
199
+ * `present()` reports itself; a paywall HOST never calls this for it.
200
+ */
201
+ observePresentation: (paywall: PaywallPresentationSource) => PaywallPresentation;
149
202
  };
150
203
 
151
204
  const EMPTY_PAYWALL_CONTEXT: PaywallContextValue = {
@@ -173,6 +226,7 @@ const EMPTY_PAYWALL_CONTEXT: PaywallContextValue = {
173
226
  acknowledgePresentation: () => {},
174
227
  customActions: EMPTY_CUSTOM_ACTIONS,
175
228
  customScreens: EMPTY_CUSTOM_SCREENS,
229
+ observePresentation: () => NOOP_PAYWALL_PRESENTATION,
176
230
  };
177
231
 
178
232
  /**
@@ -201,11 +255,29 @@ export const PaywallContext = createContext<PaywallContextValue>(EMPTY_PAYWALL_C
201
255
  */
202
256
  export const usePaywallHost = (): Pick<
203
257
  PaywallContextValue,
204
- "activePaywall" | "complete" | "acknowledgePresentation" | "customActions" | "customScreens"
258
+ | "activePaywall"
259
+ | "complete"
260
+ | "acknowledgePresentation"
261
+ | "customActions"
262
+ | "customScreens"
263
+ | "observePresentation"
205
264
  > => {
206
- const { activePaywall, complete, acknowledgePresentation, customActions, customScreens } =
207
- useContext(PaywallContext);
208
- return { activePaywall, complete, acknowledgePresentation, customActions, customScreens };
265
+ const {
266
+ activePaywall,
267
+ complete,
268
+ acknowledgePresentation,
269
+ customActions,
270
+ customScreens,
271
+ observePresentation,
272
+ } = useContext(PaywallContext);
273
+ return {
274
+ activePaywall,
275
+ complete,
276
+ acknowledgePresentation,
277
+ customActions,
278
+ customScreens,
279
+ observePresentation,
280
+ };
209
281
  };
210
282
 
211
283
  interface PaywallProviderProps {
@@ -281,6 +353,27 @@ interface PaywallProviderProps {
281
353
  * chance to land before a feature is given away.
282
354
  */
283
355
  registerTimeoutMs?: number;
356
+ /**
357
+ * Told about every paywall presentation, so the HOST can send it to its own
358
+ * analytics — this SDK sends nothing anywhere itself. Optional: omit it and
359
+ * nothing changes.
360
+ *
361
+ * `start(info)` runs once a `present()` call is accepted (never for an
362
+ * `unknown-moment` or `already-presenting` refusal) and may return a handle;
363
+ * `handle.shown()` runs when the host confirms the paywall is on screen, and
364
+ * `handle.end(outcome)` exactly once with the final `present()` result —
365
+ * including every post-acceptance error, as `status: "error"` with its
366
+ * `reason`. The inline `Paywall` onboarding step reports through the same
367
+ * observer with `surface: "paywall_step"`.
368
+ *
369
+ * Every call is guarded: an observer that throws, rejects, or returns
370
+ * something that is not a handle is logged and ignored, and never changes
371
+ * what `present()` resolves. The types match rocalytics-sdk's
372
+ * `PaywallObserver`, so its paywall tracker can be passed straight in.
373
+ *
374
+ * Read through a ref, so an inline object is fine.
375
+ */
376
+ observer?: PaywallObserver;
284
377
  }
285
378
 
286
379
  interface PaywallProviderInnerProps {
@@ -294,8 +387,70 @@ interface PaywallProviderInnerProps {
294
387
  customScreens: CustomPaywallScreens;
295
388
  presentAckTimeoutMs: number | null;
296
389
  registerTimeoutMs: number;
390
+ observer?: PaywallObserver;
297
391
  }
298
392
 
393
+ /**
394
+ * One accepted `present()` presentation, from its start to its single end:
395
+ * the observer handle, the `present()` resolver, and what the store did during
396
+ * it (a settled `purchased` sticks, with its key and the paywall bought on;
397
+ * before one, the last `cancelled` is kept). `pending` counts purchases begun on it and not
398
+ * yet settled; `timer` bounds the wait when its paywall disappeared with one in
399
+ * flight.
400
+ */
401
+ type PresentationRecord = {
402
+ presentation: PaywallPresentation;
403
+ resolve: (result: PresentResult) => void;
404
+ purchaseOutcome: PurchaseOutcomeDuringPresentation;
405
+ purchasedKey: string | null;
406
+ purchasedFrom: PaywallPresentationSource | null;
407
+ pending: number;
408
+ ended: boolean;
409
+ timer: ReturnType<typeof setTimeout> | null;
410
+ };
411
+
412
+ /**
413
+ * Whether an off-surface record should wait for its purchases rather than end
414
+ * now: only while one is in flight AND its end is still open. Once a purchase
415
+ * settled `purchased` the end is fixed (`resolveEndedOutcome`), so nothing a
416
+ * pending one settles to could change it.
417
+ */
418
+ const shouldWaitForPurchases = (record: PresentationRecord) =>
419
+ record.pending > 0 && record.purchaseOutcome !== "purchased";
420
+
421
+ /**
422
+ * Keeps an off-surface record open for the purchases still in flight on it:
423
+ * the purchase wrapper ends it when the last one settles, or this bound does,
424
+ * `dismissed`. Never cleared by an unmount, so a purchase that never settles
425
+ * cannot leak it.
426
+ */
427
+ const waitForPurchases = (record: PresentationRecord) => {
428
+ record.timer ??= setTimeout(() => endPresentation(record, { status: "dismissed" }), LATE_PURCHASE_TIMEOUT_MS);
429
+ };
430
+
431
+ /**
432
+ * The single end of a `present()` presentation: reports to the observer and
433
+ * resolves `present()` with the same reconciled outcome (`resolveEndedOutcome`:
434
+ * a settled purchase sticks, otherwise `resolvePresentedOutcome` upgrades a bare
435
+ * `dismissed` to what the store did — see its doc for why `dismiss`'s own
436
+ * `{status:"dismissed"}` isn't treated as an unoverridable explicit answer).
437
+ * Reported before resolving. Idempotent.
438
+ */
439
+ const endPresentation = (
440
+ record: PresentationRecord | null,
441
+ result: PresentResult,
442
+ reportedTransaction?: unknown
443
+ ) => {
444
+ if (!record || record.ended) return;
445
+ record.ended = true;
446
+ if (record.timer) clearTimeout(record.timer);
447
+ record.timer = null;
448
+ const outcome = resolveEndedOutcome(result, record.purchaseOutcome);
449
+ // `outcome`, never the transaction, is what `present()` resolves with.
450
+ record.presentation.end(outcome, record.purchasedKey, record.purchasedFrom, reportedTransaction);
451
+ record.resolve(outcome);
452
+ };
453
+
299
454
  const PaywallProviderInner = ({
300
455
  children,
301
456
  client,
@@ -307,6 +462,7 @@ const PaywallProviderInner = ({
307
462
  customScreens,
308
463
  presentAckTimeoutMs,
309
464
  registerTimeoutMs,
465
+ observer,
310
466
  }: PaywallProviderInnerProps) => {
311
467
  // `data` straight off `useQuery` is the single source of truth (Finding 1,
312
468
  // 2026-08-17 final review) — react-query's own cache already gets both a
@@ -414,46 +570,94 @@ const PaywallProviderInner = ({
414
570
  }
415
571
  }, [activePaywall, stripeProductProvider]);
416
572
 
417
- // Tracks what a purchase attempt resolved to during the CURRENT
418
- // presentation — read by `complete()` to upgrade a generic "dismissed"
419
- // outcome (see `resolvePresentedOutcome`), reset when a new presentation
420
- // starts (`present()`'s "start" branch) so one presentation's purchase
421
- // can never leak into the next.
422
- const lastPurchaseOutcomeRef = useRef<PurchaseOutcomeDuringPresentation>(null);
423
-
424
- // Monotonic, incremented every time a presentation actually starts (never
425
- // on the "immediate" no-op branch). Resetting `lastPurchaseOutcomeRef` at
426
- // that same moment is NOT enough to stop a stale write: paywall A's
427
- // `purchase()` can still be in flight when the user dismisses A and
428
- // paywall B is presented (which resets the ref); if A's promise settles
429
- // AFTER that reset, an unconditional write would land "purchased" in what
430
- // is now B's tracker. `purchase()` below captures the generation it
431
- // started in and only writes if that generation is still current — see
432
- // `shouldRecordPurchaseOutcome`. DO NOT remove the guard because the write
433
- // "looks" unconditional; that is exactly the race it closes.
434
- const presentationGenerationRef = useRef(0);
435
-
436
- // Wraps `productRuntime.purchase` to record the outcome above (race-guarded
437
- // — see `presentationGenerationRef`); every other field (and — critically —
438
- // the object's change cadence, since `products.purchasing` flips must
439
- // still propagate) is untouched. `productRuntime.purchase` is itself
573
+ // The presentation `present()` has on screen: its observer handle, its
574
+ // resolver and what the store did during it. One record per accepted
575
+ // `present()`, never reused, so its identity is the purchase race guard below.
576
+ const presentationRecordRef = useRef<PresentationRecord | null>(null);
577
+ // The same record as STATE, so the context's `complete` can be bound to the
578
+ // presentation a render showed (see `completeOnSurface`). State, not the
579
+ // ref: a same-moment re-present in one batch leaves `activeMoment` equal, and
580
+ // only a new object identity guarantees the context re-renders with B's
581
+ // `complete` rather than keeping A's.
582
+ const [surfaceRecord, setSurfaceRecord] = useState<PresentationRecord | null>(null);
583
+ const activePaywallRef = useRef(activePaywall);
584
+ activePaywallRef.current = activePaywall;
585
+
586
+ // Wraps `productRuntime.purchase` to record the outcome on the presentation
587
+ // the purchase STARTED on; every other field (and — critically — the
588
+ // object's change cadence, since `products.purchasing` flips must still
589
+ // propagate) is untouched. `productRuntime.purchase` is itself
440
590
  // `useCallback(…, [])`-stable (`useProducts.ts`), so this wrapper never
441
591
  // changes identity either.
442
- const purchase = useCallback(
443
- async (key: string) => {
444
- const startedInGeneration = presentationGenerationRef.current;
592
+ //
593
+ // The race guard: binding to the record captured BEFORE the await is what
594
+ // stops a stale write. Paywall A's purchase can still be in flight when the
595
+ // user dismisses A and B is presented; when A's promise settles it reaches
596
+ // A's record, which has ended, and is dropped — it never lands in B's. DO NOT
597
+ // read `presentationRecordRef` after the await because it "looks" the same;
598
+ // that is exactly the race. A record still waiting after its paywall
599
+ // disappeared has not ended, so its purchase is recorded there and ends it.
600
+ //
601
+ // The paywall a purchase was made ON is read at the start too: a background
602
+ // revalidation can swap the moment's variant mid-presentation, which stays
603
+ // credited to the variant shown first, but the bought slot's store id is the
604
+ // swapped-in variant's, and that id is what joins to revenue.
605
+ //
606
+ // A purchase with no presentation on screen (the inline step's, which tracks
607
+ // its own) is recorded nowhere.
608
+ const purchaseOn = useCallback(
609
+ async (record: PresentationRecord | null, key: string): Promise<PurchaseResult> => {
610
+ // Bound like `complete` (see `completeOnSurface`): a purchase requested
611
+ // through a presentation that is no longer on the surface — a stale
612
+ // action chain resuming after its paywall closed, e.g. a `custom` or
613
+ // `requestPermission` step followed by `purchase` — never opens the
614
+ // store over whatever is showing now, and records nothing anywhere.
615
+ // The action engine never gets here for a stale chain (it checks
616
+ // `presentationEnded` first and ends the chain); this `cancelled` is for
617
+ // a direct caller, such as a custom screen.
618
+ if (record && presentationRecordRef.current !== record) {
619
+ console.warn(
620
+ "[paywalls] A purchase was requested by a paywall that is no longer on screen; " +
621
+ "it was not started and resolves as cancelled."
622
+ );
623
+ return { status: "cancelled" };
624
+ }
625
+ const madeOn = activePaywallRef.current;
626
+ if (record) record.pending += 1;
445
627
  const result = await productRuntime.purchase(key);
628
+ if (!record || record.ended) return result;
629
+ record.pending -= 1;
446
630
  const outcome = purchaseOutcomeFromResult(result);
447
- if (outcome && shouldRecordPurchaseOutcome(startedInGeneration, presentationGenerationRef.current)) {
448
- lastPurchaseOutcomeRef.current = outcome;
631
+ // A settled purchase sticks — see `resolveEndedOutcome`.
632
+ if (outcome && record.purchaseOutcome !== "purchased") {
633
+ record.purchaseOutcome = outcome;
634
+ record.purchasedKey = result.status === "purchased" ? result.productKey : null;
635
+ record.purchasedFrom = result.status === "purchased" ? madeOn : null;
636
+ }
637
+ // Off screen (closed, or its paywall disappeared) and nothing else in
638
+ // flight: this was the purchase it was waiting for.
639
+ if (record.pending === 0 && presentationRecordRef.current !== record) {
640
+ endPresentation(record, { status: "dismissed" });
449
641
  }
450
642
  return result;
451
643
  },
452
644
  [productRuntime.purchase]
453
645
  );
646
+ // The runtime every renderer reads, its `purchase` bound to the record on
647
+ // the surface when it was rendered (null with no `present()` showing, which
648
+ // records nothing: the inline step tracks its own).
649
+ //
650
+ // `presentationEnded` is the same test `purchaseOn` refuses on, built from
651
+ // the same captured record, so the action engine's check and the refusal
652
+ // cannot disagree: a stale chain stops at its `purchase` instead of reading
653
+ // the refusal's `cancelled` as the user's and running `onCancel`.
454
654
  const productRuntimeWithPurchaseTracking = useMemo(
455
- () => ({ ...productRuntime, purchase }),
456
- [productRuntime, purchase]
655
+ () => ({
656
+ ...productRuntime,
657
+ purchase: (key: string) => purchaseOn(surfaceRecord, key),
658
+ presentationEnded: () => surfaceRecord !== null && presentationRecordRef.current !== surfaceRecord,
659
+ }),
660
+ [productRuntime, purchaseOn, surfaceRecord]
457
661
  );
458
662
 
459
663
  // `activeMoment`'s `useState` was hoisted above `productRefs` — see the
@@ -488,7 +692,7 @@ const PaywallProviderInner = ({
488
692
  // issued in the same tick (`Promise.all([present("a"), present("b")])`, or
489
693
  // two `presentPaywall` actions in one action list) both read the stale ref,
490
694
  // both take the "start" branch, and the second overwrites
491
- // `pendingResolveRef` — the first promise then never settles, exactly the
695
+ // the first one's record — that promise then never settles, exactly the
492
696
  // orphaning this whole ref/resolver scheme exists to prevent. Assigning
493
697
  // synchronously inside `present`/`complete` closes that window; this
494
698
  // render-body line stays only as a resync for the (rare) case something
@@ -496,7 +700,10 @@ const PaywallProviderInner = ({
496
700
  // callback.
497
701
  const activeMomentRef = useRef(activeMoment);
498
702
  activeMomentRef.current = activeMoment;
499
- const pendingResolveRef = useRef<((result: PresentResult) => void) | null>(null);
703
+ // Ref so `present`/`complete`/`acknowledgePresentation` keep empty deps while
704
+ // reading the CURRENT prop — hosts will pass an inline object.
705
+ const observerRef = useRef(observer);
706
+ observerRef.current = observer;
500
707
 
501
708
  // present() must not fetch anything — the catalog and products are already
502
709
  // resolved (or resolving) from mount. It only decides, synchronously,
@@ -506,22 +713,40 @@ const PaywallProviderInner = ({
506
713
  if (decision.type === "immediate") {
507
714
  return Promise.resolve(decision.result);
508
715
  }
509
- // Fresh presentation: no purchase has happened under it yet, and any
510
- // still-in-flight purchase from a PREVIOUS presentation must not be
511
- // allowed to write into this one — see `presentationGenerationRef`.
512
- lastPurchaseOutcomeRef.current = null;
513
- presentationGenerationRef.current += 1;
716
+ // A fresh record: no purchase has happened under it yet, and a purchase
717
+ // still in flight from a PREVIOUS presentation is bound to that one's
718
+ // record, never this — see the `purchase` wrapper. Only the "start"
719
+ // decision reaches here: refusals return above, before anything is
720
+ // reported (contract rule P1). The handle holds its OWN copy of the
721
+ // paywall, because by the end `activePaywall` can already be null — that
722
+ // is exactly the `paywall-disappeared` case.
723
+ const record: PresentationRecord = {
724
+ presentation: openPaywallPresentation(observerRef.current, decision.paywall, "present", Platform.OS),
725
+ resolve: () => {},
726
+ purchaseOutcome: null,
727
+ purchasedKey: null,
728
+ purchasedFrom: null,
729
+ pending: 0,
730
+ ended: false,
731
+ timer: null,
732
+ };
733
+ presentationRecordRef.current = record;
514
734
  // Authoritative NOW, synchronously — see the ref's doc above. A second
515
735
  // `present()` call before React commits reads this value, not the stale
516
736
  // pre-commit state, and correctly takes the "already showing" branch.
517
737
  activeMomentRef.current = moment;
518
738
  return new Promise<PresentResult>((resolve) => {
519
- pendingResolveRef.current = resolve;
739
+ record.resolve = resolve;
520
740
  // A new presentation is unacknowledged until the host says otherwise —
521
741
  // reset before it starts, or the previous presentation's confirmation
522
- // would vouch for this one and disable the recovery.
742
+ // would vouch for this one and disable the recovery. No exception, not
743
+ // even a successor taking a Modal that stays visible in the same commit:
744
+ // only the host knows whether it will render it (an unregistered custom
745
+ // screen or an element list that fails to parse never does), so the
746
+ // host acknowledges that case too — see `acknowledgePresentation`.
523
747
  setHostAcknowledged(false);
524
748
  setActiveMoment(moment);
749
+ setSurfaceRecord(record);
525
750
  });
526
751
  }, []);
527
752
 
@@ -561,18 +786,11 @@ const PaywallProviderInner = ({
561
786
  [present, registerTimeoutMs]
562
787
  );
563
788
 
564
- // Called by PaywallHost (Task 7) from the presented paywall's
565
- // `ScreenHost.complete`. Resolves whatever `present()` call is pending and
566
- // clears the active moment, hiding the Modal and allowing a new
567
- // `present()` to start. Safe to call with nothing pending (no-ops).
568
- //
569
- // `resolvePresentedOutcome` upgrades a bare "dismissed" to "purchased" (or
570
- // "cancelled") when the store actually did something during this
571
- // presentation — see its doc for why `dismiss`'s own `{status:"dismissed"}`
572
- // isn't treated as an unoverridable explicit answer.
573
- const complete = useCallback((result: PresentResult) => {
574
- const resolve = pendingResolveRef.current;
575
- pendingResolveRef.current = null;
789
+ // Frees the surface — clears the active moment, hiding the Modal and
790
+ // allowing a new `present()` — and hands back the record that was on it.
791
+ const releaseSurface = useCallback((): PresentationRecord | null => {
792
+ const record = presentationRecordRef.current;
793
+ presentationRecordRef.current = null;
576
794
  // Authoritative NOW, synchronously — same reasoning as `present()`'s
577
795
  // assignment above: a `present()` issued from the resolution continuation
578
796
  // (`const r = await present("a"); … present("downsell")` — a downsell
@@ -581,16 +799,80 @@ const PaywallProviderInner = ({
581
799
  // next commit.
582
800
  activeMomentRef.current = null;
583
801
  setActiveMoment(null);
802
+ setSurfaceRecord(null);
584
803
  setHostAcknowledged(false);
585
- resolve?.(resolvePresentedOutcome(result, lastPurchaseOutcomeRef.current));
804
+ return record;
586
805
  }, []);
587
806
 
807
+ // Called by PaywallHost (Task 7) from the presented paywall's
808
+ // `ScreenHost.complete`. Resolves whatever `present()` call is pending and
809
+ // clears the active moment, hiding the Modal and allowing a new
810
+ // `present()` to start. Safe to call with nothing pending (no-ops).
811
+ //
812
+ // The end is reconciled with what the store did during this presentation
813
+ // (`resolveEndedOutcome`, in `endPresentation`).
814
+ const complete = useCallback(
815
+ (result: PresentResult, transaction?: unknown) => {
816
+ // The RECONCILED outcome (`endPresentation`), so a dismiss the store
817
+ // upgraded to a purchase is reported as one. Every post-acceptance error
818
+ // funnels through here too (`host-never-presented`, the host's
819
+ // parse/render errors) — every one but `paywall-disappeared`, whose effect
820
+ // below may wait for a purchase first. Ended with the record already off
821
+ // the surface, so a downsell `present()` issued from the resolution starts
822
+ // a clean presentation.
823
+ //
824
+ // A CLOSE (`dismissed`) with a purchase in flight waits for it, as an
825
+ // inline step's blur does (owner ruling on #286): the surface is freed
826
+ // now, and the record ends with the store outcome when it settles. Any
827
+ // other reported end is the host's explicit answer and ends at once.
828
+ const record = releaseSurface();
829
+ // A transaction counts only when the screen itself reported `purchased`
830
+ // (#287): one passed with `cancelled` stays dropped even if a recorded
831
+ // purchase makes the end `purchased` — the screen tied it to a cancel.
832
+ const reported = result.status === "purchased" ? transaction : undefined;
833
+ if (record && !record.ended && transaction !== undefined && reported === undefined) {
834
+ console.warn(`[paywalls] complete() was given a transaction with status "${result.status}"; it was dropped.`);
835
+ }
836
+ if (record && !record.ended && result.status === "dismissed" && shouldWaitForPurchases(record)) {
837
+ waitForPurchases(record);
838
+ return;
839
+ }
840
+ endPresentation(record, result, reported);
841
+ },
842
+ [releaseSurface]
843
+ );
844
+
845
+ // What the context hands the host as `complete`: bound to the record this
846
+ // render showed. A paywall's action chain can outlive its presentation — a
847
+ // `{purchase, onSuccess:[dismiss]}` whose purchase settles after the Modal
848
+ // closed or the paywall disappeared, while a downsell (or the host's
849
+ // `await present()` continuation) has opened the next one — and its trailing
850
+ // `dismiss` must not end THAT one. `ScreenRenderer` reads `complete` at call
851
+ // time, so `PaywallHost` also keys its content per presentation.
852
+ const completeOnSurface = useCallback(
853
+ (result: PresentResult, transaction?: PaywallTransactionInfo) => {
854
+ // A stale call returns here, before its transaction reaches anything.
855
+ if (!surfaceRecord || presentationRecordRef.current !== surfaceRecord) return;
856
+ complete(result, transaction);
857
+ },
858
+ [surfaceRecord, complete]
859
+ );
860
+
588
861
  // Stable (empty deps) like `present`/`complete`: the host wires this straight
589
862
  // into a Modal prop, and an identity change per render would churn it.
590
863
  const acknowledgePresentation = useCallback(() => {
591
864
  setHostAcknowledged(true);
865
+ // The handle's `shown()` reaches the observer at most once and never
866
+ // throws, so a second acknowledgement of one presentation is harmless.
867
+ presentationRecordRef.current?.presentation.shown();
592
868
  }, []);
593
869
 
870
+ const observePresentation = useCallback(
871
+ (paywall: PaywallPresentationSource) =>
872
+ openPaywallPresentation(observerRef.current, paywall, "paywall_step", Platform.OS),
873
+ []
874
+ );
875
+
594
876
  // `activePaywall` was hoisted above `productRefs` — see the comment there
595
877
  // (Finding 6, 2026-08-17 final review) for why it is derived from
596
878
  // `activeMoment` rather than guarded on `catalog` alone.
@@ -601,10 +883,28 @@ const PaywallProviderInner = ({
601
883
  // `present()` call with `"error"` for the rest of the app's life.
602
884
  // `complete()` always clears `activeMoment` together with resolving the
603
885
  // pending promise, so it cannot race with or double-resolve this branch.
886
+ //
887
+ // A purchase wins over the disappearance (owner decision on #286) — a host
888
+ // that sets a user property on purchase changes the query key, which is
889
+ // exactly this case. The surface is freed either way (the Modal has nothing
890
+ // to render, and holding `activeMoment` would answer every other
891
+ // `present()` with `already-presenting`), but the record is not ended yet if
892
+ // a purchase is in flight: it waits for it, as an inline step waits after a
893
+ // blur, bounded by `LATE_PURCHASE_TIMEOUT_MS`, then ends with the store's
894
+ // outcome. One that already settled `purchased` ends it `purchased`. Only
895
+ // with neither does it end `paywall-disappeared`, at once.
604
896
  useEffect(() => {
605
897
  if (!activeMoment || activePaywall) return;
606
- complete({ status: "error", reason: "paywall-disappeared" });
607
- }, [activeMoment, activePaywall, complete]);
898
+ const record = releaseSurface();
899
+ if (!record || record.ended) return;
900
+ if (shouldWaitForPurchases(record)) {
901
+ waitForPurchases(record);
902
+ return;
903
+ }
904
+ // A purchase that already settled turns this into `purchased`
905
+ // (`resolveEndedOutcome`).
906
+ endPresentation(record, { status: "error", reason: "paywall-disappeared" });
907
+ }, [activeMoment, activePaywall, releaseSurface]);
608
908
 
609
909
  // The OTHER way a presentation never completes, and the one the guard above
610
910
  // structurally cannot catch: `activePaywall` is perfectly non-null — the
@@ -652,10 +952,11 @@ const PaywallProviderInner = ({
652
952
  isProviderMounted: true,
653
953
  productsStatus: productRuntime.status,
654
954
  activePaywall,
655
- complete,
955
+ complete: completeOnSurface,
656
956
  acknowledgePresentation,
657
957
  customActions,
658
958
  customScreens,
959
+ observePresentation,
659
960
  }),
660
961
  [
661
962
  present,
@@ -665,10 +966,11 @@ const PaywallProviderInner = ({
665
966
  catalogStatus,
666
967
  productRuntime.status,
667
968
  activePaywall,
668
- complete,
969
+ completeOnSurface,
669
970
  acknowledgePresentation,
670
971
  customActions,
671
972
  customScreens,
973
+ observePresentation,
672
974
  ]
673
975
  );
674
976
 
@@ -712,6 +1014,7 @@ export const PaywallProvider = ({
712
1014
  customScreens = EMPTY_CUSTOM_SCREENS,
713
1015
  presentAckTimeoutMs = DEFAULT_PRESENT_ACK_TIMEOUT_MS,
714
1016
  registerTimeoutMs = DEFAULT_REGISTER_TIMEOUT_MS,
1017
+ observer,
715
1018
  }: PaywallProviderProps) => {
716
1019
  // Prop wins, else whatever `OnboardingStudio.init()` built. Read during render,
717
1020
  // so `init()` must run before the first render — at module scope.
@@ -739,6 +1042,7 @@ export const PaywallProvider = ({
739
1042
  customScreens={customScreens}
740
1043
  presentAckTimeoutMs={presentAckTimeoutMs}
741
1044
  registerTimeoutMs={registerTimeoutMs}
1045
+ observer={observer}
742
1046
  >
743
1047
  {children}
744
1048
  </PaywallProviderInner>