@tolinku/react-native-sdk 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
10
  var AsyncStorage__default = /*#__PURE__*/_interopDefault(AsyncStorage);
11
11
 
12
12
  // src/types.ts
13
- var SDK_VERSION = "0.1.0";
13
+ var SDK_VERSION = "0.5.0";
14
14
 
15
15
  // src/debug.ts
16
16
  var _debugEnabled = false;
@@ -253,12 +253,33 @@ function validateEventType(eventType) {
253
253
  var BATCH_SIZE = 10;
254
254
  var FLUSH_INTERVAL_MS = 5e3;
255
255
  var MAX_QUEUE_SIZE = 1e3;
256
- var Analytics = class {
256
+ var _Analytics = class _Analytics {
257
257
  constructor(client) {
258
258
  this.queue = [];
259
259
  this.flushTimer = null;
260
260
  this.appStateSubscription = null;
261
261
  this.isFlushing = false;
262
+ /**
263
+ * Track a custom event. The event is added to the internal queue
264
+ * and will be flushed automatically or when flush() is called.
265
+ *
266
+ * Event type must match /^custom\.[a-z0-9_]+$/.
267
+ * Auto-prefixes with "custom." if missing.
268
+ */
269
+ /**
270
+ * Set once the server says this Appspace does not attribute app opens, so the
271
+ * setting costs one request a launch rather than one per link.
272
+ */
273
+ this.appOpensDisabled = false;
274
+ /**
275
+ * The last link reported, and when. Cold start and the link stream can both
276
+ * deliver the same tap, depending on the plugin, so an app instrumenting both
277
+ * paths would otherwise report it twice and be billed twice. A genuine second
278
+ * tap of the same link inside this window is implausible; a duplicate delivery
279
+ * of one tap is not.
280
+ */
281
+ this.lastOpenUrl = null;
282
+ this.lastOpenAt = 0;
262
283
  this.handleAppStateChange = (state) => {
263
284
  if (state === "background" || state === "inactive") {
264
285
  this.flush().catch(() => {
@@ -272,12 +293,51 @@ var Analytics = class {
272
293
  );
273
294
  }
274
295
  /**
275
- * Track a custom event. The event is added to the internal queue
276
- * and will be flushed automatically or when flush() is called.
296
+ * Report that a link opened the app without the browser being involved.
277
297
  *
278
- * Event type must match /^custom\.[a-z0-9_]+$/.
279
- * Auto-prefixes with "custom." if missing.
298
+ * A Universal Link or App Link hands the app the URL directly, so Tolinku is
299
+ * never contacted and the tap goes unrecorded. Those taps come from people who
300
+ * already have the app, so leaving them out makes a re-engagement campaign
301
+ * look like a failure exactly when it worked.
302
+ *
303
+ * Only http and https links are reported. A custom scheme means Tolinku's own
304
+ * hand-off page opened the app, and that tap was counted when the page was
305
+ * served, so passing one does nothing rather than counting it twice.
306
+ *
307
+ * Never throws. This runs on the path that routes the user somewhere, and a
308
+ * tap that goes unrecorded is not worth interrupting that.
280
309
  */
310
+ async trackLinkOpen(url, userId) {
311
+ if (this.appOpensDisabled) return;
312
+ const trimmed = typeof url === "string" ? url.trim() : "";
313
+ if (!trimmed) return;
314
+ let parsed;
315
+ try {
316
+ parsed = new URL(trimmed);
317
+ } catch {
318
+ return;
319
+ }
320
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return;
321
+ const now = Date.now();
322
+ if (this.lastOpenUrl === trimmed && now - this.lastOpenAt < _Analytics.OPEN_DEDUPE_MS) return;
323
+ this.lastOpenUrl = trimmed;
324
+ this.lastOpenAt = now;
325
+ try {
326
+ const result = await this.client.postPublic(
327
+ "/v1/api/opens",
328
+ {
329
+ url: trimmed,
330
+ // The User-Agent cannot say which platform this is: this SDK
331
+ // identifies itself the same way on both. Without it an app open has
332
+ // no platform and lands in a blank bucket on every breakdown.
333
+ platform: reactNative.Platform.OS === "ios" || reactNative.Platform.OS === "android" ? reactNative.Platform.OS : void 0,
334
+ ...userId ? { user_id: userId } : {}
335
+ }
336
+ );
337
+ if (result?.attribute === false) this.appOpensDisabled = true;
338
+ } catch {
339
+ }
340
+ }
281
341
  async track(eventType, properties) {
282
342
  const normalizedType = validateEventType(eventType);
283
343
  const event = {
@@ -353,6 +413,8 @@ var Analytics = class {
353
413
  }
354
414
  }
355
415
  };
416
+ _Analytics.OPEN_DEDUPE_MS = 5e3;
417
+ var Analytics = _Analytics;
356
418
  var BATCH_SIZE2 = 10;
357
419
  var FLUSH_INTERVAL_MS2 = 5e3;
358
420
  var MAX_QUEUE_SIZE2 = 500;
@@ -630,58 +692,163 @@ var Referrals = class {
630
692
  });
631
693
  }
632
694
  };
695
+ var TOKEN_KEY = "tolk_token";
696
+ function parseInstallReferrer(referrer) {
697
+ if (!referrer || !referrer.trim()) return null;
698
+ let decoded = referrer;
699
+ try {
700
+ decoded = decodeURIComponent(referrer);
701
+ } catch {
702
+ }
703
+ const pair = decoded.split("&").map((p) => p.trim()).find((p) => p.startsWith(`${TOKEN_KEY}=`));
704
+ if (!pair) return null;
705
+ const token = pair.slice(TOKEN_KEY.length + 1);
706
+ return token.trim() ? token : null;
707
+ }
708
+ function nativeProvider() {
709
+ const native = reactNative.NativeModules?.TolinkuInstallReferrer;
710
+ if (!native || typeof native.getInstallReferrer !== "function") return null;
711
+ return () => native.getInstallReferrer();
712
+ }
713
+ async function getInstallReferrerToken(provider) {
714
+ if (reactNative.Platform.OS !== "android") return null;
715
+ const source = provider ?? nativeProvider();
716
+ if (!source) return null;
717
+ try {
718
+ const referrer = await source();
719
+ return parseInstallReferrer(referrer);
720
+ } catch (err) {
721
+ debugWarn(`Install referrer lookup failed: ${err.message}`);
722
+ return null;
723
+ }
724
+ }
725
+
726
+ // src/deferred.ts
727
+ var CLAIMED_KEY = "tolinku_deferred_claimed";
633
728
  var Deferred = class {
634
729
  constructor(client) {
635
730
  this.client = client;
636
731
  }
637
732
  /** Claim a deferred deep link by referrer token (from Play Store referrer or clipboard) */
638
- async claimByToken(token) {
733
+ async claimByToken(token, appspaceId) {
639
734
  if (!token || !token.trim()) {
640
735
  throw new Error("Tolinku: token is required and must not be blank for claimByToken.");
641
736
  }
642
737
  try {
643
- return await this.client.getPublic("/v1/api/deferred/claim", { token });
738
+ return await this.client.getPublic("/v1/api/deferred/claim", {
739
+ token,
740
+ ...appspaceId ? { appspace_id: appspaceId } : {}
741
+ });
644
742
  } catch (err) {
645
743
  debugWarn(`Deferred claimByToken failed: ${err.message}`);
646
744
  return null;
647
745
  }
648
746
  }
747
+ /**
748
+ * Recover the link that led to this install, trying both mechanisms.
749
+ *
750
+ * The Play Install Referrer is asked first on Android: it names the exact
751
+ * click, survives for days, and does not care which network the device was
752
+ * on. Device signals are the fallback, and the only option on iOS, where no
753
+ * equivalent exists.
754
+ *
755
+ * Call once on first launch. Safe to call again, but a claim is consumed the
756
+ * first time it succeeds, so a second call returns null.
757
+ *
758
+ * Reading the referrer needs a native Play Services binding, which this
759
+ * package deliberately does not bundle. Pass `referrerProvider`, or install a
760
+ * supported referrer package and it is used automatically. Without either,
761
+ * Android falls back to signal matching.
762
+ */
763
+ async claimDeferredLink(options) {
764
+ if (!options.appspaceId || !options.appspaceId.trim()) {
765
+ throw new Error("Tolinku: appspaceId is required and must not be blank for claimDeferredLink.");
766
+ }
767
+ if (!options.force && await this.alreadyAttempted()) return null;
768
+ const token = await getInstallReferrerToken(options.referrerProvider);
769
+ if (token) {
770
+ const byToken = await this.claimByToken(token, options.appspaceId).catch(() => null);
771
+ if (byToken) {
772
+ await this.rememberAttempt();
773
+ return byToken;
774
+ }
775
+ }
776
+ const { link, settled } = await this.attemptSignals({ appspaceId: options.appspaceId });
777
+ if (settled) await this.rememberAttempt();
778
+ return link;
779
+ }
780
+ async alreadyAttempted() {
781
+ try {
782
+ return await AsyncStorage__default.default.getItem(CLAIMED_KEY) !== null;
783
+ } catch {
784
+ return false;
785
+ }
786
+ }
787
+ async rememberAttempt() {
788
+ try {
789
+ await AsyncStorage__default.default.setItem(CLAIMED_KEY, (/* @__PURE__ */ new Date()).toISOString());
790
+ } catch {
791
+ }
792
+ }
649
793
  /** Claim a deferred deep link by device signal matching */
650
794
  async claimBySignals(options) {
651
795
  if (!options.appspaceId || !options.appspaceId.trim()) {
652
796
  throw new Error("Tolinku: appspaceId is required and must not be blank for claimBySignals.");
653
797
  }
798
+ return (await this.attemptSignals(options)).link;
799
+ }
800
+ /**
801
+ * The signal claim, with whether the server actually answered.
802
+ *
803
+ * `settled` separates "nothing is waiting for this device", which no amount
804
+ * of asking will change, from "the request never got there". Both surface as
805
+ * null to callers of claimBySignals, but claimDeferredLink has to tell them
806
+ * apart: recording an attempt that never reached the server would spend an
807
+ * install's one chance at attribution on a dropped connection.
808
+ */
809
+ async attemptSignals(options) {
654
810
  try {
655
811
  const { width, height } = reactNative.Dimensions.get("screen");
656
- const resolvedTimezone = options.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;
657
- const resolvedLanguage = options.language || (typeof Intl !== "undefined" && typeof Intl.DateTimeFormat === "function" ? Intl.DateTimeFormat().resolvedOptions().locale : void 0) || "en";
658
- return await this.client.postPublic("/v1/api/deferred/claim-by-signals", {
812
+ const resolvedTimezone = override(options.timezone) || Intl.DateTimeFormat().resolvedOptions().timeZone;
813
+ const resolvedLanguage = override(options.language) || (typeof Intl !== "undefined" && typeof Intl.DateTimeFormat === "function" ? Intl.DateTimeFormat().resolvedOptions().locale : void 0) || "en";
814
+ const link = await this.client.postPublic("/v1/api/deferred/claim-by-signals", {
659
815
  appspace_id: options.appspaceId,
660
816
  timezone: resolvedTimezone,
661
817
  language: resolvedLanguage,
662
- screen_width: options.screenWidth || width,
663
- screen_height: options.screenHeight || height,
818
+ screen_width: override(options.screenWidth) || width,
819
+ screen_height: override(options.screenHeight) || height,
664
820
  // Separates devices reporting identical dp dimensions.
665
- device_pixel_ratio: options.devicePixelRatio || reactNative.PixelRatio.get(),
666
- os_version: options.osVersion || String(reactNative.Platform.Version)
821
+ device_pixel_ratio: override(options.devicePixelRatio) || reactNative.PixelRatio.get(),
822
+ os_version: override(options.osVersion) || String(reactNative.Platform.Version)
667
823
  });
824
+ return { link, settled: true };
668
825
  } catch (err) {
669
826
  const status = err?.statusCode ?? err?.status;
670
827
  if (status === 404) {
671
828
  debugWarn("Deferred claimBySignals: no match for this device.");
672
- return null;
829
+ return { link: null, settled: true };
673
830
  }
674
831
  if (status === 403) {
675
832
  console.warn(
676
833
  `[Tolinku] claimBySignals failed with HTTP 403. Check that appspaceId is your Appspace ID (copy it from the dashboard under Settings), not your subdomain or slug. ${err.message}`
677
834
  );
678
- return null;
835
+ return { link: null, settled: false };
679
836
  }
680
837
  debugWarn(`Deferred claimBySignals failed: ${err.message}`);
681
- return null;
838
+ return { link: null, settled: false };
682
839
  }
683
840
  }
684
841
  };
842
+ function override(value) {
843
+ if (typeof value === "string") {
844
+ const trimmed = value.trim();
845
+ return trimmed === "" ? void 0 : trimmed;
846
+ }
847
+ if (typeof value === "number") {
848
+ return Number.isFinite(value) && value > 0 ? value : void 0;
849
+ }
850
+ return void 0;
851
+ }
685
852
  var BASE_KEY = "tolinku_message_dismissed";
686
853
  var IMPRESSIONS_BASE_KEY = "tolinku_message_impressions";
687
854
  var LAST_SHOWN_BASE_KEY = "tolinku_message_last_shown";
@@ -768,6 +935,17 @@ var _Tolinku = class _Tolinku {
768
935
  * If init() is called a second time without calling destroy() first,
769
936
  * a warning is logged and the existing instance is returned.
770
937
  */
938
+ /**
939
+ * Configure the SDK.
940
+ *
941
+ * The name the Android, iOS and Flutter SDKs use for this. {@link init} does
942
+ * the same thing and still works; it is what this package shipped and
943
+ * breaking it would serve nobody. It is meant for deprecation later, once
944
+ * moving off it is a one-line change rather than a surprise.
945
+ */
946
+ static configure(config) {
947
+ _Tolinku.init(config);
948
+ }
771
949
  static init(config) {
772
950
  if (!config.apiKey) throw new Error("Tolinku: apiKey is required");
773
951
  if (_Tolinku._initialized) {
@@ -831,6 +1009,41 @@ var _Tolinku = class _Tolinku {
831
1009
  const mergedProps = _Tolinku._userId ? { user_id: _Tolinku._userId, ...properties } : properties;
832
1010
  return _Tolinku.analyticsInstance.track(eventType, mergedProps);
833
1011
  }
1012
+ /**
1013
+ * Report that a link opened the app, when it opened without the browser.
1014
+ *
1015
+ * A Universal Link or App Link hands the app the URL directly, so Tolinku is
1016
+ * never contacted and the tap goes unrecorded. Those taps come from people who
1017
+ * already have your app, so leaving them out makes a re-engagement campaign
1018
+ * look like a failure exactly when it worked.
1019
+ *
1020
+ * Both ways a link arrives need it. The listener fires only while the app is
1021
+ * already running, so a link that launched the app cold arrives separately:
1022
+ *
1023
+ * ```ts
1024
+ * // Launched by a link, app was not running.
1025
+ * const initial = await Linking.getInitialURL();
1026
+ * if (initial) Tolinku.trackLinkOpen(initial);
1027
+ *
1028
+ * // Tapped while the app was already open.
1029
+ * Linking.addEventListener('url', ({ url }) => {
1030
+ * Tolinku.trackLinkOpen(url);
1031
+ * // your own routing
1032
+ * });
1033
+ * ```
1034
+ *
1035
+ * Wiring both is safe: the same link arriving twice in quick succession is
1036
+ * reported once.
1037
+ *
1038
+ * Only http and https links are reported. A custom scheme means Tolinku's own
1039
+ * hand-off page opened the app, and that tap is already counted.
1040
+ *
1041
+ * Never throws.
1042
+ */
1043
+ static async trackLinkOpen(url) {
1044
+ if (!_Tolinku.analyticsInstance) return;
1045
+ return _Tolinku.analyticsInstance.trackLinkOpen(url, _Tolinku._userId ?? void 0);
1046
+ }
834
1047
  /**
835
1048
  * Immediately flush all queued analytics and ecommerce events to the server.
836
1049
  */
@@ -965,13 +1178,14 @@ function PuckComponentRenderer({ component, messageId, options }) {
965
1178
  case "Button": {
966
1179
  const handlePress = () => {
967
1180
  const action = props.action || "";
1181
+ if (!action) return;
1182
+ if (!isSafeUrl(action)) {
1183
+ debugWarn(`Button action URL blocked (unsafe protocol): ${action}`);
1184
+ return;
1185
+ }
968
1186
  if (options.onButtonPress) {
969
1187
  options.onButtonPress(action, messageId);
970
- } else if (action) {
971
- if (!isSafeUrl(action)) {
972
- debugWarn(`Button action URL blocked (unsafe protocol): ${action}`);
973
- return;
974
- }
1188
+ } else {
975
1189
  reactNative.Linking.openURL(action).catch(() => {
976
1190
  });
977
1191
  }
@@ -1205,6 +1419,8 @@ function TolinkuMessages({
1205
1419
  exports.Tolinku = Tolinku;
1206
1420
  exports.TolinkuError = TolinkuError;
1207
1421
  exports.TolinkuMessages = TolinkuMessages;
1422
+ exports.getInstallReferrerToken = getInstallReferrerToken;
1208
1423
  exports.isSafeUrl = isSafeUrl;
1424
+ exports.parseInstallReferrer = parseInstallReferrer;
1209
1425
  //# sourceMappingURL=index.js.map
1210
1426
  //# sourceMappingURL=index.js.map