@rocapine/react-native-onboarding 1.75.0 → 1.77.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 +30 -4
  2. package/dist/OnboardingStudioClient.d.ts +18 -0
  3. package/dist/OnboardingStudioClient.d.ts.map +1 -1
  4. package/dist/OnboardingStudioClient.js +44 -17
  5. package/dist/OnboardingStudioClient.js.map +1 -1
  6. package/dist/index.d.ts +5 -3
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +16 -2
  9. package/dist/index.js.map +1 -1
  10. package/dist/onboarding-example.d.ts +140 -0
  11. package/dist/onboarding-example.d.ts.map +1 -1
  12. package/dist/onboarding-example.js +41 -1
  13. package/dist/onboarding-example.js.map +1 -1
  14. package/dist/paywalls/PaywallProvider.d.ts +71 -5
  15. package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
  16. package/dist/paywalls/PaywallProvider.js +237 -57
  17. package/dist/paywalls/PaywallProvider.js.map +1 -1
  18. package/dist/paywalls/customScreens.d.ts +31 -0
  19. package/dist/paywalls/customScreens.d.ts.map +1 -1
  20. package/dist/paywalls/observer.d.ts +129 -0
  21. package/dist/paywalls/observer.d.ts.map +1 -0
  22. package/dist/paywalls/observer.js +211 -0
  23. package/dist/paywalls/observer.js.map +1 -0
  24. package/dist/paywalls/present.d.ts +19 -15
  25. package/dist/paywalls/present.d.ts.map +1 -1
  26. package/dist/paywalls/present.js +21 -17
  27. package/dist/paywalls/present.js.map +1 -1
  28. package/dist/paywalls/types.d.ts +3 -1
  29. package/dist/paywalls/types.d.ts.map +1 -1
  30. package/dist/products/adapters/expoIap.d.ts +38 -1
  31. package/dist/products/adapters/expoIap.d.ts.map +1 -1
  32. package/dist/products/adapters/expoIap.js +509 -75
  33. package/dist/products/adapters/expoIap.js.map +1 -1
  34. package/dist/products/index.d.ts +1 -0
  35. package/dist/products/index.d.ts.map +1 -1
  36. package/dist/products/index.js.map +1 -1
  37. package/dist/products/types.d.ts +13 -0
  38. package/dist/products/types.d.ts.map +1 -1
  39. package/dist/requestIdentity.d.ts +41 -0
  40. package/dist/requestIdentity.d.ts.map +1 -0
  41. package/dist/requestIdentity.js +70 -0
  42. package/dist/requestIdentity.js.map +1 -0
  43. package/dist/screens/completingActions.d.ts +55 -3
  44. package/dist/screens/completingActions.d.ts.map +1 -1
  45. package/dist/screens/completingActions.js +209 -15
  46. package/dist/screens/completingActions.js.map +1 -1
  47. package/dist/screens/elementTypeRegistry.d.ts +14 -0
  48. package/dist/screens/elementTypeRegistry.d.ts.map +1 -1
  49. package/dist/screens/elementTypeRegistry.js +38 -1
  50. package/dist/screens/elementTypeRegistry.js.map +1 -1
  51. package/dist/screens/elements/ButtonElement.d.ts +3 -2
  52. package/dist/screens/elements/ButtonElement.d.ts.map +1 -1
  53. package/dist/screens/elements/ButtonElement.js +5 -1
  54. package/dist/screens/elements/ButtonElement.js.map +1 -1
  55. package/dist/screens/types.d.ts +2 -2
  56. package/dist/screens/types.d.ts.map +1 -1
  57. package/dist/screens/types.js +5 -1
  58. package/dist/screens/types.js.map +1 -1
  59. package/dist/screens/unknownKeys.d.ts +25 -4
  60. package/dist/screens/unknownKeys.d.ts.map +1 -1
  61. package/dist/screens/unknownKeys.js +81 -2
  62. package/dist/screens/unknownKeys.js.map +1 -1
  63. package/dist/steps/common.types.d.ts +178 -6
  64. package/dist/steps/common.types.d.ts.map +1 -1
  65. package/dist/steps/common.types.js +64 -3
  66. package/dist/steps/common.types.js.map +1 -1
  67. package/dist/types.d.ts +17 -0
  68. package/dist/types.d.ts.map +1 -1
  69. package/dist/userProperties/reserved.d.ts +16 -15
  70. package/dist/userProperties/reserved.d.ts.map +1 -1
  71. package/dist/userProperties/reserved.js +18 -14
  72. package/dist/userProperties/reserved.js.map +1 -1
  73. package/dist/version.d.ts +10 -0
  74. package/dist/version.d.ts.map +1 -0
  75. package/dist/version.js +13 -0
  76. package/dist/version.js.map +1 -0
  77. package/package.json +5 -1
  78. package/src/OnboardingStudioClient.ts +47 -19
  79. package/src/__tests__/authoringDocEscapes.test.ts +59 -0
  80. package/src/__tests__/completingActions.test.ts +371 -1
  81. package/src/__tests__/customActionHooks.test.ts +224 -0
  82. package/src/__tests__/getOnboarding.query.test.ts +30 -0
  83. package/src/__tests__/onboardingExampleElements.test.ts +47 -0
  84. package/src/__tests__/requestIdentity.client.test.ts +115 -0
  85. package/src/__tests__/requestIdentity.test.ts +112 -0
  86. package/src/__tests__/requestPermissionAction.test.ts +138 -0
  87. package/src/__tests__/retryIdempotencyDocs.test.ts +57 -0
  88. package/src/__tests__/unknownKeys.test.ts +110 -0
  89. package/src/index.ts +33 -1
  90. package/src/onboarding-example.ts +41 -1
  91. package/src/paywalls/PaywallProvider.tsx +370 -66
  92. package/src/paywalls/__tests__/PaywallProvider.observer.test.tsx +866 -0
  93. package/src/paywalls/__tests__/getPaywalls.test.ts +30 -0
  94. package/src/paywalls/__tests__/observer.test.ts +401 -0
  95. package/src/paywalls/__tests__/present.test.ts +0 -18
  96. package/src/paywalls/customScreens.ts +34 -1
  97. package/src/paywalls/observer.ts +308 -0
  98. package/src/paywalls/present.ts +24 -18
  99. package/src/paywalls/types.ts +3 -1
  100. package/src/products/adapters/__tests__/expoIap.contract.test.ts +648 -0
  101. package/src/products/adapters/__tests__/expoIap.test.ts +25 -11
  102. package/src/products/adapters/__tests__/expoIap5Fake.ts +288 -0
  103. package/src/products/adapters/expoIap.ts +609 -78
  104. package/src/products/index.ts +1 -0
  105. package/src/products/types.ts +13 -0
  106. package/src/requestIdentity.ts +101 -0
  107. package/src/screens/completingActions.ts +223 -15
  108. package/src/screens/elementTypeRegistry.ts +34 -0
  109. package/src/screens/elements/ButtonElement.ts +9 -1
  110. package/src/screens/types.ts +2 -2
  111. package/src/screens/unknownKeys.ts +113 -7
  112. package/src/steps/common.types.ts +213 -6
  113. package/src/types.ts +17 -0
  114. package/src/userProperties/__tests__/effectiveParams.test.ts +2 -2
  115. package/src/userProperties/__tests__/primitives.test.ts +1 -1
  116. package/src/userProperties/reserved.ts +18 -14
  117. package/src/version.ts +9 -0
@@ -17,12 +17,104 @@ const toPeriod = (iso) => {
17
17
  const m = /^P(\d+)([DWMY])$/.exec(iso);
18
18
  if (!m)
19
19
  return { period: null, count: 0 };
20
+ // `D: "week"` is wrong for a daily plan and is deliberately left alone here:
21
+ // `ProductPeriod` has no "day" member, all three adapters share the same
22
+ // mapping, and widening a published union is a release-visible change rather
23
+ // than part of this fix. Tracked in #258. Only `period` is affected —
24
+ // `periodIso` is what `deriveProductFields` divides by, and it is exact.
20
25
  const map = { D: "week", W: "week", M: "month", Y: "year" };
21
26
  return { period: (_a = map[m[2]]) !== null && _a !== void 0 ? _a : null, count: Number(m[1]) };
22
27
  };
23
- // expo-iap surfaces a user cancellation as a code rather than a typed error.
24
- const isCancellation = (e) => (e === null || e === void 0 ? void 0 : e.code) === "E_USER_CANCELLED" || (e === null || e === void 0 ? void 0 : e.code) === "USER_CANCELED" || (e === null || e === void 0 ? void 0 : e.userCancelled) === true;
28
+ /**
29
+ * A user cancellation, across every code shape expo-iap has used.
30
+ *
31
+ * 5.x normalized every code to openiap kebab-case (`ErrorCode.UserCancelled
32
+ * === "user-cancelled"`, `types.js:41`) and dropped the `userCancelled`
33
+ * boolean, so testing only the pre-5.x screaming-snake codes turned a dismissed
34
+ * StoreKit sheet into `onError` on the paywall. All shapes are accepted: an
35
+ * older peer is still a supported peer.
36
+ */
37
+ const isCancellation = (e) => (e === null || e === void 0 ? void 0 : e.code) === "user-cancelled" ||
38
+ (e === null || e === void 0 ? void 0 : e.code) === "E_USER_CANCELLED" ||
39
+ (e === null || e === void 0 ? void 0 : e.code) === "USER_CANCELED" ||
40
+ (e === null || e === void 0 ? void 0 : e.userCancelled) === true;
41
+ /**
42
+ * Codes that mean the store connection is gone, so a READ is worth retrying
43
+ * after reopening it.
44
+ *
45
+ * `endConnection` is process-wide: any other `useIAP` in the host unmounting,
46
+ * or an Android `ServiceDisconnected`, closes the connection this adapter
47
+ * opened. Caching a RESOLVED connect promise then made every later call fail
48
+ * for the life of the process.
49
+ *
50
+ * **Reads only.** `requestPurchase` is never retried on these — see the comment
51
+ * on `withConnection`.
52
+ */
53
+ const CONNECTION_LOST = new Set([
54
+ "not-prepared",
55
+ "connection-closed",
56
+ "service-disconnected",
57
+ "init-connection",
58
+ "E_NOT_PREPARED",
59
+ "E_SERVICE_DISCONNECTED",
60
+ ]);
25
61
  const idFor = (ref) => react_native_1.Platform.OS === "ios" ? ref.ios : ref.android;
62
+ /**
63
+ * Play refs are authored `productId:basePlanId` (see `ProductRef.android`) —
64
+ * RevenueCat's convention, which the studio writes for every platform.
65
+ *
66
+ * expo-iap is not RevenueCat: `fetchProducts` filters the store's answer by the
67
+ * BARE `item.id` (`build/index.js:471-477`), so passing the composite id
68
+ * through matched nothing and the product was skipped — a blank Android paywall
69
+ * reporting `status: "ready"`. The base plan half is not noise either: it is
70
+ * what selects the offer, and therefore the offer token Play needs.
71
+ */
72
+ const splitAndroidRef = (id) => {
73
+ const at = id.indexOf(":");
74
+ return at < 0
75
+ ? { productId: id }
76
+ : { productId: id.slice(0, at), basePlanId: id.slice(at + 1) };
77
+ };
78
+ /** Play's `RecurrenceMode.INFINITE_RECURRING` — the ongoing phase of a base plan. */
79
+ const RECURRENCE_INFINITE = 1;
80
+ /**
81
+ * The subscription offer for the base plan the ref names.
82
+ *
83
+ * With no base plan authored there is nothing to disambiguate, so the first
84
+ * offer stands. With one authored and no offer carrying it, the ref points at a
85
+ * base plan this product does not have — worth saying out loud, because the
86
+ * purchase will be for a different plan than the price shown.
87
+ */
88
+ const offerFor = (s, basePlanId, productId) => {
89
+ const offers = Array.isArray(s === null || s === void 0 ? void 0 : s.subscriptionOffers) ? s.subscriptionOffers : [];
90
+ if (offers.length === 0)
91
+ return undefined;
92
+ if (!basePlanId)
93
+ return offers[0];
94
+ const matched = offers.find((o) => (o === null || o === void 0 ? void 0 : o.basePlanIdAndroid) === basePlanId);
95
+ if (matched)
96
+ return matched;
97
+ console.warn(`expoIapProductProvider: "${productId}" has no base plan "${basePlanId}" — ` +
98
+ `offers are [${offers.map((o) => { var _a; return (_a = o === null || o === void 0 ? void 0 : o.basePlanIdAndroid) !== null && _a !== void 0 ? _a : "?"; }).join(", ")}]. ` +
99
+ `Falling back to the first offer; the authored ref is probably stale.`);
100
+ return offers[0];
101
+ };
102
+ /**
103
+ * The phase of an Android offer that the subscriber actually recurs on.
104
+ *
105
+ * `pricingPhaseList[0]` is the TRIAL or intro phase whenever one exists, so
106
+ * reading it gave a $59.99/year plan with a one-week trial `periodIso: "P1W"` —
107
+ * and a `pricePerYear` near $3,130, because `deriveProductFields` divides the
108
+ * price by the period it is told. Prefer the infinite-recurring phase; failing
109
+ * that the last priced phase, since intro phases come first.
110
+ */
111
+ const recurringPhase = (offer) => {
112
+ var _a, _b, _c, _d;
113
+ const phases = (_b = (_a = offer === null || offer === void 0 ? void 0 : offer.pricingPhasesAndroid) === null || _a === void 0 ? void 0 : _a.pricingPhaseList) !== null && _b !== void 0 ? _b : [];
114
+ if (phases.length === 0)
115
+ return undefined;
116
+ return ((_d = (_c = phases.find((p) => Number(p === null || p === void 0 ? void 0 : p.recurrenceMode) === RECURRENCE_INFINITE)) !== null && _c !== void 0 ? _c : [...phases].reverse().find((p) => { var _a; return Number((_a = p === null || p === void 0 ? void 0 : p.priceAmountMicros) !== null && _a !== void 0 ? _a : 0) > 0; })) !== null && _d !== void 0 ? _d : phases[phases.length - 1]);
117
+ };
26
118
  const ISO_UNIT = { day: "D", week: "W", month: "M", year: "Y" };
27
119
  /**
28
120
  * The store's billing period as an ISO-8601 duration.
@@ -37,12 +129,12 @@ const ISO_UNIT = { day: "D", week: "W", month: "M", year: "Y" };
37
129
  * expo-iap has never exposed one ready-made, and the shape has moved:
38
130
  * - ≤4.x published `subscriptionPeriodISO` / `subscriptionPeriod` on the product
39
131
  * - 5.x publishes the iOS period SPLIT in two (`subscriptionPeriodUnitIOS`,
40
- * `subscriptionPeriodNumberIOS`) and the Android one buried in the first
41
- * pricing phase of the first subscription offer
132
+ * `subscriptionPeriodNumberIOS`) and the Android one in the pricing phases
133
+ * of a subscription offer
42
134
  * All three are read, newest-shape-last so an older peer keeps working.
43
135
  */
44
- const periodIsoFrom = (s) => {
45
- var _a, _b, _c, _d, _e, _f, _g, _h;
136
+ const periodIsoFrom = (s, phase) => {
137
+ var _a, _b, _c;
46
138
  const direct = (_a = s === null || s === void 0 ? void 0 : s.subscriptionPeriodISO) !== null && _a !== void 0 ? _a : s === null || s === void 0 ? void 0 : s.subscriptionPeriod;
47
139
  if (typeof direct === "string" && direct)
48
140
  return direct;
@@ -54,17 +146,207 @@ const periodIsoFrom = (s) => {
54
146
  const n = Number((_c = s === null || s === void 0 ? void 0 : s.subscriptionPeriodNumberIOS) !== null && _c !== void 0 ? _c : 1);
55
147
  return `P${Number.isFinite(n) && n > 0 ? n : 1}${unit}`;
56
148
  }
57
- const androidPeriod = (_h = (_g = (_f = (_e = (_d = s === null || s === void 0 ? void 0 : s.subscriptionOffers) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.pricingPhasesAndroid) === null || _f === void 0 ? void 0 : _f.pricingPhaseList) === null || _g === void 0 ? void 0 : _g[0]) === null || _h === void 0 ? void 0 : _h.billingPeriod;
149
+ const androidPeriod = phase === null || phase === void 0 ? void 0 : phase.billingPeriod;
58
150
  return typeof androidPeriod === "string" && androidPeriod ? androidPeriod : null;
59
151
  };
152
+ /** Does this delivered transaction belong to the sku we asked for? */
153
+ const deliversFor = (purchase, sku) => (purchase === null || purchase === void 0 ? void 0 : purchase.productId) === sku ||
154
+ (Array.isArray(purchase === null || purchase === void 0 ? void 0 : purchase.ids) && purchase.ids.includes(sku));
155
+ /** The products a `PurchaseError` names, if it names any (`types.d.ts:1164-1174`). */
156
+ const errorSkus = (e) => [e === null || e === void 0 ? void 0 : e.productId, ...(Array.isArray(e === null || e === void 0 ? void 0 : e.productIds) ? e.productIds : [])].filter((s) => typeof s === "string" && s.length > 0);
157
+ /** A transaction id, which is what `Purchase.id` carries (`types.d.ts:1151`). */
158
+ const txIdOf = (purchase) => typeof (purchase === null || purchase === void 0 ? void 0 : purchase.id) === "string" && purchase.id ? purchase.id : null;
159
+ /**
160
+ * `purchaseState` is `'pending' | 'purchased' | 'unknown'` (`types.d.ts:1264`).
161
+ *
162
+ * `getAvailablePurchases` reports UNFINISHED purchases too, so an Android
163
+ * slow-payment purchase used to entitle the user before the money moved. Grant
164
+ * only on an explicit "purchased" — with one exception, a peer that reports no
165
+ * state at all predates the field, and rejecting its silence would break every
166
+ * restore on that peer rather than tightening anything.
167
+ */
168
+ const isPaid = (p) => (p === null || p === void 0 ? void 0 : p.purchaseState) == null || p.purchaseState === "purchased";
169
+ /**
170
+ * expo-iap reports a purchase failure two different ways, and only one of them
171
+ * is an `Error`.
172
+ *
173
+ * A rejection from `requestPurchase` is a real `Error` (`createPurchaseError`,
174
+ * `utils/errorMapping.d.ts:19` — `PurchaseError extends Error`). What arrives
175
+ * on `purchaseErrorListener` is the OTHER `PurchaseError`: the plain
176
+ * `{ code, message }` shape from `types.d.ts:1164`, straight off the native
177
+ * emitter. `new Error(String(plainObject))` turns that into
178
+ * "[object Object]" — the store's diagnosis, thrown away at the one point a
179
+ * host would read it.
180
+ */
181
+ const asError = (e) => {
182
+ if (e instanceof Error)
183
+ return e;
184
+ const message = typeof (e === null || e === void 0 ? void 0 : e.message) === "string" && e.message ? e.message : String(e);
185
+ const code = e === null || e === void 0 ? void 0 : e.code;
186
+ const error = new Error(code ? `${message} (${code})` : message);
187
+ if (code)
188
+ error.code = code;
189
+ return error;
190
+ };
191
+ const failureFor = (e) => isCancellation(e) ? { status: "cancelled" } : { status: "error", error: asError(e) };
192
+ const DEFAULT_PURCHASE_TIMEOUT_MS = 180000;
60
193
  /** Direct StoreKit / Play Billing provider, no vendor in the path. */
61
- const expoIapProductProvider = (Iap = IAP) => {
194
+ const expoIapProductProvider = (Iap = IAP, options = {}) => {
195
+ var _a;
196
+ const purchaseTimeoutMs = (_a = options.purchaseTimeoutMs) !== null && _a !== void 0 ? _a : DEFAULT_PURCHASE_TIMEOUT_MS;
62
197
  const required = () => {
63
198
  if (!Iap) {
64
199
  throw new Error("expoIapProductProvider: expo-iap is not installed. Install it, or pass a different ProductProvider.");
65
200
  }
66
201
  return Iap;
67
202
  };
203
+ // ---------------------------------------------------------------------------
204
+ // The finish lifetime.
205
+ //
206
+ // Acknowledging the money is a SEPARATE concern from answering the caller,
207
+ // and an earlier version of this file conflated them: it guarded both on one
208
+ // `claimed` flag and removed its listeners the moment the caller had an
209
+ // answer. Every path that answered early — an unrelated product's error, a
210
+ // `pending` update, the timeout — permanently lost the ability to finish the
211
+ // charge, and Play auto-refunds an unacknowledged purchase after 3 days.
212
+ //
213
+ // So the listeners are opened ONCE, on first connect, and live as long as the
214
+ // provider. That is also forced by expo-iap's iOS dedupe: each new
215
+ // `purchaseUpdatedListener` seeds its history from a PROCESS-WIDE set
216
+ // (`ids: new Set(purchaseUpdatedDedupeHistoryIOS.ids)`, `build/index.js`
217
+ // :148-151, recorded into the global at :164, cleared only by a successful
218
+ // `endConnection`). Subscribing per Buy tap therefore inherits every
219
+ // transaction id any other listener in the process has ever seen — the host's
220
+ // own `useIAP`, for instance — and silently drops them. One early
221
+ // subscription sees each transaction exactly once instead.
222
+ // ---------------------------------------------------------------------------
223
+ let subscriptions = null;
224
+ /** Skus this process asked to buy. A delivery for one of these is ours. */
225
+ const dispatchedSkus = new Set();
226
+ /** Transaction ids already acknowledged, so no delivery finishes twice. */
227
+ const finishedTxIds = new Set();
228
+ /** Acknowledgements that threw, retried on the next store round-trip. */
229
+ const unfinished = new Map();
230
+ const waiters = new Set();
231
+ let warnedUnclaimed = false;
232
+ /** Only iOS publishes a consumable discriminator; see `getProducts`. */
233
+ const consumableBySku = new Map();
234
+ const finish = async (purchase, isConsumable) => {
235
+ const M = required();
236
+ const tx = txIdOf(purchase);
237
+ if (tx && finishedTxIds.has(tx))
238
+ return;
239
+ if (typeof M.finishTransaction !== "function")
240
+ return;
241
+ try {
242
+ await M.finishTransaction({ purchase, isConsumable });
243
+ if (tx) {
244
+ finishedTxIds.add(tx);
245
+ unfinished.delete(tx);
246
+ }
247
+ }
248
+ catch (e) {
249
+ // Best-effort: a failure here does not un-buy anything, so it must not
250
+ // turn a completed purchase into an error. But it must not be forgotten
251
+ // either — Play's 3-day window is still running.
252
+ if (tx)
253
+ unfinished.set(tx, { purchase, isConsumable });
254
+ console.warn(`expoIapProductProvider: could not finish transaction ${tx !== null && tx !== void 0 ? tx : "(no id)"} ` +
255
+ `for "${purchase === null || purchase === void 0 ? void 0 : purchase.productId}" — will retry on the next store call. ${String(e)}`);
256
+ }
257
+ };
258
+ /** Give an earlier failed acknowledgement another go; never throws. */
259
+ const retryUnfinished = async () => {
260
+ for (const [, record] of [...unfinished]) {
261
+ try {
262
+ await finish(record.purchase, record.isConsumable);
263
+ }
264
+ catch (_a) {
265
+ // finish() already swallows and re-queues; belt and braces
266
+ }
267
+ }
268
+ };
269
+ /** Hand a result to the one caller waiting on this transaction's sku, if any. */
270
+ const answer = (purchase, result) => {
271
+ for (const w of waiters) {
272
+ if (w.settled || !deliversFor(purchase, w.sku))
273
+ continue;
274
+ w.answer(result.status === "purchased" ? Object.assign(Object.assign({}, result), { productKey: w.productKey }) : result);
275
+ return;
276
+ }
277
+ };
278
+ const handleUpdated = async (purchase) => {
279
+ const sku = purchase === null || purchase === void 0 ? void 0 : purchase.productId;
280
+ const isConsumable = (sku != null && consumableBySku.get(sku)) || false;
281
+ // Play's slow-payment path: the user has committed but the money has not
282
+ // moved, and Android cannot acknowledge it anyway (no `purchaseToken` yet,
283
+ // `build/index.js:865-874`). Tell the caller — then keep listening, because
284
+ // Play emits `purchased` for the SAME transaction once it clears. Treating
285
+ // this as terminal is what left a cleared purchase unfinished.
286
+ if ((purchase === null || purchase === void 0 ? void 0 : purchase.purchaseState) === "pending") {
287
+ answer(purchase, { status: "pending" });
288
+ return;
289
+ }
290
+ if (sku != null && dispatchedSkus.has(sku)) {
291
+ await finish(purchase, isConsumable);
292
+ // `productKey` is filled in by `answer` from the waiting caller's ref.
293
+ answer(purchase, { status: "purchased", productKey: "" });
294
+ return;
295
+ }
296
+ // Nobody here asked for this one: a replay from a previous process, an Ask
297
+ // to Buy approval, a promoted product. Only the host knows whether it has
298
+ // been honoured, so only the host can authorise finishing it.
299
+ if (options.onUnclaimedPurchase) {
300
+ if (await options.onUnclaimedPurchase(purchase))
301
+ await finish(purchase, isConsumable);
302
+ return;
303
+ }
304
+ if (!warnedUnclaimed) {
305
+ warnedUnclaimed = true;
306
+ console.warn(`expoIapProductProvider: the store delivered a transaction nobody is waiting for ` +
307
+ `("${sku}"). It is left unfinished, so it will be re-delivered next launch. ` +
308
+ `Pass onUnclaimedPurchase to grant entitlement and finish it.`);
309
+ }
310
+ };
311
+ /**
312
+ * Attribute a store failure to the purchase it belongs to.
313
+ *
314
+ * The error listener is process-wide and unfiltered — expo-iap forwards the
315
+ * event verbatim (`build/index.js:195-200`), and on Android the module emits
316
+ * from a single listener registered per module (`ExpoIapHelper.kt`), buffering
317
+ * events while disconnected and flushing them on the next successful
318
+ * `initConnection` (`ExpoIapModule.kt:198-205`). Claiming unconditionally
319
+ * therefore let another product's failure — or a stale buffered one — answer
320
+ * this purchase, after which the real transaction arrived to a caller that
321
+ * had already been told "error".
322
+ */
323
+ const handleError = (e) => {
324
+ const open = [...waiters].filter((w) => !w.settled);
325
+ if (open.length === 0)
326
+ return;
327
+ const named = errorSkus(e);
328
+ // With no product named there is nothing to match on, so attribute it only
329
+ // when a single purchase is in flight and it cannot be anyone else's.
330
+ const target = named.length > 0
331
+ ? open.find((w) => named.includes(w.sku))
332
+ : open.length === 1
333
+ ? open[0]
334
+ : undefined;
335
+ target === null || target === void 0 ? void 0 : target.answer(failureFor(e));
336
+ };
337
+ const listen = () => {
338
+ if (subscriptions)
339
+ return;
340
+ const M = required();
341
+ const subs = [];
342
+ if (typeof M.purchaseUpdatedListener === "function") {
343
+ subs.push(M.purchaseUpdatedListener((p) => void handleUpdated(p)));
344
+ }
345
+ if (typeof M.purchaseErrorListener === "function") {
346
+ subs.push(M.purchaseErrorListener((e) => handleError(e)));
347
+ }
348
+ subscriptions = subs;
349
+ };
68
350
  // Every expo-iap query fails until the store connection is open, and nothing
69
351
  // opens it implicitly — `useIAP` does it for hook consumers, but this adapter
70
352
  // is not a hook. Cached so concurrent getProducts/purchase/restore calls share
@@ -74,8 +356,10 @@ const expoIapProductProvider = (Iap = IAP) => {
74
356
  let connecting = null;
75
357
  const connect = async () => {
76
358
  const M = required();
77
- if (typeof M.initConnection !== "function")
78
- return; // older peer: implicit connection
359
+ if (typeof M.initConnection !== "function") {
360
+ listen(); // older peer: implicit connection, but events still arrive
361
+ return;
362
+ }
79
363
  if (!connecting) {
80
364
  connecting = Promise.resolve(M.initConnection()).catch((e) => {
81
365
  connecting = null;
@@ -83,49 +367,133 @@ const expoIapProductProvider = (Iap = IAP) => {
83
367
  });
84
368
  }
85
369
  await connecting;
370
+ // As early as possible, and before any purchase: a transaction replayed at
371
+ // launch has no caller, and a listener attached later would inherit a
372
+ // dedupe history that hides it.
373
+ listen();
86
374
  };
87
- // The raw store product per resolved productId, captured during getProducts.
88
- // `purchase()` needs expo-iap's own `type` discriminator ("in-app" | "subs")
89
- // and the full Purchase to finish, neither of which survives the trip through
90
- // `ResolvedProduct`. Same pattern as stripeLink's `linkByKey`.
91
- const rawById = new Map();
375
+ /**
376
+ * Run a READ, reopening the connection once if it turns out to be gone.
377
+ *
378
+ * `requestPurchase` is deliberately NOT run through this. An earlier version
379
+ * did, on the stated reasoning that a CONNECTION_LOST code is thrown before
380
+ * any billing flow starts — which the Android module disproves.
381
+ * `requestPurchase` sets `reachedOpenIapRequest = true` BEFORE calling
382
+ * `openIap.requestPurchase` (`ExpoIapModule.kt:435-436`), and
383
+ * `deliverPurchaseRequestFailure` (`:63-75`) rejects the pending promise on
384
+ * every path, mid-flight included. Worse, `service-disconnected` is the
385
+ * catch-all code for any failure that is not an `OpenIapError` (`:60-61`), so
386
+ * the code carries no information about whether the sheet was ever shown.
387
+ * Retrying it can present a SECOND sheet, charge a consumable twice, and
388
+ * discard the result.
389
+ */
390
+ const withConnection = async (op) => {
391
+ await connect();
392
+ try {
393
+ return await op();
394
+ }
395
+ catch (e) {
396
+ if (!CONNECTION_LOST.has(String(e === null || e === void 0 ? void 0 : e.code)))
397
+ throw e;
398
+ connecting = null;
399
+ await connect();
400
+ return await op();
401
+ }
402
+ };
403
+ // Per REF key, not per productId: two refs routinely name the same Play
404
+ // subscription through different base plans ("pro:annual", "pro:monthly"),
405
+ // and they need different offer tokens. Never cleared — a second resolve used
406
+ // to wipe the first set, leaving already-rendered products unpurchasable.
407
+ const metaByKey = new Map();
92
408
  return {
409
+ dispose() {
410
+ var _a;
411
+ for (const s of subscriptions !== null && subscriptions !== void 0 ? subscriptions : []) {
412
+ try {
413
+ (_a = s.remove) === null || _a === void 0 ? void 0 : _a.call(s);
414
+ }
415
+ catch (_b) {
416
+ // a peer whose subscription has no remove(); nothing to undo
417
+ }
418
+ }
419
+ subscriptions = null;
420
+ },
93
421
  async getProducts(refs) {
94
- var _a, _b, _c, _d, _e, _f, _g, _h;
422
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
95
423
  const M = required();
96
- const wanted = refs.map((r) => ({ ref: r, id: idFor(r) })).filter((x) => !!x.id);
424
+ const wanted = refs
425
+ .map((ref) => {
426
+ const authored = idFor(ref);
427
+ if (!authored)
428
+ return null;
429
+ if (react_native_1.Platform.OS === "ios")
430
+ return { ref, id: authored, basePlanId: undefined };
431
+ const { productId, basePlanId } = splitAndroidRef(authored);
432
+ return { ref, id: productId, basePlanId };
433
+ })
434
+ .filter((x) => !!x);
97
435
  if (wanted.length === 0)
98
436
  return [];
99
- await connect();
100
- const skus = wanted.map((w) => w.id);
437
+ // Deduped: two base plans of one subscription are one product query.
438
+ const skus = Array.from(new Set(wanted.map((w) => w.id)));
101
439
  // 5.x renamed `getProducts(skus)` to `fetchProducts({ skus, type })` — an
102
440
  // object arg, not a positional array. Calling the old name on 5.x throws
103
441
  // "M.getProducts is not a function", so probe rather than assume; `"all"`
104
442
  // because a paywall mixes subscriptions and one-off lifetime products.
105
- const store = typeof M.fetchProducts === "function"
106
- ? await M.fetchProducts({ skus, type: "all" })
107
- : await M.getProducts(skus);
108
- const list = Array.isArray(store) ? store : [];
109
- const byId = new Map(list.map((s) => { var _a; return [(_a = s.id) !== null && _a !== void 0 ? _a : s.productId, s]; }));
110
- rawById.clear();
443
+ const store = await withConnection(() => typeof M.fetchProducts === "function"
444
+ ? M.fetchProducts({ skus, type: "all" })
445
+ : M.getProducts(skus));
446
+ // `FetchProductsResult` includes `null` (`types.d.ts:527`). Coercing that
447
+ // to `[]` put the runtime in `status: "ready"` with an empty catalog, so
448
+ // every `{{product.*}}` rendered blank and nothing said why. A failed
449
+ // query is an error; `useProducts` has a state for it.
450
+ if (!Array.isArray(store)) {
451
+ throw new Error(`expoIapProductProvider: expo-iap did not return a product list for [${skus.join(", ")}] ` +
452
+ `(got ${store === null ? "null" : typeof store}). The store query failed.`);
453
+ }
454
+ const byId = new Map(store.map((s) => { var _a; return [(_a = s.id) !== null && _a !== void 0 ? _a : s.productId, s]; }));
455
+ const missing = skus.filter((id) => !byId.has(id));
456
+ if (missing.length > 0) {
457
+ // Silence here is how a blank paywall reaches `status: "ready"`: an id
458
+ // the store does not know is simply absent from the answer.
459
+ console.warn(`expoIapProductProvider: the store returned no product for [${missing.join(", ")}]. ` +
460
+ `Check the id is registered and approved for this platform.`);
461
+ }
111
462
  const out = [];
112
- for (const { ref, id } of wanted) {
463
+ for (const { ref, id, basePlanId } of wanted) {
113
464
  const s = byId.get(id);
114
465
  if (!s)
115
466
  continue;
116
467
  const productId = (_a = s.id) !== null && _a !== void 0 ? _a : s.productId;
117
- rawById.set(productId, s);
118
- const iso = periodIsoFrom(s);
468
+ const offer = offerFor(s, basePlanId, productId);
469
+ const phase = recurringPhase(offer);
470
+ const iso = periodIsoFrom(s, phase);
119
471
  const { period, count } = toPeriod(iso);
472
+ metaByKey.set(ref.key, {
473
+ type: s.type,
474
+ offerToken: (_b = offer === null || offer === void 0 ? void 0 : offer.offerTokenAndroid) !== null && _b !== void 0 ? _b : undefined,
475
+ });
476
+ // Only iOS publishes the discriminator. Android one-time products are
477
+ // all `type: "in-app"` and consumability is the app's decision, so a
478
+ // Play consumable still needs the host to say so — see the CHANGELOG.
479
+ consumableBySku.set(productId, s.typeIOS === "consumable");
120
480
  out.push({
121
481
  key: ref.key,
122
482
  productId,
123
483
  store: react_native_1.Platform.OS === "ios" ? "app_store" : "play_store",
124
- title: (_b = s.title) !== null && _b !== void 0 ? _b : "",
125
- description: (_c = s.description) !== null && _c !== void 0 ? _c : "",
126
- price: (_e = (_d = s.displayPrice) !== null && _d !== void 0 ? _d : s.localizedPrice) !== null && _e !== void 0 ? _e : "",
127
- priceAmount: Number((_f = s.price) !== null && _f !== void 0 ? _f : 0),
128
- currencyCode: (_h = (_g = s.currency) !== null && _g !== void 0 ? _g : s.currencyCode) !== null && _h !== void 0 ? _h : "",
484
+ title: (_c = s.title) !== null && _c !== void 0 ? _c : "",
485
+ description: (_d = s.description) !== null && _d !== void 0 ? _d : "",
486
+ // Phase fallbacks only: what the store reports at the top level stays
487
+ // authoritative. On Android the base plan's price lives in the phase,
488
+ // and this run had no device to confirm whether openiap fills the
489
+ // top-level fields for a subscription.
490
+ price: (_g = (_f = (_e = s.displayPrice) !== null && _e !== void 0 ? _e : s.localizedPrice) !== null && _f !== void 0 ? _f : phase === null || phase === void 0 ? void 0 : phase.formattedPrice) !== null && _g !== void 0 ? _g : "",
491
+ priceAmount: typeof s.price === "number"
492
+ ? s.price
493
+ : (phase === null || phase === void 0 ? void 0 : phase.priceAmountMicros) != null
494
+ ? Number(phase.priceAmountMicros) / 1000000
495
+ : 0,
496
+ currencyCode: (_k = (_j = (_h = s.currency) !== null && _h !== void 0 ? _h : s.currencyCode) !== null && _j !== void 0 ? _j : phase === null || phase === void 0 ? void 0 : phase.priceCurrencyCode) !== null && _k !== void 0 ? _k : "",
129
497
  period,
130
498
  periodCount: count,
131
499
  periodIso: iso,
@@ -134,66 +502,132 @@ const expoIapProductProvider = (Iap = IAP) => {
134
502
  return out;
135
503
  },
136
504
  async purchase(product) {
137
- var _a;
505
+ var _a, _b;
138
506
  const M = required();
507
+ const meta = metaByKey.get(product.key);
508
+ const sku = product.productId;
509
+ // `periodIso`, not `period`: `toPeriod` rejects a compound duration like
510
+ // "P1Y1M", so a `period`-based test called a real subscription "in-app"
511
+ // and Play rejects the wrong type outright.
512
+ const isSubs = ((_a = meta === null || meta === void 0 ? void 0 : meta.type) !== null && _a !== void 0 ? _a : (product.periodIso ? "subs" : "in-app")) === "subs";
139
513
  try {
140
514
  await connect();
141
- const raw = rawById.get(product.productId);
142
- // A non-null period means a subscription even when the raw product is
143
- // missing (a host that hydrated the runtime from elsewhere).
144
- const isSubs = ((_a = raw === null || raw === void 0 ? void 0 : raw.type) !== null && _a !== void 0 ? _a : (product.period ? "subs" : "in-app")) === "subs";
145
- const sku = product.productId;
146
- // 5.x wants `{ request: { ios, android }, type }`. The old flat
147
- // `{ request: { sku } }` reaches neither platform branch, so StoreKit is
148
- // handed an undefined sku. `type` is required to tell a subscription
149
- // from a one-off — Play rejects the wrong one outright.
150
- const args = typeof M.fetchProducts === "function"
151
- ? {
152
- request: { ios: { sku }, android: { skus: [sku] } },
153
- type: isSubs ? "subs" : "in-app",
154
- }
155
- : { request: { sku } };
156
- const result = await M.requestPurchase(args);
157
- // `requestPurchase` resolves `Purchase | Purchase[] | null`. `null` is
158
- // the normal 5.x outcome: the transaction is delivered to
159
- // `purchaseUpdatedListener` instead, so at this point nothing is
160
- // confirmed. Reporting "purchased" there would grant access for a
161
- // purchase that may still fail — hence "pending", which is exactly the
162
- // outcome `PurchaseButtonAction.onPending` exists to handle.
163
- const purchase = Array.isArray(result) ? result[0] : result;
164
- if (!purchase)
165
- return { status: "pending" };
166
- // Unfinished transactions are re-delivered by StoreKit on every launch
167
- // until finished. Best-effort: a failure here does not un-buy anything,
168
- // so it must not turn a completed purchase into an error.
169
- if (typeof M.finishTransaction === "function") {
170
- try {
171
- await M.finishTransaction({ purchase, isConsumable: false });
515
+ }
516
+ catch (e) {
517
+ return failureFor(e);
518
+ }
519
+ // An acknowledgement that failed earlier gets another go now that the
520
+ // store is reachable, before anything new is dispatched.
521
+ await retryUnfinished();
522
+ let resolveWaiter;
523
+ const waiter = {
524
+ sku,
525
+ productKey: product.key,
526
+ answer: (r) => {
527
+ if (waiter.settled)
528
+ return;
529
+ waiter.settled = r;
530
+ resolveWaiter(r);
531
+ },
532
+ promise: new Promise((resolve) => {
533
+ resolveWaiter = resolve;
534
+ }),
535
+ };
536
+ waiters.add(waiter);
537
+ // Recorded BEFORE dispatch: on a fast store the transaction can be
538
+ // delivered before `requestPurchase` resolves.
539
+ dispatchedSkus.add(sku);
540
+ let timer;
541
+ try {
542
+ const apple = { sku };
543
+ const google = { skus: [sku] };
544
+ if (isSubs) {
545
+ // Play needs an offer token to know WHICH base plan is being bought;
546
+ // without one it cannot start the billing flow. `in-app` must NOT
547
+ // carry the field — expo-iap rejects the mismatch outright
548
+ // (`validateAndroidPurchaseBranchOptions`, `build/index.js:659-676`).
549
+ if (meta === null || meta === void 0 ? void 0 : meta.offerToken) {
550
+ google.subscriptionOffers = [{ sku, offerToken: meta.offerToken }];
172
551
  }
173
- catch (_b) {
174
- // ignore — reported as purchased, will be re-delivered and finished later
552
+ else if (react_native_1.Platform.OS === "android") {
553
+ console.warn(`expoIapProductProvider: no Play offer token for "${sku}" — the base plan cannot ` +
554
+ `be selected and the purchase will fail. Author the ref as "productId:basePlanId".`);
175
555
  }
176
556
  }
177
- return { status: "purchased", productKey: product.key };
557
+ // ONE shape for every supported peer. `normalizeRequestProps` reads
558
+ // `request.apple` / `request.google` in 5.x (`build/index.js:650-656`);
559
+ // 4.x reads the same keys first and only warns when it falls back to
560
+ // `request.ios` / `request.android` (4.7.2 `build/index.js:666-679`).
561
+ // So there is nothing to version-probe here — and probing on
562
+ // `fetchProducts` never worked anyway, since 4.4+ has it too.
563
+ //
564
+ // NOT wrapped in `withConnection`: see its comment. A retry here can
565
+ // present a second store sheet.
566
+ const dispatched = await M.requestPurchase({
567
+ request: { apple, google },
568
+ type: isSubs ? "subs" : "in-app",
569
+ });
570
+ // iOS resolves the transaction directly when StoreKit hands one back,
571
+ // and `[]` / `null` otherwise (`build/index.js:745-751`). Route it
572
+ // through the same handler — including the sku check, which the
573
+ // listener path applies and this one used to skip.
574
+ const direct = Array.isArray(dispatched) ? dispatched[0] : dispatched;
575
+ if (direct && deliversFor(direct, sku))
576
+ await handleUpdated(direct);
577
+ if (waiter.settled)
578
+ return waiter.settled;
579
+ // A peer too old to have `purchaseUpdatedListener` has no way to tell us
580
+ // how this ended, so there is nothing to wait for.
581
+ if (typeof M.purchaseUpdatedListener !== "function")
582
+ return { status: "pending" };
583
+ return await Promise.race([
584
+ waiter.promise,
585
+ new Promise((resolve) => {
586
+ timer = setTimeout(() => resolve({ status: "pending" }), purchaseTimeoutMs);
587
+ }),
588
+ ]);
178
589
  }
179
590
  catch (e) {
180
- if (isCancellation(e))
181
- return { status: "cancelled" };
182
- return { status: "error", error: e instanceof Error ? e : new Error(String(e)) };
591
+ // The store's own event is more specific than a rejection that may only
592
+ // say `service-disconnected`, so an answer already delivered wins.
593
+ return (_b = waiter.settled) !== null && _b !== void 0 ? _b : failureFor(e);
594
+ }
595
+ finally {
596
+ if (timer)
597
+ clearTimeout(timer);
598
+ // Only the ANSWER slot closes here. The listeners stay attached and the
599
+ // sku stays in `dispatchedSkus`, so a verdict arriving after this call
600
+ // has returned is still acknowledged.
601
+ waiters.delete(waiter);
183
602
  }
184
603
  },
185
604
  async restore() {
186
605
  const M = required();
187
606
  try {
188
- await connect();
189
- const purchases = await M.getAvailablePurchases();
190
- const ids = (purchases !== null && purchases !== void 0 ? purchases : []).map((p) => { var _a; return (_a = p.id) !== null && _a !== void 0 ? _a : p.productId; }).filter(Boolean);
607
+ const purchases = await withConnection(async () => {
608
+ // `restorePurchases()` performs the iOS StoreKit sync first and then
609
+ // refreshes, but deliberately returns nothing — "consumers should
610
+ // call `getAvailablePurchases`" (`build/index.js:886-899`). Behind a
611
+ // user-facing Restore button that sync is the point.
612
+ if (typeof M.restorePurchases === "function") {
613
+ await M.restorePurchases();
614
+ }
615
+ return M.getAvailablePurchases();
616
+ });
617
+ // `productId`, not `id`: `Purchase.id` is the TRANSACTION id and is
618
+ // always set (`types.d.ts:1151`), so `p.id ?? p.productId` never fell
619
+ // through and restore handed the host transaction ids to match against
620
+ // its entitlements. `?? p.id` stays for a peer that only has the one.
621
+ const ids = Array.from(new Set((Array.isArray(purchases) ? purchases : [])
622
+ .filter(isPaid)
623
+ .map((p) => { var _a; return (_a = p.productId) !== null && _a !== void 0 ? _a : p.id; })
624
+ .filter(Boolean)));
191
625
  return ids.length > 0
192
626
  ? { status: "restored", entitlements: ids }
193
627
  : { status: "nothing_to_restore" };
194
628
  }
195
629
  catch (e) {
196
- return { status: "error", error: e instanceof Error ? e : new Error(String(e)) };
630
+ return { status: "error", error: asError(e) };
197
631
  }
198
632
  },
199
633
  };