@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
@@ -0,0 +1,648 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { makeExpoIap5 } from "./expoIap5Fake";
3
+ import type { ProductRef } from "../../types";
4
+
5
+ // `Platform` is read at CALL time by the adapter (`idFor`), so one mutable
6
+ // object serves both platform branches. Every test in the old suite ran under
7
+ // iOS only — including the one named "reads the Android billing period" — which
8
+ // is why the Android request branch was never exercised.
9
+ const rn = vi.hoisted(() => ({ Platform: { OS: "ios" as "ios" | "android" } }));
10
+ vi.mock("react-native", () => rn);
11
+
12
+ import { expoIapProductProvider } from "../expoIap";
13
+
14
+ const YEARLY_IOS: ProductRef = { key: "yearly", ios: "pro_yearly" };
15
+ const LIFETIME_IOS: ProductRef = { key: "lifetime", ios: "pro_lifetime" };
16
+ /** Play refs are authored `productId:basePlanId` — see ProductRef.android. */
17
+ const YEARLY_PLAY: ProductRef = { key: "yearly", android: "pro_yearly:annual" };
18
+
19
+ const iosYearly = {
20
+ id: "pro_yearly",
21
+ type: "subs",
22
+ title: "Pro Yearly",
23
+ description: "Best value",
24
+ displayPrice: "$59.99",
25
+ price: 59.99,
26
+ currency: "USD",
27
+ subscriptionPeriodUnitIOS: "year",
28
+ subscriptionPeriodNumberIOS: "1",
29
+ };
30
+
31
+ const iosLifetime = {
32
+ id: "pro_lifetime",
33
+ type: "in-app",
34
+ typeIOS: "non-consumable",
35
+ title: "Lifetime",
36
+ description: "One time",
37
+ displayPrice: "$119.99",
38
+ price: 119.99,
39
+ currency: "USD",
40
+ };
41
+
42
+ /**
43
+ * A Play subscription with a 1-week free trial in front of a yearly base plan —
44
+ * the shape that made the old adapter report `periodIso: "P1W"` and a
45
+ * `pricePerYear` of about $3,130 for a $59.99/year plan.
46
+ */
47
+ const playYearly = {
48
+ id: "pro_yearly",
49
+ type: "subs",
50
+ title: "Pro Yearly",
51
+ description: "Best value",
52
+ displayPrice: "$59.99",
53
+ price: 59.99,
54
+ currency: "USD",
55
+ subscriptionOffers: [
56
+ {
57
+ id: "free-trial",
58
+ basePlanIdAndroid: "annual",
59
+ offerTokenAndroid: "tok-annual-trial",
60
+ pricingPhasesAndroid: {
61
+ pricingPhaseList: [
62
+ // recurrenceMode 2 = FINITE_RECURRING (the trial), 1 = INFINITE_RECURRING
63
+ { billingPeriod: "P1W", priceAmountMicros: "0", formattedPrice: "Free", recurrenceMode: 2 },
64
+ {
65
+ billingPeriod: "P1Y",
66
+ priceAmountMicros: "59990000",
67
+ formattedPrice: "$59.99",
68
+ recurrenceMode: 1,
69
+ },
70
+ ],
71
+ },
72
+ },
73
+ {
74
+ id: "monthly-base",
75
+ basePlanIdAndroid: "monthly",
76
+ offerTokenAndroid: "tok-monthly",
77
+ pricingPhasesAndroid: {
78
+ pricingPhaseList: [
79
+ {
80
+ billingPeriod: "P1M",
81
+ priceAmountMicros: "9990000",
82
+ formattedPrice: "$9.99",
83
+ recurrenceMode: 1,
84
+ },
85
+ ],
86
+ },
87
+ },
88
+ ],
89
+ };
90
+
91
+ const platform = () => rn.Platform.OS;
92
+ /** Let the store's setTimeout(0) deliveries land. */
93
+ const settle = () => new Promise((r) => setTimeout(r, 5));
94
+
95
+ beforeEach(() => {
96
+ rn.Platform.OS = "ios";
97
+ vi.restoreAllMocks();
98
+ });
99
+
100
+ describe("expoIapProductProvider — the payload expo-iap 5.x accepts", () => {
101
+ it("completes an iOS purchase instead of throwing EmptySkuList", async () => {
102
+ // #241 finding 1. `request: { ios, android }` reaches neither branch of
103
+ // normalizeRequestProps, so 5.x rejects before the store is ever asked and
104
+ // the user's Buy tap can only ever produce onError.
105
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
106
+ const provider = expoIapProductProvider(M);
107
+ const [product] = await provider.getProducts([YEARLY_IOS]);
108
+ expect(await provider.purchase(product)).toEqual({
109
+ status: "purchased",
110
+ productKey: "yearly",
111
+ });
112
+ });
113
+
114
+ it("completes an Android purchase", async () => {
115
+ rn.Platform.OS = "android";
116
+ const M = makeExpoIap5({ catalog: [playYearly], platform });
117
+ const provider = expoIapProductProvider(M);
118
+ const [product] = await provider.getProducts([YEARLY_PLAY]);
119
+ expect(await provider.purchase(product)).toEqual({
120
+ status: "purchased",
121
+ productKey: "yearly",
122
+ });
123
+ });
124
+
125
+ it("sends apple/google and never the removed ios/android keys", async () => {
126
+ // 4.x accepted `request.ios` with a deprecation warning; 5.0 deleted the
127
+ // shim. One shape works on both, so there is nothing to version-probe.
128
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
129
+ const provider = expoIapProductProvider(M);
130
+ const [product] = await provider.getProducts([YEARLY_IOS]);
131
+ await provider.purchase(product);
132
+ const { request, type } = M.calls.requestPurchase[0];
133
+ expect(request.apple).toEqual({ sku: "pro_yearly" });
134
+ expect(request.google.skus).toEqual(["pro_yearly"]);
135
+ expect(request).not.toHaveProperty("ios");
136
+ expect(request).not.toHaveProperty("android");
137
+ expect(type).toBe("subs");
138
+ });
139
+
140
+ it("labels a compound-period subscription subs, not in-app", async () => {
141
+ // `toPeriod` rejects "P1Y1M", so a `period`-based discriminator called a
142
+ // real subscription in-app and Play would reject the purchase outright.
143
+ const M = makeExpoIap5({
144
+ catalog: [{ ...iosYearly, type: undefined, subscriptionPeriodISO: "P1Y1M" }],
145
+ platform,
146
+ });
147
+ const provider = expoIapProductProvider(M);
148
+ const [product] = await provider.getProducts([YEARLY_IOS]);
149
+ expect(product.period).toBeNull(); // unparseable by design
150
+ await provider.purchase(product);
151
+ expect(M.calls.requestPurchase[0].type).toBe("subs");
152
+ });
153
+ });
154
+
155
+ describe("expoIapProductProvider — a purchase gets finished", () => {
156
+ it("finishes the transaction the store delivers through the listener", async () => {
157
+ // #241 finding 2. `requestPurchase` resolves null on the normal path, so
158
+ // the old adapter returned "pending" and finished nothing: iOS re-delivers
159
+ // the transaction on every launch and Play auto-refunds it after 3 days.
160
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
161
+ const provider = expoIapProductProvider(M);
162
+ const [product] = await provider.getProducts([YEARLY_IOS]);
163
+ const result = await provider.purchase(product);
164
+ expect(result).toEqual({ status: "purchased", productKey: "yearly" });
165
+ expect(M.calls.finishTransaction).toHaveLength(1);
166
+ expect(M.calls.finishTransaction[0].purchase).toMatchObject({
167
+ id: "tx-pro_yearly-1",
168
+ productId: "pro_yearly",
169
+ });
170
+ });
171
+
172
+ it("consumes a consumable rather than acknowledging it", async () => {
173
+ // An acknowledged Android consumable can never be re-bought. Only iOS
174
+ // publishes the discriminator (`typeIOS`), which is why this asserts the
175
+ // flag rather than the platform call.
176
+ const M = makeExpoIap5({
177
+ catalog: [{ ...iosLifetime, typeIOS: "consumable" }],
178
+ platform,
179
+ });
180
+ const provider = expoIapProductProvider(M);
181
+ const [product] = await provider.getProducts([LIFETIME_IOS]);
182
+ await provider.purchase(product);
183
+ expect(M.calls.finishTransaction[0].isConsumable).toBe(true);
184
+ });
185
+
186
+ it("acknowledges a non-consumable", async () => {
187
+ const M = makeExpoIap5({ catalog: [iosLifetime], platform });
188
+ const provider = expoIapProductProvider(M);
189
+ const [product] = await provider.getProducts([LIFETIME_IOS]);
190
+ await provider.purchase(product);
191
+ expect(M.calls.finishTransaction[0].isConsumable).toBe(false);
192
+ });
193
+
194
+ it("finishes a pending purchase once it clears, having answered pending first", async () => {
195
+ // Play emits `purchaseState: "pending"` and then "purchased" for the SAME
196
+ // transaction. Not finishing the pending one is right — Android has no
197
+ // purchaseToken yet — but making it TERMINAL for the whole call meant a
198
+ // purchase that did clear was never acknowledged, so Play refunded it.
199
+ rn.Platform.OS = "android";
200
+ const M = makeExpoIap5({
201
+ catalog: [playYearly],
202
+ platform,
203
+ onDispatch: (sku) => ({ id: "tx-1", productId: sku, purchaseState: "pending" }),
204
+ });
205
+ const provider = expoIapProductProvider(M);
206
+ const [product] = await provider.getProducts([YEARLY_PLAY]);
207
+
208
+ expect(await provider.purchase(product)).toEqual({ status: "pending" });
209
+ expect(M.calls.finishTransaction).toHaveLength(0);
210
+
211
+ // …and now the payment clears, after the caller has already been answered.
212
+ M.emitUpdated({ id: "tx-1", productId: "pro_yearly", purchaseState: "purchased" });
213
+ await settle();
214
+ expect(M.calls.finishTransaction).toHaveLength(1);
215
+ expect(M.calls.finishTransaction[0].purchase.id).toBe("tx-1");
216
+ });
217
+
218
+ it("finishes a verdict that arrives after the caller timed out", async () => {
219
+ // 180s is routinely exceeded by Ask to Buy, an SCA step-up, or adding a
220
+ // card inside the sheet. Removing the listeners at the timeout meant the
221
+ // verdict landed on nothing and the charge was never acknowledged.
222
+ const M = makeExpoIap5({ catalog: [iosYearly], platform, onDispatch: () => null });
223
+ const provider = expoIapProductProvider(M, { purchaseTimeoutMs: 10 });
224
+ const [product] = await provider.getProducts([YEARLY_IOS]);
225
+
226
+ expect(await provider.purchase(product)).toEqual({ status: "pending" });
227
+ expect(M.calls.finishTransaction).toHaveLength(0);
228
+
229
+ M.emitUpdated({ id: "tx-late", productId: "pro_yearly", purchaseState: "purchased" });
230
+ await settle();
231
+ expect(M.calls.finishTransaction).toHaveLength(1);
232
+ expect(M.calls.finishTransaction[0].purchase.id).toBe("tx-late");
233
+ });
234
+
235
+ it("still reports purchased when finishing throws, and retries it later", async () => {
236
+ // A finish failure must not turn a completed purchase into an error — but
237
+ // Play's 3-day window is still running, so it must not be forgotten either.
238
+ let broken = true;
239
+ const M = makeExpoIap5({ catalog: [iosYearly, iosLifetime], platform, finishFails: () => broken });
240
+ const provider = expoIapProductProvider(M);
241
+ const [yearly] = await provider.getProducts([YEARLY_IOS]);
242
+ expect(await provider.purchase(yearly)).toEqual({ status: "purchased", productKey: "yearly" });
243
+ expect(M.calls.finishTransaction).toHaveLength(1);
244
+
245
+ broken = false;
246
+ const [lifetime] = await provider.getProducts([LIFETIME_IOS]);
247
+ await provider.purchase(lifetime);
248
+ // The yearly transaction was retried on the next store round-trip.
249
+ const retried = M.calls.finishTransaction.filter(
250
+ (c: any) => c.purchase.id === "tx-pro_yearly-1"
251
+ );
252
+ expect(retried.length).toBeGreaterThan(1);
253
+ });
254
+
255
+ it("never finishes one transaction twice", async () => {
256
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
257
+ const provider = expoIapProductProvider(M);
258
+ const [product] = await provider.getProducts([YEARLY_IOS]);
259
+ await provider.purchase(product);
260
+ // A replay of the same transaction, e.g. from a buffered Android event.
261
+ M.emitUpdated({ id: "tx-pro_yearly-1", productId: "pro_yearly", purchaseState: "purchased" });
262
+ await settle();
263
+ expect(M.calls.finishTransaction).toHaveLength(1);
264
+ });
265
+
266
+ it("applies the sku check to a directly returned transaction too", async () => {
267
+ // iOS sometimes resolves the transaction from `requestPurchase` itself. The
268
+ // listener path filters by product; this path used to skip that check, so a
269
+ // replayed transaction handed back inline could answer the wrong purchase.
270
+ const M = makeExpoIap5({ catalog: [iosYearly], platform, onDispatch: () => null });
271
+ (M as any).requestPurchase = async () => ({
272
+ id: "tx-someone-else",
273
+ productId: "a_different_product",
274
+ purchaseState: "purchased",
275
+ });
276
+ const provider = expoIapProductProvider(M, { purchaseTimeoutMs: 10 });
277
+ const [product] = await provider.getProducts([YEARLY_IOS]);
278
+ expect(await provider.purchase(product)).toEqual({ status: "pending" });
279
+ expect(M.calls.finishTransaction).toHaveLength(0);
280
+ });
281
+
282
+ it("ignores a transaction for a different product", async () => {
283
+ const M = makeExpoIap5({
284
+ catalog: [iosYearly, iosLifetime],
285
+ platform,
286
+ onDispatch: () => null,
287
+ });
288
+ const provider = expoIapProductProvider(M);
289
+ const products = await provider.getProducts([YEARLY_IOS, LIFETIME_IOS]);
290
+ const pending = provider.purchase(products[0]);
291
+ setTimeout(() => M.emitUpdated({ id: "tx-old", productId: "some_other_product" }), 0);
292
+ setTimeout(() => M.emitUpdated({ id: "tx-new", productId: "pro_yearly" }), 5);
293
+ expect(await pending).toEqual({ status: "purchased", productKey: "yearly" });
294
+ expect(M.calls.finishTransaction).toHaveLength(1);
295
+ expect(M.calls.finishTransaction[0].purchase.id).toBe("tx-new");
296
+ });
297
+ });
298
+
299
+ describe("expoIapProductProvider — cancellation is not an error", () => {
300
+ it("maps the 5.x kebab-case code delivered through the error listener", async () => {
301
+ // 5.x normalized every code to openiap kebab-case (types.js:41) and dropped
302
+ // the `userCancelled` boolean, so dismissing the StoreKit sheet fired
303
+ // onError on a paywall.
304
+ const M = makeExpoIap5({
305
+ catalog: [iosYearly],
306
+ platform,
307
+ onDispatch: (sku) => ({ error: { code: "user-cancelled", message: "cancelled", productId: sku } }),
308
+ });
309
+ const provider = expoIapProductProvider(M);
310
+ const [product] = await provider.getProducts([YEARLY_IOS]);
311
+ expect(await provider.purchase(product)).toEqual({ status: "cancelled" });
312
+ });
313
+
314
+ it("maps a thrown kebab-case cancellation too", async () => {
315
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
316
+ (M as any).requestPurchase = async () => {
317
+ throw Object.assign(new Error("cancelled"), { code: "user-cancelled" });
318
+ };
319
+ const provider = expoIapProductProvider(M);
320
+ const [product] = await provider.getProducts([YEARLY_IOS]);
321
+ expect(await provider.purchase(product)).toEqual({ status: "cancelled" });
322
+ });
323
+
324
+ it("still maps the pre-5.x codes", async () => {
325
+ const M = makeExpoIap5({
326
+ catalog: [iosYearly],
327
+ platform,
328
+ onDispatch: (sku) => ({ error: { code: "E_USER_CANCELLED", productId: sku } }),
329
+ });
330
+ const provider = expoIapProductProvider(M);
331
+ const [product] = await provider.getProducts([YEARLY_IOS]);
332
+ expect(await provider.purchase(product)).toEqual({ status: "cancelled" });
333
+ });
334
+
335
+ it("reports a real store failure as an error, keeping the store's diagnosis", async () => {
336
+ // The listener delivers the PLAIN `{ code, message }` PurchaseError from
337
+ // types.d.ts:1164, not the Error subclass `requestPurchase` rejects with.
338
+ // `new Error(String(obj))` would hand the host "[object Object]".
339
+ const M = makeExpoIap5({
340
+ catalog: [iosYearly],
341
+ platform,
342
+ onDispatch: (sku) => ({ error: { code: "network-error", message: "offline", productId: sku } }),
343
+ });
344
+ const provider = expoIapProductProvider(M);
345
+ const [product] = await provider.getProducts([YEARLY_IOS]);
346
+ const result = await provider.purchase(product);
347
+ expect(result.status).toBe("error");
348
+ expect((result as any).error.message).toContain("offline");
349
+ expect((result as any).error.code).toBe("network-error");
350
+ });
351
+ });
352
+
353
+ describe("expoIapProductProvider — a store failure belongs to one product", () => {
354
+ it("does not let another product's error answer this purchase", async () => {
355
+ // `purchaseErrorListener` is process-wide and expo-iap forwards the event
356
+ // verbatim (build/index.js:195-200); on Android the module emits from one
357
+ // listener per module and FLUSHES events buffered while disconnected on the
358
+ // next initConnection (ExpoIapModule.kt:198-205). Claiming unconditionally
359
+ // meant a stale or unrelated failure answered this call, after which the
360
+ // real transaction arrived to a caller already told "error" — and was never
361
+ // finished.
362
+ const M = makeExpoIap5({ catalog: [iosYearly], platform, onDispatch: () => null });
363
+ const provider = expoIapProductProvider(M);
364
+ const [product] = await provider.getProducts([YEARLY_IOS]);
365
+
366
+ const inFlight = provider.purchase(product);
367
+ setTimeout(
368
+ () => M.emitError({ code: "item-unavailable", message: "nope", productId: "some_other_product" }),
369
+ 0
370
+ );
371
+ setTimeout(() => M.emitUpdated({ id: "tx-1", productId: "pro_yearly", purchaseState: "purchased" }), 5);
372
+
373
+ expect(await inFlight).toEqual({ status: "purchased", productKey: "yearly" });
374
+ expect(M.calls.finishTransaction).toHaveLength(1);
375
+ });
376
+
377
+ it("attributes an error that names no product when only one purchase is in flight", async () => {
378
+ // Native fallbacks do not always fill productId, and with a single purchase
379
+ // open there is no ambiguity to protect against.
380
+ const M = makeExpoIap5({
381
+ catalog: [iosYearly],
382
+ platform,
383
+ onDispatch: () => ({ error: { code: "billing-unavailable", message: "no billing" } }),
384
+ });
385
+ const provider = expoIapProductProvider(M);
386
+ const [product] = await provider.getProducts([YEARLY_IOS]);
387
+ const result = await provider.purchase(product);
388
+ expect(result.status).toBe("error");
389
+ });
390
+
391
+ it("matches an error that names the sku in productIds", async () => {
392
+ const M = makeExpoIap5({
393
+ catalog: [iosYearly],
394
+ platform,
395
+ onDispatch: (sku) => ({ error: { code: "network-error", message: "x", productIds: [sku] } }),
396
+ });
397
+ const provider = expoIapProductProvider(M);
398
+ const [product] = await provider.getProducts([YEARLY_IOS]);
399
+ expect((await provider.purchase(product)).status).toBe("error");
400
+ });
401
+ });
402
+
403
+ describe("expoIapProductProvider — the purchase is dispatched exactly once", () => {
404
+ it("does not re-present the store sheet when the dispatch rejects", async () => {
405
+ // Android reports one failure both as a `purchase-error` event and as a
406
+ // rejection, and `service-disconnected` is the CATCH-ALL rejection code for
407
+ // any non-OpenIapError failure (ExpoIapModule.kt:60-61) — including one
408
+ // raised from inside the billing flow, since `reachedOpenIapRequest` is set
409
+ // before `openIap.requestPurchase` (:435-436) and
410
+ // `deliverPurchaseRequestFailure` rejects on every path (:63-75). Retrying
411
+ // it can show a SECOND sheet and charge a consumable twice.
412
+ const M = makeExpoIap5({
413
+ catalog: [iosYearly],
414
+ platform,
415
+ onDispatch: (sku) => ({ error: { code: "service-disconnected", message: "billing died", productId: sku } }),
416
+ });
417
+ const base = M.requestPurchase.bind(M);
418
+ (M as any).requestPurchase = async (args: any) => {
419
+ await base(args);
420
+ throw Object.assign(new Error("Play disconnected"), { code: "service-disconnected" });
421
+ };
422
+ const provider = expoIapProductProvider(M);
423
+ const [product] = await provider.getProducts([YEARLY_IOS]);
424
+ const result = await provider.purchase(product);
425
+ expect(result.status).toBe("error");
426
+ expect(M.calls.requestPurchase).toHaveLength(1);
427
+ });
428
+
429
+ it("still reconnects and retries a READ that hits the same code", async () => {
430
+ // The retry is worth having; it is only the money path that must not have it.
431
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
432
+ const provider = expoIapProductProvider(M);
433
+ await provider.getProducts([YEARLY_IOS]);
434
+ M.dropConnection();
435
+ await expect(provider.getProducts([YEARLY_IOS])).resolves.toHaveLength(1);
436
+ expect(M.calls.initConnection).toBe(2);
437
+ });
438
+ });
439
+
440
+ describe("expoIapProductProvider — listener lifetime", () => {
441
+ it("subscribes once for the provider's life, however many purchases", async () => {
442
+ // Per-Buy-tap subscription is not merely wasteful: each new
443
+ // purchaseUpdatedListener seeds its dedupe history from a PROCESS-WIDE set
444
+ // of transaction ids (build/index.js:148-151), so a listener attached later
445
+ // silently drops anything another listener in the process — the host's own
446
+ // useIAP, for instance — has already seen.
447
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
448
+ const provider = expoIapProductProvider(M);
449
+ const [product] = await provider.getProducts([YEARLY_IOS]);
450
+ await provider.purchase(product);
451
+ await provider.purchase(product);
452
+ await provider.purchase(product);
453
+ expect(M.calls.updatedSubscribes).toBe(1);
454
+ });
455
+
456
+ it("hears a transaction that arrives before any purchase call", async () => {
457
+ // The launch-replay case (#257), and the reason to subscribe on connect
458
+ // rather than on Buy: with no listener attached there is nothing to hear,
459
+ // and one attached afterwards inherits a history that hides it.
460
+ const seen: any[] = [];
461
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
462
+ const provider = expoIapProductProvider(M, {
463
+ onUnclaimedPurchase: (p) => {
464
+ seen.push(p);
465
+ return false;
466
+ },
467
+ });
468
+ await provider.getProducts([YEARLY_IOS]); // opens the connection
469
+ M.emitUpdated({ id: "tx-replayed", productId: "pro_yearly", purchaseState: "purchased" });
470
+ await settle();
471
+ expect(seen.map((p) => p.id)).toEqual(["tx-replayed"]);
472
+ });
473
+
474
+ it("releases the subscriptions on dispose", async () => {
475
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
476
+ const provider = expoIapProductProvider(M);
477
+ await provider.getProducts([YEARLY_IOS]);
478
+ expect(M.calls.liveListeners).toBe(2);
479
+ provider.dispose();
480
+ expect(M.calls.liveListeners).toBe(0);
481
+ });
482
+ });
483
+
484
+ describe("expoIapProductProvider — a transaction nobody asked for", () => {
485
+ it("is left unfinished, and says so, when the host has no handler", async () => {
486
+ // Finishing it blind would take the money and grant nothing, destroying the
487
+ // replay that lets the app recover. Leaving it alone means iOS offers it
488
+ // again next launch.
489
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
490
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
491
+ const provider = expoIapProductProvider(M);
492
+ await provider.getProducts([YEARLY_IOS]);
493
+ M.emitUpdated({ id: "tx-replayed", productId: "pro_yearly", purchaseState: "purchased" });
494
+ await settle();
495
+ expect(M.calls.finishTransaction).toHaveLength(0);
496
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("nobody is waiting for"));
497
+ });
498
+
499
+ it("is finished once the host says entitlement was granted", async () => {
500
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
501
+ const provider = expoIapProductProvider(M, { onUnclaimedPurchase: async () => true });
502
+ await provider.getProducts([YEARLY_IOS]);
503
+ M.emitUpdated({ id: "tx-replayed", productId: "pro_yearly", purchaseState: "purchased" });
504
+ await settle();
505
+ expect(M.calls.finishTransaction).toHaveLength(1);
506
+ expect(M.calls.finishTransaction[0].purchase.id).toBe("tx-replayed");
507
+ });
508
+
509
+ it("is left alone when the host declines it", async () => {
510
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
511
+ const provider = expoIapProductProvider(M, { onUnclaimedPurchase: () => false });
512
+ await provider.getProducts([YEARLY_IOS]);
513
+ M.emitUpdated({ id: "tx-replayed", productId: "pro_yearly", purchaseState: "purchased" });
514
+ await settle();
515
+ expect(M.calls.finishTransaction).toHaveLength(0);
516
+ });
517
+
518
+ it("does not route a purchase this process dispatched to the host", async () => {
519
+ // The caller was told about it, so acknowledging it needs no second opinion.
520
+ const unclaimed = vi.fn().mockReturnValue(true);
521
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
522
+ const provider = expoIapProductProvider(M, { onUnclaimedPurchase: unclaimed });
523
+ const [product] = await provider.getProducts([YEARLY_IOS]);
524
+ await provider.purchase(product);
525
+ expect(unclaimed).not.toHaveBeenCalled();
526
+ expect(M.calls.finishTransaction).toHaveLength(1);
527
+ });
528
+ });
529
+
530
+ describe("expoIapProductProvider — Android base plans", () => {
531
+ beforeEach(() => {
532
+ rn.Platform.OS = "android";
533
+ });
534
+
535
+ it("queries the bare product id, not productId:basePlanId", async () => {
536
+ // fetchProducts filters on `item.id` (index.js:471-477), so the authored
537
+ // "pro_yearly:annual" matched nothing: a blank Android paywall reporting
538
+ // status "ready".
539
+ const M = makeExpoIap5({ catalog: [playYearly], platform });
540
+ const products = await expoIapProductProvider(M).getProducts([YEARLY_PLAY]);
541
+ expect(M.calls.fetchProducts[0].skus).toEqual(["pro_yearly"]);
542
+ expect(products).toHaveLength(1);
543
+ expect(products[0].productId).toBe("pro_yearly");
544
+ });
545
+
546
+ it("sends the base plan's offer token so Play can select it", async () => {
547
+ // Play Billing needs an offerToken to know WHICH base plan is being bought;
548
+ // 5.x forwards `subscriptionOffers` straight through (index.js:806-819).
549
+ const M = makeExpoIap5({ catalog: [playYearly], platform });
550
+ const provider = expoIapProductProvider(M);
551
+ const [product] = await provider.getProducts([YEARLY_PLAY]);
552
+ await provider.purchase(product);
553
+ expect(M.calls.requestPurchase[0].request.google.subscriptionOffers).toEqual([
554
+ { sku: "pro_yearly", offerToken: "tok-annual-trial" },
555
+ ]);
556
+ });
557
+
558
+ it("takes the period from the recurring phase, not the free trial", async () => {
559
+ // pricingPhaseList[0] is the trial when one exists, so a $59.99/year plan
560
+ // with a 1-week trial reported "P1W" — and pricePerYear near $3,130.
561
+ const M = makeExpoIap5({ catalog: [playYearly], platform });
562
+ const [product] = await expoIapProductProvider(M).getProducts([YEARLY_PLAY]);
563
+ expect(product.periodIso).toBe("P1Y");
564
+ expect(product.period).toBe("year");
565
+ expect(product.periodCount).toBe(1);
566
+ });
567
+
568
+ it("reads the base plan named by the ref, not merely the first offer", async () => {
569
+ const M = makeExpoIap5({ catalog: [playYearly], platform });
570
+ const [product] = await expoIapProductProvider(M).getProducts([
571
+ { key: "monthly", android: "pro_yearly:monthly" },
572
+ ]);
573
+ expect(product.periodIso).toBe("P1M");
574
+ });
575
+ });
576
+
577
+ describe("expoIapProductProvider — restore", () => {
578
+ it("returns product ids and skips unpaid purchases", async () => {
579
+ // `Purchase.id` is the TRANSACTION id and is always set, so `p.id ??
580
+ // p.productId` never fell through — restore handed the host transaction
581
+ // ids. And `getAvailablePurchases` includes unfinished purchases, so an
582
+ // Android slow payment entitled before the money moved.
583
+ const M = makeExpoIap5({
584
+ platform,
585
+ purchases: [
586
+ { id: "tx-1", productId: "pro_yearly", purchaseState: "purchased" },
587
+ { id: "tx-2", productId: "pro_pending", purchaseState: "pending" },
588
+ { id: "tx-3", productId: "pro_yearly", purchaseState: "purchased" },
589
+ ],
590
+ });
591
+ expect(await expoIapProductProvider(M).restore()).toEqual({
592
+ status: "restored",
593
+ entitlements: ["pro_yearly"],
594
+ });
595
+ });
596
+
597
+ it("syncs with StoreKit before reading, behind a user-facing Restore button", async () => {
598
+ // `restorePurchases()` does the iOS sync and then refreshes, but returns
599
+ // nothing itself — "consumers should call getAvailablePurchases"
600
+ // (build/index.js:886-899). Reading without the sync can miss purchases
601
+ // made on another device.
602
+ const M = makeExpoIap5({
603
+ platform,
604
+ purchases: [{ id: "tx-1", productId: "pro_yearly", purchaseState: "purchased" }],
605
+ });
606
+ await expoIapProductProvider(M).restore();
607
+ expect(M.calls.restorePurchases).toBe(1);
608
+ });
609
+
610
+ it("reports nothing_to_restore when every purchase is unpaid", async () => {
611
+ const M = makeExpoIap5({
612
+ platform,
613
+ purchases: [{ id: "tx-2", productId: "pro_pending", purchaseState: "pending" }],
614
+ });
615
+ expect(await expoIapProductProvider(M).restore()).toEqual({ status: "nothing_to_restore" });
616
+ });
617
+ });
618
+
619
+ describe("expoIapProductProvider — a catalog that did not resolve", () => {
620
+ it("fails rather than reporting an empty catalog as ready", async () => {
621
+ // FetchProductsResult includes `null` (types.d.ts:527). Coercing it to []
622
+ // put the runtime in `status: "ready"` with every {{product.*}} empty.
623
+ const M = makeExpoIap5({ catalog: [iosYearly], platform, fetchProductsResult: null });
624
+ await expect(expoIapProductProvider(M).getProducts([YEARLY_IOS])).rejects.toThrow(
625
+ /did not return a product list/i
626
+ );
627
+ });
628
+
629
+ it("warns by name when a ref resolves to nothing", async () => {
630
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
631
+ const M = makeExpoIap5({ catalog: [iosYearly], platform });
632
+ const products = await expoIapProductProvider(M).getProducts([YEARLY_IOS, LIFETIME_IOS]);
633
+ expect(products).toHaveLength(1);
634
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("pro_lifetime"));
635
+ });
636
+
637
+ it("keeps earlier products purchasable after a second resolve", async () => {
638
+ // `rawById.clear()` on every getProducts wiped the offer tokens and type
639
+ // discriminators of the first set, so purchasing from it fell back to
640
+ // guesswork.
641
+ const M = makeExpoIap5({ catalog: [iosYearly, iosLifetime], platform });
642
+ const provider = expoIapProductProvider(M);
643
+ const [yearly] = await provider.getProducts([YEARLY_IOS]);
644
+ await provider.getProducts([LIFETIME_IOS]);
645
+ await provider.purchase(yearly);
646
+ expect(M.calls.requestPurchase[0].type).toBe("subs");
647
+ });
648
+ });