@rocapine/react-native-onboarding 1.72.0 → 1.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +136 -3
  2. package/dist/OnboardingStudio.d.ts +82 -0
  3. package/dist/OnboardingStudio.d.ts.map +1 -0
  4. package/dist/OnboardingStudio.js +91 -0
  5. package/dist/OnboardingStudio.js.map +1 -0
  6. package/dist/OnboardingStudioClient.d.ts +14 -5
  7. package/dist/OnboardingStudioClient.d.ts.map +1 -1
  8. package/dist/OnboardingStudioClient.js +24 -9
  9. package/dist/OnboardingStudioClient.js.map +1 -1
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +43 -4
  13. package/dist/index.js.map +1 -1
  14. package/dist/infra/provider/OnboardingProvider.d.ts +11 -2
  15. package/dist/infra/provider/OnboardingProvider.d.ts.map +1 -1
  16. package/dist/infra/provider/OnboardingProvider.js +26 -2
  17. package/dist/infra/provider/OnboardingProvider.js.map +1 -1
  18. package/dist/infra/queries/cacheKey.d.ts +41 -3
  19. package/dist/infra/queries/cacheKey.d.ts.map +1 -1
  20. package/dist/infra/queries/cacheKey.js +44 -8
  21. package/dist/infra/queries/cacheKey.js.map +1 -1
  22. package/dist/infra/queries/getOnboarding.query.d.ts.map +1 -1
  23. package/dist/infra/queries/getOnboarding.query.js +6 -1
  24. package/dist/infra/queries/getOnboarding.query.js.map +1 -1
  25. package/dist/paywalls/PaywallProvider.d.ts +95 -5
  26. package/dist/paywalls/PaywallProvider.d.ts.map +1 -1
  27. package/dist/paywalls/PaywallProvider.js +121 -9
  28. package/dist/paywalls/PaywallProvider.js.map +1 -1
  29. package/dist/paywalls/catalogSettleWaiter.d.ts +31 -0
  30. package/dist/paywalls/catalogSettleWaiter.d.ts.map +1 -0
  31. package/dist/paywalls/catalogSettleWaiter.js +58 -0
  32. package/dist/paywalls/catalogSettleWaiter.js.map +1 -0
  33. package/dist/paywalls/customScreens.d.ts +83 -0
  34. package/dist/paywalls/customScreens.d.ts.map +1 -0
  35. package/dist/paywalls/customScreens.js +3 -0
  36. package/dist/paywalls/customScreens.js.map +1 -0
  37. package/dist/paywalls/getPaywalls.query.d.ts.map +1 -1
  38. package/dist/paywalls/getPaywalls.query.js +6 -1
  39. package/dist/paywalls/getPaywalls.query.js.map +1 -1
  40. package/dist/paywalls/register.d.ts +105 -0
  41. package/dist/paywalls/register.d.ts.map +1 -0
  42. package/dist/paywalls/register.js +112 -0
  43. package/dist/paywalls/register.js.map +1 -0
  44. package/dist/paywalls/usePaywall.d.ts +43 -0
  45. package/dist/paywalls/usePaywall.d.ts.map +1 -1
  46. package/dist/paywalls/usePaywall.js +11 -2
  47. package/dist/paywalls/usePaywall.js.map +1 -1
  48. package/dist/steps/Paywall/types.d.ts +63 -0
  49. package/dist/steps/Paywall/types.d.ts.map +1 -0
  50. package/dist/steps/Paywall/types.js +29 -0
  51. package/dist/steps/Paywall/types.js.map +1 -0
  52. package/dist/steps/types.d.ts +2 -1
  53. package/dist/steps/types.d.ts.map +1 -1
  54. package/dist/userProperties/applyPatch.d.ts +18 -0
  55. package/dist/userProperties/applyPatch.d.ts.map +1 -0
  56. package/dist/userProperties/applyPatch.js +57 -0
  57. package/dist/userProperties/applyPatch.js.map +1 -0
  58. package/dist/userProperties/effectiveParams.d.ts +29 -0
  59. package/dist/userProperties/effectiveParams.d.ts.map +1 -0
  60. package/dist/userProperties/effectiveParams.js +56 -0
  61. package/dist/userProperties/effectiveParams.js.map +1 -0
  62. package/dist/userProperties/index.d.ts +9 -0
  63. package/dist/userProperties/index.d.ts.map +1 -0
  64. package/dist/userProperties/index.js +21 -0
  65. package/dist/userProperties/index.js.map +1 -0
  66. package/dist/userProperties/reserved.d.ts +33 -0
  67. package/dist/userProperties/reserved.d.ts.map +1 -0
  68. package/dist/userProperties/reserved.js +45 -0
  69. package/dist/userProperties/reserved.js.map +1 -0
  70. package/dist/userProperties/serialize.d.ts +38 -0
  71. package/dist/userProperties/serialize.d.ts.map +1 -0
  72. package/dist/userProperties/serialize.js +67 -0
  73. package/dist/userProperties/serialize.js.map +1 -0
  74. package/dist/userProperties/store.d.ts +63 -0
  75. package/dist/userProperties/store.d.ts.map +1 -0
  76. package/dist/userProperties/store.js +153 -0
  77. package/dist/userProperties/store.js.map +1 -0
  78. package/dist/userProperties/types.d.ts +21 -0
  79. package/dist/userProperties/types.d.ts.map +1 -0
  80. package/dist/userProperties/types.js +3 -0
  81. package/dist/userProperties/types.js.map +1 -0
  82. package/dist/userProperties/useUserProperties.d.ts +20 -0
  83. package/dist/userProperties/useUserProperties.d.ts.map +1 -0
  84. package/dist/userProperties/useUserProperties.js +30 -0
  85. package/dist/userProperties/useUserProperties.js.map +1 -0
  86. package/package.json +1 -1
  87. package/src/OnboardingStudio.ts +147 -0
  88. package/src/OnboardingStudioClient.ts +27 -11
  89. package/src/__tests__/OnboardingStudio.test.ts +208 -0
  90. package/src/__tests__/cacheKey.test.ts +71 -0
  91. package/src/__tests__/getOnboarding.query.test.ts +47 -8
  92. package/src/index.ts +51 -0
  93. package/src/infra/provider/OnboardingProvider.tsx +45 -4
  94. package/src/infra/queries/cacheKey.ts +54 -9
  95. package/src/infra/queries/getOnboarding.query.ts +9 -1
  96. package/src/paywalls/PaywallProvider.tsx +226 -9
  97. package/src/paywalls/__tests__/catalogSettleWaiter.test.ts +134 -0
  98. package/src/paywalls/__tests__/getPaywalls.test.ts +29 -11
  99. package/src/paywalls/__tests__/register.test.ts +266 -0
  100. package/src/paywalls/catalogSettleWaiter.ts +72 -0
  101. package/src/paywalls/customScreens.ts +82 -0
  102. package/src/paywalls/getPaywalls.query.ts +9 -1
  103. package/src/paywalls/register.ts +169 -0
  104. package/src/paywalls/usePaywall.ts +63 -3
  105. package/src/steps/Paywall/types.ts +29 -0
  106. package/src/steps/types.ts +2 -0
  107. package/src/userProperties/__tests__/effectiveParams.test.ts +51 -0
  108. package/src/userProperties/__tests__/primitives.test.ts +96 -0
  109. package/src/userProperties/__tests__/store.test.ts +181 -0
  110. package/src/userProperties/applyPatch.ts +68 -0
  111. package/src/userProperties/effectiveParams.ts +60 -0
  112. package/src/userProperties/index.ts +11 -0
  113. package/src/userProperties/reserved.ts +44 -0
  114. package/src/userProperties/serialize.ts +61 -0
  115. package/src/userProperties/store.ts +177 -0
  116. package/src/userProperties/types.ts +22 -0
  117. package/src/userProperties/useUserProperties.ts +26 -0
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isReservedUserPropertyKey = exports.RESERVED_USER_PROPERTY_KEYS = void 0;
4
+ /**
5
+ * Property names a host may NOT use, because `OnboardingStudioClient` puts them
6
+ * on the querystring itself.
7
+ *
8
+ * Two of them — `moment` and `now` — mirror the server's own
9
+ * `RESERVED_AUDIENCE_VARS`, which strips them because they are server-owned (a
10
+ * client supplying `now` is self-selecting into a time-gated audience).
11
+ *
12
+ * The other six close a collision that is live today and merely unreachable,
13
+ * because nobody hand-writes these names into `customAudienceParams`. The
14
+ * client appends user params FIRST, then its own:
15
+ *
16
+ * Object.entries(userDefinedParams).forEach(([k, v]) => urlParams.append(k, v));
17
+ * urlParams.append("projectId", this.projectId);
18
+ *
19
+ * `URLSearchParams.append` permits duplicates, and the two server-side readers
20
+ * disagree about which one wins: `url.searchParams.get("projectId")` returns the
21
+ * FIRST occurrence (the user's value — so the request resolves the wrong
22
+ * project, or 400s), while `Object.fromEntries(...)` is last-wins (so the
23
+ * json-logic data still holds the real one). The result is a failed or
24
+ * cross-project request with no diagnostic pointing at the property that caused
25
+ * it.
26
+ *
27
+ * A store whose whole purpose is to let a host name keys freely makes that a
28
+ * plausible accident, so this is where it gets refused. Refusing — rather than
29
+ * prefixing or escaping — keeps the wire format unchanged and puts the warning
30
+ * at the call site responsible.
31
+ */
32
+ exports.RESERVED_USER_PROPERTY_KEYS = [
33
+ "projectId",
34
+ "platform",
35
+ "appVersion",
36
+ "draft",
37
+ "locale",
38
+ "omitNulls",
39
+ "moment",
40
+ "now",
41
+ ];
42
+ /** Exact match, never a prefix — `projectIdentifier` is a perfectly good property. */
43
+ const isReservedUserPropertyKey = (key) => exports.RESERVED_USER_PROPERTY_KEYS.includes(key);
44
+ exports.isReservedUserPropertyKey = isReservedUserPropertyKey;
45
+ //# sourceMappingURL=reserved.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reserved.js","sourceRoot":"","sources":["../../src/userProperties/reserved.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACU,QAAA,2BAA2B,GAAG;IACzC,WAAW;IACX,UAAU;IACV,YAAY;IACZ,OAAO;IACP,QAAQ;IACR,WAAW;IACX,QAAQ;IACR,KAAK;CACG,CAAC;AAIX,sFAAsF;AAC/E,MAAM,yBAAyB,GAAG,CAAC,GAAW,EAAW,EAAE,CAC/D,mCAAiD,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AADtD,QAAA,yBAAyB,6BAC6B"}
@@ -0,0 +1,38 @@
1
+ import type { UserProperties, UserPropertyValue } from "./types";
2
+ /**
3
+ * A property value as it crosses the wire.
4
+ *
5
+ * Note how this interacts with a studio audience filter. `json-logic-js` applies
6
+ * the plain JS operator, and the studio authors the literal — so the normal
7
+ * shape, `{">=": [{"var": "daysSinceInstall"}, 3]}`, coerces numerically
8
+ * (`"3" >= 3` is `true`) and behaves as an author expects. The case to know
9
+ * about is a filter whose literal is itself a STRING: `{">": [{"var":"day"}, "9"]}`
10
+ * compares lexicographically, so `"10"` is NOT greater than `"9"`. That is a
11
+ * property of the querystring wire format rather than of this function, but
12
+ * numbers being a first-class property type makes it much easier to reach.
13
+ */
14
+ export declare const serializeUserPropertyValue: (value: UserPropertyValue) => string;
15
+ /** The property map as the client's `userDefinedParams`. */
16
+ export declare const toQueryParams: (properties: UserProperties) => Record<string, string>;
17
+ /**
18
+ * A short, stable fingerprint of the resolved params, used to SCOPE the
19
+ * AsyncStorage cache keys (`infra/queries/cacheKey.ts`).
20
+ *
21
+ * Sorted by key, because the same logical params arrive in different insertion
22
+ * orders depending on whether they came from disk or from a fresh merge — an
23
+ * unsorted hash would make that a guaranteed spurious cache miss on every
24
+ * launch.
25
+ *
26
+ * `key=value;` per pair rather than bare concatenation, so `{ab:"c"}` and
27
+ * `{a:"bc"}` cannot collide.
28
+ *
29
+ * Returns `""` for an empty map. That is load-bearing: it makes the cache key of
30
+ * a host sending no params byte-identical to the pre-scoping key, so shipping
31
+ * this does not invalidate every existing install's cache.
32
+ *
33
+ * djb2 — this addresses accidental collision between one app's own param sets,
34
+ * not an adversary, and a crypto hash would mean pulling in a dependency to name
35
+ * a cache entry.
36
+ */
37
+ export declare const paramsHash: (params: Record<string, string>) => string;
38
+ //# sourceMappingURL=serialize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serialize.d.ts","sourceRoot":"","sources":["../../src/userProperties/serialize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEjE;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,0BAA0B,GAAI,OAAO,iBAAiB,KAAG,MAIrE,CAAC;AAEF,4DAA4D;AAC5D,eAAO,MAAM,aAAa,GAAI,YAAY,cAAc,KAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAM/E,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,UAAU,GAAI,QAAQ,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAAG,MAW3D,CAAC"}
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.paramsHash = exports.toQueryParams = exports.serializeUserPropertyValue = void 0;
4
+ /**
5
+ * A property value as it crosses the wire.
6
+ *
7
+ * Note how this interacts with a studio audience filter. `json-logic-js` applies
8
+ * the plain JS operator, and the studio authors the literal — so the normal
9
+ * shape, `{">=": [{"var": "daysSinceInstall"}, 3]}`, coerces numerically
10
+ * (`"3" >= 3` is `true`) and behaves as an author expects. The case to know
11
+ * about is a filter whose literal is itself a STRING: `{">": [{"var":"day"}, "9"]}`
12
+ * compares lexicographically, so `"10"` is NOT greater than `"9"`. That is a
13
+ * property of the querystring wire format rather than of this function, but
14
+ * numbers being a first-class property type makes it much easier to reach.
15
+ */
16
+ const serializeUserPropertyValue = (value) => {
17
+ if (typeof value === "number")
18
+ return String(value);
19
+ if (typeof value === "boolean")
20
+ return value ? "true" : "false";
21
+ return value;
22
+ };
23
+ exports.serializeUserPropertyValue = serializeUserPropertyValue;
24
+ /** The property map as the client's `userDefinedParams`. */
25
+ const toQueryParams = (properties) => {
26
+ const out = {};
27
+ for (const key of Object.keys(properties)) {
28
+ out[key] = (0, exports.serializeUserPropertyValue)(properties[key]);
29
+ }
30
+ return out;
31
+ };
32
+ exports.toQueryParams = toQueryParams;
33
+ /**
34
+ * A short, stable fingerprint of the resolved params, used to SCOPE the
35
+ * AsyncStorage cache keys (`infra/queries/cacheKey.ts`).
36
+ *
37
+ * Sorted by key, because the same logical params arrive in different insertion
38
+ * orders depending on whether they came from disk or from a fresh merge — an
39
+ * unsorted hash would make that a guaranteed spurious cache miss on every
40
+ * launch.
41
+ *
42
+ * `key=value;` per pair rather than bare concatenation, so `{ab:"c"}` and
43
+ * `{a:"bc"}` cannot collide.
44
+ *
45
+ * Returns `""` for an empty map. That is load-bearing: it makes the cache key of
46
+ * a host sending no params byte-identical to the pre-scoping key, so shipping
47
+ * this does not invalidate every existing install's cache.
48
+ *
49
+ * djb2 — this addresses accidental collision between one app's own param sets,
50
+ * not an adversary, and a crypto hash would mean pulling in a dependency to name
51
+ * a cache entry.
52
+ */
53
+ const paramsHash = (params) => {
54
+ const keys = Object.keys(params).sort();
55
+ if (keys.length === 0)
56
+ return "";
57
+ let hash = 5381;
58
+ for (const key of keys) {
59
+ const pair = `${key}=${params[key]};`;
60
+ for (let i = 0; i < pair.length; i++) {
61
+ hash = ((hash * 33) ^ pair.charCodeAt(i)) >>> 0;
62
+ }
63
+ }
64
+ return hash.toString(16).padStart(8, "0");
65
+ };
66
+ exports.paramsHash = paramsHash;
67
+ //# sourceMappingURL=serialize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serialize.js","sourceRoot":"","sources":["../../src/userProperties/serialize.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;GAWG;AACI,MAAM,0BAA0B,GAAG,CAAC,KAAwB,EAAU,EAAE;IAC7E,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACpD,IAAI,OAAO,KAAK,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;IAChE,OAAO,KAAK,CAAC;AACf,CAAC,CAAC;AAJW,QAAA,0BAA0B,8BAIrC;AAEF,4DAA4D;AACrD,MAAM,aAAa,GAAG,CAAC,UAA0B,EAA0B,EAAE;IAClF,MAAM,GAAG,GAA2B,EAAE,CAAC;IACvC,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QAC1C,GAAG,CAAC,GAAG,CAAC,GAAG,IAAA,kCAA0B,EAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC;IACzD,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC,CAAC;AANW,QAAA,aAAa,iBAMxB;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACI,MAAM,UAAU,GAAG,CAAC,MAA8B,EAAU,EAAE;IACnE,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;IACxC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IACjC,IAAI,IAAI,GAAG,IAAI,CAAC;IAChB,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,MAAM,IAAI,GAAG,GAAG,GAAG,IAAI,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC;QACtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACrC,IAAI,GAAG,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC,CAAC;AAXW,QAAA,UAAU,cAWrB"}
@@ -0,0 +1,63 @@
1
+ import type { UserProperties, UserPropertyPatch } from "./types";
2
+ /**
3
+ * The slice of AsyncStorage this needs, injected so the store is testable
4
+ * without mocking a module.
5
+ */
6
+ export type UserPropertyStorage = {
7
+ getItem: (key: string) => Promise<string | null>;
8
+ setItem: (key: string, value: string) => Promise<void>;
9
+ removeItem: (key: string) => Promise<void>;
10
+ };
11
+ /**
12
+ * ONE constant, deliberately not namespaced by `client.options.cacheKey` the way
13
+ * the payload caches are. `cacheKey` exists to pin a payload VERSION; user
14
+ * properties describe the USER, which is orthogonal. Deriving this from
15
+ * `cacheKey` would also force the store to learn about a client before it could
16
+ * hydrate, reintroducing the ordering problem hydration exists to remove.
17
+ *
18
+ * It also deliberately does NOT start with `rocapine-onboarding` or
19
+ * `rocapine-paywalls`, the two prefixes `OnboardingStudioClient.clearCache`
20
+ * scans: clearing a payload cache must not forget who the user is.
21
+ */
22
+ export declare const USER_PROPERTIES_STORAGE_KEY = "rocapine-user-properties";
23
+ export type UserPropertySnapshot = {
24
+ properties: UserProperties;
25
+ status: "hydrating" | "ready";
26
+ };
27
+ export type UserPropertyStore = {
28
+ get: () => UserProperties;
29
+ set: (patch: UserPropertyPatch) => void;
30
+ remove: (key: string) => void;
31
+ reset: () => void;
32
+ getSnapshot: () => UserPropertySnapshot;
33
+ subscribe: (listener: () => void) => () => void;
34
+ ensureHydrated: () => Promise<void>;
35
+ };
36
+ /**
37
+ * The mutable, persisted user-property map that feeds audience resolution.
38
+ *
39
+ * A module singleton (see `userProperties` below) rather than a provider +
40
+ * context, which is what every other piece of state in this package uses. The
41
+ * departure is deliberate and is the reason the feature exists: properties get
42
+ * set from a login handler, an analytics service, a push-token callback — code
43
+ * that is not a component and cannot call a hook. Superwall's own
44
+ * `setUserAttributes` is a singleton for the same reason.
45
+ *
46
+ * It also REMOVES a source of truth rather than adding one. With
47
+ * `customAudienceParams` passed separately to `OnboardingProvider` and
48
+ * `PaywallProvider`, an onboarding audience and a paywall audience can disagree
49
+ * about the same user. One store makes that impossible.
50
+ *
51
+ * Storage is injected so the whole thing is testable as a plain object.
52
+ */
53
+ export declare const createUserPropertyStore: (storage: UserPropertyStorage) => UserPropertyStore;
54
+ /**
55
+ * The process-wide store.
56
+ *
57
+ * INTERNAL: hosts reach this through `OnboardingStudio` (`setUserProperty`,
58
+ * `reset`, …) and `useUserProperties()`, never directly. Keeping one public
59
+ * front door means a host cannot half-use the facade and half-use the store, and
60
+ * leaves this module free to change shape.
61
+ */
62
+ export declare const userPropertyStore: UserPropertyStore;
63
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/userProperties/store.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEjE;;;GAGG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAChC,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACjD,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACvD,UAAU,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5C,CAAC;AAEF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,2BAA2B,6BAA6B,CAAC;AAEtE,MAAM,MAAM,oBAAoB,GAAG;IACjC,UAAU,EAAE,cAAc,CAAC;IAC3B,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC;CAC/B,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,GAAG,EAAE,MAAM,cAAc,CAAC;IAC1B,GAAG,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,CAAC;IACxC,MAAM,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAC9B,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,WAAW,EAAE,MAAM,oBAAoB,CAAC;IACxC,SAAS,EAAE,CAAC,QAAQ,EAAE,MAAM,IAAI,KAAK,MAAM,IAAI,CAAC;IAChD,cAAc,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACrC,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,uBAAuB,GAAI,SAAS,mBAAmB,KAAG,iBA2GtE,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,mBAAwC,CAAC"}
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.userPropertyStore = exports.createUserPropertyStore = exports.USER_PROPERTIES_STORAGE_KEY = void 0;
7
+ const async_storage_1 = __importDefault(require("@react-native-async-storage/async-storage"));
8
+ const applyPatch_1 = require("./applyPatch");
9
+ /**
10
+ * ONE constant, deliberately not namespaced by `client.options.cacheKey` the way
11
+ * the payload caches are. `cacheKey` exists to pin a payload VERSION; user
12
+ * properties describe the USER, which is orthogonal. Deriving this from
13
+ * `cacheKey` would also force the store to learn about a client before it could
14
+ * hydrate, reintroducing the ordering problem hydration exists to remove.
15
+ *
16
+ * It also deliberately does NOT start with `rocapine-onboarding` or
17
+ * `rocapine-paywalls`, the two prefixes `OnboardingStudioClient.clearCache`
18
+ * scans: clearing a payload cache must not forget who the user is.
19
+ */
20
+ exports.USER_PROPERTIES_STORAGE_KEY = "rocapine-user-properties";
21
+ /**
22
+ * The mutable, persisted user-property map that feeds audience resolution.
23
+ *
24
+ * A module singleton (see `userProperties` below) rather than a provider +
25
+ * context, which is what every other piece of state in this package uses. The
26
+ * departure is deliberate and is the reason the feature exists: properties get
27
+ * set from a login handler, an analytics service, a push-token callback — code
28
+ * that is not a component and cannot call a hook. Superwall's own
29
+ * `setUserAttributes` is a singleton for the same reason.
30
+ *
31
+ * It also REMOVES a source of truth rather than adding one. With
32
+ * `customAudienceParams` passed separately to `OnboardingProvider` and
33
+ * `PaywallProvider`, an onboarding audience and a paywall audience can disagree
34
+ * about the same user. One store makes that impossible.
35
+ *
36
+ * Storage is injected so the whole thing is testable as a plain object.
37
+ */
38
+ const createUserPropertyStore = (storage) => {
39
+ let properties = {};
40
+ let status = "hydrating";
41
+ let snapshot = { properties, status };
42
+ const listeners = new Set();
43
+ let hydration = null;
44
+ let writeScheduled = false;
45
+ // A fresh object per change, so `useSyncExternalStore` can compare snapshots
46
+ // by identity — and the SAME object between changes, or React would re-render
47
+ // on every check.
48
+ const publish = () => {
49
+ snapshot = { properties, status };
50
+ for (const listener of listeners)
51
+ listener();
52
+ };
53
+ // Coalesced: a burst of `set` calls in one tick costs one write. Skipped
54
+ // entirely while hydrating — writing then would persist a map that has not yet
55
+ // been merged with what is already on disk, i.e. silently delete properties
56
+ // the host set on a previous launch.
57
+ const scheduleWrite = () => {
58
+ if (status !== "ready" || writeScheduled)
59
+ return;
60
+ writeScheduled = true;
61
+ setTimeout(() => {
62
+ writeScheduled = false;
63
+ void storage.setItem(exports.USER_PROPERTIES_STORAGE_KEY, JSON.stringify(properties)).catch((error) => {
64
+ // The in-memory map stays authoritative: a failed write costs
65
+ // persistence across launches, not correctness in this one.
66
+ console.warn("[user-properties] Failed to persist:", error);
67
+ });
68
+ }, 0);
69
+ };
70
+ const commit = (next, warnings) => {
71
+ for (const warning of warnings)
72
+ console.warn(warning);
73
+ if (next === properties)
74
+ return;
75
+ properties = next;
76
+ publish();
77
+ scheduleWrite();
78
+ };
79
+ return {
80
+ get: () => properties,
81
+ set: (patch) => {
82
+ const { next, warnings } = (0, applyPatch_1.applyUserPropertyPatch)(properties, patch);
83
+ commit(next, warnings);
84
+ },
85
+ remove: (key) => {
86
+ const { next, warnings } = (0, applyPatch_1.applyUserPropertyPatch)(properties, { [key]: null });
87
+ commit(next, warnings);
88
+ },
89
+ reset: () => {
90
+ if (Object.keys(properties).length > 0) {
91
+ properties = {};
92
+ publish();
93
+ }
94
+ void storage.removeItem(exports.USER_PROPERTIES_STORAGE_KEY).catch((error) => {
95
+ console.warn("[user-properties] Failed to clear persisted properties:", error);
96
+ });
97
+ },
98
+ getSnapshot: () => snapshot,
99
+ subscribe: (listener) => {
100
+ listeners.add(listener);
101
+ return () => void listeners.delete(listener);
102
+ },
103
+ // Memoized: several providers await this on mount and it must read the disk
104
+ // once. Never rejects — a store that cannot hydrate must still let the app
105
+ // fetch a catalog, so a failure degrades to "no persisted properties".
106
+ ensureHydrated: () => {
107
+ if (hydration)
108
+ return hydration;
109
+ hydration = (async () => {
110
+ let persisted = {};
111
+ try {
112
+ const raw = await storage.getItem(exports.USER_PROPERTIES_STORAGE_KEY);
113
+ if (raw) {
114
+ const parsed = JSON.parse(raw);
115
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
116
+ // Through the same validation as a live `set` — defence in depth
117
+ // against a payload written by an older version or hand-edited.
118
+ // Warnings are dropped rather than logged: `set` already refused
119
+ // these values when they were first written, so anything caught
120
+ // here cannot occur in a normally-produced payload, and warning
121
+ // on every launch about it would be noise.
122
+ persisted = (0, applyPatch_1.applyUserPropertyPatch)({}, parsed).next;
123
+ }
124
+ }
125
+ }
126
+ catch (error) {
127
+ console.warn("[user-properties] Failed to hydrate, continuing empty:", error);
128
+ }
129
+ // Disk UNDER memory: anything the host set while hydration was in flight
130
+ // is newer than what was on disk and must win.
131
+ properties = Object.assign(Object.assign({}, persisted), properties);
132
+ status = "ready";
133
+ publish();
134
+ // Persist the merged result if the host wrote during hydration, which
135
+ // `scheduleWrite` refused to do while status was "hydrating".
136
+ if (Object.keys(properties).length > 0)
137
+ scheduleWrite();
138
+ })();
139
+ return hydration;
140
+ },
141
+ };
142
+ };
143
+ exports.createUserPropertyStore = createUserPropertyStore;
144
+ /**
145
+ * The process-wide store.
146
+ *
147
+ * INTERNAL: hosts reach this through `OnboardingStudio` (`setUserProperty`,
148
+ * `reset`, …) and `useUserProperties()`, never directly. Keeping one public
149
+ * front door means a host cannot half-use the facade and half-use the store, and
150
+ * leaves this module free to change shape.
151
+ */
152
+ exports.userPropertyStore = (0, exports.createUserPropertyStore)(async_storage_1.default);
153
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/userProperties/store.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The value types a user property may hold.
3
+ *
4
+ * Deliberately narrower than `customAudienceParams`' `Record<string, any>`,
5
+ * which this store supersedes as the place runtime targeting values live.
6
+ * Everything reaches the server as a STRING (the client builds a
7
+ * `URLSearchParams`; the edge function reads
8
+ * `Object.fromEntries(url.searchParams.entries())`), so a value type that
9
+ * cannot be stringified unambiguously has no meaning on the wire — see
10
+ * `serialize.ts`.
11
+ */
12
+ export type UserPropertyValue = string | number | boolean;
13
+ /** The resolved property map. Always fully valid — invalid input never lands here. */
14
+ export type UserProperties = Record<string, UserPropertyValue>;
15
+ /**
16
+ * What `set` accepts. `null`/`undefined` for a key DELETES it, which is both
17
+ * how Superwall's attribute API behaves and what a caller reaching for "unset
18
+ * this" writes without thinking about it.
19
+ */
20
+ export type UserPropertyPatch = Record<string, UserPropertyValue | null | undefined>;
21
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/userProperties/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AAE1D,sFAAsF;AACtF,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;AAE/D;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,iBAAiB,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC"}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/userProperties/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,20 @@
1
+ import type { UserPropertySnapshot } from "./store";
2
+ /**
3
+ * Read the user properties `OnboardingStudio` holds.
4
+ *
5
+ * The read path for React; the WRITE path is `OnboardingStudio.setUserProperty`
6
+ * / `setUserProperties`, which is callable from anywhere — a login handler, an
7
+ * analytics service — precisely because it is not a hook.
8
+ *
9
+ * `useSyncExternalStore` rather than a context: the store is process-wide so
10
+ * non-React code can write to it, and this is the supported way to read an
11
+ * external mutable source without tearing.
12
+ *
13
+ * Hydration is kicked off HERE as well as in `OnboardingStudio.init`, so a
14
+ * provider that calls this is gated correctly even if the host never called
15
+ * `init` (passing a `client` prop instead). `ensureHydrated` is memoized, so
16
+ * calling it from a render body is safe: every call after the first returns the
17
+ * same promise and touches no storage.
18
+ */
19
+ export declare const useUserProperties: () => UserPropertySnapshot;
20
+ //# sourceMappingURL=useUserProperties.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useUserProperties.d.ts","sourceRoot":"","sources":["../../src/userProperties/useUserProperties.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAEpD;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,iBAAiB,QAAO,oBAIpC,CAAC"}
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useUserProperties = void 0;
4
+ const react_1 = require("react");
5
+ const store_1 = require("./store");
6
+ /**
7
+ * Read the user properties `OnboardingStudio` holds.
8
+ *
9
+ * The read path for React; the WRITE path is `OnboardingStudio.setUserProperty`
10
+ * / `setUserProperties`, which is callable from anywhere — a login handler, an
11
+ * analytics service — precisely because it is not a hook.
12
+ *
13
+ * `useSyncExternalStore` rather than a context: the store is process-wide so
14
+ * non-React code can write to it, and this is the supported way to read an
15
+ * external mutable source without tearing.
16
+ *
17
+ * Hydration is kicked off HERE as well as in `OnboardingStudio.init`, so a
18
+ * provider that calls this is gated correctly even if the host never called
19
+ * `init` (passing a `client` prop instead). `ensureHydrated` is memoized, so
20
+ * calling it from a render body is safe: every call after the first returns the
21
+ * same promise and touches no storage.
22
+ */
23
+ const useUserProperties = () => {
24
+ const snapshot = (0, react_1.useSyncExternalStore)(store_1.userPropertyStore.subscribe, store_1.userPropertyStore.getSnapshot);
25
+ if (snapshot.status === "hydrating")
26
+ void store_1.userPropertyStore.ensureHydrated();
27
+ return snapshot;
28
+ };
29
+ exports.useUserProperties = useUserProperties;
30
+ //# sourceMappingURL=useUserProperties.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useUserProperties.js","sourceRoot":"","sources":["../../src/userProperties/useUserProperties.ts"],"names":[],"mappings":";;;AAAA,iCAA6C;AAC7C,mCAA4C;AAG5C;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,iBAAiB,GAAG,GAAyB,EAAE;IAC1D,MAAM,QAAQ,GAAG,IAAA,4BAAoB,EAAC,yBAAiB,CAAC,SAAS,EAAE,yBAAiB,CAAC,WAAW,CAAC,CAAC;IAClG,IAAI,QAAQ,CAAC,MAAM,KAAK,WAAW;QAAE,KAAK,yBAAiB,CAAC,cAAc,EAAE,CAAC;IAC7E,OAAO,QAAQ,CAAC;AAClB,CAAC,CAAC;AAJW,QAAA,iBAAiB,qBAI5B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rocapine/react-native-onboarding",
3
- "version": "1.72.0",
3
+ "version": "1.74.0",
4
4
  "description": "Headless React Native SDK for Rocapine Onboarding Studio - Data fetching, state management, and hooks",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -0,0 +1,147 @@
1
+ import { OnboardingStudioClient } from "./OnboardingStudioClient";
2
+ import type { OnboardingStudioClientOptions } from "./types";
3
+ import { userPropertyStore } from "./userProperties/store";
4
+ import type { UserPropertyStore } from "./userProperties/store";
5
+ import type {
6
+ UserProperties,
7
+ UserPropertyPatch,
8
+ UserPropertyValue,
9
+ } from "./userProperties/types";
10
+
11
+ /**
12
+ * What `OnboardingStudio.init` takes: everything `new OnboardingStudioClient()`
13
+ * takes, plus the project id it takes positionally, plus optional initial user
14
+ * properties.
15
+ *
16
+ * `userProperties` here is a genuine convenience rather than sugar. Audience
17
+ * targeting is evaluated against the property map, and persisted properties are
18
+ * only hydrated from disk — so on a first-EVER install there is nothing to
19
+ * hydrate and the first catalog fetch matches the catch-all audience. Seeding at
20
+ * `init`, which runs before any provider mounts, is the only way to be targeted
21
+ * correctly on that first launch.
22
+ */
23
+ export type OnboardingStudioConfig = { projectId: string } & OnboardingStudioClientOptions & {
24
+ userProperties?: UserPropertyPatch;
25
+ };
26
+
27
+ export type OnboardingStudioFacade = {
28
+ /**
29
+ * Configure the SDK. Returns the client it built, so a host that needs
30
+ * `clearCache()` (or wants to pass it explicitly) can keep hold of it.
31
+ *
32
+ * Idempotent for an unchanged config — Fast Refresh re-runs module scope, and
33
+ * rebuilding the client there would orphan the one the providers already hold.
34
+ * A genuinely CHANGED config replaces the client and warns, because silently
35
+ * ignoring it would be worse than either alternative.
36
+ */
37
+ init: (config: OnboardingStudioConfig) => OnboardingStudioClient;
38
+ /** The configured client, or `null` before `init`. */
39
+ getClient: () => OnboardingStudioClient | null;
40
+ isInitialized: () => boolean;
41
+ /** Set one property. `null` deletes it. */
42
+ setUserProperty: (key: string, value: UserPropertyValue | null) => void;
43
+ /** Set several at once. Merges; a `null` value deletes that key. */
44
+ setUserProperties: (patch: UserPropertyPatch) => void;
45
+ removeUserProperty: (key: string) => void;
46
+ getUserProperties: () => UserProperties;
47
+ /**
48
+ * Forget the user: clears every user property, in memory and on disk. Call it
49
+ * on logout.
50
+ *
51
+ * Deliberately does NOT clear the payload cache or the configuration. Logging
52
+ * out should forget who someone is, not force a refetch of content that has
53
+ * not changed — `getClient()?.clearCache()` is right there if both are wanted.
54
+ */
55
+ reset: () => void;
56
+ };
57
+
58
+ /** Stable signature of a config, for the idempotency check in `init`. */
59
+ const configSignature = (projectId: string, options: Record<string, unknown>): string =>
60
+ `${projectId}::${JSON.stringify(options)}`;
61
+
62
+ /**
63
+ * The SDK's front door, in the shape the SDKs it sits alongside use
64
+ * (`Superwall.configure` / `Purchases.configure` / `amplitude.init`): one
65
+ * module-level object that owns configuration and user identity.
66
+ *
67
+ * A factory with the store injected, so its tests need a fake store rather than
68
+ * a module mock — the same reason `createUserPropertyStore` is a factory.
69
+ *
70
+ * `register`/`present` deliberately do NOT live here. Presenting needs the
71
+ * mounted provider's catalog and presentation state, so they stay on
72
+ * `usePaywall()`, where that state is reachable and where a call cannot be made
73
+ * before a provider exists.
74
+ */
75
+ export const createOnboardingStudio = (store: UserPropertyStore): OnboardingStudioFacade => {
76
+ let client: OnboardingStudioClient | null = null;
77
+ let signature: string | null = null;
78
+
79
+ return {
80
+ init: (config) => {
81
+ const { projectId, userProperties: initialProperties, ...options } = config;
82
+ const next = configSignature(projectId, options);
83
+
84
+ if (client && signature === next) {
85
+ // Same config: hand back the same client. Seeding the same properties
86
+ // again would be a no-op anyway (`applyUserPropertyPatch` returns the
87
+ // same object when nothing changed), so there is nothing else to do.
88
+ return client;
89
+ }
90
+
91
+ if (client) {
92
+ console.warn(
93
+ `[onboarding-studio] init() was called again with a DIFFERENT config ` +
94
+ `(projectId "${projectId}"). The previous client has been replaced. ` +
95
+ "Providers already holding the old client keep using it until they " +
96
+ "re-render — call init() once, at module scope."
97
+ );
98
+ }
99
+
100
+ client = new OnboardingStudioClient(projectId, options);
101
+ signature = next;
102
+
103
+ // Before hydration on purpose: the store merges disk UNDER memory, so a
104
+ // property the host states here beats a stale one from a previous launch.
105
+ if (initialProperties) store.set(initialProperties);
106
+ // Start reading the persisted map now rather than at the first provider
107
+ // mount, so it is ready before anything queries.
108
+ void store.ensureHydrated();
109
+
110
+ return client;
111
+ },
112
+
113
+ getClient: () => client,
114
+ isInitialized: () => client !== null,
115
+
116
+ setUserProperty: (key, value) => store.set({ [key]: value }),
117
+ setUserProperties: (patch) => store.set(patch),
118
+ removeUserProperty: (key) => store.remove(key),
119
+ getUserProperties: () => store.get(),
120
+ reset: () => store.reset(),
121
+ };
122
+ };
123
+
124
+ /** The facade every host uses. */
125
+ export const OnboardingStudio = createOnboardingStudio(userPropertyStore);
126
+
127
+ /**
128
+ * Which client a provider should use: an explicit `client` prop wins, otherwise
129
+ * the one `OnboardingStudio.init()` built.
130
+ *
131
+ * The prop keeps winning so every host that already passes one is untouched by
132
+ * `init` existing.
133
+ */
134
+ export const resolveProviderClient = (
135
+ prop: OnboardingStudioClient | undefined,
136
+ fromStudio: OnboardingStudioClient | null
137
+ ): OnboardingStudioClient | null => prop ?? fromStudio;
138
+
139
+ /**
140
+ * Shared by both providers, because a host hitting this has exactly two fixes
141
+ * and should be told both rather than left to guess which one this provider
142
+ * wanted.
143
+ */
144
+ export const MISSING_CLIENT_MESSAGE =
145
+ "[onboarding-studio] No client. Either call OnboardingStudio.init({ projectId }) " +
146
+ "once at module scope, or pass a `client` prop built with " +
147
+ "`new OnboardingStudioClient(projectId, options)`.";