@rocapine/react-native-onboarding 1.77.0 → 1.78.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.
- package/README.md +24 -6
- package/dist/OnboardingStudio.d.ts +14 -1
- package/dist/OnboardingStudio.d.ts.map +1 -1
- package/dist/OnboardingStudio.js +5 -1
- package/dist/OnboardingStudio.js.map +1 -1
- package/dist/OnboardingStudioClient.d.ts +29 -0
- package/dist/OnboardingStudioClient.d.ts.map +1 -1
- package/dist/OnboardingStudioClient.js +76 -19
- package/dist/OnboardingStudioClient.js.map +1 -1
- package/dist/assignmentId.d.ts +107 -0
- package/dist/assignmentId.d.ts.map +1 -0
- package/dist/assignmentId.js +215 -0
- package/dist/assignmentId.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/paywalls/customScreens.d.ts +7 -0
- package/dist/paywalls/customScreens.d.ts.map +1 -1
- package/dist/paywalls/observer.d.ts +2 -0
- package/dist/paywalls/observer.d.ts.map +1 -1
- package/dist/paywalls/observer.js +21 -9
- package/dist/paywalls/observer.js.map +1 -1
- package/dist/paywalls/types.d.ts +22 -0
- package/dist/paywalls/types.d.ts.map +1 -1
- package/dist/products/adapters/expoIap.d.ts +34 -13
- package/dist/products/adapters/expoIap.d.ts.map +1 -1
- package/dist/products/adapters/expoIap.js +136 -21
- package/dist/products/adapters/expoIap.js.map +1 -1
- package/dist/types.d.ts +47 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -1
- package/dist/userProperties/reserved.d.ts +3 -2
- package/dist/userProperties/reserved.d.ts.map +1 -1
- package/dist/userProperties/reserved.js +3 -1
- package/dist/userProperties/reserved.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/src/OnboardingStudio.ts +19 -1
- package/src/OnboardingStudioClient.ts +79 -31
- package/src/__tests__/assignmentId.clear.test.ts +413 -0
- package/src/__tests__/assignmentId.client.test.ts +288 -0
- package/src/__tests__/assignmentId.test.ts +195 -0
- package/src/__tests__/onboardingMetadata.client.test.ts +76 -0
- package/src/assignmentId.ts +278 -0
- package/src/index.ts +1 -0
- package/src/paywalls/__tests__/PaywallProvider.observer.test.tsx +51 -0
- package/src/paywalls/__tests__/getPaywalls.test.ts +77 -2
- package/src/paywalls/__tests__/observer.test.ts +37 -0
- package/src/paywalls/__tests__/present.test.ts +14 -0
- package/src/paywalls/customScreens.ts +7 -0
- package/src/paywalls/observer.ts +22 -2
- package/src/paywalls/types.ts +22 -0
- package/src/products/adapters/__tests__/expoIap.contract.test.ts +305 -0
- package/src/products/adapters/expoIap.ts +171 -32
- package/src/types.ts +48 -0
- package/src/userProperties/__tests__/primitives.test.ts +1 -1
- package/src/userProperties/reserved.ts +3 -1
- package/src/version.ts +1 -1
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `assignmentId`: the stable per-person value every `getSteps` / `getPaywalls`
|
|
5
|
+
* request carries, so the server can put the same person in the same variant
|
|
6
|
+
* every time (it hashes this value with the id of the group being split).
|
|
7
|
+
* The SDK's only job is to send the same value every time for the same person.
|
|
8
|
+
*
|
|
9
|
+
* Resolution, per request:
|
|
10
|
+
* 1. the host's `assignmentId` option (a string, or a getter called on every
|
|
11
|
+
* request — e.g. `() => Purchases.getAppUserID()`),
|
|
12
|
+
* 2. else an installation id, generated once and persisted under
|
|
13
|
+
* `ASSIGNMENT_ID_STORAGE_KEY`,
|
|
14
|
+
* 3. else nothing: the `X-Assignment-Id` header is not sent rather than
|
|
15
|
+
* carrying an invented id, so the server can tell "no stable id" from "a
|
|
16
|
+
* fresh id it will never see again".
|
|
17
|
+
*
|
|
18
|
+
* `false` (as the option, or returned by the getter) OPTS OUT: nothing is sent
|
|
19
|
+
* and the installation id is never read, created or written — e.g. until the
|
|
20
|
+
* user consents. `null` / `""` are not an opt-out; they fall through to 2.
|
|
21
|
+
*
|
|
22
|
+
* A host value of `undefined`, `null` or `""` falls through to the installation
|
|
23
|
+
* id. A getter that throws, rejects, or does not settle within
|
|
24
|
+
* `HOST_ASSIGNMENT_ID_TIMEOUT_MS` FAILS CLOSED: the id is omitted for that
|
|
25
|
+
* request and the installation id is not read, created or written. A getter
|
|
26
|
+
* that cannot answer may be one that would have answered `false` (no consent
|
|
27
|
+
* yet), so it must never be overridden by the stored id.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** `false` opts out; `null` / `undefined` / `""` mean "no host value". */
|
|
31
|
+
export type AssignmentIdValue = string | false | null | undefined;
|
|
32
|
+
|
|
33
|
+
/** The `OnboardingStudioClientOptions.assignmentId` option. */
|
|
34
|
+
export type AssignmentIdOption =
|
|
35
|
+
| AssignmentIdValue
|
|
36
|
+
| (() => AssignmentIdValue | Promise<AssignmentIdValue>);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Deliberately NOT under the `rocapine-onboarding` / `rocapine-paywalls`
|
|
40
|
+
* prefixes `OnboardingStudioClient.clearCache` scans, and not the user
|
|
41
|
+
* property key `OnboardingStudio.reset()` removes: clearing a payload cache or
|
|
42
|
+
* logging out must not move the install to another variant.
|
|
43
|
+
*/
|
|
44
|
+
export const ASSIGNMENT_ID_STORAGE_KEY = "rocapine-assignment-id";
|
|
45
|
+
|
|
46
|
+
/** How long a host getter may take before the installation id is used instead. */
|
|
47
|
+
export const HOST_ASSIGNMENT_ID_TIMEOUT_MS = 2000;
|
|
48
|
+
|
|
49
|
+
export type AssignmentIdStorage = {
|
|
50
|
+
getItem: (key: string) => Promise<string | null>;
|
|
51
|
+
setItem: (key: string, value: string) => Promise<void>;
|
|
52
|
+
removeItem: (key: string) => Promise<void>;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const nonEmpty = (v: unknown): string | undefined =>
|
|
56
|
+
typeof v === "string" && v.trim() !== "" ? v.trim() : undefined;
|
|
57
|
+
|
|
58
|
+
/** RFC 4122 v4. `crypto.randomUUID` when present; Hermes may not have it. */
|
|
59
|
+
const generateUuidV4 = (): string => {
|
|
60
|
+
const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
|
|
61
|
+
if (typeof c?.randomUUID === "function") return c.randomUUID();
|
|
62
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => {
|
|
63
|
+
const r = (Math.random() * 16) | 0;
|
|
64
|
+
return (ch === "x" ? r : (r & 0x3) | 0x8).toString(16);
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Bound on how long a CALLER waits for each queued operation. The queue itself
|
|
70
|
+
* still waits for the real storage call, so ordering holds even when it hangs.
|
|
71
|
+
*/
|
|
72
|
+
export const STORAGE_OP_TIMEOUT_MS = HOST_ASSIGNMENT_ID_TIMEOUT_MS;
|
|
73
|
+
|
|
74
|
+
export type InstallationIdStore = {
|
|
75
|
+
/**
|
|
76
|
+
* The current clear() generation. Take it BEFORE any await that precedes
|
|
77
|
+
* `get(token)` (e.g. a host getter), so a `clear()` in between is seen.
|
|
78
|
+
*/
|
|
79
|
+
token: () => number;
|
|
80
|
+
/**
|
|
81
|
+
* The installation id, or `undefined`. With a `token` older than the last
|
|
82
|
+
* `clear()`, returns `undefined` without reading or writing storage.
|
|
83
|
+
*/
|
|
84
|
+
get: (token?: number) => Promise<string | undefined>;
|
|
85
|
+
/**
|
|
86
|
+
* Removes the stored id and forgets the in-memory one, so a later request
|
|
87
|
+
* mints a new id. Rejects if the removal fails or the caller's wait for it
|
|
88
|
+
* exceeds `STORAGE_OP_TIMEOUT_MS` (the removal itself still runs, in order).
|
|
89
|
+
*/
|
|
90
|
+
clear: () => Promise<void>;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* One in-flight resolution per store, so `getSteps` and `getPaywalls` fired
|
|
95
|
+
* together on a first launch share one generated id and write it once. A
|
|
96
|
+
* failure is not memoized: the next request retries.
|
|
97
|
+
*
|
|
98
|
+
* `clear()` must win against a load already in flight, or the id it removes
|
|
99
|
+
* comes back. Two mechanisms:
|
|
100
|
+
* - every storage operation runs on ONE queue, so a removal is ordered after
|
|
101
|
+
* any write already started, and a load started after `clear()` runs after
|
|
102
|
+
* the removal (and is therefore never deleted by it);
|
|
103
|
+
* - an `epoch` bumped by `clear()`: a load that began before it neither writes
|
|
104
|
+
* nor returns an id, so the request in flight sends nothing. Callers that
|
|
105
|
+
* await something first (`resolveAssignmentId` awaits the host getter) take
|
|
106
|
+
* the epoch as a `token()` up front and pass it to `get(token)`.
|
|
107
|
+
*
|
|
108
|
+
* The caller's wait on each queued operation is bounded by
|
|
109
|
+
* `STORAGE_OP_TIMEOUT_MS`, counted from when it was queued. On expiry the
|
|
110
|
+
* caller's promise rejects (`clear()` rejects; `get()` fails closed with
|
|
111
|
+
* `undefined`). A write or removal still holds the queue until the real call
|
|
112
|
+
* settles, so a removal can never overtake a write in flight; callers behind a
|
|
113
|
+
* hung write or removal fail closed at their own bound. A load abandoned BEFORE
|
|
114
|
+
* it issued `setItem` releases the queue at once, since it can no longer write:
|
|
115
|
+
* a hung read does not stall the rest of the process.
|
|
116
|
+
*
|
|
117
|
+
* A timed-out load is marked abandoned, and checks that right before minting
|
|
118
|
+
* and right before writing: a timed-out request never mints. (A write that had
|
|
119
|
+
* already started when the bound fired cannot be recalled; it lands, in order,
|
|
120
|
+
* ahead of any later removal.)
|
|
121
|
+
*/
|
|
122
|
+
export const createInstallationIdStore = (
|
|
123
|
+
storage: AssignmentIdStorage,
|
|
124
|
+
generate: () => string = generateUuidV4,
|
|
125
|
+
): InstallationIdStore => {
|
|
126
|
+
let pending: Promise<string | undefined> | null = null;
|
|
127
|
+
let epoch = 0;
|
|
128
|
+
let queue: Promise<unknown> = Promise.resolve();
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Runs `op` after every earlier operation has settled; the returned promise
|
|
132
|
+
* only bounds how long the caller waits. When the caller gives up,
|
|
133
|
+
* `onTimeout` runs, and if it returns `true` the queue is released at once:
|
|
134
|
+
* the op promises it will issue no further storage writes, so a later
|
|
135
|
+
* operation may safely start while it is still pending. Otherwise the queue
|
|
136
|
+
* keeps waiting for the real call (a write or removal must stay ordered).
|
|
137
|
+
*/
|
|
138
|
+
const enqueue = <T>(op: () => Promise<T>, onTimeout?: () => boolean): Promise<T> => {
|
|
139
|
+
const real = queue.then(op);
|
|
140
|
+
let release!: () => void;
|
|
141
|
+
const released = new Promise<void>((resolve) => {
|
|
142
|
+
release = resolve;
|
|
143
|
+
});
|
|
144
|
+
queue = Promise.race([real.catch(() => {}), released]);
|
|
145
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
146
|
+
return Promise.race([
|
|
147
|
+
real,
|
|
148
|
+
new Promise<never>((_, reject) => {
|
|
149
|
+
timer = setTimeout(() => {
|
|
150
|
+
if (onTimeout?.()) release();
|
|
151
|
+
reject(new Error(`[assignment-id] storage operation timed out after ${STORAGE_OP_TIMEOUT_MS}ms`));
|
|
152
|
+
}, STORAGE_OP_TIMEOUT_MS);
|
|
153
|
+
}),
|
|
154
|
+
]).finally(() => clearTimeout(timer));
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
/** `writing` flips, synchronously, the moment the load issues `setItem`. */
|
|
158
|
+
type LoadState = { abandoned: boolean; writing: boolean };
|
|
159
|
+
|
|
160
|
+
const load = async (startedAt: number, state: LoadState): Promise<string | undefined> => {
|
|
161
|
+
let stored: string | null;
|
|
162
|
+
try {
|
|
163
|
+
stored = await storage.getItem(ASSIGNMENT_ID_STORAGE_KEY);
|
|
164
|
+
} catch (error) {
|
|
165
|
+
// An unreadable key may still hold an id: generating now could overwrite it.
|
|
166
|
+
console.warn("[assignment-id] Failed to read the installation id; omitting it:", error);
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
if (epoch !== startedAt) return undefined; // cleared meanwhile: do not mint
|
|
170
|
+
const existing = nonEmpty(stored);
|
|
171
|
+
if (existing) return existing;
|
|
172
|
+
// The caller timed out: never mint (and so never write). Nothing async lies
|
|
173
|
+
// between here and `setItem`, so this is also the last check before it.
|
|
174
|
+
if (state.abandoned) return undefined;
|
|
175
|
+
const fresh = generate();
|
|
176
|
+
state.writing = true; // same tick as the check above and the call below
|
|
177
|
+
try {
|
|
178
|
+
await storage.setItem(ASSIGNMENT_ID_STORAGE_KEY, fresh);
|
|
179
|
+
} catch (error) {
|
|
180
|
+
// Not persisted means not stable: the next launch would send another one.
|
|
181
|
+
console.warn("[assignment-id] Failed to persist the installation id; omitting it:", error);
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
return fresh;
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
token: () => epoch,
|
|
189
|
+
get: (token) => {
|
|
190
|
+
// Cleared since the caller started: no load, no write.
|
|
191
|
+
if (token !== undefined && token !== epoch) return Promise.resolve(undefined);
|
|
192
|
+
if (!pending) {
|
|
193
|
+
const startedAt = epoch;
|
|
194
|
+
const settle = (id: string | undefined) => {
|
|
195
|
+
// Cleared while loading: `clear()` already dropped this memo.
|
|
196
|
+
if (epoch !== startedAt) return undefined;
|
|
197
|
+
if (!id) pending = null;
|
|
198
|
+
return id;
|
|
199
|
+
};
|
|
200
|
+
const state: LoadState = { abandoned: false, writing: false };
|
|
201
|
+
pending = enqueue(
|
|
202
|
+
() => load(startedAt, state),
|
|
203
|
+
() => {
|
|
204
|
+
state.abandoned = true;
|
|
205
|
+
// Not yet writing: the abandoned load will never write now, so the
|
|
206
|
+
// queue need not wait for its read. A write in flight still holds it.
|
|
207
|
+
return !state.writing;
|
|
208
|
+
},
|
|
209
|
+
).then(settle, (error) => {
|
|
210
|
+
console.warn("[assignment-id] Loading the installation id failed; omitting it:", error);
|
|
211
|
+
return settle(undefined);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
return pending;
|
|
215
|
+
},
|
|
216
|
+
clear: () => {
|
|
217
|
+
epoch++;
|
|
218
|
+
pending = null;
|
|
219
|
+
return enqueue(() => storage.removeItem(ASSIGNMENT_ID_STORAGE_KEY));
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Calls a host getter; never throws, never waits past the bound. Returns
|
|
226
|
+
* `false` (omit, store untouched) for an explicit opt-out AND for a getter that
|
|
227
|
+
* throws or times out; `undefined` only for "no host value".
|
|
228
|
+
*/
|
|
229
|
+
const readHostValue = async (option: AssignmentIdOption): Promise<string | false | undefined> => {
|
|
230
|
+
if (option === false) return false;
|
|
231
|
+
if (typeof option !== "function") return nonEmpty(option);
|
|
232
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
233
|
+
try {
|
|
234
|
+
const value = await Promise.race([
|
|
235
|
+
Promise.resolve().then(option),
|
|
236
|
+
new Promise<false>((resolve) => {
|
|
237
|
+
timer = setTimeout(() => {
|
|
238
|
+
console.warn(
|
|
239
|
+
`[assignment-id] The assignmentId getter did not settle within ${HOST_ASSIGNMENT_ID_TIMEOUT_MS}ms; ` +
|
|
240
|
+
"sending no assignmentId for this request."
|
|
241
|
+
);
|
|
242
|
+
resolve(false);
|
|
243
|
+
}, HOST_ASSIGNMENT_ID_TIMEOUT_MS);
|
|
244
|
+
}),
|
|
245
|
+
]);
|
|
246
|
+
return value === false ? false : nonEmpty(value);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
console.warn("[assignment-id] The assignmentId getter threw; sending no assignmentId for this request:", error);
|
|
249
|
+
return false;
|
|
250
|
+
} finally {
|
|
251
|
+
clearTimeout(timer);
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Opt-out, throw or timeout → `undefined` (store untouched); host value →
|
|
257
|
+
* installation id → `undefined`. Never throws.
|
|
258
|
+
*/
|
|
259
|
+
export const resolveAssignmentId = async (
|
|
260
|
+
option: AssignmentIdOption,
|
|
261
|
+
installation: Pick<InstallationIdStore, "get" | "token">,
|
|
262
|
+
): Promise<string | undefined> => {
|
|
263
|
+
// Before the host getter's await: a clear() while it runs must be seen.
|
|
264
|
+
const token = installation.token();
|
|
265
|
+
const host = await readHostValue(option);
|
|
266
|
+
if (host === false) return undefined;
|
|
267
|
+
return host ?? installation.get(token);
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
let installationIdStore = createInstallationIdStore(AsyncStorage);
|
|
271
|
+
|
|
272
|
+
/** The process-wide installation id store: shared by every client, like the disk it reads. */
|
|
273
|
+
export const getInstallationIdStore = (): InstallationIdStore => installationIdStore;
|
|
274
|
+
|
|
275
|
+
/** Test-only: forget the in-memory id, as a new process would. */
|
|
276
|
+
export const __resetInstallationIdForTests = (): void => {
|
|
277
|
+
installationIdStore = createInstallationIdStore(AsyncStorage);
|
|
278
|
+
};
|
package/src/index.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Core client and types
|
|
2
2
|
export { OnboardingStudioClient } from "./OnboardingStudioClient";
|
|
3
3
|
export * from "./types";
|
|
4
|
+
export type { AssignmentIdOption, AssignmentIdValue } from "./assignmentId";
|
|
4
5
|
export * from "./onboarding-example";
|
|
5
6
|
// Cache key helper (advanced/host use — e.g. to read/clear the persisted key)
|
|
6
7
|
export {
|
|
@@ -742,6 +742,57 @@ describe("PaywallProvider observer — observePresentation (the inline step's se
|
|
|
742
742
|
});
|
|
743
743
|
});
|
|
744
744
|
|
|
745
|
+
describe("PaywallProvider observer — the served arm reaches start() on both surfaces (#237)", () => {
|
|
746
|
+
const armedCatalog = (arm: Record<string, unknown>) => {
|
|
747
|
+
const catalog = catalogOf("upgrade");
|
|
748
|
+
Object.assign(catalog.paywalls.upgrade, arm);
|
|
749
|
+
return catalog;
|
|
750
|
+
};
|
|
751
|
+
const presentStart = async (arm: Record<string, unknown>) => {
|
|
752
|
+
const { observer, calls } = recordingObserver();
|
|
753
|
+
const { captured } = await mount({ observer, catalog: armedCatalog(arm) });
|
|
754
|
+
await act(async () => void captured.ctx.present("upgrade"));
|
|
755
|
+
await settle();
|
|
756
|
+
await act_(() => captured.ctx.complete({ status: "dismissed" }));
|
|
757
|
+
return calls[0];
|
|
758
|
+
};
|
|
759
|
+
const stepStart = async (arm: Record<string, unknown>) => {
|
|
760
|
+
const { observer, calls } = recordingObserver();
|
|
761
|
+
const { captured } = await mount({ observer });
|
|
762
|
+
captured.ctx.observePresentation({ ...paywall("upgrade"), ...arm });
|
|
763
|
+
return calls[0];
|
|
764
|
+
};
|
|
765
|
+
|
|
766
|
+
it.each([
|
|
767
|
+
["present()", presentStart],
|
|
768
|
+
["the paywall step", stepStart],
|
|
769
|
+
])("%s reports a served variant", async (_label, start) => {
|
|
770
|
+
expect(await start({ variantKey: "b", deploymentId: 42 })).toEqual([
|
|
771
|
+
"start",
|
|
772
|
+
expect.objectContaining({ variantKey: "b", deploymentId: "42" }),
|
|
773
|
+
]);
|
|
774
|
+
});
|
|
775
|
+
|
|
776
|
+
it.each([
|
|
777
|
+
["present()", presentStart],
|
|
778
|
+
["the paywall step", stepStart],
|
|
779
|
+
])("%s reports the parent paywall as main", async (_label, start) => {
|
|
780
|
+
expect(await start({ variantKey: "main", deploymentId: 7 })).toEqual([
|
|
781
|
+
"start",
|
|
782
|
+
expect.objectContaining({ variantKey: "main", deploymentId: "7" }),
|
|
783
|
+
]);
|
|
784
|
+
});
|
|
785
|
+
|
|
786
|
+
it.each([
|
|
787
|
+
["present()", presentStart],
|
|
788
|
+
["the paywall step", stepStart],
|
|
789
|
+
])("%s adds no property for an older server", async (_label, start) => {
|
|
790
|
+
const [, info] = (await start({})) as [string, Record<string, unknown>];
|
|
791
|
+
expect(Object.keys(info)).not.toContain("variantKey");
|
|
792
|
+
expect(Object.keys(info)).not.toContain("deploymentId");
|
|
793
|
+
});
|
|
794
|
+
});
|
|
795
|
+
|
|
745
796
|
describe("PaywallProvider observer — complete() carries a custom screen's transaction (#287)", () => {
|
|
746
797
|
const tx = { originalTransactionIdentifier: "2000000123", productId: "com.app.annual.ios" };
|
|
747
798
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
1
|
+
import { describe, it, expect, expectTypeOf, vi, beforeEach, afterEach } from "vitest";
|
|
2
2
|
|
|
3
3
|
// react-native is mocked so OnboardingStudioClient (which reads `Platform.OS`)
|
|
4
4
|
// loads under Node — same stub `getOnboarding.query.test.ts` uses.
|
|
@@ -26,7 +26,8 @@ import {
|
|
|
26
26
|
DEFAULT_PAYWALLS_CACHE_KEY,
|
|
27
27
|
} from "../../infra/queries/cacheKey";
|
|
28
28
|
import { getPaywallsQuery } from "../getPaywalls.query";
|
|
29
|
-
import type { PaywallCatalog } from "../types";
|
|
29
|
+
import type { Paywall, PaywallCatalog } from "../types";
|
|
30
|
+
import type { CustomPaywallScreenProps } from "../customScreens";
|
|
30
31
|
|
|
31
32
|
const CACHE_KEY = "rocapine-paywalls-studio";
|
|
32
33
|
const CUSTOM_KEY = "v2";
|
|
@@ -383,3 +384,77 @@ describe("getPaywallsQuery cache key and request identity", () => {
|
|
|
383
384
|
expect(setItem).toHaveBeenCalledWith(CUSTOM_CACHE_KEY, JSON.stringify(catalog));
|
|
384
385
|
});
|
|
385
386
|
});
|
|
387
|
+
|
|
388
|
+
// #235: each resolved paywall carries its own variant identity, PER MOMENT
|
|
389
|
+
// (like `audienceId`). The values are the server's; the SDK passes them through
|
|
390
|
+
// untouched — `null` stays `null`, and a field an older `get-paywalls` never
|
|
391
|
+
// sent stays absent.
|
|
392
|
+
describe("Paywall variant identity (variantKey / deploymentId)", () => {
|
|
393
|
+
const base = {
|
|
394
|
+
name: "pw",
|
|
395
|
+
audienceId: 1,
|
|
396
|
+
audienceName: "default",
|
|
397
|
+
elements: [],
|
|
398
|
+
billing: "store" as const,
|
|
399
|
+
products: [],
|
|
400
|
+
configuration: null,
|
|
401
|
+
};
|
|
402
|
+
const twoArms: PaywallCatalog = {
|
|
403
|
+
metadata: { locale: "en", draft: false },
|
|
404
|
+
paywalls: {
|
|
405
|
+
onboarding_end: {
|
|
406
|
+
...base,
|
|
407
|
+
id: "pw-a",
|
|
408
|
+
moment: "onboarding_end",
|
|
409
|
+
variantKey: "b",
|
|
410
|
+
deploymentId: 42,
|
|
411
|
+
},
|
|
412
|
+
settings_upgrade: {
|
|
413
|
+
...base,
|
|
414
|
+
id: "pw-b",
|
|
415
|
+
moment: "settings_upgrade",
|
|
416
|
+
// The parent paywall reports the reserved key.
|
|
417
|
+
variantKey: "main",
|
|
418
|
+
deploymentId: 7,
|
|
419
|
+
},
|
|
420
|
+
// An older `get-paywalls` that predates the fields.
|
|
421
|
+
legacy: { ...base, id: "pw-c", moment: "legacy" },
|
|
422
|
+
},
|
|
423
|
+
fonts: null,
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
const expectArms = (data: PaywallCatalog) => {
|
|
427
|
+
const { onboarding_end, settings_upgrade, legacy } = data.paywalls;
|
|
428
|
+
expect([onboarding_end.variantKey, onboarding_end.deploymentId]).toEqual(["b", 42]);
|
|
429
|
+
expect([settings_upgrade.variantKey, settings_upgrade.deploymentId]).toEqual(["main", 7]);
|
|
430
|
+
expect([legacy.variantKey, legacy.deploymentId]).toEqual([undefined, undefined]);
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
it("is declared on the resolved Paywall type, optional and nullable", () => {
|
|
434
|
+
expectTypeOf<Paywall["variantKey"]>().toEqualTypeOf<string | null | undefined>();
|
|
435
|
+
expectTypeOf<Paywall["deploymentId"]>().toEqualTypeOf<number | null | undefined>();
|
|
436
|
+
// A custom paywall screen gets the same two fields, same types.
|
|
437
|
+
expectTypeOf<CustomPaywallScreenProps["paywall"]["variantKey"]>().toEqualTypeOf<string | null | undefined>();
|
|
438
|
+
expectTypeOf<CustomPaywallScreenProps["paywall"]["deploymentId"]>().toEqualTypeOf<number | null | undefined>();
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
it("getPaywalls passes each moment's own values through, absent stays undefined", async () => {
|
|
442
|
+
const fetchMock = vi.fn().mockResolvedValue(fakeResponse(JSON.parse(JSON.stringify(twoArms))));
|
|
443
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
444
|
+
try {
|
|
445
|
+
const { data } = await new OnboardingStudioClient("proj-1", {}).getPaywalls();
|
|
446
|
+
expectArms(data);
|
|
447
|
+
} finally {
|
|
448
|
+
vi.unstubAllGlobals();
|
|
449
|
+
}
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
it("survives the production cache round-trip (served from AsyncStorage)", async () => {
|
|
453
|
+
getItem.mockReset();
|
|
454
|
+
setItem.mockReset();
|
|
455
|
+
setItem.mockResolvedValue(undefined);
|
|
456
|
+
getItem.mockResolvedValue(JSON.stringify(twoArms));
|
|
457
|
+
const data = await run(makeClient({ isSandbox: false, cacheKey: CUSTOM_KEY, data: catalog }));
|
|
458
|
+
expectArms(data);
|
|
459
|
+
});
|
|
460
|
+
});
|
|
@@ -38,6 +38,43 @@ afterEach(() => {
|
|
|
38
38
|
vi.restoreAllMocks();
|
|
39
39
|
});
|
|
40
40
|
|
|
41
|
+
describe("openPaywallPresentation — the served arm on start() (#237)", () => {
|
|
42
|
+
const startInfo = (extra: Partial<PaywallPresentationSource>) => {
|
|
43
|
+
const { observer, calls } = recordingObserver();
|
|
44
|
+
openPaywallPresentation(observer, { ...PAYWALL, ...extra }, "present", "ios");
|
|
45
|
+
return calls[0][1] as Record<string, unknown>;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
it("carries a served variant's key, and its deploymentId as a decimal string", () => {
|
|
49
|
+
expect(startInfo({ variantKey: "b", deploymentId: 42 })).toMatchObject({ variantKey: "b", deploymentId: "42" });
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("carries the reserved main key for the parent paywall", () => {
|
|
53
|
+
expect(startInfo({ variantKey: "main", deploymentId: 7 })).toMatchObject({ variantKey: "main", deploymentId: "7" });
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it("keeps a deploymentId of 0 rather than treating it as absent", () => {
|
|
57
|
+
expect(startInfo({ variantKey: "b", deploymentId: 0 })).toMatchObject({ deploymentId: "0" });
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("carries the key alone when the server sent no deploymentId", () => {
|
|
61
|
+
const info = startInfo({ variantKey: "b", deploymentId: null });
|
|
62
|
+
expect(info.variantKey).toBe("b");
|
|
63
|
+
expect(Object.keys(info)).not.toContain("deploymentId");
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it.each([
|
|
67
|
+
["an older server (both absent)", {}],
|
|
68
|
+
["a null variantKey", { variantKey: null, deploymentId: null }],
|
|
69
|
+
["an empty variantKey", { variantKey: "", deploymentId: 42 }],
|
|
70
|
+
["a deploymentId with no variantKey", { deploymentId: 42 }],
|
|
71
|
+
])("sets neither key for %s", (_label, extra) => {
|
|
72
|
+
const info = startInfo(extra as Partial<PaywallPresentationSource>);
|
|
73
|
+
expect(Object.keys(info)).not.toContain("variantKey");
|
|
74
|
+
expect(Object.keys(info)).not.toContain("deploymentId");
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
41
78
|
describe("openPaywallPresentation — the info handed to start()", () => {
|
|
42
79
|
it("stringifies audienceId, defaults renderMode to elements, and names the surface", () => {
|
|
43
80
|
const { observer, calls } = recordingObserver();
|
|
@@ -86,6 +86,20 @@ describe("resolvePresentDecision", () => {
|
|
|
86
86
|
expect(decision).toEqual({ type: "start", paywall });
|
|
87
87
|
});
|
|
88
88
|
|
|
89
|
+
it("hands present() the moment's own variant identity, per moment (#235)", () => {
|
|
90
|
+
const armed = makePaywall({ id: "a", moment: "end", variantKey: "b", deploymentId: 42 });
|
|
91
|
+
const other = makePaywall({ id: "b", moment: "settings", variantKey: "main", deploymentId: 7 });
|
|
92
|
+
const both = makeCatalog([armed, other]);
|
|
93
|
+
|
|
94
|
+
const pick = (moment: string) => {
|
|
95
|
+
const d = resolvePresentDecision(both, null, moment);
|
|
96
|
+
if (d.type !== "start") throw new Error(`expected start, got ${d.type}`);
|
|
97
|
+
return [d.paywall.variantKey, d.paywall.deploymentId];
|
|
98
|
+
};
|
|
99
|
+
expect(pick("end")).toEqual(["b", 42]);
|
|
100
|
+
expect(pick("settings")).toEqual(["main", 7]);
|
|
101
|
+
});
|
|
102
|
+
|
|
89
103
|
// Every error below carries a `reason`. The bare `{status:"error"}` these
|
|
90
104
|
// used to assert is what made two conditions with OPPOSITE correct responses
|
|
91
105
|
// — "retry later, the catalog may still arrive" vs "do not retry, something
|
|
@@ -90,12 +90,19 @@ export type CustomPaywallScreenProps = {
|
|
|
90
90
|
* `name` are the studio's, for analytics. Enough to report a conversion
|
|
91
91
|
* without also handing over the `elements` tree a custom paywall has no use
|
|
92
92
|
* for.
|
|
93
|
+
*
|
|
94
|
+
* `variantKey` and `deploymentId` are the catalog entry's own, passed
|
|
95
|
+
* through untouched: see `Paywall.variantKey` / `Paywall.deploymentId` for
|
|
96
|
+
* what they mean. `null` and absent are equivalent (no variant or
|
|
97
|
+
* deployment information).
|
|
93
98
|
*/
|
|
94
99
|
paywall: {
|
|
95
100
|
id: string;
|
|
96
101
|
name: string;
|
|
97
102
|
moment: string;
|
|
98
103
|
customScreenId: string;
|
|
104
|
+
variantKey?: string | null;
|
|
105
|
+
deploymentId?: number | null;
|
|
99
106
|
};
|
|
100
107
|
};
|
|
101
108
|
|
package/src/paywalls/observer.ts
CHANGED
|
@@ -65,6 +65,8 @@ export type PaywallPresentationSource = {
|
|
|
65
65
|
billing?: "store" | "stripe";
|
|
66
66
|
renderMode?: "elements" | "custom" | null;
|
|
67
67
|
products?: ReadonlyArray<{ key: string; ios?: string; android?: string }>;
|
|
68
|
+
variantKey?: string | null;
|
|
69
|
+
deploymentId?: number | null;
|
|
68
70
|
};
|
|
69
71
|
|
|
70
72
|
/**
|
|
@@ -132,6 +134,25 @@ const isHandle = (value: unknown): value is PaywallPresentationHandle =>
|
|
|
132
134
|
typeof (value as PaywallPresentationHandle).shown === "function" &&
|
|
133
135
|
typeof (value as PaywallPresentationHandle).end === "function";
|
|
134
136
|
|
|
137
|
+
const nonEmptyString = (value: unknown): value is string => typeof value === "string" && value.length > 0;
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The arm this paywall was served as (#237): a variant's key, or the reserved
|
|
141
|
+
* `"main"` for the parent. Both keys are left UNSET, never empty or
|
|
142
|
+
* `"none"`, when the server sent no `variantKey` (an older server), so an app
|
|
143
|
+
* on one sees no new property. `deploymentId` is only sent alongside a key,
|
|
144
|
+
* and as a decimal string because that is the contract's type.
|
|
145
|
+
*
|
|
146
|
+
* `end()` carries no info of its own: an observer attributes a purchase or a
|
|
147
|
+
* dismiss to the presentation `start()` opened, so this covers them too.
|
|
148
|
+
*/
|
|
149
|
+
const servedArm = (paywall: PaywallPresentationSource): Pick<PaywallPresentationInfo, "variantKey" | "deploymentId"> => {
|
|
150
|
+
if (!nonEmptyString(paywall.variantKey)) return {};
|
|
151
|
+
return paywall.deploymentId == null
|
|
152
|
+
? { variantKey: paywall.variantKey }
|
|
153
|
+
: { variantKey: paywall.variantKey, deploymentId: String(paywall.deploymentId) };
|
|
154
|
+
};
|
|
155
|
+
|
|
135
156
|
export const buildPresentationInfo = (
|
|
136
157
|
paywall: PaywallPresentationSource,
|
|
137
158
|
surface: PaywallSurface
|
|
@@ -144,6 +165,7 @@ export const buildPresentationInfo = (
|
|
|
144
165
|
renderMode: paywall.renderMode === "custom" ? "custom" : "elements",
|
|
145
166
|
billing: paywall.billing === "stripe" ? "stripe" : "store",
|
|
146
167
|
surface,
|
|
168
|
+
...servedArm(paywall),
|
|
147
169
|
});
|
|
148
170
|
|
|
149
171
|
/**
|
|
@@ -164,8 +186,6 @@ const resolveProductId = (
|
|
|
164
186
|
return undefined;
|
|
165
187
|
};
|
|
166
188
|
|
|
167
|
-
const nonEmptyString = (value: unknown): value is string => typeof value === "string" && value.length > 0;
|
|
168
|
-
|
|
169
189
|
/**
|
|
170
190
|
* A custom screen's `complete({ transaction })`, reduced to the contract: the
|
|
171
191
|
* three ids only when they are non-empty strings, `restored` only when it is
|
package/src/paywalls/types.ts
CHANGED
|
@@ -23,6 +23,28 @@ export type Paywall = {
|
|
|
23
23
|
moment: string;
|
|
24
24
|
audienceId: number | null;
|
|
25
25
|
audienceName: string | null;
|
|
26
|
+
/**
|
|
27
|
+
* Which variant of the paywall this moment resolved to. Resolved PER MOMENT,
|
|
28
|
+
* for the same reason as `audienceId` above: one moment can serve a variant
|
|
29
|
+
* while another serves the parent paywall, so two entries in one catalog can
|
|
30
|
+
* carry different values.
|
|
31
|
+
*
|
|
32
|
+
* The parent paywall itself reports the reserved key `"main"`; any other
|
|
33
|
+
* value names a variant of it.
|
|
34
|
+
*
|
|
35
|
+
* Passed through exactly as `get-paywalls` sends it; the SDK neither reads
|
|
36
|
+
* nor normalizes it. `null` and ABSENT (`undefined`) are equivalent: both
|
|
37
|
+
* mean "no variant information". Absent is what an older `get-paywalls`
|
|
38
|
+
* that predates the field produces — a device on a new SDK can be talking
|
|
39
|
+
* to one — so a consumer must not treat the two differently.
|
|
40
|
+
*/
|
|
41
|
+
variantKey?: string | null;
|
|
42
|
+
/**
|
|
43
|
+
* Which published deployment this moment's paywall was served from. Same
|
|
44
|
+
* per-moment and pass-through rules as `variantKey`, and the same
|
|
45
|
+
* equivalence: `null` and absent both mean "no deployment information".
|
|
46
|
+
*/
|
|
47
|
+
deploymentId?: number | null;
|
|
26
48
|
/** UIElement[] — parsed by the UI adapter (Task 7's `ScreenElementsSchema`), not here. */
|
|
27
49
|
elements: unknown[];
|
|
28
50
|
/**
|