@rocapine/react-native-onboarding 1.69.0 → 1.70.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 (49) hide show
  1. package/dist/OnboardingStudioClient.d.ts +4 -4
  2. package/dist/OnboardingStudioClient.js +7 -7
  3. package/dist/OnboardingStudioClient.js.map +1 -1
  4. package/dist/paywalls/PaywallProvider.d.ts +24 -7
  5. package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
  6. package/dist/paywalls/PaywallProvider.js +80 -42
  7. package/dist/paywalls/PaywallProvider.js.map +1 -1
  8. package/dist/paywalls/present.d.ts +60 -14
  9. package/dist/paywalls/present.d.ts.map +1 -1
  10. package/dist/paywalls/present.js +67 -18
  11. package/dist/paywalls/present.js.map +1 -1
  12. package/dist/paywalls/types.d.ts +48 -23
  13. package/dist/paywalls/types.d.ts.map +1 -1
  14. package/dist/paywalls/types.js +0 -7
  15. package/dist/paywalls/types.js.map +1 -1
  16. package/dist/paywalls/usePaywall.d.ts +5 -5
  17. package/dist/paywalls/usePaywall.d.ts.map +1 -1
  18. package/dist/products/adapters/stripeLink.d.ts +57 -0
  19. package/dist/products/adapters/stripeLink.d.ts.map +1 -0
  20. package/dist/products/adapters/stripeLink.js +158 -0
  21. package/dist/products/adapters/stripeLink.js.map +1 -0
  22. package/dist/products/index.d.ts +4 -1
  23. package/dist/products/index.d.ts.map +1 -1
  24. package/dist/products/index.js +5 -1
  25. package/dist/products/index.js.map +1 -1
  26. package/dist/products/refIdentity.d.ts +3 -0
  27. package/dist/products/refIdentity.d.ts.map +1 -0
  28. package/dist/products/refIdentity.js +37 -0
  29. package/dist/products/refIdentity.js.map +1 -0
  30. package/dist/products/types.d.ts +29 -1
  31. package/dist/products/types.d.ts.map +1 -1
  32. package/dist/products/useProducts.d.ts.map +1 -1
  33. package/dist/products/useProducts.js +7 -1
  34. package/dist/products/useProducts.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/OnboardingStudioClient.ts +7 -7
  37. package/src/paywalls/PaywallProvider.tsx +109 -46
  38. package/src/paywalls/__tests__/getPaywalls.test.ts +15 -12
  39. package/src/paywalls/__tests__/present.test.ts +149 -28
  40. package/src/paywalls/present.ts +74 -21
  41. package/src/paywalls/types.ts +49 -23
  42. package/src/paywalls/usePaywall.ts +5 -5
  43. package/src/products/__tests__/refIdentity.test.ts +44 -0
  44. package/src/products/adapters/__tests__/stripeLink.test.ts +179 -0
  45. package/src/products/adapters/stripeLink.ts +245 -0
  46. package/src/products/index.ts +4 -0
  47. package/src/products/refIdentity.ts +33 -0
  48. package/src/products/types.ts +30 -1
  49. package/src/products/useProducts.ts +7 -4
@@ -1,23 +1,46 @@
1
+ import type { StripeProductRef } from "../products/types";
2
+
1
3
  /**
2
4
  * Response types for `OnboardingStudioClient.getPaywalls()` (spec §6.1). The
3
- * endpoint returns every placement for the project/audience/locale in one
5
+ * endpoint returns every moment for the project/audience/locale in one
4
6
  * payload — a paywall must render the instant the user taps upgrade, and a
5
7
  * network round-trip at that moment is a conversion bug, so there is no
6
- * per-placement fetch in the common path (see `PaywallOptions.placement`).
8
+ * per-moment fetch in the common path (see `PaywallOptions.moment`).
7
9
  */
8
10
 
9
- /** A single studio-authored paywall, keyed by `placement` in `PaywallCatalog.paywalls`. */
11
+ /**
12
+ * A single studio-authored paywall, keyed by `moment` in `PaywallCatalog.paywalls`.
13
+ *
14
+ * `audienceId`/`audienceName` are resolved PER MOMENT, not once for the whole
15
+ * catalog: each moment (an onboarding-end upsell, a settings-screen upgrade,
16
+ * …) runs its own independent audience waterfall, so two entries in the same
17
+ * catalog can legitimately have matched different audiences. That is why
18
+ * these fields live here and not on `PaywallCatalog.metadata`.
19
+ */
10
20
  export type Paywall = {
11
21
  id: string;
12
22
  name: string;
13
- placement: string;
23
+ moment: string;
24
+ audienceId: number | null;
25
+ audienceName: string | null;
14
26
  /** UIElement[] — parsed by the UI adapter (Task 7's `ScreenElementsSchema`), not here. */
15
27
  elements: unknown[];
28
+ /**
29
+ * Which billing path this paywall's buy actions take. `"store"` uses the
30
+ * host's store adapter (`PaywallProvider`'s `productProvider`); `"stripe"`
31
+ * uses `PaywallProvider`'s `stripeProductProvider` and opens a Payment Link.
32
+ *
33
+ * A property of the PAYWALL, not the moment or the project, so one moment
34
+ * audience can weight a `store` variant against a `stripe` variant and ramp
35
+ * the billing change as an A/B test.
36
+ */
37
+ billing: "store" | "stripe";
16
38
  products: Array<{
17
39
  key: string;
18
40
  ios?: string;
19
41
  android?: string;
20
42
  compareTo?: string;
43
+ stripe?: StripeProductRef;
21
44
  }>;
22
45
  configuration: Record<string, unknown> | null;
23
46
  };
@@ -25,12 +48,10 @@ export type Paywall = {
25
48
  /** Full response body of `GET get-paywalls`. */
26
49
  export type PaywallCatalog = {
27
50
  metadata: {
28
- audienceId: number | null;
29
- audienceName: string | null;
30
51
  locale: string | null;
31
52
  draft: boolean;
32
53
  };
33
- /** Keyed by placement, not by paywall id. */
54
+ /** Keyed by moment, not by paywall id. */
34
55
  paywalls: Record<string, Paywall>;
35
56
  fonts: Record<string, unknown> | null;
36
57
  };
@@ -38,14 +59,14 @@ export type PaywallCatalog = {
38
59
  /**
39
60
  * Options for `OnboardingStudioClient.getPaywalls()`.
40
61
  *
41
- * `placement` narrows the response to a single paywall — the exception, not
42
- * the default. Omit it to get every placement in one round-trip, which is
62
+ * `moment` narrows the response to a single paywall — the exception, not
63
+ * the default. Omit it to get every moment in one round-trip, which is
43
64
  * what lets a paywall render instantly at buy-tap time (see the module doc
44
65
  * above).
45
66
  */
46
67
  export type PaywallOptions = {
47
68
  locale?: string;
48
- placement?: string;
69
+ moment?: string;
49
70
  };
50
71
 
51
72
  /**
@@ -53,22 +74,27 @@ export type PaywallOptions = {
53
74
  * trio (`ONBS-Onboarding-Id` / `ONBS-Audience-Id` / `ONBS-Onboarding-Name`) —
54
75
  * the paywall endpoint has no single onboarding/audience-name concept and
55
76
  * instead reports which paywall ids came back.
77
+ *
78
+ * `ONBS-Audience-Ids` is plural (comma-separated) and parallel in order to
79
+ * `ONBS-Paywall-Ids`: each moment resolves its own audience waterfall (see
80
+ * `Paywall.audienceId`), so there is no single catalog-level audience left
81
+ * to report under a singular header.
56
82
  */
57
83
  export interface GetPaywallsResponseHeaders {
58
- "ONBS-Audience-Id": string | null;
84
+ "ONBS-Audience-Ids": string | null;
59
85
  "ONBS-Paywall-Ids": string | null;
60
86
  }
61
87
 
62
88
  /**
63
- * Resolved outcome of a `usePaywall().present(placement)` call (spec §7).
89
+ * Resolved outcome of a `usePaywall().present(moment)` call (spec §7).
64
90
  * Closed union, not the open-ended `ScreenHost.CompleteOutcome` — a
65
91
  * presentation ends in exactly one of these four ways, and `present()`'s
66
92
  * caller (typically an `await`) should be able to switch over it exhaustively.
67
93
  *
68
- * `"error"` covers both: (a) `placement` is absent from the catalog (or the
94
+ * `"error"` covers both: (a) `moment` is absent from the catalog (or the
69
95
  * catalog hasn't resolved yet), and (b) `present()` was called while another
70
96
  * paywall is already being presented. Both resolve rather than throw — a
71
- * missing placement or a mistimed call must not crash a host app mid-flow.
97
+ * missing moment or a mistimed call must not crash a host app mid-flow.
72
98
  * See `resolvePresentDecision` in `present.ts` for the exact decision logic.
73
99
  *
74
100
  * `"purchased"` / `"cancelled"` are NOT produced by any ButtonAction directly
@@ -99,18 +125,18 @@ export interface GetPaywallsResponseHeaders {
99
125
  * absent on every other status.
100
126
  *
101
127
  * This exists because `"error"` alone conflates conditions whose correct
102
- * recovery is OPPOSITE. `"unknown-placement"` means the catalog may simply not
128
+ * recovery is OPPOSITE. `"unknown-moment"` means the catalog may simply not
103
129
  * have arrived yet, so retrying later is right. `"already-presenting"` means a
104
130
  * presentation is in progress, so retrying is wrong and something may be
105
131
  * stuck. A caller given only the status can act correctly on neither, and two
106
132
  * separate multi-hour production investigations were spent reconstructing by
107
133
  * elimination what the SDK already knew here.
108
134
  *
109
- * - `unknown-placement` — absent from the catalog, or the catalog has not
135
+ * - `unknown-moment` — absent from the catalog, or the catalog has not
110
136
  * resolved yet. The two are indistinguishable at this layer, and both are
111
137
  * worth retrying once `usePaywall().isReady` is true.
112
- * - `already-presenting` — one paywall shows at a time. `activePlacement` on
113
- * the result names the one that IS showing: the same placement means the
138
+ * - `already-presenting` — one paywall shows at a time. `activeMoment` on
139
+ * the result names the one that IS showing: the same moment means the
114
140
  * caller double-called and wants its own in-flight guard, a different one
115
141
  * means something else holds the surface.
116
142
  * - `parse-error` — `elements` failed the UI schema, so the Modal was never
@@ -125,11 +151,11 @@ export interface GetPaywallsResponseHeaders {
125
151
  * keep the surface usable. In practice the platform refused to present
126
152
  * (iOS will not present over an already-presenting view controller — another
127
153
  * Modal, a `presentation: "modal"` route, a StoreKit alert).
128
- * - `paywall-disappeared` — the placement vanished from the catalog while it
154
+ * - `paywall-disappeared` — the moment vanished from the catalog while it
129
155
  * was on screen (a studio publish, or a query-key change mid-presentation).
130
156
  */
131
157
  export type PresentErrorReason =
132
- | "unknown-placement"
158
+ | "unknown-moment"
133
159
  | "already-presenting"
134
160
  | "parse-error"
135
161
  | "render-error"
@@ -141,9 +167,9 @@ export type PresentResult = {
141
167
  /** Why it failed. Set on `"error"` only — see `PresentErrorReason`. */
142
168
  reason?: PresentErrorReason;
143
169
  /**
144
- * The placement currently being presented. Set only alongside
145
- * `reason: "already-presenting"`, where knowing WHICH placement holds the
170
+ * The moment currently being presented. Set only alongside
171
+ * `reason: "already-presenting"`, where knowing WHICH moment holds the
146
172
  * surface is what distinguishes a caller double-call from an unrelated stall.
147
173
  */
148
- activePlacement?: string;
174
+ activeMoment?: string;
149
175
  };
@@ -6,27 +6,27 @@ import type { ProductStatus } from "../products/types";
6
6
 
7
7
  export type UsePaywallResult = {
8
8
  /**
9
- * Present a paywall by placement. Never fetches — the catalog and its
9
+ * Present a paywall by moment. Never fetches — the catalog and its
10
10
  * products are already resolved (or resolving) from `PaywallProvider`
11
11
  * mount, which is the whole point: a paywall must render the instant the
12
12
  * user taps upgrade.
13
13
  *
14
- * Resolves `{ status: "error" }` — never throws — when `placement` is
14
+ * Resolves `{ status: "error" }` — never throws — when `moment` is
15
15
  * absent from the catalog, or when another paywall is already being
16
16
  * presented. See `resolvePresentDecision` in `present.ts`.
17
17
  */
18
- present: (placement: string) => Promise<PresentResult>;
18
+ present: (moment: string) => Promise<PresentResult>;
19
19
  /**
20
20
  * `true` once BOTH the catalog and its products have resolved — the one
21
21
  * flag meaning "calling `present()` now will not show a spinner".
22
22
  */
23
23
  isReady: boolean;
24
- /** The full resolved catalog (every placement), or `null` before it loads. */
24
+ /** The full resolved catalog (every moment), or `null` before it loads. */
25
25
  catalog: PaywallCatalog | null;
26
26
  /**
27
27
  * What the catalog is doing, for hosts that need more than `isReady`'s one
28
28
  * bit. `"revalidating"` is the important one: the catalog on hand was served
29
- * from disk and a fresh fetch is in flight, so a placement missing from it may
29
+ * from disk and a fresh fetch is in flight, so a moment missing from it may
30
30
  * simply not have arrived yet. Gate "fall back to another engine" on
31
31
  * `"ready"`, not merely on a non-null catalog.
32
32
  */
@@ -0,0 +1,44 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { productRefIdentity } from "../refIdentity";
3
+ import type { ProductRef } from "../types";
4
+
5
+ const STRIPE = {
6
+ paymentLink: "https://buy.stripe.com/test_a",
7
+ amount: 79,
8
+ currency: "USD",
9
+ } as const;
10
+
11
+ describe("productRefIdentity", () => {
12
+ it("distinguishes two refs that differ ONLY in their stripe block", () => {
13
+ const a: ProductRef = { key: "yearly", stripe: { ...STRIPE } };
14
+ const b: ProductRef = { key: "yearly", stripe: { ...STRIPE, paymentLink: "https://buy.stripe.com/test_b" } };
15
+ expect(productRefIdentity(a)).not.toBe(productRefIdentity(b));
16
+ });
17
+
18
+ it("distinguishes a store-only ref from the same key with a stripe block", () => {
19
+ expect(productRefIdentity({ key: "yearly", ios: "y_ios" })).not.toBe(
20
+ productRefIdentity({ key: "yearly", ios: "y_ios", stripe: { ...STRIPE } }),
21
+ );
22
+ });
23
+
24
+ it("is stable for two structurally equal refs", () => {
25
+ expect(productRefIdentity({ key: "yearly", ios: "y_ios", stripe: { ...STRIPE } })).toBe(
26
+ productRefIdentity({ key: "yearly", ios: "y_ios", stripe: { ...STRIPE } }),
27
+ );
28
+ });
29
+
30
+ it("still separates the pre-existing store fields", () => {
31
+ expect(productRefIdentity({ key: "k", ios: "a" })).not.toBe(productRefIdentity({ key: "k", ios: "b" }));
32
+ expect(productRefIdentity({ key: "k", android: "a" })).not.toBe(productRefIdentity({ key: "k", android: "b" }));
33
+ expect(productRefIdentity({ key: "k", compareTo: "a" })).not.toBe(
34
+ productRefIdentity({ key: "k", compareTo: "b" }),
35
+ );
36
+ });
37
+
38
+ it("does not collide across field boundaries", () => {
39
+ // "a|b" split across two fields must not equal "a|b" in one.
40
+ expect(productRefIdentity({ key: "k", ios: "a", android: "b" })).not.toBe(
41
+ productRefIdentity({ key: "k", ios: "a|b" }),
42
+ );
43
+ });
44
+ });
@@ -0,0 +1,179 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { stripeLinkProductProvider } from "../stripeLink";
3
+ import type { ProductRef } from "../../types";
4
+
5
+ const YEARLY: ProductRef = {
6
+ key: "yearly",
7
+ ios: "pro_yearly_ios",
8
+ stripe: {
9
+ paymentLink: "https://buy.stripe.com/test_yearly",
10
+ priceId: "price_123",
11
+ amount: 79,
12
+ currency: "USD",
13
+ periodIso: "P1Y",
14
+ trialDays: 7,
15
+ },
16
+ };
17
+
18
+ const STORE_ONLY: ProductRef = { key: "monthly", ios: "pro_monthly_ios" };
19
+
20
+ const harness = (over: Partial<Parameters<typeof stripeLinkProductProvider>[0]> = {}) => {
21
+ const opened: string[] = [];
22
+ const provider = stripeLinkProductProvider({
23
+ clientReferenceId: () => "rc_user_1",
24
+ openUrl: (url) => void opened.push(url),
25
+ ...over,
26
+ });
27
+ return { provider, opened };
28
+ };
29
+
30
+ describe("stripeLinkProductProvider.getProducts", () => {
31
+ it("synthesises a ResolvedProduct from the ref, with no network call", async () => {
32
+ const { provider } = harness();
33
+ const [p] = await provider.getProducts([YEARLY]);
34
+ expect(p.key).toBe("yearly");
35
+ expect(p.store).toBe("stripe");
36
+ expect(p.productId).toBe("price_123");
37
+ expect(p.priceAmount).toBe(79);
38
+ expect(p.currencyCode).toBe("USD");
39
+ expect(p.periodIso).toBe("P1Y");
40
+ expect(p.period).toBe("year");
41
+ expect(p.periodCount).toBe(1);
42
+ expect(p.trial).toEqual({ period: "week", periodCount: 1, days: 7 });
43
+ });
44
+
45
+ it("formats price in the product's currency", async () => {
46
+ const { provider } = harness();
47
+ const [p] = await provider.getProducts([YEARLY]);
48
+ // Exact glyph placement is Intl's business; assert the part we control.
49
+ expect(p.price).toContain("79");
50
+ });
51
+
52
+ it("falls back to the payment link as productId when priceId is absent", async () => {
53
+ const { provider } = harness();
54
+ const ref: ProductRef = { key: "k", stripe: { paymentLink: "https://buy.stripe.com/x", amount: 1, currency: "USD" } };
55
+ const [p] = await provider.getProducts([ref]);
56
+ expect(p.productId).toBe("https://buy.stripe.com/x");
57
+ });
58
+
59
+ it("drops refs with no stripe block, exactly as the store adapters drop refs with no platform id", async () => {
60
+ const { provider } = harness();
61
+ expect(await provider.getProducts([STORE_ONLY])).toEqual([]);
62
+ expect((await provider.getProducts([YEARLY, STORE_ONLY])).map((p) => p.key)).toEqual(["yearly"]);
63
+ });
64
+
65
+ it("omits trial when trialDays is absent or zero", async () => {
66
+ const { provider } = harness();
67
+ const [p] = await provider.getProducts([
68
+ { key: "k", stripe: { paymentLink: "https://buy.stripe.com/x", amount: 1, currency: "USD", trialDays: 0 } },
69
+ ]);
70
+ expect(p.trial).toBeUndefined();
71
+ });
72
+ });
73
+
74
+ describe("stripeLinkProductProvider.purchase", () => {
75
+ it("opens the link with client_reference_id and resolves pending", async () => {
76
+ const { provider, opened } = harness();
77
+ const [p] = await provider.getProducts([YEARLY]);
78
+ const result = await provider.purchase(p);
79
+ expect(result).toEqual({ status: "pending" });
80
+ expect(opened).toHaveLength(1);
81
+ const url = new URL(opened[0]);
82
+ expect(url.origin + url.pathname).toBe("https://buy.stripe.com/test_yearly");
83
+ expect(url.searchParams.get("client_reference_id")).toBe("rc_user_1");
84
+ });
85
+
86
+ it("adds prefilled_email when configured", async () => {
87
+ const { provider, opened } = harness({ prefilledEmail: () => "a@b.com" });
88
+ const [p] = await provider.getProducts([YEARLY]);
89
+ await provider.purchase(p);
90
+ expect(new URL(opened[0]).searchParams.get("prefilled_email")).toBe("a@b.com");
91
+ });
92
+
93
+ it("refuses (fails closed) rather than open the link with no client_reference_id", async () => {
94
+ const { provider, opened } = harness({ clientReferenceId: () => null });
95
+ const [p] = await provider.getProducts([YEARLY]);
96
+ const result = await provider.purchase(p);
97
+ expect(result.status).toBe("error");
98
+ // The whole point: nothing opens, so no money moves for a purchase
99
+ // RevenueCat could never attribute.
100
+ expect(opened).toHaveLength(0);
101
+ });
102
+
103
+ it("also refuses for an undefined or empty-string client_reference_id", async () => {
104
+ for (const value of [undefined, ""]) {
105
+ const { provider, opened } = harness({ clientReferenceId: () => value });
106
+ const [p] = await provider.getProducts([YEARLY]);
107
+ const result = await provider.purchase(p);
108
+ expect(result.status).toBe("error");
109
+ expect(opened).toHaveLength(0);
110
+ }
111
+ });
112
+
113
+ it("allowAnonymous: true opens the link anyway, omitting client_reference_id", async () => {
114
+ const { provider, opened } = harness({ clientReferenceId: () => null, allowAnonymous: true });
115
+ const [p] = await provider.getProducts([YEARLY]);
116
+ const result = await provider.purchase(p);
117
+ expect(result).toEqual({ status: "pending" });
118
+ expect(opened).toHaveLength(1);
119
+ // Still omitted rather than sent as the literal string "null" —
120
+ // `allowAnonymous` opts into opening the link, not into a bad param.
121
+ expect(new URL(opened[0]).searchParams.has("client_reference_id")).toBe(false);
122
+ });
123
+
124
+ it("preserves query parameters already on the payment link", async () => {
125
+ const { provider, opened } = harness();
126
+ const [p] = await provider.getProducts([
127
+ { key: "k", stripe: { paymentLink: "https://buy.stripe.com/x?locale=fr", amount: 1, currency: "USD" } },
128
+ ]);
129
+ await provider.purchase(p);
130
+ const url = new URL(opened[0]);
131
+ expect(url.searchParams.get("locale")).toBe("fr");
132
+ expect(url.searchParams.get("client_reference_id")).toBe("rc_user_1");
133
+ });
134
+
135
+ it("errors for a product it never resolved, instead of opening nothing silently", async () => {
136
+ const { provider, opened } = harness();
137
+ const result = await provider.purchase({
138
+ key: "ghost", productId: "x", store: "stripe", title: "", description: "",
139
+ price: "", priceAmount: 0, currencyCode: "USD", period: null, periodCount: 0, periodIso: null,
140
+ });
141
+ expect(result.status).toBe("error");
142
+ expect(opened).toHaveLength(0);
143
+ });
144
+
145
+ it("resolves status: error (never rejects) for a malformed payment link", async () => {
146
+ const { provider, opened } = harness();
147
+ const [p] = await provider.getProducts([
148
+ { key: "k", stripe: { paymentLink: "not a url", amount: 1, currency: "USD" } },
149
+ ]);
150
+ const result = await provider.purchase(p);
151
+ expect(result.status).toBe("error");
152
+ expect(opened).toHaveLength(0);
153
+ });
154
+
155
+ it("does not serve a stale link once a key's stripe block is dropped from the catalog", async () => {
156
+ const { provider, opened } = harness();
157
+ const ref: ProductRef = { key: "k", stripe: { paymentLink: "https://buy.stripe.com/x", amount: 1, currency: "USD" } };
158
+ const [p] = await provider.getProducts([ref]);
159
+ // Re-authored off Stripe billing: the same key, now with no stripe block.
160
+ await provider.getProducts([{ key: "k" }]);
161
+ const result = await provider.purchase(p);
162
+ expect(result.status).toBe("error");
163
+ expect(opened).toHaveLength(0);
164
+ });
165
+ });
166
+
167
+ describe("stripeLinkProductProvider.restore", () => {
168
+ it("errors by default rather than reporting nothing_to_restore", async () => {
169
+ const { provider } = harness();
170
+ const result = await provider.restore();
171
+ // `nothing_to_restore` would make a Restore button silently do nothing.
172
+ expect(result.status).toBe("error");
173
+ });
174
+
175
+ it("delegates when the host supplies a restore implementation", async () => {
176
+ const { provider } = harness({ restore: async () => ({ status: "restored", entitlements: ["pro"] }) });
177
+ expect(await provider.restore()).toEqual({ status: "restored", entitlements: ["pro"] });
178
+ });
179
+ });
@@ -0,0 +1,245 @@
1
+ import { formatCurrency } from "../derive";
2
+ import type {
3
+ ProductPeriod,
4
+ ProductProvider,
5
+ ProductRef,
6
+ ResolvedProduct,
7
+ RestoreResult,
8
+ } from "../types";
9
+
10
+ /**
11
+ * Stripe Payment Link provider.
12
+ *
13
+ * Deliberately NOT a store adapter. It makes no network call and holds no
14
+ * Stripe key: the price is authored in Onboarding Studio and travels inline on
15
+ * the `ProductRef` (`ProductRef.stripe`), so `getProducts` is a synchronous
16
+ * synthesis and `purchase` is a link-out.
17
+ *
18
+ * What it does NOT do, on purpose:
19
+ * - grant or verify anything. `purchase()` resolves `{ status: "pending" }`
20
+ * because the browser leaves the app — on web the JS context is destroyed.
21
+ * The entitlement arrives later through RevenueCat's Stripe integration,
22
+ * which is why `clientReferenceId` MUST return the RevenueCat App User ID:
23
+ * it is the key RevenueCat's webhook matches on, and the only thing tying
24
+ * the payment to the user. Return the wrong id and the money is taken with
25
+ * no entitlement granted. An ABSENT id (null/undefined/empty) is handled
26
+ * differently: `purchase()` refuses before opening anything, unless
27
+ * `allowAnonymous` opts in — see `StripeLinkProviderConfig.allowAnonymous`.
28
+ * - import `react-native` at module scope, so this file is safe to load on
29
+ * web. URL opening is injected (`openUrl`) for the same reason, and so the
30
+ * provider is testable under Node.
31
+ */
32
+ export type StripeLinkProviderConfig = {
33
+ /**
34
+ * The RevenueCat App User ID, as a getter — it changes on login/logout, and
35
+ * a value captured at provider construction would go stale.
36
+ */
37
+ clientReferenceId: () => string | null | undefined;
38
+ /** Optional email prefill for the Checkout page. */
39
+ prefilledEmail?: () => string | null | undefined;
40
+ /**
41
+ * How to leave the app. Defaults to `react-native`'s `Linking.openURL`,
42
+ * required lazily so this module stays importable where react-native is not.
43
+ */
44
+ openUrl?: (url: string) => void | Promise<void>;
45
+ /**
46
+ * Restoring is a store-account operation Stripe links cannot perform. Supply
47
+ * the host's real implementation (usually the RevenueCat adapter's
48
+ * `restore`) to make a Restore button work on a Stripe paywall.
49
+ */
50
+ restore?: ProductProvider["restore"];
51
+ /** Passed to `Intl.NumberFormat` when formatting the authored price. */
52
+ locale?: string;
53
+ /**
54
+ * Opt-in for checkout with no `clientReferenceId()`. Default `false`:
55
+ * `purchase()` refuses (fails closed) rather than open a Payment Link it
56
+ * cannot attribute to a RevenueCat user, because a payment that opens
57
+ * anyway is taken with NO way to grant the entitlement afterwards — see
58
+ * `purchase()` below. Set `true` only if you genuinely want anonymous
59
+ * checkout; entitlements from those purchases cannot be attributed
60
+ * automatically and must be reconciled out of band.
61
+ */
62
+ allowAnonymous?: boolean;
63
+ };
64
+
65
+ const PERIOD_FROM_UNIT: Record<string, ProductPeriod> = {
66
+ D: "week",
67
+ W: "week",
68
+ M: "month",
69
+ Y: "year",
70
+ };
71
+
72
+ /** Same shape the store adapters parse, for one consistent notion of period. */
73
+ const toPeriod = (iso: string | null | undefined): { period: ProductPeriod | null; count: number } => {
74
+ if (!iso) return { period: null, count: 0 };
75
+ const m = /^P(\d+)([DWMY])$/.exec(iso);
76
+ if (!m) return { period: null, count: 0 };
77
+ return { period: PERIOD_FROM_UNIT[m[2]] ?? null, count: Number(m[1]) };
78
+ };
79
+
80
+ const lazyLinking = (url: string): void | Promise<void> => {
81
+ // Required lazily and defensively: this provider's whole point is running on
82
+ // web, where react-native may be absent entirely.
83
+ try {
84
+ const RN = require("react-native");
85
+ return RN.Linking.openURL(url);
86
+ } catch {
87
+ if (typeof globalThis !== "undefined" && (globalThis as any).location) {
88
+ (globalThis as any).location.assign(url);
89
+ return;
90
+ }
91
+ throw new Error(
92
+ "stripeLinkProductProvider: no way to open a URL. Pass `openUrl` in the provider config.",
93
+ );
94
+ }
95
+ };
96
+
97
+ const withParams = (
98
+ link: string,
99
+ params: Record<string, string | null | undefined>,
100
+ ): string => {
101
+ // Parsed rather than string-concatenated so a link that already carries
102
+ // query parameters (`?locale=fr`) keeps them and does not gain a second `?`.
103
+ const url = new URL(link);
104
+ for (const [name, value] of Object.entries(params)) {
105
+ // Omit rather than emit — Stripe would receive the literal string "null".
106
+ if (value === null || value === undefined || value === "") continue;
107
+ url.searchParams.set(name, value);
108
+ }
109
+ return url.toString();
110
+ };
111
+
112
+ export const stripeLinkProductProvider = (config: StripeLinkProviderConfig): ProductProvider => {
113
+ const { clientReferenceId, prefilledEmail, openUrl = lazyLinking, restore, locale, allowAnonymous = false } =
114
+ config;
115
+
116
+ // `ResolvedProduct` has no field for the payment link and widening it would
117
+ // put a Stripe concern on every store product, so the link is remembered
118
+ // here, populated by `getProducts` — the same call that produced the
119
+ // `ResolvedProduct` `purchase` is later handed.
120
+ const linkByKey = new Map<string, string>();
121
+
122
+ return {
123
+ async getProducts(refs: ProductRef[]): Promise<ResolvedProduct[]> {
124
+ // Cleared, not merged: this call's `refs` is the full current catalog, so
125
+ // it defines the resolvable set on its own. A key that carried a stripe
126
+ // block last call but not this one (re-authored off Stripe billing) must
127
+ // stop resolving — an accumulating map would keep `purchase()` opening
128
+ // that stale link indefinitely instead of taking the "no link" error path.
129
+ linkByKey.clear();
130
+ const out: ResolvedProduct[] = [];
131
+ for (const ref of refs) {
132
+ const s = ref.stripe;
133
+ // A ref with no stripe block is not an error — the catalog union spans
134
+ // every paywall, including `billing: "store"` ones. Dropping it is the
135
+ // same contract the store adapters have for a missing platform id.
136
+ if (!s || !s.paymentLink) continue;
137
+ linkByKey.set(ref.key, s.paymentLink);
138
+ const { period, count } = toPeriod(s.periodIso);
139
+ const trialDays = s.trialDays ?? 0;
140
+ out.push({
141
+ key: ref.key,
142
+ productId: s.priceId ?? s.paymentLink,
143
+ store: "stripe",
144
+ title: "",
145
+ description: "",
146
+ price: formatCurrency(s.amount, s.currency, locale),
147
+ priceAmount: s.amount,
148
+ currencyCode: s.currency,
149
+ period,
150
+ periodCount: count,
151
+ periodIso: s.periodIso ?? null,
152
+ // Expressed in days, which is what `deriveProductFields` reads via
153
+ // `trial.days`; the period/count pair is filled in consistently so
154
+ // nothing downstream sees a half-populated trial.
155
+ ...(trialDays > 0
156
+ ? {
157
+ trial: {
158
+ period: "week" as ProductPeriod,
159
+ periodCount: Math.max(1, Math.round(trialDays / 7)),
160
+ days: trialDays,
161
+ },
162
+ }
163
+ : {}),
164
+ });
165
+ }
166
+ return out;
167
+ },
168
+
169
+ async purchase(product) {
170
+ const link = linkByKey.get(product.key);
171
+ if (!link) {
172
+ return {
173
+ status: "error",
174
+ error: new Error(
175
+ `stripeLinkProductProvider: no payment link for "${product.key}". ` +
176
+ "getProducts() never resolved this key, so the ref carries no `stripe.paymentLink`.",
177
+ ),
178
+ };
179
+ }
180
+ // Resolved and checked BEFORE the link opens — once it opens, the
181
+ // browser has left the app and the payment cannot be stopped. A
182
+ // null/undefined/empty id is not exotic: a getter wired to
183
+ // RevenueCat's `appUserID` before `Purchases.configure()` resolves, or
184
+ // read while the user is logged out, returns null. Without this check
185
+ // the link would still open, `purchase()` would still resolve
186
+ // "pending", the user would pay, and RevenueCat would have nothing to
187
+ // match the payment to — nothing fails loudly at any layer. See this
188
+ // file's top comment: "Return the wrong id and the money is taken with
189
+ // no entitlement granted" — this is that, for the ABSENT case.
190
+ const refId = clientReferenceId();
191
+ const hasRefId = refId !== null && refId !== undefined && refId !== "";
192
+ if (!hasRefId && !allowAnonymous) {
193
+ return {
194
+ status: "error",
195
+ error: new Error(
196
+ "stripeLinkProductProvider: clientReferenceId() returned no id — refusing to open the " +
197
+ "Payment Link. Opening it anyway would take payment with no way to attribute the " +
198
+ "entitlement RevenueCat grants afterwards. Wire `clientReferenceId` to the RevenueCat App " +
199
+ "User ID and make sure it resolves AFTER `Purchases.configure()` completes (reading it " +
200
+ "before configure() finishes, or while the user is logged out, is what returns null). " +
201
+ "Pass `allowAnonymous: true` in the provider config if anonymous checkout — with no " +
202
+ "automatic entitlement attribution — is genuinely what you want.",
203
+ ),
204
+ };
205
+ }
206
+ // `withParams` throws synchronously on a malformed link (`new URL`) —
207
+ // a plausible failure mode for an author-pasted Stripe URL. That throw
208
+ // happens before any `await`, so left unguarded it would make
209
+ // `purchase()` return a REJECTED promise instead of the resolved
210
+ // `{ status: "error", error }` every other failure path in this file
211
+ // uses. Callers awaiting `purchase()` should only ever see it resolve.
212
+ try {
213
+ await openUrl(
214
+ withParams(link, {
215
+ client_reference_id: refId,
216
+ prefilled_email: prefilledEmail?.(),
217
+ }),
218
+ );
219
+ } catch (e) {
220
+ // Always renamed to name the offending link — a bare `Invalid URL`
221
+ // (what `new URL` throws) gives an author nothing to act on.
222
+ const reason = e instanceof Error ? e.message : String(e);
223
+ return {
224
+ status: "error",
225
+ error: new Error(`stripeLinkProductProvider: failed to open payment link "${link}": ${reason}`),
226
+ };
227
+ }
228
+ // Never "purchased": the browser has taken over and, on web, this JS
229
+ // context is about to be destroyed. RevenueCat reports the entitlement.
230
+ return { status: "pending" };
231
+ },
232
+
233
+ async restore(): Promise<RestoreResult> {
234
+ if (restore) return restore();
235
+ return {
236
+ status: "error",
237
+ error: new Error(
238
+ "stripeLinkProductProvider: restore is not configured. A Stripe Payment Link cannot " +
239
+ "enumerate past purchases; pass `restore` (usually your RevenueCat adapter's) in the " +
240
+ "provider config so a Restore button does something.",
241
+ ),
242
+ };
243
+ },
244
+ };
245
+ };