@joryio/react-native-sdk 1.4.0-beta.2 → 1.4.0-beta.4

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/src/index.ts CHANGED
@@ -1,7 +1,19 @@
1
1
  import { NativeModules, NativeEventEmitter, Platform } from 'react-native';
2
+ import * as ReactNative from 'react-native';
3
+ import * as React from 'react';
2
4
 
3
5
  const { JoryioModule } = NativeModules;
4
6
 
7
+ /**
8
+ * This package's version - the same number every Joryio SDK carries
9
+ * (sdk-version-parity.spec.ts pins it; the release tooling rewrites it).
10
+ * Handed to the native SDK at initialize() as `sdkWrapperVersion`, which
11
+ * sends it on every request as `X-Joryio-SDK-Wrapper-Version` next to
12
+ * `X-Joryio-SDK-Wrapper: react-native` (D427), so the dashboard shows the
13
+ * version of THIS package, the one the app upgrades.
14
+ */
15
+ export const SDK_VERSION = '1.4.0';
16
+
5
17
  /**
6
18
  * Mirrors the backend's SUBSCRIPTION_CHANNELS and the web SDK. Five, including
7
19
  * viber - it was added to the backend and to no SDK.
@@ -138,6 +150,19 @@ export interface JoryioConfig {
138
150
  */
139
151
  holdInAppMessagesForHandler?: boolean;
140
152
 
153
+ /**
154
+ * iOS only (default false): an https link from Joryio content - an in-app
155
+ * message, a placement, a card, a push - whose host is one of your app's
156
+ * associated domains (`applinks:` entries, `*.shop.com` included) goes to
157
+ * your app's own universal-link handling (`scene(_:continue:)` /
158
+ * `application(_:continue:restorationHandler:)`) instead of Safari. With
159
+ * React Native that usually means the `Linking` 'url' event. Ignored on
160
+ * Android, which routes verified App Links to the app itself. A handler set
161
+ * with {@link JoryioSDK.setLinkHandler} runs first. Same option on iOS
162
+ * (`JoryioConfig.forwardUniversalLinks`) and Unity.
163
+ */
164
+ forwardUniversalLinks?: boolean;
165
+
141
166
  /**
142
167
  * Tracking consent at start-up. Same option and values as the web, iOS,
143
168
  * Android and Unity SDKs.
@@ -545,6 +570,13 @@ function finiteProperties(caller: string, properties: Record<string, unknown>):
545
570
  * expect - was a fatal JS error in a release build and skipped every other
546
571
  * listener of the same event. A returned promise that rejects is caught too.
547
572
  */
573
+ /** A flag key must be a non-empty string; otherwise the getter answers its default. */
574
+ function flagKeyOk(method: string, key: unknown): key is string {
575
+ if (typeof key === 'string' && key.length > 0) return true;
576
+ warn(`${method}() needs a flag key; the default is returned.`);
577
+ return false;
578
+ }
579
+
548
580
  function guardedCallback<T>(name: string, callback: (event: T) => unknown): (event: T) => void {
549
581
  const report = (err: unknown) => {
550
582
  // eslint-disable-next-line no-console
@@ -604,6 +636,397 @@ export const MAX_PRE_INIT_CALLS = 1000;
604
636
  */
605
637
  export const IN_APP_DISPLAY_DWELL_MS = 1000;
606
638
 
639
+ // ── Placements (docs/PLACEMENTS_PLAN.md, D444) ──────────────────────────────
640
+
641
+ /** Share of an item that must be on screen for it to count as seen - the same on every Joryio SDK. */
642
+ export const PLACEMENT_VIEWABLE_FRACTION = 0.5;
643
+ /** A placement key is fetched from the network at most once per this many seconds - the same on every Joryio SDK. */
644
+ export const PLACEMENT_MIN_REFRESH_SECONDS = 30;
645
+
646
+ /**
647
+ * A drawn product card's tap is reported as `clicked` with the elementId
648
+ * `product:<product id>` (at most 128 characters) - the same on every Joryio SDK.
649
+ */
650
+ export const PLACEMENT_PRODUCT_ELEMENT_PREFIX = 'product:';
651
+ /** Width of a drawn product card when the app does not set one (dp / points) - the same on every Joryio SDK. */
652
+ export const PLACEMENT_PRODUCT_CARD_WIDTH = 160;
653
+ /** The elementId a product card's click is reported with - use it with `markClicked` when you draw the cards yourself. */
654
+ export function placementProductElementId(productId: string): string {
655
+ return `${PLACEMENT_PRODUCT_ELEMENT_PREFIX}${productId}`.slice(0, 128);
656
+ }
657
+
658
+ export type PlacementEmptyBehavior = 'collapse' | 'keep_space';
659
+
660
+ export interface PlacementContent {
661
+ kind: 'native' | 'html';
662
+ title?: string;
663
+ body?: string;
664
+ imageUrl?: string;
665
+ buttons?: Array<{ id: string; text: string; action: string; url?: string }>;
666
+ closeButton?: boolean;
667
+ html?: string;
668
+ css?: string;
669
+ }
670
+
671
+ /** A product card of a recommendation placement item (D444 Phase 2b). Same names on all five SDKs. */
672
+ export interface PlacementProduct {
673
+ id: string;
674
+ title: string | null;
675
+ price: string | null;
676
+ compareAtPrice: string | null;
677
+ discountPercent: number | null;
678
+ imageUrl: string | null;
679
+ url: string | null;
680
+ }
681
+
682
+ /** An item to draw, with the calls that report what the person did with it. */
683
+ export interface PlacementItem {
684
+ id: string;
685
+ variantId?: string | null;
686
+ kind: 'native' | 'html' | 'data';
687
+ data: Record<string, string | number | boolean | null>;
688
+ content?: PlacementContent | null;
689
+ /** Products picked for the person by a recommendation model; [] when the item has none. Draw them as cards. */
690
+ products: PlacementProduct[];
691
+ /** A viewable impression (your UI drew it): once at least half of it was on screen for IN_APP_DISPLAY_DWELL_MS. */
692
+ markDisplayed(): void;
693
+ markClicked(elementId?: string): void;
694
+ markDismissed(): void;
695
+ }
696
+
697
+ export interface Placement {
698
+ placementKey: string;
699
+ items: PlacementItem[];
700
+ isControl: boolean;
701
+ emptyBehavior: PlacementEmptyBehavior;
702
+ maxItems: number;
703
+ ttlSeconds: number;
704
+ /** For a held-out person (`isControl`): the empty spot was on screen. */
705
+ markDisplayed(): void;
706
+ }
707
+
708
+ /** The bridge's product cards, defensively typed: an entry without an id is dropped. */
709
+ function toProducts(raw: unknown): PlacementProduct[] {
710
+ if (!Array.isArray(raw)) return [];
711
+ const str = (v: unknown) => (typeof v === 'string' ? v : null);
712
+ return raw
713
+ .filter((p: any) => p && typeof p === 'object' && (typeof p.id === 'string' || typeof p.id === 'number'))
714
+ .map((p: any) => ({
715
+ id: String(p.id),
716
+ title: str(p.title),
717
+ price: str(p.price),
718
+ compareAtPrice: str(p.compareAtPrice),
719
+ discountPercent: typeof p.discountPercent === 'number' ? p.discountPercent : null,
720
+ imageUrl: str(p.imageUrl),
721
+ url: str(p.url),
722
+ }));
723
+ }
724
+
725
+ /** Native JSON (Placement.toJson on iOS / Android) -> objects whose mark* calls go back to native. */
726
+ function toPlacements(json: unknown): Record<string, Placement> {
727
+ let raw: Record<string, any> = {};
728
+ try {
729
+ raw = typeof json === 'string' ? JSON.parse(json) : (json as Record<string, any>) || {};
730
+ } catch {
731
+ raw = {};
732
+ }
733
+ const mark = (key: string, itemId: string | null, action: string, elementId?: string) => {
734
+ JoryioModule?.markPlacement?.(key, itemId, action, elementId ?? null);
735
+ };
736
+ const out: Record<string, Placement> = {};
737
+ for (const [key, p] of Object.entries(raw || {})) {
738
+ if (!p || typeof p !== 'object') continue;
739
+ out[key] = {
740
+ placementKey: p.placementKey || key,
741
+ isControl: p.isControl === true,
742
+ emptyBehavior: p.emptyBehavior === 'keep_space' ? 'keep_space' : 'collapse',
743
+ maxItems: typeof p.maxItems === 'number' ? p.maxItems : 1,
744
+ ttlSeconds: typeof p.ttlSeconds === 'number' ? p.ttlSeconds : 300,
745
+ items: (Array.isArray(p.items) ? p.items : []).map((i: any) => ({
746
+ id: String(i.id),
747
+ variantId: i.variantId ?? null,
748
+ kind: i.kind,
749
+ data: i.data || {},
750
+ content: i.content ?? null,
751
+ products: toProducts(i.products),
752
+ markDisplayed: () => mark(key, String(i.id), 'displayed'),
753
+ markClicked: (elementId?: string) => mark(key, String(i.id), 'clicked', elementId),
754
+ markDismissed: () => mark(key, String(i.id), 'dismissed'),
755
+ })),
756
+ markDisplayed: () => mark(key, null, 'control'),
757
+ };
758
+ }
759
+ return out;
760
+ }
761
+
762
+ export interface JoryioPlacementProps {
763
+ placementKey: string;
764
+ style?: unknown;
765
+ /** After each draw: what was drawn and its height (0 when collapsed). */
766
+ onRender?: (info: { placementKey: string; itemCount: number; isControl: boolean; emptyBehavior: PlacementEmptyBehavior; height: number }) => void;
767
+ /**
768
+ * A `deep_link` button with an app link (`myapp://cart`) was tapped: route
769
+ * it. An http(s) link is opened by the native SDK instead, and any other
770
+ * scheme (javascript:, data:, intent:, ...) is refused - see isAppDeepLink.
771
+ * A handler set with setLinkHandler sees every link first; this one is
772
+ * called when it declines.
773
+ */
774
+ onDeepLink?: (url: string) => void;
775
+ /**
776
+ * Draw an item's recommended products as a horizontal row of product cards
777
+ * (image, title, price, optional button) - the native view does it. Default true.
778
+ */
779
+ showProducts?: boolean;
780
+ /** Label of a button on every product card; unset = no button (the whole card opens the product). */
781
+ productButtonText?: string;
782
+ /** Width of one product card in dp / points (default PLACEMENT_PRODUCT_CARD_WIDTH). */
783
+ productCardWidth?: number;
784
+ }
785
+
786
+ /** Schemes never opened nor handed to the app, whatever a link says (the backend's placement / card link rule). */
787
+ const REFUSED_LINK_SCHEMES = ['javascript', 'data', 'file', 'vbscript', 'blob', 'about', 'content', 'intent'];
788
+
789
+ /**
790
+ * An app deep link (`myapp://cart`) that may go to the app's own handler: a
791
+ * `scheme://` link whose scheme is not http(s) and not a refused one. The
792
+ * native PlacementView applies the same rule before a link reaches JS; this
793
+ * layer checks again. The same rule on every Joryio SDK.
794
+ */
795
+ export function isAppDeepLink(url: unknown): boolean {
796
+ if (typeof url !== 'string') return false;
797
+ const m = /^([a-z][a-z0-9+.-]*):\/\/./i.exec(url.trim());
798
+ if (!m) return false;
799
+ const scheme = m[1].toLowerCase();
800
+ return scheme !== 'http' && scheme !== 'https' && !REFUSED_LINK_SCHEMES.includes(scheme);
801
+ }
802
+
803
+ /**
804
+ * Where a link the SDK is about to open came from. The same wire values on
805
+ * every Joryio SDK. `push` comes from iOS only: on Android the native SDK
806
+ * never opens a push link itself - your launcher activity receives it.
807
+ */
808
+ export type JoryioLinkSource = 'in_app' | 'placement' | 'card' | 'push';
809
+
810
+ /** A link the native SDK is about to open, handed to {@link JoryioSDK.setLinkHandler} first. */
811
+ export interface JoryioLink {
812
+ /** An http(s) link or an app deep link (`myapp://cart`); a push link may be another scheme the system opens. */
813
+ url: string;
814
+ source: JoryioLinkSource;
815
+ campaignId?: string;
816
+ placementKey?: string;
817
+ itemId?: string;
818
+ cardId?: string;
819
+ /** True for an app-scheme link, false for http(s). */
820
+ isAppDeepLink: boolean;
821
+ }
822
+
823
+ /**
824
+ * Return true (or a Promise of true) to take the link over, false to let the
825
+ * native SDK open it as it does without a handler. A Promise is how to decide
826
+ * later: the link waits for it.
827
+ */
828
+ export type JoryioLinkHandler = (link: JoryioLink) => boolean | Promise<boolean>;
829
+
830
+ const LINK_SOURCES: readonly JoryioLinkSource[] = ['in_app', 'placement', 'card', 'push'];
831
+
832
+ /** The `JoryioLink` event body as a JoryioLink, or null when it is not one. */
833
+ function toLink(e: any): JoryioLink | null {
834
+ if (!e || typeof e.url !== 'string' || !LINK_SOURCES.includes(e.source)) return null;
835
+ const link: JoryioLink = { url: e.url, source: e.source, isAppDeepLink: e.isAppDeepLink === true };
836
+ for (const key of ['campaignId', 'placementKey', 'itemId', 'cardId'] as const) {
837
+ if (typeof e[key] === 'string' && e[key]) link[key] = e[key];
838
+ }
839
+ return link;
840
+ }
841
+
842
+ let nativePlacementView: any = null;
843
+
844
+ /**
845
+ * `<JoryioPlacement placementKey="home_hero" />` - the native SDK's own
846
+ * PlacementView (iOS and Android): fetching, caching, viewability, the
847
+ * holdout and the reports are the native ones. The component sizes itself to
848
+ * the drawn content (0 when the placement collapses); a `style` height wins.
849
+ */
850
+ export function JoryioPlacement(props: JoryioPlacementProps): any {
851
+ const [height, setHeight] = React.useState(0);
852
+ if (!nativePlacementView) {
853
+ const requireNative = (ReactNative as any).requireNativeComponent;
854
+ if (typeof requireNative !== 'function') return null;
855
+ nativePlacementView = requireNative('JoryioPlacementView');
856
+ }
857
+ return React.createElement(nativePlacementView, {
858
+ placementKey: props.placementKey,
859
+ // Passed to the native PlacementView's properties of the same names.
860
+ showProducts: props.showProducts !== false,
861
+ productButtonText: typeof props.productButtonText === 'string' ? props.productButtonText : null,
862
+ productCardWidth:
863
+ typeof props.productCardWidth === 'number' && Number.isFinite(props.productCardWidth) && props.productCardWidth > 0
864
+ ? props.productCardWidth
865
+ : PLACEMENT_PRODUCT_CARD_WIDTH,
866
+ style: [{ height }, props.style],
867
+ onPlacementRender: (e: any) => {
868
+ const info = e?.nativeEvent || {};
869
+ setHeight(typeof info.height === 'number' ? info.height : 0);
870
+ props.onRender?.(info);
871
+ },
872
+ onPlacementDeepLink: (e: any) => {
873
+ const url = e?.nativeEvent?.url;
874
+ if (isAppDeepLink(url)) props.onDeepLink?.(url);
875
+ },
876
+ });
877
+ }
878
+
879
+ // ── Content cards (docs/PLACEMENTS_PLAN.md section 11, D444 Phase 3) ────────
880
+
881
+ /** The feed goes to the network at most once per this many seconds; extra calls coalesce - the same on every Joryio SDK. */
882
+ export const CARD_MIN_REFRESH_SECONDS = 30;
883
+ /** How long the feed is served from the device cache before it is asked for again - the same on every Joryio SDK. */
884
+ export const CARD_FEED_TTL_SECONDS = 300;
885
+
886
+ /**
887
+ * `server`: read / clicked / dismissed are kept per person on the server, the
888
+ * same on every device. `device`: an anonymous visitor - this device keeps
889
+ * what was read and dismissed (the native SDK does it).
890
+ */
891
+ export type CardStateScope = 'server' | 'device';
892
+
893
+ /** One card of the person's feed. */
894
+ export interface Card {
895
+ /** Stable id of this card for this person. */
896
+ id: string;
897
+ /** Campaign id, or `journey:<canvasId>:<nodeId>` for a journey card. */
898
+ campaignId: string;
899
+ variantId: string | null;
900
+ title: string | null;
901
+ body: string | null;
902
+ imageUrl: string | null;
903
+ /** Button label; null = no button (the whole card opens `url` when set). */
904
+ buttonText: string | null;
905
+ /** An http(s) URL or the app's own deep link; null = nothing to open. */
906
+ url: string | null;
907
+ pinned: boolean;
908
+ /** ISO 8601. */
909
+ createdAt: string;
910
+ /** ISO 8601, or null. */
911
+ expiresAt: string | null;
912
+ read: boolean;
913
+ clicked: boolean;
914
+ }
915
+
916
+ /** The person's feed (or one page of it). */
917
+ export interface CardFeed {
918
+ /** Pinned first, then newest first. */
919
+ cards: Card[];
920
+ /** Unread cards across the whole feed, not this page: the badge. */
921
+ unreadCount: number;
922
+ /** Pass to `getCards({ cursor })` for the next page; null on the last one. */
923
+ nextCursor: string | null;
924
+ stateScope: CardStateScope;
925
+ }
926
+
927
+ const EMPTY_CARD_FEED_JSON = '{"cards":[],"unreadCount":0,"nextCursor":null,"stateScope":"server"}';
928
+
929
+ const str = (v: unknown): string | null => (typeof v === 'string' ? v : null);
930
+
931
+ /** Native JSON (CardFeed.toJson on iOS / Android) -> a CardFeed. A bad answer is the empty feed. */
932
+ function toCardFeed(json: unknown): CardFeed {
933
+ let raw: any = null;
934
+ try {
935
+ raw = typeof json === 'string' ? JSON.parse(json) : json;
936
+ } catch {
937
+ raw = null;
938
+ }
939
+ if (!raw || typeof raw !== 'object') raw = {};
940
+ const cards: Card[] = (Array.isArray(raw.cards) ? raw.cards : [])
941
+ .filter((c: any) => c && typeof c === 'object' && typeof c.id === 'string')
942
+ .map((c: any) => ({
943
+ id: c.id,
944
+ campaignId: str(c.campaignId) ?? '',
945
+ variantId: str(c.variantId),
946
+ title: str(c.title),
947
+ body: str(c.body),
948
+ imageUrl: str(c.imageUrl),
949
+ buttonText: str(c.buttonText),
950
+ url: str(c.url),
951
+ pinned: c.pinned === true,
952
+ createdAt: str(c.createdAt) ?? '',
953
+ expiresAt: str(c.expiresAt),
954
+ read: c.read === true,
955
+ clicked: c.clicked === true,
956
+ }));
957
+ return {
958
+ cards,
959
+ unreadCount: typeof raw.unreadCount === 'number' && raw.unreadCount >= 0 ? raw.unreadCount : 0,
960
+ nextCursor: str(raw.nextCursor),
961
+ stateScope: raw.stateScope === 'device' ? 'device' : 'server',
962
+ };
963
+ }
964
+
965
+ /** A card or its id. */
966
+ const cardIdOf = (card: Card | string): string | null => {
967
+ const id = typeof card === 'string' ? card : card && typeof card === 'object' ? card.id : null;
968
+ return typeof id === 'string' && id.length > 0 ? id : null;
969
+ };
970
+
971
+ export interface JoryioCardFeedProps {
972
+ /** Give it a size (e.g. `{ flex: 1 }`, the default): the feed scrolls inside it. */
973
+ style?: unknown;
974
+ /** Shown when the feed is empty. Default "No messages yet". */
975
+ emptyText?: string;
976
+ /** The marker on a pinned card. Default "Pinned". */
977
+ pinnedLabel?: string;
978
+ /** The accessible label of the dismiss control. Default "Dismiss". */
979
+ dismissLabel?: string;
980
+ /** The accessible label of the unread dot. Default "Unread". */
981
+ unreadLabel?: string;
982
+ /**
983
+ * A card's url is an app deep link (`myapp://...`): route it in your app
984
+ * (the click is already reported). Without this only an http(s) link is
985
+ * opened; no other scheme is ever handed to the system.
986
+ */
987
+ onDeepLink?: (url: string, cardId: string) => void;
988
+ /** After each draw: how many cards were drawn, and the unread count. */
989
+ onRender?: (info: { cardCount: number; unreadCount: number }) => void;
990
+ }
991
+
992
+ let nativeCardFeedView: any = null;
993
+
994
+ /**
995
+ * `<JoryioCardFeed />` - the person's content cards as a plain scrolling list:
996
+ * the native SDK's own feed view (iOS CardFeedViewController, Android
997
+ * CardFeedView), so paging, the unread dot, the dismiss control, the
998
+ * viewed / read / clicked / dismissed reports (a card at least
999
+ * PLACEMENT_VIEWABLE_FRACTION on screen for IN_APP_DISPLAY_DWELL_MS is viewed
1000
+ * then read) and the link rule are the native ones. The look follows the
1001
+ * system theme, dark mode included.
1002
+ */
1003
+ export function JoryioCardFeed(props: JoryioCardFeedProps): any {
1004
+ if (!nativeCardFeedView) {
1005
+ const requireNative = (ReactNative as any).requireNativeComponent;
1006
+ if (typeof requireNative !== 'function') return null;
1007
+ nativeCardFeedView = requireNative('JoryioCardFeedView');
1008
+ }
1009
+ return React.createElement(nativeCardFeedView, {
1010
+ style: [{ flex: 1 }, props.style],
1011
+ emptyText: props.emptyText,
1012
+ pinnedLabel: props.pinnedLabel,
1013
+ dismissLabel: props.dismissLabel,
1014
+ unreadLabel: props.unreadLabel,
1015
+ onCardFeedRender: (e: any) => {
1016
+ const info = e?.nativeEvent || {};
1017
+ props.onRender?.({
1018
+ cardCount: typeof info.cardCount === 'number' ? info.cardCount : 0,
1019
+ unreadCount: typeof info.unreadCount === 'number' ? info.unreadCount : 0,
1020
+ });
1021
+ },
1022
+ onCardDeepLink: (e: any) => {
1023
+ const url = e?.nativeEvent?.url;
1024
+ const cardId = e?.nativeEvent?.cardId;
1025
+ if (typeof url === 'string') props.onDeepLink?.(url, typeof cardId === 'string' ? cardId : '');
1026
+ },
1027
+ });
1028
+ }
1029
+
607
1030
  /**
608
1031
  * What a held call is, which decides what a later privacy decision discards
609
1032
  * and what a full hold drops first.
@@ -780,6 +1203,14 @@ class JoryioSDK {
780
1203
  */
781
1204
  private _inAppHandedToJs = false;
782
1205
 
1206
+ private _placementListeners = 0;
1207
+
1208
+ private _cardListeners = 0;
1209
+
1210
+ private _linkHandler: JoryioLinkHandler | null = null;
1211
+
1212
+ private _linkSubscription: { remove: () => void } | null = null;
1213
+
783
1214
  constructor() {
784
1215
  this._ready = new Promise<void>((resolve) => {
785
1216
  this._markReady = resolve;
@@ -1273,6 +1704,8 @@ class JoryioSDK {
1273
1704
  if (forNative.trackingConsent === 'denied') this._initConfigDenied = true;
1274
1705
  if (forNative.optOut === true) this._initConfigOptedOut = true;
1275
1706
  }
1707
+ // The bridge names itself on every request (D427); not an app option.
1708
+ forNative.sdkWrapperVersion = SDK_VERSION;
1276
1709
  try {
1277
1710
  await JoryioModule.initialize(sdkKey, apiHost, forNative);
1278
1711
  } catch (e) {
@@ -2224,6 +2657,293 @@ class JoryioSDK {
2224
2657
  this._dispatch(() => JoryioModule.syncInAppCampaigns?.());
2225
2658
  }
2226
2659
 
2660
+ // ─── Feature flags (BACKLOG D446) ───────────────────────────────────────
2661
+ //
2662
+ // The native SDK holds the answer and logs exposures; these route to it.
2663
+ // The getters resolve at once with what the device holds - they never wait
2664
+ // for the network - and with the in-code default before initialize(), for a
2665
+ // flag Joryio did not send, for a value of another type, or without
2666
+ // tracking consent. A Promise because every native call crosses the bridge
2667
+ // asynchronously; the names and the wire are the same on all five SDKs.
2668
+
2669
+ /** A flag's value of any type, or `defaultValue`. The first read in a session logs an exposure. */
2670
+ getFlag<T = unknown>(key: string, defaultValue: T): Promise<T> {
2671
+ if (!flagKeyOk('getFlag', key)) return Promise.resolve(defaultValue);
2672
+ return this._query<{ value: T } | null>('getFlag', null, () => {
2673
+ return JoryioModule.getFlag(key, defaultValue ?? null);
2674
+ }).then(
2675
+ (r) => (r && typeof r === 'object' && 'value' in r ? (r.value as T) : defaultValue),
2676
+ );
2677
+ }
2678
+
2679
+ /** A boolean flag, or `defaultValue` (also for a flag of another type). */
2680
+ getBoolFlag(key: string, defaultValue: boolean): Promise<boolean> {
2681
+ if (!flagKeyOk('getBoolFlag', key)) return Promise.resolve(defaultValue);
2682
+ return this._query('getBoolFlag', defaultValue, () => {
2683
+ return JoryioModule.getBoolFlag(key, !!defaultValue);
2684
+ });
2685
+ }
2686
+
2687
+ /** A string flag, or `defaultValue`. */
2688
+ getStringFlag(key: string, defaultValue: string): Promise<string> {
2689
+ if (!flagKeyOk('getStringFlag', key)) return Promise.resolve(defaultValue);
2690
+ return this._query('getStringFlag', defaultValue, () => {
2691
+ return JoryioModule.getStringFlag(key, String(defaultValue ?? ''));
2692
+ });
2693
+ }
2694
+
2695
+ /** A number flag, or `defaultValue`. */
2696
+ getNumberFlag(key: string, defaultValue: number): Promise<number> {
2697
+ if (!flagKeyOk('getNumberFlag', key)) return Promise.resolve(defaultValue);
2698
+ return this._query('getNumberFlag', defaultValue, () => {
2699
+ return JoryioModule.getNumberFlag(key, Number(defaultValue));
2700
+ });
2701
+ }
2702
+
2703
+ /** A JSON flag (object, array or scalar), or `defaultValue`. */
2704
+ getJsonFlag<T = unknown>(key: string, defaultValue: T): Promise<T> {
2705
+ if (!flagKeyOk('getJsonFlag', key)) return Promise.resolve(defaultValue);
2706
+ return this._query<{ value: T } | null>('getJsonFlag', null, () => {
2707
+ return JoryioModule.getJsonFlag(key, defaultValue ?? null);
2708
+ }).then(
2709
+ (r) => (r && typeof r === 'object' && 'value' in r ? (r.value as T) : defaultValue),
2710
+ );
2711
+ }
2712
+
2713
+ /** Every flag held for this person, key -> value. Logs no exposure. */
2714
+ getAllFlags(): Promise<Record<string, unknown>> {
2715
+ return this._query<Record<string, unknown>>('getAllFlags', {}, () => {
2716
+ return JoryioModule.getAllFlags();
2717
+ });
2718
+ }
2719
+
2720
+ /** Ask the server now; resolves when the answer is in (or the request failed: the held flags stay). */
2721
+ refreshFlags(): Promise<void> {
2722
+ return this._query<void>('refreshFlags', undefined, () => {
2723
+ return JoryioModule.refreshFlags();
2724
+ }).then(() => undefined);
2725
+ }
2726
+
2727
+ /**
2728
+ * `callback(keys)` is called with the keys whose value changed. Returns an
2729
+ * unsubscribe function. Safe before initialize(): updates start once the
2730
+ * SDK runs.
2731
+ */
2732
+ onFlagsUpdated(callback: (keys: string[]) => unknown): () => void {
2733
+ if (typeof callback !== 'function') {
2734
+ warn('onFlagsUpdated() needs a callback function; ignored.');
2735
+ return () => {};
2736
+ }
2737
+ if (!isModuleAvailable || !emitter) return () => {};
2738
+ const guarded = guardedCallback<string[]>('onFlagsUpdated', callback);
2739
+ const subscription = emitter.addListener('JoryioFlagsUpdated', (event: unknown) => {
2740
+ const keys = (event as { keys?: unknown } | null)?.keys;
2741
+ guarded(Array.isArray(keys) ? keys.filter((k): k is string => typeof k === 'string') : []);
2742
+ });
2743
+ // One native subscription for the module, held until initialize() like
2744
+ // any control call; native ignores a second enable.
2745
+ this._dispatch(() => JoryioModule.enableFlagsUpdates?.());
2746
+ return () => subscription.remove();
2747
+ }
2748
+
2749
+ /**
2750
+ * The placements for `placementKeys`, to draw with your own components
2751
+ * (or use `<JoryioPlacement placementKey=... />`). Report with
2752
+ * `item.markDisplayed()` once at least half of it was on screen for
2753
+ * IN_APP_DISPLAY_DWELL_MS, `item.markClicked()`, `item.markDismissed()`,
2754
+ * and `placement.markDisplayed()` for a held-out person's empty spot.
2755
+ * Waits for initialize(); resolves `{}` without the native module.
2756
+ */
2757
+ getPlacements(placementKeys: string[]): Promise<Record<string, Placement>> {
2758
+ const keys = Array.isArray(placementKeys) ? placementKeys.filter((k) => typeof k === 'string') : [];
2759
+ // A read: waits for initialize() like the other queries.
2760
+ return this._query<string>('getPlacements', '{}', () => {
2761
+ return JoryioModule.getPlacements(keys);
2762
+ }).then(toPlacements);
2763
+ }
2764
+
2765
+ /** Ask the server again (all placements on screen when no keys). At most once per key per PLACEMENT_MIN_REFRESH_SECONDS. */
2766
+ refreshPlacements(placementKeys?: string[]): void {
2767
+ this._dispatch(() => JoryioModule.refreshPlacements?.(Array.isArray(placementKeys) ? placementKeys : null));
2768
+ }
2769
+
2770
+ /**
2771
+ * Called with the placements whose content changed. Returns an unsubscribe.
2772
+ * An app with its own push messaging handler should call
2773
+ * refreshPlacements() on a `jry_sync: "placements"` data message; the
2774
+ * native SDKs handle it themselves otherwise.
2775
+ */
2776
+ onPlacementsUpdated(callback: (placements: Record<string, Placement>) => unknown): () => void {
2777
+ if (typeof callback !== 'function' || !isModuleAvailable || !emitter) return () => {};
2778
+ const subscription = emitter.addListener('JoryioPlacementsUpdated', (e: any) => {
2779
+ try {
2780
+ callback(toPlacements(e?.json));
2781
+ } catch (error) {
2782
+ warn(`onPlacementsUpdated callback threw: ${String(error)}`);
2783
+ }
2784
+ });
2785
+ this._placementListeners += 1;
2786
+ this._dispatch(() => JoryioModule.enablePlacementsUpdates?.());
2787
+ let removed = false;
2788
+ return () => {
2789
+ if (removed) return;
2790
+ removed = true;
2791
+ subscription.remove();
2792
+ this._placementListeners = Math.max(0, this._placementListeners - 1);
2793
+ if (this._placementListeners === 0) this._dispatch(() => JoryioModule.disablePlacementsUpdates?.());
2794
+ };
2795
+ }
2796
+
2797
+ /**
2798
+ * The person's content cards - pinned first, newest first - with the unread
2799
+ * count for a badge, from the native SDK's cache for CARD_FEED_TTL_SECONDS.
2800
+ * Pass a feed's `nextCursor` as `{ cursor }` for the next page (the native
2801
+ * SDK adds it to the cached feed). Draw it with `<JoryioCardFeed />`, or
2802
+ * yourself and report with markCardViewed / markCardRead /
2803
+ * markCardClicked / dismissCard. Waits for initialize(); resolves the empty
2804
+ * feed without the native module.
2805
+ */
2806
+ getCards(options?: { cursor?: string | null }): Promise<CardFeed> {
2807
+ const cursor = typeof options?.cursor === 'string' && options.cursor.length > 0 ? options.cursor : null;
2808
+ // A read: waits for initialize() like the other queries.
2809
+ return this._query<string>('getCards', EMPTY_CARD_FEED_JSON, () => {
2810
+ return JoryioModule.getCards(cursor);
2811
+ }).then(toCardFeed);
2812
+ }
2813
+
2814
+ /**
2815
+ * Unread cards, from the native SDK's cache (never a network call): the
2816
+ * badge. A Promise here because every React Native read crosses the bridge;
2817
+ * the native SDKs answer synchronously.
2818
+ */
2819
+ getUnreadCardCount(): Promise<number> {
2820
+ return this._query<number>('getUnreadCardCount', 0, () => {
2821
+ return JoryioModule.getUnreadCardCount();
2822
+ }).then((n) => (typeof n === 'number' && n >= 0 ? n : 0));
2823
+ }
2824
+
2825
+ /** The card was on screen (`viewed`). Once per card; `<JoryioCardFeed />` does it itself. */
2826
+ markCardViewed(card: Card | string): void {
2827
+ const id = cardIdOf(card);
2828
+ if (id) this._dispatch(() => JoryioModule.markCardViewed?.(id), 'data');
2829
+ }
2830
+
2831
+ /** The person read the card (`read`): it stops counting as unread at once. */
2832
+ markCardRead(card: Card | string): void {
2833
+ const id = cardIdOf(card);
2834
+ if (id) this._dispatch(() => JoryioModule.markCardRead?.(id), 'data');
2835
+ }
2836
+
2837
+ /** The person tapped the card or its button (`clicked`, which also marks it read). Open its url yourself. */
2838
+ markCardClicked(card: Card | string): void {
2839
+ const id = cardIdOf(card);
2840
+ if (id) this._dispatch(() => JoryioModule.markCardClicked?.(id), 'data');
2841
+ }
2842
+
2843
+ /** The person removed the card (`dismissed`): it leaves the feed at once and never comes back. */
2844
+ dismissCard(card: Card | string): void {
2845
+ const id = cardIdOf(card);
2846
+ if (id) this._dispatch(() => JoryioModule.dismissCard?.(id), 'data');
2847
+ }
2848
+
2849
+ /**
2850
+ * Ask the server for the feed again. At most once per
2851
+ * CARD_MIN_REFRESH_SECONDS; extra calls coalesce. An app with its own push
2852
+ * messaging handler calls this on a `jry_sync: "cards"` data message; the
2853
+ * native SDKs handle it themselves otherwise.
2854
+ */
2855
+ refreshCards(): void {
2856
+ this._dispatch(() => JoryioModule.refreshCards?.());
2857
+ }
2858
+
2859
+ /** Called with the whole feed whenever it changes (a refresh, a report, an identity change). Returns an unsubscribe. */
2860
+ onCardsUpdated(callback: (feed: CardFeed) => unknown): () => void {
2861
+ if (typeof callback !== 'function' || !isModuleAvailable || !emitter) return () => {};
2862
+ const subscription = emitter.addListener('JoryioCardsUpdated', (e: any) => {
2863
+ try {
2864
+ callback(toCardFeed(e?.json));
2865
+ } catch (error) {
2866
+ warn(`onCardsUpdated callback threw: ${String(error)}`);
2867
+ }
2868
+ });
2869
+ this._cardListeners += 1;
2870
+ this._dispatch(() => JoryioModule.enableCardsUpdates?.());
2871
+ let removed = false;
2872
+ return () => {
2873
+ if (removed) return;
2874
+ removed = true;
2875
+ subscription.remove();
2876
+ this._cardListeners = Math.max(0, this._cardListeners - 1);
2877
+ if (this._cardListeners === 0) this._dispatch(() => JoryioModule.disableCardsUpdates?.());
2878
+ };
2879
+ }
2880
+
2881
+ /**
2882
+ * Receive EVERY link the native SDK is about to open - an in-app message
2883
+ * button or link, a `<JoryioPlacement />` button, a `<JoryioCardFeed />`
2884
+ * tap, an iOS push tap - before it opens: http(s) links and app deep links
2885
+ * (`myapp://cart`) alike, with where it came from (`link.source`) and the
2886
+ * ids that go with it. Return true to take the link over (navigate in your
2887
+ * app), false to let the native SDK open it as it does without a handler -
2888
+ * http(s) to the system (or your universal-link handling with
2889
+ * `forwardUniversalLinks` on iOS), an app deep link to the component's
2890
+ * `onDeepLink`. A Promise decides later. A refused scheme (javascript:,
2891
+ * data:, intent:, ...) never reaches it. One handler: a second call
2892
+ * replaces the first. Works before initialize(). Same name on iOS,
2893
+ * Android, web and Unity (`SetLinkHandler`).
2894
+ */
2895
+ setLinkHandler(handler: JoryioLinkHandler): void {
2896
+ if (typeof handler !== 'function') {
2897
+ warn('setLinkHandler() needs a function; use clearLinkHandler() to remove one');
2898
+ return;
2899
+ }
2900
+ this._linkHandler = handler;
2901
+ if (!isModuleAvailable || !emitter) return;
2902
+ if (!this._linkSubscription) {
2903
+ this._linkSubscription = emitter.addListener('JoryioLink', (e: any) => this._onLink(e));
2904
+ }
2905
+ // Not held for initialize(): the native handler is app-wide and works before it.
2906
+ JoryioModule.enableLinkHandler?.();
2907
+ }
2908
+
2909
+ /** Remove the handler set with setLinkHandler: links open as they do without one. */
2910
+ clearLinkHandler(): void {
2911
+ this._linkHandler = null;
2912
+ this._linkSubscription?.remove();
2913
+ this._linkSubscription = null;
2914
+ if (isModuleAvailable) JoryioModule.disableLinkHandler?.();
2915
+ }
2916
+
2917
+ /** A link from native: ask the handler, then tell native whether it was taken. */
2918
+ private _onLink(e: any): void {
2919
+ const linkId = e?.linkId;
2920
+ if (typeof linkId !== 'string') return;
2921
+ const complete = (handled: unknown) => JoryioModule.completeLink?.(linkId, handled === true);
2922
+ const handler = this._linkHandler;
2923
+ const link = toLink(e);
2924
+ if (!handler || !link) {
2925
+ complete(false);
2926
+ return;
2927
+ }
2928
+ let result: boolean | Promise<boolean>;
2929
+ try {
2930
+ result = handler(link);
2931
+ } catch (error) {
2932
+ // A throwing handler declines: the link still opens.
2933
+ warn(`setLinkHandler handler threw; the link opens as without one: ${String(error)}`);
2934
+ complete(false);
2935
+ return;
2936
+ }
2937
+ if (result && typeof (result as Promise<boolean>).then === 'function') {
2938
+ (result as Promise<boolean>).then(complete, (error) => {
2939
+ warn(`setLinkHandler handler rejected; the link opens as without one: ${String(error)}`);
2940
+ complete(false);
2941
+ });
2942
+ } else {
2943
+ complete(result);
2944
+ }
2945
+ }
2946
+
2227
2947
  /**
2228
2948
  * Forget which in-app campaigns have already been shown on this device.
2229
2949
  *