UNPKG

43.4 kBJavaScriptView Raw
1define(['exports'], (function (exports) { 'use strict';
2
3 var messageId = 1;
4 var webviewId = "".concat(Date.now(), "-").concat(String(Math.random()).slice(-8));
5 /**
6 * Message ID generator. Ids should be unique.
7 *
8 * the "web" prefix indicates that the message was originated from the web side.
9 *
10 * Using a timestamp as webviewId (assuming two webviews are not opened in the same millisecond),
11 * but if that ever happens, the last part is a random number to avoid collisions.
12 */
13 var getId = function () { return "web-".concat(messageId++, "-").concat(webviewId); };
14
15 var BRIDGE = '__tuenti_webview_bridge';
16 var hasAndroidPostMessage = function () {
17 return !!(typeof window !== 'undefined' &&
18 window.tuentiWebView &&
19 window.tuentiWebView.postMessage);
20 };
21 var hasWebKitPostMessage = function () {
22 return !!(typeof window !== 'undefined' &&
23 window.webkit &&
24 window.webkit.messageHandlers &&
25 window.webkit.messageHandlers.tuentiWebView &&
26 window.webkit.messageHandlers.tuentiWebView.postMessage);
27 };
28 /**
29 * Maybe returns postMessage function exposed by native apps
30 */
31 var getWebViewPostMessage = function () {
32 if (typeof window === 'undefined') {
33 return null;
34 }
35 // Android
36 if (hasAndroidPostMessage()) {
37 return function (jsonMessage) {
38 window.tuentiWebView.postMessage(jsonMessage);
39 };
40 }
41 // iOS
42 if (hasWebKitPostMessage()) {
43 return function (jsonMessage) {
44 window.webkit.messageHandlers.tuentiWebView.postMessage(jsonMessage);
45 };
46 }
47 return null;
48 };
49 var messageListeners = [];
50 var subscribe = function (listener) {
51 messageListeners.push(listener);
52 };
53 var unsubscribe = function (listener) {
54 messageListeners = messageListeners.filter(function (f) { return f !== listener; });
55 };
56 var isInIframe = function () {
57 try {
58 return window.self !== window.top;
59 }
60 catch (e) {
61 return true;
62 }
63 };
64 var isDisabledFromIframe = function () {
65 var _a;
66 if (typeof window === 'undefined') {
67 return false;
68 }
69 if (!isInIframe()) {
70 return false;
71 }
72 return !((_a = window === null || window === void 0 ? void 0 : window.frameElement) === null || _a === void 0 ? void 0 : _a.hasAttribute('data-enable-webview-bridge'));
73 };
74 var log = undefined;
75 var setLogger = function (logger) {
76 log = logger;
77 };
78 /**
79 * Returns true if there is a WebView Bridge installed
80 */
81 var isWebViewBridgeAvailable = function () {
82 return !isDisabledFromIframe() &&
83 (hasAndroidPostMessage() || hasWebKitPostMessage());
84 };
85 /**
86 * Send message to native app and waits for response
87 */
88 var postMessageToNativeApp = function (_a, timeout) {
89 var type = _a.type, _b = _a.id, id = _b === void 0 ? getId() : _b, payload = _a.payload;
90 var postMessage = getWebViewPostMessage();
91 var message = JSON.stringify({ type: type, id: id, payload: payload });
92 log === null || log === void 0 ? void 0 : log('[WebView Bridge] SEND:', message);
93 if (!postMessage) {
94 return Promise.reject({
95 code: 500,
96 reason: 'WebView postMessage not available',
97 });
98 }
99 // ensure postMessage call is async
100 setTimeout(function () {
101 postMessage(message);
102 });
103 return new Promise(function (resolve, reject) {
104 var timedOut = false;
105 var listener = function (response) {
106 if (response.id === id && !timedOut) {
107 if (response.type === type) {
108 resolve(response.payload);
109 }
110 else if (response.type === 'ERROR') {
111 reject(response.payload);
112 }
113 else {
114 reject({
115 code: 500,
116 reason: "bad type: ".concat(response.type, ". Expecting ").concat(type),
117 });
118 }
119 unsubscribe(listener);
120 }
121 };
122 subscribe(listener);
123 if (timeout) {
124 setTimeout(function () {
125 timedOut = true;
126 unsubscribe(listener);
127 reject({ code: 408, reason: 'request timeout' });
128 }, timeout);
129 }
130 });
131 };
132 /**
133 * Initiates WebApp postMessage function, which will be called by native apps
134 */
135 if (typeof window !== 'undefined') {
136 window[BRIDGE] = window[BRIDGE] || {
137 postMessage: function (jsonMessage) {
138 log === null || log === void 0 ? void 0 : log('[WebView Bridge] RCVD:', jsonMessage);
139 var message;
140 try {
141 message = JSON.parse(jsonMessage);
142 }
143 catch (e) {
144 throw Error("Problem parsing webview message: ".concat(jsonMessage));
145 }
146 messageListeners.forEach(function (f) { return f(message); });
147 },
148 };
149 }
150 var listenToNativeMessage = function (type, handler) {
151 var listener = function (message) {
152 if (message.type === type) {
153 Promise.resolve(handler(message.payload)).then(function (responsePayload) {
154 var postMessage = getWebViewPostMessage();
155 if (postMessage) {
156 postMessage(JSON.stringify({
157 type: message.type,
158 id: message.id,
159 payload: responsePayload,
160 }));
161 }
162 });
163 }
164 };
165 subscribe(listener);
166 return function () {
167 unsubscribe(listener);
168 };
169 };
170 var onNativeEvent = function (eventHandler) {
171 var handler = function (payload) {
172 var response = eventHandler({
173 event: payload.event,
174 });
175 return {
176 action: response.action || 'default',
177 };
178 };
179 return listenToNativeMessage('NATIVE_EVENT', handler);
180 };
181
182 var nativeConfirm = function (_a) {
183 var message = _a.message, title = _a.title, acceptText = _a.acceptText, cancelText = _a.cancelText;
184 if (isWebViewBridgeAvailable()) {
185 return postMessageToNativeApp({
186 type: 'CONFIRM',
187 payload: { message: message, title: title, acceptText: acceptText, cancelText: cancelText },
188 }).then(function (_a) {
189 var result = _a.result;
190 return result;
191 });
192 }
193 else {
194 return Promise.resolve(typeof window === 'undefined' ? false : window.confirm(message));
195 }
196 };
197 var nativeAlert = function (_a) {
198 var message = _a.message, title = _a.title, buttonText = _a.buttonText;
199 if (isWebViewBridgeAvailable()) {
200 return postMessageToNativeApp({
201 type: 'ALERT',
202 payload: { title: title, message: message, buttonText: buttonText },
203 });
204 }
205 else {
206 if (typeof window !== 'undefined') {
207 window.alert(message);
208 }
209 return Promise.resolve();
210 }
211 };
212 var nativeMessage = function (_a) {
213 var message = _a.message, duration = _a.duration, buttonText = _a.buttonText, type = _a.type;
214 if (isWebViewBridgeAvailable()) {
215 return postMessageToNativeApp({
216 type: 'MESSAGE',
217 payload: { message: message, duration: duration, buttonText: buttonText, type: type },
218 });
219 }
220 else {
221 if (typeof window !== 'undefined') {
222 window.alert(message);
223 }
224 return Promise.resolve();
225 }
226 };
227
228 var TIMEOUT = 200;
229 var requestSimIcc = function () {
230 return postMessageToNativeApp({ type: 'SIM_ICC' }, TIMEOUT)
231 .then(function (_a) {
232 var icc = _a.icc;
233 return icc;
234 })
235 .catch(function () { return null; });
236 };
237 var requestSimImsi = function () {
238 return postMessageToNativeApp({ type: 'IMSI' }, TIMEOUT)
239 .then(function (_a) {
240 var imsi = _a.imsi;
241 return imsi;
242 })
243 .catch(function () { return null; });
244 };
245 var requestDeviceImei = function () {
246 return postMessageToNativeApp({ type: 'IMEI' }, TIMEOUT)
247 .then(function (_a) {
248 var imei = _a.imei;
249 return imei;
250 })
251 .catch(function () { return null; });
252 };
253 var internalNavigation = function (feature) {
254 return postMessageToNativeApp({
255 type: 'INTERNAL_NAVIGATION',
256 payload: {
257 feature: feature,
258 },
259 });
260 };
261 var dismiss = function (onCompletionUrl) {
262 return postMessageToNativeApp({
263 type: 'DISMISS',
264 payload: {
265 onCompletionUrl: onCompletionUrl,
266 },
267 });
268 };
269 var requestVibration = function (type) {
270 return postMessageToNativeApp({
271 type: 'VIBRATION',
272 payload: {
273 type: type,
274 },
275 });
276 };
277 var getDiskSpaceInfo = function () {
278 return postMessageToNativeApp({
279 type: 'GET_DISK_SPACE_INFO',
280 });
281 };
282 var getEsimInfo = function () {
283 return postMessageToNativeApp({
284 type: 'GET_ESIM_INFO',
285 }).catch(function () { return ({
286 supportsEsim: false,
287 }); });
288 };
289
290 var attachToEmail = function (_a) {
291 var url = _a.url, subject = _a.subject, fileName = _a.fileName, recipient = _a.recipient, body = _a.body;
292 return postMessageToNativeApp({
293 type: 'ATTACH_TO_EMAIL',
294 payload: { url: url, subject: subject, fileName: fileName, recipient: recipient, body: body },
295 });
296 };
297 var share = function (options) {
298 return postMessageToNativeApp({
299 type: 'SHARE',
300 payload: options,
301 });
302 };
303 var updateNavigationBar = function (_a) {
304 var title = _a.title, expandedTitle = _a.expandedTitle, showBackButton = _a.showBackButton, showReloadButton = _a.showReloadButton, showProfileButton = _a.showProfileButton, backgroundColor = _a.backgroundColor;
305 if (isWebViewBridgeAvailable()) {
306 return postMessageToNativeApp({
307 type: 'NAVIGATION_BAR',
308 payload: {
309 title: title,
310 expandedTitle: expandedTitle,
311 showBackButton: showBackButton,
312 showReloadButton: showReloadButton,
313 showProfileButton: showProfileButton,
314 backgroundColor: backgroundColor,
315 },
316 });
317 }
318 else {
319 if (typeof title !== 'undefined' && typeof document !== 'undefined') {
320 document.title = title;
321 }
322 return Promise.resolve();
323 }
324 };
325 /**
326 * @deprecated
327 */
328 var setWebViewTitle = function (title) {
329 if (isWebViewBridgeAvailable()) {
330 return updateNavigationBar({ title: title });
331 }
332 else {
333 if (typeof document !== 'undefined') {
334 document.title = title;
335 }
336 return Promise.resolve();
337 }
338 };
339 var notifyPageLoaded = function () {
340 return postMessageToNativeApp({ type: 'PAGE_LOADED' });
341 };
342 var notifyBridgeReady = function () {
343 return postMessageToNativeApp({ type: 'BRIDGE_READY' });
344 };
345 var remoteConfig = null;
346 var isRemoteConfigAvailable = function (key) {
347 return remoteConfig.result[key] === 'true';
348 };
349 var isABTestingAvailable = function (key) {
350 if (!remoteConfig) {
351 // If GET_REMOTE_CONFIG takes more than 5s to respond, resolve to false
352 var timeoutP = new Promise(function (resolve) {
353 setTimeout(function () {
354 resolve(false);
355 }, 500);
356 });
357 var configP = postMessageToNativeApp({
358 type: 'GET_REMOTE_CONFIG',
359 }).then(function (res) {
360 remoteConfig = res;
361 return isRemoteConfigAvailable(key);
362 });
363 return Promise.race([timeoutP, configP]);
364 }
365 else {
366 return Promise.resolve(isRemoteConfigAvailable(key));
367 }
368 };
369 var reportStatus = function (_a) {
370 var feature = _a.feature, status = _a.status, reason = _a.reason;
371 return postMessageToNativeApp({
372 type: 'STATUS_REPORT',
373 payload: { feature: feature, status: status, reason: reason },
374 });
375 };
376 var fetch = function (_a) {
377 var url = _a.url, method = _a.method, headers = _a.headers, body = _a.body;
378 if (isWebViewBridgeAvailable()) {
379 return postMessageToNativeApp({
380 type: 'FETCH',
381 payload: { url: url, method: method, headers: headers, body: body },
382 }).catch(function () { return ({
383 status: 500,
384 headers: {},
385 body: 'Bridge call failed',
386 }); });
387 }
388 return Promise.resolve({
389 status: 500,
390 headers: {},
391 body: 'Bridge not available',
392 });
393 };
394 var checkPermissionStatus = function (feature, params) {
395 return postMessageToNativeApp({
396 type: 'OS_PERMISSION_STATUS',
397 payload: {
398 feature: feature,
399 params: params,
400 },
401 }).then(function (_a) {
402 var granted = _a.granted;
403 return granted;
404 });
405 };
406 var getAppMetadata = function (appToken) {
407 return postMessageToNativeApp({
408 type: 'GET_APP_METADATA',
409 payload: {
410 appToken: appToken,
411 },
412 });
413 };
414 var setActionBehavior = function (actions) {
415 return postMessageToNativeApp({
416 type: 'SET_ACTION_BEHAVIOR',
417 payload: {
418 actions: actions,
419 },
420 }).catch(function () {
421 // do nothing
422 });
423 };
424 /**
425 * Returns the Topaz SDK Token
426 * https://www.topaz.com.br/ofd/index.php
427 */
428 var getTopazToken = function (options) {
429 if (options === void 0) { options = {}; }
430 return postMessageToNativeApp({
431 type: 'GET_TOPAZ_TOKEN',
432 payload: {},
433 }, options.timeout);
434 };
435
436 var msToS = function (ms) { return Math.floor(ms / 1000); };
437 var createCalendarEvent = function (_a) {
438 var beginTime = _a.beginTime, endTime = _a.endTime, title = _a.title;
439 return postMessageToNativeApp({
440 type: 'CREATE_CALENDAR_EVENT',
441 payload: {
442 beginTime: msToS(beginTime),
443 endTime: msToS(endTime),
444 title: title,
445 },
446 });
447 };
448
449 var requestContact = function (_a) {
450 var _b = _a === void 0 ? {} : _a, _c = _b.filter, filter = _c === void 0 ? 'phone' : _c;
451 return postMessageToNativeApp({ type: 'GET_CONTACT_DATA', payload: { filter: filter } });
452 };
453 var fetchContactsByPhone = function (phoneNumbers) {
454 return postMessageToNativeApp({
455 type: 'FETCH_CONTACTS_DATA',
456 payload: { phoneNumbers: phoneNumbers },
457 });
458 };
459 var fetchPhoneNumbers = function () {
460 return postMessageToNativeApp({
461 type: 'FETCH_PHONE_NUMBERS',
462 });
463 };
464 var updatePhoneNumbers = function (phoneNumbers) {
465 return postMessageToNativeApp({
466 type: 'UPDATE_PHONE_NUMBERS',
467 payload: { phoneNumbers: phoneNumbers },
468 });
469 };
470
471 var highlightNavigationTab = function (_a) {
472 var tab = _a.tab, highlight = _a.highlight, count = _a.count;
473 return postMessageToNativeApp({
474 type: 'HIGHLIGHT_TAB',
475 payload: {
476 tab: tab,
477 highlight: highlight,
478 count: count,
479 },
480 });
481 };
482
483 /*! *****************************************************************************
484 Copyright (c) Microsoft Corporation.
485
486 Permission to use, copy, modify, and/or distribute this software for any
487 purpose with or without fee is hereby granted.
488
489 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
490 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
491 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
492 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
493 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
494 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
495 PERFORMANCE OF THIS SOFTWARE.
496 ***************************************************************************** */
497
498 var __assign = function() {
499 __assign = Object.assign || function __assign(t) {
500 for (var s, i = 1, n = arguments.length; i < n; i++) {
501 s = arguments[i];
502 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
503 }
504 return t;
505 };
506 return __assign.apply(this, arguments);
507 };
508
509 function __rest(s, e) {
510 var t = {};
511 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
512 t[p] = s[p];
513 if (s != null && typeof Object.getOwnPropertySymbols === "function")
514 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
515 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
516 t[p[i]] = s[p[i]];
517 }
518 return t;
519 }
520
521 function __awaiter(thisArg, _arguments, P, generator) {
522 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
523 return new (P || (P = Promise))(function (resolve, reject) {
524 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
525 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
526 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
527 step((generator = generator.apply(thisArg, _arguments || [])).next());
528 });
529 }
530
531 function __generator(thisArg, body) {
532 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
533 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
534 function verb(n) { return function (v) { return step([n, v]); }; }
535 function step(op) {
536 if (f) throw new TypeError("Generator is already executing.");
537 while (_) try {
538 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
539 if (y = 0, t) op = [op[0] & 2, t.value];
540 switch (op[0]) {
541 case 0: case 1: t = op; break;
542 case 4: _.label++; return { value: op[1], done: false };
543 case 5: _.label++; y = op[1]; op = [0]; continue;
544 case 7: op = _.ops.pop(); _.trys.pop(); continue;
545 default:
546 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
547 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
548 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
549 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
550 if (t[2]) _.ops.pop();
551 _.trys.pop(); continue;
552 }
553 op = body.call(thisArg, _);
554 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
555 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
556 }
557 }
558
559 function __read(o, n) {
560 var m = typeof Symbol === "function" && o[Symbol.iterator];
561 if (!m) return o;
562 var i = m.call(o), r, ar = [], e;
563 try {
564 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
565 }
566 catch (error) { e = { error: error }; }
567 finally {
568 try {
569 if (r && !r.done && (m = i["return"])) m.call(i);
570 }
571 finally { if (e) throw e.error; }
572 }
573 return ar;
574 }
575
576 /** @deprecated */
577 var CD_WEBAPP_INSTALLED = 4;
578 /** @deprecated */
579 var CD_NOVUM_UID = 7;
580 /** @deprecated */
581 var CD_EVENT_VALUE = 8;
582 var DEFAULT_EVENT_LABEL = 'null_label';
583 var DEFAULT_EVENT_VALUE = 0;
584 var CALLBACK_TIMEOUT = 500;
585 var MAX_TIMEOUT_TIMES = 3;
586 var timeoutCounter = 0;
587 var createCallback = function (resolve) {
588 // Analytics may fail to load (for example, if blocked by an adblocker). If that happens, we still need to resolve
589 // the logEvent promises, so we stablish a timeout for those cases.
590 // If the log times out more than MAX_TIMEOUT_TIMES times consecutively, we don't try to send more events and inmediately resolve
591 // all the promises.
592 var tid = setTimeout(function () {
593 resolve();
594 timeoutCounter++;
595 }, CALLBACK_TIMEOUT);
596 return function () {
597 clearTimeout(tid);
598 timeoutCounter = 0;
599 resolve();
600 };
601 };
602 var withAnalytics = function (_a) {
603 var onAndroid = _a.onAndroid, onIos = _a.onIos, onWeb = _a.onWeb;
604 if (typeof window === 'undefined') {
605 return Promise.resolve();
606 }
607 if (window.AnalyticsWebInterface) {
608 // Call Android interface
609 return onAndroid(window.AnalyticsWebInterface);
610 }
611 else if (window.webkit &&
612 window.webkit.messageHandlers &&
613 window.webkit.messageHandlers.firebase) {
614 // Call iOS interface
615 return onIos(window.webkit.messageHandlers.firebase);
616 }
617 else if (
618 // @ts-ignore TS thinks gtag is always available, but it may not be the case if the page has not loaded the gtag script
619 window.gtag &&
620 timeoutCounter < MAX_TIMEOUT_TIMES) {
621 // Use Google Analytics when webapp is outside the native app webview
622 return onWeb(window.gtag);
623 }
624 else {
625 return Promise.resolve();
626 }
627 };
628 var removeAccents = function (str) {
629 // Normalize to NFD (normal form decomposition) and delete Combining Diacritical Marks Unicode
630 // https://stackoverflow.com/a/37511463/3874587
631 return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
632 };
633 var EVENT_PARAM_NAME_CHARS_LIMIT = 40;
634 var EVENT_PARAM_VALUE_CHARS_LIMIT = 100;
635 var EVENT_PARAMS_LIMIT = 25;
636 var sanitizeAnalyticsParam = function (str) {
637 return removeAccents(str)
638 .toLocaleLowerCase()
639 .replace(/[^a-z0-9\s\-\_\/\|\:]/g, '') // Remove all non allowed characters
640 .replace(/\s+/g, ' ') // Replace repeated whitespaces with a single space
641 .trim()
642 .replace(/\s/g, '_') // Replace spaces with underscores
643 .slice(0, EVENT_PARAM_VALUE_CHARS_LIMIT);
644 };
645 var sanitizeAnalyticsParams = function (params) {
646 var sanitizedParams = {};
647 Object.entries(params).forEach(function (_a) {
648 var _b = __read(_a, 2), key = _b[0], value = _b[1];
649 var sanitizedValue = value;
650 var sanitizedKey = key.slice(0, EVENT_PARAM_NAME_CHARS_LIMIT);
651 if (typeof value === 'string') {
652 // Some string params may contain strings with accents (some of them may be copies/translations), so we need to sanitize them
653 sanitizedValue = sanitizeAnalyticsParam(value);
654 }
655 sanitizedParams[sanitizedKey] = sanitizedValue;
656 });
657 return sanitizedParams;
658 };
659 var getLegacyAnalyticsEventParams = function (_a) {
660 var category = _a.category, action = _a.action, label = _a.label, value = _a.value, fieldsObject = __rest(_a, ["category", "action", "label", "value"]);
661 if (!label) {
662 label = DEFAULT_EVENT_LABEL;
663 }
664 if (!value) {
665 value = DEFAULT_EVENT_VALUE;
666 }
667 return __assign({ eventCategory: category, eventAction: action, eventLabel: removeAccents(label), eventValue: value }, fieldsObject);
668 };
669 var defaultEventOptions = { sanitize: true };
670 var currentScreenName = '';
671 var logEvent = function (event, options) {
672 var sanitize = __assign(__assign({}, defaultEventOptions), options).sanitize;
673 var name = event.name, params = __rest(event, ["name"]);
674 // If the event doesn't have a name, it's a legacy analytics event
675 if (!name) {
676 if (!event.category || !event.action) {
677 console.warn('LegacyAnalyticsEvent should have "category" and "action"', {
678 category: event.category,
679 action: event.action,
680 });
681 return Promise.resolve();
682 }
683 params = getLegacyAnalyticsEventParams(event);
684 name = event.category;
685 }
686 else {
687 if (Object.keys(params).length > EVENT_PARAMS_LIMIT) {
688 console.warn("Trying to log FirebaseEvent with name ".concat(name, " exceeding the limit of ").concat(EVENT_PARAMS_LIMIT, " params"));
689 }
690 if (sanitize) {
691 params = sanitizeAnalyticsParams(params);
692 name = sanitizeAnalyticsParam(name);
693 }
694 }
695 // set screen name if not set
696 params = __assign(__assign({}, params), { screenName: params.screenName || currentScreenName });
697 return withAnalytics({
698 onAndroid: function (androidFirebase) {
699 if (androidFirebase.logEvent) {
700 androidFirebase.logEvent(name, JSON.stringify(params));
701 }
702 return Promise.resolve();
703 },
704 onIos: function (iosFirebase) {
705 iosFirebase.postMessage({
706 command: 'logEvent',
707 name: name,
708 parameters: params,
709 });
710 return Promise.resolve();
711 },
712 onWeb: function (gtag) {
713 return new Promise(function (resolve) {
714 gtag('event', name, __assign(__assign({}, params), { event_callback: createCallback(resolve) }));
715 });
716 },
717 });
718 };
719 var logEcommerceEvent = function (name, params) {
720 // set screen name if not set
721 params = __assign(__assign({}, params), { screenName: params.screenName || currentScreenName });
722 return withAnalytics({
723 onAndroid: function (androidFirebase) {
724 if (androidFirebase.logEvent) {
725 androidFirebase.logEvent(name, JSON.stringify(params));
726 }
727 return Promise.resolve();
728 },
729 onIos: function (iosFirebase) {
730 iosFirebase.postMessage({
731 command: 'logEvent',
732 name: name,
733 parameters: params,
734 });
735 return Promise.resolve();
736 },
737 onWeb: function () {
738 // not implemented on web
739 return Promise.resolve();
740 },
741 });
742 };
743 var logTiming = function (_a) {
744 var _b = _a.category, category = _b === void 0 ? 'performance_timer' : _b, variable = _a.variable, value = _a.value, label = _a.label;
745 if (!category || !variable || !value) {
746 console.warn('Analytics timing should have "category", "variable" and "value"', { category: category, variable: variable, value: value });
747 return Promise.resolve();
748 }
749 value = Math.round(value);
750 var params = {
751 timingCategory: category,
752 timingVar: variable,
753 timingValue: value,
754 timingLabel: label,
755 };
756 var name = category;
757 return withAnalytics({
758 onAndroid: function (androidFirebase) {
759 if (androidFirebase.logEvent) {
760 androidFirebase.logEvent(name, JSON.stringify(params));
761 }
762 return Promise.resolve();
763 },
764 onIos: function (iosFirebase) {
765 iosFirebase.postMessage({
766 command: 'logEvent',
767 name: name,
768 parameters: params,
769 });
770 return Promise.resolve();
771 },
772 onWeb: function () {
773 return new Promise(function (resolve) {
774 gtag('event', name, __assign(__assign({}, params), { event_callback: createCallback(resolve) }));
775 });
776 },
777 });
778 };
779 var setScreenName = function (screenName, params) {
780 if (!screenName) {
781 console.warn('Missing analytics screenName');
782 return Promise.resolve();
783 }
784 var previousScreenName = currentScreenName;
785 currentScreenName = screenName;
786 return withAnalytics({
787 onAndroid: function (androidFirebase) {
788 // The method to send params with the screen name is only implemented in new app versions.
789 if (androidFirebase.setScreenNameWithParams) {
790 androidFirebase.setScreenNameWithParams(screenName, JSON.stringify(params));
791 }
792 else if (androidFirebase.setScreenName) {
793 androidFirebase.setScreenName(screenName);
794 }
795 return Promise.resolve();
796 },
797 onIos: function (iosFirebase) {
798 iosFirebase.postMessage({
799 command: 'setScreenName',
800 name: screenName,
801 parameters: params,
802 });
803 return Promise.resolve();
804 },
805 onWeb: function (gtag) {
806 return new Promise(function (resolve) {
807 gtag('event', 'page_view', __assign(__assign({ screenName: screenName, page_title: screenName, previousScreenName: previousScreenName }, sanitizeAnalyticsParams(params !== null && params !== void 0 ? params : {})), { event_callback: createCallback(resolve) }));
808 });
809 },
810 });
811 };
812 var setUserProperty = function (name, value) {
813 if (!name || !value) {
814 console.warn('Trying to set analytics user property without name or value', name, value);
815 return Promise.resolve();
816 }
817 value = String(value);
818 return withAnalytics({
819 onAndroid: function (androidFirebase) {
820 if (androidFirebase.setUserProperty) {
821 androidFirebase.setUserProperty(name, value);
822 }
823 return Promise.resolve();
824 },
825 onIos: function (iosFirebase) {
826 iosFirebase.postMessage({
827 command: 'setUserProperty',
828 name: name,
829 value: value,
830 });
831 return Promise.resolve();
832 },
833 onWeb: function (gtag) {
834 var _a;
835 gtag('set', 'user_properties', (_a = {},
836 _a[name] = sanitizeAnalyticsParam(value),
837 _a));
838 return Promise.resolve();
839 },
840 });
841 };
842 var setCustomerHash = function (hash) {
843 return postMessageToNativeApp({
844 type: 'SET_CUSTOMER_HASH',
845 payload: {
846 hash: hash,
847 },
848 });
849 };
850 var getCustomerHash = function () {
851 return postMessageToNativeApp({
852 type: 'GET_CUSTOMER_HASH',
853 });
854 };
855 var setTrackingProperty = function (system, name, value) {
856 return postMessageToNativeApp({
857 type: 'SET_TRACKING_PROPERTY',
858 payload: {
859 system: system,
860 name: name,
861 value: value,
862 },
863 }).catch(function () {
864 // do nothing
865 });
866 };
867
868 /**
869 * This method is used by webapp to request the native app to renew current session
870 * When webapp (running inside a webview) receives a 401 api response from server, uses this
871 * bridge method to renew the session.
872 */
873 var renewSession = function (oldAccessToken, options) {
874 if (options === void 0) { options = {}; }
875 return postMessageToNativeApp({
876 type: 'RENEW_SESSION',
877 payload: { accessToken: oldAccessToken || null },
878 }, options.timeout).then(function (_a) {
879 var accessToken = _a.accessToken;
880 return accessToken;
881 });
882 };
883 /**
884 * This method is used to listen for session renewals made by native app. Whenever the native app
885 * renews the session with the api, it should notify webpp with this message.
886 * This message is initiated by native app.
887 */
888 var onSessionRenewed = function (handler) {
889 return listenToNativeMessage('SESSION_RENEWED', function (_a) {
890 var accessToken = _a.accessToken;
891 return handler(accessToken);
892 });
893 };
894 /**
895 * This method is used by webapp to request the native app to end the current session
896 */
897 var logout = function () {
898 return postMessageToNativeApp({ type: 'LOG_OUT' });
899 };
900
901 /**
902 * This method is used by webapp to request the native app to launch the app rating dialog
903 */
904 var showAppRating = function () {
905 return postMessageToNativeApp({ type: 'SHOW_APP_RATING' });
906 };
907
908 var sheetLock = false;
909 var bottomSheet = function (payload) { return __awaiter(void 0, void 0, void 0, function () {
910 var tid, response, e_1;
911 return __generator(this, function (_a) {
912 switch (_a.label) {
913 case 0:
914 if (sheetLock) {
915 throw {
916 code: 423,
917 reason: 'BottomSheet is locked. You can only have one bottom sheet in the screen',
918 };
919 }
920 sheetLock = true;
921 tid = setTimeout(function () {
922 sheetLock = false;
923 }, 1000);
924 _a.label = 1;
925 case 1:
926 _a.trys.push([1, 3, , 4]);
927 return [4 /*yield*/, postMessageToNativeApp({ type: 'SHEET', payload: payload })];
928 case 2:
929 response = _a.sent();
930 sheetLock = false;
931 clearTimeout(tid);
932 return [2 /*return*/, response];
933 case 3:
934 e_1 = _a.sent();
935 sheetLock = false;
936 clearTimeout(tid);
937 throw e_1;
938 case 4: return [2 /*return*/];
939 }
940 });
941 }); };
942 var bottomSheetSingleSelector = function (_a) {
943 var title = _a.title, subtitle = _a.subtitle, description = _a.description, selectedId = _a.selectedId, items = _a.items;
944 return bottomSheet({
945 title: title,
946 subtitle: subtitle,
947 description: description,
948 content: [
949 {
950 type: 'LIST',
951 id: 'list-0',
952 listType: 'SINGLE_SELECTION',
953 autoSubmit: true,
954 selectedIds: typeof selectedId === 'string' ? [selectedId] : [],
955 items: items,
956 },
957 ],
958 }).then(function (_a) {
959 var action = _a.action, result = _a.result;
960 if (action === 'SUBMIT') {
961 return {
962 action: action,
963 selectedId: result[0].selectedIds[0],
964 };
965 }
966 else {
967 return {
968 action: action,
969 selectedId: null,
970 };
971 }
972 });
973 };
974 var bottomSheetActionSelector = function (_a) {
975 var title = _a.title, subtitle = _a.subtitle, description = _a.description, items = _a.items;
976 return bottomSheet({
977 title: title,
978 subtitle: subtitle,
979 description: description,
980 content: [
981 {
982 type: 'LIST',
983 id: 'list-0',
984 listType: 'ACTIONS',
985 autoSubmit: true,
986 selectedIds: [],
987 items: items,
988 },
989 ],
990 }).then(function (_a) {
991 var action = _a.action, result = _a.result;
992 if (action === 'SUBMIT') {
993 return {
994 action: action,
995 selectedId: result[0].selectedIds[0],
996 };
997 }
998 else {
999 return {
1000 action: action,
1001 selectedId: null,
1002 };
1003 }
1004 });
1005 };
1006 var bottomSheetInfo = function (_a) {
1007 var title = _a.title, subtitle = _a.subtitle, description = _a.description, items = _a.items;
1008 return __awaiter(void 0, void 0, void 0, function () {
1009 return __generator(this, function (_b) {
1010 switch (_b.label) {
1011 case 0: return [4 /*yield*/, bottomSheet({
1012 title: title,
1013 subtitle: subtitle,
1014 description: description,
1015 content: [
1016 {
1017 type: 'LIST',
1018 id: 'list-0',
1019 listType: 'INFORMATIVE',
1020 autoSubmit: false,
1021 selectedIds: [],
1022 items: items,
1023 },
1024 ],
1025 })];
1026 case 1:
1027 _b.sent();
1028 return [2 /*return*/];
1029 }
1030 });
1031 });
1032 };
1033
1034 exports.CD_EVENT_VALUE = CD_EVENT_VALUE;
1035 exports.CD_NOVUM_UID = CD_NOVUM_UID;
1036 exports.CD_WEBAPP_INSTALLED = CD_WEBAPP_INSTALLED;
1037 exports.attachToEmail = attachToEmail;
1038 exports.bottomSheet = bottomSheet;
1039 exports.bottomSheetActionSelector = bottomSheetActionSelector;
1040 exports.bottomSheetInfo = bottomSheetInfo;
1041 exports.bottomSheetSingleSelector = bottomSheetSingleSelector;
1042 exports.checkPermissionStatus = checkPermissionStatus;
1043 exports.createCalendarEvent = createCalendarEvent;
1044 exports.dismiss = dismiss;
1045 exports.fetch = fetch;
1046 exports.fetchContactsByPhone = fetchContactsByPhone;
1047 exports.fetchPhoneNumbers = fetchPhoneNumbers;
1048 exports.getAppMetadata = getAppMetadata;
1049 exports.getCustomerHash = getCustomerHash;
1050 exports.getDiskSpaceInfo = getDiskSpaceInfo;
1051 exports.getEsimInfo = getEsimInfo;
1052 exports.getTopazToken = getTopazToken;
1053 exports.highlightNavigationTab = highlightNavigationTab;
1054 exports.internalNavigation = internalNavigation;
1055 exports.isABTestingAvailable = isABTestingAvailable;
1056 exports.isWebViewBridgeAvailable = isWebViewBridgeAvailable;
1057 exports.logEcommerceEvent = logEcommerceEvent;
1058 exports.logEvent = logEvent;
1059 exports.logTiming = logTiming;
1060 exports.logout = logout;
1061 exports.nativeAlert = nativeAlert;
1062 exports.nativeConfirm = nativeConfirm;
1063 exports.nativeMessage = nativeMessage;
1064 exports.notifyBridgeReady = notifyBridgeReady;
1065 exports.notifyPageLoaded = notifyPageLoaded;
1066 exports.onNativeEvent = onNativeEvent;
1067 exports.onSessionRenewed = onSessionRenewed;
1068 exports.renewSession = renewSession;
1069 exports.reportStatus = reportStatus;
1070 exports.requestContact = requestContact;
1071 exports.requestDeviceImei = requestDeviceImei;
1072 exports.requestSimIcc = requestSimIcc;
1073 exports.requestSimImsi = requestSimImsi;
1074 exports.requestVibration = requestVibration;
1075 exports.sanitizeAnalyticsParam = sanitizeAnalyticsParam;
1076 exports.sanitizeAnalyticsParams = sanitizeAnalyticsParams;
1077 exports.setActionBehavior = setActionBehavior;
1078 exports.setCustomerHash = setCustomerHash;
1079 exports.setLogger = setLogger;
1080 exports.setScreenName = setScreenName;
1081 exports.setTrackingProperty = setTrackingProperty;
1082 exports.setUserProperty = setUserProperty;
1083 exports.setWebViewTitle = setWebViewTitle;
1084 exports.share = share;
1085 exports.showAppRating = showAppRating;
1086 exports.updateNavigationBar = updateNavigationBar;
1087 exports.updatePhoneNumbers = updatePhoneNumbers;
1088
1089 Object.defineProperty(exports, '__esModule', { value: true });
1090
1091}));