@rocapine/react-native-onboarding 1.77.0 → 1.79.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 (77) hide show
  1. package/README.md +38 -10
  2. package/dist/OnboardingStudio.d.ts +14 -1
  3. package/dist/OnboardingStudio.d.ts.map +1 -1
  4. package/dist/OnboardingStudio.js +5 -1
  5. package/dist/OnboardingStudio.js.map +1 -1
  6. package/dist/OnboardingStudioClient.d.ts +31 -0
  7. package/dist/OnboardingStudioClient.d.ts.map +1 -1
  8. package/dist/OnboardingStudioClient.js +80 -19
  9. package/dist/OnboardingStudioClient.js.map +1 -1
  10. package/dist/assignmentId.d.ts +107 -0
  11. package/dist/assignmentId.d.ts.map +1 -0
  12. package/dist/assignmentId.js +215 -0
  13. package/dist/assignmentId.js.map +1 -0
  14. package/dist/index.d.ts +5 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +9 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/paywalls/PaywallProvider.d.ts +8 -1
  19. package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
  20. package/dist/paywalls/PaywallProvider.js +5 -1
  21. package/dist/paywalls/PaywallProvider.js.map +1 -1
  22. package/dist/paywalls/customScreens.d.ts +7 -0
  23. package/dist/paywalls/customScreens.d.ts.map +1 -1
  24. package/dist/paywalls/devHook.d.ts +26 -0
  25. package/dist/paywalls/devHook.d.ts.map +1 -0
  26. package/dist/paywalls/devHook.js +29 -0
  27. package/dist/paywalls/devHook.js.map +1 -0
  28. package/dist/paywalls/observer.d.ts +2 -0
  29. package/dist/paywalls/observer.d.ts.map +1 -1
  30. package/dist/paywalls/observer.js +21 -9
  31. package/dist/paywalls/observer.js.map +1 -1
  32. package/dist/paywalls/types.d.ts +22 -0
  33. package/dist/paywalls/types.d.ts.map +1 -1
  34. package/dist/products/adapters/expoIap.d.ts +34 -13
  35. package/dist/products/adapters/expoIap.d.ts.map +1 -1
  36. package/dist/products/adapters/expoIap.js +136 -21
  37. package/dist/products/adapters/expoIap.js.map +1 -1
  38. package/dist/steps/ComposableScreen/types.d.ts +21 -0
  39. package/dist/steps/ComposableScreen/types.d.ts.map +1 -1
  40. package/dist/steps/ComposableScreen/types.js +14 -0
  41. package/dist/steps/ComposableScreen/types.js.map +1 -1
  42. package/dist/types.d.ts +47 -0
  43. package/dist/types.d.ts.map +1 -1
  44. package/dist/types.js +6 -0
  45. package/dist/types.js.map +1 -1
  46. package/dist/userProperties/reserved.d.ts +8 -5
  47. package/dist/userProperties/reserved.d.ts.map +1 -1
  48. package/dist/userProperties/reserved.js +9 -4
  49. package/dist/userProperties/reserved.js.map +1 -1
  50. package/dist/version.d.ts +1 -1
  51. package/dist/version.js +1 -1
  52. package/package.json +1 -1
  53. package/src/OnboardingStudio.ts +19 -1
  54. package/src/OnboardingStudioClient.ts +84 -31
  55. package/src/__tests__/assignmentId.clear.test.ts +413 -0
  56. package/src/__tests__/assignmentId.client.test.ts +288 -0
  57. package/src/__tests__/assignmentId.test.ts +195 -0
  58. package/src/__tests__/onboardingMetadata.client.test.ts +76 -0
  59. package/src/assignmentId.ts +278 -0
  60. package/src/index.ts +9 -0
  61. package/src/paywalls/PaywallProvider.tsx +13 -0
  62. package/src/paywalls/__tests__/PaywallProvider.observer.test.tsx +51 -0
  63. package/src/paywalls/__tests__/devHook.test.ts +70 -0
  64. package/src/paywalls/__tests__/getPaywalls.test.ts +77 -2
  65. package/src/paywalls/__tests__/observer.test.ts +37 -0
  66. package/src/paywalls/__tests__/present.test.ts +14 -0
  67. package/src/paywalls/customScreens.ts +7 -0
  68. package/src/paywalls/devHook.ts +48 -0
  69. package/src/paywalls/observer.ts +22 -2
  70. package/src/paywalls/types.ts +22 -0
  71. package/src/products/adapters/__tests__/expoIap.contract.test.ts +305 -0
  72. package/src/products/adapters/expoIap.ts +171 -32
  73. package/src/steps/ComposableScreen/types.ts +21 -0
  74. package/src/types.ts +48 -0
  75. package/src/userProperties/__tests__/primitives.test.ts +1 -1
  76. package/src/userProperties/reserved.ts +9 -4
  77. package/src/version.ts +1 -1
@@ -0,0 +1,413 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2
+
3
+ vi.mock("react-native", () => ({ Platform: { OS: "ios" } }));
4
+ const disk = vi.hoisted(() => ({ data: {} as Record<string, string> }));
5
+ vi.mock("@react-native-async-storage/async-storage", () => ({
6
+ default: {
7
+ getItem: vi.fn(async (k: string) => disk.data[k] ?? null),
8
+ setItem: vi.fn(async (k: string, v: string) => {
9
+ disk.data[k] = v;
10
+ }),
11
+ removeItem: vi.fn(async (k: string) => {
12
+ delete disk.data[k];
13
+ }),
14
+ getAllKeys: vi.fn(async () => []),
15
+ multiRemove: vi.fn(async () => {}),
16
+ },
17
+ }));
18
+
19
+ import {
20
+ ASSIGNMENT_ID_STORAGE_KEY,
21
+ STORAGE_OP_TIMEOUT_MS,
22
+ createInstallationIdStore,
23
+ resolveAssignmentId,
24
+ __resetInstallationIdForTests,
25
+ type AssignmentIdStorage,
26
+ } from "../assignmentId";
27
+ import { OnboardingStudioClient } from "../OnboardingStudioClient";
28
+ import { createOnboardingStudio } from "../OnboardingStudio";
29
+ import type { UserPropertyStore } from "../userProperties/store";
30
+
31
+ const KEY = ASSIGNMENT_ID_STORAGE_KEY;
32
+
33
+ /** Storage whose every call can be held open, to interleave operations. */
34
+ const controllableStorage = (initial: Record<string, string> = {}) => {
35
+ const data: Record<string, string> = { ...initial };
36
+ const held: Array<() => void> = [];
37
+ let holding = false;
38
+ const maybeHold = () =>
39
+ holding ? new Promise<void>((resolve) => held.push(resolve)) : Promise.resolve();
40
+ const storage = {
41
+ getItem: vi.fn(async (k: string): Promise<string | null> => {
42
+ const v = data[k] ?? null; // read at call time, like a real store
43
+ await maybeHold();
44
+ return v;
45
+ }),
46
+ setItem: vi.fn(async (k: string, v: string) => {
47
+ await maybeHold();
48
+ data[k] = v;
49
+ }),
50
+ removeItem: vi.fn(async (k: string) => {
51
+ await maybeHold();
52
+ delete data[k];
53
+ }),
54
+ } satisfies AssignmentIdStorage;
55
+ return {
56
+ data,
57
+ storage,
58
+ hold: () => {
59
+ holding = true;
60
+ },
61
+ /** Stop holding and let every held call through, in order. */
62
+ releaseAll: async () => {
63
+ holding = false;
64
+ while (held.length) held.shift()!();
65
+ for (let i = 0; i < 20; i++) await Promise.resolve();
66
+ },
67
+ };
68
+ };
69
+
70
+ let n = 0;
71
+ const counter = () => `generated-${++n}`;
72
+
73
+ beforeEach(() => {
74
+ vi.spyOn(console, "warn").mockImplementation(() => {});
75
+ });
76
+ afterEach(() => {
77
+ vi.restoreAllMocks();
78
+ });
79
+
80
+ describe("installation id store: clear()", () => {
81
+ it("removes the stored id, and the next get mints and persists a different one", async () => {
82
+ const s = controllableStorage();
83
+ const store = createInstallationIdStore(s.storage, counter);
84
+ const first = await store.get();
85
+ expect(s.data[KEY]).toBe(first);
86
+
87
+ await store.clear();
88
+ expect(s.data[KEY]).toBeUndefined();
89
+
90
+ const second = await store.get();
91
+ expect(second).toMatch(/^generated-/);
92
+ expect(second).not.toBe(first);
93
+ expect(s.data[KEY]).toBe(second);
94
+ });
95
+
96
+ it("running during an in-flight FIRST-LAUNCH load does not resurrect the id", async () => {
97
+ const s = controllableStorage();
98
+ const store = createInstallationIdStore(s.storage, counter);
99
+ s.hold(); // getItem → null is held, then generate + setItem would follow
100
+ const inFlight = store.get();
101
+ const cleared = store.clear();
102
+ await s.releaseAll();
103
+ await cleared;
104
+
105
+ // The request that was in flight must not send an id that no longer exists…
106
+ expect(await inFlight).toBeUndefined();
107
+ // …and the id it generated must not be on disk afterwards.
108
+ expect(s.data[KEY]).toBeUndefined();
109
+ });
110
+
111
+ it("running while the first-launch WRITE is in flight does not resurrect the id", async () => {
112
+ const s = controllableStorage();
113
+ const store = createInstallationIdStore(s.storage, counter);
114
+ const inFlight = store.get();
115
+ // Let getItem resolve, then hold the setItem that follows.
116
+ await Promise.resolve();
117
+ s.hold();
118
+ for (let i = 0; i < 5; i++) await Promise.resolve();
119
+ const cleared = store.clear();
120
+ await s.releaseAll();
121
+ await cleared;
122
+
123
+ expect(await inFlight).toBeUndefined();
124
+ expect(s.data[KEY]).toBeUndefined();
125
+ });
126
+
127
+ it("a removal that the platform would finish BEFORE an earlier, slow write still wins", async () => {
128
+ // AsyncStorage does not promise ordering between calls, so a removeItem
129
+ // issued after a setItem may complete first. Here the write is slow and the
130
+ // removal instant: without ordering, the write lands last and the id is back.
131
+ const data: Record<string, string> = {};
132
+ let finishWrite!: () => void;
133
+ const storage = {
134
+ getItem: vi.fn(async (k: string) => data[k] ?? null),
135
+ setItem: vi.fn(
136
+ (k: string, v: string) =>
137
+ new Promise<void>((resolve) => {
138
+ finishWrite = () => {
139
+ data[k] = v;
140
+ resolve();
141
+ };
142
+ }),
143
+ ),
144
+ removeItem: vi.fn(async (k: string) => {
145
+ delete data[k];
146
+ }),
147
+ } satisfies AssignmentIdStorage;
148
+ const store = createInstallationIdStore(storage, counter);
149
+ const inFlight = store.get();
150
+ for (let i = 0; i < 10; i++) await Promise.resolve();
151
+ expect(storage.setItem).toHaveBeenCalledTimes(1); // the write is in flight
152
+ const cleared = store.clear();
153
+ for (let i = 0; i < 10; i++) await Promise.resolve();
154
+ finishWrite();
155
+ await cleared;
156
+ expect(await inFlight).toBeUndefined();
157
+ expect(data[KEY]).toBeUndefined();
158
+ });
159
+
160
+ it("running during an in-flight read of an existing id: that request sends nothing, disk is empty", async () => {
161
+ const s = controllableStorage({ [KEY]: "existing" });
162
+ const store = createInstallationIdStore(s.storage, counter);
163
+ s.hold();
164
+ const inFlight = store.get();
165
+ const cleared = store.clear();
166
+ await s.releaseAll();
167
+ await cleared;
168
+ expect(await inFlight).toBeUndefined();
169
+ expect(s.data[KEY]).toBeUndefined();
170
+ });
171
+
172
+ it("a get started after clear, while the old load is still writing, keeps ITS id on disk", async () => {
173
+ const s = controllableStorage();
174
+ const store = createInstallationIdStore(s.storage, counter);
175
+ s.hold();
176
+ const old = store.get();
177
+ const cleared = store.clear();
178
+ const fresh = store.get();
179
+ await s.releaseAll();
180
+ await cleared;
181
+
182
+ expect(await old).toBeUndefined();
183
+ const id = await fresh;
184
+ expect(id).toMatch(/^generated-/);
185
+ expect(s.data[KEY]).toBe(id);
186
+ });
187
+
188
+ it("rejects when the removal fails, and the store still works afterwards", async () => {
189
+ const s = controllableStorage({ [KEY]: "existing" });
190
+ const store = createInstallationIdStore(s.storage, counter);
191
+ expect(await store.get()).toBe("existing");
192
+ s.storage.removeItem.mockRejectedValueOnce(new Error("disk"));
193
+ await expect(store.clear()).rejects.toThrow("disk");
194
+ // The memo was reset: the next get reads disk again.
195
+ expect(await store.get()).toBe("existing");
196
+ expect(s.storage.getItem).toHaveBeenCalledTimes(2);
197
+ });
198
+ });
199
+
200
+ describe("clear() against a request whose host getter is still pending", () => {
201
+ it("a consent getter pending across clear() does not mint, persist or send an id", async () => {
202
+ vi.useFakeTimers();
203
+ try {
204
+ const s = controllableStorage();
205
+ const store = createInstallationIdStore(s.storage, counter);
206
+ let consented = true;
207
+ // Async consent check: answers `null` ("no host id") 50ms later.
208
+ const getter = () => new Promise<null>((r) => setTimeout(() => r(null), 50));
209
+
210
+ const request = resolveAssignmentId(getter, store);
211
+ await vi.advanceTimersByTimeAsync(10);
212
+ consented = false; // consent withdrawn while the request is in flight
213
+ await store.clear();
214
+ await vi.advanceTimersByTimeAsync(100);
215
+
216
+ expect(consented).toBe(false);
217
+ expect(await request).toBeUndefined();
218
+ expect(s.storage.setItem).not.toHaveBeenCalled();
219
+ expect(s.data[KEY]).toBeUndefined();
220
+ } finally {
221
+ vi.useRealTimers();
222
+ }
223
+ });
224
+
225
+ it("a request that starts after clear() still mints normally", async () => {
226
+ const s = controllableStorage();
227
+ const store = createInstallationIdStore(s.storage, counter);
228
+ await store.clear();
229
+ const id = await resolveAssignmentId(async () => null, store);
230
+ expect(id).toMatch(/^generated-/);
231
+ expect(s.data[KEY]).toBe(id);
232
+ });
233
+ });
234
+
235
+ describe("a storage call slower than the bound", () => {
236
+ /** A storage call that settles after `ms` (fake timers), running `effect` then. */
237
+ const slow =
238
+ <T>(ms: number, effect: () => T) =>
239
+ () =>
240
+ new Promise<T>((resolve) => setTimeout(() => resolve(effect()), ms));
241
+
242
+ beforeEach(() => {
243
+ vi.useFakeTimers();
244
+ });
245
+ afterEach(() => {
246
+ vi.useRealTimers();
247
+ });
248
+
249
+ it("getItem takes 2.5s: get() omits at 2s, and the abandoned load never mints or writes", async () => {
250
+ const s = controllableStorage();
251
+ s.storage.getItem.mockImplementationOnce(slow(2500, () => null));
252
+ const generate = vi.fn(counter);
253
+ const store = createInstallationIdStore(s.storage, generate);
254
+
255
+ const first = store.get();
256
+ const firstAt = settleTime(first);
257
+ await vi.advanceTimersByTimeAsync(STORAGE_OP_TIMEOUT_MS);
258
+ expect(await first).toBeUndefined();
259
+ expect(await firstAt).toBe(STORAGE_OP_TIMEOUT_MS);
260
+
261
+ // The read finishes at 2.5s with "no id": the abandoned load must stop there.
262
+ await vi.advanceTimersByTimeAsync(1000);
263
+ expect(generate).not.toHaveBeenCalled();
264
+ expect(s.storage.setItem).not.toHaveBeenCalled();
265
+ expect(s.data[KEY]).toBeUndefined();
266
+
267
+ // A later request is not affected.
268
+ const later = store.get();
269
+ await vi.advanceTimersByTimeAsync(10);
270
+ expect(await later).toMatch(/^generated-/);
271
+ });
272
+
273
+ it("a getItem that never settles does not hold the queue: the next get() mints at once", async () => {
274
+ const s = controllableStorage();
275
+ s.storage.getItem.mockImplementationOnce(() => new Promise<never>(() => {}));
276
+ const store = createInstallationIdStore(s.storage, counter);
277
+
278
+ const first = store.get();
279
+ await vi.advanceTimersByTimeAsync(STORAGE_OP_TIMEOUT_MS);
280
+ expect(await first).toBeUndefined();
281
+
282
+ const next = store.get();
283
+ const nextAt = settleTime(next);
284
+ await vi.advanceTimersByTimeAsync(10);
285
+ const id = await next;
286
+ expect(id).toMatch(/^generated-/);
287
+ expect(await nextAt).toBeLessThan(10); // did not wait behind the hung read
288
+ expect(s.data[KEY]).toBe(id);
289
+ });
290
+
291
+ it("a setItem that never settles keeps holding the queue: later get() calls fail closed", async () => {
292
+ const s = controllableStorage();
293
+ s.storage.setItem.mockImplementationOnce(() => new Promise<never>(() => {}));
294
+ const store = createInstallationIdStore(s.storage, counter);
295
+
296
+ const first = store.get();
297
+ await vi.advanceTimersByTimeAsync(STORAGE_OP_TIMEOUT_MS);
298
+ expect(await first).toBeUndefined();
299
+
300
+ const next = store.get();
301
+ const nextAt = settleTime(next);
302
+ await vi.advanceTimersByTimeAsync(STORAGE_OP_TIMEOUT_MS);
303
+ expect(await next).toBeUndefined();
304
+ expect(await nextAt).toBe(STORAGE_OP_TIMEOUT_MS); // waited its own bound
305
+ expect(s.storage.getItem).toHaveBeenCalledTimes(1); // never ran: queue held
306
+ });
307
+
308
+ it("setItem takes 2.5s: a clear() issued meanwhile removes the key AFTER the write lands", async () => {
309
+ const s = controllableStorage();
310
+ s.storage.setItem.mockImplementationOnce((k: string, v: string) =>
311
+ slow(2500, () => {
312
+ s.data[k] = v;
313
+ })(),
314
+ );
315
+ const store = createInstallationIdStore(s.storage, counter);
316
+
317
+ const request = store.get();
318
+ await vi.advanceTimersByTimeAsync(STORAGE_OP_TIMEOUT_MS);
319
+ expect(await request).toBeUndefined(); // the caller stopped waiting at 2s
320
+
321
+ // The abandoned write is still in flight. The removal must queue behind it.
322
+ await vi.advanceTimersByTimeAsync(100);
323
+ const cleared = store.clear().catch(() => {});
324
+ await vi.advanceTimersByTimeAsync(1000); // the write lands at 2.5s
325
+ await cleared;
326
+ expect(s.data[KEY]).toBeUndefined();
327
+ });
328
+
329
+ it("removeItem takes 5s: clear() rejects at 2s, a get() meanwhile fails closed, then things proceed", async () => {
330
+ const s = controllableStorage({ [KEY]: "existing" });
331
+ s.storage.removeItem.mockImplementationOnce((k: string) =>
332
+ slow(5000, () => {
333
+ delete s.data[k];
334
+ })(),
335
+ );
336
+ const generate = vi.fn(counter);
337
+ const store = createInstallationIdStore(s.storage, generate);
338
+
339
+ const outcome = store.clear().then(
340
+ () => "resolved",
341
+ (e: Error) => e.message,
342
+ );
343
+ const during = store.get(); // queued behind the hung removal
344
+ await vi.advanceTimersByTimeAsync(STORAGE_OP_TIMEOUT_MS);
345
+ expect(await outcome).toMatch(/timed out/);
346
+ // It did not skip ahead of the removal: it waited its own 2s and omitted.
347
+ await vi.advanceTimersByTimeAsync(10);
348
+ expect(await during).toBeUndefined();
349
+ expect(s.data[KEY]).toBe("existing"); // removal still in flight
350
+
351
+ // The removal settles at 5s; the abandoned get never mints or writes.
352
+ await vi.advanceTimersByTimeAsync(3500);
353
+ expect(s.data[KEY]).toBeUndefined();
354
+ expect(generate).not.toHaveBeenCalled();
355
+
356
+ const after = store.get();
357
+ await vi.advanceTimersByTimeAsync(10);
358
+ expect(await after).toMatch(/^generated-/);
359
+ expect(s.data[KEY]).toBe(await after);
360
+ });
361
+ });
362
+
363
+ /** Fake-clock time (ms) at which `p` settles, measured from now. */
364
+ const settleTime = (p: Promise<unknown>) => {
365
+ const start = Date.now();
366
+ return p.then(
367
+ () => Date.now() - start,
368
+ () => Date.now() - start,
369
+ );
370
+ };
371
+
372
+ describe("clearAssignmentId() on the client and the facade", () => {
373
+ const fakeResponse = {
374
+ ok: true,
375
+ status: 200,
376
+ statusText: "OK",
377
+ json: async () => ({ metadata: {}, steps: [], paywalls: {} }),
378
+ headers: { get: () => null },
379
+ };
380
+
381
+ beforeEach(() => {
382
+ disk.data = {};
383
+ __resetInstallationIdForTests();
384
+ vi.spyOn(console, "info").mockImplementation(() => {});
385
+ });
386
+ afterEach(() => vi.unstubAllGlobals());
387
+
388
+ it("client.clearAssignmentId() removes the stored id; the next request sends a new one", async () => {
389
+ const fetchMock = vi.fn().mockResolvedValue(fakeResponse);
390
+ vi.stubGlobal("fetch", fetchMock);
391
+ const client = new OnboardingStudioClient("proj-1", {});
392
+ const sent = (i: number) =>
393
+ new Headers((fetchMock.mock.calls[i][1] as RequestInit | undefined)?.headers).get("X-Assignment-Id");
394
+
395
+ await client.getSteps();
396
+ const first = sent(0);
397
+ expect(disk.data[KEY]).toBe(first);
398
+
399
+ await client.clearAssignmentId();
400
+ expect(disk.data[KEY]).toBeUndefined();
401
+
402
+ await client.getPaywalls();
403
+ expect(sent(1)).toBeTruthy();
404
+ expect(sent(1)).not.toBe(first);
405
+ });
406
+
407
+ it("OnboardingStudio.clearAssignmentId() works before init and clears the process-wide id", async () => {
408
+ disk.data[KEY] = "existing";
409
+ const studio = createOnboardingStudio({} as UserPropertyStore);
410
+ await studio.clearAssignmentId();
411
+ expect(disk.data[KEY]).toBeUndefined();
412
+ });
413
+ });
@@ -0,0 +1,288 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2
+
3
+ vi.mock("react-native", () => ({ Platform: { OS: "ios" } }));
4
+ const disk = vi.hoisted(() => ({ data: {} as Record<string, string> }));
5
+ vi.mock("@react-native-async-storage/async-storage", () => ({
6
+ default: {
7
+ getItem: vi.fn(async (k: string) => disk.data[k] ?? null),
8
+ setItem: vi.fn(async (k: string, v: string) => {
9
+ disk.data[k] = v;
10
+ }),
11
+ removeItem: vi.fn(async () => {}),
12
+ getAllKeys: vi.fn(async () => []),
13
+ multiRemove: vi.fn(async () => {}),
14
+ },
15
+ }));
16
+
17
+ import { OnboardingStudioClient } from "../OnboardingStudioClient";
18
+ import { ASSIGNMENT_ID_STORAGE_KEY, __resetInstallationIdForTests } from "../assignmentId";
19
+ import { isReservedUserPropertyKey } from "../userProperties/reserved";
20
+ import AsyncStorage from "@react-native-async-storage/async-storage";
21
+
22
+ const fakeResponse = (body: unknown) => ({
23
+ ok: true,
24
+ status: 200,
25
+ statusText: "OK",
26
+ json: async () => body,
27
+ headers: { get: () => null },
28
+ });
29
+
30
+ // The id travels as the `X-Assignment-Id` header, never on the URL: edge
31
+ // invocation logs record the full URL, and the id may be a host's user id.
32
+ const idHeader = (fetchMock: ReturnType<typeof vi.fn>, i = 0) =>
33
+ new Headers((fetchMock.mock.calls[i][1] as RequestInit | undefined)?.headers).get("X-Assignment-Id");
34
+
35
+ const fetches = {
36
+ getSteps: (c: OnboardingStudioClient, params?: Record<string, string>) =>
37
+ c.getSteps({ locale: "en" }, params),
38
+ getPaywalls: (c: OnboardingStudioClient, params?: Record<string, string>) =>
39
+ c.getPaywalls({ locale: "en" }, params),
40
+ };
41
+
42
+ describe.each(Object.entries(fetches))("%s assignmentId", (_name, fetchWith) => {
43
+ let fetchMock: ReturnType<typeof vi.fn>;
44
+
45
+ beforeEach(() => {
46
+ vi.clearAllMocks(); // the AsyncStorage module mock keeps call history across tests
47
+ disk.data = {};
48
+ __resetInstallationIdForTests();
49
+ fetchMock = vi.fn().mockResolvedValue(fakeResponse({ metadata: {}, steps: [], paywalls: {} }));
50
+ vi.stubGlobal("fetch", fetchMock);
51
+ vi.spyOn(console, "info").mockImplementation(() => {});
52
+ });
53
+
54
+ afterEach(() => {
55
+ vi.unstubAllGlobals();
56
+ vi.restoreAllMocks();
57
+ });
58
+
59
+ const sent = (i = 0) => new URL(fetchMock.mock.calls[i][0] as string).searchParams;
60
+ const sentId = (i = 0) => idHeader(fetchMock, i);
61
+
62
+ it("sends a persisted installation id, the same one across launches", async () => {
63
+ await fetchWith(new OnboardingStudioClient("proj-1", {}));
64
+ const first = sentId();
65
+ expect(first).toBeTruthy();
66
+ expect(disk.data[ASSIGNMENT_ID_STORAGE_KEY]).toBe(first);
67
+
68
+ // Next launch: module memo gone, disk kept.
69
+ __resetInstallationIdForTests();
70
+ await fetchWith(new OnboardingStudioClient("proj-1", {}));
71
+ expect(sentId(1)).toBe(first);
72
+ });
73
+
74
+ it("sends it in sandbox (draft) requests too", async () => {
75
+ await fetchWith(new OnboardingStudioClient("proj-1", { isSandbox: true }));
76
+ expect(sent().get("draft")).toBe("true");
77
+ expect(sentId()).toBeTruthy();
78
+ });
79
+
80
+ it("a host override wins and is read on every request", async () => {
81
+ let id = "anon-1";
82
+ const client = new OnboardingStudioClient("proj-1", { assignmentId: () => id });
83
+ await fetchWith(client);
84
+ id = "user-42";
85
+ await fetchWith(client);
86
+ expect(sentId(0)).toBe("anon-1");
87
+ expect(sentId(1)).toBe("user-42");
88
+ expect(disk.data[ASSIGNMENT_ID_STORAGE_KEY]).toBeUndefined();
89
+ });
90
+
91
+ it("assignmentId: false sends nothing and never touches storage", async () => {
92
+ const client = new OnboardingStudioClient("proj-1", { assignmentId: false });
93
+ await fetchWith(client);
94
+ expect(sentId()).toBeNull();
95
+ expect(sent().has("assignmentId")).toBe(false);
96
+ expect(AsyncStorage.getItem).not.toHaveBeenCalledWith(ASSIGNMENT_ID_STORAGE_KEY);
97
+ expect(AsyncStorage.setItem).not.toHaveBeenCalledWith(ASSIGNMENT_ID_STORAGE_KEY, expect.anything());
98
+ expect(disk.data[ASSIGNMENT_ID_STORAGE_KEY]).toBeUndefined();
99
+ });
100
+
101
+ it("opting out drops a user param named assignmentId too", async () => {
102
+ await fetchWith(new OnboardingStudioClient("proj-1", { assignmentId: () => false }), {
103
+ assignmentId: "spoofed",
104
+ });
105
+ expect(sentId()).toBeNull();
106
+ expect(sent().has("assignmentId")).toBe(false);
107
+ });
108
+
109
+ it("is absent when nothing stable is available (storage unreadable)", async () => {
110
+ vi.spyOn(console, "warn").mockImplementation(() => {});
111
+ vi.mocked(AsyncStorage.getItem).mockRejectedValueOnce(new Error("disk"));
112
+ await fetchWith(new OnboardingStudioClient("proj-1", {}));
113
+ expect(sentId()).toBeNull();
114
+ expect(sent().has("assignmentId")).toBe(false);
115
+ });
116
+
117
+ it("sends the id as the X-Assignment-Id header and never on the URL", async () => {
118
+ await fetchWith(new OnboardingStudioClient("proj-1", { assignmentId: "user-42" }));
119
+ expect(sentId()).toBe("user-42");
120
+ const url = fetchMock.mock.calls[0][0] as string;
121
+ expect(url).not.toMatch(/assignmentId/i);
122
+ expect(url).not.toContain("user-42");
123
+ });
124
+
125
+ it("a getter that throws fails closed: no header, nothing on the URL", async () => {
126
+ vi.spyOn(console, "warn").mockImplementation(() => {});
127
+ await fetchWith(
128
+ new OnboardingStudioClient("proj-1", {
129
+ assignmentId: () => {
130
+ throw new Error("boom");
131
+ },
132
+ }),
133
+ );
134
+ expect(sentId()).toBeNull();
135
+ expect(sent().has("assignmentId")).toBe(false);
136
+ });
137
+
138
+ it("a user param named assignmentId never reaches the wire as the id", async () => {
139
+ vi.spyOn(console, "warn").mockImplementation(() => {});
140
+ vi.mocked(AsyncStorage.getItem).mockRejectedValueOnce(new Error("disk"));
141
+ await fetchWith(new OnboardingStudioClient("proj-1", {}), { assignmentId: "spoofed" });
142
+ expect(sent().getAll("assignmentId")).toEqual([]);
143
+ expect(sentId()).toBeNull();
144
+
145
+ await fetchWith(new OnboardingStudioClient("proj-1", { assignmentId: "host" }), {
146
+ assignmentId: "spoofed",
147
+ });
148
+ expect(sent(1).getAll("assignmentId")).toEqual([]);
149
+ expect(sentId(1)).toBe("host");
150
+ });
151
+ });
152
+
153
+ it("getSteps and getPaywalls fired together on a first launch send the same id", async () => {
154
+ disk.data = {};
155
+ __resetInstallationIdForTests();
156
+ const fetchMock = vi.fn().mockResolvedValue(fakeResponse({ metadata: {}, steps: [], paywalls: {} }));
157
+ vi.stubGlobal("fetch", fetchMock);
158
+ vi.spyOn(console, "info").mockImplementation(() => {});
159
+ const client = new OnboardingStudioClient("proj-1", {});
160
+ await Promise.all([fetches.getSteps(client), fetches.getPaywalls(client)]);
161
+ const ids = [idHeader(fetchMock, 0), idHeader(fetchMock, 1)];
162
+ expect(ids[0]).toBeTruthy();
163
+ expect(ids[1]).toBe(ids[0]);
164
+ vi.unstubAllGlobals();
165
+ vi.restoreAllMocks();
166
+ });
167
+
168
+ it("assignmentId is a reserved user property key", () => {
169
+ expect(isReservedUserPropertyKey("assignmentId")).toBe(true);
170
+ });
171
+
172
+ describe.each(Object.entries(fetches))("%s: fail closed and one timeout budget", (name, fetchWith) => {
173
+ const fallbackOnboarding = { metadata: { id: "fb" }, steps: [], configuration: {} } as never;
174
+ let fetchMock: ReturnType<typeof vi.fn>;
175
+
176
+ beforeEach(() => {
177
+ vi.clearAllMocks();
178
+ vi.useFakeTimers();
179
+ disk.data = {};
180
+ __resetInstallationIdForTests();
181
+ vi.spyOn(console, "info").mockImplementation(() => {});
182
+ vi.spyOn(console, "warn").mockImplementation(() => {});
183
+ vi.spyOn(console, "error").mockImplementation(() => {});
184
+ });
185
+
186
+ afterEach(() => {
187
+ vi.useRealTimers();
188
+ vi.unstubAllGlobals();
189
+ vi.restoreAllMocks();
190
+ });
191
+
192
+ /** fetch that answers after `ms`. */
193
+ const slowFetch = (ms: number) => {
194
+ fetchMock = vi.fn(
195
+ () => new Promise((r) => setTimeout(() => r(fakeResponse({ metadata: {}, steps: [], paywalls: {} })), ms)),
196
+ );
197
+ vi.stubGlobal("fetch", fetchMock);
198
+ };
199
+
200
+ /** Settles the request, recording when (in fake ms) it did and how. */
201
+ const settle = async (p: Promise<unknown>, budget: number) => {
202
+ const out: { at?: number; value?: unknown; error?: unknown } = {};
203
+ const start = Date.now();
204
+ p.then(
205
+ (value) => Object.assign(out, { at: Date.now() - start, value }),
206
+ (error) => Object.assign(out, { at: Date.now() - start, error }),
207
+ );
208
+ await vi.advanceTimersByTimeAsync(budget);
209
+ return out;
210
+ };
211
+
212
+ it("a getter that resolves false after 2.5s: nothing sent, nothing stored", async () => {
213
+ slowFetch(0);
214
+ const client = new OnboardingStudioClient("proj-1", {
215
+ assignmentId: () => new Promise<false>((r) => setTimeout(() => r(false), 2500)),
216
+ });
217
+ const out = await settle(fetchWith(client), 3000);
218
+ expect(out.error).toBeUndefined();
219
+ expect(idHeader(fetchMock)).toBeNull();
220
+ expect(new URL(fetchMock.mock.calls[0][0] as string).searchParams.has("assignmentId")).toBe(false);
221
+ expect(AsyncStorage.getItem).not.toHaveBeenCalledWith(ASSIGNMENT_ID_STORAGE_KEY);
222
+ expect(AsyncStorage.setItem).not.toHaveBeenCalledWith(ASSIGNMENT_ID_STORAGE_KEY, expect.anything());
223
+ expect(disk.data[ASSIGNMENT_ID_STORAGE_KEY]).toBeUndefined();
224
+ });
225
+
226
+ it("a getter that resolves an id after 2.5s fails closed: no header, nothing on the URL", async () => {
227
+ slowFetch(0);
228
+ const client = new OnboardingStudioClient("proj-1", {
229
+ assignmentId: () => new Promise<string>((r) => setTimeout(() => r("late-user"), 2500)),
230
+ });
231
+ const out = await settle(fetchWith(client), 3000);
232
+ expect(out.error).toBeUndefined();
233
+ expect(idHeader(fetchMock)).toBeNull();
234
+ expect(fetchMock.mock.calls[0][0] as string).not.toMatch(/assignmentId|late-user/);
235
+ });
236
+
237
+ it("options.timeout covers id resolution AND fetch: 800ms + 500ms against 1000ms times out at 1000ms", async () => {
238
+ slowFetch(500);
239
+ const client = new OnboardingStudioClient("proj-1", {
240
+ timeout: 1000,
241
+ fallbackOnboarding,
242
+ assignmentId: () => new Promise<string>((r) => setTimeout(() => r("user-42"), 800)),
243
+ });
244
+ const out = await settle(fetchWith(client), 3000);
245
+ expect(out.at).toBe(1000);
246
+ if (name === "getSteps") {
247
+ expect((out.value as { headers: Record<string, string> }).headers["ONBS-Onboarding-Id"]).toBe("fallback");
248
+ } else {
249
+ expect(String(out.error)).toMatch(/timeout/);
250
+ }
251
+ });
252
+
253
+ it("a hanging getter does not delay fallbackOnboarding past options.timeout", async () => {
254
+ slowFetch(0);
255
+ const client = new OnboardingStudioClient("proj-1", {
256
+ timeout: 500,
257
+ fallbackOnboarding,
258
+ assignmentId: () => new Promise<string>(() => {}),
259
+ });
260
+ const out = await settle(fetchWith(client), 3000);
261
+ expect(out.at).toBe(500);
262
+ });
263
+
264
+ it("a request that timed out while resolving the id is never sent afterwards", async () => {
265
+ slowFetch(0);
266
+ const client = new OnboardingStudioClient("proj-1", {
267
+ timeout: 500,
268
+ fallbackOnboarding,
269
+ assignmentId: () => new Promise<string>((r) => setTimeout(() => r("user-42"), 800)),
270
+ });
271
+ const out = await settle(fetchWith(client), 3000);
272
+ expect(out.at).toBe(500);
273
+ expect(fetchMock).not.toHaveBeenCalled();
274
+ });
275
+
276
+ it("within budget the request succeeds: 300ms + 300ms against 1000ms", async () => {
277
+ slowFetch(300);
278
+ const client = new OnboardingStudioClient("proj-1", {
279
+ timeout: 1000,
280
+ fallbackOnboarding,
281
+ assignmentId: () => new Promise<string>((r) => setTimeout(() => r("user-42"), 300)),
282
+ });
283
+ const out = await settle(fetchWith(client), 3000);
284
+ expect(out.error).toBeUndefined();
285
+ expect(out.at).toBe(600);
286
+ expect(idHeader(fetchMock)).toBe("user-42");
287
+ });
288
+ });