@zean-chat/react-native 0.1.15 → 0.1.17

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/README.md CHANGED
@@ -10,7 +10,7 @@ npx expo install @zean-chat/react-native expo-application @react-native-async-st
10
10
  npm install @zean-chat/react-native react-native-device-info @react-native-async-storage/async-storage react-native-image-picker
11
11
  ```
12
12
 
13
- Already using MMKV or Expo SQLite? Skip AsyncStorage: the chat finds your storage by itself, with no code. Already have a photo picker? Skip it too. The photo picker is optional: without one, the chat has no photo button. `expo-application` (Expo) or `react-native-device-info` (React Native CLI) is required: the chat reads your app's Bundle ID or Package name with it, and stays hidden without it.
13
+ Already using MMKV or Expo SQLite? Skip AsyncStorage: the chat finds your storage by itself, with no code. Already have a photo picker? Skip it too. The photo picker is optional: without one, the chat has no photo button. `expo-application` (Expo) or `react-native-device-info` (React Native CLI) is required: the chat reads your app's Bundle ID or Package name with it, and stays hidden without it. It also gives the app version for Device details, and `react-native-device-info` or `expo-device` the exact model.
14
14
 
15
15
  ```tsx
16
16
  import { ZeanChat, useZean } from "@zean-chat/react-native";
package/dist/i18n/en.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  export declare const en: {
2
2
  ai: string;
3
- request_human: string;
4
3
  close_chat: string;
5
4
  online: string;
6
5
  away: string;
package/dist/i18n/fr.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  /** The chat's words, the same as the web widget's. French is the reference: `en.ts` carries the same keys. */
2
2
  export declare const fr: {
3
3
  ai: string;
4
- request_human: string;
5
4
  close_chat: string;
6
5
  online: string;
7
6
  away: string;
package/dist/index.js CHANGED
@@ -76,6 +76,9 @@ var TEST_DEVICE_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
76
76
  var QUOTE_HIGHLIGHT_MS = 1600;
77
77
 
78
78
  // ../shared/src/constants/widget.ts
79
+ var APP_PLATFORMS = ["web", "react_native"];
80
+ var DEVICE_TYPES = ["phone", "tablet", "computer"];
81
+ var DEVICE_DETAIL_MAX_LENGTH = 80;
79
82
  var EXPO_GO_BUNDLE_ID = "host.exp.exponent";
80
83
  var DEFAULT_WIDGET_TEXTS = {
81
84
  fr: {
@@ -144,23 +147,23 @@ function cleanContactUser(value) {
144
147
  if (typeof id !== "string" || !id.trim() || id.trim().length > CONTACT_ID_MAX_LENGTH) return { user: null, dropped: [] };
145
148
  const user = { id: id.trim() };
146
149
  const dropped = [];
147
- const text = (key) => {
150
+ const text2 = (key) => {
148
151
  const raw = input[key];
149
152
  if (raw === void 0 || raw === null) return null;
150
153
  const cleaned = typeof raw === "string" ? squashSpaces(raw) : "";
151
154
  if (!cleaned) dropped.push(key);
152
155
  return cleaned || null;
153
156
  };
154
- const name = text("name");
157
+ const name = text2("name");
155
158
  if (name !== null && name.length <= CONTACT_NAME_MAX_LENGTH) user.name = name;
156
159
  else if (name !== null) dropped.push("name");
157
- const email = text("email");
160
+ const email = text2("email");
158
161
  if (email !== null && isEmail(normaliseEmail(email))) user.email = normaliseEmail(email);
159
162
  else if (email !== null) dropped.push("email");
160
- const phone = text("phone");
163
+ const phone = text2("phone");
161
164
  if (phone !== null && phone.length <= CONTACT_PHONE_MAX_LENGTH && PHONE_PATTERN.test(phone)) user.phone = phone;
162
165
  else if (phone !== null) dropped.push("phone");
163
- const language = text("language");
166
+ const language = text2("language");
164
167
  if (language !== null && LANGUAGE_TAG_PATTERN.test(language)) user.language = languageTag(language);
165
168
  else if (language !== null) dropped.push("language");
166
169
  return { user, dropped };
@@ -190,8 +193,8 @@ function isWithinBusinessHours(hours, at) {
190
193
  const { weekday, minutes } = clockIn(hours.timeZone, at);
191
194
  return hours.days.some((day) => day.weekday === weekday && minutesOf(day.opens) <= minutes && minutes < minutesOf(day.closes));
192
195
  }
193
- function pickText(text, locale, defaultLocale, fallback) {
194
- return text?.[locale]?.trim() || text?.[defaultLocale]?.trim() || fallback[locale];
196
+ function pickText(text2, locale, defaultLocale, fallback) {
197
+ return text2?.[locale]?.trim() || text2?.[defaultLocale]?.trim() || fallback[locale];
195
198
  }
196
199
  function clockIn(timeZone, at) {
197
200
  let parts;
@@ -227,9 +230,26 @@ var KEPT_MESSAGES = 100;
227
230
  var KEPT_VERSION = 1;
228
231
  var LIVE_AFTER_CLOSE_MS = 2 * 6e4;
229
232
  var ADVANCE_AFTER = WIDGET_PAGE_SIZE / 2;
233
+ var QUIET_CALLS = /* @__PURE__ */ new Set(["start", "reportInstall", "setTyping", "setPushToken", "markRead", "signOut"]);
230
234
  function emailKey(offer) {
231
235
  return `${offer.kind}:${offer.email}`;
232
236
  }
237
+ function placeShowsApp(place) {
238
+ return place.app !== void 0;
239
+ }
240
+ function joinedSession(place, own) {
241
+ if (!placeShowsApp(place)) return place;
242
+ if (own.state === "not_found") return own;
243
+ const blocked = own.state === "blocked";
244
+ return {
245
+ state: place.state === "unavailable" ? "unavailable" : blocked ? "blocked" : "ready",
246
+ app: place.app,
247
+ contact: own.contact,
248
+ emailCode: place.state === "ready" && !blocked ? own.emailCode : null,
249
+ identity: own.identity,
250
+ report: place.report
251
+ };
252
+ }
233
253
  function createChatStore(backend, options) {
234
254
  const secretKey = `zean:${options.appKey}:device`;
235
255
  const outboxKey = `zean:${options.appKey}:outbox`;
@@ -280,7 +300,7 @@ function createChatStore(backend, options) {
280
300
  let identifying = null;
281
301
  let identified = false;
282
302
  let identifiedKnown = false;
283
- let watchers = [];
303
+ let sessionWatch = null;
284
304
  let pushToken2;
285
305
  let pushSent = null;
286
306
  let destroyed = false;
@@ -303,8 +323,7 @@ function createChatStore(backend, options) {
303
323
  const device = () => ({
304
324
  locale: state.locale,
305
325
  ...deviceLanguage ? { language: deviceLanguage } : {},
306
- browser: options.browser,
307
- os: options.os,
326
+ ...options.deviceDetails ? { details: options.deviceDetails() } : {},
308
327
  timeZone
309
328
  });
310
329
  const deviceWaiters = [];
@@ -335,14 +354,76 @@ function createChatStore(backend, options) {
335
354
  stops.push(() => clearInterval(clock));
336
355
  })();
337
356
  function watchAll() {
338
- watchers = [
339
- backend.watch("session", args(), handleSession, () => {
340
- failedToLoad = true;
341
- emit2();
342
- })
343
- ];
357
+ watchSession();
344
358
  if (!keep || open2) watchLive();
345
359
  }
360
+ function sessionLive() {
361
+ return !keep || open2 || session !== null && historyOf(session) !== null;
362
+ }
363
+ function watchSession() {
364
+ sessionWatch?.stop();
365
+ const live = sessionLive();
366
+ let stopped = false;
367
+ const watches = [];
368
+ const entry = {
369
+ live,
370
+ // Once: the Convex client throws on a second unsubscribe.
371
+ stop: () => {
372
+ if (stopped) return;
373
+ stopped = true;
374
+ for (const stop of watches.splice(0)) stop();
375
+ }
376
+ };
377
+ sessionWatch = entry;
378
+ let place = null;
379
+ let own = null;
380
+ const handle = () => {
381
+ if (!place || !own) return;
382
+ handleSession(joinedSession(place, own));
383
+ if (!live && sessionWatch === entry) entry.stop();
384
+ };
385
+ const handleError = () => {
386
+ failedToLoad = true;
387
+ emit2();
388
+ };
389
+ const { deviceSecret: secret, ...where } = args();
390
+ const placeStop = backend.watch(
391
+ "place",
392
+ where,
393
+ (result) => {
394
+ place = result;
395
+ handle();
396
+ },
397
+ handleError
398
+ );
399
+ watches.push(placeStop);
400
+ const deviceStop = backend.watch(
401
+ "device",
402
+ { appKey: options.appKey, deviceSecret: secret },
403
+ (result) => {
404
+ own = result;
405
+ handle();
406
+ },
407
+ handleError
408
+ );
409
+ if (stopped) deviceStop();
410
+ else watches.push(deviceStop);
411
+ }
412
+ function updateSessionLive() {
413
+ if (!sessionWatch || sessionWatch.live === sessionLive()) return;
414
+ if (sessionLive()) watchSession();
415
+ else {
416
+ sessionWatch.stop();
417
+ sessionWatch = { live: false, stop: () => {
418
+ } };
419
+ }
420
+ }
421
+ function rereadSession() {
422
+ if (sessionWatch && !sessionWatch.live && deviceSecret && !destroyed) watchSession();
423
+ }
424
+ const call = (name, input) => backend.call(name, input).finally(() => {
425
+ if (!QUIET_CALLS.has(name)) rereadSession();
426
+ });
346
427
  function watchLive() {
347
428
  watchMessages();
348
429
  stopTyping?.();
@@ -392,7 +473,7 @@ function createChatStore(backend, options) {
392
473
  if (mine !== generation || destroyed || !deviceSecret) return;
393
474
  identifiedKnown = state.known;
394
475
  try {
395
- const result = await backend.call("identify", { ...args(), user: person, device: device() });
476
+ const result = await call("identify", { ...args(), user: person, device: device() });
396
477
  if (mine !== generation) return;
397
478
  idCode = result.state === "code_available" ? { email: result.email, sent: idCode?.sent ?? false } : null;
398
479
  identified = true;
@@ -420,12 +501,13 @@ function createChatStore(backend, options) {
420
501
  emit2();
421
502
  if ("report" in result && result.report && !reported) {
422
503
  reported = true;
423
- backend.call("reportInstall", args()).catch(() => {
504
+ call("reportInstall", args()).catch(() => {
424
505
  });
425
506
  }
426
507
  startOnce();
427
508
  if (state.known && !state.verified && !identifiedKnown && user && !identifying) void sendIdentity();
428
509
  if (state.known && Object.keys(heldAttributes).length > 0) void sendAttributes();
510
+ updateSessionLive();
429
511
  }
430
512
  async function sendAttributes() {
431
513
  if (identifying) await identifying;
@@ -434,7 +516,7 @@ function createChatStore(backend, options) {
434
516
  heldAttributes = {};
435
517
  saveAttributes();
436
518
  try {
437
- await backend.call("setAttributes", { ...args(), attributes: attributes2 });
519
+ await call("setAttributes", { ...args(), attributes: attributes2 });
438
520
  return { ok: true };
439
521
  } catch (error) {
440
522
  if (codeOf(error) === "invalid_attributes")
@@ -447,7 +529,7 @@ function createChatStore(backend, options) {
447
529
  if (pushSent?.deviceSecret === deviceSecret && pushSent.token === pushToken2) return;
448
530
  const sent = { deviceSecret, token: pushToken2 };
449
531
  pushSent = sent;
450
- backend.call("setPushToken", { ...args(), token: pushToken2 }).catch((error) => {
532
+ call("setPushToken", { ...args(), token: pushToken2 }).catch((error) => {
451
533
  if (pushSent === sent) pushSent = null;
452
534
  if (codeOf(error) === "invalid_push_token") console.warn(`${APP_NAME}: the push token was refused: it is too long.`);
453
535
  });
@@ -455,7 +537,7 @@ function createChatStore(backend, options) {
455
537
  function startOnce() {
456
538
  if (started || state.status === "loading" || state.status === "hidden") return;
457
539
  started = true;
458
- if (state.known || devLoad) backend.call("start", { ...args(), device: device() }).catch(() => {
540
+ if (state.known || devLoad) call("start", { ...args(), device: device() }).catch(() => {
459
541
  });
460
542
  for (const entry of outbox) if (entry.error === null) deliver(entry);
461
543
  }
@@ -507,7 +589,7 @@ function createChatStore(backend, options) {
507
589
  );
508
590
  }
509
591
  function deliver(entry) {
510
- backend.call("send", {
592
+ call("send", {
511
593
  ...args(),
512
594
  body: entry.body,
513
595
  ...entry.attachments ? { attachments: entry.attachments } : {},
@@ -735,25 +817,25 @@ function createChatStore(backend, options) {
735
817
  getState: () => state,
736
818
  draft: () => draft2 ? { text: draft2.text, files: draft2.files } : null,
737
819
  saveDraft(given) {
738
- const text = given.text;
820
+ const text2 = given.text;
739
821
  const files = given.files.map((file) => file.uri && /^https?:/i.test(file.uri) ? { ...file, uri: null } : file);
740
- if (!text.trim() && files.length === 0) {
822
+ if (!text2.trim() && files.length === 0) {
741
823
  writeDraft(null);
742
824
  return;
743
825
  }
744
- if (draft2 && JSON.stringify({ text, files }) === JSON.stringify({ text: draft2.text, files: draft2.files })) return;
745
- writeDraft({ text, files, history: session ? historyOf(session) : null, updatedAt: Date.now() });
826
+ if (draft2 && JSON.stringify({ text: text2, files }) === JSON.stringify({ text: draft2.text, files: draft2.files })) return;
827
+ writeDraft({ text: text2, files, history: session ? historyOf(session) : null, updatedAt: Date.now() });
746
828
  },
747
829
  subscribe(listener) {
748
830
  listeners2.add(listener);
749
831
  return () => listeners2.delete(listener);
750
832
  },
751
833
  send(body, attachments = []) {
752
- const text = body.trim();
753
- if (!text && attachments.length === 0 || !deviceSecret) return;
834
+ const text2 = body.trim();
835
+ if (!text2 && attachments.length === 0 || !deviceSecret) return;
754
836
  const entry = {
755
837
  clientId: newClientId(),
756
- body: text,
838
+ body: text2,
757
839
  ...attachments.length > 0 ? { attachments } : {},
758
840
  createdAt: Date.now(),
759
841
  error: null
@@ -795,26 +877,27 @@ function createChatStore(backend, options) {
795
877
  if (open2 === value) return;
796
878
  open2 = value;
797
879
  if (!keep) return;
880
+ updateSessionLive();
798
881
  keepLive();
799
882
  if (!value) stopLiveLater();
800
883
  else if (!stopMessages && deviceSecret) watchLive();
801
884
  },
802
885
  markRead() {
803
886
  if (state.unread === 0 || !deviceSecret) return;
804
- backend.call("markRead", args()).catch(() => {
887
+ call("markRead", args()).catch(() => {
805
888
  });
806
889
  },
807
890
  typing() {
808
891
  const now = Date.now();
809
892
  if (state.status !== "ready" || !state.known || now - lastTypingSignal < TYPING_SIGNAL_MS) return;
810
893
  lastTypingSignal = now;
811
- backend.call("setTyping", args()).catch(() => {
894
+ call("setTyping", args()).catch(() => {
812
895
  });
813
896
  },
814
897
  async setEmail(email) {
815
898
  if (!deviceSecret) return { ok: false, code: "not_found" };
816
899
  try {
817
- await backend.call("setEmail", { ...args(), email });
900
+ await call("setEmail", { ...args(), email });
818
901
  emailGiven = true;
819
902
  emit2();
820
903
  return { ok: true };
@@ -868,10 +951,10 @@ function createChatStore(backend, options) {
868
951
  if (!deviceSecret || !offer || offer.kind === "id" && !person) return { ok: false, code: "not_found" };
869
952
  try {
870
953
  if (offer.kind !== "id") {
871
- await backend.call("requestEmailCode", args());
954
+ await call("requestEmailCode", args());
872
955
  emailCodeSent = emailKey(offer);
873
956
  } else {
874
- await backend.call("requestCode", { ...args(), userId: person.id });
957
+ await call("requestCode", { ...args(), userId: person.id });
875
958
  if (idCode && user === person) idCode = { ...idCode, sent: true };
876
959
  }
877
960
  emit2();
@@ -886,13 +969,13 @@ function createChatStore(backend, options) {
886
969
  if (!deviceSecret || !offer || offer.kind === "id" && !person) return { ok: false, code: "not_found" };
887
970
  try {
888
971
  if (offer.kind !== "id") {
889
- const result2 = await backend.call("confirmEmailCode", { ...args(), code: code2 });
972
+ const result2 = await call("confirmEmailCode", { ...args(), code: code2 });
890
973
  if (!result2.ok) return result2;
891
974
  emailCodeSent = null;
892
975
  emit2();
893
976
  return { ok: true };
894
977
  }
895
- const result = await backend.call("confirmCode", { ...args(), userId: person.id, code: code2 });
978
+ const result = await call("confirmCode", { ...args(), userId: person.id, code: code2 });
896
979
  if (!result.ok) return result;
897
980
  idCode = null;
898
981
  emit2();
@@ -908,7 +991,7 @@ function createChatStore(backend, options) {
908
991
  if (offer.kind === "id") idCodeDismissed = true;
909
992
  else {
910
993
  emailCodeDismissed = emailKey(offer);
911
- backend.call("dismissEmailCode", args()).catch(() => {
994
+ call("dismissEmailCode", args()).catch(() => {
912
995
  });
913
996
  }
914
997
  emit2();
@@ -927,10 +1010,10 @@ function createChatStore(backend, options) {
927
1010
  emailGiven = false;
928
1011
  identifying = null;
929
1012
  identifiedKnown = false;
930
- if (deviceSecret) backend.call("signOut", args()).catch(() => {
1013
+ if (deviceSecret) call("signOut", args()).catch(() => {
931
1014
  });
932
- for (const stop of watchers) stop();
933
- watchers = [];
1015
+ sessionWatch?.stop();
1016
+ sessionWatch = null;
934
1017
  stopLive();
935
1018
  forgetKept();
936
1019
  forgetDraft();
@@ -961,7 +1044,7 @@ function createChatStore(backend, options) {
961
1044
  await starting;
962
1045
  await deviceKnown();
963
1046
  if (destroyed || !deviceSecret) return;
964
- await backend.call("joinWithPass", { ...args(), pass }).catch(() => {
1047
+ await call("joinWithPass", { ...args(), pass }).catch(() => {
965
1048
  });
966
1049
  },
967
1050
  destroy() {
@@ -969,7 +1052,7 @@ function createChatStore(backend, options) {
969
1052
  for (const resolve of deviceWaiters.splice(0)) resolve();
970
1053
  stopMessages?.();
971
1054
  stopTyping?.();
972
- for (const stop of watchers) stop();
1055
+ sessionWatch?.stop();
973
1056
  for (const stop of stops) stop();
974
1057
  if (typingTimer) clearTimeout(typingTimer);
975
1058
  keepLive();
@@ -4483,9 +4566,9 @@ var markNames = [
4483
4566
  "convexFirstMessageReceived"
4484
4567
  ];
4485
4568
  function mark(name, sessionId) {
4486
- const detail = { sessionId };
4569
+ const detail2 = { sessionId };
4487
4570
  if (typeof performance === "undefined" || !performance.mark) return;
4488
- performance.mark(name, { detail });
4571
+ performance.mark(name, { detail: detail2 });
4489
4572
  }
4490
4573
  function performanceMarkToJson(mark2) {
4491
4574
  let name = mark2.name.slice("convex".length);
@@ -6496,10 +6579,99 @@ var MAX_ATTACHMENTS = 6;
6496
6579
  var MAX_IMAGE_SIDE = 1600;
6497
6580
  var IMAGE_TYPES = ["image/jpeg", "image/png", "image/webp"];
6498
6581
 
6582
+ // ../shared/src/utils/devices.ts
6583
+ var BROWSERS = [
6584
+ [/Edg(?:A|iOS)?\/(\d+)/, "Edge"],
6585
+ [/OPR\/(\d+)/, "Opera"],
6586
+ [/SamsungBrowser\/(\d+)/, "Samsung Internet"],
6587
+ [/(?:Firefox|FxiOS)\/(\d+)/, "Firefox"],
6588
+ [/(?:Chrome|CriOS)\/(\d+)/, "Chrome"],
6589
+ [/Version\/(\d+)[^ ]* (?:Mobile\/\S+ )?Safari/, "Safari"]
6590
+ ];
6591
+ var ANDROID_BRANDS = [
6592
+ [/^(?:SM-|Galaxy)/i, "Samsung"],
6593
+ [/^Pixel/i, "Google"],
6594
+ [/^(?:Redmi|POCO|Mi |M2\d)/i, "Xiaomi"],
6595
+ [/^moto/i, "Motorola"],
6596
+ [/^(?:ONEPLUS|CPH)/i, "OnePlus"],
6597
+ [/^(?:TECNO)/i, "Tecno"],
6598
+ [/^(?:Infinix)/i, "Infinix"],
6599
+ [/^(?:itel)/i, "itel"],
6600
+ [/^(?:HUAWEI)/i, "Huawei"],
6601
+ [/^Nokia/i, "Nokia"]
6602
+ ];
6603
+ var HIDDEN_MODELS = /* @__PURE__ */ new Set(["K", "wv", "Mobile", "Tablet"]);
6604
+ var SCREEN_MAX = 2e4;
6605
+ function detailsFromUserAgent(userAgent, touchPoints = 0) {
6606
+ const browser = browserOf(userAgent);
6607
+ const details = { platform: "web", ...browser ? { browser } : {} };
6608
+ const ios = /(iPhone|iPad|iPod)[^)]*?OS (\d+)[_.](\d+)/.exec(userAgent) ?? /(iPhone|iPad|iPod)/.exec(userAgent);
6609
+ if (ios) {
6610
+ const model = ios[1] === "iPod" ? "iPod touch" : ios[1];
6611
+ const version2 = ios[2] ? ` ${ios[2]}.${ios[3]}` : "";
6612
+ return { ...details, type: ios[1] === "iPad" ? "tablet" : "phone", brand: "Apple", model, os: `iOS${version2}` };
6613
+ }
6614
+ const android = /Android (\d+(?:\.\d+)?)(?:; ([^;)]+?))?(?: Build\/[^;)]*)?[;)]/.exec(userAgent);
6615
+ if (android) {
6616
+ const named = android[2]?.trim();
6617
+ const model = named && !HIDDEN_MODELS.has(named) ? named : void 0;
6618
+ const brand = model && brandOf(model);
6619
+ return {
6620
+ ...details,
6621
+ type: /Mobile/.test(userAgent) ? "phone" : "tablet",
6622
+ ...brand ? { brand } : {},
6623
+ ...model ? { model } : {},
6624
+ os: `Android ${android[1]}`
6625
+ };
6626
+ }
6627
+ if (/Macintosh|Mac OS X/.test(userAgent)) {
6628
+ if (touchPoints > 1) return { ...details, type: "tablet", brand: "Apple", model: "iPad", os: "iOS" };
6629
+ return { ...details, type: "computer", brand: "Apple", model: "Mac", os: "macOS" };
6630
+ }
6631
+ const computer = [
6632
+ [/Windows/, "Windows"],
6633
+ [/CrOS/, "ChromeOS"],
6634
+ [/Linux/, "Linux"]
6635
+ ].find(([pattern]) => pattern.test(userAgent));
6636
+ return computer ? { ...details, type: "computer", os: computer[1] } : details;
6637
+ }
6638
+ function uprightScreen(screen, type) {
6639
+ if (!(screen.width > 0 && screen.height > 0)) return void 0;
6640
+ if (type === "computer") return { width: screen.width, height: screen.height };
6641
+ return { width: Math.min(screen.width, screen.height), height: Math.max(screen.width, screen.height) };
6642
+ }
6643
+ function cleanDeviceDetails(details) {
6644
+ const texts = ["brand", "model", "os", "browser", "appVersion", "appBuild"].flatMap((key) => {
6645
+ const value = details[key]?.trim().slice(0, DEVICE_DETAIL_MAX_LENGTH);
6646
+ return value ? [[key, value]] : [];
6647
+ });
6648
+ const width = Math.round(details.screen?.width ?? 0);
6649
+ const height = Math.round(details.screen?.height ?? 0);
6650
+ const screen = width > 0 && height > 0 && width <= SCREEN_MAX && height <= SCREEN_MAX ? { width, height } : null;
6651
+ return {
6652
+ ...details.platform && APP_PLATFORMS.includes(details.platform) ? { platform: details.platform } : {},
6653
+ ...details.type && DEVICE_TYPES.includes(details.type) ? { type: details.type } : {},
6654
+ ...Object.fromEntries(texts),
6655
+ ...screen ? { screen } : {}
6656
+ };
6657
+ }
6658
+ function browserOf(userAgent) {
6659
+ for (const [pattern, name] of BROWSERS) {
6660
+ const match = pattern.exec(userAgent);
6661
+ if (match) return `${name} ${match[1]}`;
6662
+ }
6663
+ return void 0;
6664
+ }
6665
+ function brandOf(model) {
6666
+ return ANDROID_BRANDS.find(([pattern]) => pattern.test(model))?.[1];
6667
+ }
6668
+
6499
6669
  // src/models/sdk.constants.ts
6500
6670
  var OFFLINE_NOTICE_MS = 3e3;
6501
6671
  var ANDROID_NAVIGATION_BAR = 48;
6502
6672
  var DEFAULT_MAX_PHOTOS = 4;
6673
+ var ANDROID_TABLET_SIDE = 600;
6674
+ var EXPO_DEVICE_TYPES = { 1: "phone", 2: "tablet", 3: "computer" };
6503
6675
  var CHAT_STORAGE_ID = "zean-chat";
6504
6676
  var LINK_RETRY_MS = 1500;
6505
6677
  var LINK_RETRIES = 5;
@@ -6571,7 +6743,7 @@ function deviceLanguages() {
6571
6743
  }
6572
6744
  function appBundle() {
6573
6745
  if (import_react_native.Platform.OS !== "ios" && import_react_native.Platform.OS !== "android") return void 0;
6574
- const id = expoApplicationId() ?? deviceInfoBundleId();
6746
+ const id = text(expoApplication()?.applicationId) ?? text(detail(deviceInfo()?.getBundleId));
6575
6747
  return id ? { os: import_react_native.Platform.OS, id } : void 0;
6576
6748
  }
6577
6749
  function chatStorage(storage) {
@@ -6638,23 +6810,38 @@ function isKeyValue(value) {
6638
6810
  const { getItem, setItem } = value;
6639
6811
  return typeof getItem === "function" && typeof setItem === "function";
6640
6812
  }
6641
- function expoApplicationId() {
6813
+ function expoApplication() {
6642
6814
  try {
6643
- const expo = require("expo-application");
6644
- return typeof expo?.applicationId === "string" ? expo.applicationId : null;
6815
+ return require("expo-application");
6645
6816
  } catch {
6646
6817
  return null;
6647
6818
  }
6648
6819
  }
6649
- function deviceInfoBundleId() {
6820
+ function expoDevice() {
6821
+ try {
6822
+ return require("expo-device");
6823
+ } catch {
6824
+ return null;
6825
+ }
6826
+ }
6827
+ function deviceInfo() {
6650
6828
  try {
6651
6829
  const module2 = require("react-native-device-info");
6652
- const getBundleId = module2?.getBundleId ?? module2?.default?.getBundleId;
6653
- return typeof getBundleId === "function" ? getBundleId() : null;
6830
+ return module2 && { ...module2.default, ...module2 };
6654
6831
  } catch {
6655
6832
  return null;
6656
6833
  }
6657
6834
  }
6835
+ function detail(read) {
6836
+ try {
6837
+ return read?.();
6838
+ } catch {
6839
+ return void 0;
6840
+ }
6841
+ }
6842
+ function text(value) {
6843
+ return typeof value === "string" && value.trim() !== "" && value !== "unknown" ? value : void 0;
6844
+ }
6658
6845
  function isDevBuild() {
6659
6846
  return typeof __DEV__ !== "undefined" && __DEV__;
6660
6847
  }
@@ -6676,10 +6863,57 @@ function objectOf(data) {
6676
6863
  }
6677
6864
  return typeof value === "object" && value !== null ? value : null;
6678
6865
  }
6679
- function deviceOs() {
6680
- if (import_react_native.Platform.OS === "ios") return `iOS ${import_react_native.Platform.Version}`;
6681
- if (import_react_native.Platform.OS === "android") return `Android ${import_react_native.Platform.constants.Release}`;
6682
- return void 0;
6866
+ function deviceDetails() {
6867
+ const screen = import_react_native.Dimensions.get("screen");
6868
+ const system = systemDetails(screen);
6869
+ const installed = import_react_native.Platform.OS === "web" ? {} : installedDetails();
6870
+ const type = installed.type ?? system.type;
6871
+ return cleanDeviceDetails({
6872
+ ...system,
6873
+ platform: "react_native",
6874
+ type,
6875
+ brand: installed.brand ?? system.brand,
6876
+ model: installed.model ?? system.model,
6877
+ screen: uprightScreen(screen, type),
6878
+ appVersion: installed.appVersion,
6879
+ appBuild: installed.appBuild
6880
+ });
6881
+ }
6882
+ function systemDetails(screen) {
6883
+ if (import_react_native.Platform.OS === "ios") {
6884
+ const pad = import_react_native.Platform.isPad;
6885
+ return { type: pad ? "tablet" : "phone", brand: "Apple", model: pad ? "iPad" : "iPhone", os: `iOS ${import_react_native.Platform.Version}` };
6886
+ }
6887
+ if (import_react_native.Platform.OS === "android") {
6888
+ const { Release, Brand, Manufacturer, Model } = import_react_native.Platform.constants;
6889
+ const tablet = Math.min(screen.width, screen.height) >= ANDROID_TABLET_SIDE;
6890
+ return { type: tablet ? "tablet" : "phone", brand: brandName(Brand || Manufacturer), model: Model, os: `Android ${Release}` };
6891
+ }
6892
+ if (import_react_native.Platform.OS === "web") {
6893
+ const { userAgent, maxTouchPoints } = globalThis.navigator;
6894
+ return detailsFromUserAgent(userAgent, maxTouchPoints);
6895
+ }
6896
+ return {};
6897
+ }
6898
+ function installedDetails() {
6899
+ const device = expoDevice();
6900
+ const application = expoApplication();
6901
+ const info = deviceInfo();
6902
+ const tablet = detail(info?.isTablet);
6903
+ const infoType = typeof tablet === "boolean" ? tablet ? "tablet" : "phone" : void 0;
6904
+ return {
6905
+ type: EXPO_DEVICE_TYPES[Number(device?.deviceType)] ?? infoType,
6906
+ brand: brandName(text(device?.brand) ?? text(detail(info?.getBrand))),
6907
+ model: text(device?.modelName) ?? text(detail(info?.getModel)),
6908
+ appVersion: text(application?.nativeApplicationVersion) ?? text(detail(info?.getVersion)),
6909
+ appBuild: text(application?.nativeBuildVersion) ?? text(detail(info?.getBuildNumber))
6910
+ };
6911
+ }
6912
+ function brandName(brand) {
6913
+ if (!brand) return void 0;
6914
+ const shouted = brand.length > 3 && brand === brand.toUpperCase();
6915
+ if (brand !== brand.toLowerCase() && !shouted) return brand;
6916
+ return brand.charAt(0).toUpperCase() + brand.slice(1).toLowerCase();
6683
6917
  }
6684
6918
  function screenInsets() {
6685
6919
  if (import_react_native.Platform.OS === "android") {
@@ -6831,7 +7065,6 @@ function useChatContext() {
6831
7065
  // src/i18n/en.ts
6832
7066
  var en = {
6833
7067
  ai: "AI",
6834
- request_human: "Talk to a Member",
6835
7068
  close_chat: "Close chat",
6836
7069
  online: "Online",
6837
7070
  away: "Away for now",
@@ -6891,7 +7124,6 @@ var en = {
6891
7124
  // src/i18n/fr.ts
6892
7125
  var fr = {
6893
7126
  ai: "IA",
6894
- request_human: "Parler \xE0 un membre",
6895
7127
  close_chat: "Fermer le chat",
6896
7128
  online: "En ligne",
6897
7129
  away: "Absents pour le moment",
@@ -7605,11 +7837,11 @@ var styles6 = import_react_native10.StyleSheet.create({
7605
7837
  var import_jsx_runtime8 = require("react/jsx-runtime");
7606
7838
  function Composer() {
7607
7839
  const { chat: chat2, t, colors } = useChatContext();
7608
- const [text, setText] = (0, import_react8.useState)(() => chat2.draft()?.text ?? "");
7609
- const typed = (0, import_react8.useRef)(text);
7840
+ const [text2, setText] = (0, import_react8.useState)(() => chat2.draft()?.text ?? "");
7841
+ const typed = (0, import_react8.useRef)(text2);
7610
7842
  const pending = usePendingPhotos();
7611
7843
  const picker = photoPicker();
7612
- const canSend = !pending.sending && (text.trim().length > 0 || pending.photos.length > 0);
7844
+ const canSend = !pending.sending && (text2.trim().length > 0 || pending.photos.length > 0);
7613
7845
  const draft2 = (0, import_react8.useSyncExternalStore)(subscribeChatView, chatDraft);
7614
7846
  const changeText = (value) => {
7615
7847
  typed.current = value;
@@ -7621,8 +7853,8 @@ function Composer() {
7621
7853
  clearDraft();
7622
7854
  }, [draft2]);
7623
7855
  (0, import_react8.useEffect)(() => {
7624
- chat2.saveDraft({ text, files: pending.draftFiles });
7625
- }, [chat2, text, pending.draftFiles]);
7856
+ chat2.saveDraft({ text: text2, files: pending.draftFiles });
7857
+ }, [chat2, text2, pending.draftFiles]);
7626
7858
  const handleSend = async () => {
7627
7859
  const attachments = pending.photos.length > 0 ? await pending.send() : [];
7628
7860
  if (!attachments) return;
@@ -7660,7 +7892,7 @@ function Composer() {
7660
7892
  /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
7661
7893
  import_react_native11.TextInput,
7662
7894
  {
7663
- value: text,
7895
+ value: text2,
7664
7896
  onChangeText: (value) => {
7665
7897
  changeText(value);
7666
7898
  chat2.typing();
@@ -8033,7 +8265,7 @@ function MessageQuote({ quote, app, onQuote }) {
8033
8265
  const image = quoteImageOf(quote);
8034
8266
  const links = useAttachmentLinks(chat2, image ? [image.key] : [], true);
8035
8267
  const url = image && links.get(image.key);
8036
- const text = quoteLineOf(quote, { deleted: t.message_deleted, photo: t.photo });
8268
+ const text2 = quoteLineOf(quote, { deleted: t.message_deleted, photo: t.photo });
8037
8269
  const { deleted } = quote;
8038
8270
  return /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(
8039
8271
  import_react_native17.Pressable,
@@ -8051,7 +8283,7 @@ function MessageQuote({ quote, app, onQuote }) {
8051
8283
  children: [
8052
8284
  /* @__PURE__ */ (0, import_jsx_runtime13.jsxs)(import_react_native17.View, { style: styles11.lines, children: [
8053
8285
  /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react_native17.Text, { style: [styles11.name, { color: colors.primaryText }], numberOfLines: 1, children: quoteAuthorOf(quote, t.you, app.name) }),
8054
- /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react_native17.Text, { style: [styles11.text, { color: colors.muted }, quote.deleted && styles11.deleted], numberOfLines: 1, children: text })
8286
+ /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react_native17.Text, { style: [styles11.text, { color: colors.muted }, quote.deleted && styles11.deleted], numberOfLines: 1, children: text2 })
8055
8287
  ] }),
8056
8288
  image && (url ? /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(import_react_native17.Image, { source: { uri: url }, style: [styles11.thumb, { borderColor: colors.border }], accessibilityIgnoresInvertColors: true }) : /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Skeleton, { style: [styles11.thumb, { borderColor: colors.border }] }))
8057
8289
  ]
@@ -8189,7 +8421,6 @@ var MessageBubble = (0, import_react13.memo)(function MessageBubble2({ row, app,
8189
8421
  /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(MessageFiles, { attachments: message.attachments, own: false, stored: true })
8190
8422
  ] })
8191
8423
  ] }),
8192
- message.ai && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_react_native19.Pressable, { accessibilityRole: "button", onPress: () => chat2.send(t.request_human), hitSlop: 8, style: styles13.teamMeta, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_react_native19.Text, { style: [styles13.human, { color: colors.primaryText }], children: t.request_human }) }),
8193
8424
  endsRun && !row.welcome && /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_react_native19.View, { style: styles13.teamMeta, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(MessageMeta, { row, onRetry: handleRetry }) })
8194
8425
  ] })
8195
8426
  ]
@@ -8218,7 +8449,6 @@ var styles13 = import_react_native19.StyleSheet.create({
8218
8449
  avatar: { width: AVATAR },
8219
8450
  teamColumn: { flexShrink: 1, alignItems: "flex-start", gap: 4 },
8220
8451
  teamMeta: { marginLeft: AVATAR + 8 },
8221
- human: { fontSize: 13, fontWeight: "600", textDecorationLine: "underline", paddingVertical: 8 },
8222
8452
  bubble: {
8223
8453
  borderRadius: RADII.group,
8224
8454
  paddingHorizontal: 14,
@@ -8559,7 +8789,8 @@ function ZeanChat({
8559
8789
  // A chosen language goes first: the chat takes the first one it speaks.
8560
8790
  languages: locale ? [locale] : deviceLanguages(),
8561
8791
  deviceLanguage: deviceLanguages()[0],
8562
- os: deviceOs(),
8792
+ // Read again each time the chat tells the backend about the device.
8793
+ deviceDetails,
8563
8794
  // Checked against the App's Bundle ID or Package name: another app with the same key shows no chat.
8564
8795
  bundle: appBundle(),
8565
8796
  // The Conversation stays on the phone: the next start shows it at once and asks only for newer messages.
@@ -1,11 +1,16 @@
1
1
  import type { IconName, NeutralColors } from './sdk.interface';
2
2
  import type { ZeanColorScheme } from '../interfaces';
3
+ import type { DeviceType } from '@zean/shared/constants/widget';
3
4
  /** How long the connection is down before the chat says so: a short blip is not worth a notice. */
4
5
  export declare const OFFLINE_NOTICE_MS = 3000;
5
6
  /** Android's navigation bar with its three buttons, in points: the gesture bar is half as tall. */
6
7
  export declare const ANDROID_NAVIGATION_BAR = 48;
7
8
  /** Photos a Contact sends in one message, unless `ZeanChat`'s `maxPhotos` says otherwise. */
8
9
  export declare const DEFAULT_MAX_PHOTOS = 4;
10
+ /** Android calls a device whose shorter screen side is this many dp or more a tablet. */
11
+ export declare const ANDROID_TABLET_SIDE = 600;
12
+ /** `expo-device`'s `deviceType` numbers: a TV, or one it cannot tell, is left to React Native. */
13
+ export declare const EXPO_DEVICE_TYPES: Partial<Record<number, DeviceType>>;
9
14
  /** The chat's own MMKV instance, apart from the app's. */
10
15
  export declare const CHAT_STORAGE_ID = "zean-chat";
11
16
  /** A photo's link asked for before its message is stored is refused: asked again this often, a few times. */
@@ -256,16 +256,30 @@ export interface MMKVModule {
256
256
  id: string;
257
257
  }) => ZeanMMKV;
258
258
  }
259
- /** `expo-application`: the app's Bundle ID on iOS, its Package name on Android. */
259
+ /** `expo-application`: the app's Bundle ID on iOS, its Package name on Android, its version and its build. */
260
260
  export interface ExpoApplicationModule {
261
261
  applicationId: string | null;
262
+ nativeApplicationVersion: string | null;
263
+ nativeBuildVersion: string | null;
262
264
  }
263
- /** `react-native-device-info`, its named exports or its default one. */
264
- export interface DeviceInfoModule {
265
+ /** `expo-device`: the exact model, as "iPhone 16 Pro", its brand, and its kind as a number. */
266
+ export interface ExpoDeviceModule {
267
+ modelName: string | null;
268
+ brand: string | null;
269
+ deviceType: number | null;
270
+ }
271
+ /** What the chat reads from `react-native-device-info`. */
272
+ export interface DeviceInfoFunctions {
265
273
  getBundleId?: () => string;
266
- default?: {
267
- getBundleId?: () => string;
268
- };
274
+ getModel?: () => string;
275
+ getBrand?: () => string;
276
+ isTablet?: () => boolean;
277
+ getVersion?: () => string;
278
+ getBuildNumber?: () => string;
279
+ }
280
+ /** `react-native-device-info`, its named exports or its default one. */
281
+ export interface DeviceInfoModule extends DeviceInfoFunctions {
282
+ default?: DeviceInfoFunctions;
269
283
  }
270
284
  export interface ImagePickerModule {
271
285
  launchImageLibrary: (options: ImagePickerOptions) => Promise<ImagePickerResult>;
@@ -1,5 +1,6 @@
1
1
  import type { ChatColors, ScreenInsets } from './sdk.interface';
2
2
  import type { AppBundle, ChatStorage } from '@zean/sdk-core';
3
+ import type { DeviceDetails } from '@zean/shared/interfaces/widget';
3
4
  import type { ZeanColorScheme, ZeanStorage } from '../interfaces';
4
5
  /** `{name}` in a text, filled from `values`. */
5
6
  export declare function format(template: string, values: Record<string, string | number>): string;
@@ -33,8 +34,12 @@ export declare function isDevBuild(): boolean;
33
34
  * deliver it.
34
35
  */
35
36
  export declare function isZeanNotification(data: unknown): boolean;
36
- /** "iOS 18.2" or "Android 15", for the Contact panel. */
37
- export declare function deviceOs(): string | undefined;
37
+ /**
38
+ * The Contact's Device details, with nothing for the app to install. React Native gives the system, the screen and, on
39
+ * Android, the brand and model. An app that already has `expo-device`, `expo-application` or `react-native-device-info`
40
+ * also gives the exact model and its own version. Unknown details are left out.
41
+ */
42
+ export declare function deviceDetails(): DeviceDetails;
38
43
  /**
39
44
  * The room the system takes at the top and the bottom of the chat, without a native module. On Android and on an iPad
40
45
  * the chat covers the whole screen, under the status bar and the navigation bar. On an iPhone it is a sheet below the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zean-chat/react-native",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "description": "In-app support chat for React Native and Expo, iOS and Android. Pure JS, no native module. A free Intercom, Crisp and Zendesk mobile SDK alternative.",
5
5
  "keywords": [
6
6
  "react-native",
@@ -58,6 +58,7 @@
58
58
  "peerDependencies": {
59
59
  "@react-native-async-storage/async-storage": "*",
60
60
  "expo-application": "*",
61
+ "expo-device": "*",
61
62
  "expo-image-picker": "*",
62
63
  "expo-sqlite": "*",
63
64
  "react": ">=19",
@@ -70,6 +71,9 @@
70
71
  "expo-application": {
71
72
  "optional": true
72
73
  },
74
+ "expo-device": {
75
+ "optional": true
76
+ },
73
77
  "react-native-device-info": {
74
78
  "optional": true
75
79
  },
@@ -102,7 +106,7 @@
102
106
  "convex": "1.46.0",
103
107
  "jest": "29.7.0",
104
108
  "react": "19.3.0",
105
- "react-native": "0.88.0",
109
+ "react-native": "0.88.1",
106
110
  "test-renderer": "1.3.1",
107
111
  "typescript": "6.0.3",
108
112
  "vitest": "4.1.11"