@tolinku/react-native-sdk 0.5.0 → 0.6.1

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,10 @@
1
- import { StyleSheet, Platform, NativeModules, AppState, Dimensions, PixelRatio, Modal, Pressable, TouchableOpacity, Text, ScrollView, View, ImageBackground, Image, Linking } from 'react-native';
1
+ import { StyleSheet, Platform, NativeModules, AppState, Dimensions, PixelRatio, Modal, Pressable, TouchableOpacity, Text, ScrollView, View, Image, ImageBackground, Linking } from 'react-native';
2
2
  import AsyncStorage from '@react-native-async-storage/async-storage';
3
- import { useState, useRef, useMemo, useEffect, useCallback } from 'react';
3
+ import React, { useState, useRef, useMemo, useEffect, useCallback } from 'react';
4
4
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
5
 
6
6
  // src/types.ts
7
- var SDK_VERSION = "0.5.0";
7
+ var SDK_VERSION = "0.6.1";
8
8
 
9
9
  // src/debug.ts
10
10
  var _debugEnabled = false;
@@ -68,6 +68,25 @@ var HttpClient = class {
68
68
  headers: this.publicHeaders()
69
69
  });
70
70
  }
71
+ /**
72
+ * POST to a host other than the configured one, without the API key.
73
+ *
74
+ * A few public endpoints work out which Appspace they belong to from the
75
+ * hostname the request arrived on rather than from a key or an id, so a
76
+ * question about a link on a customer's own domain has to be asked on that
77
+ * domain. Everything else about the request is unchanged: same timeout, same
78
+ * retries, same headers.
79
+ */
80
+ async postPublicToOrigin(origin, path, body) {
81
+ return this.executeWithRetry(origin.replace(/\/+$/, "") + path, {
82
+ method: "POST",
83
+ headers: {
84
+ ...this.publicHeaders(),
85
+ "Content-Type": "application/json"
86
+ },
87
+ body: body ? JSON.stringify(body) : void 0
88
+ });
89
+ }
71
90
  /** POST without API key auth (for public endpoints like deferred claim) */
72
91
  async postPublic(path, body) {
73
92
  return this.executeWithRetry(this.baseUrl + path, {
@@ -199,16 +218,44 @@ var TolinkuError = class extends Error {
199
218
  };
200
219
 
201
220
  // src/validation.ts
221
+ function urlScheme(url) {
222
+ if (!url || typeof url !== "string") return null;
223
+ const cleaned = url.replace(/[\t\n\r]/g, "").replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g, "");
224
+ const match = /^([a-zA-Z][a-zA-Z\d+\-._]*):/.exec(cleaned);
225
+ return match ? `${match[1].toLowerCase()}:` : null;
226
+ }
227
+ function parseHttpUrl(url) {
228
+ if (!url || typeof url !== "string") return null;
229
+ const cleaned = url.replace(/[\t\n\r]/g, "").trim();
230
+ const match = /^(https?):\/\/([^/?#]+)([^?#]*)/i.exec(cleaned);
231
+ if (!match) return null;
232
+ const [, scheme, authority, path] = match;
233
+ if (!authority) return null;
234
+ return {
235
+ origin: `${scheme.toLowerCase()}://${authority.toLowerCase()}`,
236
+ // A URL with no path means the root, which is what a server expects to be
237
+ // asked about.
238
+ pathname: path || "/"
239
+ };
240
+ }
202
241
  function isSafeUrl(url) {
203
- if (!url || typeof url !== "string") return false;
204
- const trimmed = url.trim();
205
- if (!trimmed) return false;
206
- try {
207
- const parsed = new URL(trimmed);
208
- return parsed.protocol === "http:" || parsed.protocol === "https:";
209
- } catch {
210
- return false;
211
- }
242
+ const scheme = urlScheme(url);
243
+ return scheme === "http:" || scheme === "https:";
244
+ }
245
+ var EXECUTABLE_SCHEMES = /* @__PURE__ */ new Set([
246
+ "javascript:",
247
+ "vbscript:",
248
+ "data:",
249
+ "blob:",
250
+ "file:",
251
+ "content:",
252
+ "jar:",
253
+ "filesystem:"
254
+ ]);
255
+ function isSafeActionUrl(url) {
256
+ const scheme = urlScheme(url);
257
+ if (!scheme) return false;
258
+ return !EXECUTABLE_SCHEMES.has(scheme);
212
259
  }
213
260
  function validateBaseUrl(baseUrl) {
214
261
  if (typeof baseUrl !== "string") {
@@ -305,13 +352,7 @@ var _Analytics = class _Analytics {
305
352
  if (this.appOpensDisabled) return;
306
353
  const trimmed = typeof url === "string" ? url.trim() : "";
307
354
  if (!trimmed) return;
308
- let parsed;
309
- try {
310
- parsed = new URL(trimmed);
311
- } catch {
312
- return;
313
- }
314
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return;
355
+ if (!isSafeUrl(trimmed)) return;
315
356
  const now = Date.now();
316
357
  if (this.lastOpenUrl === trimmed && now - this.lastOpenAt < _Analytics.OPEN_DEDUPE_MS) return;
317
358
  this.lastOpenUrl = trimmed;
@@ -843,6 +884,48 @@ function override(value) {
843
884
  }
844
885
  return void 0;
845
886
  }
887
+
888
+ // src/links.ts
889
+ function isRoutablePath(path) {
890
+ return typeof path === "string" && path.startsWith("/") && !path.startsWith("//");
891
+ }
892
+ var Links = class {
893
+ constructor(client) {
894
+ this.client = client;
895
+ }
896
+ /**
897
+ * What this link means, or null if it means nothing here.
898
+ *
899
+ * `url` is a whole link as the app received it. The question goes to the
900
+ * link's own host, because that is how the platform knows which Appspace is
901
+ * being asked about, which also means a link on a domain that is not yours
902
+ * simply answers nothing.
903
+ *
904
+ * Never throws. A link that cannot be resolved, for a bad network or any
905
+ * other reason, is one the app should fall back to its own handling for, and
906
+ * an exception in the middle of a cold start is no way to say so.
907
+ */
908
+ async resolve(url) {
909
+ if (!url || typeof url !== "string") return null;
910
+ const parsed = parseHttpUrl(url);
911
+ if (!parsed) {
912
+ debugWarn(`Links.resolve: not an http(s) URL: ${url}`);
913
+ return null;
914
+ }
915
+ try {
916
+ const result = await this.client.postPublicToOrigin(
917
+ parsed.origin,
918
+ "/v1/api/path",
919
+ { path: parsed.pathname }
920
+ );
921
+ if (!result || !result.route || !isRoutablePath(result.deep_link_path)) return null;
922
+ return result;
923
+ } catch (err) {
924
+ debugWarn(`Links.resolve failed: ${err.message}`);
925
+ return null;
926
+ }
927
+ }
928
+ };
846
929
  var BASE_KEY = "tolinku_message_dismissed";
847
930
  var IMPRESSIONS_BASE_KEY = "tolinku_message_impressions";
848
931
  var LAST_SHOWN_BASE_KEY = "tolinku_message_last_shown";
@@ -966,6 +1049,7 @@ var _Tolinku = class _Tolinku {
966
1049
  _Tolinku.ecommerceInstance = new Ecommerce(_Tolinku.client, () => _Tolinku._userId);
967
1050
  _Tolinku.referralsInstance = new Referrals(_Tolinku.client);
968
1051
  _Tolinku.deferredInstance = new Deferred(_Tolinku.client);
1052
+ _Tolinku.linksInstance = new Links(_Tolinku.client);
969
1053
  _Tolinku._initialized = true;
970
1054
  debugLog(`Tolinku SDK v${SDK_VERSION} initialized (baseUrl=${baseUrl})`);
971
1055
  }
@@ -1071,6 +1155,18 @@ var _Tolinku = class _Tolinku {
1071
1155
  }
1072
1156
  return _Tolinku.deferredInstance;
1073
1157
  }
1158
+ /**
1159
+ * Turning a link the app was handed into the route and token it means.
1160
+ *
1161
+ * Needed for short links, which arrive as an opaque code that nothing on the
1162
+ * device can interpret. See {@link Links.resolve}.
1163
+ */
1164
+ static get links() {
1165
+ if (!_Tolinku.linksInstance) {
1166
+ throw new Error("Tolinku: SDK not initialized. Call Tolinku.init() first.");
1167
+ }
1168
+ return _Tolinku.linksInstance;
1169
+ }
1074
1170
  /**
1075
1171
  * Shut down the SDK and release resources.
1076
1172
  * Flushes remaining analytics events, cancels timers, removes listeners,
@@ -1094,6 +1190,7 @@ var _Tolinku = class _Tolinku {
1094
1190
  _Tolinku.ecommerceInstance = null;
1095
1191
  _Tolinku.referralsInstance = null;
1096
1192
  _Tolinku.deferredInstance = null;
1193
+ _Tolinku.linksInstance = null;
1097
1194
  _Tolinku._initialized = false;
1098
1195
  _Tolinku._userId = null;
1099
1196
  setDebugEnabled(false);
@@ -1105,32 +1202,368 @@ _Tolinku.analyticsInstance = null;
1105
1202
  _Tolinku.ecommerceInstance = null;
1106
1203
  _Tolinku.referralsInstance = null;
1107
1204
  _Tolinku.deferredInstance = null;
1205
+ _Tolinku.linksInstance = null;
1108
1206
  _Tolinku._initialized = false;
1109
1207
  _Tolinku._userId = null;
1110
1208
  var Tolinku = _Tolinku;
1209
+ var DEFAULT_IMAGE_HEIGHT = 200;
1210
+ function dimension(raw) {
1211
+ if (typeof raw === "number" && isFinite(raw) && raw > 0) return raw;
1212
+ if (typeof raw !== "string") return void 0;
1213
+ const value = raw.trim();
1214
+ if (!value) return void 0;
1215
+ if (value.endsWith("%")) {
1216
+ return /^\d+(?:\.\d+)?%$/.test(value) ? value : void 0;
1217
+ }
1218
+ const match = /^(\d+(?:\.\d+)?)(?:px)?$/i.exec(value);
1219
+ if (!match) {
1220
+ debugWarn(`Dimension "${raw}" is not a size React Native understands; ignoring it.`);
1221
+ return void 0;
1222
+ }
1223
+ const parsed = parseFloat(match[1]);
1224
+ return parsed > 0 ? parsed : void 0;
1225
+ }
1226
+ function num(raw, fallback) {
1227
+ if (typeof raw === "number" && isFinite(raw)) return raw;
1228
+ if (typeof raw === "string" && raw.trim()) {
1229
+ const parsed = parseFloat(raw);
1230
+ if (isFinite(parsed)) return parsed;
1231
+ }
1232
+ return fallback;
1233
+ }
1234
+ function alignment(raw) {
1235
+ return raw === "center" || raw === "right" || raw === "justify" ? raw : "left";
1236
+ }
1237
+ var NAMED_COLORS = /* @__PURE__ */ new Set([
1238
+ "transparent",
1239
+ "aliceblue",
1240
+ "antiquewhite",
1241
+ "aqua",
1242
+ "aquamarine",
1243
+ "azure",
1244
+ "beige",
1245
+ "bisque",
1246
+ "black",
1247
+ "blanchedalmond",
1248
+ "blue",
1249
+ "blueviolet",
1250
+ "brown",
1251
+ "burlywood",
1252
+ "cadetblue",
1253
+ "chartreuse",
1254
+ "chocolate",
1255
+ "coral",
1256
+ "cornflowerblue",
1257
+ "cornsilk",
1258
+ "crimson",
1259
+ "cyan",
1260
+ "darkblue",
1261
+ "darkcyan",
1262
+ "darkgoldenrod",
1263
+ "darkgray",
1264
+ "darkgreen",
1265
+ "darkgrey",
1266
+ "darkkhaki",
1267
+ "darkmagenta",
1268
+ "darkolivegreen",
1269
+ "darkorange",
1270
+ "darkorchid",
1271
+ "darkred",
1272
+ "darksalmon",
1273
+ "darkseagreen",
1274
+ "darkslateblue",
1275
+ "darkslategray",
1276
+ "darkslategrey",
1277
+ "darkturquoise",
1278
+ "darkviolet",
1279
+ "deeppink",
1280
+ "deepskyblue",
1281
+ "dimgray",
1282
+ "dimgrey",
1283
+ "dodgerblue",
1284
+ "firebrick",
1285
+ "floralwhite",
1286
+ "forestgreen",
1287
+ "fuchsia",
1288
+ "gainsboro",
1289
+ "ghostwhite",
1290
+ "gold",
1291
+ "goldenrod",
1292
+ "gray",
1293
+ "green",
1294
+ "greenyellow",
1295
+ "grey",
1296
+ "honeydew",
1297
+ "hotpink",
1298
+ "indianred",
1299
+ "indigo",
1300
+ "ivory",
1301
+ "khaki",
1302
+ "lavender",
1303
+ "lavenderblush",
1304
+ "lawngreen",
1305
+ "lemonchiffon",
1306
+ "lightblue",
1307
+ "lightcoral",
1308
+ "lightcyan",
1309
+ "lightgoldenrodyellow",
1310
+ "lightgray",
1311
+ "lightgreen",
1312
+ "lightgrey",
1313
+ "lightpink",
1314
+ "lightsalmon",
1315
+ "lightseagreen",
1316
+ "lightskyblue",
1317
+ "lightslategray",
1318
+ "lightslategrey",
1319
+ "lightsteelblue",
1320
+ "lightyellow",
1321
+ "lime",
1322
+ "limegreen",
1323
+ "linen",
1324
+ "magenta",
1325
+ "maroon",
1326
+ "mediumaquamarine",
1327
+ "mediumblue",
1328
+ "mediumorchid",
1329
+ "mediumpurple",
1330
+ "mediumseagreen",
1331
+ "mediumslateblue",
1332
+ "mediumspringgreen",
1333
+ "mediumturquoise",
1334
+ "mediumvioletred",
1335
+ "midnightblue",
1336
+ "mintcream",
1337
+ "mistyrose",
1338
+ "moccasin",
1339
+ "navajowhite",
1340
+ "navy",
1341
+ "oldlace",
1342
+ "olive",
1343
+ "olivedrab",
1344
+ "orange",
1345
+ "orangered",
1346
+ "orchid",
1347
+ "palegoldenrod",
1348
+ "palegreen",
1349
+ "paleturquoise",
1350
+ "palevioletred",
1351
+ "papayawhip",
1352
+ "peachpuff",
1353
+ "peru",
1354
+ "pink",
1355
+ "plum",
1356
+ "powderblue",
1357
+ "purple",
1358
+ "rebeccapurple",
1359
+ "red",
1360
+ "rosybrown",
1361
+ "royalblue",
1362
+ "saddlebrown",
1363
+ "salmon",
1364
+ "sandybrown",
1365
+ "seagreen",
1366
+ "seashell",
1367
+ "sienna",
1368
+ "silver",
1369
+ "skyblue",
1370
+ "slateblue",
1371
+ "slategray",
1372
+ "slategrey",
1373
+ "snow",
1374
+ "springgreen",
1375
+ "steelblue",
1376
+ "tan",
1377
+ "teal",
1378
+ "thistle",
1379
+ "tomato",
1380
+ "turquoise",
1381
+ "violet",
1382
+ "wheat",
1383
+ "white",
1384
+ "whitesmoke",
1385
+ "yellow",
1386
+ "yellowgreen"
1387
+ ]);
1388
+ function color(raw, fallback) {
1389
+ if (typeof raw !== "string") return fallback;
1390
+ const value = raw.trim();
1391
+ if (!value) return fallback;
1392
+ if (/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value)) return value;
1393
+ if (/^(?:rgb|rgba|hsl|hsla)\(\s*[\d.]+\s*,[^)%]*\)$/i.test(value)) return value;
1394
+ if (NAMED_COLORS.has(value.toLowerCase())) return value.toLowerCase();
1395
+ debugWarn(`Colour "${raw}" is not one React Native can read; using ${fallback}.`);
1396
+ return fallback;
1397
+ }
1398
+ function softVariant(hex) {
1399
+ if (/^#[0-9a-f]{6}$/i.test(hex)) return `${hex}22`;
1400
+ if (/^#[0-9a-f]{3}$/i.test(hex)) {
1401
+ const [, r, g, b] = hex;
1402
+ return `#${r}${r}${g}${g}${b}${b}22`;
1403
+ }
1404
+ return null;
1405
+ }
1406
+ function richText(text, onPressUrl) {
1407
+ if (!text) return "";
1408
+ const regex = /\[([^\]]+)\]\(([^)]+)\)/g;
1409
+ const parts = [];
1410
+ let lastIndex = 0;
1411
+ let match;
1412
+ let key = 0;
1413
+ while ((match = regex.exec(text)) !== null) {
1414
+ if (match.index > lastIndex) parts.push(text.slice(lastIndex, match.index));
1415
+ const [full, label, rawUrl] = match;
1416
+ const url = (rawUrl || "").trim();
1417
+ if (isSafeActionUrl(url)) {
1418
+ parts.push(
1419
+ /* @__PURE__ */ jsx(
1420
+ Text,
1421
+ {
1422
+ style: { textDecorationLine: "underline" },
1423
+ onPress: () => onPressUrl(url),
1424
+ children: label
1425
+ },
1426
+ `link-${key++}`
1427
+ )
1428
+ );
1429
+ } else {
1430
+ parts.push(full);
1431
+ }
1432
+ lastIndex = regex.lastIndex;
1433
+ }
1434
+ if (lastIndex < text.length) parts.push(text.slice(lastIndex));
1435
+ return parts.length === 1 ? parts[0] : parts;
1436
+ }
1437
+ function useImageRatio(uri, enabled) {
1438
+ const [ratio, setRatio] = React.useState(null);
1439
+ React.useEffect(() => {
1440
+ if (!enabled || !uri) return;
1441
+ let cancelled = false;
1442
+ Image.getSize(
1443
+ uri,
1444
+ (w, h) => {
1445
+ if (!cancelled && w > 0 && h > 0) setRatio(w / h);
1446
+ },
1447
+ () => {
1448
+ }
1449
+ );
1450
+ return () => {
1451
+ cancelled = true;
1452
+ };
1453
+ }, [uri, enabled]);
1454
+ return ratio;
1455
+ }
1456
+ function MessageImage({
1457
+ uri,
1458
+ width,
1459
+ height,
1460
+ borderRadius,
1461
+ borderWidth,
1462
+ borderColor,
1463
+ alt
1464
+ }) {
1465
+ const wantsNaturalHeight = height === void 0;
1466
+ const ratio = useImageRatio(uri, wantsNaturalHeight);
1467
+ const style = {
1468
+ width: width ?? "100%",
1469
+ borderRadius,
1470
+ alignSelf: "center",
1471
+ marginBottom: 8,
1472
+ ...borderWidth > 0 ? { borderWidth, borderColor } : {},
1473
+ ...wantsNaturalHeight ? ratio ? { aspectRatio: ratio } : { height: DEFAULT_IMAGE_HEIGHT } : { height }
1474
+ };
1475
+ return /* @__PURE__ */ jsx(
1476
+ Image,
1477
+ {
1478
+ source: { uri },
1479
+ style,
1480
+ resizeMode: wantsNaturalHeight && !ratio ? "contain" : "cover",
1481
+ accessibilityLabel: alt
1482
+ }
1483
+ );
1484
+ }
1485
+ function StoreBadge({
1486
+ uri,
1487
+ height,
1488
+ label,
1489
+ onPress
1490
+ }) {
1491
+ const usable = !!uri && isSafeUrl(uri);
1492
+ const ratio = useImageRatio(usable ? uri : "", usable);
1493
+ const usableHeight = height > 0 ? height : 44;
1494
+ return /* @__PURE__ */ jsx(TouchableOpacity, { onPress, activeOpacity: 0.7, accessibilityRole: "button", children: usable ? /* @__PURE__ */ jsx(
1495
+ Image,
1496
+ {
1497
+ source: { uri },
1498
+ style: { height: usableHeight, width: usableHeight * (ratio || 3.47), marginHorizontal: 6 },
1499
+ resizeMode: "contain",
1500
+ accessibilityLabel: label
1501
+ }
1502
+ ) : (
1503
+ // A text link rather than a blank space, for the case where the badge
1504
+ // artwork itself cannot be loaded.
1505
+ /* @__PURE__ */ jsx(Text, { style: { color: "#1B1B1B", fontSize: 15, fontWeight: "600", marginHorizontal: 6 }, children: label })
1506
+ ) });
1507
+ }
1508
+ var SUPPORTED = /* @__PURE__ */ new Set([
1509
+ "Heading",
1510
+ "TextBlock",
1511
+ "Image",
1512
+ "Button",
1513
+ "DeepLinkButton",
1514
+ "Section",
1515
+ "Spacer",
1516
+ "Divider",
1517
+ "AppIcon",
1518
+ "StoreButtons"
1519
+ ]);
1520
+ function drawsAnything(content, app) {
1521
+ return (content || []).some((c) => {
1522
+ if (!c || !SUPPORTED.has(c.type)) return false;
1523
+ const props = c.props || {};
1524
+ if (c.type === "Image") return isSafeUrl(props.url || "");
1525
+ if (c.type === "DeepLinkButton") return !!app?.deep_link_url;
1526
+ if (c.type === "StoreButtons") {
1527
+ const ios = props.showIos !== false && (props.iosUrlOverride || app?.ios_store_url);
1528
+ const android = props.showAndroid !== false && (props.androidUrlOverride || app?.android_store_url);
1529
+ return !!(ios || android);
1530
+ }
1531
+ return true;
1532
+ });
1533
+ }
1534
+ var MAX_SECTION_DEPTH = 20;
1111
1535
  function PuckComponentRenderer({ component, messageId, options }) {
1112
- const { props } = component;
1536
+ if (!component || typeof component !== "object" || typeof component.type !== "string") return null;
1537
+ const props = component.props && typeof component.props === "object" ? component.props : {};
1538
+ const app = options.app;
1539
+ const follow = (url) => {
1540
+ if (options.onButtonPress) options.onButtonPress(url, messageId);
1541
+ else Linking.openURL(url).catch(() => {
1542
+ });
1543
+ };
1113
1544
  switch (component.type) {
1114
1545
  case "Heading": {
1546
+ const fontSize = num(props.fontSize, 28);
1115
1547
  const style = {
1116
- fontSize: props.fontSize || 28,
1548
+ fontSize,
1117
1549
  fontWeight: "700",
1118
- color: props.color || "#1B1B1B",
1119
- textAlign: props.alignment || "left",
1120
- lineHeight: (props.fontSize || 28) * 1.2,
1550
+ color: color(props.color, "#1B1B1B"),
1551
+ textAlign: alignment(props.alignment),
1552
+ lineHeight: fontSize * 1.2,
1121
1553
  marginBottom: 8
1122
1554
  };
1123
1555
  return /* @__PURE__ */ jsx(Text, { style, children: props.text || "" });
1124
1556
  }
1125
1557
  case "TextBlock": {
1558
+ const fontSize = num(props.fontSize, 15);
1126
1559
  const style = {
1127
- fontSize: props.fontSize || 15,
1128
- color: props.color || "#555555",
1129
- textAlign: props.alignment || "left",
1130
- lineHeight: (props.fontSize || 15) * 1.5,
1560
+ fontSize,
1561
+ color: color(props.color, "#555555"),
1562
+ textAlign: alignment(props.alignment),
1563
+ lineHeight: fontSize * 1.5,
1131
1564
  marginBottom: 8
1132
1565
  };
1133
- return /* @__PURE__ */ jsx(Text, { style, children: props.content || "" });
1566
+ return /* @__PURE__ */ jsx(Text, { style, children: richText(props.content || "", follow) });
1134
1567
  }
1135
1568
  case "Image": {
1136
1569
  const imageUrl = props.url || "";
@@ -1142,82 +1575,85 @@ function PuckComponentRenderer({ component, messageId, options }) {
1142
1575
  debugWarn(`Image URL blocked (unsafe protocol): ${imageUrl}`);
1143
1576
  return null;
1144
1577
  }
1145
- const widthRaw = props.width || "100%";
1146
- let imageWidth = "100%";
1147
- if (widthRaw.endsWith("px")) {
1148
- imageWidth = parseInt(widthRaw, 10);
1149
- } else if (widthRaw.endsWith("%")) {
1150
- imageWidth = widthRaw;
1151
- } else {
1152
- const parsed = parseInt(widthRaw, 10);
1153
- imageWidth = isNaN(parsed) ? "100%" : parsed;
1154
- }
1155
- const style = {
1156
- width: imageWidth,
1157
- height: props.height || 200,
1158
- borderRadius: props.borderRadius || 8,
1159
- alignSelf: "center",
1160
- marginBottom: 8
1161
- };
1162
1578
  return /* @__PURE__ */ jsx(
1163
- Image,
1579
+ MessageImage,
1164
1580
  {
1165
- source: { uri: imageUrl },
1166
- style,
1167
- resizeMode: "cover",
1168
- accessibilityLabel: props.alt || ""
1581
+ uri: imageUrl,
1582
+ width: dimension(props.width) ?? "100%",
1583
+ height: dimension(props.height),
1584
+ borderRadius: num(props.borderRadius, 8),
1585
+ borderWidth: num(props.borderWidth, 0),
1586
+ borderColor: color(props.borderColor, "#1B1B1B"),
1587
+ alt: props.alt || ""
1169
1588
  }
1170
1589
  );
1171
1590
  }
1172
- case "Button": {
1591
+ case "Button":
1592
+ case "DeepLinkButton": {
1593
+ const isDeepLink = component.type === "DeepLinkButton";
1594
+ const action = isDeepLink ? app?.deep_link_url || "" : props.action || "";
1595
+ const label = isDeepLink ? props.label || "Open in App" : props.label || "";
1596
+ if (isDeepLink && !action) return null;
1173
1597
  const handlePress = () => {
1174
- const action = props.action || "";
1175
1598
  if (!action) return;
1176
- if (!isSafeUrl(action)) {
1177
- debugWarn(`Button action URL blocked (unsafe protocol): ${action}`);
1599
+ if (action === "close") {
1600
+ options.onRequestClose?.();
1178
1601
  return;
1179
1602
  }
1180
- if (options.onButtonPress) {
1181
- options.onButtonPress(action, messageId);
1182
- } else {
1183
- Linking.openURL(action).catch(() => {
1184
- });
1603
+ if (!isSafeActionUrl(action)) {
1604
+ debugWarn(`Button action URL blocked (unsafe protocol): ${action}`);
1605
+ return;
1185
1606
  }
1607
+ follow(action);
1186
1608
  };
1609
+ const variant = props.style || "filled";
1610
+ const isOutline = variant === "outline";
1611
+ const tint = variant === "soft" ? softVariant(color(props.bgColor, "#1B1B1B")) : null;
1612
+ const isSoft = tint !== null;
1613
+ const baseColor = color(props.bgColor, "#1B1B1B");
1614
+ const background = isOutline ? "transparent" : isSoft ? tint : baseColor;
1615
+ const labelColor = isOutline || isSoft ? baseColor : color(props.textColor, "#ffffff");
1187
1616
  const containerStyle = {
1188
- backgroundColor: props.bgColor || "#1B1B1B",
1189
- borderRadius: props.borderRadius || 8,
1190
- paddingVertical: 10,
1191
- paddingHorizontal: 20,
1617
+ backgroundColor: background,
1618
+ borderRadius: num(props.borderRadius, 8),
1619
+ paddingVertical: 12,
1620
+ paddingHorizontal: 24,
1192
1621
  marginVertical: 8,
1193
1622
  alignItems: "center",
1194
- ...props.fullWidth ? { width: "100%" } : {}
1623
+ ...isOutline ? { borderWidth: 2, borderColor: baseColor } : {},
1624
+ // A button that is not full width is a compact, centred one. Without
1625
+ // alignSelf it stretches to the column anyway, which made the setting
1626
+ // do nothing at all.
1627
+ ...props.fullWidth ? { width: "100%" } : { alignSelf: "center" }
1195
1628
  };
1196
1629
  const textStyle = {
1197
- color: props.textColor || "#ffffff",
1198
- fontSize: props.fontSize || 16,
1630
+ color: labelColor,
1631
+ fontSize: num(props.fontSize, 16),
1199
1632
  fontWeight: "600"
1200
1633
  };
1201
- return /* @__PURE__ */ jsx(TouchableOpacity, { onPress: handlePress, style: containerStyle, activeOpacity: 0.7, children: /* @__PURE__ */ jsx(Text, { style: textStyle, children: props.label || "Click" }) });
1634
+ const emoji = props.emoji || "";
1635
+ return /* @__PURE__ */ jsx(TouchableOpacity, { onPress: handlePress, style: containerStyle, activeOpacity: 0.7, children: /* @__PURE__ */ jsx(Text, { style: textStyle, children: emoji ? `${emoji} ${label}` : label }) });
1202
1636
  }
1203
1637
  case "Section": {
1204
- const children = props.children || [];
1638
+ const sectionId = typeof props.id === "string" && props.id ? props.id : null;
1639
+ const depth = options.depth || 0;
1640
+ const children = sectionId && depth < MAX_SECTION_DEPTH ? options.zones?.[`${sectionId}:content`] || [] : [];
1205
1641
  const containerStyle = {
1206
- backgroundColor: props.bgColor || void 0,
1207
- padding: props.padding || 16,
1208
- borderRadius: props.borderRadius || 0,
1642
+ backgroundColor: typeof props.bgColor === "string" && props.bgColor ? color(props.bgColor, "transparent") : void 0,
1643
+ padding: num(props.padding, 16),
1644
+ borderRadius: num(props.borderRadius, 0),
1209
1645
  marginVertical: 8
1210
1646
  };
1211
- const bgImage = props.bgImage || "";
1212
1647
  const content = children.map((child, index) => /* @__PURE__ */ jsx(
1213
1648
  PuckComponentRenderer,
1214
1649
  {
1215
1650
  component: child,
1216
1651
  messageId,
1217
- options
1652
+ options: { ...options, depth: depth + 1 }
1218
1653
  },
1219
- `${messageId}-section-${index}-${child.type}`
1654
+ `${messageId}-section-${index}-${child?.type}`
1220
1655
  ));
1656
+ const bgImage = props.bgImage || "";
1221
1657
  if (bgImage) {
1222
1658
  if (!isSafeUrl(bgImage)) {
1223
1659
  debugWarn(`Section background image URL blocked (unsafe protocol): ${bgImage}`);
@@ -1229,32 +1665,93 @@ function PuckComponentRenderer({ component, messageId, options }) {
1229
1665
  source: { uri: bgImage },
1230
1666
  style: containerStyle,
1231
1667
  resizeMode: props.bgSize === "contain" ? "contain" : "cover",
1232
- imageStyle: { borderRadius: props.borderRadius || 0 },
1668
+ imageStyle: { borderRadius: num(props.borderRadius, 0) },
1233
1669
  children: content
1234
1670
  }
1235
1671
  );
1236
1672
  }
1237
1673
  return /* @__PURE__ */ jsx(View, { style: containerStyle, children: content });
1238
1674
  }
1239
- case "Spacer": {
1240
- const style = {
1241
- height: props.height || 24
1242
- };
1243
- return /* @__PURE__ */ jsx(View, { style });
1675
+ case "Spacer":
1676
+ return /* @__PURE__ */ jsx(View, { style: { height: num(props.height, 24) } });
1677
+ case "Divider":
1678
+ return /* @__PURE__ */ jsx(
1679
+ View,
1680
+ {
1681
+ style: {
1682
+ borderTopWidth: num(props.thickness, 1),
1683
+ borderTopColor: color(props.color, "#e5e5e5"),
1684
+ marginVertical: 8
1685
+ }
1686
+ }
1687
+ );
1688
+ case "AppIcon": {
1689
+ const size = num(props.size, 80);
1690
+ const borderRadius = num(props.borderRadius, 16);
1691
+ const iconUrl = app?.icon_url || "";
1692
+ if (!iconUrl || !isSafeUrl(iconUrl)) {
1693
+ return /* @__PURE__ */ jsx(
1694
+ View,
1695
+ {
1696
+ style: { width: size, height: size, borderRadius, backgroundColor: "#f0f0f0", alignSelf: "center", marginBottom: 8 }
1697
+ }
1698
+ );
1699
+ }
1700
+ return /* @__PURE__ */ jsx(
1701
+ Image,
1702
+ {
1703
+ source: { uri: iconUrl },
1704
+ style: { width: size, height: size, borderRadius, alignSelf: "center", marginBottom: 8 },
1705
+ resizeMode: "cover",
1706
+ accessibilityLabel: app?.name || "App icon"
1707
+ }
1708
+ );
1244
1709
  }
1245
- case "Divider": {
1246
- const style = {
1247
- borderTopWidth: props.thickness || 1,
1248
- borderTopColor: props.color || "#e5e5e5",
1249
- marginVertical: 8
1250
- };
1251
- return /* @__PURE__ */ jsx(View, { style });
1710
+ case "StoreButtons": {
1711
+ const iosUrl = props.iosUrlOverride || app?.ios_store_url || "";
1712
+ const androidUrl = props.androidUrlOverride || app?.android_store_url || "";
1713
+ const showIos = props.showIos !== false && !!iosUrl;
1714
+ const showAndroid = props.showAndroid !== false && !!androidUrl;
1715
+ if (!showIos && !showAndroid) return null;
1716
+ const height = num(props.height, 44);
1717
+ const alignment2 = props.alignment;
1718
+ const justifyContent = alignment2 === "left" ? "flex-start" : alignment2 === "right" ? "flex-end" : "center";
1719
+ return /* @__PURE__ */ jsxs(View, { style: { flexDirection: "row", justifyContent, alignItems: "center", flexWrap: "wrap", marginVertical: 8 }, children: [
1720
+ showIos ? /* @__PURE__ */ jsx(
1721
+ StoreBadge,
1722
+ {
1723
+ uri: app?.ios_badge_url,
1724
+ height,
1725
+ label: "Download on the App Store",
1726
+ onPress: () => follow(iosUrl)
1727
+ },
1728
+ "ios"
1729
+ ) : null,
1730
+ showAndroid ? /* @__PURE__ */ jsx(
1731
+ StoreBadge,
1732
+ {
1733
+ uri: app?.android_badge_url,
1734
+ height,
1735
+ label: "Get it on Google Play",
1736
+ onPress: () => follow(androidUrl)
1737
+ },
1738
+ "android"
1739
+ ) : null
1740
+ ] });
1252
1741
  }
1253
1742
  default:
1743
+ debugWarn(`Message component "${component.type}" is not supported here; skipping it.`);
1254
1744
  return null;
1255
1745
  }
1256
1746
  }
1257
- function MessageModal({ message, visible, onClose, options }) {
1747
+ function gradientStartColor(gradient) {
1748
+ if (typeof gradient !== "string" || !gradient) return null;
1749
+ const match = /#[0-9a-f]{3,8}|rgba?\([^)]*\)/i.exec(gradient);
1750
+ if (!match) return null;
1751
+ const validated = color(match[0], "");
1752
+ return validated || null;
1753
+ }
1754
+ function MessageModal({ message, visible, onClose, options, app }) {
1258
1755
  if (!message) {
1259
1756
  return /* @__PURE__ */ jsx(Fragment, {});
1260
1757
  }
@@ -1263,6 +1760,18 @@ function MessageModal({ message, visible, onClose, options }) {
1263
1760
  options.onDismiss?.(message.id);
1264
1761
  onClose();
1265
1762
  };
1763
+ const rootProps = message.content?.root?.props || {};
1764
+ const background = gradientStartColor(rootProps.bgGradient) || (typeof rootProps.bgColor === "string" && rootProps.bgColor ? color(rootProps.bgColor, "") : "") || message.background_color || "#ffffff";
1765
+ const cardStyle = {
1766
+ backgroundColor: background,
1767
+ padding: Math.max(0, num(rootProps.padding, 20)),
1768
+ // Clamped, unlike the other authored numbers. A padding of zero is a
1769
+ // choice; a width of zero is the whole message gone, and the field's own
1770
+ // minimum is zero. The bounds and the default match the server renderer.
1771
+ maxWidth: Math.min(2e3, Math.max(100, num(rootProps.contentWidth, 480)))
1772
+ };
1773
+ const content = message.content?.content || [];
1774
+ const hasDesignedContent = drawsAnything(content, app);
1266
1775
  return /* @__PURE__ */ jsx(
1267
1776
  Modal,
1268
1777
  {
@@ -1270,7 +1779,7 @@ function MessageModal({ message, visible, onClose, options }) {
1270
1779
  transparent: true,
1271
1780
  animationType: "fade",
1272
1781
  onRequestClose: handleDismiss,
1273
- children: /* @__PURE__ */ jsx(Pressable, { style: styles.overlay, onPress: handleDismiss, children: /* @__PURE__ */ jsxs(Pressable, { style: [styles.card, { backgroundColor: message.background_color || "#ffffff" }], onPress: () => {
1782
+ children: /* @__PURE__ */ jsx(Pressable, { style: styles.overlay, onPress: handleDismiss, children: /* @__PURE__ */ jsxs(Pressable, { style: [styles.card, cardStyle], onPress: () => {
1274
1783
  }, children: [
1275
1784
  /* @__PURE__ */ jsx(
1276
1785
  TouchableOpacity,
@@ -1287,15 +1796,23 @@ function MessageModal({ message, visible, onClose, options }) {
1287
1796
  {
1288
1797
  style: styles.scrollContent,
1289
1798
  showsVerticalScrollIndicator: false,
1290
- children: message.content?.content?.map((component, index) => /* @__PURE__ */ jsx(
1799
+ children: hasDesignedContent ? content.map((component, index) => /* @__PURE__ */ jsx(
1291
1800
  PuckComponentRenderer,
1292
1801
  {
1293
1802
  component,
1294
1803
  messageId: message.id,
1295
- options
1804
+ options: {
1805
+ ...options,
1806
+ zones: message.content?.zones,
1807
+ app,
1808
+ onRequestClose: handleDismiss
1809
+ }
1296
1810
  },
1297
1811
  `${message.id}-${index}-${component.type}`
1298
- ))
1812
+ )) : /* @__PURE__ */ jsxs(Fragment, { children: [
1813
+ message.title ? /* @__PURE__ */ jsx(Text, { style: styles.fallbackTitle, children: message.title }) : null,
1814
+ message.body ? /* @__PURE__ */ jsx(Text, { style: styles.fallbackBody, children: message.body }) : null
1815
+ ] })
1299
1816
  }
1300
1817
  )
1301
1818
  ] }) })
@@ -1311,11 +1828,9 @@ var styles = StyleSheet.create({
1311
1828
  },
1312
1829
  card: {
1313
1830
  position: "relative",
1314
- maxWidth: 375,
1315
1831
  width: "90%",
1316
1832
  maxHeight: "80%",
1317
1833
  borderRadius: 16,
1318
- padding: 24,
1319
1834
  shadowColor: "#000",
1320
1835
  shadowOffset: { width: 0, height: 20 },
1321
1836
  shadowOpacity: 0.3,
@@ -1341,6 +1856,19 @@ var styles = StyleSheet.create({
1341
1856
  },
1342
1857
  scrollContent: {
1343
1858
  marginTop: 8
1859
+ },
1860
+ // Used only when a message has no designed content, so its title and body
1861
+ // are all there is to show.
1862
+ fallbackTitle: {
1863
+ fontSize: 20,
1864
+ fontWeight: "700",
1865
+ color: "#1B1B1B",
1866
+ marginBottom: 8
1867
+ },
1868
+ fallbackBody: {
1869
+ fontSize: 15,
1870
+ lineHeight: 22,
1871
+ color: "#555555"
1344
1872
  }
1345
1873
  });
1346
1874
  function TolinkuMessages({
@@ -1351,6 +1879,7 @@ function TolinkuMessages({
1351
1879
  }) {
1352
1880
  const [message, setMessage] = useState(null);
1353
1881
  const [visible, setVisible] = useState(false);
1882
+ const [app, setApp] = useState(null);
1354
1883
  const onDismissRef = useRef(onDismiss);
1355
1884
  onDismissRef.current = onDismiss;
1356
1885
  const onButtonPressRef = useRef(onButtonPress);
@@ -1371,7 +1900,9 @@ function TolinkuMessages({
1371
1900
  const userId = Tolinku.getUserId();
1372
1901
  if (userId) params.user_id = userId;
1373
1902
  const data = await client.get("/v1/api/messages", params);
1374
- if (cancelled || !data.messages || data.messages.length === 0) return;
1903
+ if (cancelled) return;
1904
+ if (data.app) setApp(data.app);
1905
+ if (!data.messages || data.messages.length === 0) return;
1375
1906
  const candidates = [];
1376
1907
  for (const m of data.messages) {
1377
1908
  if (triggerValue && m.trigger_value !== triggerValue) continue;
@@ -1405,7 +1936,8 @@ function TolinkuMessages({
1405
1936
  message,
1406
1937
  visible,
1407
1938
  onClose: handleClose,
1408
- options
1939
+ options,
1940
+ app
1409
1941
  }
1410
1942
  );
1411
1943
  }