@tolinku/react-native-sdk 0.8.0 → 0.8.2

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.mjs CHANGED
@@ -1,10 +1,12 @@
1
- import { StyleSheet, Platform, NativeModules, AppState, Dimensions, PixelRatio, Modal, Pressable, TouchableOpacity, Text, ScrollView, View, Image, ImageBackground, Linking } from 'react-native';
1
+ import { StyleSheet, Platform, Linking, NativeModules, AppState, Dimensions, PixelRatio, Modal, Pressable, TouchableOpacity, Text, ScrollView, View, Image, ImageBackground } from 'react-native';
2
2
  import AsyncStorage from '@react-native-async-storage/async-storage';
3
3
  import React, { useState, useRef, useMemo, useEffect, useCallback } from 'react';
4
4
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
5
 
6
+ // src/Tolinku.ts
7
+
6
8
  // src/types.ts
7
- var SDK_VERSION = "0.8.0";
9
+ var SDK_VERSION = "0.8.2";
8
10
 
9
11
  // src/debug.ts
10
12
  var _debugEnabled = false;
@@ -90,6 +92,52 @@ var HttpClient = class {
90
92
  body: body ? JSON.stringify(body) : void 0
91
93
  });
92
94
  }
95
+ /**
96
+ * The hostname of the configured API, lowercased and without a port, for
97
+ * telling whether some other URL points at the same host. Empty if the base
98
+ * URL cannot be read, which init's validation should already have ruled out.
99
+ */
100
+ get apiHostname() {
101
+ const match = /^https?:\/\/(?:[^/?#@]*@)?([^/?#]+)/i.exec(this.baseUrl);
102
+ return match ? hostnameOf(match[1]) : "";
103
+ }
104
+ /** Whether there is a key to send, so callers can skip a call that would only be refused. */
105
+ get hasApiKey() {
106
+ return typeof this.apiKey === "string" && this.apiKey.length > 0;
107
+ }
108
+ /**
109
+ * POST once, without the API key, to a host other than the configured one,
110
+ * and hand back whatever came back, whatever the status.
111
+ *
112
+ * For a question that must not be asked twice: no retries, and its own time
113
+ * limit rather than the client's. Throws only when there is no reply at all
114
+ * (a network failure, the time limit, or a destroyed client).
115
+ */
116
+ async postPublicOnceToOrigin(origin, path, body, timeoutMs) {
117
+ return this.executeOnce(origin.replace(/\/+$/, "") + path, {
118
+ method: "POST",
119
+ headers: {
120
+ ...this.publicHeaders(),
121
+ "Content-Type": "application/json"
122
+ },
123
+ body: JSON.stringify(body)
124
+ }, timeoutMs);
125
+ }
126
+ /**
127
+ * POST once, with the API key, to the configured API. Same terms as
128
+ * {@link postPublicOnceToOrigin}: one attempt, its own time limit, the reply
129
+ * handed back whatever its status.
130
+ */
131
+ async postOnce(path, body, timeoutMs) {
132
+ return this.executeOnce(this.baseUrl + path, {
133
+ method: "POST",
134
+ headers: {
135
+ ...this.authenticatedHeaders(),
136
+ "Content-Type": "application/json"
137
+ },
138
+ body: JSON.stringify(body)
139
+ }, timeoutMs);
140
+ }
93
141
  /** POST without API key auth (for public endpoints like deferred claim) */
94
142
  async postPublic(path, body) {
95
143
  return this.executeWithRetry(this.baseUrl + path, {
@@ -125,6 +173,40 @@ var HttpClient = class {
125
173
  "User-Agent": `TolinkuReactNativeSDK/${SDK_VERSION}`
126
174
  };
127
175
  }
176
+ /**
177
+ * One request, one attempt, aborted after `timeoutMs`. The body is read as
178
+ * JSON when it is JSON and left undefined when it is not, so the caller can
179
+ * tell a reply from our own server apart from somebody else's error page.
180
+ */
181
+ async executeOnce(url, init, timeoutMs) {
182
+ if (this.destroyed) {
183
+ throw new TolinkuError("Tolinku: client has been destroyed. Call Tolinku.init() to reinitialize.", 0);
184
+ }
185
+ const controller = new AbortController();
186
+ this.pendingControllers.add(controller);
187
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
188
+ try {
189
+ const res = await fetch(url, { ...init, signal: controller.signal });
190
+ let body;
191
+ try {
192
+ body = JSON.parse(await res.text());
193
+ } catch {
194
+ body = void 0;
195
+ }
196
+ return { status: res.status, body };
197
+ } catch (err) {
198
+ if (this.destroyed) {
199
+ throw new TolinkuError("Tolinku: request aborted (client destroyed).", 0);
200
+ }
201
+ if (isAbortError(err)) {
202
+ throw new TolinkuError(`Tolinku: request timed out after ${timeoutMs}ms`, 0);
203
+ }
204
+ throw err;
205
+ } finally {
206
+ clearTimeout(timeoutId);
207
+ this.pendingControllers.delete(controller);
208
+ }
209
+ }
128
210
  /**
129
211
  * Execute a fetch request with retry logic. Retries on:
130
212
  * - Network errors (fetch throws)
@@ -208,6 +290,10 @@ var HttpClient = class {
208
290
  throw lastError || new TolinkuError("Tolinku: request failed after retries", 0);
209
291
  }
210
292
  };
293
+ function hostnameOf(authority) {
294
+ const match = /^(\[[^\]]*\]|[^:]*)/.exec(authority);
295
+ return (match ? match[1] : authority).toLowerCase();
296
+ }
211
297
  function sleep(ms) {
212
298
  return new Promise((resolve) => setTimeout(resolve, ms));
213
299
  }
@@ -227,20 +313,6 @@ function urlScheme(url) {
227
313
  const match = /^([a-zA-Z][a-zA-Z\d+\-._]*):/.exec(cleaned);
228
314
  return match ? `${match[1].toLowerCase()}:` : null;
229
315
  }
230
- function parseHttpUrl(url) {
231
- if (!url || typeof url !== "string") return null;
232
- const cleaned = url.replace(/[\t\n\r]/g, "").trim();
233
- const match = /^(https?):\/\/([^/?#]+)([^?#]*)/i.exec(cleaned);
234
- if (!match) return null;
235
- const [, scheme, authority, path] = match;
236
- if (!authority) return null;
237
- return {
238
- origin: `${scheme.toLowerCase()}://${authority.toLowerCase()}`,
239
- // A URL with no path means the root, which is what a server expects to be
240
- // asked about.
241
- pathname: path || "/"
242
- };
243
- }
244
316
  function isSafeUrl(url) {
245
317
  const scheme = urlScheme(url);
246
318
  return scheme === "http:" || scheme === "https:";
@@ -324,6 +396,16 @@ var _Analytics = class _Analytics {
324
396
  */
325
397
  this.lastOpenUrl = null;
326
398
  this.lastOpenAt = 0;
399
+ /**
400
+ * Part of the key, not carried alongside it. An ordinary open and a deferred
401
+ * one are different events on the server and only the app can tell them
402
+ * apart, so a deferred report just after an ordinary one for the same link is
403
+ * new information rather than a repeat. Keyed on the URL alone, somebody who
404
+ * tapped a link, installed, then tapped it again would have the deferred
405
+ * report swallowed, losing the last stage of the install funnel in the one
406
+ * case it exists to show.
407
+ */
408
+ this.lastOpenDeferred = false;
327
409
  this.handleAppStateChange = (state) => {
328
410
  if (state === "background" || state === "inactive") {
329
411
  this.flush().catch(() => {
@@ -357,9 +439,10 @@ var _Analytics = class _Analytics {
357
439
  if (!trimmed) return;
358
440
  if (!isSafeUrl(trimmed)) return;
359
441
  const now = Date.now();
360
- if (this.lastOpenUrl === trimmed && now - this.lastOpenAt < _Analytics.OPEN_DEDUPE_MS) return;
442
+ if (this.lastOpenUrl === trimmed && this.lastOpenDeferred === deferred && now - this.lastOpenAt < _Analytics.OPEN_DEDUPE_MS) return;
361
443
  this.lastOpenUrl = trimmed;
362
444
  this.lastOpenAt = now;
445
+ this.lastOpenDeferred = deferred;
363
446
  try {
364
447
  const result = await this.client.postPublic(
365
448
  "/v1/api/opens",
@@ -899,6 +982,36 @@ function override(value) {
899
982
  function isRoutablePath(path) {
900
983
  return typeof path === "string" && path.startsWith("/") && !path.startsWith("//");
901
984
  }
985
+ var RESOLVE_TIMEOUT_MS = 5e3;
986
+ function normaliseLink(url) {
987
+ if (!url || typeof url !== "string") return null;
988
+ const cleaned = url.replace(/[\t\n\r]/g, "").trim();
989
+ const match = /^https?:\/\/([^/?#]*)([^?#]*)(\?[^#]*)?/i.exec(cleaned);
990
+ if (!match) return null;
991
+ const [, rawAuthority, rawPath, rawQuery] = match;
992
+ const authority = rawAuthority.slice(rawAuthority.lastIndexOf("@") + 1);
993
+ const hostPort = /^(\[[^\]]*\]|[^:]*)(?::(\d*))?$/.exec(authority);
994
+ if (!hostPort || !hostPort[1]) return null;
995
+ const hostname = hostPort[1].toLowerCase();
996
+ const port = hostPort[2];
997
+ const keepPort = port && port !== "443" && port !== "80" ? `:${port}` : "";
998
+ const origin = `https://${hostname}${keepPort}`;
999
+ const path = rawPath || "/";
1000
+ const query = rawQuery && rawQuery.length > 1 ? rawQuery : "";
1001
+ return { origin, hostname, path, whole: origin + path + query };
1002
+ }
1003
+ function answerIn(reply) {
1004
+ if (reply.status !== 200) return null;
1005
+ const result = reply.body;
1006
+ if (!result || typeof result !== "object" || !result.route || !isRoutablePath(result.deep_link_path)) {
1007
+ return null;
1008
+ }
1009
+ return result;
1010
+ }
1011
+ function isTolinkuReply(reply) {
1012
+ const body = reply.body;
1013
+ return typeof body === "object" && body !== null && typeof body.error === "string";
1014
+ }
902
1015
  var Links = class {
903
1016
  constructor(client) {
904
1017
  this.client = client;
@@ -908,30 +1021,63 @@ var Links = class {
908
1021
  *
909
1022
  * `url` is a whole link as the app received it. The question goes to the
910
1023
  * link's own host, because that is how the platform knows which Appspace is
911
- * being asked about, which also means a link on a domain that is not yours
912
- * simply answers nothing.
1024
+ * being asked about. If that host is not Tolinku's (no reply, or one that is
1025
+ * not ours), and it is not the API's own host, the question goes once more to
1026
+ * the configured API with the key: a link in an email arrives wrapped in the
1027
+ * email platform's click tracking domain, which knows nothing about routes,
1028
+ * and the API can unwrap it.
1029
+ *
1030
+ * Each question is asked once, with a five second limit. Asking a click
1031
+ * tracking host again would count the email click again.
913
1032
  *
914
1033
  * Never throws. A link that cannot be resolved, for a bad network or any
915
1034
  * other reason, is one the app should fall back to its own handling for, and
916
1035
  * an exception in the middle of a cold start is no way to say so.
917
1036
  */
918
1037
  async resolve(url) {
919
- if (!url || typeof url !== "string") return null;
920
- const parsed = parseHttpUrl(url);
921
- if (!parsed) {
1038
+ try {
1039
+ return await this.resolveLink(url);
1040
+ } catch (err) {
1041
+ debugWarn(`Links.resolve failed: ${err.message}`);
1042
+ return null;
1043
+ }
1044
+ }
1045
+ async resolveLink(url) {
1046
+ const link = normaliseLink(url);
1047
+ if (!link) {
922
1048
  debugWarn(`Links.resolve: not an http(s) URL: ${url}`);
923
1049
  return null;
924
1050
  }
925
- try {
926
- const result = await this.client.postPublicToOrigin(
927
- parsed.origin,
1051
+ const direct = await this.askOnce(
1052
+ () => this.client.postPublicOnceToOrigin(
1053
+ link.origin,
928
1054
  "/v1/api/path",
929
- { path: parsed.pathname }
930
- );
931
- if (!result || !result.route || !isRoutablePath(result.deep_link_path)) return null;
932
- return result;
1055
+ { path: link.path, url: link.whole },
1056
+ RESOLVE_TIMEOUT_MS
1057
+ ),
1058
+ "Links.resolve"
1059
+ );
1060
+ if (direct) {
1061
+ const found = answerIn(direct);
1062
+ if (found) return found;
1063
+ if (isTolinkuReply(direct)) return null;
1064
+ }
1065
+ const apiHostname = this.client.apiHostname;
1066
+ if (!this.client.hasApiKey || !apiHostname || link.hostname === apiHostname) {
1067
+ return null;
1068
+ }
1069
+ const fallback = await this.askOnce(
1070
+ () => this.client.postOnce("/v1/api/links/resolve", { url: link.whole }, RESOLVE_TIMEOUT_MS),
1071
+ "Links.resolve fallback"
1072
+ );
1073
+ return fallback ? answerIn(fallback) : null;
1074
+ }
1075
+ /** One request; null when there was no reply at all. */
1076
+ async askOnce(request, label) {
1077
+ try {
1078
+ return await request();
933
1079
  } catch (err) {
934
- debugWarn(`Links.resolve failed: ${err.message}`);
1080
+ debugWarn(`${label} failed: ${err.message}`);
935
1081
  return null;
936
1082
  }
937
1083
  }
@@ -1061,8 +1207,30 @@ var _Tolinku = class _Tolinku {
1061
1207
  _Tolinku.deferredInstance = new Deferred(_Tolinku.client);
1062
1208
  _Tolinku.linksInstance = new Links(_Tolinku.client);
1063
1209
  _Tolinku._initialized = true;
1210
+ if (config.autoTrackLinkOpens === true) _Tolinku.startAutoLinkTracking();
1064
1211
  debugLog(`Tolinku SDK v${SDK_VERSION} initialized (baseUrl=${baseUrl})`);
1065
1212
  }
1213
+ /**
1214
+ * Report incoming links without the app wiring anything.
1215
+ *
1216
+ * A link arrives in two places and both need reporting: one that launches the
1217
+ * app cold arrives at getInitialURL, one tapped while it is already running
1218
+ * arrives at the listener. Instrumenting only the second is the common
1219
+ * mistake, because it works in every test done by hand with the app open.
1220
+ *
1221
+ * Both are wired, and the same link arriving at both inside a few seconds is
1222
+ * reported once: trackLinkOpen drops a repeat of the same URL, which is why
1223
+ * covering both here is safe rather than double counting.
1224
+ */
1225
+ static startAutoLinkTracking() {
1226
+ Linking.getInitialURL().then((url) => {
1227
+ if (url) void _Tolinku.trackLinkOpen(url);
1228
+ }).catch(() => {
1229
+ });
1230
+ _Tolinku.linkSubscription = Linking.addEventListener("url", ({ url }) => {
1231
+ if (url) void _Tolinku.trackLinkOpen(url);
1232
+ });
1233
+ }
1066
1234
  /** Check whether the SDK has been initialized. */
1067
1235
  static isConfigured() {
1068
1236
  return _Tolinku._initialized;
@@ -1195,6 +1363,10 @@ var _Tolinku = class _Tolinku {
1195
1363
  _Tolinku.client.abort();
1196
1364
  }
1197
1365
  resetStorageNamespace();
1366
+ if (_Tolinku.linkSubscription) {
1367
+ _Tolinku.linkSubscription.remove();
1368
+ _Tolinku.linkSubscription = null;
1369
+ }
1198
1370
  _Tolinku.client = null;
1199
1371
  _Tolinku.analyticsInstance = null;
1200
1372
  _Tolinku.ecommerceInstance = null;
@@ -1215,6 +1387,14 @@ _Tolinku.deferredInstance = null;
1215
1387
  _Tolinku.linksInstance = null;
1216
1388
  _Tolinku._initialized = false;
1217
1389
  _Tolinku._userId = null;
1390
+ /**
1391
+ * Removes the automatic link listener, when one was installed.
1392
+ *
1393
+ * Held here rather than inside Analytics because it is a property of this
1394
+ * configuration: destroy() has to take it back down or a reconfigured SDK
1395
+ * reports every link twice.
1396
+ */
1397
+ _Tolinku.linkSubscription = null;
1218
1398
  var Tolinku = _Tolinku;
1219
1399
  var DEFAULT_IMAGE_HEIGHT = 200;
1220
1400
  function dimension(raw) {